Skip to main content

lx_cli/
config.rs

1use crate::sort::{SortField, SortOptions, SortOrder};
2use crate::theme::Theme;
3use chrono::format::{Item, StrftimeItems};
4use serde::{Deserialize, Deserializer};
5use std::collections::{BTreeMap, HashMap};
6use std::fs;
7use std::os::unix::fs::MetadataExt;
8use std::path::{Path, PathBuf};
9use toml::Table;
10
11#[derive(Debug, Clone, Default)]
12pub struct Config {
13    pub theme: Theme,
14    pub icons: IconConfig,
15    pub display: DisplayConfig,
16}
17
18impl<'de> Deserialize<'de> for Config {
19    fn deserialize<DeserializerType>(
20        deserializer: DeserializerType,
21    ) -> Result<Self, DeserializerType::Error>
22    where
23        DeserializerType: Deserializer<'de>,
24    {
25        let document = Table::deserialize(deserializer)?;
26        resolve_config(document, None, &mut Vec::new()).map_err(serde::de::Error::custom)
27    }
28}
29
30#[derive(Deserialize, Default)]
31struct Settings {
32    #[serde(default)]
33    theme: Option<String>,
34    #[serde(default)]
35    icons: IconConfig,
36    #[serde(default)]
37    display: DisplayConfig,
38}
39
40pub use crate::theme::FontStyle;
41
42#[derive(Debug, Deserialize, Clone, Default)]
43pub struct IconConfig {
44    #[serde(default)]
45    pub enabled: bool,
46    #[serde(default)]
47    pub directory: Option<String>,
48    #[serde(default)]
49    pub executable: Option<String>,
50    #[serde(default)]
51    pub regular: Option<String>,
52    #[serde(default)]
53    pub symlink: Option<String>,
54    /// Icons by filesystem identity, resolved from path keys when reading configuration.
55    #[serde(default, deserialize_with = "deserialize_path_icons")]
56    pub paths: HashMap<(u64, u64), String>,
57    #[serde(default)]
58    pub patterns: Vec<IconPattern>,
59}
60
61/// An ordered icon rule matching an entry's name or absolute path.
62#[derive(Debug, Deserialize, Clone)]
63pub struct IconPattern {
64    pub pattern: String,
65    pub icon: String,
66    #[serde(default)]
67    pub kind: IconPatternKind,
68}
69
70#[derive(Debug, Deserialize, Clone, Copy, Default)]
71#[serde(rename_all = "snake_case")]
72pub enum IconPatternKind {
73    #[default]
74    Any,
75    File,
76    Directory,
77}
78
79fn deserialize_path_icons<'de, DeserializerType>(
80    deserializer: DeserializerType,
81) -> Result<HashMap<(u64, u64), String>, DeserializerType::Error>
82where
83    DeserializerType: Deserializer<'de>,
84{
85    let paths = BTreeMap::<String, String>::deserialize(deserializer)?;
86    Ok(paths
87        .into_iter()
88        .filter_map(|(path, icon)| {
89            if path.is_empty() {
90                return None;
91            }
92            let path = PathBuf::from(path);
93            let path = if path.is_absolute() {
94                path
95            } else {
96                dirs::home_dir()?.join(path.strip_prefix("~").unwrap_or(&path))
97            };
98            let metadata = fs::symlink_metadata(path).ok()?;
99            Some(((metadata.dev(), metadata.ino()), icon))
100        })
101        .collect())
102}
103
104#[derive(Debug, Deserialize, Clone)]
105pub struct DisplayConfig {
106    #[serde(default = "default_column_spacing")]
107    pub column_spacing: usize,
108    #[serde(default = "default_max_rows")]
109    pub max_rows: usize,
110    #[serde(default = "default_compact_max_rows")]
111    pub compact_max_rows: usize,
112    #[serde(default)]
113    pub sort_field: Option<SortField>,
114    #[serde(default)]
115    pub sort_order: SortOrder,
116    #[serde(default = "default_datetime_format")]
117    pub datetime_format: String,
118    #[serde(default)]
119    pub tree: TreeConfig,
120    /// Validated in `resolve_config` so unknown names become diagnostics.
121    #[serde(skip_deserializing, default = "default_long_format_fields")]
122    pub long_format_fields: Vec<LongField>,
123    #[serde(default = "default_long_format_titles")]
124    pub long_format_titles: bool,
125    #[serde(default)]
126    pub language_colors: bool,
127}
128
129#[derive(Debug, Deserialize, Clone)]
130pub struct TreeConfig {
131    #[serde(default = "default_tree_style")]
132    pub style: String,
133}
134
135impl Default for TreeConfig {
136    fn default() -> Self {
137        TreeConfig {
138            style: default_tree_style(),
139        }
140    }
141}
142
143impl Default for DisplayConfig {
144    fn default() -> Self {
145        DisplayConfig {
146            column_spacing: default_column_spacing(),
147            max_rows: default_max_rows(),
148            compact_max_rows: default_compact_max_rows(),
149            sort_field: None,
150            sort_order: SortOrder::Asc,
151            datetime_format: default_datetime_format(),
152            tree: TreeConfig::default(),
153            long_format_fields: default_long_format_fields(),
154            long_format_titles: default_long_format_titles(),
155            language_colors: false,
156        }
157    }
158}
159
160fn default_column_spacing() -> usize {
161    2
162}
163
164fn default_max_rows() -> usize {
165    0 // 0 means no limit
166}
167
168fn default_compact_max_rows() -> usize {
169    10
170}
171
172const DEFAULT_DATETIME_FORMAT: &str = "%-d %b %H:%M";
173
174fn default_datetime_format() -> String {
175    DEFAULT_DATETIME_FORMAT.to_string()
176}
177
178fn default_tree_style() -> String {
179    "ascii".to_string()
180}
181
182fn default_long_format_fields() -> Vec<LongField> {
183    vec![
184        LongField::Permissions,
185        LongField::Size,
186        LongField::Modified,
187        LongField::Git,
188        LongField::Filename,
189    ]
190}
191
192/// A column in long output.
193#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
194pub enum LongField {
195    Git,
196    Permissions,
197    Nlink,
198    Owner,
199    Group,
200    Size,
201    Modified,
202    Filename,
203}
204
205impl LongField {
206    /// Parses a configured field name; `Ok(None)` marks the ignored legacy `icon` field.
207    fn parse(name: &str) -> Result<Option<Self>, ()> {
208        Ok(Some(match name {
209            "git" => Self::Git,
210            "permissions" => Self::Permissions,
211            "nlink" | "links" => Self::Nlink,
212            "owner" => Self::Owner,
213            "group" => Self::Group,
214            "size" => Self::Size,
215            "modified" => Self::Modified,
216            "filename" => Self::Filename,
217            "icon" => return Ok(None),
218            _ => return Err(()),
219        }))
220    }
221
222    /// The field name used by legacy per-column style settings.
223    pub fn name(self) -> &'static str {
224        match self {
225            Self::Git => "git",
226            Self::Permissions => "permissions",
227            Self::Nlink => "nlink",
228            Self::Owner => "owner",
229            Self::Group => "group",
230            Self::Size => "size",
231            Self::Modified => "modified",
232            Self::Filename => "filename",
233        }
234    }
235
236    pub fn title(self) -> &'static str {
237        match self {
238            Self::Git => "Git",
239            Self::Permissions => "Permissions",
240            Self::Nlink => "Links",
241            Self::Owner => "Owner",
242            Self::Group => "Group",
243            Self::Size => "Size",
244            Self::Modified => "Modified",
245            Self::Filename => "Name",
246        }
247    }
248}
249
250fn default_long_format_titles() -> bool {
251    true
252}
253
254impl IconConfig {
255    pub fn get_directory_icon(&self) -> String {
256        crate::icon::FileIcon::Directory.as_str_custom(self)
257    }
258
259    pub fn get_executable_icon(&self) -> String {
260        crate::icon::FileIcon::Executable.as_str_custom(self)
261    }
262
263    pub fn get_regular_icon(&self) -> String {
264        crate::icon::FileIcon::RegularFile.as_str_custom(self)
265    }
266
267    pub fn get_symlink_icon(&self) -> String {
268        crate::icon::FileIcon::Symlink.as_str_custom(self)
269    }
270
271    /// Whether any file type has a visible icon after applying overrides.
272    pub fn has_icons(&self) -> bool {
273        [
274            self.get_directory_icon(),
275            self.get_executable_icon(),
276            self.get_regular_icon(),
277            self.get_symlink_icon(),
278        ]
279        .iter()
280        .any(|icon| !icon.is_empty())
281            || self.paths.values().any(|icon| !icon.is_empty())
282            || self.patterns.iter().any(|rule| !rule.icon.is_empty())
283    }
284}
285
286impl DisplayConfig {
287    pub fn uses_sizes(&self, long: bool, sort: SortOptions) -> bool {
288        sort.field == Some(SortField::Size)
289            || (long && self.long_format_fields.contains(&LongField::Size))
290    }
291
292    /// Parsed `datetime_format` items; the format is validated when the config loads.
293    pub(crate) fn datetime_items(&self) -> Vec<Item<'_>> {
294        StrftimeItems::new(&self.datetime_format)
295            .parse()
296            .unwrap_or_else(|_| {
297                StrftimeItems::new(DEFAULT_DATETIME_FORMAT)
298                    .parse()
299                    .expect("default datetime format is valid")
300            })
301    }
302
303    pub fn default_sort(&self) -> SortOptions {
304        SortOptions::new(self.sort_field, self.sort_order)
305    }
306}
307
308pub fn load_config() -> Config {
309    let directory = dirs::home_dir()
310        .unwrap_or_else(|| PathBuf::from("."))
311        .join(".config/lx");
312    let preferred = directory.join("config.toml");
313    let config_path = match fs::symlink_metadata(&preferred) {
314        Err(error) if error.kind() == std::io::ErrorKind::NotFound => directory.join("config"),
315        _ => preferred,
316    };
317    let contents = match fs::read_to_string(&config_path) {
318        Ok(contents) => contents,
319        Err(error) => {
320            if error.kind() != std::io::ErrorKind::NotFound || config_path.ends_with("config.toml")
321            {
322                eprintln!(
323                    "lx: cannot read config '{}': {error}",
324                    config_path.display()
325                );
326            }
327            return Config::default();
328        }
329    };
330    let document = match toml::from_str::<Table>(&contents) {
331        Ok(document) => document,
332        Err(error) => {
333            eprintln!(
334                "lx: cannot parse config '{}': {error}",
335                config_path.display()
336            );
337            return Config::default();
338        }
339    };
340    let mut diagnostics = Vec::new();
341    let result = resolve_config(document, Some(&directory), &mut diagnostics);
342    for diagnostic in diagnostics {
343        eprintln!("lx: config '{}': {diagnostic}", config_path.display());
344    }
345    result.unwrap_or_else(|error| {
346        eprintln!(
347            "lx: cannot parse config '{}': {error}",
348            config_path.display()
349        );
350        Config::default()
351    })
352}
353
354fn resolve_config(
355    document: Table,
356    directory: Option<&Path>,
357    diagnostics: &mut Vec<String>,
358) -> Result<Config, toml::de::Error> {
359    let settings: Settings = toml::Value::Table(document.clone()).try_into()?;
360    let mut theme = Theme::default();
361    if let (Some(name), Some(directory)) = (settings.theme.as_deref(), directory) {
362        apply_named_theme(&mut theme, name, directory, diagnostics);
363    }
364    theme.apply_legacy(&document, diagnostics);
365    theme.apply_document(&document, true, diagnostics);
366    let mut display = settings.display;
367    if StrftimeItems::new(&display.datetime_format)
368        .parse()
369        .is_err()
370    {
371        diagnostics.push(format!(
372            "invalid display.datetime_format {:?}; using {DEFAULT_DATETIME_FORMAT:?}",
373            display.datetime_format
374        ));
375        display.datetime_format = default_datetime_format();
376    }
377    if let Some(fields) = document
378        .get("display")
379        .and_then(|display| display.get("long_format_fields"))
380    {
381        match fields.clone().try_into::<Vec<String>>() {
382            Ok(names) => {
383                display.long_format_fields = names
384                    .iter()
385                    .filter_map(|name| {
386                        LongField::parse(name).unwrap_or_else(|()| {
387                            diagnostics
388                                .push(format!("unknown display.long_format_fields entry {name:?}"));
389                            None
390                        })
391                    })
392                    .collect();
393            }
394            Err(error) => diagnostics.push(format!("display.long_format_fields: {error}")),
395        }
396    }
397    Ok(Config {
398        theme,
399        icons: settings.icons,
400        display,
401    })
402}
403
404fn apply_named_theme(
405    theme: &mut Theme,
406    name: &str,
407    directory: &Path,
408    diagnostics: &mut Vec<String>,
409) {
410    if name.is_empty() || name == "." || name == ".." || name.contains(['/', '\\']) {
411        diagnostics.push(format!("invalid theme name: {name:?}"));
412        return;
413    }
414    let path = directory.join("themes").join(format!("{name}.toml"));
415    let contents = match fs::read_to_string(&path) {
416        Ok(contents) => contents,
417        Err(error) if name == "default" && error.kind() == std::io::ErrorKind::NotFound => return,
418        Err(error) => {
419            diagnostics.push(format!("cannot read theme '{}': {error}", path.display()));
420            return;
421        }
422    };
423    match toml::from_str::<Table>(&contents) {
424        Ok(document) => {
425            let mut theme_diagnostics = Vec::new();
426            for key in document.keys().filter(|key| key.as_str() != "style") {
427                theme_diagnostics.push(format!("unknown key {key:?}; themes contain only style"));
428            }
429            let mut candidate = theme.clone();
430            candidate.apply_document(&document, false, &mut theme_diagnostics);
431            if theme_diagnostics.is_empty() {
432                *theme = candidate;
433            }
434            diagnostics.extend(
435                theme_diagnostics
436                    .into_iter()
437                    .map(|message| format!("theme '{}': {message}", path.display())),
438            );
439        }
440        Err(error) => diagnostics.push(format!("cannot parse theme '{}': {error}", path.display())),
441    }
442}