Skip to main content

f00_cli/
config.rs

1//! User TOML configuration for f00.
2//!
3//! Search order (first found wins):
4//! 1. `--config PATH` if provided
5//! 2. `$F00_CONFIG` if set
6//! 3. Platform config dir:
7//!    - Unix: `$XDG_CONFIG_HOME/f00/config.toml` or `~/.config/f00/config.toml`
8//!      (macOS via `directories`: `~/Library/Application Support/f00/config.toml`)
9//!    - Windows: `%APPDATA%\f00\config.toml`
10
11use std::fs;
12use std::path::{Path, PathBuf};
13
14use serde::Deserialize;
15
16use crate::cli::{Args, ColorArg, IconsArg};
17use f00_core::IconsWhen;
18
19/// Optional defaults from a TOML config file.
20#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize)]
21#[serde(default)]
22pub struct ConfigDefaults {
23    pub all: Option<bool>,
24    pub almost_all: Option<bool>,
25    pub long: Option<bool>,
26    #[serde(alias = "human")]
27    pub human_readable: Option<bool>,
28    pub color: Option<String>,
29    /// Icons when: bool (`true`/`false`) or string (`auto`/`always`/`never`).
30    #[serde(default, deserialize_with = "deserialize_opt_icons")]
31    pub icons: Option<IconsArg>,
32    pub dirs_first: Option<bool>,
33    pub git: Option<bool>,
34    pub classify: Option<bool>,
35}
36
37/// Root of `config.toml`. Fields may live under `[defaults]` or at the root.
38#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize)]
39#[serde(default)]
40pub struct FileConfig {
41    #[serde(default)]
42    pub defaults: ConfigDefaults,
43    // Root-level keys (take precedence over nested `[defaults]` when present).
44    pub all: Option<bool>,
45    pub almost_all: Option<bool>,
46    pub long: Option<bool>,
47    #[serde(alias = "human")]
48    pub human_readable: Option<bool>,
49    pub color: Option<String>,
50    #[serde(default, deserialize_with = "deserialize_opt_icons")]
51    pub icons: Option<IconsArg>,
52    pub dirs_first: Option<bool>,
53    pub git: Option<bool>,
54    pub classify: Option<bool>,
55}
56
57impl FileConfig {
58    /// Flatten root-level keys on top of `[defaults]`.
59    pub fn resolved_defaults(&self) -> ConfigDefaults {
60        ConfigDefaults {
61            all: self.all.or(self.defaults.all),
62            almost_all: self.almost_all.or(self.defaults.almost_all),
63            long: self.long.or(self.defaults.long),
64            human_readable: self.human_readable.or(self.defaults.human_readable),
65            color: self.color.clone().or_else(|| self.defaults.color.clone()),
66            icons: self.icons.or(self.defaults.icons),
67            dirs_first: self.dirs_first.or(self.defaults.dirs_first),
68            git: self.git.or(self.defaults.git),
69            classify: self.classify.or(self.defaults.classify),
70        }
71    }
72}
73
74/// Parse TOML text into a [`FileConfig`].
75pub fn parse_config_str(s: &str) -> Result<FileConfig, toml::de::Error> {
76    toml::from_str(s)
77}
78
79/// Load config from an explicit path.
80pub fn load_config_from_path(path: &Path) -> anyhow::Result<FileConfig> {
81    let text = fs::read_to_string(path)
82        .map_err(|e| anyhow::anyhow!("failed to read config {}: {e}", path.display()))?;
83    parse_config_str(&text)
84        .map_err(|e| anyhow::anyhow!("failed to parse config {}: {e}", path.display()))
85}
86
87/// Resolve the platform user config path (`…/f00/config.toml`), if available.
88pub fn platform_config_path() -> Option<PathBuf> {
89    directories::ProjectDirs::from("", "", "f00").map(|d| d.config_dir().join("config.toml"))
90}
91
92/// Paths to try when no `--config` override is given.
93pub fn config_search_paths() -> Vec<PathBuf> {
94    let mut paths = Vec::new();
95    if let Ok(p) = std::env::var("F00_CONFIG") {
96        if !p.is_empty() {
97            paths.push(PathBuf::from(p));
98        }
99    }
100    if let Some(p) = platform_config_path() {
101        paths.push(p);
102    }
103    paths
104}
105
106/// Load config: explicit path, else first existing search path, else `None`.
107pub fn load_user_config(explicit: Option<&Path>) -> anyhow::Result<Option<FileConfig>> {
108    if let Some(path) = explicit {
109        return Ok(Some(load_config_from_path(path)?));
110    }
111    for path in config_search_paths() {
112        if path.is_file() {
113            return Ok(Some(load_config_from_path(&path)?));
114        }
115    }
116    Ok(None)
117}
118
119fn parse_color_arg(s: &str) -> Option<ColorArg> {
120    // Keep in sync with `ColorArg` clap aliases (GNU coreutils ls --color=WHEN).
121    match s.to_ascii_lowercase().as_str() {
122        "auto" | "tty" | "if-tty" => Some(ColorArg::Auto),
123        "always" | "yes" | "force" | "true" | "on" => Some(ColorArg::Always),
124        "never" | "no" | "none" | "false" | "off" => Some(ColorArg::Never),
125        _ => None,
126    }
127}
128
129fn parse_icons_arg(s: &str) -> Option<IconsArg> {
130    IconsWhen::parse(s).map(IconsArg::from)
131}
132
133/// Accept bool or string for `icons` in TOML (`true`/`false`/`"auto"`/`"always"`/`"never"`).
134fn deserialize_opt_icons<'de, D>(deserializer: D) -> Result<Option<IconsArg>, D::Error>
135where
136    D: serde::Deserializer<'de>,
137{
138    use serde::de::{self, Visitor};
139    use std::fmt;
140
141    struct IconsVisitor;
142
143    impl<'de> Visitor<'de> for IconsVisitor {
144        type Value = Option<IconsArg>;
145
146        fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
147            f.write_str("a bool or icons when string (auto/always/never)")
148        }
149
150        fn visit_none<E: de::Error>(self) -> Result<Self::Value, E> {
151            Ok(None)
152        }
153
154        fn visit_unit<E: de::Error>(self) -> Result<Self::Value, E> {
155            Ok(None)
156        }
157
158        fn visit_bool<E: de::Error>(self, v: bool) -> Result<Self::Value, E> {
159            Ok(Some(if v { IconsArg::Always } else { IconsArg::Never }))
160        }
161
162        fn visit_str<E: de::Error>(self, v: &str) -> Result<Self::Value, E> {
163            parse_icons_arg(v)
164                .map(Some)
165                .ok_or_else(|| de::Error::custom(format!("invalid icons value: {v}")))
166        }
167
168        fn visit_string<E: de::Error>(self, v: String) -> Result<Self::Value, E> {
169            self.visit_str(&v)
170        }
171    }
172
173    deserializer.deserialize_any(IconsVisitor)
174}
175
176/// Whether `flag` (e.g. `--icons` or `--git`) appears in process args.
177pub fn cli_has_long(flag: &str) -> bool {
178    let eq = format!("{flag}=");
179    std::env::args().any(|a| a == flag || a.starts_with(&eq))
180}
181
182/// Merge file defaults into CLI args.
183///
184/// Precedence: built-in defaults < config < CLI flags (when set / non-default).
185/// For false-default bools, config `true` enables.
186/// For `git` (CLI default true), config applies unless `--git` was on the command line.
187/// For `color` / `icons`, config applies when no explicit `--color` / `--icons` on the CLI.
188pub fn merge_config_into_args(args: &mut Args, file: &FileConfig) {
189    let d = file.resolved_defaults();
190
191    if let Some(true) = d.all {
192        args.all = true;
193    }
194    if let Some(true) = d.almost_all {
195        args.almost_all = true;
196    }
197    if let Some(true) = d.long {
198        args.long = true;
199    }
200    if let Some(true) = d.human_readable {
201        args.human_readable = true;
202    }
203    if let Some(true) = d.classify {
204        args.classify = Some(ColorArg::Always);
205    }
206
207    if let Some(v) = d.icons {
208        if !cli_has_long("--icons") {
209            args.icons = v;
210        }
211    }
212    if let Some(v) = d.dirs_first {
213        if v {
214            args.dirs_first = true;
215        } else if !cli_has_long("--dirs-first") {
216            args.dirs_first = false;
217        }
218    }
219
220    if let Some(v) = d.git {
221        if !cli_has_long("--git") {
222            args.git = v;
223        }
224    }
225
226    if let Some(ref c) = d.color {
227        if !cli_has_long("--color") {
228            if let Some(parsed) = parse_color_arg(c) {
229                args.color = parsed;
230            }
231        }
232    }
233}
234
235/// Apply env overrides (`F00_GNU`).
236pub fn apply_env_overrides(args: &mut Args) {
237    if args.gnu {
238        return;
239    }
240    if let Ok(v) = std::env::var("F00_GNU") {
241        let v = v.to_ascii_lowercase();
242        if matches!(v.as_str(), "1" | "true" | "yes" | "on") {
243            args.gnu = true;
244        }
245    }
246}
247
248/// Detect whether the binary was invoked as `ls` / `ls.exe`.
249pub fn invoked_as_ls() -> bool {
250    invoked_as_ls_from(std::env::args_os().next())
251}
252
253/// Testable argv0 check.
254pub fn invoked_as_ls_from(argv0: Option<std::ffi::OsString>) -> bool {
255    let Some(argv0) = argv0 else {
256        return false;
257    };
258    // Prefer Path (correct separators for the host OS).
259    if let Some(stem) = Path::new(&argv0).file_stem().and_then(|s| s.to_str()) {
260        if stem.eq_ignore_ascii_case("ls") {
261            return true;
262        }
263    }
264    // Also handle Windows-style paths when parsing on Unix (and vice versa).
265    if let Some(s) = argv0.to_str() {
266        let name = s.rsplit(['/', '\\']).next().unwrap_or(s);
267        let stem = name
268            .strip_suffix(".exe")
269            .or_else(|| name.strip_suffix(".EXE"))
270            .unwrap_or(name);
271        return stem.eq_ignore_ascii_case("ls");
272    }
273    false
274}
275
276/// Resolve effective args after clap parse.
277///
278/// Order: argv0 soft defaults → config file → env (`F00_GNU`).
279/// CLI flags already present in `args` win over config where merge logic allows.
280pub fn resolve_args(args: &mut Args, file: Option<&FileConfig>, as_ls: bool) {
281    if as_ls {
282        // Soft drop-in: keep full f00 chrome (icons/git). Only quiet dirs-first
283        // unless the user asked for it. Strict plain mode is `--gnu` only.
284        f00_compat::prefer_ls_defaults(
285            &mut args.dirs_first,
286            cli_has_long("--dirs-first") || cli_has_long("--group-directories-first"),
287        );
288    }
289    if let Some(file) = file {
290        merge_config_into_args(args, file);
291    }
292    apply_env_overrides(args);
293}
294
295#[cfg(test)]
296mod tests {
297    use super::*;
298    use crate::cli::{ColorArg, IconsArg};
299
300    fn empty_args() -> Args {
301        let mut a = Args::test_default();
302        a.git = true;
303        a.color = ColorArg::Auto;
304        a
305    }
306
307    #[test]
308    fn parse_defaults_section() {
309        let cfg = parse_config_str(
310            r#"
311            [defaults]
312            all = true
313            icons = true
314            color = "never"
315            dirs_first = true
316            git = false
317            "#,
318        )
319        .unwrap();
320        let d = cfg.resolved_defaults();
321        assert_eq!(d.all, Some(true));
322        assert_eq!(d.icons, Some(IconsArg::Always));
323        assert_eq!(d.color.as_deref(), Some("never"));
324        assert_eq!(d.dirs_first, Some(true));
325        assert_eq!(d.git, Some(false));
326    }
327
328    #[test]
329    fn parse_icons_when_string() {
330        let cfg = parse_config_str(r#"icons = "auto""#).unwrap();
331        assert_eq!(cfg.resolved_defaults().icons, Some(IconsArg::Auto));
332        let cfg = parse_config_str(r#"icons = "never""#).unwrap();
333        assert_eq!(cfg.resolved_defaults().icons, Some(IconsArg::Never));
334    }
335
336    #[test]
337    fn parse_root_level_and_human_alias() {
338        let cfg = parse_config_str(
339            r#"
340            long = true
341            human = true
342            classify = true
343            "#,
344        )
345        .unwrap();
346        let d = cfg.resolved_defaults();
347        assert_eq!(d.long, Some(true));
348        assert_eq!(d.human_readable, Some(true));
349        assert_eq!(d.classify, Some(true));
350    }
351
352    #[test]
353    fn merge_enables_flags_from_config() {
354        let cfg = parse_config_str(
355            r#"
356            [defaults]
357            all = true
358            long = true
359            icons = true
360            human_readable = true
361            "#,
362        )
363        .unwrap();
364        let mut args = empty_args();
365        merge_config_into_args(&mut args, &cfg);
366        assert!(args.all);
367        assert!(args.long);
368        assert_eq!(args.icons, IconsArg::Always);
369        assert!(args.human_readable);
370    }
371
372    #[test]
373    fn merge_color_from_config() {
374        let cfg = parse_config_str(r#"color = "never""#).unwrap();
375        let mut args = empty_args();
376        merge_config_into_args(&mut args, &cfg);
377        assert!(matches!(args.color, ColorArg::Never));
378    }
379
380    #[test]
381    fn parse_color_arg_gnu_synonyms() {
382        for s in ["auto", "tty", "if-tty", "TTY", "If-Tty"] {
383            assert!(
384                matches!(parse_color_arg(s), Some(ColorArg::Auto)),
385                "auto synonym: {s}"
386            );
387        }
388        for s in ["always", "yes", "force", "true", "on"] {
389            assert!(
390                matches!(parse_color_arg(s), Some(ColorArg::Always)),
391                "always synonym: {s}"
392            );
393        }
394        for s in ["never", "no", "none", "false", "off"] {
395            assert!(
396                matches!(parse_color_arg(s), Some(ColorArg::Never)),
397                "never synonym: {s}"
398            );
399        }
400        assert!(parse_color_arg("rainbow").is_none());
401    }
402
403    #[test]
404    fn merge_color_tty_from_config() {
405        let cfg = parse_config_str(r#"color = "tty""#).unwrap();
406        let mut args = empty_args();
407        merge_config_into_args(&mut args, &cfg);
408        assert!(matches!(args.color, ColorArg::Auto));
409    }
410
411    #[test]
412    fn merge_git_false_from_config() {
413        let cfg = parse_config_str(r#"git = false"#).unwrap();
414        let mut args = empty_args();
415        assert!(args.git);
416        merge_config_into_args(&mut args, &cfg);
417        // Without --git on the real CLI of this test process, config applies.
418        if !cli_has_long("--git") {
419            assert!(!args.git);
420        }
421    }
422
423    #[test]
424    fn argv0_ls_detection() {
425        assert!(invoked_as_ls_from(Some("ls".into())));
426        assert!(invoked_as_ls_from(Some("/usr/bin/ls".into())));
427        assert!(invoked_as_ls_from(Some(r"C:\bin\ls.exe".into())));
428        assert!(invoked_as_ls_from(Some("LS".into())));
429        assert!(!invoked_as_ls_from(Some("f00".into())));
430        assert!(!invoked_as_ls_from(Some("/usr/local/bin/f00".into())));
431        assert!(!invoked_as_ls_from(None));
432    }
433
434    #[test]
435    fn platform_path_ends_with_config_toml() {
436        if let Some(p) = platform_config_path() {
437            assert_eq!(p.file_name().and_then(|s| s.to_str()), Some("config.toml"));
438            assert!(p
439                .components()
440                .any(|c| c.as_os_str() == "f00" || c.as_os_str() == ".config"));
441        }
442    }
443
444    #[test]
445    fn resolve_ls_soft_mode_keeps_default_icons() {
446        let mut args = empty_args();
447        assert_eq!(args.icons, IconsArg::Auto);
448        resolve_args(&mut args, None, true);
449        assert_eq!(
450            args.icons,
451            IconsArg::Auto,
452            "argv0 ls must keep icons=auto (full chrome; only --gnu strips icons)"
453        );
454        assert!(
455            !args.dirs_first,
456            "soft ls still defaults dirs-first off like GNU"
457        );
458    }
459
460    #[test]
461    fn resolve_ls_config_can_set_icons_always() {
462        let cfg = parse_config_str(r#"icons = true"#).unwrap();
463        let mut args = empty_args();
464        resolve_args(&mut args, Some(&cfg), true);
465        assert_eq!(args.icons, IconsArg::Always);
466    }
467}