rs-hop 0.4.1

Fuzzy-finder TUI to jump between git repositories and folders
Documentation
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
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
//! Loads [`Config`] settings from the TOML file (entries are read separately).
//!
//! Precedence: built-in defaults < `config.toml` < `HOP_`-prefixed env vars.
//! The `[[repos]]` array in the same file is ignored here; the repository owns
//! it.

use std::collections::{BTreeMap, HashMap};
use std::path::Path;
use std::{env, fs};

use serde::Deserialize;

use crate::config::{Appearance, ColumnWidth, ColumnWidths, Config};
use crate::domain::error::{Error, Result};
use crate::theme::{GlyphVariant, Palette, ThemeColors, parse_color};

/// Environment override for the git tool.
const GIT_PROGRAM_ENV: &str = "HOP_GIT_PROGRAM";

/// Environment override for the editor.
const EDITOR_ENV: &str = "HOP_EDITOR";

/// Environment override for the active theme.
const THEME_ENV: &str = "HOP_THEME";

/// Environment override for the glyph variant (`unicode`/`ascii`).
const GLYPHS_ENV: &str = "HOP_GLYPHS";

/// Environment override for the quit confirmation.
const CONFIRM_QUIT_ENV: &str = "HOP_CONFIRM_QUIT";

/// Raw settings as read from TOML; the `repos` array is intentionally ignored.
#[derive(Debug, Default, Deserialize)]
struct RawConfig {
    git_program: Option<String>,
    github_username: Option<String>,
    example_mode: Option<bool>,
    fetch_on_start: Option<bool>,
    confirm_quit: Option<bool>,
    editor: Option<String>,
    editor_extensions: Option<Vec<String>>,
    appearance: Option<RawAppearance>,
    /// Legacy `[icons]` table (pre-migration), folded into `appearance.glyphs`.
    icons: Option<RawIcons>,
    themes: Option<BTreeMap<String, HashMap<String, String>>>,
    keys: Option<BTreeMap<String, KeyBinding>>,
    column_widths: Option<HashMap<String, RawColumnWidth>>,
    zip_backup_folder: Option<String>,
    zip_exclude_dirs: Option<Vec<String>>,
}

/// The `[appearance]` table.
#[derive(Debug, Default, Deserialize)]
struct RawAppearance {
    theme: Option<String>,
    colors: Option<BTreeMap<String, String>>,
    glyphs: Option<String>,
}

/// The legacy `[icons]` table.
#[derive(Debug, Default, Deserialize)]
struct RawIcons {
    variant: Option<String>,
}

/// A `[keys]` binding: one key string or a list of them.
#[derive(Debug, Deserialize)]
#[serde(untagged)]
enum KeyBinding {
    One(String),
    Many(Vec<String>),
}

impl KeyBinding {
    /// The bound keys as a list.
    fn into_keys(self) -> Vec<String> {
        match self {
            KeyBinding::One(key) => vec![key],
            KeyBinding::Many(keys) => keys,
        }
    }
}

/// A column width as either a bare integer (minimum) or a `{ min, max }` table.
#[derive(Debug, Deserialize)]
#[serde(untagged)]
enum RawColumnWidth {
    Fixed(usize),
    Range {
        min: Option<usize>,
        max: Option<usize>,
    },
}

impl RawColumnWidth {
    /// Converts to a [`ColumnWidth`], falling back to `default` for any missing
    /// bound.
    fn resolve(&self, default: ColumnWidth) -> ColumnWidth {
        match self {
            RawColumnWidth::Fixed(min) => ColumnWidth {
                min: *min,
                max: None,
            },
            RawColumnWidth::Range { min, max } => ColumnWidth {
                min: min.unwrap_or(default.min),
                max: max.or(default.max),
            },
        }
    }
}

/// Loads the configuration settings from `path`, returning defaults when the
/// file does not exist.
///
/// # Errors
///
/// Returns [`Error::Config`] if the file exists but cannot be read or parsed.
pub fn load_config(path: &Path) -> Result<Config> {
    let raw = read_raw(path)?;
    let mut config = build(raw);
    apply_env(&mut config);
    Ok(config)
}

/// Reads and parses the raw settings, or returns defaults when `path` is absent.
fn read_raw(path: &Path) -> Result<RawConfig> {
    if !path.exists() {
        return Ok(RawConfig::default());
    }
    let text = fs::read_to_string(path).map_err(|e| {
        Error::config(path.display().to_string(), e.to_string())
    })?;
    toml::from_str(&text)
        .map_err(|e| Error::config(path.display().to_string(), e.to_string()))
}

/// Merges a [`RawConfig`] onto the defaults.
fn build(raw: RawConfig) -> Config {
    let defaults = Config::default();
    report_unknown(&unknown_color_names(&raw));
    Config {
        git_program: raw.git_program.or(defaults.git_program),
        github_username: raw.github_username.or(defaults.github_username),
        example_mode: raw.example_mode.unwrap_or(defaults.example_mode),
        fetch_on_start: raw.fetch_on_start.unwrap_or(defaults.fetch_on_start),
        confirm_quit: raw.confirm_quit.unwrap_or(defaults.confirm_quit),
        editor: raw.editor.or(defaults.editor),
        editor_extensions: raw
            .editor_extensions
            .filter(|exts| !exts.is_empty())
            .unwrap_or(defaults.editor_extensions),
        appearance: resolve_appearance(
            raw.appearance,
            raw.icons,
            defaults.appearance,
        ),
        themes: resolve_themes(raw.themes),
        keys: raw
            .keys
            .map(|keys| {
                keys.into_iter()
                    .map(|(action, binding)| (action, binding.into_keys()))
                    .collect()
            })
            .unwrap_or(defaults.keys),
        column_widths: resolve_column_widths(raw.column_widths.as_ref()),
        zip_backup_folder: raw.zip_backup_folder.or(defaults.zip_backup_folder),
        zip_exclude_dirs: raw
            .zip_exclude_dirs
            .filter(|dirs| !dirs.is_empty())
            .unwrap_or(defaults.zip_exclude_dirs),
    }
}

/// Resolves the `[appearance]` settings, folding the legacy `[icons].variant`
/// into `glyphs` for back-compat (the new `[appearance].glyphs` wins when both
/// are present).
fn resolve_appearance(
    raw: Option<RawAppearance>,
    legacy_icons: Option<RawIcons>,
    defaults: Appearance,
) -> Appearance {
    let raw = raw.unwrap_or_default();
    let legacy_glyph = legacy_icons.and_then(|icons| icons.variant);
    let glyphs = raw
        .glyphs
        .or(legacy_glyph)
        .map_or(defaults.glyphs, |value| parse_glyph_variant(&value));
    Appearance {
        theme: raw.theme.unwrap_or(defaults.theme),
        colors: raw.colors.unwrap_or(defaults.colors),
        glyphs,
    }
}

/// Parses a glyph-variant config string, defaulting to Unicode.
fn parse_glyph_variant(value: &str) -> GlyphVariant {
    match value.trim().to_lowercase().as_str() {
        "ascii" => GlyphVariant::Ascii,
        _ => GlyphVariant::Unicode,
    }
}

/// Resolves user `[themes.<name>]` tables into `(name, ThemeColors)` pairs; each
/// theme may set only some colors (the rest are derived from
/// accent/foreground/background).
fn resolve_themes(
    raw: Option<BTreeMap<String, HashMap<String, String>>>,
) -> Vec<(String, ThemeColors)> {
    let Some(raw) = raw else {
        return Vec::new();
    };
    raw.into_iter()
        .map(|(name, colors)| {
            let theme = ThemeColors::from_lookup(|key| {
                colors.get(key).and_then(|value| parse_color(value))
            });
            (name, theme)
        })
        .collect()
}

/// Every color the file names in a section that cannot carry it, as
/// `(section, name)` pairs.
///
/// The two sections take different color sets, and mixing them up is silent:
/// `[appearance].colors` overrides any palette color, while a
/// `[themes.<name>]` contributes only the [`ThemeColors`] a palette is derived
/// *from*. Validating a theme against `Palette::KEYS` accepts the derived ones
/// (`selection`, `cursor`, `input_bg`, ...) and then drops the value without a
/// word.
fn unknown_color_names(raw: &RawConfig) -> Vec<(String, String)> {
    let mut unknown = Vec::new();
    if let Some(colors) =
        raw.appearance.as_ref().and_then(|it| it.colors.as_ref())
    {
        for name in unknown_colors(colors.keys(), Palette::KEYS) {
            unknown.push(("appearance.colors".to_string(), name));
        }
    }
    for (theme, colors) in raw.themes.iter().flatten() {
        for name in unknown_colors(colors.keys(), ThemeColors::KEYS) {
            unknown.push((format!("themes.{theme}"), name));
        }
    }
    unknown
}

/// The names in `names` that are not in `known`.
fn unknown_colors<'a>(
    names: impl Iterator<Item = &'a String>,
    known: &[&str],
) -> Vec<String> {
    names
        .filter(|name| !known.contains(&name.as_str()))
        .cloned()
        .collect()
}

/// Warns about each unusable color name, so a typo (or a color in the wrong
/// section) surfaces instead of being silently ignored.
fn report_unknown(unknown: &[(String, String)]) {
    for (section, name) in unknown {
        log::warn!("unknown color '{name}' in [{section}], ignoring");
    }
}

/// Resolves the column width budgets, applying any configured override onto the
/// per-column defaults.
fn resolve_column_widths(
    raw: Option<&HashMap<String, RawColumnWidth>>,
) -> ColumnWidths {
    let defaults = ColumnWidths::default();
    let Some(raw) = raw else {
        return defaults;
    };
    let resolve = |key: &str, default: ColumnWidth| {
        raw.get(key).map_or(default, |value| value.resolve(default))
    };
    ColumnWidths {
        name: resolve("name", defaults.name),
        current_branch_name: resolve(
            "current_branch_name",
            defaults.current_branch_name,
        ),
        status: resolve("status", defaults.status),
        github_repo_name: resolve(
            "github_repo_name",
            defaults.github_repo_name,
        ),
        zip_backup: resolve("zip_backup", defaults.zip_backup),
    }
}

/// Applies environment overrides (git tool, editor, theme, glyphs, quit
/// confirmation).
fn apply_env(config: &mut Config) {
    if let Ok(value) = env::var(GIT_PROGRAM_ENV)
        && !value.trim().is_empty()
    {
        config.git_program = Some(value);
    }
    if let Ok(value) = env::var(EDITOR_ENV)
        && !value.trim().is_empty()
    {
        config.editor = Some(value);
    }
    if let Ok(value) = env::var(THEME_ENV)
        && !value.trim().is_empty()
    {
        config.appearance.theme = value;
    }
    if let Ok(value) = env::var(GLYPHS_ENV)
        && !value.trim().is_empty()
    {
        config.appearance.glyphs = parse_glyph_variant(&value);
    }
    if let Ok(value) = env::var(CONFIRM_QUIT_ENV)
        && let Some(flag) = parse_bool(&value)
    {
        config.confirm_quit = flag;
    }
}

/// Parses a boolean environment value. Anything else leaves the setting alone,
/// so a typo cannot silently turn the quit confirmation off.
fn parse_bool(value: &str) -> Option<bool> {
    match value.trim().to_lowercase().as_str() {
        "1" | "true" | "yes" | "on" => Some(true),
        "0" | "false" | "no" | "off" => Some(false),
        _ => None,
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    /// The `(section, name)` pairs `content` reports as unusable.
    fn unknown(content: &str) -> Vec<(String, String)> {
        let raw: RawConfig = toml::from_str(content).expect("valid toml");
        unknown_color_names(&raw)
    }

    #[test]
    fn a_theme_table_rejects_the_palettes_derived_colors() {
        // `cursor`, `selection` and the input fills are derived by the toolkit;
        // a theme cannot contribute them. Accepting them here would drop the
        // value without a word.
        let mut reported = unknown(
            "[themes.mine]\n\
             accent = \"#010203\"\n\
             border = \"#010203\"\n\
             cursor = \"#010203\"\n\
             selection = \"#010203\"\n",
        );
        reported.sort();
        assert_eq!(
            reported,
            vec![
                ("themes.mine".to_string(), "cursor".to_string()),
                ("themes.mine".to_string(), "selection".to_string()),
            ],
        );
    }

    #[test]
    fn appearance_colors_may_name_any_palette_color() {
        let reported = unknown(
            "[appearance]\n\
             colors = { cursor = \"#010203\", selection = \"#010203\" }\n",
        );
        assert!(reported.is_empty(), "{reported:?}");
    }

    #[test]
    fn a_theme_may_name_every_theme_color() {
        let table =
            ThemeColors::KEYS
                .iter()
                .fold(String::new(), |mut table, name| {
                    table.push_str(name);
                    table.push_str(" = \"#010203\"\n");
                    table
                });
        assert!(unknown(&format!("[themes.mine]\n{table}")).is_empty());
    }

    #[test]
    fn both_sections_report_a_typo() {
        assert_eq!(
            unknown("[appearance]\ncolors = { bordr = \"#010203\" }\n"),
            vec![("appearance.colors".to_string(), "bordr".to_string())],
        );
        assert_eq!(
            unknown("[themes.mine]\nbordr = \"#010203\"\n"),
            vec![("themes.mine".to_string(), "bordr".to_string())],
        );
    }

    #[test]
    fn a_clean_file_reports_nothing() {
        assert!(unknown("[appearance]\ntheme = \"default\"\n").is_empty());
    }

    #[test]
    fn every_theme_color_name_is_also_a_palette_color_name() {
        for name in ThemeColors::KEYS {
            assert!(Palette::KEYS.contains(name), "{name} is unreachable");
        }
    }

    #[test]
    fn defaults_when_empty() {
        let config = build(RawConfig::default());
        assert_eq!(config.git_program.as_deref(), Some("lazygit"));
        assert!(!config.example_mode);
        assert!(!config.fetch_on_start);
        assert_eq!(config.appearance.glyphs, GlyphVariant::Unicode);
        assert_eq!(config.column_widths, ColumnWidths::default());
        assert!(config.editor_extensions.iter().any(|e| e == "rs"));
    }

    #[test]
    fn editor_extensions_override_replaces_default() {
        let text = "editor_extensions = [\"md\", \"txt\"]\n";
        let raw: RawConfig = toml::from_str(text).unwrap();
        let config = build(raw);
        assert_eq!(config.editor_extensions, ["md", "txt"]);
    }

    #[test]
    fn parses_settings_and_ignores_repos() {
        let text = r#"
git_program = "gitui"
github_username = "cgroening"
example_mode = true
fetch_on_start = true

[icons]
variant = "ascii"

[column_widths]
name = 40
[column_widths.current_branch_name]
min = 8
max = 20

[[repos]]
name = "ignored here"
path = "/tmp/x"
"#;
        let raw: RawConfig = toml::from_str(text).unwrap();
        let config = build(raw);
        assert_eq!(config.git_program.as_deref(), Some("gitui"));
        assert_eq!(config.github_username.as_deref(), Some("cgroening"));
        assert!(config.example_mode);
        assert!(config.fetch_on_start);
        assert_eq!(config.appearance.glyphs, GlyphVariant::Ascii);
        assert_eq!(config.column_widths.name, ColumnWidth::min(40));
        assert_eq!(
            config.column_widths.current_branch_name,
            ColumnWidth::range(8, 20)
        );
        // Unspecified columns keep their defaults.
        assert_eq!(config.column_widths.status, ColumnWidth::min(6));
    }

    #[test]
    fn parses_appearance_themes_and_keys() {
        let text = r##"
[appearance]
theme = "midnight"
glyphs = "ascii"
colors = { accent = "#ff0000" }

[themes.midnight]
accent = "#8899ff"
background = "#000010"

[keys]
add = "N"
delete = ["d", "backspace"]
"##;
        let raw: RawConfig = toml::from_str(text).unwrap();
        let config = build(raw);
        assert_eq!(config.appearance.theme, "midnight");
        assert_eq!(config.appearance.glyphs, GlyphVariant::Ascii);
        assert_eq!(
            config.appearance.colors.get("accent").map(String::as_str),
            Some("#ff0000"),
        );
        assert!(config.themes.iter().any(|(name, _)| name == "midnight"));
        assert_eq!(config.keys.get("add"), Some(&vec!["N".to_string()]));
        assert_eq!(
            config.keys.get("delete"),
            Some(&vec!["d".to_string(), "backspace".to_string()]),
        );
        // The custom theme resolves through the registry.
        assert!(config.theme_registry().contains("midnight"));
    }

    #[test]
    fn new_appearance_glyphs_wins_over_legacy_icons() {
        // An old config used `[icons]`; a config carrying both prefers the new
        // `[appearance].glyphs`, and one with only `[icons]` still loads.
        let both = "[appearance]\nglyphs = \"unicode\"\n\n[icons]\nvariant = \"ascii\"\n";
        let config = build(toml::from_str(both).unwrap());
        assert_eq!(config.appearance.glyphs, GlyphVariant::Unicode);

        let legacy = "[icons]\nvariant = \"ascii\"\n";
        let config = build(toml::from_str(legacy).unwrap());
        assert_eq!(config.appearance.glyphs, GlyphVariant::Ascii);
    }

    #[test]
    fn a_bool_env_value_reads_the_usual_spellings() {
        for on in ["1", "true", "TRUE", " yes ", "on"] {
            assert_eq!(parse_bool(on), Some(true), "{on:?}");
        }
        for off in ["0", "false", "no", "OFF"] {
            assert_eq!(parse_bool(off), Some(false), "{off:?}");
        }
    }

    #[test]
    fn a_misspelt_bool_env_value_leaves_the_setting_alone() {
        // Returning `false` here would silently disable the quit confirmation.
        assert_eq!(parse_bool("ja"), None);
        assert_eq!(parse_bool(""), None);
    }
}