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
use super::Error;
use std::path::PathBuf;
use std::{ffi::OsString, process::Command};
/// Cargo features flags
#[derive(Debug, Clone)]
pub enum Features {
/// Run cargo with `--features-all`
All,
/// Run cargo with `--no-default-features`
NoDefault,
/// Run cargo with `--features <FEATURES>`
Selected(Vec<String>),
}
/// A builder for configurating `cargo metadata` invocation.
#[derive(Debug, Clone, Default)]
pub struct MetadataCommand {
/// Path to `cargo` executable. If not set, this will use the
/// the `$CARGO` environment variable, and if that is not set, will
/// simply be `cargo`.
cargo_path: Option<PathBuf>,
/// Path to `Cargo.toml`
manifest_path: Option<PathBuf>,
/// Current directory of the `cargo metadata` process.
current_dir: Option<PathBuf>,
/// Output information only about workspace members and don't fetch dependencies.
no_deps: bool,
/// Collections of `CargoOpt::SomeFeatures(..)`
features: Vec<String>,
/// Latched `CargoOpt::AllFeatures`
all_features: bool,
/// Latched `CargoOpt::NoDefaultFeatures`
no_default_features: bool,
/// Arbitrary command line flags to pass to `cargo`. These will be added
/// to the end of the command line invocation.
other_options: Vec<String>,
/// Arbitrary environment variables to set when running `cargo`. These will be merged into
/// the calling environment, overriding any which clash.
env: std::collections::BTreeMap<OsString, OsString>,
/// Show stderr
verbose: bool,
}
impl MetadataCommand {
/// Creates a default `cargo metadata` command, which will look for
/// `Cargo.toml` in the ancestors of the current directory.
pub fn new() -> Self {
Self::default()
}
/// Path to `cargo` executable. If not set, this will use the
/// the `$CARGO` environment variable, and if that is not set, will
/// simply be `cargo`.
pub fn cargo_path(&mut self, path: impl Into<PathBuf>) -> &mut Self {
self.cargo_path = Some(path.into());
self
}
/// Path to `Cargo.toml`
pub fn manifest_path(&mut self, path: impl Into<PathBuf>) -> &mut Self {
self.manifest_path = Some(path.into());
self
}
/// Current directory of the `cargo metadata` process.
pub fn current_dir(&mut self, path: impl Into<PathBuf>) -> &mut Self {
self.current_dir = Some(path.into());
self
}
/// Output information only about workspace members and don't fetch dependencies.
pub fn no_deps(&mut self) -> &mut Self {
self.no_deps = true;
self
}
/// Which features to include.
pub fn features(&mut self, features: Features) -> &mut Self {
match features {
Features::Selected(features) => self.features.extend(features),
Features::NoDefault => {
assert!(
!self.no_default_features,
"Do not supply CargoOpt::NoDefaultFeatures more than once!"
);
self.no_default_features = true;
}
Features::All => {
assert!(
!self.all_features,
"Do not supply CargoOpt::AllFeatures more than once!"
);
self.all_features = true;
}
}
self
}
/// Arbitrary command line flags to pass to `cargo`. These will be added
/// to the end of the command line invocation.
pub fn other_options(&mut self, options: impl Into<Vec<String>>) -> &mut Self {
self.other_options = options.into();
self
}
/// Arbitrary environment variables to set when running `cargo`. These will be merged into
/// the calling environment, overriding any which clash.
pub fn env<K: Into<OsString>, V: Into<OsString>>(
&mut self,
key: K,
val: V,
) -> &mut MetadataCommand {
self.env.insert(key.into(), val.into());
self
}
/// Set whether to show stderr
pub fn verbose(&mut self, verbose: bool) -> &mut MetadataCommand {
self.verbose = verbose;
self
}
/// Builds a command for `cargo metadata`. This is the first
/// part of the work of `exec`.
pub fn cargo_command(&self) -> Command {
let cargo = self
.cargo_path
.clone()
.or_else(|| std::env::var("CARGO").map(PathBuf::from).ok())
.unwrap_or_else(|| PathBuf::from("cargo"));
let mut cmd = Command::new(cargo);
cmd.args(["metadata", "--format-version", "1"]);
if self.no_deps {
cmd.arg("--no-deps");
}
if let Some(path) = self.current_dir.as_ref() {
cmd.current_dir(path);
}
if !self.features.is_empty() {
cmd.arg("--features").arg(self.features.join(","));
}
if self.all_features {
cmd.arg("--all-features");
}
if self.no_default_features {
cmd.arg("--no-default-features");
}
if let Some(manifest_path) = &self.manifest_path {
cmd.arg("--manifest-path").arg(manifest_path.as_os_str());
}
cmd.args(&self.other_options);
cmd.envs(&self.env);
cmd
}
/// Parses `cargo metadata` output. `data` must have been
/// produced by a command built with `cargo_command`.
pub fn parse(data: &str) -> Result<super::Metadata, Error> {
let meta = serde_json::from_str(data)?;
Ok(meta)
}
/// Runs configured `cargo metadata` and returns parsed `Metadata`.
pub fn exec(&self) -> Result<super::Metadata, Error> {
let mut command = self.cargo_command();
if self.verbose {
command.stderr(std::process::Stdio::inherit());
}
let output = command.output()?;
if !output.status.success() {
return Err(Error::CargoMetadata {
stderr: String::from_utf8(output.stderr)?,
});
}
let stdout = std::str::from_utf8(&output.stdout)?
.lines()
.find(|line| line.starts_with('{'))
.ok_or(Error::NoJson)?;
Self::parse(stdout)
}
}