cargo_hakari/
cargo_cli.rs1use crate::output::OutputContext;
7use camino::Utf8PathBuf;
8use std::{convert::TryInto, env, path::PathBuf};
9
10#[derive(Clone, Debug)]
11pub(crate) struct CargoCli<'a> {
12 cargo_path: Utf8PathBuf,
13 output: OutputContext,
14 command: &'a str,
15 args: Vec<&'a str>,
16}
17
18impl<'a> CargoCli<'a> {
19 pub(crate) fn new(command: &'a str, output: OutputContext) -> Self {
20 let cargo_path = cargo_path();
21 Self {
22 cargo_path,
23 output,
24 command,
25 args: vec![],
26 }
27 }
28
29 pub(crate) fn add_arg(&mut self, arg: &'a str) -> &mut Self {
30 self.args.push(arg);
31 self
32 }
33
34 pub(crate) fn add_args(&mut self, args: impl IntoIterator<Item = &'a str>) -> &mut Self {
35 self.args.extend(args);
36 self
37 }
38
39 pub(crate) fn all_args(&self) -> Vec<&str> {
40 let mut all_args = vec![self.cargo_path.as_str(), self.command];
41 all_args.extend_from_slice(&self.args);
42 all_args
43 }
44
45 pub(crate) fn to_expression(&self) -> duct::Expression {
46 let mut initial_args = vec![];
47 if self.output.quiet {
48 initial_args.push("--quiet");
49 }
50 if self.output.verbose {
51 initial_args.push("--verbose");
52 }
53 initial_args.push(self.output.color.to_arg());
54
55 initial_args.push(self.command);
56
57 duct::cmd(
58 self.cargo_path.as_std_path(),
59 initial_args.into_iter().chain(self.args.iter().copied()),
60 )
61 }
62}
63
64fn cargo_path() -> Utf8PathBuf {
65 match env::var_os("CARGO") {
66 Some(cargo_path) => PathBuf::from(cargo_path)
67 .try_into()
68 .expect("CARGO env var is not valid UTF-8"),
69 None => Utf8PathBuf::from("cargo"),
70 }
71}