Skip to main content

flux_bin/
config.rs

1//! Loading of `.flux/config.toml`, the configuration of a `cargo flux` invocation.
2//!
3//! Configuration files are discovered and merged following the same rules cargo uses for
4//! `.cargo/config.toml`:
5//!
6//! * Starting from the current directory, `.flux/config.toml` is read in every ancestor directory,
7//!   followed by `$FLUX_HOME/config.toml` (`~/.flux/config.toml` by default) if it wasn't already
8//!   found.
9//! * Files closer to the current directory take precedence. Tables are merged key by key, arrays
10//!   are concatenated (with items from higher precedence files placed later), and any other value
11//!   is replaced.
12//! * Relative paths are resolved relative to the parent of the directory containing the file,
13//!   e.g., a path in `/project/.flux/config.toml` is relative to `/project`.
14//!
15//! Settings can be overridden for specific packages in `[package.<spec>]` tables, where `<spec>`
16//! is a package name, `<name>@<version>`, or `*` for all packages that are not workspace members.
17//! As in cargo's profile overrides, a package's settings are taken from its own table, then from
18//! `[package."*"]`, and then from the top level.
19//!
20
21mod value;
22
23use std::{collections::BTreeMap, env, fs};
24
25use anyhow::{Context, bail};
26use cargo_metadata::camino::{Utf8Path, Utf8PathBuf};
27use flux_sysroot::flux_home_dir;
28use serde::Deserialize;
29use value::ConfigValue;
30pub use value::{Located, Location};
31
32/// The merged content of all configuration files.
33#[derive(Debug, Default)]
34pub struct FluxConfig {
35    pub build: Build,
36    /// Top-level settings, kept untyped to merge them with package overrides. `None` if there are
37    /// no configuration files.
38    settings: Option<ConfigValue>,
39    /// `[package.<spec>]` tables, indexed by spec.
40    packages: BTreeMap<String, PackageOverride>,
41}
42
43/// A `[package.<spec>]` table.
44#[derive(Debug)]
45struct PackageOverride {
46    settings: ConfigValue,
47    fluxflags: Option<Vec<String>>,
48}
49
50/// The configuration of a single package.
51#[derive(Debug)]
52pub struct PackageConfig {
53    pub settings: Settings,
54    /// Flags from the package overrides. They are passed before the global flags, like cargo does
55    /// with `rustflags` in profile overrides.
56    pub fluxflags: Vec<String>,
57}
58
59/// The `[build]` table.
60#[derive(Clone, Debug, Default, Deserialize)]
61#[serde(default, deny_unknown_fields, rename_all = "kebab-case")]
62pub struct Build {
63    /// Extra flags passed to every package checked by Flux, like cargo's `build.rustflags`.
64    pub fluxflags: Option<StringList>,
65}
66
67/// A list of strings written either as an array or as a space-separated string.
68#[derive(Clone, Debug, Deserialize)]
69#[serde(untagged)]
70pub enum StringList {
71    String(String),
72    List(Vec<String>),
73}
74
75impl StringList {
76    fn into_vec(self) -> Vec<String> {
77        match self {
78            StringList::String(s) => split_space_separated(&s),
79            StringList::List(list) => list,
80        }
81    }
82}
83
84/// Environment variable with flags separated by `0x1f` (ASCII Unit Separator). Takes precedence
85/// over [`FLUXFLAGS`]. Like cargo's `CARGO_ENCODED_RUSTFLAGS`, it allows flags containing spaces.
86pub const FLUX_ENCODED_FLAGS: &str = "FLUX_ENCODED_FLAGS";
87
88/// Environment variable with space-separated flags. Takes precedence over `build.fluxflags`.
89pub const FLUXFLAGS: &str = "FLUXFLAGS";
90
91/// Settings that are translated into flags for the driver.
92#[derive(Clone, Debug, Default, Deserialize)]
93#[serde(default, deny_unknown_fields, rename_all = "kebab-case")]
94pub struct Settings {
95    pub cache: Cache,
96    pub fixpoint: Fixpoint,
97    pub diagnostics: Diagnostics,
98    pub stats: Stats,
99    pub debug: Debug,
100}
101
102#[derive(Clone, Debug, Default, Deserialize)]
103#[serde(default, deny_unknown_fields, rename_all = "kebab-case")]
104pub struct Cache {
105    /// Enables fixpoint query caching.
106    pub enabled: Option<bool>,
107    /// Directory where cache files are saved. Defaults to `<target-dir>/flux-cache`.
108    pub dir: Option<Located<Utf8PathBuf>>,
109}
110
111#[derive(Clone, Debug, Default, Deserialize)]
112#[serde(default, deny_unknown_fields, rename_all = "kebab-case")]
113pub struct Fixpoint {
114    /// Timeout in seconds for each fixpoint query (`-Ffixpoint-timeout`).
115    pub timeout: Option<u64>,
116}
117
118#[derive(Clone, Debug, Default, Deserialize)]
119#[serde(default, deny_unknown_fields, rename_all = "kebab-case")]
120pub struct Diagnostics {
121    /// Produce more detailed error messages (`-Fflux-verbose`).
122    pub verbose: Option<bool>,
123    /// Emit suggestions in diagnostics (the inverse of `-Fno-suggestions`).
124    pub suggestions: Option<bool>,
125    /// Attach a note to failing items with a command to re-run them (`-Frerun-hint`).
126    pub rerun_hint: Option<bool>,
127}
128
129#[derive(Clone, Debug, Default, Deserialize)]
130#[serde(default, deny_unknown_fields, rename_all = "kebab-case")]
131pub struct Stats {
132    /// Print a summary of the number of functions checked, trusted, etc. (`-Fsummary`).
133    pub summary: Option<bool>,
134    /// Print the time taken to analyze each function (`-Ftimings`).
135    pub timings: Option<bool>,
136    /// Compute statistics about annotations (`-Fannots`).
137    pub annots: Option<bool>,
138}
139
140#[derive(Clone, Debug, Default, Deserialize)]
141#[serde(default, deny_unknown_fields, rename_all = "kebab-case")]
142pub struct Debug {
143    /// Directory where debug data is dumped (`-Flog-dir`).
144    pub log_dir: Option<Located<Utf8PathBuf>>,
145    pub dump_constraint: Option<bool>,
146    pub dump_fhir: Option<bool>,
147    pub dump_rty: Option<bool>,
148    pub dump_checker_trace: Option<TraceLevel>,
149    /// Dump the call and type dependency graphs as JSON (`-Fdump-dep-graph`).
150    pub dump_dep_graph: Option<bool>,
151    pub catch_bugs: Option<bool>,
152}
153
154#[derive(Clone, Copy, Debug, Deserialize)]
155#[serde(rename_all = "lowercase")]
156pub enum TraceLevel {
157    Error,
158    Warn,
159    Info,
160    Debug,
161    Trace,
162}
163
164impl TraceLevel {
165    fn as_str(self) -> &'static str {
166        match self {
167            TraceLevel::Error => "error",
168            TraceLevel::Warn => "warn",
169            TraceLevel::Info => "info",
170            TraceLevel::Debug => "debug",
171            TraceLevel::Trace => "trace",
172        }
173    }
174}
175
176/// Top-level keys that are not [`Settings`].
177const BUILD_KEY: &str = "build";
178const PACKAGE_KEY: &str = "package";
179
180/// Key for flags in a `[package.<spec>]` table.
181const FLUXFLAGS_KEY: &str = "fluxflags";
182
183/// Spec matching all packages that are not workspace members.
184const ALL_NON_MEMBERS: &str = "*";
185
186impl Settings {
187    /// Translates the settings into flags for the driver.
188    pub fn to_flags(&self, target_dir: &Utf8Path) -> Vec<String> {
189        let mut flags = vec![];
190        if let Some(true) = self.cache.enabled {
191            let dir = self
192                .cache
193                .dir
194                .as_ref()
195                .map(Located::resolve)
196                .unwrap_or_else(|| target_dir.join("flux-cache"));
197            flags.push(format!("-Fcache={dir}"));
198        }
199        if let Some(v) = self.fixpoint.timeout {
200            flags.push(format!("-Ffixpoint-timeout={v}"));
201        }
202        if let Some(v) = self.diagnostics.verbose {
203            flags.push(format!("-Fflux-verbose={v}"));
204        }
205        if let Some(v) = self.diagnostics.suggestions {
206            flags.push(format!("-Fno-suggestions={}", !v));
207        }
208        if let Some(v) = self.diagnostics.rerun_hint {
209            flags.push(format!("-Frerun-hint={v}"));
210        }
211        if let Some(v) = self.stats.summary {
212            flags.push(format!("-Fsummary={v}"));
213        }
214        if let Some(v) = self.stats.timings {
215            flags.push(format!("-Ftimings={v}"));
216        }
217        if let Some(v) = self.stats.annots {
218            flags.push(format!("-Fannots={v}"));
219        }
220        if let Some(v) = &self.debug.log_dir {
221            flags.push(format!("-Flog-dir={}", v.resolve()));
222        }
223        if let Some(v) = self.debug.dump_constraint {
224            flags.push(format!("-Fdump-constraint={v}"));
225        }
226        if let Some(v) = self.debug.dump_fhir {
227            flags.push(format!("-Fdump-fhir={v}"));
228        }
229        if let Some(v) = self.debug.dump_rty {
230            flags.push(format!("-Fdump-rty={v}"));
231        }
232        if let Some(v) = self.debug.dump_checker_trace {
233            flags.push(format!("-Fdump-checker-trace={}", v.as_str()));
234        }
235        if let Some(v) = self.debug.dump_dep_graph {
236            flags.push(format!("-Fdump-dep-graph={v}"));
237        }
238        if let Some(v) = self.debug.catch_bugs {
239            flags.push(format!("-Fcatch-bugs={v}"));
240        }
241        flags
242    }
243}
244
245impl FluxConfig {
246    /// Discovers and loads the configuration for an invocation in the current directory.
247    pub fn load() -> anyhow::Result<FluxConfig> {
248        let cwd = Utf8PathBuf::try_from(env::current_dir()?)?;
249        let flux_home = Utf8PathBuf::try_from(flux_home_dir())?;
250        Self::load_files(&discover(&cwd, &flux_home))
251    }
252
253    /// Loads and merges the given files, ordered from highest to lowest precedence.
254    fn load_files(paths: &[Utf8PathBuf]) -> anyhow::Result<FluxConfig> {
255        let values = paths
256            .iter()
257            .rev()
258            .map(|path| read_file(path))
259            .collect::<anyhow::Result<Vec<_>>>()?;
260        match ConfigValue::merge_all(values)? {
261            Some(merged) => Self::from_value(merged),
262            None => Ok(FluxConfig::default()),
263        }
264    }
265
266    fn from_value(mut value: ConfigValue) -> anyhow::Result<FluxConfig> {
267        let build: Build = match value.remove(BUILD_KEY) {
268            Some(build) => {
269                build
270                    .deserialize_into()
271                    .context("invalid `[build]` table")?
272            }
273            None => Build::default(),
274        };
275        let packages = match value.remove(PACKAGE_KEY) {
276            Some(packages) => {
277                let ConfigValue::Table(packages, _) = packages else {
278                    bail!("{}: `package` must be a table", packages.location());
279                };
280                packages
281                    .into_iter()
282                    .map(|(spec, value)| {
283                        let package = PackageOverride::from_value(value)
284                            .with_context(|| format!("invalid `[package.\"{spec}\"]` table"))?;
285                        Ok((spec, package))
286                    })
287                    .collect::<anyhow::Result<_>>()?
288            }
289            None => BTreeMap::new(),
290        };
291        value.clone().deserialize_into::<Settings>()?;
292        Ok(FluxConfig { build, settings: Some(value), packages })
293    }
294
295    /// Returns the configuration for the package `name` at `version`.
296    pub fn for_package(
297        &self,
298        name: &str,
299        version: &str,
300        is_workspace_member: bool,
301    ) -> anyhow::Result<PackageConfig> {
302        let matching: Vec<_> = self
303            .packages
304            .iter()
305            .filter(|(spec, _)| spec_matches(spec, name, version))
306            .collect();
307        if matching.len() >= 2 {
308            bail!(
309                "multiple `[package]` tables in `.flux/config.toml` match package `{name}`: `{}` and \
310                 `{}`",
311                matching[0].0,
312                matching[1].0
313            );
314        }
315        let named = matching.first().map(|(_, package)| *package);
316        let all_non_members =
317            if is_workspace_member { None } else { self.packages.get(ALL_NON_MEMBERS) };
318
319        // Overrides in increasing order of precedence. Settings are merged field by field.
320        let mut settings: Vec<ConfigValue> = self.settings.iter().cloned().collect();
321        let mut fluxflags = vec![];
322        for package in [all_non_members, named].into_iter().flatten() {
323            settings.push(package.settings.clone());
324            if let Some(flags) = &package.fluxflags {
325                fluxflags = flags.clone();
326            }
327        }
328        let settings = match ConfigValue::merge_all(settings)? {
329            Some(settings) => settings.deserialize_into()?,
330            None => Settings::default(),
331        };
332        Ok(PackageConfig { settings, fluxflags })
333    }
334
335    /// Returns the specs of `[package.<spec>]` tables that match none of `packages`, given as pairs
336    /// of name and version.
337    pub fn unmatched_specs(&self, packages: &[(String, String)]) -> Vec<&str> {
338        self.packages
339            .keys()
340            .filter(|spec| {
341                *spec != ALL_NON_MEMBERS
342                    && !packages
343                        .iter()
344                        .any(|(name, version)| spec_matches(spec, name, version))
345            })
346            .map(String::as_str)
347            .collect()
348    }
349
350    /// Returns the extra flags passed to every package. Following cargo's rules for rustflags,
351    /// they come from the first source that is set among [`FLUX_ENCODED_FLAGS`], [`FLUXFLAGS`] and
352    /// `build.fluxflags`. Sources are not combined.
353    pub fn global_fluxflags(&self) -> Vec<String> {
354        if let Ok(flags) = env::var(FLUX_ENCODED_FLAGS) {
355            if flags.is_empty() {
356                vec![]
357            } else {
358                flags.split('\x1f').map(str::to_string).collect()
359            }
360        } else if let Ok(flags) = env::var(FLUXFLAGS) {
361            split_space_separated(&flags)
362        } else {
363            self.build
364                .fluxflags
365                .clone()
366                .map(StringList::into_vec)
367                .unwrap_or_default()
368        }
369    }
370}
371
372impl PackageOverride {
373    fn from_value(mut settings: ConfigValue) -> anyhow::Result<PackageOverride> {
374        let fluxflags = match settings.remove(FLUXFLAGS_KEY) {
375            Some(value) => Some(value.deserialize_into::<StringList>()?.into_vec()),
376            None => None,
377        };
378        settings.clone().deserialize_into::<Settings>()?;
379        Ok(PackageOverride { settings, fluxflags })
380    }
381}
382
383/// Whether `spec` is `name` or `name@version`.
384fn spec_matches(spec: &str, name: &str, version: &str) -> bool {
385    match spec.split_once('@') {
386        Some((spec_name, spec_version)) => spec_name == name && spec_version == version,
387        None => spec == name,
388    }
389}
390
391fn split_space_separated(s: &str) -> Vec<String> {
392    s.split(' ')
393        .map(str::trim)
394        .filter(|s| !s.is_empty())
395        .map(str::to_string)
396        .collect()
397}
398
399/// Returns the configuration files that apply to `cwd`, ordered from highest to lowest
400/// precedence.
401fn discover(cwd: &Utf8Path, flux_home: &Utf8Path) -> Vec<Utf8PathBuf> {
402    let mut paths: Vec<Utf8PathBuf> = cwd
403        .ancestors()
404        .map(|dir| dir.join(".flux").join("config.toml"))
405        .filter(|path| path.is_file())
406        .collect();
407    let home_config = flux_home.join("config.toml");
408    if home_config.is_file() && !paths.iter().any(|path| same_file(path, &home_config)) {
409        paths.push(home_config);
410    }
411    paths
412}
413
414fn same_file(a: &Utf8Path, b: &Utf8Path) -> bool {
415    match (fs::canonicalize(a), fs::canonicalize(b)) {
416        (Ok(a), Ok(b)) => a == b,
417        _ => a == b,
418    }
419}
420
421/// Reads a configuration file and validates it on its own, so invalid values are reported even if
422/// another file overrides them.
423fn read_file(path: &Utf8Path) -> anyhow::Result<ConfigValue> {
424    let value = ConfigValue::parse_file(path)?;
425    FluxConfig::from_value(value.clone())?;
426    Ok(value)
427}