gitwig 2.1.1

a rust based tui, an alternative to sourcetree and gitui
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
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
use std::error::Error;
use std::fs;
use std::path::{Path, PathBuf};

use serde::{Deserialize, Serialize};

#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum SortOrder {
    Alphabetical,
    RecentVisit,
    LatestChanges,
    Custom,
}

fn default_sort_by() -> SortOrder {
    SortOrder::Custom
}

fn default_visits() -> std::collections::HashMap<String, u64> {
    std::collections::HashMap::new()
}

/// How long the event loop waits for input before re-drawing (milliseconds).
/// Lower values feel more responsive; higher values use less CPU.
fn default_poll_interval_ms() -> u64 {
    100
}

fn default_max_commits() -> usize {
    500
}

fn default_graph_max_commits() -> usize {
    1000
}

fn default_detail_cache_ttl_secs() -> u64 {
    30
}

fn default_tab_ttl_secs() -> u64 {
    60
}

fn default_page_size() -> usize {
    10
}

fn default_git_app() -> String {
    "gitui".to_string()
}

#[derive(Debug, Deserialize, Serialize, Clone, PartialEq, Eq)]
pub struct ThemeConfig {
    #[serde(default = "default_accent")]
    pub accent: String,
    #[serde(default = "default_warning")]
    pub warning: String,
    #[serde(default = "default_danger")]
    pub danger: String,
    #[serde(default = "default_success")]
    pub success: String,
    #[serde(default = "default_border_type")]
    pub border_type: String,
}

#[derive(Debug, Deserialize, Serialize, Clone, PartialEq, Eq)]
pub struct FzfConfig {
    #[serde(default = "default_fzf_max_depth")]
    pub max_depth: usize,
    #[serde(default = "default_fzf_excludes")]
    pub excludes: Vec<String>,
    #[serde(default = "default_fzf_start_dir")]
    pub start_dir: String,
    #[serde(default = "default_fzf_git_only")]
    pub git_only: bool,
    #[serde(default = "default_fzf_enabled")]
    pub enabled: bool,
}

impl Default for ThemeConfig {
    fn default() -> Self {
        default_theme()
    }
}

impl Default for FzfConfig {
    fn default() -> Self {
        default_fzf()
    }
}

fn default_accent() -> String {
    "cyan".to_string()
}
fn default_warning() -> String {
    "yellow".to_string()
}
fn default_danger() -> String {
    "red".to_string()
}
fn default_success() -> String {
    "green".to_string()
}
fn default_border_type() -> String {
    "rounded".to_string()
}

fn default_theme() -> ThemeConfig {
    ThemeConfig {
        accent: default_accent(),
        warning: default_warning(),
        danger: default_danger(),
        success: default_success(),
        border_type: default_border_type(),
    }
}

fn default_theme_name() -> String {
    "default".to_string()
}

fn default_fzf_max_depth() -> usize {
    6
}
fn default_fzf_excludes() -> Vec<String> {
    vec![]
}

fn default_fzf_start_dir() -> String {
    dirs::home_dir()
        .map(|p| {
            let mut s = p.to_string_lossy().into_owned();
            if !s.ends_with(std::path::MAIN_SEPARATOR) {
                s.push(std::path::MAIN_SEPARATOR);
            }
            s
        })
        .unwrap_or_else(|| "/".to_string())
}
fn default_fzf_git_only() -> bool {
    true
}
fn default_fzf_enabled() -> bool {
    true
}
fn default_compatibility_mode() -> bool {
    true
}
fn default_resync_on_tab_change() -> bool {
    false
}
fn default_enable_commit_signatures() -> bool {
    false
}

fn default_fzf() -> FzfConfig {
    FzfConfig {
        max_depth: default_fzf_max_depth(),
        excludes: default_fzf_excludes(),
        start_dir: default_fzf_start_dir(),
        git_only: default_fzf_git_only(),
        enabled: default_fzf_enabled(),
    }
}

/// Represents the structure of the configuration file.
#[derive(Debug, Deserialize, Serialize, Clone)]
pub struct Config {
    /// Repository/directory paths shown in the main list.
    pub items: Vec<String>,
    /// Event-loop poll interval in milliseconds (default: 100).
    /// Lower → more responsive, higher → less CPU. Sane range: 16–500.
    #[serde(default = "default_poll_interval_ms")]
    pub poll_interval_ms: u64,
    /// Maximum commits to load in workspace view. Default is 0 (unlimited).
    #[serde(default = "default_max_commits")]
    pub max_commits: usize,
    /// Maximum commits visualised in the Graph tab (0 = unlimited; default 1000)
    #[serde(default = "default_graph_max_commits")]
    pub graph_max_commits: usize,
    /// TTL in seconds for the detail view cache (default: 30)
    #[serde(default = "default_detail_cache_ttl_secs")]
    pub detail_cache_ttl_secs: u64,
    /// TTL in seconds for the lazy-loaded tabs (default: 60)
    #[serde(default = "default_tab_ttl_secs")]
    pub tab_ttl_secs: u64,
    /// Number of lines/items to scroll when PageUp or PageDown is pressed. Default is 10.
    #[serde(default = "default_page_size")]
    pub page_size: usize,
    /// Sort mode for the main page.
    #[serde(default = "default_sort_by")]
    pub sort_by: SortOrder,
    /// Map of repository items to their last visit time.
    #[serde(default = "default_visits")]
    pub visits: std::collections::HashMap<String, u64>,
    /// Map of repository paths to their labels.
    #[serde(default)]
    pub labels: std::collections::HashMap<String, Vec<String>>,
    /// Whether sorting should be reversed.
    #[serde(default)]
    pub sort_reverse: bool,
    /// List of pinned repository paths.
    #[serde(default)]
    pub pinned: std::collections::HashSet<String>,
    /// Theme configurations for styling the terminal TUI.
    #[serde(skip)]
    pub theme: ThemeConfig,
    /// Active theme name selection.
    #[serde(rename = "theme", default = "default_theme_name")]
    pub theme_name: String,
    /// Configuration for interactive repository discovery via fzf.
    #[serde(default = "default_fzf")]
    pub fzf: FzfConfig,
    /// Preferred Git application (e.g. gitui or lazygit).
    #[serde(default = "default_git_app")]
    pub git_app: String,
    /// Enable compatibility mode to use ASCII/simple symbols instead of complex Unicode.
    #[serde(default = "default_compatibility_mode")]
    pub compatibility_mode: bool,
    /// Whether to resync the repository details from disk on tab change.
    #[serde(default = "default_resync_on_tab_change")]
    pub resync_on_tab_change: bool,
    /// Whether to enable commit GPG/SSH signatures collection (spawns a git shell process).
    #[serde(default = "default_enable_commit_signatures")]
    pub enable_commit_signatures: bool,
}

impl Config {
    pub fn sym(&self, key: &str) -> &'static str {
        if self.compatibility_mode {
            match key {
                "branch" => "* ",
                "git_repo" => "G  ",
                "arrow_down" => "v",
                "arrow_right" => ">",
                "folder_tree_expanded" => "v ",
                "folder_tree_collapsed" => "> ",
                "file_tree" => "  -  ",
                "folder" => "[D]",
                "file" => "[F]",
                "pinned" => "[P]",
                "action" => "[!]",
                "warning" => "! ",
                "close" => "x",
                "bullet_empty" => "o",
                "bullet_filled" => "*",
                "star" => "*",
                "block" => "#",
                "bar" => "|",
                "esc" => "ESC",
                "backspace" => "Backspace",
                "tab" => "Tab",
                "shift" => "Shift",
                "enter" => "Enter",
                "up" => "^",
                "down" => "v",
                "page_up" => "PgUp",
                "page_down" => "PgDn",
                "transfer" => "<->",
                "up_down" => "^/v",
                "selection_mark" => "> ",
                _ => "",
            }
        } else {
            match key {
                "branch" => "",
                "git_repo" => "",
                "arrow_down" => "",
                "arrow_right" => "",
                "folder_tree_expanded" => "",
                "folder_tree_collapsed" => "> ",
                "file_tree" => "  📄 ",
                "folder" => "📁 ",
                "file" => "📄 ",
                "pinned" => "📌 ",
                "action" => "",
                "warning" => "",
                "close" => "",
                "bullet_empty" => "",
                "bullet_filled" => "",
                "star" => "",
                "block" => "",
                "bar" => "",
                "esc" => "",
                "backspace" => "",
                "tab" => "",
                "shift" => "",
                "enter" => "",
                "up" => "",
                "down" => "",
                "page_up" => "",
                "page_down" => "",
                "transfer" => "",
                "up_down" => "↑↓",
                "selection_mark" => "",
                _ => "",
            }
        }
    }
}

/// Returns `~/.gitwig/`, the canonical Gitwig data directory.
/// Falls back to `./.gitwig/` in the unlikely event that the home directory
/// cannot be resolved (e.g. inside a stripped-down container).
fn home_gitwig_dir() -> PathBuf {
    dirs::home_dir().unwrap_or_else(|| PathBuf::from(".")).join(".gitwig")
}

/// Loads the configuration, ensuring `~/.gitwig/` always exists.
///
/// Resolution order:
/// 1. CLI-provided path (if given, skip all migration logic).
/// 2. `~/.gitwig/config.toml` — the canonical location. If it already
///    exists it is loaded directly.
/// 3. First-run migration: copy the first config found among
///    `./config/config.toml` (CWD or exe-dir), `~/.twig/config.toml`,
///    `~/.config/gitwig/config.toml`, or `~/.config/twig/config.toml`
///    into `~/.gitwig/config.toml`, then load from there.
/// 4. No prior config anywhere: write a default config to
///    `~/.gitwig/config.toml` so the next run is an ordinary case 2.
///
/// # Returns
/// `Ok((Config, PathBuf))` — the parsed config plus its write-back path.
pub fn load_config(cli_path: Option<PathBuf>) -> Result<(Config, PathBuf), Box<dyn Error>> {
    // ── 1. CLI override ───────────────────────────────────────────────────
    if let Some(path) = cli_path {
        if path.exists() {
            let contents = fs::read_to_string(&path)?;
            let mut config: Config = toml::from_str(&contents)?;

            let themes_dir = path.parent().unwrap_or(&path).join("themes");
            fs::create_dir_all(&themes_dir)?;
            write_popular_themes(&themes_dir)?;

            let theme_path = themes_dir.join(format!("{}.theme", config.theme_name));
            if theme_path.exists() {
                let theme_contents = fs::read_to_string(&theme_path)?;
                if let Ok(theme) = toml::from_str::<ThemeConfig>(&theme_contents) {
                    config.theme = theme;
                }
            } else {
                let legacy_theme_path = path.with_file_name("theme.toml");
                if legacy_theme_path.exists() {
                    let _ = fs::copy(&legacy_theme_path, themes_dir.join("default.theme"));
                    let _ = fs::remove_file(&legacy_theme_path);
                }

                let theme_serialized = toml::to_string_pretty(&config.theme)?;
                fs::write(&theme_path, theme_serialized)?;
            }

            return Ok((config, path));
        }
        let fallback_theme = default_theme();
        let fallback_theme_name = default_theme_name();

        let themes_dir = path.parent().unwrap_or(&path).join("themes");
        fs::create_dir_all(&themes_dir)?;
        write_popular_themes(&themes_dir)?;
        let theme_path = themes_dir.join(format!("{}.theme", fallback_theme_name));
        let theme_serialized = toml::to_string_pretty(&fallback_theme)?;
        fs::write(&theme_path, theme_serialized)?;

        return Ok((
            Config {
                items: vec![],
                poll_interval_ms: default_poll_interval_ms(),
                max_commits: default_max_commits(),
                graph_max_commits: default_graph_max_commits(),
                detail_cache_ttl_secs: default_detail_cache_ttl_secs(),
                tab_ttl_secs: default_tab_ttl_secs(),
                page_size: default_page_size(),
                sort_by: default_sort_by(),
                visits: default_visits(),
                labels: std::collections::HashMap::new(),
                sort_reverse: false,
                pinned: std::collections::HashSet::new(),
                theme_name: fallback_theme_name,
                theme: fallback_theme,
                fzf: default_fzf(),
                git_app: default_git_app(),
                compatibility_mode: true,
                resync_on_tab_change: false,
                enable_commit_signatures: false,
            },
            path,
        ));
    }

    // ── Always ensure ~/.gitwig/ exists ───────────────────────────────────
    let gitwig_dir = home_gitwig_dir();
    fs::create_dir_all(&gitwig_dir)?;
    let canonical = gitwig_dir.join("config.toml");
    let themes_dir = gitwig_dir.join("themes");
    fs::create_dir_all(&themes_dir)?;
    write_popular_themes(&themes_dir)?;

    // ── 2. Canonical file already present ─────────────────────────────────
    if canonical.exists() {
        let contents = fs::read_to_string(&canonical)?;
        let mut config: Config = toml::from_str(&contents)?;

        let theme_path = themes_dir.join(format!("{}.theme", config.theme_name));
        if theme_path.exists() {
            let theme_contents = fs::read_to_string(&theme_path)?;
            let theme: ThemeConfig = toml::from_str(&theme_contents)?;
            config.theme = theme;
        } else {
            let legacy_theme_path = gitwig_dir.join("theme.toml");
            if legacy_theme_path.exists() {
                let _ = fs::copy(&legacy_theme_path, themes_dir.join("default.theme"));
                let _ = fs::remove_file(&legacy_theme_path);
            }

            let theme_serialized = toml::to_string_pretty(&config.theme)?;
            fs::write(&theme_path, theme_serialized)?;
        }

        return Ok((config, canonical));
    }

    // ── 3. First run: migrate an existing config into ~/.gitwig/ ──────────
    if let Some(source) = find_legacy_config() {
        fs::copy(&source, &canonical)?;
        let contents = fs::read_to_string(&canonical)?;
        let mut config: Config = toml::from_str(&contents)?;

        let theme_path = themes_dir.join(format!("{}.theme", config.theme_name));
        if theme_path.exists() {
            let theme_contents = fs::read_to_string(&theme_path)?;
            let theme: ThemeConfig = toml::from_str(&theme_contents)?;
            config.theme = theme;
        } else {
            let legacy_theme_path = gitwig_dir.join("theme.toml");
            if legacy_theme_path.exists() {
                let _ = fs::copy(&legacy_theme_path, themes_dir.join("default.theme"));
                let _ = fs::remove_file(&legacy_theme_path);
            }

            let theme_serialized = toml::to_string_pretty(&config.theme)?;
            fs::write(&theme_path, theme_serialized)?;
        }

        return Ok((config, canonical));
    }

    // ── 4. No config anywhere: write a default and use it ─────────────────
    let fallback = Config {
        items: vec![
            "Nice job. You forgot the config, genius.".to_string(),
            "Still looking... it's not here either.".to_string(),
        ],
        poll_interval_ms: default_poll_interval_ms(),
        max_commits: default_max_commits(),
        graph_max_commits: default_graph_max_commits(),
        detail_cache_ttl_secs: default_detail_cache_ttl_secs(),
        tab_ttl_secs: default_tab_ttl_secs(),
        page_size: default_page_size(),
        sort_by: default_sort_by(),
        visits: default_visits(),
        labels: std::collections::HashMap::new(),
        sort_reverse: false,
        pinned: std::collections::HashSet::new(),
        theme_name: default_theme_name(),
        theme: default_theme(),
        fzf: default_fzf(),
        git_app: default_git_app(),
        compatibility_mode: true,
        resync_on_tab_change: false,
        enable_commit_signatures: false,
    };
    save_config(&fallback, &canonical)?;

    let theme_path = themes_dir.join(format!("{}.theme", fallback.theme_name));
    let theme_serialized = toml::to_string_pretty(&fallback.theme)?;
    fs::write(&theme_path, theme_serialized)?;

    Ok((fallback, canonical))
}

/// Writes the popular themes to the themes directory if they don't already exist.
fn write_popular_themes(themes_dir: &Path) -> Result<(), Box<dyn Error>> {
    let popular_themes = [
        (
            "dracula",
            r#"accent = "lightmagenta"
warning = "lightyellow"
danger = "lightred"
success = "lightgreen"
border_type = "rounded"
"#,
        ),
        (
            "forest",
            r#"accent = "lightgreen"
warning = "yellow"
danger = "lightred"
success = "green"
border_type = "rounded"
"#,
        ),
        (
            "gruvbox",
            r#"accent = "yellow"
warning = "lightyellow"
danger = "red"
success = "green"
border_type = "plain"
"#,
        ),
        (
            "monokai",
            r#"accent = "lightyellow"
warning = "yellow"
danger = "red"
success = "green"
border_type = "rounded"
"#,
        ),
        (
            "nord",
            r#"accent = "lightblue"
warning = "yellow"
danger = "red"
success = "green"
border_type = "rounded"
"#,
        ),
        (
            "oceanic",
            r#"accent = "lightcyan"
warning = "yellow"
danger = "red"
success = "lightgreen"
border_type = "rounded"
"#,
        ),
    ];

    for (name, content) in popular_themes {
        let theme_path = themes_dir.join(format!("{}.theme", name));
        if !theme_path.exists() {
            fs::write(theme_path, content)?;
        }
    }
    Ok(())
}

/// Searches for a pre-existing config at legacy / local locations.
/// Returns the first path that exists, or `None`.
fn find_legacy_config() -> Option<PathBuf> {
    // Local project config relative to CWD.
    let local = PathBuf::from("config/config.toml");
    if local.exists() {
        return Some(local);
    }
    // Local project config relative to the executable directory.
    if let Ok(exe) = std::env::current_exe() {
        if let Some(dir) = exe.parent() {
            let p = dir.join("config/config.toml");
            if p.exists() {
                return Some(p);
            }
        }
    }
    // Legacy Twig home location: ~/.twig/config.toml.
    if let Some(home) = dirs::home_dir() {
        let p = home.join(".twig/config.toml");
        if p.exists() {
            return Some(p);
        }
    }
    // New Gitwig XDG config location: ~/.config/gitwig/config.toml.
    if let Some(p) = dirs::config_dir().map(|d| d.join("gitwig/config.toml")) {
        if p.exists() {
            return Some(p);
        }
    }
    // Legacy Twig XDG config location: ~/.config/twig/config.toml.
    if let Some(p) = dirs::config_dir().map(|d| d.join("twig/config.toml")) {
        if p.exists() {
            return Some(p);
        }
    }
    None
}

/// Serializes the config back to TOML and writes it to `path`, creating any
/// missing parent directories first.
pub fn save_config(config: &Config, path: &Path) -> Result<(), Box<dyn Error>> {
    if let Some(parent) = path.parent() {
        if !parent.as_os_str().is_empty() {
            fs::create_dir_all(parent)?;
        }
    }
    let serialized = toml::to_string_pretty(config)?;
    fs::write(path, serialized)?;
    Ok(())
}

#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::panic)]
mod tests {
    use super::*;

    #[test]
    fn test_theme_separation_load_and_save() {
        let unique_id =
            std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos();
        let test_dir = std::env::temp_dir().join(format!("gitwig_test_theme_{}", unique_id));
        fs::create_dir_all(&test_dir).unwrap();
        let config_path = test_dir.join("config.toml");
        let themes_dir = test_dir.join("themes");
        let theme_path = themes_dir.join("default.theme");

        // 1. Initial load when files do not exist (should write themes/default.theme but not config.toml in CLI mode)
        let (config, path) = load_config(Some(config_path.clone())).unwrap();
        assert_eq!(path, config_path);
        assert!(!config_path.exists());
        assert!(theme_path.exists());

        // Verify config.theme is default
        assert_eq!(config.theme.accent, "cyan");
        assert_eq!(config.theme_name, "default");

        // Verify default.theme contains "accent = "cyan""
        let theme_content = fs::read_to_string(&theme_path).unwrap();
        assert!(theme_content.contains("accent = \"cyan\""));

        // Save config
        save_config(&config, &config_path).unwrap();
        assert!(config_path.exists());

        // Verify config.toml does NOT contain the [theme] section but has theme name string
        let config_content = fs::read_to_string(&config_path).unwrap();
        assert!(!config_content.contains("[theme]"));
        assert!(config_content.contains("theme = \"default\""));

        // 2. Modify default.theme and reload
        let custom_theme = r#"accent = "magenta"
warning = "yellow"
danger = "red"
success = "green"
border_type = "double"
"#;
        fs::write(&theme_path, custom_theme).unwrap();
        let (loaded_config, _) = load_config(Some(config_path.clone())).unwrap();
        assert_eq!(loaded_config.theme.accent, "magenta");
        assert_eq!(loaded_config.theme.border_type, "double");

        // 3. Save config and verify config.toml still has no [theme] section but has theme name string
        save_config(&loaded_config, &config_path).unwrap();
        let config_content_after_save = fs::read_to_string(&config_path).unwrap();
        assert!(!config_content_after_save.contains("[theme]"));
        assert!(config_content_after_save.contains("theme = \"default\""));

        // Clean up
        let _ = fs::remove_dir_all(&test_dir);
    }

    #[test]
    fn test_write_popular_themes_creates_files() {
        let unique_id =
            std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos();
        let test_dir =
            std::env::temp_dir().join(format!("gitwig_test_popular_themes_{}", unique_id));
        fs::create_dir_all(&test_dir).unwrap();

        write_popular_themes(&test_dir).unwrap();

        // Verify that Dracula, Forest, Gruvbox, Monokai, Nord, and Oceanic files are written
        assert!(test_dir.join("dracula.theme").exists());
        assert!(test_dir.join("forest.theme").exists());
        assert!(test_dir.join("gruvbox.theme").exists());
        assert!(test_dir.join("monokai.theme").exists());
        assert!(test_dir.join("nord.theme").exists());
        assert!(test_dir.join("oceanic.theme").exists());

        // Read one theme to verify content
        let contents = fs::read_to_string(test_dir.join("oceanic.theme")).unwrap();
        assert!(contents.contains("accent = \"lightcyan\""));

        let _ = fs::remove_dir_all(&test_dir);
    }
}