gitwig 2.6.7

a rust based tui, an alternative to sourcetree and gitui
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
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
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
//! Configuration loader, migrator, and settings persistence for TOML configs.

use std::error::Error;
use std::fs;
use std::path::{Path, PathBuf};

use serde::{Deserialize, Serialize};

use crate::state::{AppState, load_state, save_state};

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

impl SortOrder {
    /// The next mode in the `o` cycle: Custom → Alphabetical → Recent Visit →
    /// Latest Changes → Custom.
    pub fn next(self) -> Self {
        match self {
            SortOrder::Custom => SortOrder::Alphabetical,
            SortOrder::Alphabetical => SortOrder::RecentVisit,
            SortOrder::RecentVisit => SortOrder::LatestChanges,
            SortOrder::LatestChanges => SortOrder::Custom,
        }
    }

    /// The previous mode in the cycle (the inverse of [`SortOrder::next`]).
    pub fn prev(self) -> Self {
        match self {
            SortOrder::Custom => SortOrder::LatestChanges,
            SortOrder::Alphabetical => SortOrder::Custom,
            SortOrder::RecentVisit => SortOrder::Alphabetical,
            SortOrder::LatestChanges => SortOrder::RecentVisit,
        }
    }

    /// Human-readable name used by the sort caption and settings rows.
    pub fn display_name(self) -> &'static str {
        match self {
            SortOrder::Custom => "Custom",
            SortOrder::Alphabetical => "Alphabetical",
            SortOrder::RecentVisit => "Recent Visit",
            SortOrder::LatestChanges => "Latest Changes",
        }
    }
}

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

/// 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
}

/// How long a background `git fetch` may run before it is cancelled (seconds).
///
/// A remote that accepts the TCP connection but never replies — a firewall
/// blackhole, a dead VPN route — would otherwise leave the card spinning forever
/// with no way to clear it. `0` disables the limit.
fn default_fetch_timeout_secs() -> u64 {
    30
}

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()
}

/// `BatchMode=yes` is load-bearing: without it, ssh bypasses the captured
/// stdio pipes and prompts for passphrases or confirmations directly on
/// `/dev/tty`, painting raw text over the TUI's alternate screen. With it,
/// ssh fails immediately and the error is captured, classified, and shown
/// through the normal error popup instead.
pub fn ssh_command_val() -> &'static str {
    if std::env::var("GITWIG_SSH_STRICT").map(|v| v == "1").unwrap_or(false) {
        "ssh -o BatchMode=yes -o StrictHostKeyChecking=yes"
    } else {
        "ssh -o BatchMode=yes -o StrictHostKeyChecking=accept-new"
    }
}

#[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, Default)]
pub struct RepoConfig {
    #[serde(default)]
    pub theme: Option<String>,
    #[serde(default)]
    pub page_size: Option<usize>,
    #[serde(default)]
    pub max_commits: Option<usize>,
    #[serde(default)]
    pub resync_on_tab_change: Option<bool>,
    /// Per-repository auto-fetch cadence in minutes. `None` inherits the global
    /// `auto_fetch_interval_mins`; `Some(0)` disables auto-fetch for this repo only.
    #[serde(default)]
    pub auto_fetch_interval_mins: Option<u64>,
    #[serde(default)]
    pub editor: Option<String>,
    #[serde(default)]
    pub note: Option<String>,
}

/// Settings that can be attached to a label and shared by every repository
/// carrying that label. This is the *settings* subset of [`RepoConfig`] — it
/// deliberately excludes per-repo data like `note`, which describes one
/// repository rather than a group. (Commit-message history, which older
/// versions also kept here, now lives in `state.toml`; see `crate::state`.)
///
/// Resolution is three-tier: a per-repo override in [`RepoConfig`] wins first,
/// then the first of the repo's labels (in stored order) that defines the
/// setting, then the global [`Config`] default.
#[derive(Debug, Deserialize, Serialize, Clone, PartialEq, Eq, Default)]
pub struct LabelConfig {
    #[serde(default)]
    pub theme: Option<String>,
    #[serde(default)]
    pub page_size: Option<usize>,
    #[serde(default)]
    pub max_commits: Option<usize>,
    #[serde(default)]
    pub resync_on_tab_change: Option<bool>,
    /// Auto-fetch cadence in minutes for repos with this label. `None` inherits
    /// the global `auto_fetch_interval_mins`; `Some(0)` disables auto-fetch for
    /// the whole group.
    #[serde(default)]
    pub auto_fetch_interval_mins: Option<u64>,
    #[serde(default)]
    pub editor: Option<String>,
    /// Sort mode for the home list while this label's filter ("project view")
    /// is active. `None` inherits the global `sort_by`. Unlike the other rows
    /// this is a property of the label view, not of the repositories in it,
    /// so it has no per-repo counterpart.
    #[serde(default)]
    pub sort_by: Option<SortOrder>,
    /// Sort direction for the home list while this label's filter is active.
    /// `None` inherits the global `sort_reverse`.
    #[serde(default)]
    pub sort_reverse: Option<bool>,
    /// Home list layout (cards, compact rows or the tile grid) while this
    /// label's filter is active. `None` inherits the global `view_mode`. Like
    /// the sort, a property of the label view with no per-repo counterpart.
    #[serde(default)]
    pub view_mode: Option<HomeViewMode>,
}

#[derive(Debug, Deserialize, Serialize, Clone, PartialEq, Eq)]
pub struct ScanConfig {
    #[serde(default = "default_scan_max_depth")]
    pub max_depth: usize,
    #[serde(default = "default_scan_excludes")]
    pub excludes: Vec<String>,
    #[serde(default = "default_scan_start_dir")]
    pub start_dir: String,
    #[serde(default = "default_scan_git_only")]
    pub git_only: bool,
}

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

impl Default for ScanConfig {
    fn default() -> Self {
        default_scan()
    }
}

impl Default for Config {
    fn default() -> Self {
        Config {
            items: Vec::new(),
            poll_interval_ms: default_poll_interval_ms(),
            fetch_timeout_secs: default_fetch_timeout_secs(),
            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(),
            labels: std::collections::HashMap::new(),
            repo_configs: std::collections::HashMap::new(),
            label_configs: std::collections::HashMap::new(),
            sort_reverse: false,
            pinned: std::collections::HashSet::new(),
            starred: std::collections::HashSet::new(),
            watch_dirs: Vec::new(),
            theme: ThemeConfig::default(),
            theme_name: default_theme_name(),
            scan: default_scan(),
            git_app: default_git_app(),
            compatibility_mode: default_compatibility_mode(),
            resync_on_tab_change: default_resync_on_tab_change(),
            prompt_cwd_repo: default_prompt_cwd_repo(),
            enable_commit_signatures: default_enable_commit_signatures(),
            ssh_strict_host_checking: default_ssh_strict_host_checking(),
            editor: default_editor(),
            compact_view: false,
            view_mode: HomeViewMode::Normal,
            tile_columns: 0,
            show_grouping: true,
            auto_fetch_interval_mins: default_auto_fetch_interval_mins(),
            show_system_stats: default_show_system_stats(),
            show_separators: default_show_separators(),
            stale_threshold_months: default_stale_threshold_months(),
            show_stale_projects: default_show_stale_projects(),
            enable_watch_dirs: default_enable_watch_dirs(),
        }
    }
}

fn default_ssh_strict_host_checking() -> bool {
    false
}

fn default_editor() -> String {
    std::env::var("EDITOR").or_else(|_| std::env::var("VISUAL")).unwrap_or_else(|_| {
        if cfg!(target_os = "windows") { "notepad".to_string() } else { "vim".to_string() }
    })
}

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_scan_max_depth() -> usize {
    6
}
pub fn default_scan_excludes() -> Vec<String> {
    vec![
        "node_modules".to_string(),
        "target".to_string(),
        "venv".to_string(),
        ".venv".to_string(),
        "checkout".to_string(),
    ]
}

fn default_scan_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_scan_git_only() -> bool {
    true
}
fn default_compatibility_mode() -> bool {
    true
}
fn default_show_grouping() -> bool {
    true
}
fn default_resync_on_tab_change() -> bool {
    false
}
fn default_enable_commit_signatures() -> bool {
    false
}
fn default_auto_fetch_interval_mins() -> u64 {
    10
}
fn default_show_system_stats() -> bool {
    false
}
fn default_show_separators() -> bool {
    true
}
fn default_stale_threshold_months() -> u32 {
    1
}
fn default_show_stale_projects() -> bool {
    true
}
fn default_enable_watch_dirs() -> bool {
    true
}
fn default_prompt_cwd_repo() -> bool {
    true
}

fn default_scan() -> ScanConfig {
    ScanConfig {
        max_depth: default_scan_max_depth(),
        excludes: default_scan_excludes(),
        start_dir: default_scan_start_dir(),
        git_only: default_scan_git_only(),
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize, Default)]
#[serde(rename_all = "snake_case")]
pub enum HomeViewMode {
    #[default]
    Normal,
    Compact,
    Tile,
}

impl HomeViewMode {
    /// The layout the `v` key moves to: cards → compact → tile → cards.
    pub fn next(self) -> Self {
        match self {
            HomeViewMode::Normal => HomeViewMode::Compact,
            HomeViewMode::Compact => HomeViewMode::Tile,
            HomeViewMode::Tile => HomeViewMode::Normal,
        }
    }

    /// The layout before this one in the `v` cycle.
    pub fn prev(self) -> Self {
        match self {
            HomeViewMode::Normal => HomeViewMode::Tile,
            HomeViewMode::Compact => HomeViewMode::Normal,
            HomeViewMode::Tile => HomeViewMode::Compact,
        }
    }

    pub fn display_name(self) -> &'static str {
        match self {
            HomeViewMode::Normal => "Normal",
            HomeViewMode::Compact => "Compact",
            HomeViewMode::Tile => "Tile",
        }
    }
}

/// 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;
    /// the Settings editor refuses anything below 10.
    #[serde(default = "default_poll_interval_ms")]
    pub poll_interval_ms: u64,
    /// Seconds a background `git fetch` may run before it is cancelled (default: 30).
    /// `0` disables the limit. Raise it for slow remotes on high-latency links.
    #[serde(default = "default_fetch_timeout_secs")]
    pub fetch_timeout_secs: u64,
    /// Maximum commits to load in workspace view. Default: 500; 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 paths to their labels.
    #[serde(default)]
    pub labels: std::collections::HashMap<String, Vec<String>>,
    /// Repository specific configurations.
    #[serde(default)]
    pub repo_configs: std::collections::HashMap<String, RepoConfig>,
    /// Per-label settings shared by every repository carrying that label.
    /// Resolved between the per-repo override and the global default.
    #[serde(default)]
    pub label_configs: std::collections::HashMap<String, LabelConfig>,
    /// Whether sorting should be reversed.
    #[serde(default)]
    pub sort_reverse: bool,
    /// List of pinned repository paths.
    #[serde(default)]
    pub pinned: std::collections::HashSet<String>,
    /// List of starred repository paths.
    #[serde(default)]
    pub starred: std::collections::HashSet<String>,
    /// Directories to watch for automatic workspace syncing.
    #[serde(default)]
    pub watch_dirs: Vec<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 repository discovery via scanning.
    #[serde(alias = "fzf", rename = "scan", default = "default_scan")]
    pub scan: ScanConfig,
    /// 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 offer to track the repository Gitwig was launched from, when
    /// the working directory sits inside a repo that is not on the list yet.
    #[serde(default = "default_prompt_cwd_repo")]
    pub prompt_cwd_repo: 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,
    /// Whether to enforce strict SSH host key checking (StrictHostKeyChecking=yes)
    #[serde(default = "default_ssh_strict_host_checking")]
    pub ssh_strict_host_checking: bool,
    /// Custom terminal editor to open files with.
    #[serde(default = "default_editor")]
    pub editor: String,
    /// Whether to show the compact (1-row) list on the home page.
    #[serde(default)]
    pub compact_view: bool,
    /// The view mode to use for the home page list.
    #[serde(default)]
    pub view_mode: HomeViewMode,
    /// Number of columns in tile mode. 0 means auto-calculate.
    #[serde(default)]
    pub tile_columns: usize,
    /// Whether to enable repository grouping on the home page.
    #[serde(default = "default_show_grouping")]
    pub show_grouping: bool,
    /// Time interval in minutes to automatically run git fetch in the background for all repositories. Set to 0 to disable.
    #[serde(default = "default_auto_fetch_interval_mins")]
    pub auto_fetch_interval_mins: u64,
    /// Whether to show current CPU & Memory stats in the status bar at the bottom.
    #[serde(default = "default_show_system_stats")]
    pub show_system_stats: bool,
    /// Whether to draw the home page's separator rules: the one between the
    /// summary bar and the quick-label chips, the dashes of the sort rule
    /// (its caption stays), and the one under the last pinned repository.
    #[serde(default = "default_show_separators")]
    pub show_separators: bool,
    /// Number of months inactive to be considered stale.
    #[serde(default = "default_stale_threshold_months")]
    pub stale_threshold_months: u32,
    /// Hide stale projects if disabled.
    #[serde(default = "default_show_stale_projects")]
    pub show_stale_projects: bool,
    /// Whether the Watch Directories auto-discovery feature is enabled.
    #[serde(default = "default_enable_watch_dirs")]
    pub enable_watch_dirs: 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" => "*",
                "rule" => "-",
                "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" => "●",
                "rule" => "┄",
                "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")
}

fn handle_parse_error(path: &Path, _error: Box<dyn Error>) -> (Config, Option<String>) {
    let ts = std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map(|d| d.as_secs())
        .unwrap_or(0);
    let corrupt_path = path.with_extension(format!("toml.corrupt-{}", ts));
    let rename_result = fs::rename(path, &corrupt_path);

    let fallback = Config {
        items: vec![],
        poll_interval_ms: default_poll_interval_ms(),
        fetch_timeout_secs: default_fetch_timeout_secs(),
        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(),
        labels: std::collections::HashMap::new(),
        repo_configs: std::collections::HashMap::new(),
        label_configs: std::collections::HashMap::new(),
        sort_reverse: false,
        pinned: std::collections::HashSet::new(),
        starred: std::collections::HashSet::new(),
        watch_dirs: vec![],
        theme_name: default_theme_name(),
        theme: default_theme(),
        scan: default_scan(),
        git_app: default_git_app(),
        compatibility_mode: true,
        resync_on_tab_change: false,
        enable_commit_signatures: false,
        ssh_strict_host_checking: false,
        editor: default_editor(),
        compact_view: false,
        view_mode: HomeViewMode::Normal,
        tile_columns: 0,
        show_grouping: true,
        auto_fetch_interval_mins: default_auto_fetch_interval_mins(),
        show_system_stats: default_show_system_stats(),
        show_separators: default_show_separators(),
        stale_threshold_months: default_stale_threshold_months(),
        show_stale_projects: default_show_stale_projects(),
        prompt_cwd_repo: default_prompt_cwd_repo(),
        enable_watch_dirs: default_enable_watch_dirs(),
    };

    // Attempt to save the fallback back to the original path.
    let _ = save_config(&fallback, path);

    let msg = match rename_result {
        Ok(_) => format!(
            "Config corrupt! Moved to {} and reset to defaults",
            corrupt_path.file_name().unwrap_or_default().to_string_lossy()
        ),
        Err(e) => format!("Config corrupt! Reset to defaults (failed to rename: {})", e),
    };
    (fallback, Some(msg))
}

/// Parses `path` into a [`Config`]. Usage state that older versions kept in
/// `config.toml` (`visits`, `label_slots`, `active_label_filter`, and each
/// repo's `commit_history`) is lifted out and returned separately so
/// `load_config` can fold it into `state.toml`.
fn load_and_parse_config(path: &Path) -> (Config, Option<AppState>, Option<String>) {
    let parsed = fs::read_to_string(path).map_err(|e| e.into()).and_then(|contents| {
        toml::from_str::<toml::Table>(&contents).map_err(|e| e.into()).and_then(|mut table| {
            let legacy = AppState::take_legacy(&mut table);
            toml::Value::Table(table)
                .try_into::<Config>()
                .map(|config| (config, legacy))
                .map_err(|e| e.into())
        })
    });
    match parsed {
        Ok((config, legacy)) => {
            let (config, warning) = sanitize_config(config);
            (config, legacy, warning)
        }
        Err(err) => {
            let (config, warning) = handle_parse_error(path, err);
            (config, None, warning)
        }
    }
}

/// Applies the one-off migrations and validations a freshly parsed config needs.
fn sanitize_config(mut config: Config) -> (Config, Option<String>) {
    if config.compact_view && config.view_mode == HomeViewMode::Normal {
        config.view_mode = HomeViewMode::Compact;
        config.compact_view = false;
    }

    if config.scan.excludes.is_empty() {
        config.scan.excludes = default_scan_excludes();
    } else if config.scan.excludes.contains(&"target".to_string())
        && !config.scan.excludes.contains(&"checkout".to_string())
    {
        config.scan.excludes.push("checkout".to_string());
    }

    let allowed = ["git", "gitui", "lazygit"];
    if !allowed.contains(&config.git_app.as_str()) {
        let old_val = config.git_app.clone();
        config.git_app = "gitui".to_string();
        let warning = format!("Invalid preferred Git client '{}' reset to 'gitui'", old_val);
        (config, Some(warning))
    } else {
        (config, None)
    }
}

/// 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.
///
/// Whichever file the config came from, the usage state is read from the
/// `state.toml` beside it. State keys still found inside `config.toml`
/// (written by older versions) are moved across: merged into `state.toml`
/// without overriding what it already holds, and dropped from `config.toml`
/// by rewriting it.
///
/// # Returns
/// `Ok((Config, AppState, PathBuf, Option<String>))` — the parsed config, the
/// usage state, the config's write-back path, and an optional recovery warning.
pub fn load_config(cli_path: Option<PathBuf>) -> Result<LoadedConfig, Box<dyn Error>> {
    let (config, legacy, path, warning) = load_config_file(cli_path)?;
    let state_path = AppState::path_for(&path);
    let (mut state, state_warning) = load_state(&state_path);

    if let Some(legacy) = legacy {
        state.absorb(legacy);
        // Move the keys across for good: state.toml first, then a clean
        // config.toml. A failure here is not fatal — the next run retries.
        if save_state(&state, &state_path).is_ok() {
            let _ = save_config(&config, &path);
        }
    }

    let warning = match (warning, state_warning) {
        (Some(a), Some(b)) => Some(format!("{}; {}", a, b)),
        (a, b) => a.or(b),
    };
    Ok((config, state, path, warning))
}

/// What [`load_config`] hands back: the config, the usage state, the config's
/// write-back path, and an optional recovery warning for the status bar.
pub type LoadedConfig = (Config, AppState, PathBuf, Option<String>);

/// What [`load_config_file`] hands back: the config, any legacy usage state
/// found inside the file, the config's write-back path, and a recovery warning.
type LoadedConfigFile = (Config, Option<AppState>, PathBuf, Option<String>);

/// The config-file half of [`load_config`]: finds, migrates and parses the
/// config, returning any legacy usage state found inside it alongside.
fn load_config_file(cli_path: Option<PathBuf>) -> Result<LoadedConfigFile, Box<dyn Error>> {
    // ── 1. CLI override ───────────────────────────────────────────────────
    if let Some(path) = cli_path {
        if path.exists() {
            let (mut config, legacy, warning) = load_and_parse_config(&path);

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

            let theme_path = themes_dir.join(format!("{}.theme", config.theme_name));
            if theme_path.exists() {
                if let Ok(theme_contents) = fs::read_to_string(&theme_path) {
                    if let Ok(theme) = toml::from_str::<ThemeConfig>(&theme_contents) {
                        config.theme = theme;
                    } else {
                        config.theme = default_theme();
                    }
                } else {
                    config.theme = default_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);
                }

                if let Ok(theme_serialized) = toml::to_string_pretty(&config.theme) {
                    let _ = fs::write(&theme_path, theme_serialized);
                }
            }

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

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

        return Ok((
            Config {
                items: vec![],
                poll_interval_ms: default_poll_interval_ms(),
                fetch_timeout_secs: default_fetch_timeout_secs(),
                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(),
                labels: std::collections::HashMap::new(),
                repo_configs: std::collections::HashMap::new(),
                label_configs: std::collections::HashMap::new(),
                sort_reverse: false,
                pinned: std::collections::HashSet::new(),
                starred: std::collections::HashSet::new(),
                watch_dirs: vec![],
                theme_name: fallback_theme_name,
                theme: fallback_theme,
                scan: default_scan(),
                git_app: default_git_app(),
                compatibility_mode: true,
                resync_on_tab_change: false,
                enable_commit_signatures: false,
                ssh_strict_host_checking: false,
                editor: default_editor(),
                compact_view: false,
                view_mode: HomeViewMode::Normal,
                tile_columns: 0,
                show_grouping: true,
                auto_fetch_interval_mins: default_auto_fetch_interval_mins(),
                show_system_stats: default_show_system_stats(),
                show_separators: default_show_separators(),
                stale_threshold_months: default_stale_threshold_months(),
                show_stale_projects: default_show_stale_projects(),
                prompt_cwd_repo: default_prompt_cwd_repo(),
                enable_watch_dirs: default_enable_watch_dirs(),
            },
            None,
            path,
            None,
        ));
    }

    // ── Always ensure ~/.gitwig/ exists ───────────────────────────────────
    let gitwig_dir = home_gitwig_dir();
    let _ = fs::create_dir_all(&gitwig_dir);
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        if let Ok(meta) = fs::metadata(&gitwig_dir) {
            let mut perms = meta.permissions();
            perms.set_mode(0o700);
            let _ = fs::set_permissions(&gitwig_dir, perms);
        }
    }
    let canonical = gitwig_dir.join("config.toml");
    let themes_dir = gitwig_dir.join("themes");
    let _ = fs::create_dir_all(&themes_dir);
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        if let Ok(meta) = fs::metadata(&themes_dir) {
            let mut perms = meta.permissions();
            perms.set_mode(0o700);
            let _ = fs::set_permissions(&themes_dir, perms);
        }
    }
    let _ = write_popular_themes(&themes_dir);

    // ── 2. Canonical file already present ─────────────────────────────────
    if canonical.exists() {
        let (mut config, legacy, warning) = load_and_parse_config(&canonical);

        let theme_path = themes_dir.join(format!("{}.theme", config.theme_name));
        if theme_path.exists() {
            if let Ok(theme_contents) = fs::read_to_string(&theme_path) {
                if let Ok(theme) = toml::from_str::<ThemeConfig>(&theme_contents) {
                    config.theme = theme;
                } else {
                    config.theme = default_theme();
                }
            } else {
                config.theme = default_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);
            }

            if let Ok(theme_serialized) = toml::to_string_pretty(&config.theme) {
                let _ = fs::write(&theme_path, theme_serialized);
            }
        }

        return Ok((config, legacy, canonical, warning));
    }

    // ── 3. First run: migrate an existing config into ~/.gitwig/ ──────────
    if let Some(source) = find_legacy_config() {
        fs::copy(&source, &canonical)?;
        let (mut config, legacy, warning) = load_and_parse_config(&canonical);

        let theme_path = themes_dir.join(format!("{}.theme", config.theme_name));
        if theme_path.exists() {
            if let Ok(theme_contents) = fs::read_to_string(&theme_path) {
                if let Ok(theme) = toml::from_str::<ThemeConfig>(&theme_contents) {
                    config.theme = theme;
                } else {
                    config.theme = default_theme();
                }
            } else {
                config.theme = default_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);
            }

            if let Ok(theme_serialized) = toml::to_string_pretty(&config.theme) {
                let _ = fs::write(&theme_path, theme_serialized);
            }
        }

        return Ok((config, legacy, canonical, warning));
    }

    // ── 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(),
        fetch_timeout_secs: default_fetch_timeout_secs(),
        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(),
        labels: std::collections::HashMap::new(),
        repo_configs: std::collections::HashMap::new(),
        label_configs: std::collections::HashMap::new(),
        sort_reverse: false,
        pinned: std::collections::HashSet::new(),
        starred: std::collections::HashSet::new(),
        watch_dirs: vec![],
        theme_name: default_theme_name(),
        theme: default_theme(),
        scan: default_scan(),
        git_app: default_git_app(),
        compatibility_mode: true,
        resync_on_tab_change: false,
        enable_commit_signatures: false,
        ssh_strict_host_checking: false,
        editor: default_editor(),
        compact_view: false,
        view_mode: HomeViewMode::Normal,
        tile_columns: 0,
        show_grouping: true,
        auto_fetch_interval_mins: default_auto_fetch_interval_mins(),
        show_system_stats: default_show_system_stats(),
        show_separators: default_show_separators(),
        stale_threshold_months: default_stale_threshold_months(),
        show_stale_projects: default_show_stale_projects(),
        prompt_cwd_repo: default_prompt_cwd_repo(),
        enable_watch_dirs: default_enable_watch_dirs(),
    };
    save_config(&fallback, &canonical)?;

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

    Ok((fallback, None, canonical, None))
}

/// 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 = [
        (
            "catppuccin",
            r#"accent = "lightblue"
warning = "lightyellow"
danger = "lightred"
success = "lightgreen"
border_type = "rounded"
"#,
        ),
        (
            "cyberpunk",
            r#"accent = "lightmagenta"
warning = "lightyellow"
danger = "lightred"
success = "lightcyan"
border_type = "double"
"#,
        ),
        (
            "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"
"#,
        ),
        (
            // Pulled straight from the checked-in theme file so the brand palette
            // has exactly one source of truth; see `branding/theme.json`.
            "gitwig",
            include_str!("../config/themes/gitwig.theme"),
        ),
        (
            "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"
"#,
        ),
        (
            "onedark",
            r#"accent = "blue"
warning = "yellow"
danger = "lightred"
success = "green"
border_type = "rounded"
"#,
        ),
        (
            "rosepine",
            r#"accent = "lightmagenta"
warning = "yellow"
danger = "lightred"
success = "lightcyan"
border_type = "rounded"
"#,
        ),
        (
            "solarized_dark",
            r#"accent = "cyan"
warning = "yellow"
danger = "red"
success = "green"
border_type = "rounded"
"#,
        ),
        (
            "tokyonight",
            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>> {
    let serialized = toml::to_string_pretty(config)?;
    write_toml_atomic(path, &serialized)
}

/// Writes `serialized` to `path` atomically (via a `.tmp` sibling and a
/// rename), creating any missing parent directories first and keeping both
/// the directory and the file private to the user.
pub(crate) fn write_toml_atomic(path: &Path, serialized: &str) -> Result<(), Box<dyn Error>> {
    if let Some(parent) = path.parent() {
        if !parent.as_os_str().is_empty() {
            fs::create_dir_all(parent)?;
            #[cfg(unix)]
            {
                use std::os::unix::fs::PermissionsExt;
                if let Ok(meta) = fs::metadata(parent) {
                    let mut perms = meta.permissions();
                    perms.set_mode(0o700);
                    let _ = fs::set_permissions(parent, perms);
                }
            }
        }
    }
    // Write atomically: write to a .tmp file first, then rename. The tmp name
    // is unique per process and write so two writers aiming at the same file
    // (parallel tests, two Gitwig instances) cannot rename each other's tmp
    // away mid-flight; the loser simply gets overwritten by the final rename.
    static TMP_COUNTER: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
    let tmp_path = path.with_extension(format!(
        "toml.tmp-{}-{}",
        std::process::id(),
        TMP_COUNTER.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
    ));
    if let Err(e) = fs::write(&tmp_path, serialized) {
        let _ = fs::remove_file(&tmp_path);
        return Err(e.into());
    }

    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        if let Ok(meta) = fs::metadata(&tmp_path) {
            let mut perms = meta.permissions();
            perms.set_mode(0o600);
            let _ = fs::set_permissions(&tmp_path, perms);
        }
    }

    if let Err(e) = fs::rename(&tmp_path, path) {
        let _ = fs::remove_file(&tmp_path);
        return Err(e.into());
    }
    Ok(())
}

#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::panic)]
mod tests {
    use super::*;
    use std::sync::atomic::{AtomicUsize, Ordering};

    static TEST_DIR_COUNTER: AtomicUsize = AtomicUsize::new(0);

    fn get_unique_id() -> String {
        let count = TEST_DIR_COUNTER.fetch_add(1, Ordering::SeqCst);
        let pid = std::process::id();
        let nanos =
            std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos();
        format!("{}_{}_{}", pid, nanos, count)
    }

    #[test]
    fn test_theme_separation_load_and_save() {
        let unique_id = get_unique_id();
        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 = get_unique_id();
        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, Oceanic and new popular themes are written
        assert!(test_dir.join("catppuccin.theme").exists());
        assert!(test_dir.join("cyberpunk.theme").exists());
        assert!(test_dir.join("dracula.theme").exists());
        assert!(test_dir.join("forest.theme").exists());
        assert!(test_dir.join("gitwig.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());
        assert!(test_dir.join("onedark.theme").exists());
        assert!(test_dir.join("rosepine.theme").exists());
        assert!(test_dir.join("solarized_dark.theme").exists());
        assert!(test_dir.join("tokyonight.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);
    }

    #[test]
    fn test_corrupt_config_recovery() {
        let unique_id = get_unique_id();
        let test_dir = std::env::temp_dir().join(format!("gitwig_test_corrupt_{}", unique_id));
        fs::create_dir_all(&test_dir).unwrap();
        let config_path = test_dir.join("config.toml");

        // Write a corrupt/invalid TOML file
        fs::write(&config_path, "items = [").unwrap();

        // Load config (should move to .corrupt-<ts>, create default config and return warning)
        let (config, _, path, warning) = load_config(Some(config_path.clone())).unwrap();
        assert_eq!(path, config_path);
        assert!(config_path.exists());
        assert!(warning.is_some());
        assert!(warning.unwrap().contains("Config corrupt!"));

        // Verify loaded config is default
        assert!(config.items.is_empty());

        // Verify that a corrupt backup file was created in the same directory
        let files = fs::read_dir(&test_dir).unwrap();
        let corrupt_exists = files
            .filter_map(Result::ok)
            .any(|entry| entry.file_name().to_string_lossy().contains("config.toml.corrupt-"));
        assert!(corrupt_exists);

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

    #[test]
    fn test_git_app_validation_recovery() {
        let unique_id = get_unique_id();
        let test_dir = std::env::temp_dir().join(format!("gitwig_test_git_app_{}", unique_id));
        fs::create_dir_all(&test_dir).unwrap();
        let config_path = test_dir.join("config.toml");

        let config_toml = r#"
items = []
poll_interval_ms = 1000
max_commits = 100
graph_max_commits = 100
detail_cache_ttl_secs = 60
tab_ttl_secs = 60
page_size = 50
sort_by = "alphabetical"
visits = {}
labels = {}
repo_configs = {}
sort_reverse = false
pinned = []
theme_name = "default"
scan = { excludes = [], max_depth = 5, start_dir = "~" }
git_app = "malicious_binary"
compatibility_mode = true
resync_on_tab_change = false
enable_commit_signatures = false
"#;
        fs::write(&config_path, config_toml).unwrap();

        let (config, _, path, warning) = load_config(Some(config_path.clone())).unwrap();
        assert_eq!(path, config_path);
        assert_eq!(config.git_app, "gitui");
        assert!(warning.is_some());
        assert!(warning.unwrap().contains("Invalid preferred Git client"));

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

    #[test]
    fn test_config_coverage_boost() {
        // 1. ssh_command_val
        let ssh_val = ssh_command_val();
        assert!(!ssh_val.is_empty());

        // 2. sym on configuration symbols
        let config = Config { compatibility_mode: true, ..Config::default() };
        assert_eq!(config.sym("branch"), "* ");
        let config2 = Config { compatibility_mode: false, ..Config::default() };
        assert_eq!(config2.sym("branch"), "\u{e0a0} ");

        // 3. handle_parse_error
        let unique_id = get_unique_id();
        let test_dir = std::env::temp_dir().join(format!("gitwig_test_parse_err_{}", unique_id));
        fs::create_dir_all(&test_dir).unwrap();
        let err_path = test_dir.join("config.toml");
        let (config, warning) =
            handle_parse_error(&err_path, Box::new(std::io::Error::other("mock error")));
        assert!(warning.is_some());
        assert!(config.items.is_empty());
        let _ = fs::remove_dir_all(&test_dir);

        // 4. find_legacy_config
        let _legacy = find_legacy_config();
    }

    #[test]
    fn test_state_keys_migrate_out_of_config_toml() {
        let unique_id = get_unique_id();
        let test_dir =
            std::env::temp_dir().join(format!("gitwig_test_state_migrate_{}", unique_id));
        fs::create_dir_all(&test_dir).unwrap();
        let config_path = test_dir.join("config.toml");
        let state_path = AppState::path_for(&config_path);

        // A config written by a version that still kept usage state inline.
        let legacy_config = r#"
items = ["/a", "/b"]
sort_by = "recent_visit"
active_label_filter = "work"
label_slots = ["work", "oss"]

[visits]
"/a" = 10
"/b" = 20

[labels]
"/a" = ["work"]

[repo_configs."/a"]
page_size = 5
commit_history = ["second", "first"]
"#;
        fs::write(&config_path, legacy_config).unwrap();
        assert!(!state_path.exists());

        let (config, state, path, warning) = load_config(Some(config_path.clone())).unwrap();
        assert_eq!(path, config_path);
        assert!(warning.is_none());

        // Settings survive untouched...
        assert_eq!(config.items, vec!["/a".to_string(), "/b".to_string()]);
        assert_eq!(config.sort_by, SortOrder::RecentVisit);
        assert_eq!(config.repo_configs["/a"].page_size, Some(5));
        assert_eq!(config.labels["/a"], vec!["work".to_string()]);

        // ...and the usage state comes back through `AppState`.
        assert_eq!(state.visits.get("/a"), Some(&10));
        assert_eq!(state.visits.get("/b"), Some(&20));
        assert_eq!(state.active_label_filter.as_deref(), Some("work"));
        assert_eq!(state.label_slots, vec!["work".to_string(), "oss".to_string()]);
        assert_eq!(state.commit_history_for("/a"), vec!["second".to_string(), "first".to_string()]);

        // The move is made permanent on disk: state.toml exists and config.toml
        // was rewritten without the state keys but with everything else.
        assert!(state_path.exists());
        let rewritten = fs::read_to_string(&config_path).unwrap();
        for key in ["visits", "active_label_filter", "label_slots", "commit_history"] {
            assert!(!rewritten.contains(key), "`{}` still in config.toml:\n{}", key, rewritten);
        }
        assert!(rewritten.contains("page_size = 5"), "rewritten: {}", rewritten);
        let (from_disk, _) = load_state(&state_path);
        assert_eq!(from_disk, state);

        // A second load is an ordinary run: nothing left to migrate, same result.
        let (_, state_again, _, warning) = load_config(Some(config_path.clone())).unwrap();
        assert!(warning.is_none());
        assert_eq!(state_again, state);

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

    #[test]
    fn test_state_toml_wins_over_stale_keys_left_in_config_toml() {
        let unique_id = get_unique_id();
        let test_dir = std::env::temp_dir().join(format!("gitwig_test_state_merge_{}", unique_id));
        fs::create_dir_all(&test_dir).unwrap();
        let config_path = test_dir.join("config.toml");
        let state_path = AppState::path_for(&config_path);

        fs::write(
            &config_path,
            "items = [\"/a\"]\nactive_label_filter = \"old\"\n[visits]\n\"/a\" = 1\n\"/b\" = 2\n",
        )
        .unwrap();
        let mut existing = AppState::default();
        existing.visits.insert("/a".to_string(), 99);
        existing.active_label_filter = Some("new".to_string());
        save_state(&existing, &state_path).unwrap();

        let (_, state, _, _) = load_config(Some(config_path.clone())).unwrap();
        assert_eq!(state.visits.get("/a"), Some(&99), "state.toml value kept");
        assert_eq!(state.visits.get("/b"), Some(&2), "missing entry filled from config");
        assert_eq!(state.active_label_filter.as_deref(), Some("new"));

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