cargo_flux/
cargo-flux.rs

1use std::{
2    self, env,
3    io::{BufWriter, Write},
4    process::{Command, exit},
5};
6
7use anyhow::anyhow;
8use cargo_metadata::{Metadata, MetadataCommand, camino::Utf8Path};
9use flux_bin::{
10    FluxMetadata,
11    utils::{
12        EXIT_ERR, LIB_PATH, get_flux_driver_path, get_rust_toolchain, get_rustc_driver_lib_path,
13        prepend_path_to_env_var, sysroot_dir,
14    },
15};
16use itertools::Itertools;
17use tempfile::NamedTempFile;
18
19fn main() {
20    let exit_code = match run() {
21        Ok(code) => code,
22        Err(e) => {
23            println!("Failed to run `cargo-flux`, error={e}");
24            EXIT_ERR
25        }
26    };
27    exit(exit_code)
28}
29
30fn run() -> anyhow::Result<i32> {
31    let toolchain = get_rust_toolchain()?;
32
33    let metadata = MetadataCommand::new().exec()?;
34    let config_file = write_cargo_config(&toolchain, metadata)?;
35
36    // Cargo can be called like `cargo [OPTIONS] flux`, so we skip all arguments until `flux` is found.
37    let mut args = env::args()
38        .skip_while(|arg| arg != "flux")
39        .skip(1)
40        .collect::<Vec<_>>();
41
42    // Unless we are calling `cargo flux clean` add a `check`
43    match &args[..] {
44        [subcommand, ..] if subcommand == "clean" => {}
45        _ => {
46            args.insert(0, "check".to_string());
47        }
48    }
49    args.extend(["--profile".to_string(), "flux".to_string()]);
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    let sysroot = sysroot_dir();
56    let flux_driver_path = get_flux_driver_path(&sysroot)?;
57    let exit_code = Command::new("cargo")
58        .env("RUSTC", flux_driver_path)
59        .env("RUSTC_WRAPPER", "")
60        .arg(format!("+{toolchain}"))
61        .arg("--config")
62        .arg(config_file.path())
63        .args(args)
64        .status()?
65        .code();
66
67    Ok(exit_code.unwrap_or(EXIT_ERR))
68}
69
70fn write_cargo_config(toolchain: &str, metadata: Metadata) -> anyhow::Result<NamedTempFile> {
71    let ld_library_path = get_rustc_driver_lib_path(toolchain)?;
72    let extended_lib_path = prepend_path_to_env_var(LIB_PATH, ld_library_path)?;
73
74    let flux_flags: Option<Vec<String>> = if let Ok(flags) = env::var("FLUXFLAGS") {
75        Some(flags.split(" ").map(Into::into).collect())
76    } else {
77        None
78    };
79
80    let flux_toml = config::Config::builder()
81        .add_source(config::File::with_name("flux.toml").required(false))
82        .build()?;
83
84    if flux_toml.get_bool("enabled").is_ok() {
85        return Err(anyhow!("`enabled` cannot be set in `flux.toml`"));
86    }
87
88    let mut file = NamedTempFile::new()?;
89    {
90        let mut w = BufWriter::new(&mut file);
91        write!(
92            w,
93            r#"
94[unstable]
95profile-rustflags = true
96
97[env]
98LIB_PATH = "{lib_path}"
99FLUX_BUILD_SYSROOT = "1"
100FLUX_CARGO = "1"
101
102[profile.flux]
103inherits = "dev"
104incremental = false
105        "#,
106            lib_path = extended_lib_path.display(),
107        )?;
108
109        for package in metadata.packages {
110            let flux_metadata: FluxMetadata = config::Config::builder()
111                .add_source(FluxMetadataSource::new(
112                    package.manifest_path.to_string(),
113                    package.metadata,
114                ))
115                .add_source(flux_toml.clone())
116                .build()?
117                .try_deserialize()?;
118
119            if flux_metadata.enabled {
120                // For workspace members, cargo sets the workspace's root as the working dir
121                // when running flux. Paths will be relative to that, so we must normalize
122                // glob patterns to be relative to the workspace's root.
123                let manifest_dir_relative_to_workspace = package
124                    .manifest_path
125                    .strip_prefix(&metadata.workspace_root)
126                    .ok()
127                    .and_then(Utf8Path::parent);
128                write!(
129                    w,
130                    r#"
131[profile.flux.package."{}"]
132rustflags = [{:?}]
133                        "#,
134                    package.id,
135                    flux_metadata
136                        .into_flags(&metadata.target_directory, manifest_dir_relative_to_workspace)
137                        .iter()
138                        .chain(flux_flags.iter().flatten())
139                        .map(|s| s.as_ref())
140                        .chain(["-Fverify=on", "-Ffull-compilation=on"])
141                        .format(", ")
142                )?;
143            }
144        }
145    }
146    Ok(file)
147}
148
149#[derive(Clone, Debug)]
150struct FluxMetadataSource {
151    origin: String,
152    value: serde_json::Value,
153}
154
155impl FluxMetadataSource {
156    fn new(origin: String, value: serde_json::Value) -> Self {
157        Self { origin, value }
158    }
159}
160
161impl config::Source for FluxMetadataSource {
162    fn clone_into_box(&self) -> Box<dyn config::Source + Send + Sync> {
163        Box::new(self.clone())
164    }
165
166    fn collect(&self) -> Result<config::Map<String, config::Value>, config::ConfigError> {
167        if let serde_json::Value::Object(metadata) = &self.value
168            && let Some(flux_metadata) = metadata.get("flux")
169        {
170            let config_value = serde_json_to_config(flux_metadata, &self.origin)?;
171            if let config::ValueKind::Table(table) = config_value.kind {
172                Ok(table)
173            } else {
174                Err(config::ConfigError::Message("expected a table".to_string()))
175            }
176        } else {
177            Ok(Default::default())
178        }
179    }
180}
181
182fn serde_json_to_config(
183    value: &serde_json::Value,
184    origin: &String,
185) -> Result<config::Value, config::ConfigError> {
186    let kind = match value {
187        serde_json::Value::Null => config::ValueKind::Nil,
188        serde_json::Value::Bool(b) => config::ValueKind::Boolean(*b),
189        serde_json::Value::Number(number) => {
190            if let Some(n) = number.as_u128() {
191                config::ValueKind::U128(n)
192            } else if let Some(n) = number.as_i128() {
193                config::ValueKind::I128(n)
194            } else if let Some(n) = number.as_u64() {
195                config::ValueKind::U64(n)
196            } else if let Some(n) = number.as_i64() {
197                config::ValueKind::I64(n)
198            } else if let Some(n) = number.as_f64() {
199                config::ValueKind::Float(n)
200            } else {
201                return Err(config::ConfigError::Message("invalid number".to_string()));
202            }
203        }
204        serde_json::Value::String(s) => config::ValueKind::String(s.to_string()),
205        serde_json::Value::Array(values) => {
206            config::ValueKind::Array(
207                values
208                    .iter()
209                    .map(|v| serde_json_to_config(v, origin))
210                    .try_collect()?,
211            )
212        }
213        serde_json::Value::Object(map) => {
214            config::ValueKind::Table(
215                map.iter()
216                    .map(|(k, v)| Ok((k.to_string(), serde_json_to_config(v, origin)?)))
217                    .try_collect()?,
218            )
219        }
220    };
221    Ok(config::Value::new(Some(origin), kind))
222}