Skip to main content

cargo_flux/
cargo-flux.rs

1use std::{
2    self,
3    io::{BufWriter, Write},
4    process::{Command, exit},
5};
6
7use cargo_metadata::{Metadata, camino::Utf8Path};
8use clap::Parser as _;
9use flux_bin::{
10    FluxMetadata,
11    cargo_flux_opts::{CargoFluxCommand, Cli},
12    config::FluxConfig,
13    utils::{
14        EXIT_ERR, flux_sysroot_dir, get_binary_path, get_flux_driver_path, get_rust_toolchain,
15        print_version_and_exit,
16    },
17};
18use itertools::Itertools;
19use tempfile::NamedTempFile;
20
21fn main() {
22    let Cli::Flux { check_opts, command, version, verbose } = Cli::parse();
23
24    // Handle version flag (-V or --version with optional -v for verbose)
25    if version {
26        print_version_and_exit("cargo-flux", verbose > 0);
27    }
28
29    let command = command.unwrap_or(CargoFluxCommand::Check(check_opts));
30
31    match run(command) {
32        Ok(exit_code) => exit(exit_code),
33        Err(e) => {
34            println!("Failed to run `cargo-flux`, error={e:#}");
35            exit(EXIT_ERR)
36        }
37    };
38}
39
40fn run(cargo_flux_cmd: CargoFluxCommand) -> anyhow::Result<i32> {
41    let toolchain = get_rust_toolchain()?;
42    let cargo_path = get_binary_path(&toolchain, "cargo")?;
43
44    let metadata = cargo_flux_cmd.metadata().cargo_path(&cargo_path).exec()?;
45    let sysroot = flux_sysroot_dir();
46    let flux_driver_path = get_flux_driver_path(&sysroot)?;
47    let config_file = write_cargo_config(metadata, &sysroot, &cargo_flux_cmd)?;
48
49    let mut cargo_command = Command::new("cargo");
50
51    // We set `RUSTC` as an environment variable and not in in the [build]
52    // section of the config file to make sure we run flux even when the
53    // variable is already set. We also unset `RUSTC_WRAPPER` to avoid
54    // conflicts, e.g., see https://github.com/flux-rs/flux/issues/1155
55    cargo_command
56        .env("RUSTC", flux_driver_path)
57        .env("RUSTC_WRAPPER", "")
58        .arg(format!("+{toolchain}"));
59
60    cargo_flux_cmd.forward_args(&mut cargo_command, config_file.path());
61
62    Ok(cargo_command.status()?.code().unwrap_or(EXIT_ERR))
63}
64
65fn write_cargo_config(
66    metadata: Metadata,
67    sysroot: &std::path::Path,
68    cargo_flux_cmd: &CargoFluxCommand,
69) -> anyhow::Result<NamedTempFile> {
70    let flux_config = FluxConfig::load()?;
71    let global_fluxflags = flux_config.global_fluxflags();
72    let package_versions = metadata
73        .packages
74        .iter()
75        .map(|package| (package.name.to_string(), package.version.to_string()))
76        .collect_vec();
77    for spec in flux_config.unmatched_specs(&package_versions) {
78        eprintln!(
79            "warning: `[package.\"{spec}\"]` in `.flux/config.toml` did not match any packages"
80        );
81    }
82    let targeted_package_ids = cargo_flux_cmd.targeted_package_ids(&metadata);
83    let cli_flags = cargo_flux_cmd.rustflags();
84
85    let mut file = NamedTempFile::new()?;
86    {
87        let mut w = BufWriter::new(&mut file);
88        write!(
89            w,
90            r#"
91[unstable]
92profile-rustflags = true
93
94[env]
95FLUX_BUILD_SYSROOT = "1"
96FLUX_CARGO = "1"
97
98[profile.flux]
99inherits = "dev"
100incremental = false
101        "#
102        )?;
103
104        for package in &metadata.packages {
105            let flux_metadata = FluxMetadata::from_package(package)?;
106
107            if flux_metadata.enabled {
108                let package_config = flux_config.for_package(
109                    &package.name,
110                    &package.version.to_string(),
111                    metadata.workspace_members.contains(&package.id),
112                )?;
113                // For workspace members, cargo sets the workspace's root as the working dir
114                // when running flux. Paths will be relative to that, so we must normalize
115                // glob patterns to be relative to the workspace's root.
116                let manifest_dir_relative_to_workspace = package
117                    .manifest_path
118                    .strip_prefix(&metadata.workspace_root)
119                    .ok()
120                    .and_then(Utf8Path::parent);
121
122                let sysroot_flag = format!("-Fsysroot={}", sysroot.display());
123                write!(
124                    w,
125                    r#"
126[profile.flux.package."{}"]
127rustflags = [{:?}]
128                        "#,
129                    package.id,
130                    // flags `cargo-flux` sets come first, so any of them can be overridden.
131                    ["-Fverify=on", "-Ffull-compilation=on", sysroot_flag.as_str()]
132                        .into_iter()
133                        .chain(
134                            flux_metadata
135                                .into_flags(
136                                    manifest_dir_relative_to_workspace,
137                                    cargo_flux_cmd
138                                        .only_check()
139                                        .filter(|_| targeted_package_ids.contains(&package.id))
140                                )
141                                .iter()
142                                .chain(
143                                    package_config
144                                        .settings
145                                        .to_flags(&metadata.target_directory)
146                                        .iter()
147                                )
148                                .chain(package_config.fluxflags.iter())
149                                .chain(global_fluxflags.iter())
150                                .chain(cli_flags.iter())
151                                .map(String::as_str)
152                        )
153                        .format(", ")
154                )?;
155            }
156        }
157    }
158    Ok(file)
159}