1mod 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#[derive(Debug, Default)]
34pub struct FluxConfig {
35 pub build: Build,
36 settings: Option<ConfigValue>,
39 packages: BTreeMap<String, PackageOverride>,
41}
42
43#[derive(Debug)]
45struct PackageOverride {
46 settings: ConfigValue,
47 fluxflags: Option<Vec<String>>,
48}
49
50#[derive(Debug)]
52pub struct PackageConfig {
53 pub settings: Settings,
54 pub fluxflags: Vec<String>,
57}
58
59#[derive(Clone, Debug, Default, Deserialize)]
61#[serde(default, deny_unknown_fields, rename_all = "kebab-case")]
62pub struct Build {
63 pub fluxflags: Option<StringList>,
65}
66
67#[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
84pub const FLUX_ENCODED_FLAGS: &str = "FLUX_ENCODED_FLAGS";
87
88pub const FLUXFLAGS: &str = "FLUXFLAGS";
90
91#[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 pub enabled: Option<bool>,
107 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 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 pub verbose: Option<bool>,
123 pub suggestions: Option<bool>,
125 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 pub summary: Option<bool>,
134 pub timings: Option<bool>,
136 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 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 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
176const BUILD_KEY: &str = "build";
178const PACKAGE_KEY: &str = "package";
179
180const FLUXFLAGS_KEY: &str = "fluxflags";
182
183const ALL_NON_MEMBERS: &str = "*";
185
186impl Settings {
187 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 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 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 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 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 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 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
383fn 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
399fn 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
421fn read_file(path: &Utf8Path) -> anyhow::Result<ConfigValue> {
424 let value = ConfigValue::parse_file(path)?;
425 FluxConfig::from_value(value.clone())?;
426 Ok(value)
427}