lx-ls 0.10.1

The file lister with personality! 🌟
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
//! Data types deserialised from a `lxconfig.toml` file.
//!
//! These are the on-disk schema: the top-level `Config`, plus the
//! per-section types (`PersonalityDef`, `ThemeDef`, `StyleDef`,
//! `ConditionalOverride`).  None of the resolution or rendering logic
//! lives here — see `personality.rs`, `themes.rs`, etc.

use std::collections::HashMap;
use std::env;
use std::ffi::OsString;
use std::path::PathBuf;

use serde::Deserialize;

use super::settings::settings_to_args;

// ── Config schema versioning ────────────────────────────────────

/// The current config schema version.
pub const CONFIG_VERSION: &str = "0.6";

/// Accepted config versions.  0.3, 0.4, and 0.5 are forward-compatible
/// subsets of 0.6: any config file from these versions loads fine in
/// the current parser.  0.6 adds glob and array support to `[[when]]`
/// env conditions — both purely additive.  The only ever-removed
/// setting is `time = "..."` (gone in 0.5), which triggers a warning
/// and is ignored if found in 0.3/0.4 files.
pub(super) const ACCEPTED_VERSIONS: &[&str] = &["0.3", "0.4", "0.5", "0.6"];

// ── Top-level config ────────────────────────────────────────────

/// Top-level config file structure.
#[derive(Debug, Default, Deserialize)]
#[serde(default)]
pub struct Config {
    /// Config schema version.  `None` means a legacy (pre-0.2) config.
    pub version: Option<String>,

    #[serde(default)]
    pub format: HashMap<String, Vec<String>>,

    #[serde(default)]
    pub personality: HashMap<String, PersonalityDef>,

    /// Named theme definitions: `[theme.NAME]`.
    #[serde(default)]
    pub theme: HashMap<String, ThemeDef>,

    /// Named file colour style sets: `[style.NAME]`.
    #[serde(default)]
    pub style: HashMap<String, StyleDef>,

    /// File-type class definitions: `[class]`.
    /// Each key is a class name, each value a list of glob patterns.
    #[serde(default)]
    pub class: HashMap<String, Vec<String>>,

    /// Paths of loaded drop-in fragments (for `--show-config`).
    #[serde(skip)]
    pub drop_in_paths: Vec<PathBuf>,
}

impl Config {
    /// Merge a drop-in fragment into this config.  Each named entry
    /// in the fragment overrides the same-named entry in `self`.
    pub(super) fn merge(&mut self, other: Config) {
        for (k, v) in other.format {
            self.format.insert(k, v);
        }
        for (k, v) in other.personality {
            self.personality.insert(k, v);
        }
        for (k, v) in other.theme {
            self.theme.insert(k, v);
        }
        for (k, v) in other.style {
            self.style.insert(k, v);
        }
        for (k, v) in other.class {
            self.class.insert(k, v);
        }
    }
}

// ── ThemeDef ────────────────────────────────────────────────────

/// A named theme definition under `[theme.NAME]`.
///
/// UI element keys are captured via `serde(flatten)` into a flat map.
/// File colour styles are referenced by name from `[style.NAME]`
/// sections.
///
/// Theme selection happens through personalities (`theme = "NAME"`)
/// or the `--theme=NAME` CLI flag.
///
/// Themes can inherit from other themes via `inherits = "NAME"`.
/// The special name `"exa"` refers to the compiled-in default theme.
/// Without `inherits`, a theme starts from a blank slate.
#[derive(Debug, Default, Deserialize, Clone)]
#[serde(default, rename_all = "kebab-case")]
pub struct ThemeDef {
    /// Optional one-line description, shown under
    /// `--show-config`'s available-catalogue section.
    pub description: Option<String>,

    /// Inherit from another theme.  The parent's UI keys are applied
    /// first; this theme's keys override.  The special name `"exa"`
    /// refers to the compiled-in default theme.
    pub inherits: Option<String>,

    /// Reference a named style set from `[style.NAME]`.
    pub use_style: Option<String>,

    /// UI element colour overrides (flat keys like `directory`, `date`, etc.)
    #[serde(flatten)]
    pub ui: HashMap<String, String>,
}

// ── StyleDef ────────────────────────────────────────────────────

/// A named file colour style set under `[style.NAME]`.
///
/// Class references use bare dotted TOML keys (`class.media`),
/// which serde deserialises into the `class` sub-table.  File
/// patterns use quoted TOML keys (`"*.rs"`, `"Makefile"`), which
/// land in the `patterns` map via `serde(flatten)`.
#[derive(Debug, Default, Deserialize, Clone)]
#[serde(default)]
pub struct StyleDef {
    /// Class references: `class.NAME = "colour"` (bare dotted keys).
    #[serde(default, rename = "class")]
    pub classes: HashMap<String, String>,

    /// File patterns: `"*.rs" = "colour"` (quoted keys).
    /// Keys with glob metacharacters are glob patterns; keys without
    /// are exact filename matches.
    #[serde(flatten)]
    pub patterns: HashMap<String, String>,
}

// ── ConditionalOverride ─────────────────────────────────────────

/// A conditional override block: `[[personality.NAME.when]]`.
///
/// Environment conditions use `env.VAR = value` where the value type
/// determines the check:
/// - **String** (`env.TERM_PROGRAM = "ghostty"`) — exact match
/// - **`true`** (`env.SSH_CONNECTION = true`) — variable must be set
///   (to any value, including empty)
/// - **`false`** (`env.DISPLAY = false`) — variable must be truly
///   unset (not just empty)
///
/// Platform conditions use `platform = ...` to gate on the host
/// operating system, matched against `std::env::consts::OS`
/// (e.g. `"macos"`, `"linux"`, `"freebsd"`).
///
/// All conditions in a block must match (AND logic).
#[derive(Debug, Default, Deserialize, Clone)]
#[serde(default)]
pub struct ConditionalOverride {
    /// Environment variable conditions.  Values are either strings
    /// (exact match), `true` (must be set), or `false` (must be unset).
    #[serde(default)]
    pub env: HashMap<String, toml::Value>,

    /// Platform condition.  Matched against `std::env::consts::OS`
    /// (e.g. `"macos"`, `"linux"`, `"freebsd"`).  Accepts a string
    /// (exact match) or array of strings (any-of).
    #[serde(default)]
    pub platform: Option<toml::Value>,

    /// Settings to overlay when conditions match.
    #[serde(flatten)]
    pub settings: HashMap<String, toml::Value>,
}

impl ConditionalOverride {
    /// Check whether all conditions (env + platform) are satisfied.
    ///
    /// `env` values can be:
    /// - **String** — literal exact match, OR a glob pattern if it
    ///   contains glob metacharacters (`*`, `?`, `[`).
    /// - **Array of strings** — any element matches (each element is
    ///   independently treated as literal-or-glob).
    /// - **`true`** — variable must be set to anything (even empty).
    /// - **`false`** — variable must be unset entirely.
    ///
    /// `platform` accepts a string (exact match against
    /// `std::env::consts::OS`) or an array of strings (any-of).
    ///
    /// Globs and arrays were added in config schema 0.6; the existing
    /// literal-string and boolean forms continue to work unchanged.
    /// The `platform` predicate was added later and is purely
    /// additive.
    pub(super) fn matches(&self) -> bool {
        let env_ok = self.env.iter().all(|(key, condition)| {
            let actual = env::var(key).unwrap_or_default();
            match condition {
                toml::Value::String(expected) => super::load::match_string(&actual, expected),
                toml::Value::Array(items) => items.iter().any(|item| match item {
                    toml::Value::String(s) => super::load::match_string(&actual, s),
                    _ => false,
                }),
                toml::Value::Boolean(true) => env::var(key).is_ok(),
                toml::Value::Boolean(false) => env::var(key).is_err(),
                // Anything else: ignore (treat as always-true).
                _ => true,
            }
        });

        let platform_ok = match &self.platform {
            None => true,
            Some(toml::Value::String(want)) => want == std::env::consts::OS,
            Some(toml::Value::Array(items)) => items.iter().any(|item| match item {
                toml::Value::String(s) => s == std::env::consts::OS,
                _ => false,
            }),
            // Unsupported value type: ignore (treat as always-true).
            Some(_) => true,
        };

        env_ok && platform_ok
    }

    /// Like `matches`, but returns a structured per-condition
    /// outcome usable by diagnostic surfaces (`--show-config`).
    /// Each entry is one condition (an `env.X` row, or the
    /// `platform` row), pre-rendered for display.
    pub fn explain(&self) -> Vec<ConditionOutcome> {
        let mut out = Vec::new();
        let mut env_keys: Vec<_> = self.env.keys().collect();
        env_keys.sort();
        for key in env_keys {
            let condition = &self.env[key];
            let actual = env::var(key).unwrap_or_default();
            let matched = match condition {
                toml::Value::String(expected) => super::load::match_string(&actual, expected),
                toml::Value::Array(items) => items.iter().any(|item| match item {
                    toml::Value::String(s) => super::load::match_string(&actual, s),
                    _ => false,
                }),
                toml::Value::Boolean(true) => env::var(key).is_ok(),
                toml::Value::Boolean(false) => env::var(key).is_err(),
                _ => true,
            };
            out.push(ConditionOutcome {
                description: format!("env.{key} = {}", condition_repr(condition)),
                matched,
            });
        }
        if let Some(p) = &self.platform {
            let current = std::env::consts::OS;
            let matched = match p {
                toml::Value::String(want) => want == current,
                toml::Value::Array(items) => items.iter().any(|item| match item {
                    toml::Value::String(s) => s == current,
                    _ => false,
                }),
                _ => true,
            };
            out.push(ConditionOutcome {
                description: format!("platform = {}", condition_repr(p)),
                matched,
            });
        }
        out
    }
}

/// Outcome of evaluating a single condition (one `env.X` or the
/// `platform`).
#[derive(Debug, Clone)]
pub struct ConditionOutcome {
    /// Human-readable rendering of the condition itself
    /// (e.g. `env.LX_DEBUG = "1"`, `platform = ["macos", "linux"]`).
    pub description: String,
    /// Whether this condition is satisfied in the current
    /// environment.
    pub matched: bool,
}

/// Render a condition value as it would appear in the source
/// TOML (best-effort: strings get quoted, arrays bracketed,
/// booleans verbatim).
fn condition_repr(v: &toml::Value) -> String {
    match v {
        toml::Value::String(s) => format!("\"{s}\""),
        toml::Value::Boolean(b) => b.to_string(),
        toml::Value::Array(items) => {
            let parts: Vec<String> = items.iter().map(condition_repr).collect();
            format!("[{}]", parts.join(", "))
        }
        other => other.to_string(),
    }
}

// ── PersonalityDef ──────────────────────────────────────────────

/// A personality bundles format, columns, and settings.
///
/// `format` and `columns` are structural fields (they define the
/// column layout).  `inherits` controls how personalities compose.
/// All other settings are captured via `serde(flatten)` and
/// converted to CLI args via `SETTING_FLAGS`.
///
/// Conditional overrides (`[[personality.NAME.when]]`) allow settings
/// to vary based on environment variables.
#[derive(Debug, Default, Deserialize, Clone)]
#[serde(default)]
pub struct PersonalityDef {
    /// Optional one-line description, shown under
    /// `--show-config`'s available-catalogue section.
    pub description: Option<String>,

    /// Inherit from another personality.  The parent's settings
    /// are applied first; this personality's values override per-key.
    /// `format` and `columns` replace (not merge) the parent's.
    pub inherits: Option<String>,

    /// Reference to a named format (looked up in `[format.*]`).
    pub format: Option<String>,

    /// Inline column list (overrides `format` if both given).
    /// Accepts a TOML array or a comma-separated string.
    pub columns: Option<StringOrList>,

    /// Conditional overrides: `[[personality.NAME.when]]` blocks.
    #[serde(default)]
    pub when: Vec<ConditionalOverride>,

    /// All other settings, converted to CLI args via `SETTING_FLAGS`.
    #[serde(flatten)]
    pub settings: HashMap<String, toml::Value>,
}

impl PersonalityDef {
    /// Convert this personality's settings to synthetic CLI arguments.
    /// Order: columns/format first, then named settings.
    pub fn to_args(&self) -> Vec<OsString> {
        let mut args = Vec::new();

        // Structural fields.
        if let Some(ref cols) = self.columns {
            args.push(format!("--columns={}", cols.to_csv()).into());
        } else if let Some(ref fmt) = self.format {
            args.push(format!("--format={fmt}").into());
        }

        // Named settings.
        args.extend(settings_to_args(&self.settings, "[personality]"));

        args
    }
}

// ── StringOrList ────────────────────────────────────────────────

/// A value that can be either a TOML string (comma-separated) or a
/// TOML array of strings.  Used for the `columns` field.
#[derive(Debug, Clone)]
pub enum StringOrList {
    Str(String),
    List(Vec<String>),
}

impl StringOrList {
    /// Convert to a comma-separated string suitable for `--columns=`.
    pub fn to_csv(&self) -> String {
        match self {
            Self::Str(s) => s.clone(),
            Self::List(v) => v.join(","),
        }
    }
}

impl<'de> Deserialize<'de> for StringOrList {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        use serde::de;

        struct Visitor;

        impl<'de> de::Visitor<'de> for Visitor {
            type Value = StringOrList;

            fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
                f.write_str("a string or array of strings")
            }

            fn visit_str<E: de::Error>(self, v: &str) -> Result<StringOrList, E> {
                Ok(StringOrList::Str(v.to_string()))
            }

            fn visit_seq<A: de::SeqAccess<'de>>(
                self,
                mut seq: A,
            ) -> Result<StringOrList, A::Error> {
                let mut v = Vec::new();
                while let Some(s) = seq.next_element::<String>()? {
                    v.push(s);
                }
                Ok(StringOrList::List(v))
            }
        }

        deserializer.deserialize_any(Visitor)
    }
}