Skip to main content

toasty_cli/
cargo.rs

1//! Cargo interaction: `cargo metadata`, artifact builds, and JSON message
2//! parsing. Cargo runs as a subprocess with its injected environment scrubbed
3//! (see [`is_injected`]); stderr is inherited so the user sees build progress.
4
5use anyhow::{Context, Result, bail};
6use cargo_metadata::{CrateType, Message, Target, TargetKind};
7use std::path::{Path, PathBuf};
8use std::process::{Command, Stdio};
9
10/// Cargo's feature-selection flags, forwarded to the schema build.
11///
12/// A model behind a feature only exists in the artifact when the feature is
13/// on, so the flags must reach the build.
14#[derive(clap::Args, Debug, Default, Clone)]
15pub struct Features {
16    /// Space or comma separated list of features to activate
17    #[arg(short = 'F', long = "features", global = true, value_name = "FEATURES")]
18    features: Vec<String>,
19
20    /// Activate all available features
21    #[arg(long, global = true)]
22    all_features: bool,
23
24    /// Do not activate the `default` feature
25    #[arg(long, global = true)]
26    no_default_features: bool,
27}
28
29impl Features {
30    /// Appends the flags verbatim; cargo splits the lists itself.
31    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
46/// Output of `cargo metadata`.
47pub struct Metadata {
48    inner: cargo_metadata::Metadata,
49}
50
51impl Metadata {
52    /// Runs `cargo metadata` in the current directory. The resolve is kept
53    /// only for its root: without it, the "current directory" package falls
54    /// back to the workspace root manifest instead of the package the user is
55    /// standing in.
56    pub fn load() -> Result<Self> {
57        // `MetadataCommand` would spawn cargo itself, bypassing the scrubbing.
58        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    /// The workspace root directory.
81    pub fn workspace_root(&self) -> &Path {
82        self.inner.workspace_root.as_std_path()
83    }
84
85    /// Selects the target package: `-p <name>`, or the workspace root package.
86    ///
87    /// Only workspace members qualify: selecting a registry or out-of-workspace
88    /// path dependency would write the migration tree into someone else's
89    /// package.
90    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
124/// A package entry from `cargo metadata`.
125pub struct Package<'a>(&'a cargo_metadata::Package);
126
127impl Package<'_> {
128    /// The package name.
129    pub fn name(&self) -> &str {
130        self.0.name.as_str()
131    }
132
133    /// The directory containing the package's `Cargo.toml`.
134    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    /// Names of the package's `[[bin]]` targets.
143    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    /// Returns `true` if the package has a lib target. Any linkable crate type
153    /// counts: `cargo rustc --crate-type cdylib` overrides the manifest.
154    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/// The artifact to build for schema extraction.
171#[derive(Debug, Clone)]
172pub enum BuildTarget {
173    /// Build a `[[bin]]` target; the artifact is executed directly.
174    Bin(String),
175
176    /// Build the lib target as a `cdylib`; the artifact is loaded with
177    /// `dlopen` by `toasty __load-cdylib`.
178    Cdylib,
179}
180
181/// Returns `true` if `toasty` is a normal dependency of `package`, directly
182/// or transitively, under the selected features.
183///
184/// Extraction runs the built artifact. Without `toasty` linked there is no
185/// dump constructor, and running the artifact would run the user's `main`.
186/// `cargo tree` is asked rather than `cargo metadata` because `-p` and the
187/// feature flags scope it exactly like the build; only normal edges count,
188/// since build- and proc-macro dependencies are compiled for the host and
189/// never linked into the artifact.
190pub 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
211/// Whether a `cargo tree --prefix none` listing names the `toasty` package.
212/// Each line is `<name> v<version> (<source>)`, so the name is matched up to
213/// the space, which keeps `toasty-core` and friends out.
214fn lists_toasty(tree: &[u8]) -> bool {
215    String::from_utf8_lossy(tree)
216        .lines()
217        .any(|line| line.starts_with("toasty "))
218}
219
220/// Builds the selected target of `package` in the `dev` profile and returns
221/// the artifact path.
222pub 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
256/// Extracts the artifact path from a `--message-format=json` stream.
257fn 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                // Only the requested package is built as a cdylib. Cargo lists
276                // both the `deps/` copy and the uplifted one; prefer the latter.
277                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
313/// Creates a command with the environment variables cargo and rustup inject
314/// removed. See [`is_injected`].
315fn 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
328/// Whether an environment variable was injected by cargo or rustup rather
329/// than set by the user.
330///
331/// Scrubbing them keeps builds spawned by the CLI fingerprint-identical to the
332/// user's own (running the CLI under `cargo run` would otherwise cache-bust
333/// them) and stops `RUSTUP_TOOLCHAIN` pinning the build to the CLI's
334/// toolchain. Only the variables cargo sets for the crate it runs are listed;
335/// `CARGO_HOME`, `CARGO_BUILD_RUSTFLAGS`, `CARGO_NET_*`, `RUSTFLAGS`, and the
336/// like are the user's build configuration and must survive.
337fn 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        // `--prefix none` prints one `<name> v<version> (<source>)` line per
371        // package; `toasty-core` and the CLI's own package must not count.
372        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        // Fall back to the deps/ copy when no uplifted path is listed.
393        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        // Cargo configuration the user set themselves, never injected.
403        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}