Skip to main content

xtask/
main.rs

1#![feature(variant_count)]
2
3mod dist;
4mod solvers;
5
6use std::{
7    collections::BTreeMap,
8    env,
9    ffi::OsStr,
10    fs,
11    mem::variant_count,
12    path::{Path, PathBuf},
13    process::{Command, ExitStatus},
14};
15
16use anyhow::anyhow;
17use cargo_metadata::{
18    camino::{Utf8Path, Utf8PathBuf},
19    Artifact, Message, TargetKind,
20};
21use flux_sysroot::{
22    bin_dir, bin_path, default_flux_sysroot_dir,
23    dev::{default_flags, Suite},
24    install::{self, copy_file, create_dir, link_binaries, remove_path, replace_dir, sibling_path},
25    lib_dir, parse_toolchain_file, FluxVersion, SysrootCrate, SysrootManifest, FLUX_SYSROOT,
26    SYSROOT_MANIFEST,
27};
28
29use crate::solvers::BundleSolvers;
30
31xflags::xflags! {
32    cmd xtask {
33        /// If true, run all cargo commands with `--offline`
34        optional --offline
35        /// If true, run cargo build commands with --features rust-fixpiont
36        optional --rust-fixpoint
37        /// Run regression tests
38        cmd test {
39            /// Only run tests containing `filter` as a substring.
40            optional filter: String
41            /// Run only the named suite(s). May be repeated. If omitted, all suites run.
42            repeated --suite suite: Suite
43            /// Timeout in seconds for each fixpoint query (passed as `-Ffixpoint-timeout`)
44            optional --fixpoint-timeout seconds: u64
45        }
46        /// Run lean benchmarks: emit lean files for each test in tests/pos/
47        cmd lean-bench {
48            /// Only run tests containing `filter` as a substring.
49            optional filter: String
50        }
51        /// Run the `flux` binary on the given input file.
52        cmd run {
53            /// Input file
54            required input: PathBuf
55            /// Extra options to pass to the `flux` binary, e.g., `cargo x run file.rs -- -Zdump-mir=renumber`
56            repeated opts: String
57            /// Do not build Flux libs for extern specs
58            optional --no-extern-specs
59        }
60        /// Expand Flux macros
61        cmd expand {
62            /// Input file
63            required input: PathBuf
64        }
65        /// Install the Flux sysroot (binaries and precompiled libraries) to `~/.flux/sysroot` and link
66        /// `flux` and `cargo-flux` from `~/.cargo/bin`
67        cmd install {
68            /// Select build profile for the `flux-driver`, either 'release', 'dev', or 'profiling'. Default 'release'
69            optional --profile profile: Profile
70            /// Do not install Flux libs or extern specs
71            optional --no-extern-specs
72            /// Download prebuilt `fixpoint` and `z3` into the sysroot, if there are any for this platform
73            optional --bundle-solvers
74        }
75        /// Build a release archive of the Flux sysroot for this platform, with the solvers bundled
76        cmd dist {
77            /// Directory to write the archive to. Default `target/dist`
78            optional --out-dir dir: PathBuf
79        }
80        /// Uninstall Flux binaries and libraries
81        cmd uninstall { }
82        /// Generate precompiled libraries
83        cmd build-sysroot { }
84        /// Build the documentation
85        cmd doc { }
86        /// Start blick, which runs Flux on programs and shows its checker trace in the browser. The
87        /// page can open the regression tests in `tests/tests`
88        cmd blick {
89            /// The port to listen on (on 127.0.0.1). Default 8765
90            optional --port port: u16
91        }
92    }
93}
94
95#[derive(Clone, Copy, Debug)]
96enum Profile {
97    Release,
98    Dev,
99    Profiling,
100}
101
102impl Profile {
103    fn as_str(self) -> &'static str {
104        match self {
105            Profile::Release => "release",
106            Profile::Dev => "dev",
107            Profile::Profiling => "profiling",
108        }
109    }
110}
111
112impl std::str::FromStr for Profile {
113    type Err = &'static str;
114
115    fn from_str(s: &str) -> Result<Self, Self::Err> {
116        match s {
117            "release" => Ok(Self::Release),
118            "dev" => Ok(Self::Dev),
119            "profiling" => Ok(Self::Profiling),
120            _ => Err("invalid profile"),
121        }
122    }
123}
124
125fn main() -> anyhow::Result<()> {
126    let cmd = match Xtask::from_env() {
127        Ok(cmd) => cmd,
128        Err(err) => {
129            if err.is_help() {
130                println!("{}", Xtask::HELP_);
131                std::process::exit(0);
132            } else {
133                eprintln!("{err}");
134                std::process::exit(2);
135            }
136        }
137    };
138
139    if cmd.offline {
140        // Inherited by every cargo we run, including the one `cargo-flux` runs to build the libraries.
141        // SAFETY: xtask is single-threaded, so nothing reads the environment concurrently.
142        unsafe { env::set_var("CARGO_NET_OFFLINE", "true") };
143        if matches!(&cmd.subcommand, XtaskCmd::Install(args) if args.bundle_solvers) {
144            return Err(anyhow!("`--bundle-solvers` needs to download the solvers, so it can't be used with `--offline`"));
145        }
146        if matches!(&cmd.subcommand, XtaskCmd::Dist(_)) {
147            return Err(anyhow!(
148                "`dist` needs to download the solvers, so it can't be used with `--offline`"
149            ));
150        }
151    }
152
153    match cmd.subcommand {
154        XtaskCmd::Test(args) => test(args, cmd.rust_fixpoint),
155        XtaskCmd::LeanBench(args) => lean_bench(args, cmd.rust_fixpoint),
156        XtaskCmd::Run(args) => run(args, cmd.rust_fixpoint),
157        XtaskCmd::Install(args) => install(&args, cmd.rust_fixpoint),
158        XtaskCmd::Doc(args) => doc(args),
159        XtaskCmd::BuildSysroot(_) => {
160            let config = SysrootConfig {
161                profile: Profile::Dev,
162                rust_fixpoint: cmd.rust_fixpoint,
163                dst: local_sysroot_dir()?,
164                build_libs: BuildLibs { force: true, libs: FluxLib::ALL },
165                bundle_solvers: BundleSolvers::No,
166            };
167            install_sysroot(&config)?;
168            Ok(())
169        }
170        XtaskCmd::Dist(args) => dist::dist(&args, cmd.rust_fixpoint),
171        XtaskCmd::Uninstall(_) => uninstall(),
172        XtaskCmd::Expand(args) => expand(args),
173        XtaskCmd::Blick(args) => blick(&args),
174    }
175}
176
177fn run_tests(
178    flux_driver: &Utf8Path,
179    sysroot: &Path,
180    suite: &str,
181    filter: Option<&str>,
182    fixpoint_timeout: Option<u64>,
183) -> anyhow::Result<()> {
184    Command::new("cargo")
185        .args(["test", "-p", "tests", "--"])
186        .args(["--flux-driver", flux_driver.as_str()])
187        .args(["--sysroot".as_ref(), sysroot.as_os_str()])
188        .args(["--suite", suite])
189        .args_if_some(filter, |filter| ["--filter", filter])
190        .args_if_some(fixpoint_timeout, |timeout| {
191            ["--fixpoint-timeout".to_string(), timeout.to_string()]
192        })
193        .run()
194}
195
196fn test(args: Test, rust_fixpoint: bool) -> anyhow::Result<()> {
197    let dst = local_sysroot_dir()?;
198
199    let suites: &[Suite] = if args.suite.is_empty() { Suite::ALL } else { &args.suite };
200
201    for suite in suites {
202        let libs = match suite {
203            Suite::Basic => &[FluxLib::FluxAttrs],
204            Suite::WithDeps => FluxLib::ALL,
205        };
206        let config = SysrootConfig {
207            profile: Profile::Dev,
208            rust_fixpoint,
209            dst: dst.clone(),
210            build_libs: BuildLibs { force: false, libs },
211            bundle_solvers: BundleSolvers::No,
212        };
213        let flux_driver = install_sysroot(&config)?;
214        run_tests(&flux_driver, &dst, suite.name(), args.filter.as_deref(), args.fixpoint_timeout)?;
215    }
216    Ok(())
217}
218
219fn lean_bench(args: LeanBench, rust_fixpoint: bool) -> anyhow::Result<()> {
220    use walkdir::WalkDir;
221
222    let config = SysrootConfig {
223        profile: Profile::Dev,
224        rust_fixpoint,
225        dst: local_sysroot_dir()?,
226        build_libs: BuildLibs { force: false, libs: FluxLib::ALL },
227        bundle_solvers: BundleSolvers::No,
228    };
229    let flux_driver = install_sysroot(&config)?;
230
231    let pos_path = PathBuf::from("tests/tests/pos");
232    let lean_bench_dir = PathBuf::from("tests/lean_bench");
233
234    if !pos_path.exists() {
235        return Err(anyhow!("tests/tests/pos directory not found"));
236    }
237
238    // Find all .rs test files
239    let test_files: Vec<PathBuf> = WalkDir::new(&pos_path)
240        .into_iter()
241        .filter_map(|e| e.ok())
242        .filter(|e| e.path().extension().is_some_and(|ext| ext == "rs"))
243        .map(|e| e.path().to_path_buf())
244        .filter(|path| {
245            // Apply filter if specified
246            if let Some(ref filter) = args.filter {
247                path.to_string_lossy().contains(filter)
248            } else {
249                true
250            }
251        })
252        .collect();
253
254    if test_files.is_empty() {
255        if args.filter.is_some() {
256            eprintln!("No test files found matching filter: {:?}", args.filter);
257        } else {
258            eprintln!("No test files found under {:?}", pos_path);
259        }
260        return Ok(());
261    }
262
263    eprintln!("Found {} test files", test_files.len());
264    eprintln!("{}", "-".repeat(60));
265
266    let mut failures: Vec<(PathBuf, String)> = Vec::new();
267    let mut successes = 0;
268
269    for (i, test_path) in test_files.iter().enumerate() {
270        let rel_path = test_path.strip_prefix(&pos_path).unwrap();
271
272        // Create lean output dir: ./tests/lean_bench/<path>/<to>/<file>/
273        let mut lean_dir = lean_bench_dir.clone();
274        if let Some(parent) = rel_path.parent() {
275            if parent != Path::new("") {
276                lean_dir.push(parent);
277            }
278        }
279        if let Some(stem) = rel_path.file_stem() {
280            lean_dir.push(stem);
281        }
282
283        eprint!("[{}/{}] Running: {} ... ", i + 1, test_files.len(), rel_path.display());
284
285        // Create the output directory
286        if let Err(e) = fs::create_dir_all(&lean_dir) {
287            eprintln!("ERROR");
288            failures.push((test_path.clone(), format!("Failed to create directory: {}", e)));
289            continue;
290        }
291
292        // Build rustc flags
293        let mut rustc_flags = default_flags(&config.dst, SysrootManifest::extern_args(&config.dst));
294        rustc_flags.push("-Flean=emit".to_string());
295        rustc_flags.push(format!("-Flean-dir={}", lean_dir.display()));
296
297        // Run the test
298        let result = Command::new(&flux_driver)
299            .args(&rustc_flags)
300            .arg(test_path)
301            .env(FLUX_SYSROOT, &config.dst)
302            .stdout(std::process::Stdio::null())
303            .stderr(std::process::Stdio::piped())
304            .output();
305
306        match result {
307            Ok(output) if output.status.success() => {
308                eprintln!("OK");
309                successes += 1;
310            }
311            Ok(output) => {
312                eprintln!("ERROR");
313                let stderr = String::from_utf8_lossy(&output.stderr).to_string();
314                failures.push((test_path.clone(), stderr));
315            }
316            Err(e) => {
317                eprintln!("ERROR");
318                failures.push((test_path.clone(), e.to_string()));
319            }
320        }
321    }
322
323    // Print summary
324    eprintln!();
325    eprintln!("{}", "=".repeat(60));
326    eprintln!("SUMMARY");
327    eprintln!("{}", "=".repeat(60));
328    eprintln!("Total tests run: {}", test_files.len());
329    eprintln!("Passed: {}", successes);
330    eprintln!("Failed: {}", failures.len());
331
332    if !failures.is_empty() {
333        eprintln!();
334        eprintln!("Failed tests:");
335        for (path, _) in &failures {
336            let rel_path = path.strip_prefix(&pos_path).unwrap_or(path);
337            eprintln!("  - {}", rel_path.display());
338        }
339        eprintln!("{}", "=".repeat(60));
340        return Err(anyhow!("{} test(s) failed", failures.len()));
341    }
342
343    eprintln!("{}", "=".repeat(60));
344    Ok(())
345}
346
347fn run(args: Run, rust_fixpoint: bool) -> anyhow::Result<()> {
348    let libs = if args.no_extern_specs { &[FluxLib::FluxRs] } else { FluxLib::ALL };
349    run_inner(
350        args.input,
351        BuildLibs { force: false, libs },
352        ["-Ztrack-diagnostics=y".to_string()]
353            .into_iter()
354            .chain(args.opts),
355        rust_fixpoint,
356    )?;
357    Ok(())
358}
359
360fn expand(args: Expand) -> Result<(), anyhow::Error> {
361    run_inner(
362        args.input,
363        BuildLibs { force: false, libs: &[FluxLib::FluxRs] },
364        ["-Zunpretty=expanded".to_string()],
365        false,
366    )?;
367    Ok(())
368}
369
370fn run_inner(
371    input: PathBuf,
372    build_libs: BuildLibs,
373    flags: impl IntoIterator<Item = String>,
374    rust_fixpoint: bool,
375) -> Result<(), anyhow::Error> {
376    let config = SysrootConfig {
377        profile: Profile::Dev,
378        rust_fixpoint,
379        dst: local_sysroot_dir()?,
380        build_libs,
381        bundle_solvers: BundleSolvers::No,
382    };
383
384    let flux_driver = install_sysroot(&config)?;
385
386    let mut rustc_flags = default_flags(&config.dst, SysrootManifest::extern_args(&config.dst));
387    rustc_flags.extend(flags);
388
389    Command::new(flux_driver)
390        .args(&rustc_flags)
391        .arg(&input)
392        .env(FLUX_SYSROOT, &config.dst)
393        .run()
394}
395
396fn install(args: &Install, rust_fixpoint: bool) -> anyhow::Result<()> {
397    let libs = if args.no_extern_specs { &[FluxLib::FluxRs] } else { FluxLib::ALL };
398    let config = SysrootConfig {
399        profile: args.profile(),
400        rust_fixpoint,
401        dst: default_flux_sysroot_dir(),
402        build_libs: BuildLibs { force: false, libs },
403        bundle_solvers: if args.bundle_solvers {
404            BundleSolvers::Yes { required: false }
405        } else {
406            BundleSolvers::No
407        },
408    };
409    install_sysroot(&config)?;
410    link_binaries(&config.dst)
411}
412
413fn uninstall() -> anyhow::Result<()> {
414    install::uninstall(&default_flux_sysroot_dir())
415}
416
417fn doc(_args: Doc) -> anyhow::Result<()> {
418    Command::new("cargo")
419        .args(["doc", "--workspace", "--document-private-items", "--no-deps"])
420        .env("RUSTDOCFLAGS", "-Zunstable-options --enable-index-page")
421        .run()?;
422    Ok(())
423}
424
425fn blick(args: &Blick) -> anyhow::Result<()> {
426    Command::new("cargo")
427        .args(["run", "--package", "blick"])
428        .arg("--")
429        .args_if_some(args.port, |port| ["--port".to_string(), port.to_string()])
430        // the regression tests, to open in the page
431        .arg(Path::new(env!("CARGO_MANIFEST_DIR")).join("../tests/tests"))
432        .run()
433}
434
435fn build_binary(bin: &str, profile: Profile, rust_fixpoint: bool) -> anyhow::Result<Utf8PathBuf> {
436    Command::new("cargo")
437        .args(["build", "--bin", bin, "--profile", profile.as_str()])
438        .args_if(rust_fixpoint, ["--features", "rust-fixpoint"])
439        .run_with_cargo_metadata()?
440        .into_iter()
441        .find(|artifact| artifact.target.name == bin && artifact.target.is_kind(TargetKind::Bin))
442        .and_then(|artifact| artifact.executable)
443        .ok_or_else(|| anyhow!("cannot find binary: `{bin}`"))
444}
445
446struct SysrootConfig {
447    /// Profile used to build `flux-driver` and libraries
448    profile: Profile,
449    /// Whether rust-fixpoint should be enabled to build `flux-driver`
450    rust_fixpoint: bool,
451    /// Destination path for sysroot artifacts
452    dst: PathBuf,
453    build_libs: BuildLibs,
454    /// Whether to download prebuilt solvers into the sysroot
455    bundle_solvers: BundleSolvers,
456}
457
458struct BuildLibs {
459    /// If true, forces a clean build.
460    force: bool,
461    /// List of libraries to install
462    libs: &'static [FluxLib],
463}
464
465#[allow(clippy::enum_variant_names)]
466#[derive(Clone, Copy)]
467enum FluxLib {
468    FluxAlloc,
469    FluxAttrs,
470    FluxCore,
471    FluxRs,
472}
473
474impl FluxLib {
475    const ALL: &[FluxLib] = &[Self::FluxAlloc, Self::FluxAttrs, Self::FluxCore, Self::FluxRs];
476
477    const _ASSERT_ALL: () = { assert!(Self::ALL.len() == variant_count::<Self>()) };
478
479    const fn package_name(self) -> &'static str {
480        match self {
481            FluxLib::FluxAlloc => "flux-alloc",
482            FluxLib::FluxAttrs => "flux-attrs",
483            FluxLib::FluxCore => "flux-core",
484            FluxLib::FluxRs => "flux-rs",
485        }
486    }
487
488    const fn target_name(self) -> &'static str {
489        match self {
490            FluxLib::FluxAlloc => "flux_alloc",
491            FluxLib::FluxAttrs => "flux_attrs",
492            FluxLib::FluxCore => "flux_core",
493            FluxLib::FluxRs => "flux_rs",
494        }
495    }
496
497    /// Whether this lib's specs are injected as force externs under `-Fstd-extern-specs`.
498    const fn is_std_extern_spec(self) -> bool {
499        match self {
500            FluxLib::FluxCore | FluxLib::FluxAlloc => true,
501            FluxLib::FluxAttrs | FluxLib::FluxRs => false,
502        }
503    }
504
505    fn from_artifact(artifact: &Artifact) -> Option<FluxLib> {
506        Self::ALL
507            .iter()
508            .copied()
509            .find(|lib| artifact.target.name == lib.target_name())
510    }
511}
512
513/// Builds the sysroot in a staging directory next to `config.dst` and then replaces `config.dst`
514/// with it, so a failed build leaves the existing sysroot untouched.
515fn install_sysroot(config: &SysrootConfig) -> anyhow::Result<Utf8PathBuf> {
516    let staging = sibling_path(&config.dst, "new");
517    remove_path(&staging)?;
518    create_dir(&bin_dir(&staging))?;
519    create_dir(&lib_dir(&staging))?;
520
521    let flux_driver = build_binary("flux-driver", config.profile, config.rust_fixpoint)?;
522    copy_file(&flux_driver, bin_path(&staging, "flux-driver"))?;
523
524    // The libraries are built with `cargo-flux` using the staging sysroot, which needs a valid
525    // manifest to find the toolchain. Write one without crates now and add them once built.
526    let mut manifest = SysrootManifest {
527        toolchain: rust_toolchain()?,
528        version: flux_version(),
529        crates: BTreeMap::new(),
530    };
531    write_sysroot_toml(&manifest, &staging)?;
532
533    let cargo_flux = build_binary("cargo-flux", config.profile, config.rust_fixpoint)?;
534    copy_file(&cargo_flux, bin_path(&staging, "cargo-flux"))?;
535    let flux = build_binary("flux", config.profile, config.rust_fixpoint)?;
536    copy_file(&flux, bin_path(&staging, "flux"))?;
537
538    if config.build_libs.force {
539        Command::new(&cargo_flux)
540            .args(["flux", "clean"])
541            .env(FLUX_SYSROOT, &staging)
542            .run()?;
543    }
544    let artifacts = Command::new(&cargo_flux)
545        .args(["flux", "build"])
546        .args(
547            config
548                .build_libs
549                .libs
550                .iter()
551                .flat_map(|lib| ["-p", lib.package_name()]),
552        )
553        .env(FLUX_SYSROOT, &staging)
554        .run_with_cargo_metadata()?;
555    manifest.crates = copy_artifacts(&artifacts, &lib_dir(&staging))?;
556    write_sysroot_toml(&manifest, &staging)?;
557
558    if let BundleSolvers::Yes { required } = config.bundle_solvers {
559        solvers::bundle(&staging, required)?;
560    }
561
562    replace_dir(&staging, &config.dst)?;
563    Ok(flux_driver)
564}
565
566/// Version of the Flux sources, read from git when the sysroot is built.
567fn flux_version() -> FluxVersion {
568    FluxVersion {
569        sha: git(&["describe", "--always", "--dirty=*"]),
570        sha_full: git(&["describe", "--always", "--abbrev=0", "--dirty=*"]),
571        date: git(&["show", "-s", "--format=%cd", "--date=format:%Y-%m-%d", "HEAD"]),
572    }
573}
574
575/// Rust toolchain used to build the sysroot. When xtask runs through rustup, `RUSTUP_TOOLCHAIN`
576/// holds the active toolchain, whether it comes from `+toolchain` or `rust-toolchain.toml`.
577/// Otherwise, it's the one in `rust-toolchain.toml`.
578fn rust_toolchain() -> anyhow::Result<String> {
579    if let Ok(toolchain) = env::var("RUSTUP_TOOLCHAIN") {
580        return Ok(toolchain);
581    }
582    let path = workspace_root().join("rust-toolchain.toml");
583    let content = fs::read_to_string(&path)
584        .map_err(|err| anyhow!("failed to read `{}`: {err}", path.display()))?;
585    Ok(parse_toolchain_file(&content)?)
586}
587
588fn workspace_root() -> &'static Path {
589    Path::new(env!("CARGO_MANIFEST_DIR")).parent().unwrap()
590}
591
592/// Runs git in the workspace root and returns its trimmed output, or `unknown` if it fails.
593fn git(args: &[&str]) -> String {
594    Command::new("git")
595        .args(args)
596        .current_dir(workspace_root())
597        .output()
598        .ok()
599        .filter(|output| output.status.success())
600        .and_then(|output| String::from_utf8(output.stdout).ok())
601        .map_or_else(|| "unknown".to_string(), |stdout| stdout.trim().to_string())
602}
603
604fn copy_artifacts(
605    artifacts: &[Artifact],
606    lib_dir: &Path,
607) -> anyhow::Result<BTreeMap<String, SysrootCrate>> {
608    let mut crates = BTreeMap::<String, SysrootCrate>::new();
609    for artifact in artifacts {
610        let Some(lib) = FluxLib::from_artifact(artifact) else { continue };
611
612        let entry = crates.entry(lib.target_name().to_string()).or_default();
613        entry.extern_spec = lib.is_std_extern_spec();
614
615        for filename in &artifact.filenames {
616            copy_artifact(artifact, filename, lib_dir, entry)?;
617        }
618    }
619    Ok(crates)
620}
621
622fn copy_artifact(
623    artifact: &Artifact,
624    filename: &Utf8Path,
625    dst: &Path,
626    entry: &mut SysrootCrate,
627) -> anyhow::Result<()> {
628    let name = sysroot_file_name(artifact, filename)?;
629    copy_file(filename, dst.join(&name))?;
630    record_artifact(entry, &name);
631
632    if filename.extension() == Some("rmeta") {
633        // Flux finds its own metadata by swapping the extension on the resolved `.rmeta` path,
634        // so the two must travel together.
635        let fluxmeta = filename.with_extension("fluxmeta");
636        if fluxmeta.exists() {
637            let name = sysroot_file_name(artifact, &fluxmeta)?;
638            copy_file(&fluxmeta, dst.join(&name))?;
639            record_artifact(entry, &name);
640        }
641    }
642    Ok(())
643}
644
645fn record_artifact(entry: &mut SysrootCrate, name: &str) {
646    let slot = match Utf8Path::new(name).extension() {
647        Some("rlib") => &mut entry.rlib,
648        Some("rmeta") => &mut entry.rmeta,
649        Some("fluxmeta") => &mut entry.fluxmeta,
650        // Proc macros are always built for the host. Anything else cargo reports, like `.pdb`
651        // debug symbols on Windows, is not a crate.
652        Some(extension) if extension == env::consts::DLL_EXTENSION => &mut entry.dylib,
653        _ => return,
654    };
655    *slot = Some(name.to_string());
656}
657
658/// Name an artifact gets inside the sysroot.
659///
660/// Cargo reports an uplifted, hash-free `.rlib` for these crates but a hashed `.rmeta`, and rustc
661/// pairs the two by the infix between `lib<crate>` and the extension, so we cannot reuse cargo's
662/// names. Naming by crate keeps the pairing intact.
663fn sysroot_file_name(artifact: &Artifact, filename: &Utf8Path) -> anyhow::Result<String> {
664    let krate = &artifact.target.name;
665    let name = filename
666        .file_name()
667        .ok_or_else(|| anyhow!("artifact `{filename}` has no file name"))?;
668    let extension = filename
669        .extension()
670        .ok_or_else(|| anyhow!("artifact `{filename}` has no extension"))?;
671    match extension {
672        // rustc hardcodes the `lib` prefix for its own formats on every target.
673        "rlib" | "rmeta" | "fluxmeta" => Ok(format!("lib{krate}.{extension}")),
674        // A dylib's prefix is target-dependent (empty on Windows), so recover it from the name
675        // cargo produced.
676        _ => {
677            let prefix = name
678                .find(krate.as_str())
679                .map(|idx| &name[..idx])
680                .ok_or_else(|| anyhow!("artifact `{name}` does not mention crate `{krate}`"))?;
681            Ok(format!("{prefix}{krate}.{extension}"))
682        }
683    }
684}
685
686fn write_sysroot_toml(manifest: &SysrootManifest, sysroot: &Path) -> anyhow::Result<()> {
687    let content = toml::to_string(manifest)?;
688    let path = sysroot.join(SYSROOT_MANIFEST);
689    eprintln!("$ write {}", path.display());
690    fs::write(&path, &content).map_err(|e| anyhow!("failed to write `{}`: {e}", path.display()))
691}
692
693impl Install {
694    fn profile(&self) -> Profile {
695        self.profile.unwrap_or(Profile::Release)
696    }
697}
698
699fn local_sysroot_dir() -> anyhow::Result<PathBuf> {
700    Ok(Path::new(file!())
701        .canonicalize()?
702        .ancestors()
703        .nth(3)
704        .unwrap()
705        .join("sysroot"))
706}
707
708fn check_status(st: ExitStatus) -> anyhow::Result<()> {
709    if st.success() {
710        return Ok(());
711    }
712    let err = match st.code() {
713        Some(code) => anyhow!("command exited with non-zero code: {code}"),
714        #[cfg(unix)]
715        None => {
716            use std::os::unix::process::ExitStatusExt;
717            match st.signal() {
718                Some(sig) => anyhow!("command was terminated by a signal: {sig}"),
719                None => anyhow!("command was terminated by a signal"),
720            }
721        }
722        #[cfg(not(unix))]
723        None => anyhow!("command was terminated by a signal"),
724    };
725    Err(err)
726}
727
728fn display_command(cmd: &Command) {
729    for var in cmd.get_envs() {
730        if let Some(val) = var.1 {
731            eprintln!("$ export {}={}", var.0.display(), val.display());
732        }
733    }
734
735    let prog = cmd.get_program();
736    eprint!("$ {}", prog.display());
737    for arg in cmd.get_args() {
738        eprint!(" {}", arg.display());
739    }
740    eprintln!();
741}
742
743trait CommandExt {
744    fn run(&mut self) -> anyhow::Result<()>;
745    fn run_with_cargo_metadata(&mut self) -> anyhow::Result<Vec<Artifact>>;
746    /// Add `args` if `cond` is true.
747    fn args_if<I, S>(&mut self, cond: bool, args: I) -> &mut Self
748    where
749        I: IntoIterator<Item = S>,
750        S: AsRef<OsStr>;
751    /// If `opt` is `Some`, add the arguments computed by `f` from its value.
752    fn args_if_some<T, I, S>(&mut self, opt: Option<T>, f: impl FnOnce(T) -> I) -> &mut Self
753    where
754        I: IntoIterator<Item = S>,
755        S: AsRef<OsStr>;
756}
757
758impl CommandExt for Command {
759    fn args_if<I, S>(&mut self, cond: bool, args: I) -> &mut Self
760    where
761        I: IntoIterator<Item = S>,
762        S: AsRef<OsStr>,
763    {
764        if cond {
765            self.args(args);
766        }
767        self
768    }
769
770    fn args_if_some<T, I, S>(&mut self, opt: Option<T>, f: impl FnOnce(T) -> I) -> &mut Self
771    where
772        I: IntoIterator<Item = S>,
773        S: AsRef<OsStr>,
774    {
775        if let Some(val) = opt {
776            self.args(f(val));
777        }
778        self
779    }
780
781    fn run(&mut self) -> anyhow::Result<()> {
782        display_command(self);
783        let mut child = self.spawn()?;
784        check_status(child.wait()?)
785    }
786
787    fn run_with_cargo_metadata(&mut self) -> anyhow::Result<Vec<Artifact>> {
788        self.arg("--message-format=json-render-diagnostics")
789            .stdout(std::process::Stdio::piped());
790
791        display_command(self);
792
793        let mut child = self.spawn()?;
794
795        let mut artifacts = vec![];
796        let reader = std::io::BufReader::new(child.stdout.take().unwrap());
797        for message in cargo_metadata::Message::parse_stream(reader) {
798            match message.unwrap() {
799                Message::CompilerMessage(msg) => {
800                    println!("{msg}");
801                }
802                Message::CompilerArtifact(artifact) => {
803                    artifacts.push(artifact);
804                }
805                _ => (),
806            }
807        }
808
809        check_status(child.wait()?)?;
810
811        Ok(artifacts)
812    }
813}