1use anyhow::{Context, Result, bail};
6use cargo_metadata::{CrateType, Message, Target, TargetKind};
7use std::path::{Path, PathBuf};
8use std::process::{Command, Stdio};
9
10#[derive(clap::Args, Debug, Default, Clone)]
15pub struct Features {
16 #[arg(short = 'F', long = "features", global = true, value_name = "FEATURES")]
18 features: Vec<String>,
19
20 #[arg(long, global = true)]
22 all_features: bool,
23
24 #[arg(long, global = true)]
26 no_default_features: bool,
27}
28
29impl Features {
30 fn apply_to(&self, cmd: &mut Command) {
32 for features in &self.features {
33 cmd.args(["--features", features]);
34 }
35
36 if self.all_features {
37 cmd.arg("--all-features");
38 }
39
40 if self.no_default_features {
41 cmd.arg("--no-default-features");
42 }
43 }
44}
45
46pub struct Metadata {
48 inner: cargo_metadata::Metadata,
49}
50
51impl Metadata {
52 pub fn load() -> Result<Self> {
57 let mut cmd = scrubbed_command("cargo");
59 cmd.args(["metadata", "--format-version=1"]);
60
61 let output = cmd
62 .stdout(Stdio::piped())
63 .stderr(Stdio::inherit())
64 .output()
65 .context("failed to run `cargo metadata`; is `cargo` installed?")?;
66
67 if !output.status.success() {
68 bail!("`cargo metadata` failed; run from inside a Cargo package");
69 }
70
71 let stdout =
72 String::from_utf8(output.stdout).context("`cargo metadata` produced invalid UTF-8")?;
73
74 let inner = cargo_metadata::MetadataCommand::parse(stdout)
75 .context("failed to parse `cargo metadata`")?;
76
77 Ok(Metadata { inner })
78 }
79
80 pub fn workspace_root(&self) -> &Path {
82 self.inner.workspace_root.as_std_path()
83 }
84
85 pub fn select_package(&self, name: Option<&str>) -> Result<Package<'_>> {
91 if let Some(name) = name {
92 return self
93 .inner
94 .workspace_packages()
95 .into_iter()
96 .find(|pkg| pkg.name.as_str() == name)
97 .map(Package)
98 .with_context(|| {
99 format!(
100 "package `{name}` not found in this workspace; available packages: {}",
101 self.package_names().join(", ")
102 )
103 });
104 }
105
106 self.inner.root_package().map(Package).with_context(|| {
107 format!(
108 "the workspace root has no package (virtual manifest); select one with \
109 `-p <package>`; available packages: {}",
110 self.package_names().join(", ")
111 )
112 })
113 }
114
115 fn package_names(&self) -> Vec<&str> {
116 self.inner
117 .workspace_packages()
118 .iter()
119 .map(|pkg| pkg.name.as_str())
120 .collect()
121 }
122}
123
124pub struct Package<'a>(&'a cargo_metadata::Package);
126
127impl Package<'_> {
128 pub fn name(&self) -> &str {
130 self.0.name.as_str()
131 }
132
133 pub fn root(&self) -> PathBuf {
135 self.0
136 .manifest_path
137 .parent()
138 .map(|path| path.as_std_path().to_path_buf())
139 .unwrap_or_default()
140 }
141
142 pub fn bin_names(&self) -> Vec<String> {
144 self.0
145 .targets
146 .iter()
147 .filter(|target| target.is_kind(TargetKind::Bin))
148 .map(|target| target.name.clone())
149 .collect()
150 }
151
152 pub fn has_lib(&self) -> bool {
155 self.0.targets.iter().any(|target| {
156 target.kind.iter().any(|kind| {
157 matches!(
158 kind,
159 TargetKind::Lib
160 | TargetKind::RLib
161 | TargetKind::DyLib
162 | TargetKind::CDyLib
163 | TargetKind::StaticLib
164 )
165 })
166 })
167 }
168}
169
170#[derive(Debug, Clone)]
172pub enum BuildTarget {
173 Bin(String),
175
176 Cdylib,
179}
180
181pub fn links_toasty(workspace_root: &Path, package: &str, features: &Features) -> Result<bool> {
191 let mut cmd = scrubbed_command("cargo");
192 cmd.current_dir(workspace_root);
193 cmd.args([
194 "tree", "-p", package, "--edges", "normal", "--prefix", "none",
195 ]);
196 features.apply_to(&mut cmd);
197
198 let output = cmd
199 .stdout(Stdio::piped())
200 .stderr(Stdio::inherit())
201 .output()
202 .context("failed to run `cargo tree`")?;
203
204 if !output.status.success() {
205 bail!("`cargo tree -p {package}` failed");
206 }
207
208 Ok(lists_toasty(&output.stdout))
209}
210
211fn lists_toasty(tree: &[u8]) -> bool {
215 String::from_utf8_lossy(tree)
216 .lines()
217 .any(|line| line.starts_with("toasty "))
218}
219
220pub fn build_artifact(
223 workspace_root: &Path,
224 package: &str,
225 target: &BuildTarget,
226 features: &Features,
227) -> Result<PathBuf> {
228 let mut cmd = scrubbed_command("cargo");
229 cmd.current_dir(workspace_root);
230
231 match target {
232 BuildTarget::Bin(name) => {
233 cmd.args(["build", "-p", package, "--bin", name]);
234 }
235 BuildTarget::Cdylib => {
236 cmd.args(["rustc", "-p", package, "--lib", "--crate-type", "cdylib"]);
237 }
238 }
239 features.apply_to(&mut cmd);
240 cmd.arg("--message-format=json-render-diagnostics");
241
242 let output = cmd
243 .stdout(Stdio::piped())
244 .stderr(Stdio::inherit())
245 .output()
246 .context("failed to run `cargo build`")?;
247
248 if !output.status.success() {
249 bail!("building `{package}` failed");
250 }
251
252 find_artifact(&output.stdout, target)
253 .with_context(|| format!("`cargo build` produced no artifact for `{package}`"))
254}
255
256fn find_artifact(messages: &[u8], target: &BuildTarget) -> Option<PathBuf> {
258 let mut fallback = None;
259
260 for message in Message::parse_stream(messages).filter_map(Result::ok) {
261 let Message::CompilerArtifact(artifact) = message else {
262 continue;
263 };
264
265 match target {
266 BuildTarget::Bin(name) => {
267 if artifact.target.is_kind(TargetKind::Bin)
268 && artifact.target.name == *name
269 && let Some(path) = artifact.executable
270 {
271 return Some(path.into_std_path_buf());
272 }
273 }
274 BuildTarget::Cdylib => {
275 if !is_cdylib(&artifact.target) {
278 continue;
279 }
280 for path in artifact.filenames {
281 let path = path.into_std_path_buf();
282 if !is_dylib(&path) {
283 continue;
284 }
285 let in_deps = path
286 .parent()
287 .and_then(Path::file_name)
288 .is_some_and(|dir| dir == "deps");
289 if in_deps {
290 fallback = Some(path);
291 } else {
292 return Some(path);
293 }
294 }
295 }
296 }
297 }
298
299 fallback
300}
301
302fn is_cdylib(target: &Target) -> bool {
303 target.crate_types.contains(&CrateType::CDyLib)
304}
305
306fn is_dylib(path: &Path) -> bool {
307 matches!(
308 path.extension().and_then(|ext| ext.to_str()),
309 Some("so" | "dylib" | "dll")
310 )
311}
312
313fn scrubbed_command(program: &str) -> Command {
316 let mut cmd = Command::new(program);
317 for (key, _) in std::env::vars_os() {
318 let Some(key_str) = key.to_str() else {
319 continue;
320 };
321 if is_injected(key_str) {
322 cmd.env_remove(key);
323 }
324 }
325 cmd
326}
327
328fn is_injected(key: &str) -> bool {
338 matches!(
339 key,
340 "CARGO"
341 | "CARGO_MANIFEST_DIR"
342 | "CARGO_MANIFEST_PATH"
343 | "CARGO_CRATE_NAME"
344 | "CARGO_BIN_NAME"
345 | "CARGO_PRIMARY_PACKAGE"
346 | "CARGO_TARGET_TMPDIR"
347 | "RUSTUP_TOOLCHAIN"
348 ) || key.starts_with("CARGO_PKG_")
349 || key.starts_with("CARGO_BIN_EXE_")
350}
351
352#[cfg(test)]
353mod tests {
354 use super::*;
355
356 #[test]
357 fn find_bin_artifact() {
358 let messages = br#"
359{"reason":"compiler-artifact","package_id":"path+file:///t#dep@0.0.0","manifest_path":"/t/Cargo.toml","target":{"kind":["lib"],"crate_types":["lib"],"name":"dep","src_path":"/t/src/lib.rs","edition":"2021","doctest":false,"test":true,"doc":true},"profile":{"opt_level":"0","debug_assertions":true,"overflow_checks":true,"test":false},"features":[],"filenames":["/t/debug/deps/libdep.rlib"],"executable":null,"fresh":false}
360{"reason":"compiler-artifact","package_id":"path+file:///t#app@0.0.0","manifest_path":"/t/Cargo.toml","target":{"kind":["bin"],"crate_types":["bin"],"name":"other","src_path":"/t/src/main.rs","edition":"2021","doctest":false,"test":true,"doc":true},"profile":{"opt_level":"0","debug_assertions":true,"overflow_checks":true,"test":false},"features":[],"filenames":["/t/debug/other"],"executable":"/t/debug/other","fresh":false}
361{"reason":"compiler-artifact","package_id":"path+file:///t#app@0.0.0","manifest_path":"/t/Cargo.toml","target":{"kind":["bin"],"crate_types":["bin"],"name":"app","src_path":"/t/src/main.rs","edition":"2021","doctest":false,"test":true,"doc":true},"profile":{"opt_level":"0","debug_assertions":true,"overflow_checks":true,"test":false},"features":[],"filenames":["/t/debug/app"],"executable":"/t/debug/app","fresh":false}
362{"reason":"build-finished","success":true}
363"#;
364 let path = find_artifact(messages, &BuildTarget::Bin("app".into())).unwrap();
365 assert_eq!(path, PathBuf::from("/t/debug/app"));
366 }
367
368 #[test]
369 fn toasty_is_matched_by_package_name_in_a_tree_listing() {
370 let tree = b"app v0.0.0 (/t)\ntoasty-core v0.11.0 (/x/toasty-core)\n\
373 toasty-cli v0.11.0 (/x/toasty-cli)\n";
374 assert!(!lists_toasty(tree));
375
376 let tree = b"app v0.0.0 (/t)\ntoasty v0.11.0 (/x/toasty)\n\
377 toasty-core v0.11.0 (/x/toasty-core)\n";
378 assert!(lists_toasty(tree));
379
380 assert!(!lists_toasty(b""));
381 }
382
383 #[test]
384 fn find_cdylib_artifact_prefers_uplifted_copy() {
385 let messages = br#"
386{"reason":"compiler-artifact","package_id":"path+file:///t#dep@0.0.0","manifest_path":"/t/Cargo.toml","target":{"kind":["lib"],"crate_types":["lib"],"name":"dep","src_path":"/t/src/lib.rs","edition":"2021","doctest":false,"test":true,"doc":true},"profile":{"opt_level":"0","debug_assertions":true,"overflow_checks":true,"test":false},"features":[],"filenames":["/t/debug/deps/libdep.rlib"],"executable":null,"fresh":false}
387{"reason":"compiler-artifact","package_id":"path+file:///t#app@0.0.0","manifest_path":"/t/Cargo.toml","target":{"kind":["lib"],"crate_types":["cdylib"],"name":"app","src_path":"/t/src/lib.rs","edition":"2021","doctest":false,"test":true,"doc":true},"profile":{"opt_level":"0","debug_assertions":true,"overflow_checks":true,"test":false},"features":[],"filenames":["/t/debug/deps/libapp.so","/t/debug/libapp.so"],"executable":null,"fresh":false}
388"#;
389 let path = find_artifact(messages, &BuildTarget::Cdylib).unwrap();
390 assert_eq!(path, PathBuf::from("/t/debug/libapp.so"));
391
392 let messages = br#"
394{"reason":"compiler-artifact","package_id":"path+file:///t#app@0.0.0","manifest_path":"/t/Cargo.toml","target":{"kind":["lib"],"crate_types":["cdylib"],"name":"app","src_path":"/t/src/lib.rs","edition":"2021","doctest":false,"test":true,"doc":true},"profile":{"opt_level":"0","debug_assertions":true,"overflow_checks":true,"test":false},"features":[],"filenames":["/t/debug/deps/libapp.so"],"executable":null,"fresh":false}
395"#;
396 let path = find_artifact(messages, &BuildTarget::Cdylib).unwrap();
397 assert_eq!(path, PathBuf::from("/t/debug/deps/libapp.so"));
398 }
399
400 #[test]
401 fn user_build_configuration_is_not_scrubbed() {
402 for key in [
404 "CARGO_HOME",
405 "CARGO_TARGET_DIR",
406 "CARGO_BUILD_RUSTFLAGS",
407 "CARGO_ENCODED_RUSTFLAGS",
408 "CARGO_NET_OFFLINE",
409 "CARGO_REGISTRIES_MINE_TOKEN",
410 "RUSTFLAGS",
411 "RUSTC",
412 "RUSTC_WRAPPER",
413 "RUSTC_WORKSPACE_WRAPPER",
414 ] {
415 assert!(!is_injected(key), "{key}");
416 }
417 }
418}