cargo-port 0.2.0

A TUI for inspecting and managing Rust projects
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
#[cfg(test)]
use std::cell::RefCell;
use std::path::Path;
#[cfg(test)]
use std::path::PathBuf;
use std::sync::OnceLock;
use std::sync::RwLock;

use confique::Config as _;
use serde::Deserialize;
use serde::Serialize;
use toml::Table;
use toml::Value;

use super::constants::APP_NAME;
use super::constants::CARGO_COMMAND_NAME;
use super::constants::CLIPPY_LINT_COMMAND_NAME;
use super::constants::CONFIG_FILE;
use super::constants::DEFAULT_CLIPPY_LINT_COMMAND;
use super::constants::MIN_CPU_POLL_MS;
use crate::constants::BYTES_PER_GIB;
use crate::constants::BYTES_PER_KIB;
use crate::constants::BYTES_PER_MIB;
use crate::constants::DEFAULT_CACHE_SIZE;
use crate::project::AbsolutePath;

/// Whether non-Rust projects (git repos without `Cargo.toml`) are included in scans.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(from = "bool", into = "bool")]
pub(crate) enum NonRustInclusion {
    Include,
    #[default]
    Exclude,
}

impl From<bool> for NonRustInclusion {
    fn from(b: bool) -> Self { if b { Self::Include } else { Self::Exclude } }
}

impl From<NonRustInclusion> for bool {
    fn from(val: NonRustInclusion) -> Self { matches!(val, NonRustInclusion::Include) }
}

impl NonRustInclusion {
    pub(crate) const fn includes_non_rust(self) -> bool { matches!(self, Self::Include) }
}

/// Scroll direction for mouse wheel events.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(from = "bool", into = "bool")]
pub(crate) enum ScrollDirection {
    #[default]
    Normal,
    Inverted,
}

impl From<bool> for ScrollDirection {
    fn from(b: bool) -> Self { if b { Self::Inverted } else { Self::Normal } }
}

impl From<ScrollDirection> for bool {
    fn from(val: ScrollDirection) -> Self { matches!(val, ScrollDirection::Inverted) }
}

impl ScrollDirection {
    pub(crate) const fn is_inverted(self) -> bool { matches!(self, Self::Inverted) }
}

/// Whether newly discovered projects trigger an immediate lint run or wait
/// for a real file-system change event.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(from = "bool", into = "bool")]
pub(crate) enum DiscoveryLint {
    /// Run lints immediately when a new project appears after the initial scan.
    Immediate,
    /// Wait for an actual disk event before running lints on new projects.
    #[default]
    Deferred,
}

impl From<bool> for DiscoveryLint {
    fn from(b: bool) -> Self { if b { Self::Immediate } else { Self::Deferred } }
}

impl From<DiscoveryLint> for bool {
    fn from(val: DiscoveryLint) -> Self { matches!(val, DiscoveryLint::Immediate) }
}

impl DiscoveryLint {
    pub(crate) const fn is_immediate(self) -> bool { matches!(self, Self::Immediate) }
}

/// Whether `hjkl` should mirror arrow-key navigation in non-text panes.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(from = "bool", into = "bool")]
pub(crate) enum NavigationKeys {
    #[default]
    ArrowsOnly,
    ArrowsAndVim,
}

impl From<bool> for NavigationKeys {
    fn from(enabled: bool) -> Self {
        if enabled {
            Self::ArrowsAndVim
        } else {
            Self::ArrowsOnly
        }
    }
}

impl From<NavigationKeys> for bool {
    fn from(value: NavigationKeys) -> Self { matches!(value, NavigationKeys::ArrowsAndVim) }
}

impl NavigationKeys {
    pub(crate) const fn uses_vim(self) -> bool { matches!(self, Self::ArrowsAndVim) }
}

/// Whether scrolling past the top or bottom of a list rolls focus to the
/// adjacent pane in tab order, or stops at the edge.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(from = "bool", into = "bool")]
pub(crate) enum EdgeScroll {
    #[default]
    Stops,
    AdvancesPane,
}

impl From<bool> for EdgeScroll {
    fn from(enabled: bool) -> Self {
        if enabled {
            Self::AdvancesPane
        } else {
            Self::Stops
        }
    }
}

impl From<EdgeScroll> for bool {
    fn from(value: EdgeScroll) -> Self { matches!(value, EdgeScroll::AdvancesPane) }
}

impl EdgeScroll {
    pub(crate) const fn advances_pane(self) -> bool { matches!(self, Self::AdvancesPane) }
}

/// Whether lint status indicators render for projects.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(from = "bool", into = "bool")]
pub(crate) enum LintIndicator {
    Enabled,
    #[default]
    Disabled,
}

impl From<bool> for LintIndicator {
    fn from(enabled: bool) -> Self {
        if enabled {
            Self::Enabled
        } else {
            Self::Disabled
        }
    }
}

impl From<LintIndicator> for bool {
    fn from(value: LintIndicator) -> Self { matches!(value, LintIndicator::Enabled) }
}

impl LintIndicator {
    pub(crate) const fn is_enabled(self) -> bool { matches!(self, Self::Enabled) }
}

/// Whether the focused pane receives a background tint.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(from = "bool", into = "bool")]
pub(crate) enum FocusedPaneTint {
    #[default]
    Enabled,
    Disabled,
}

impl From<bool> for FocusedPaneTint {
    fn from(enabled: bool) -> Self {
        if enabled {
            Self::Enabled
        } else {
            Self::Disabled
        }
    }
}

impl From<FocusedPaneTint> for bool {
    fn from(value: FocusedPaneTint) -> Self { matches!(value, FocusedPaneTint::Enabled) }
}

impl FocusedPaneTint {
    pub(crate) const fn is_enabled(self) -> bool { matches!(self, Self::Enabled) }
}

/// Whether GitHub HTTP calls synthesize rate-limit responses.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(from = "bool", into = "bool")]
pub(crate) enum GitHubRateLimitMode {
    Forced,
    #[default]
    Normal,
}

impl From<bool> for GitHubRateLimitMode {
    fn from(forced: bool) -> Self { if forced { Self::Forced } else { Self::Normal } }
}

impl From<GitHubRateLimitMode> for bool {
    fn from(value: GitHubRateLimitMode) -> Self { matches!(value, GitHubRateLimitMode::Forced) }
}

impl GitHubRateLimitMode {
    pub(crate) const fn is_forced(self) -> bool { matches!(self, Self::Forced) }
}

/// Cache storage settings shared by CI and lint-history data.
#[derive(Clone, Debug, Default, PartialEq, Eq, confique::Config, Serialize)]
pub(crate) struct CacheConfig {
    /// Override the app cache root. Empty uses the system cache directory.
    #[config(default = "")]
    pub root: String,
}

/// Lint status indicator settings.
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
pub(crate) struct LintCommandConfig {
    #[serde(default)]
    pub name:    String,
    #[serde(default)]
    pub command: String,
}

#[derive(Clone, Debug, PartialEq, Eq, confique::Config, Serialize)]
pub(crate) struct LintConfig {
    /// Show a lint status indicator per project by reading cache-rooted
    /// lint JSON artifacts.
    #[config(default = false)]
    pub enabled: LintIndicator,

    /// Allow-list lint execution to projects whose display or absolute path
    /// starts with one of these prefixes. Empty means no projects are eligible.
    #[config(default = [])]
    pub include: Vec<String>,

    /// Skip lint execution for projects whose display or absolute path starts
    /// with one of these prefixes.
    #[config(default = [])]
    pub exclude: Vec<String>,

    /// Commands to run when a watched project changes. Empty falls back to the
    /// built-in clippy command.
    #[config(default = [])]
    pub commands: Vec<LintCommandConfig>,

    /// Maximum retained size for lint run artifacts. `0` and `unlimited`
    /// disable pruning.
    #[config(default = "512 MiB")]
    pub cache_size: String,

    /// Run lints immediately when a new project appears (`true`), or wait
    /// for an actual file change before linting (`false`). When `false`,
    /// startup and new-project discovery only set up file watchers — lints
    /// run only after you edit code.
    #[config(default = false)]
    pub on_discovery: DiscoveryLint,
}

impl Default for LintConfig {
    fn default() -> Self {
        Self {
            enabled:      LintIndicator::Disabled,
            include:      Vec::new(),
            exclude:      Vec::new(),
            commands:     Vec::new(),
            cache_size:   DEFAULT_CACHE_SIZE.to_string(),
            on_discovery: DiscoveryLint::Deferred,
        }
    }
}

impl LintConfig {
    pub(crate) fn resolved_commands(&self) -> Vec<LintCommandConfig> {
        let commands = normalize_lint_commands(&self.commands);
        if commands.is_empty() {
            return vec![default_clippy_lint_command()];
        }
        commands
    }

    pub(crate) fn cache_size_bytes(&self) -> Result<Option<u64>, String> {
        parse_cache_size(&self.cache_size).map(|parsed| parsed.bytes)
    }

    pub(crate) fn normalized_cache_size(&self) -> Result<String, String> {
        parse_cache_size(&self.cache_size).map(|parsed| parsed.normalized)
    }
}

pub(crate) fn default_clippy_lint_command() -> LintCommandConfig {
    LintCommandConfig {
        name:    CLIPPY_LINT_COMMAND_NAME.to_string(),
        command: DEFAULT_CLIPPY_LINT_COMMAND.to_string(),
    }
}

pub(crate) fn builtin_lint_command(name: &str) -> Option<LintCommandConfig> {
    match name.trim().to_ascii_lowercase().as_str() {
        CLIPPY_LINT_COMMAND_NAME => Some(default_clippy_lint_command()),
        _ => None,
    }
}

pub(crate) fn infer_lint_command_name(command: &str) -> String {
    let mut parts = command.split_whitespace();
    let Some(first) = parts.next() else {
        return String::new();
    };

    if first == CARGO_COMMAND_NAME {
        if let Some(second) = parts.next()
            && !second.starts_with('-')
        {
            return second.to_string();
        }
        return CARGO_COMMAND_NAME.to_string();
    }

    Path::new(first)
        .file_name()
        .and_then(|name| name.to_str())
        .unwrap_or(first)
        .to_string()
}

fn normalize_lint_command(command: &LintCommandConfig) -> Option<LintCommandConfig> {
    let name = command.name.trim();
    let command_str = command.command.trim();

    if command_str.is_empty() {
        return builtin_lint_command(name);
    }

    Some(LintCommandConfig {
        name:    if name.is_empty() {
            infer_lint_command_name(command_str)
        } else {
            name.to_string()
        },
        command: command_str.to_string(),
    })
}

pub(crate) fn normalize_lint_commands(commands: &[LintCommandConfig]) -> Vec<LintCommandConfig> {
    commands.iter().filter_map(normalize_lint_command).collect()
}

pub(crate) struct ParsedCacheSize {
    pub bytes:      Option<u64>,
    pub normalized: String,
}

fn normalize_cache_size_number(number: &str) -> Result<String, String> {
    let (whole_raw, fraction_raw) = number
        .split_once('.')
        .map_or((number, None), |(whole, fraction)| (whole, Some(fraction)));

    if whole_raw.is_empty() && fraction_raw.is_none() {
        return Err(format!("Invalid cache size quantity `{number}`"));
    }
    if !whole_raw.is_empty() && !whole_raw.chars().all(|ch| ch.is_ascii_digit()) {
        return Err(format!("Invalid cache size quantity `{number}`"));
    }

    let whole = if whole_raw.is_empty() {
        "0"
    } else {
        whole_raw.trim_start_matches('0')
    };
    let whole = if whole.is_empty() { "0" } else { whole };

    let Some(fraction_raw) = fraction_raw else {
        return Ok(whole.to_string());
    };
    if !fraction_raw.chars().all(|ch| ch.is_ascii_digit()) {
        return Err(format!("Invalid cache size quantity `{number}`"));
    }

    let fraction = fraction_raw.trim_end_matches('0');
    if fraction.is_empty() {
        Ok(whole.to_string())
    } else {
        Ok(format!("{whole}.{fraction}"))
    }
}

fn parse_cache_size_bytes(number: &str, multiplier: u64) -> Result<Option<u64>, String> {
    let (whole_raw, fraction_raw) = number
        .split_once('.')
        .map_or((number, None), |(whole, fraction)| (whole, Some(fraction)));
    if whole_raw.is_empty() && fraction_raw.is_none() {
        return Err(format!("Invalid cache size quantity `{number}`"));
    }

    let whole = if whole_raw.is_empty() {
        0_u128
    } else {
        whole_raw
            .parse::<u128>()
            .map_err(|_| format!("Invalid cache size quantity `{number}`"))?
    };
    let multiplier = u128::from(multiplier);
    let whole_bytes = whole
        .checked_mul(multiplier)
        .ok_or_else(|| "Cache size is too large".to_string())?;

    let Some(fraction_raw) = fraction_raw else {
        return u64::try_from(whole_bytes)
            .map(Some)
            .map_err(|_| "Cache size is too large".to_string());
    };
    if !fraction_raw.chars().all(|ch| ch.is_ascii_digit()) {
        return Err(format!("Invalid cache size quantity `{number}`"));
    }
    if fraction_raw.is_empty() {
        return u64::try_from(whole_bytes)
            .map(Some)
            .map_err(|_| "Cache size is too large".to_string());
    }

    let fraction = fraction_raw
        .parse::<u128>()
        .map_err(|_| format!("Invalid cache size quantity `{number}`"))?;
    let scale = 10_u128
        .checked_pow(u32::try_from(fraction_raw.len()).unwrap_or(u32::MAX))
        .ok_or_else(|| "Cache size is too large".to_string())?;
    let fraction_bytes = fraction
        .checked_mul(multiplier)
        .ok_or_else(|| "Cache size is too large".to_string())?
        .div_ceil(scale);
    let total = whole_bytes
        .checked_add(fraction_bytes)
        .ok_or_else(|| "Cache size is too large".to_string())?;

    if total == 0 {
        Ok(None)
    } else {
        u64::try_from(total)
            .map(Some)
            .map_err(|_| "Cache size is too large".to_string())
    }
}

fn canonical_cache_size_unit(unit: &str) -> Option<(&'static str, u64)> {
    match unit.trim().to_ascii_lowercase().as_str() {
        "b" | "byte" | "bytes" => Some(("B", 1)),
        "kib" | "kb" => Some(("KiB", BYTES_PER_KIB)),
        "mib" | "mb" => Some(("MiB", BYTES_PER_MIB)),
        "gib" | "gb" => Some(("GiB", BYTES_PER_GIB)),
        _ => None,
    }
}

pub(crate) fn parse_cache_size(value: &str) -> Result<ParsedCacheSize, String> {
    let trimmed = value.trim();
    if trimmed.is_empty() {
        return Err("Cache size cannot be empty".to_string());
    }
    if trimmed.eq_ignore_ascii_case("unlimited") {
        return Ok(ParsedCacheSize {
            bytes:      None,
            normalized: "unlimited".to_string(),
        });
    }
    if trimmed == "0" {
        return Ok(ParsedCacheSize {
            bytes:      None,
            normalized: "0".to_string(),
        });
    }

    let split_at = trimmed
        .find(|ch: char| !(ch.is_ascii_digit() || ch == '.'))
        .unwrap_or(trimmed.len());
    let number = trimmed[..split_at].trim();
    let unit = trimmed[split_at..].trim();

    if number.is_empty() || unit.is_empty() {
        return Err(
            "Cache size must include a number and unit like `512 MiB` or `1.5 GiB`".to_string(),
        );
    }

    let Some((canonical_unit, multiplier)) = canonical_cache_size_unit(unit) else {
        return Err(format!("Unsupported cache size unit `{unit}`"));
    };
    let normalized = format!(
        "{} {}",
        normalize_cache_size_number(number)?,
        canonical_unit
    );
    Ok(ParsedCacheSize {
        bytes: parse_cache_size_bytes(number, multiplier)?,
        normalized,
    })
}

pub(crate) fn normalize_config(mut config: CargoPortConfig) -> Result<CargoPortConfig, String> {
    config.lint.commands = normalize_lint_commands(&config.lint.commands);
    config.lint.cache_size = config.lint.normalized_cache_size()?;
    config.cpu.poll_ms = config.cpu.poll_ms.max(MIN_CPU_POLL_MS);
    config.cpu.low_utilization_max_percent = config.cpu.low_utilization_max_percent.min(100);
    config.cpu.medium_utilization_max_percent = config
        .cpu
        .medium_utilization_max_percent
        .max(config.cpu.low_utilization_max_percent)
        .min(100);
    config.tui.main_branch = normalize_branch_name(&config.tui.main_branch, "tui.main_branch")?;
    config.tui.other_primary_branches = normalize_branch_list(
        &config.tui.other_primary_branches,
        "tui.other_primary_branches",
    )?;
    config.tui.discovery_shimmer_secs =
        normalize_non_negative_secs(config.tui.discovery_shimmer_secs);
    Ok(config)
}

impl CargoPortConfig {
    pub(crate) fn from_table(table: &Table) -> Result<Self, String> {
        use confique::Layer as _;

        let value = Value::Table(table.clone());
        let layer: <Self as confique::Config>::Layer = value
            .try_into()
            .map_err(|err| format!("config from table: {err}"))?;
        Self::from_layer(layer.with_fallback(<Self as confique::Config>::Layer::default_values()))
            .map_err(|err| format!("config from table: {err}"))
            .and_then(normalize_config)
    }
}

pub(crate) fn normalize_branch_name(value: &str, field: &str) -> Result<String, String> {
    let branch = value.trim();
    if branch.is_empty() {
        return Err(format!("{field} must not be empty"));
    }
    validate_branch_name(branch, field)?;
    Ok(branch.to_string())
}

pub(crate) fn normalize_branch_list(values: &[String], field: &str) -> Result<Vec<String>, String> {
    values
        .iter()
        .enumerate()
        .filter_map(|(index, value)| {
            let trimmed = value.trim();
            if trimmed.is_empty() {
                None
            } else {
                Some((index, trimmed))
            }
        })
        .map(|(index, branch)| {
            validate_branch_name(branch, &format!("{field}[{index}]"))?;
            Ok(branch.to_string())
        })
        .collect()
}

fn validate_branch_name(branch: &str, field: &str) -> Result<(), String> {
    if branch == "@"
        || branch.starts_with('-')
        || branch.starts_with('/')
        || branch.ends_with('/')
        || branch.ends_with('.')
        || std::path::Path::new(branch)
            .extension()
            .is_some_and(|ext| ext.eq_ignore_ascii_case("lock"))
        || branch.contains("..")
        || branch.contains("@{")
        || branch.contains("//")
    {
        return Err(format!("{field} must be a valid branch name"));
    }

    if branch
        .split('/')
        .any(|part| part.is_empty() || part == "." || part == ".." || part.starts_with('.'))
    {
        return Err(format!("{field} must be a valid branch name"));
    }

    if branch.chars().any(|ch| {
        ch.is_ascii_control()
            || ch.is_whitespace()
            || matches!(ch, '~' | '^' | ':' | '?' | '*' | '[' | '\\')
    }) {
        return Err(format!("{field} must be a valid branch name"));
    }

    Ok(())
}

fn normalize_non_negative_secs(secs: f64) -> f64 {
    if secs.is_finite() && secs >= 0.0 {
        secs
    } else {
        0.0
    }
}

/// Top-level application configuration.
#[derive(Clone, Debug, Default, PartialEq, confique::Config, Serialize)]
pub(crate) struct CargoPortConfig {
    #[config(nested)]
    pub cache:      CacheConfig,
    #[config(nested)]
    pub cpu:        CpuConfig,
    #[config(nested)]
    pub mouse:      MouseConfig,
    #[config(nested)]
    pub tui:        TuiConfig,
    #[config(nested)]
    pub lint:       LintConfig,
    #[config(nested)]
    pub debug:      DebugConfig,
    #[config(nested)]
    pub appearance: AppearanceConfig,
}

/// Theme selection and OS appearance tracking.
///
/// `mode` selects between three resolution strategies:
/// - `"auto"`: follow the OS light/dark setting (Phase 5 plugs OS state in; until then `auto`
///   behaves identically to `"dark"`).
/// - `"light"`: always use `light_theme` regardless of OS state.
/// - `"dark"`: always use `dark_theme` regardless of OS state.
///
/// `light_theme` and `dark_theme` are theme ids (display names) looked up
/// in [`tui_pane::ThemeRegistry`]. Unknown names fall back to the
/// compiled-in built-ins with a toast naming the missing id.
#[derive(Clone, Debug, PartialEq, Eq, confique::Config, Serialize)]
pub(crate) struct AppearanceConfig {
    /// Theme appearance mode: `"auto"`, `"light"`, or `"dark"`.
    #[config(default = "dark")]
    pub mode:              String,
    /// Theme name to use when the resolved appearance is light.
    #[config(default = "Default Light")]
    pub light_theme:       String,
    /// Theme name to use when the resolved appearance is dark.
    #[config(default = "Default Dark")]
    pub dark_theme:        String,
    /// Controls whether the focused pane gets a subtle background tint so it
    /// lifts away from neighbouring panes. Disabling it keeps every pane drawn
    /// against the terminal's native background (preserves iTerm2 /
    /// window-level transparency).
    #[config(default = true)]
    pub focused_pane_tint: FocusedPaneTint,
}

impl Default for AppearanceConfig {
    fn default() -> Self {
        Self {
            mode:              "dark".to_string(),
            light_theme:       "Default Light".to_string(),
            dark_theme:        "Default Dark".to_string(),
            focused_pane_tint: FocusedPaneTint::Enabled,
        }
    }
}

/// Developer / testing affordances. Intentionally narrow — anything here
/// exists only to exercise code paths that are hard to reproduce
/// organically (e.g. GitHub rate-limit behaviour).
#[derive(Clone, Debug, Default, PartialEq, Eq, confique::Config, Serialize)]
pub(crate) struct DebugConfig {
    /// When true, all GitHub HTTP requests short-circuit to a synthetic
    /// rate-limited response without hitting the network. Lets the
    /// rate-limit toast, `/rate_limit` display, and recovery probe be
    /// verified deterministically. Default false.
    #[config(default = false)]
    pub force_github_rate_limit: GitHubRateLimitMode,
}

/// CPU meter settings for the TUI host metrics pane.
#[derive(Clone, Debug, PartialEq, Eq, confique::Config, Serialize)]
pub(crate) struct CpuConfig {
    /// How often to refresh CPU utilization values in milliseconds.
    #[config(default = 1000)]
    pub poll_ms: u64,

    /// Upper bound for the low CPU utilization band.
    #[config(default = 60)]
    pub low_utilization_max_percent: u8,

    /// Upper bound for the medium CPU utilization band.
    #[config(default = 85)]
    pub medium_utilization_max_percent: u8,
}

impl Default for CpuConfig {
    fn default() -> Self {
        Self {
            poll_ms:                        1000,
            low_utilization_max_percent:    60,
            medium_utilization_max_percent: 85,
        }
    }
}

/// TUI display and behaviour settings.
#[derive(Clone, Debug, PartialEq, confique::Config, Serialize)]
pub(crate) struct TuiConfig {
    /// Directory names whose members are shown inline (pulled up to the
    /// workspace level). For example, `["crates"]` means projects under
    /// `workspace/crates/` appear directly under the workspace rather than
    /// in a "crates" folder.
    #[config(default = ["crates"])]
    pub inline_dirs: Vec<String>,

    /// Number of recent CI runs to fetch per project.
    #[config(default = 5)]
    pub ci_run_count: u32,

    /// Whether `hjkl` mirrors arrow navigation in non-text panes.
    #[config(default = false)]
    pub navigation_keys: NavigationKeys,

    /// Whether scrolling past the top or bottom of a list moves focus to the
    /// adjacent pane in tab order instead of stopping at the edge.
    #[config(default = false)]
    pub edge_scroll: EdgeScroll,

    /// Directories to scan for projects (relative to the scan root, or
    /// absolute paths). When empty, the entire scan root is walked.
    #[config(default = [])]
    pub include_dirs: Vec<String>,

    /// Whether to include non-Rust projects (git repos without Cargo.toml).
    #[config(default = false)]
    pub include_non_rust: NonRustInclusion,

    /// Editor application name, opened via `open -a <editor> <path>`.
    #[config(default = "zed")]
    pub editor: String,

    /// OS/terminal-specific shell command used by the global terminal shortcut.
    /// Leave blank to disable terminal opening. The command runs with the
    /// selected project-list path as cwd; use `{path}` if your terminal needs
    /// that path explicitly. Do not add shell quotes around `{path}`.
    /// Examples:
    /// - `open -a Terminal .`
    /// - `osascript -e "tell application \"iTerm2\" to create window with default profile command
    ///   \"cd {path} && exec zsh\""`
    #[config(default = "")]
    pub terminal_command: String,

    /// Preferred local branch used for Git-panel `M` comparisons.
    /// Example: `main`
    #[config(default = "main")]
    pub main_branch: String,

    /// Optional fallback local branch names checked after `main_branch`.
    /// Example: `["primary"]`
    #[config(default = [])]
    pub other_primary_branches: Vec<String>,

    /// Default remote host URL prefix. Remote URLs beginning with this prefix
    /// are shortened in the Git panel's Remotes table to `owner/repo` form;
    /// remotes on other hosts are shown with the full URL.
    #[config(default = "https://github.com/")]
    pub default_remote_host_url: String,

    /// How long (in seconds) newly discovered project names shimmer in the
    /// project list. `0.0` disables the effect.
    #[config(default = 10.0)]
    pub discovery_shimmer_secs: f64,
}

impl Default for TuiConfig {
    fn default() -> Self {
        Self {
            inline_dirs:             vec!["crates".to_string()],
            ci_run_count:            5,
            navigation_keys:         NavigationKeys::ArrowsOnly,
            edge_scroll:             EdgeScroll::Stops,
            include_dirs:            Vec::new(),
            include_non_rust:        NonRustInclusion::Exclude,
            editor:                  "zed".to_string(),
            terminal_command:        String::new(),
            main_branch:             "main".to_string(),
            other_primary_branches:  Vec::new(),
            default_remote_host_url: "https://github.com/".to_string(),
            discovery_shimmer_secs:  10.0,
        }
    }
}

/// Mouse input settings.
#[derive(Clone, Debug, PartialEq, Eq, confique::Config, Serialize)]
pub(crate) struct MouseConfig {
    /// Whether to invert mouse scroll direction.
    #[config(default = true)]
    pub invert_scroll: ScrollDirection,
}

impl Default for MouseConfig {
    fn default() -> Self {
        Self {
            invert_scroll: ScrollDirection::Inverted,
        }
    }
}

pub(crate) fn config_path() -> Option<AbsolutePath> {
    #[cfg(test)]
    if let Some(path) = CONFIG_PATH_OVERRIDE.with(|slot| slot.borrow().clone()) {
        return Some(path.into());
    }

    dirs::config_dir().map(|d| d.join(APP_NAME).join(CONFIG_FILE).into())
}

#[cfg(test)]
thread_local! {
    static CONFIG_PATH_OVERRIDE: RefCell<Option<PathBuf>> = const {
        RefCell::new(None)
    };
}

#[cfg(test)]
pub(crate) struct ConfigPathOverrideGuard {
    previous: Option<PathBuf>,
}

#[cfg(test)]
impl Drop for ConfigPathOverrideGuard {
    fn drop(&mut self) {
        let previous = self.previous.take();
        CONFIG_PATH_OVERRIDE.with(|slot| {
            *slot.borrow_mut() = previous;
        });
    }
}

#[cfg(test)]
pub(crate) fn override_config_path_for_test(path: PathBuf) -> ConfigPathOverrideGuard {
    let previous = CONFIG_PATH_OVERRIDE.with(|slot| slot.replace(Some(path)));
    ConfigPathOverrideGuard { previous }
}

fn active_config_cell() -> &'static RwLock<CargoPortConfig> {
    static ACTIVE_CONFIG: OnceLock<RwLock<CargoPortConfig>> = OnceLock::new();
    ACTIVE_CONFIG.get_or_init(|| RwLock::new(CargoPortConfig::default()))
}

pub(crate) fn active_config() -> CargoPortConfig {
    active_config_cell()
        .read()
        .map_or_else(|_| CargoPortConfig::default(), |cfg| cfg.clone())
}

pub(crate) fn set_active_config(config: &CargoPortConfig) {
    if let Ok(mut active) = active_config_cell().write() {
        *active = normalize_config(config.clone()).unwrap_or_else(|_| config.clone());
    }
}

#[cfg(test)]
#[allow(
    clippy::expect_used,
    reason = "tests should panic on unexpected values"
)]
mod tests {
    use confique::Config as _;

    use super::*;
    use crate::test_support;

    fn assert_default_config_subset(cfg: &CargoPortConfig, expected_ci_run_count: u32) {
        assert!(cfg.cache.root.is_empty());
        assert_eq!(cfg.cpu.poll_ms, 1000);
        assert_eq!(cfg.cpu.low_utilization_max_percent, 60);
        assert_eq!(cfg.cpu.medium_utilization_max_percent, 85);
        assert_eq!(cfg.tui.inline_dirs, vec!["crates".to_string()]);
        assert_eq!(cfg.tui.ci_run_count, expected_ci_run_count);
        assert!(cfg.tui.include_dirs.is_empty());
        assert_eq!(cfg.tui.include_non_rust, NonRustInclusion::Exclude);
        assert_eq!(cfg.tui.editor, "zed");
        assert!(cfg.tui.terminal_command.is_empty());
        assert_eq!(cfg.tui.main_branch, "main");
        assert!(cfg.tui.other_primary_branches.is_empty());
        assert!((cfg.tui.discovery_shimmer_secs - 10.0).abs() < f64::EPSILON);
        assert_eq!(cfg.tui.navigation_keys, NavigationKeys::ArrowsOnly);
        assert_eq!(cfg.tui.edge_scroll, EdgeScroll::Stops);
        assert_eq!(cfg.mouse.invert_scroll, ScrollDirection::Inverted);
        assert_eq!(cfg.lint.enabled, LintIndicator::Disabled);
        assert!(cfg.lint.include.is_empty());
        assert!(cfg.lint.exclude.is_empty());
        assert!(cfg.lint.commands.is_empty());
        assert_eq!(cfg.lint.cache_size, "512 MiB");
    }

    /// `Config::default()` returns correct values for every field.
    #[test]
    fn defaults_are_correct() {
        let cfg = CargoPortConfig::default();
        assert_default_config_subset(&cfg, 5);
    }

    /// Generated template parses back into a valid `CargoPortConfig` via confique.
    #[test]
    fn template_round_trips() {
        let template =
            confique::toml::template::<CargoPortConfig>(confique::toml::FormatOptions::default());

        let dir = tempfile::tempdir().expect("tempdir");
        let path = dir.path().join("config.toml");
        std::fs::write(&path, &template).expect("write template");

        // Template has all fields commented out, so loading it should
        // succeed with defaults filling every field.
        let cfg = CargoPortConfig::builder()
            .file(&path)
            .load()
            .expect("template should parse");
        assert_default_config_subset(&cfg, 5);
    }

    /// A partial config file gets defaults for missing fields.
    #[test]
    fn partial_config_fills_defaults() {
        let dir = tempfile::tempdir().expect("tempdir");
        let path = dir.path().join("config.toml");
        std::fs::write(&path, "[tui]\nci_run_count = 10\n").expect("write");

        let cfg = CargoPortConfig::builder()
            .file(&path)
            .load()
            .expect("partial config should load");
        assert_default_config_subset(&cfg, 10);
    }

    #[test]
    fn table_config_fills_defaults() {
        let table = toml::from_str::<toml::Table>("[tui]\nci_run_count = 10\n").expect("table");

        let cfg = CargoPortConfig::from_table(&table).expect("config from table");

        assert_default_config_subset(&cfg, 10);
    }

    #[test]
    fn table_config_rejects_invalid_normalized_values() {
        let table = toml::from_str::<toml::Table>("[tui]\nmain_branch = \"\"\n").expect("table");

        let err = CargoPortConfig::from_table(&table).expect_err("invalid branch");

        assert!(err.contains("tui.main_branch must not be empty"));
    }

    /// An empty config file gets all defaults.
    #[test]
    fn empty_config_gets_defaults() {
        let dir = tempfile::tempdir().expect("tempdir");
        let path = dir.path().join("config.toml");
        std::fs::write(&path, "").expect("write");

        let cfg = CargoPortConfig::builder()
            .file(&path)
            .load()
            .expect("empty config should load");
        assert_default_config_subset(&cfg, 5);
    }

    /// Saving and reloading preserves all values.
    #[test]
    fn save_and_reload_round_trip() {
        let dir = tempfile::tempdir().expect("tempdir");
        let path = dir.path().join("config.toml");

        let mut cfg = CargoPortConfig::default();
        cfg.cache.root = "/tmp/cargo-port-cache".to_string();
        cfg.tui.ci_run_count = 42;
        cfg.tui.editor = "vim".to_string();
        cfg.tui.terminal_command = "open -a Terminal .".to_string();
        cfg.tui.main_branch = "primary".to_string();
        cfg.tui.other_primary_branches = vec!["main".to_string(), "release".to_string()];
        cfg.tui.navigation_keys = NavigationKeys::ArrowsAndVim;
        cfg.tui.discovery_shimmer_secs = 4.5;
        cfg.cpu.poll_ms = 1500;
        cfg.cpu.low_utilization_max_percent = 55;
        cfg.cpu.medium_utilization_max_percent = 90;
        cfg.mouse.invert_scroll = ScrollDirection::Normal;

        let contents = toml::to_string_pretty(&cfg).expect("serialize");
        std::fs::write(&path, &contents).expect("write");

        let reloaded = CargoPortConfig::builder()
            .file(&path)
            .load()
            .expect("reloaded config");
        assert_eq!(reloaded.cache.root, "/tmp/cargo-port-cache");
        assert_eq!(reloaded.tui.ci_run_count, 42);
        assert_eq!(reloaded.tui.editor, "vim");
        assert_eq!(reloaded.cpu.poll_ms, 1500);
        assert_eq!(reloaded.cpu.low_utilization_max_percent, 55);
        assert_eq!(reloaded.cpu.medium_utilization_max_percent, 90);
        assert_eq!(reloaded.tui.terminal_command, "open -a Terminal .");
        assert_eq!(reloaded.tui.main_branch, "primary");
        assert_eq!(
            reloaded.tui.other_primary_branches,
            vec!["main".to_string(), "release".to_string()]
        );
        assert_eq!(reloaded.tui.navigation_keys, NavigationKeys::ArrowsAndVim);
        assert!((reloaded.tui.discovery_shimmer_secs - 4.5).abs() < f64::EPSILON);
        assert_eq!(reloaded.mouse.invert_scroll, ScrollDirection::Normal);
        assert!(reloaded.tui.include_dirs.is_empty());
        assert_eq!(reloaded.tui.include_non_rust, NonRustInclusion::Exclude);
        assert!(reloaded.lint.commands.is_empty());
        assert!(reloaded.lint.include.is_empty());
        assert!(reloaded.lint.exclude.is_empty());
        assert_eq!(reloaded.lint.enabled, LintIndicator::Disabled);
        assert_eq!(reloaded.lint.cache_size, "512 MiB");
    }

    #[test]
    fn legacy_toast_tui_keys_do_not_break_config_load() {
        let dir = tempfile::tempdir().expect("tempdir");
        let path = dir.path().join("config.toml");
        std::fs::write(
            &path,
            "[tui]\nstatus_flash_secs = 5.0\ntask_linger_secs = 1.0\n",
        )
        .expect("write legacy config");

        let cfg = CargoPortConfig::builder()
            .file(&path)
            .load()
            .expect("legacy toast keys should be ignored by app config");

        assert_eq!(cfg.tui.ci_run_count, 5);
    }

    /// Bool-based enums deserialize correctly from TOML booleans.
    #[test]
    fn bool_enums_from_toml() {
        let dir = tempfile::tempdir().expect("tempdir");
        let path = dir.path().join("config.toml");
        std::fs::write(
            &path,
            "[mouse]\ninvert_scroll = false\n\n[tui]\ninclude_non_rust = true\nnavigation_keys = true\nedge_scroll = true\n\n[lint]\nenabled = true\n\n[appearance]\nfocused_pane_tint = false\n\n[debug]\nforce_github_rate_limit = true\n",
        )
        .expect("write");

        let cfg = CargoPortConfig::builder()
            .file(&path)
            .load()
            .expect("bool enums should parse");
        assert!(cfg.cache.root.is_empty());
        assert_eq!(cfg.mouse.invert_scroll, ScrollDirection::Normal);
        assert_eq!(cfg.tui.include_non_rust, NonRustInclusion::Include);
        assert_eq!(cfg.tui.navigation_keys, NavigationKeys::ArrowsAndVim);
        assert_eq!(cfg.tui.edge_scroll, EdgeScroll::AdvancesPane);
        assert_eq!(cfg.lint.enabled, LintIndicator::Enabled);
        assert_eq!(cfg.appearance.focused_pane_tint, FocusedPaneTint::Disabled);
        assert_eq!(
            cfg.debug.force_github_rate_limit,
            GitHubRateLimitMode::Forced
        );
    }

    /// Cache root override parses from TOML.
    #[test]
    fn cache_root_override_parses() {
        let dir = tempfile::tempdir().expect("tempdir");
        let path = dir.path().join("config.toml");
        std::fs::write(&path, "[cache]\nroot = \"/tmp/cargo-port\"\n").expect("write");

        let cfg = CargoPortConfig::builder()
            .file(&path)
            .load()
            .expect("cache root should parse");
        assert_eq!(cfg.cache.root, "/tmp/cargo-port");
        assert_eq!(cfg.lint.enabled, LintIndicator::Disabled);
    }

    /// Lint command arrays parse from TOML and preserve ordering.
    #[test]
    fn lint_commands_parse() {
        let dir = tempfile::tempdir().expect("tempdir");
        let path = dir.path().join("config.toml");
        std::fs::write(
            &path,
            "[lint]\n\
             enabled = true\n\
             include = [\"~/rust/cargo-port_report\"]\n\
             exclude = [\"~/rust/archive\"]\n\
             [[lint.commands]]\n\
             name = \"fmt\"\n\
             command = \"cargo fmt --check\"\n\
             [[lint.commands]]\n\
             name = \"clippy\"\n\
             command = \"cargo clippy -- -D warnings\"\n",
        )
        .expect("write");

        let cfg = CargoPortConfig::builder()
            .file(&path)
            .load()
            .expect("lint commands should parse");
        assert_eq!(cfg.lint.enabled, LintIndicator::Enabled);
        assert_eq!(cfg.lint.include, vec!["~/rust/cargo-port_report"]);
        assert_eq!(cfg.lint.exclude, vec!["~/rust/archive"]);
        assert_eq!(cfg.lint.commands.len(), 2);
        assert_eq!(cfg.lint.commands[0].name, "fmt");
        assert_eq!(cfg.lint.commands[0].command, "cargo fmt --check");
        assert_eq!(cfg.lint.commands[1].name, "clippy");
    }

    #[test]
    fn normalize_config_resolves_builtin_name_only_commands() {
        let cfg = normalize_config(CargoPortConfig {
            lint: LintConfig {
                commands: vec![LintCommandConfig {
                    name:    "clippy".to_string(),
                    command: String::new(),
                }],
                ..LintConfig::default()
            },
            ..CargoPortConfig::default()
        })
        .expect("normalize config");

        assert_eq!(cfg.lint.commands.len(), 1);
        assert_eq!(cfg.lint.commands[0].name, "clippy");
        assert!(cfg.lint.commands[0].command.contains("cargo clippy"));
    }

    #[test]
    fn normalize_config_names_raw_commands() {
        let cfg = normalize_config(CargoPortConfig {
            lint: LintConfig {
                commands: vec![LintCommandConfig {
                    name:    String::new(),
                    command: "cargo fmt --check".to_string(),
                }],
                ..LintConfig::default()
            },
            ..CargoPortConfig::default()
        })
        .expect("normalize config");

        assert_eq!(cfg.lint.commands.len(), 1);
        assert_eq!(cfg.lint.commands[0].name, "fmt");
        assert_eq!(cfg.lint.commands[0].command, "cargo fmt --check");
    }

    /// Empty lint command config falls back to the built-in clippy command.
    #[test]
    fn resolved_lint_commands_default_to_builtins() {
        let cfg = CargoPortConfig::default();
        let commands = cfg.lint.resolved_commands();
        assert_eq!(commands.len(), 1);
        assert_eq!(commands[0].name, "clippy");
        assert!(commands[0].command.contains("cargo clippy"));
    }

    #[test]
    fn parse_cache_size_accepts_decimal_binary_units() {
        let parsed = parse_cache_size("1.5 GiB").expect("parse cache size");
        assert_eq!(parsed.normalized, "1.5 GiB");
        assert_eq!(parsed.bytes, Some(1_610_612_736));
    }

    #[test]
    fn parse_cache_size_accepts_unlimited_aliases() {
        assert_eq!(
            parse_cache_size("unlimited").expect("unlimited").bytes,
            None
        );
        assert_eq!(parse_cache_size("0").expect("zero").bytes, None);
    }

    #[test]
    fn normalize_config_normalizes_cache_size_units() {
        let cfg = normalize_config(CargoPortConfig {
            lint: LintConfig {
                cache_size: "1.50 gib".to_string(),
                ..LintConfig::default()
            },
            ..CargoPortConfig::default()
        })
        .expect("normalize config");

        assert_eq!(cfg.lint.cache_size, "1.5 GiB");
    }

    #[test]
    fn normalize_config_clamps_invalid_tui_seconds_to_zero() {
        let mut cfg = CargoPortConfig::default();
        cfg.tui.discovery_shimmer_secs = f64::INFINITY;

        let normalized = normalize_config(cfg).expect("normalize config");

        assert!(normalized.tui.discovery_shimmer_secs.abs() < f64::EPSILON);
    }

    #[test]
    fn normalize_config_trims_main_and_other_primary_branches() {
        let mut cfg = CargoPortConfig::default();
        cfg.tui.main_branch = "  primary  ".to_string();
        cfg.tui.other_primary_branches = vec![
            "  main  ".to_string(),
            " ".to_string(),
            "release".to_string(),
        ];

        let normalized = normalize_config(cfg).expect("normalize config");

        assert_eq!(normalized.tui.main_branch, "primary");
        assert_eq!(
            normalized.tui.other_primary_branches,
            vec!["main".to_string(), "release".to_string()]
        );
    }

    #[test]
    fn invalid_branch_names_are_rejected() {
        assert!(normalize_branch_name(" ", "tui.main_branch").is_err());
        assert!(normalize_branch_name("bad branch", "tui.main_branch").is_err());
        assert!(
            normalize_branch_list(
                &["main".to_string(), "bad branch".to_string()],
                "tui.other_primary_branches"
            )
            .is_err()
        );
    }

    #[test]
    fn default_config_template_matches_golden_file() {
        let template =
            confique::toml::template::<CargoPortConfig>(confique::toml::FormatOptions::default());
        let expected = include_str!("../tests/assets/default-config.toml");

        assert_eq!(
            test_support::normalize_line_endings(&template),
            test_support::normalize_line_endings(expected)
        );
    }
}