Files
addr2line
adler
aho_corasick
arrayvec
atty
backtrace
bitflags
camino
cargo_metadata
cargo_nextest
cargo_platform
cfg_expr
cfg_if
chrono
clap
clap_derive
color_eyre
config
crossbeam_channel
crossbeam_deque
crossbeam_epoch
crossbeam_utils
ctrlc
datatest_stable
debug_ignore
duct
either
enable_ansi_support
env_logger
eyre
fixedbitset
gimli
guppy
guppy_workspace_hack
hashbrown
humantime
humantime_serde
indent_write
indenter
indexmap
is_ci
itertools
itoa
lazy_static
lexical_core
libc
log
memchr
memoffset
miniz_oxide
nested
nextest_metadata
nextest_runner
nix
nom
num_cpus
num_integer
num_traits
object
once_cell
os_pipe
os_str_bytes
owo_colors
pathdiff
petgraph
proc_macro2
proc_macro_error
proc_macro_error_attr
quick_junit
quick_xml
quote
rayon
rayon_core
regex
regex_syntax
rustc_demangle
ryu
same_file
scopeguard
semver
serde
serde_derive
serde_json
shared_child
shellwords
smallvec
static_assertions
strip_ansi_escapes
strsim
structopt
structopt_derive
supports_color
syn
target_lexicon
target_spec
termcolor
textwrap
time
toml
twox_hash
unicode_xid
utf8parse
vte
vte_generate_state_changes
walkdir
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
// Copyright (c) The diem-devtools Contributors
// SPDX-License-Identifier: MIT OR Apache-2.0

//! Cargo CLI support.

use crate::output::OutputContext;
use camino::{Utf8Path, Utf8PathBuf};
use clap::{AppSettings, Args};
use std::path::PathBuf;

/// Options passed down to cargo.
#[derive(Debug, Args)]
#[clap(help_heading = "CARGO OPTIONS", setting = AppSettings::DeriveDisplayOrder)]
pub(crate) struct CargoOptions {
    /// Test only this package's library unit tests
    #[clap(long)]
    lib: bool,

    /// Test only the specified binary
    #[clap(long)]
    bin: Vec<String>,

    /// Test all binaries
    #[clap(long)]
    bins: bool,

    /// Test only the specified test target
    #[clap(long)]
    test: Vec<String>,

    /// Test all targets
    #[clap(long)]
    tests: bool,

    /// Test only the specified bench target
    #[clap(long)]
    bench: Vec<String>,

    /// Test all benches
    #[clap(long)]
    benches: bool,

    /// Test all targets
    #[clap(long)]
    all_targets: bool,

    //  TODO: doc?
    // no-run is handled by test runner
    /// Package to test
    #[clap(short = 'p', long = "package")]
    packages: Vec<String>,

    /// Build all packages in the workspace
    #[clap(long)]
    workspace: bool,

    /// Exclude packages from the test
    #[clap(long)]
    exclude: Vec<String>,

    /// Alias for workspace (deprecated)
    #[clap(long)]
    all: bool,

    // jobs is handled by test runner
    /// Build artifacts in release mode, with optimizations
    #[clap(long)]
    release: bool,

    /// Build artifacts with the specified Cargo profile
    #[clap(long, value_name = "NAME")]
    cargo_profile: Option<String>,

    /// Number of build jobs to run
    #[clap(long, value_name = "JOBS")]
    build_jobs: Option<String>,

    /// Space or comma separated list of features to activate
    #[clap(long)]
    features: Vec<String>,

    /// Activate all available features
    #[clap(long)]
    all_features: bool,

    /// Do not activate the `default` feature
    #[clap(long)]
    no_default_features: bool,

    /// Build for the target triple
    #[clap(long, value_name = "TRIPLE")]
    target: Option<String>,

    /// Directory for all generated artifacts
    #[clap(long, value_name = "DIR")]
    target_dir: Option<String>,

    /// Ignore `rust-version` specification in packages
    #[clap(long)]
    ignore_rust_version: bool,
    // --message-format is captured by nextest
    /// Output build graph in JSON (unstable)
    #[clap(long)]
    unit_graph: bool,

    /// Outputs a future incompatibility report at the end of the build (unstable)
    #[clap(long)]
    future_incompat_report: bool,

    // --verbose is not currently supported
    // --color is handled by runner
    /// Require Cargo.lock and cache are up to date
    #[clap(long)]
    frozen: bool,

    /// Require Cargo.lock is up to date
    #[clap(long)]
    locked: bool,

    /// Run without accessing the network
    #[clap(long)]
    offline: bool,

    /// Override a configuration value (unstable)
    #[clap(long, value_name = "KEY=VALUE")]
    config: Vec<String>,

    /// Unstable (nightly-only) flags to Cargo, see 'cargo -Z help' for details
    #[clap(short = 'Z', value_name = "FLAG")]
    unstable_flags: Vec<String>,
}

#[derive(Clone, Debug)]
pub(crate) struct CargoCli<'a> {
    cargo_path: Utf8PathBuf,
    manifest_path: Option<&'a Utf8Path>,
    output: OutputContext,
    command: &'a str,
    args: Vec<&'a str>,
}

impl<'a> CargoCli<'a> {
    pub(crate) fn new(
        command: &'a str,
        manifest_path: Option<&'a Utf8Path>,
        output: OutputContext,
    ) -> Self {
        let cargo_path = cargo_path();
        Self {
            cargo_path,
            manifest_path,
            output,
            command,
            args: vec![],
        }
    }

    #[allow(dead_code)]
    pub(crate) fn add_arg(&mut self, arg: &'a str) -> &mut Self {
        self.args.push(arg);
        self
    }

    pub(crate) fn add_args(&mut self, args: impl IntoIterator<Item = &'a str>) -> &mut Self {
        self.args.extend(args);
        self
    }

    pub(crate) fn add_options(&mut self, options: &'a CargoOptions) -> &mut Self {
        if options.lib {
            self.args.push("--lib");
        }
        self.args
            .extend(options.bin.iter().flat_map(|s| ["--bin", s.as_str()]));
        if options.bins {
            self.args.push("--bins");
        }
        self.args
            .extend(options.test.iter().flat_map(|s| ["--test", s.as_str()]));
        if options.tests {
            self.args.push("--tests");
        }
        self.args
            .extend(options.bench.iter().flat_map(|s| ["--bench", s.as_str()]));
        if options.benches {
            self.args.push("--benches");
        }
        if options.all_targets {
            self.args.push("--all-targets");
        }
        self.args.extend(
            options
                .packages
                .iter()
                .flat_map(|s| ["--package", s.as_str()]),
        );
        if options.workspace {
            self.args.push("--workspace");
        }
        self.args.extend(
            options
                .exclude
                .iter()
                .flat_map(|s| ["--exclude", s.as_str()]),
        );
        if options.all {
            self.args.push("--all");
        }
        if options.release {
            self.args.push("--release");
        }
        if let Some(profile) = &options.cargo_profile {
            self.args.extend(["--profile", profile]);
        }
        if let Some(build_jobs) = &options.build_jobs {
            self.args.extend(["--jobs", build_jobs.as_str()]);
        }
        self.args
            .extend(options.features.iter().flat_map(|s| ["--features", s]));
        if options.all_features {
            self.args.push("--all-features");
        }
        if options.no_default_features {
            self.args.push("--no-default-features");
        }
        if let Some(target) = &options.target {
            self.args.extend(["--target", target]);
        }
        if let Some(target_dir) = &options.target_dir {
            self.args.extend(["--target-dir", target_dir]);
        }
        if options.ignore_rust_version {
            self.args.push("--ignore-rust-version");
        }
        if options.unit_graph {
            self.args.push("--unit-graph");
        }
        if options.future_incompat_report {
            self.args.push("--future-incompat-report");
        }
        if options.frozen {
            self.args.push("--frozen");
        }
        if options.locked {
            self.args.push("--locked");
        }
        if options.offline {
            self.args.push("--offline");
        }
        self.args
            .extend(options.config.iter().flat_map(|s| ["--config", s.as_str()]));
        self.args.extend(
            options
                .unstable_flags
                .iter()
                .flat_map(|s| ["-Z", s.as_str()]),
        );

        // TODO: other options

        self
    }

    #[allow(dead_code)]
    pub(crate) fn all_args(&self) -> Vec<&str> {
        let mut all_args = vec![self.cargo_path.as_str(), self.command];
        all_args.extend_from_slice(&self.args);
        all_args
    }

    pub(crate) fn to_expression(&self) -> duct::Expression {
        let mut initial_args = vec![self.output.color.to_arg(), self.command];
        if let Some(path) = self.manifest_path {
            initial_args.extend(["--manifest-path", path.as_str()]);
        }
        duct::cmd(
            // Ensure that cargo gets picked up from PATH if necessary, by calling as_str
            // rather than as_std_path.
            self.cargo_path.as_std_path(),
            initial_args.into_iter().chain(self.args.iter().copied()),
        )
    }
}

fn cargo_path() -> Utf8PathBuf {
    match std::env::var_os("CARGO") {
        Some(cargo_path) => PathBuf::from(cargo_path)
            .try_into()
            .expect("CARGO env var is not valid UTF-8"),
        None => Utf8PathBuf::from("cargo"),
    }
}