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
|
use std::path::{Path, PathBuf};
use tracing::warn;
use super::{model::LoadedConfig, Config, CONFIG_PATH_ENV_VAR};
const KNOWN_TOP_LEVEL_CONFIG_KEYS: &[&str] = &[
"advanced",
"experimental",
"keys",
"onboarding",
"remote",
"server",
"session",
"terminal",
"theme",
"ui",
"update",
"worktrees",
];
pub fn app_dir_name() -> &'static str {
if cfg!(debug_assertions) {
"herdr-dev"
} else {
"herdr"
}
}
pub fn config_dir() -> PathBuf {
if let Ok(dir) = std::env::var("XDG_CONFIG_HOME") {
return PathBuf::from(dir).join(app_dir_name());
}
platform_config_dir()
}
pub fn state_dir() -> PathBuf {
if let Ok(dir) = std::env::var("XDG_STATE_HOME") {
return PathBuf::from(dir).join(app_dir_name());
}
platform_state_dir()
}
#[cfg(windows)]
fn platform_config_dir() -> PathBuf {
if let Ok(dir) = std::env::var("APPDATA") {
return PathBuf::from(dir).join(app_dir_name());
}
if let Ok(profile) = std::env::var("USERPROFILE") {
return PathBuf::from(profile)
.join("AppData")
.join("Roaming")
.join(app_dir_name());
}
if let Ok(home) = std::env::var("HOME") {
return PathBuf::from(home).join(format!(".config/{}", app_dir_name()));
}
std::env::temp_dir().join(app_dir_name())
}
#[cfg(not(windows))]
fn platform_config_dir() -> PathBuf {
if let Ok(home) = std::env::var("HOME") {
PathBuf::from(home).join(format!(".config/{}", app_dir_name()))
} else {
std::env::temp_dir().join(app_dir_name())
}
}
#[cfg(windows)]
fn platform_state_dir() -> PathBuf {
if let Ok(dir) = std::env::var("LOCALAPPDATA") {
return PathBuf::from(dir).join(app_dir_name());
}
if let Ok(profile) = std::env::var("USERPROFILE") {
return PathBuf::from(profile)
.join("AppData")
.join("Local")
.join(app_dir_name());
}
if let Ok(home) = std::env::var("HOME") {
return PathBuf::from(home).join(format!(".local/state/{}", app_dir_name()));
}
std::env::temp_dir().join(format!("{}-state", app_dir_name()))
}
#[cfg(not(windows))]
fn platform_state_dir() -> PathBuf {
if let Ok(home) = std::env::var("HOME") {
PathBuf::from(home).join(format!(".local/state/{}", app_dir_name()))
} else {
std::env::temp_dir().join(format!("{}-state", app_dir_name()))
}
}
/// Normalize UTF-8 byte-order marks in config text.
///
/// TOML tolerates a single BOM at the very start of the document, but a BOM at
/// the start of a later line makes the parser reject the whole file. A
/// line-oriented edit can displace a leading BOM into the middle of the file,
/// so drop line-start BOMs that the TOML parser actually rejects. A U+FEFF that
/// is valid string data is kept, because its parse error would not point at it.
fn normalize_utf8_bom(content: &str) -> String {
let content = content.strip_prefix('\u{feff}').unwrap_or(content);
if !content.contains('\u{feff}') {
return content.to_owned();
}
let mut normalized = content.to_owned();
while let Err(error) = normalized.parse::<toml::Value>() {
let Some(span) = error.span() else {
break;
};
if normalized.get(span.clone()) != Some("\u{feff}") {
break;
}
normalized.replace_range(span, "");
}
normalized
}
pub(super) fn read_optional_config(path: &Path) -> std::io::Result<Option<String>> {
match std::fs::read_to_string(path) {
Ok(content) => Ok(Some(normalize_utf8_bom(&content))),
Err(err) if err.kind() == std::io::ErrorKind::NotFound => Ok(None),
Err(err) => Err(err),
}
}
impl Config {
pub fn load() -> LoadedConfig {
let path = config_path();
let content = match read_optional_config(&path) {
Ok(Some(content)) => content,
Ok(None) => {
return LoadedConfig {
config: Self::default(),
diagnostics: Vec::new(),
invalid_sections: Vec::new(),
};
}
Err(err) => {
warn!(err = %err, "config read error, using defaults");
return LoadedConfig {
config: Self::default(),
diagnostics: vec![format!("config read error: {err}; using defaults")],
invalid_sections: Vec::new(),
};
}
};
match deserialize_with_ignored::<Config, _>(toml::Deserializer::new(&content)) {
Ok((config, ignored_keys)) => {
let (unknown_sections, mut diagnostics) =
unknown_top_level_sections_from_str(&content);
diagnostics.extend(unknown_config_key_diagnostics(
ignored_keys
.into_iter()
.filter(|path| {
!matches!(path.as_slice(), [ConfigKeyPathSegment::Key(key)] if unknown_sections.contains(key))
})
.collect(),
None,
));
diagnostics.extend(config.collect_diagnostics());
LoadedConfig {
config,
diagnostics,
invalid_sections: Vec::new(),
}
}
Err(err) => {
warn!(err = %err, "config parse error, using defaults");
LoadedConfig {
config: Self::default(),
diagnostics: vec![format!("config parse error: {err}; using defaults")],
invalid_sections: Vec::new(),
}
}
}
}
}
pub(super) fn resolve_config_relative_path(path: &Path) -> PathBuf {
if path.is_absolute() {
return path.to_path_buf();
}
config_path()
.parent()
.unwrap_or_else(|| Path::new("."))
.join(path)
}
pub fn config_path() -> PathBuf {
if let Ok(path) = std::env::var(CONFIG_PATH_ENV_VAR) {
return PathBuf::from(path);
}
config_dir().join("config.toml")
}
pub fn config_diagnostic_summary(diagnostics: &[String]) -> Option<String> {
if diagnostics.is_empty() {
return None;
}
let target = config_path()
.file_name()
.and_then(|name| name.to_str())
.unwrap_or("config.toml")
.to_string();
let read_error = diagnostics
.iter()
.any(|diagnostic| diagnostic.starts_with("config read error:"));
let impact = if diagnostics
.iter()
.any(|diagnostic| diagnostic.contains("using defaults"))
{
if read_error {
" unreadable; using defaults"
} else {
" invalid; using defaults"
}
} else if diagnostics
.iter()
.any(|diagnostic| diagnostic.contains("keeping current config"))
{
if read_error {
" unreadable; keeping current config"
} else {
" invalid; keeping current config"
}
} else if diagnostics
.iter()
.all(|diagnostic| diagnostic.starts_with("unknown config key "))
{
" has unknown keys"
} else {
""
};
Some(format!("{target}{impact}; herdr config check"))
}
pub fn load_live_config() -> Result<LoadedConfig, Vec<String>> {
let path = config_path();
let content = match read_optional_config(&path) {
Ok(Some(content)) => content,
Ok(None) => {
return Ok(LoadedConfig {
config: Config::default(),
diagnostics: Vec::new(),
invalid_sections: Vec::new(),
});
}
Err(err) => {
return Err(vec![format!(
"config read error: {err}; keeping current config"
)]);
}
};
load_live_config_from_str(&content)
}
fn load_live_config_from_str(content: &str) -> Result<LoadedConfig, Vec<String>> {
let value = content
.parse::<toml::Value>()
.map_err(|err| vec![format!("config parse error: {err}; keeping current config")])?;
let table = value.as_table().ok_or_else(|| {
vec![
"config parse error: top-level config must be a table; keeping current config"
.to_string(),
]
})?;
let mut config = Config::default();
let mut diagnostics = unknown_top_level_section_diagnostics(table);
diagnostics.extend(unknown_top_level_config_key_diagnostics(table));
let mut invalid_sections = Vec::new();
if let Some(value) = table.get("onboarding") {
match value.clone().try_into::<Option<bool>>() {
Ok(onboarding) => config.onboarding = onboarding,
Err(err) => diagnostics.push(format!(
"invalid onboarding setting: {err}; keeping current onboarding state"
)),
}
}
load_live_section(
table,
"theme",
"theme config",
&mut diagnostics,
&mut invalid_sections,
|section| config.theme = section,
);
load_live_section(
table,
"keys",
"keybinding config",
&mut diagnostics,
&mut invalid_sections,
|section| config.keys = section,
);
load_live_section(
table,
"terminal",
"terminal config",
&mut diagnostics,
&mut invalid_sections,
|section| config.terminal = section,
);
load_live_section(
table,
"session",
"session config",
&mut diagnostics,
&mut invalid_sections,
|section| config.session = section,
);
load_live_section(
table,
"server",
"server config",
&mut diagnostics,
&mut invalid_sections,
|section| config.server = section,
);
load_live_section(
table,
"update",
"update config",
&mut diagnostics,
&mut invalid_sections,
|section| config.update = section,
);
load_live_section(
table,
"ui",
"ui config",
&mut diagnostics,
&mut invalid_sections,
|section| config.ui = section,
);
load_live_section(
table,
"advanced",
"advanced config",
&mut diagnostics,
&mut invalid_sections,
|section| config.advanced = section,
);
load_live_section(
table,
"worktrees",
"worktree config",
&mut diagnostics,
&mut invalid_sections,
|section| config.worktrees = section,
);
load_live_section(
table,
"experimental",
"experimental config",
&mut diagnostics,
&mut invalid_sections,
|section| config.experimental = section,
);
load_live_section(
table,
"remote",
"remote config",
&mut diagnostics,
&mut invalid_sections,
|section| config.remote = section,
);
diagnostics.extend(config.theme.diagnostics());
Ok(LoadedConfig {
config,
diagnostics,
invalid_sections,
})
}
fn unknown_top_level_sections_from_str(content: &str) -> (Vec<String>, Vec<String>) {
let Ok(value) = content.parse::<toml::Value>() else {
return (Vec::new(), Vec::new());
};
let Some(table) = value.as_table() else {
return (Vec::new(), Vec::new());
};
let mut keys = Vec::new();
let mut diagnostics = Vec::new();
for (key, value) in table {
if let Some(diagnostic) = unknown_top_level_section_diagnostic(key, value) {
keys.push(key.clone());
diagnostics.push(diagnostic);
}
}
(keys, diagnostics)
}
fn unknown_top_level_section_diagnostics(
table: &toml::map::Map<String, toml::Value>,
) -> Vec<String> {
table
.iter()
.filter_map(|(key, value)| unknown_top_level_section_diagnostic(key, value))
.collect()
}
fn unknown_top_level_section_diagnostic(key: &str, value: &toml::Value) -> Option<String> {
if KNOWN_TOP_LEVEL_CONFIG_KEYS.contains(&key) {
return None;
}
let header = if value.is_table() {
format!("[{key}]")
} else if value
.as_array()
.is_some_and(|items| !items.is_empty() && items.iter().all(toml::Value::is_table))
{
format!("[[{key}]]")
} else {
return None;
};
if key == "toast" {
Some(format!(
"unknown config section {header}; did you mean [ui.toast]? ignoring section"
))
} else {
Some(format!("unknown config section {header}; ignoring section"))
}
}
fn unknown_top_level_config_key_diagnostics(
table: &toml::map::Map<String, toml::Value>,
) -> Vec<String> {
let paths = table
.iter()
.filter(|(key, value)| {
!KNOWN_TOP_LEVEL_CONFIG_KEYS.contains(&key.as_str())
&& unknown_top_level_section_diagnostic(key, value).is_none()
})
.map(|(key, _)| vec![ConfigKeyPathSegment::Key(key.clone())])
.collect();
unknown_config_key_diagnostics(paths, None)
}
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
enum ConfigKeyPathSegment {
Key(String),
Index(usize),
}
fn config_key_path(path: &serde_ignored::Path<'_>) -> Vec<ConfigKeyPathSegment> {
fn visit(path: &serde_ignored::Path<'_>, segments: &mut Vec<ConfigKeyPathSegment>) {
match path {
serde_ignored::Path::Root => {}
serde_ignored::Path::Seq { parent, index } => {
visit(parent, segments);
segments.push(ConfigKeyPathSegment::Index(*index));
}
serde_ignored::Path::Map { parent, key } => {
visit(parent, segments);
segments.push(ConfigKeyPathSegment::Key(key.clone()));
}
serde_ignored::Path::Some { parent }
| serde_ignored::Path::NewtypeStruct { parent }
| serde_ignored::Path::NewtypeVariant { parent } => visit(parent, segments),
}
}
let mut segments = Vec::new();
visit(path, &mut segments);
segments
}
fn format_config_key_path(path: &[ConfigKeyPathSegment]) -> String {
path.iter()
.map(|segment| match segment {
ConfigKeyPathSegment::Key(key)
if !key.is_empty()
&& key.bytes().all(|byte| {
byte.is_ascii_alphanumeric() || matches!(byte, b'_' | b'-')
}) =>
{
key.clone()
}
ConfigKeyPathSegment::Key(key) => toml::Value::String(key.clone()).to_string(),
ConfigKeyPathSegment::Index(index) => index.to_string(),
})
.collect::<Vec<_>>()
.join(".")
}
fn unknown_config_key_diagnostics(
paths: Vec<Vec<ConfigKeyPathSegment>>,
section: Option<&str>,
) -> Vec<String> {
let mut paths: Vec<Vec<ConfigKeyPathSegment>> = paths
.into_iter()
.map(|mut path| {
if let Some(section) = section {
path.insert(0, ConfigKeyPathSegment::Key(section.to_string()));
}
path
})
.collect();
paths.sort();
paths.dedup();
paths
.into_iter()
.map(|path| {
format!(
"unknown config key {}; ignoring key",
format_config_key_path(&path)
)
})
.collect()
}
fn deserialize_with_ignored<'de, T, D>(
deserializer: D,
) -> Result<(T, Vec<Vec<ConfigKeyPathSegment>>), D::Error>
where
T: serde::Deserialize<'de>,
D: serde::Deserializer<'de>,
{
let mut ignored = Vec::new();
let value = serde_ignored::deserialize(deserializer, |path| {
ignored.push(config_key_path(&path));
})?;
Ok((value, ignored))
}
fn load_live_section<T>(
table: &toml::map::Map<String, toml::Value>,
section: &'static str,
label: &str,
diagnostics: &mut Vec<String>,
invalid_sections: &mut Vec<String>,
apply: impl FnOnce(T),
) where
T: serde::de::DeserializeOwned,
{
let Some(value) = table.get(section) else {
return;
};
match deserialize_with_ignored(value.clone()) {
Ok((section_config, ignored_keys)) => {
diagnostics.extend(unknown_config_key_diagnostics(ignored_keys, Some(section)));
apply(section_config);
}
Err(err) => {
diagnostics.push(format!(
"invalid {label}: {err}; keeping current {section} settings"
));
invalid_sections.push(section.to_string());
}
}
}
pub(crate) fn upsert_top_level_bool(content: &str, key: &str, value: bool) -> String {
let replacement = format!("{key} = {value}");
let mut lines: Vec<String> = content.lines().map(|line| line.to_string()).collect();
let mut in_section = false;
for line in &mut lines {
let trimmed = line.trim();
if trimmed.starts_with('[') && trimmed.ends_with(']') {
in_section = true;
continue;
}
if in_section {
continue;
}
if trimmed.starts_with(&format!("{key} ")) || trimmed.starts_with(&format!("{key}=")) {
*line = replacement.clone();
return lines.join("\n") + "\n";
}
}
if lines.is_empty() {
format!("{replacement}\n")
} else {
format!("{replacement}\n{}\n", lines.join("\n").trim_end())
}
}
/// Write a key = value pair in a TOML section (creates section if missing).
pub fn upsert_section_value(content: &str, section: &str, key: &str, value: &str) -> String {
upsert_section_raw(content, section, key, value)
}
pub fn upsert_section_bool(content: &str, section: &str, key: &str, value: bool) -> String {
upsert_section_raw(content, section, key, &value.to_string())
}
pub fn remove_section_key(content: &str, section: &str, key: &str) -> String {
let header = format!("[{section}]");
let lines: Vec<&str> = content.lines().collect();
let mut result = Vec::new();
let mut i = 0;
let mut in_section = false;
while i < lines.len() {
let line = lines[i];
let trimmed = line.trim();
if trimmed.starts_with('[') && trimmed.ends_with(']') {
in_section = trimmed == header;
result.push(line.to_string());
i += 1;
continue;
}
if in_section
&& (trimmed.starts_with(&format!("{key} ")) || trimmed.starts_with(&format!("{key}=")))
{
i += 1;
continue;
}
result.push(line.to_string());
i += 1;
}
result.join("\n") + "\n"
}
pub fn remove_keybinding_config_sections(content: &str) -> (String, bool) {
let mut result = Vec::new();
let mut removed = false;
let mut skipping_key_section = false;
let mut in_table = false;
for line in content.lines() {
let trimmed = line.trim();
if let Some(table_name) = toml_table_header_name(trimmed) {
in_table = true;
skipping_key_section = is_keys_table_name(table_name);
if skipping_key_section {
removed = true;
continue;
}
} else if skipping_key_section || (!in_table && is_top_level_keys_assignment(trimmed)) {
removed = true;
continue;
}
result.push(line.to_string());
}
let mut updated = result.join("\n");
if content.ends_with('\n') || !updated.is_empty() {
updated.push('\n');
}
(updated, removed)
}
fn toml_table_header_name(trimmed: &str) -> Option<&str> {
if let Some(name) = trimmed
.strip_prefix("[[")
.and_then(|value| value.strip_suffix("]]"))
{
return Some(name.trim());
}
trimmed
.strip_prefix('[')
.and_then(|value| value.strip_suffix(']'))
.map(str::trim)
}
fn is_keys_table_name(name: &str) -> bool {
name == "keys" || name.starts_with("keys.")
}
fn is_top_level_keys_assignment(trimmed: &str) -> bool {
trimmed.starts_with("keys ") || trimmed.starts_with("keys=") || trimmed.starts_with("keys.")
}
fn upsert_section_raw(content: &str, section: &str, key: &str, value: &str) -> String {
let header = format!("[{section}]");
let assignment = format!("{key} = {value}");
let lines: Vec<&str> = content.lines().collect();
let mut result = Vec::new();
let mut i = 0;
let mut found_section = false;
let mut inserted = false;
while i < lines.len() {
let line = lines[i];
let trimmed = line.trim();
if trimmed == header {
found_section = true;
result.push(line.to_string());
i += 1;
while i < lines.len() {
let current = lines[i];
let current_trimmed = current.trim();
if current_trimmed.starts_with('[') && current_trimmed.ends_with(']') {
if !inserted {
result.push(assignment.clone());
inserted = true;
}
break;
}
if current_trimmed.starts_with(&format!("{key} "))
|| current_trimmed.starts_with(&format!("{key}="))
{
result.push(assignment.clone());
inserted = true;
} else {
result.push(current.to_string());
}
i += 1;
}
continue;
}
result.push(line.to_string());
i += 1;
}
if !found_section {
if !result.is_empty() && !result.last().is_some_and(|line| line.trim().is_empty()) {
result.push(String::new());
}
result.push(header);
result.push(assignment);
} else if !inserted {
result.push(assignment);
}
result.join("\n") + "\n"
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn upsert_top_level_bool_replaces_existing_value() {
let content = "onboarding = true\n[keys]\nprefix = \"ctrl+b\"\n";
let updated = upsert_top_level_bool(content, "onboarding", false);
assert!(updated.contains("onboarding = false"));
assert!(!updated.contains("onboarding = true"));
}
#[test]
fn upsert_section_bool_adds_missing_section() {
let updated = upsert_section_bool("", "ui.toast", "enabled", true);
assert!(updated.contains("[ui.toast]"));
assert!(updated.contains("enabled = true"));
}
#[test]
fn remove_section_key_removes_matching_key_from_section() {
let content =
"[ui.toast]\nenabled = true\ndelivery = \"herdr\"\n[ui.sound]\nenabled = true\n";
let updated = remove_section_key(content, "ui.toast", "enabled");
assert!(!updated.contains("[ui.toast]\nenabled = true"));
assert!(updated.contains("delivery = \"herdr\""));
assert!(updated.contains("[ui.sound]\nenabled = true"));
}
#[test]
fn config_diagnostic_summary_uses_compact_actionable_banner() {
let diagnostics = vec![
"one".to_string(),
"two".to_string(),
"three".to_string(),
"four".to_string(),
"five".to_string(),
];
assert_eq!(
config_diagnostic_summary(&diagnostics).as_deref(),
Some("config.toml; herdr config check")
);
}
#[test]
fn config_diagnostic_summary_reports_unknown_keys_compactly() {
let diagnostics = vec![
"unknown config key ui.mouse_captur; ignoring key".to_string(),
"unknown config key keys.new_tabb; ignoring key".to_string(),
];
assert_eq!(
config_diagnostic_summary(&diagnostics).as_deref(),
Some("config.toml has unknown keys; herdr config check")
);
}
#[test]
fn config_diagnostic_summary_keeps_mixed_diagnostics_generic() {
let diagnostics = vec![
"invalid ui config: invalid type: string; keeping current ui settings".to_string(),
"unknown config key keys.new_tabb; ignoring key".to_string(),
];
assert_eq!(
config_diagnostic_summary(&diagnostics).as_deref(),
Some("config.toml; herdr config check")
);
}
#[test]
fn config_diagnostic_summary_reports_default_fallback() {
let diagnostics = vec![
"config parse error: TOML parse error at line 33, column 8\n |\n33 | type = \"popup\"\n | ^^^^^^^\nunknown variant `popup`; using defaults"
.to_string(),
];
assert_eq!(
config_diagnostic_summary(&diagnostics).as_deref(),
Some("config.toml invalid; using defaults; herdr config check")
);
}
#[test]
fn config_diagnostic_summary_reports_unreadable_config_impact() {
let startup = vec!["config read error: permission denied; using defaults".to_string()];
assert_eq!(
config_diagnostic_summary(&startup).as_deref(),
Some("config.toml unreadable; using defaults; herdr config check")
);
let reload =
vec!["config read error: permission denied; keeping current config".to_string()];
assert_eq!(
config_diagnostic_summary(&reload).as_deref(),
Some("config.toml unreadable; keeping current config; herdr config check")
);
}
#[test]
fn config_diagnostic_summary_reports_retained_live_config() {
let diagnostics = vec![
"config parse error: TOML parse error at line 7, column 4; keeping current config"
.to_string(),
];
assert_eq!(
config_diagnostic_summary(&diagnostics).as_deref(),
Some("config.toml invalid; keeping current config; herdr config check")
);
}
#[test]
fn config_loaders_report_unreadable_path() {
let _guard = crate::config::test_config_env_lock().lock().unwrap();
let path =
std::env::temp_dir().join(format!("herdr-config-unreadable-{}", std::process::id()));
std::fs::create_dir_all(&path).unwrap();
std::env::set_var(CONFIG_PATH_ENV_VAR, &path);
let startup = Config::load();
assert!(startup
.diagnostics
.iter()
.any(|diagnostic| diagnostic.contains("config read error")
&& diagnostic.contains("using defaults")));
let reload = load_live_config().unwrap_err();
assert!(reload.iter().any(|diagnostic| {
diagnostic.contains("config read error")
&& diagnostic.contains("keeping current config")
}));
std::env::remove_var(CONFIG_PATH_ENV_VAR);
let _ = std::fs::remove_dir_all(path);
}
#[test]
fn load_live_config_parses_session_section() {
let loaded = load_live_config_from_str(
r#"
[session]
resume_agents_on_restore = true
"#,
)
.unwrap();
assert!(loaded.config.session.resume_agents_on_restore);
assert!(loaded.diagnostics.is_empty());
assert!(loaded.invalid_sections.is_empty());
}
#[test]
fn load_live_config_warns_about_unknown_theme_names() {
let loaded = load_live_config_from_str(
r#"
[theme]
name = "catppucin"
"#,
)
.unwrap();
assert_eq!(loaded.diagnostics.len(), 1);
assert!(loaded.diagnostics[0].contains("theme.name = \"catppucin\""));
}
#[test]
fn load_live_config_warns_about_unknown_top_level_sections() {
let loaded = load_live_config_from_str(
r#"
[toast]
delivery = "system"
[ui.toast]
delivery = "herdr"
"#,
)
.unwrap();
assert_eq!(
loaded.diagnostics,
vec!["unknown config section [toast]; did you mean [ui.toast]? ignoring section"]
);
assert!(loaded.invalid_sections.is_empty());
assert_eq!(
loaded.config.ui.toast.delivery,
super::super::ToastDelivery::Herdr
);
}
#[test]
fn load_live_config_warns_about_unknown_keys_and_applies_known_siblings() {
let loaded = load_live_config_from_str(
r##"
plugin = []
[theme.custom]
accentt = "#ffffff"
[advanced]
scrollback_lines = 42
[keys]
fullscreen = "prefix+z"
new_tabb = "prefix+t"
[[keys.command]]
key = "prefix+g"
command = "git status"
descrption = "status"
[ui]
mouse_capture = false
mouse_captur = true
"foo.bar" = true
"foo.?.bar" = false
[ui.toast]
enabled = true
delivry = "system"
[ui.sidebar.agents.rows_by_agent]
claude = [["terminal_title"]]
"##,
)
.unwrap();
assert_eq!(
loaded.diagnostics,
vec![
"unknown config key plugin; ignoring key",
"unknown config key theme.custom.accentt; ignoring key",
"unknown config key keys.command.0.descrption; ignoring key",
"unknown config key keys.new_tabb; ignoring key",
"unknown config key ui.\"foo.?.bar\"; ignoring key",
"unknown config key ui.\"foo.bar\"; ignoring key",
"unknown config key ui.mouse_captur; ignoring key",
"unknown config key ui.toast.delivry; ignoring key",
]
);
assert!(loaded.invalid_sections.is_empty());
assert_eq!(loaded.config.advanced.scrollback_limit_bytes, 42);
assert!(!loaded.config.ui.mouse_capture);
assert_eq!(
loaded.config.ui.toast.delivery,
super::super::ToastDelivery::Herdr
);
assert!(loaded
.config
.keybinds()
.zoom
.bindings
.iter()
.any(|binding| binding.label == "prefix+z"));
}
#[test]
fn load_live_config_accepts_legacy_agent_panel_scope_without_warning() {
let loaded = load_live_config_from_str(
r#"
[ui]
agent_panel_scope = "current"
agent_panel_sort = "priority"
"#,
)
.unwrap();
assert!(loaded.diagnostics.is_empty());
assert!(loaded.invalid_sections.is_empty());
assert_eq!(
loaded.config.ui.agent_panel_sort,
super::super::AgentPanelSortConfig::Priority
);
}
#[test]
fn load_live_config_discards_ignored_keys_from_an_invalid_section() {
let loaded = load_live_config_from_str(
r#"
[ui]
mouse_capture = "yes"
mouse_captur = true
"#,
)
.unwrap();
assert_eq!(loaded.diagnostics.len(), 1);
assert!(loaded.diagnostics[0].contains("invalid ui config"));
assert!(!loaded.diagnostics[0].starts_with("unknown config key"));
assert_eq!(loaded.invalid_sections, vec!["ui"]);
}
#[test]
fn startup_config_accepts_legacy_agent_panel_scope_without_warning() {
let _guard = crate::config::test_config_env_lock().lock().unwrap();
let path = std::env::temp_dir().join(format!(
"herdr-config-legacy-agent-panel-scope-{}.toml",
std::process::id()
));
std::fs::write(&path, "[ui]\nagent_panel_scope = \"all\"\n").unwrap();
std::env::set_var(CONFIG_PATH_ENV_VAR, &path);
let loaded = Config::load();
std::env::remove_var(CONFIG_PATH_ENV_VAR);
let _ = std::fs::remove_file(path);
assert!(loaded.diagnostics.is_empty(), "{:?}", loaded.diagnostics);
}
#[test]
fn startup_config_load_warns_about_unknown_top_level_sections() {
let _guard = crate::config::test_config_env_lock().lock().unwrap();
let path = std::env::temp_dir().join(format!(
"herdr-config-unknown-section-{}.toml",
std::process::id()
));
std::fs::write(
&path,
r#"
[[plugin]]
id = "example"
[ui.toast]
delivery = "system"
"#,
)
.unwrap();
std::env::set_var(CONFIG_PATH_ENV_VAR, &path);
let loaded = Config::load();
assert_eq!(
loaded.diagnostics,
vec!["unknown config section [[plugin]]; ignoring section"]
);
assert_eq!(
loaded.config.ui.toast.delivery,
super::super::ToastDelivery::System
);
std::env::remove_var(CONFIG_PATH_ENV_VAR);
let _ = std::fs::remove_file(path);
}
#[test]
fn remove_keybinding_config_sections_removes_keys_tables_only() {
let content = r#"onboarding = false
[theme]
name = "catppuccin"
[keys]
prefix = "ctrl+a"
new_tab = "c"
[[keys.command]]
key = "g"
command = "lazygit"
[keys.indexed]
tabs = "ctrl"
[ui]
mouse_capture = false
"#;
let (updated, removed) = remove_keybinding_config_sections(content);
assert!(removed);
assert!(updated.contains("onboarding = false"));
assert!(updated.contains("[theme]\nname = \"catppuccin\""));
assert!(updated.contains("[ui]\nmouse_capture = false"));
assert!(!updated.contains("[keys]"));
assert!(!updated.contains("[[keys.command]]"));
assert!(!updated.contains("[keys.indexed]"));
assert!(toml::from_str::<toml::Value>(&updated).is_ok());
}
#[test]
fn remove_keybinding_config_sections_reports_noop_without_keys() {
let content = "[ui]\nmouse_capture = true\n";
let (updated, removed) = remove_keybinding_config_sections(content);
assert!(!removed);
assert_eq!(updated, content);
}
#[test]
fn normalize_utf8_bom_removes_a_leading_bom() {
let content = "\u{feff}onboarding = false\n[terminal]\n";
assert_eq!(
normalize_utf8_bom(content),
"onboarding = false\n[terminal]\n"
);
}
#[test]
fn normalize_utf8_bom_recovers_from_a_displaced_mid_file_bom() {
let content = "onboarding = false\n\u{feff}[terminal]\ndefault_shell = \"pwsh.exe\"\n";
let normalized = normalize_utf8_bom(content);
assert_eq!(
normalized,
"onboarding = false\n[terminal]\ndefault_shell = \"pwsh.exe\"\n"
);
assert!(normalized.parse::<toml::Value>().is_ok());
}
#[test]
fn normalize_utf8_bom_preserves_boms_in_multiline_basic_strings() {
let content = "[theme]\nname = \"\"\"\nfirst\n\u{feff}second\n\"\"\"\n";
assert!(content.parse::<toml::Value>().is_ok());
assert_eq!(normalize_utf8_bom(content), content);
}
#[test]
fn normalize_utf8_bom_preserves_boms_in_multiline_literal_strings() {
let content = "[theme]\nname = '''\nfirst\n\u{feff}second\n'''\n";
assert!(content.parse::<toml::Value>().is_ok());
assert_eq!(normalize_utf8_bom(content), content);
}
#[test]
fn normalize_utf8_bom_preserves_string_boms_despite_other_errors() {
let content = "[theme]\nname = \"\"\"\nfirst\n\u{feff}second\n\"\"\"\nbroken = \n";
assert!(content.parse::<toml::Value>().is_err());
assert_eq!(normalize_utf8_bom(content), content);
}
#[test]
fn config_load_recovers_from_a_mid_file_bom() {
let _guard = crate::config::test_config_env_lock().lock().unwrap();
let path = std::env::temp_dir().join(format!(
"herdr-config-mid-file-bom-{}.toml",
std::process::id()
));
std::fs::write(
&path,
b"onboarding = false\n\xEF\xBB\xBF[terminal]\ndefault_shell = \"pwsh.exe\"\n",
)
.unwrap();
std::env::set_var(CONFIG_PATH_ENV_VAR, &path);
let loaded = Config::load();
std::env::remove_var(CONFIG_PATH_ENV_VAR);
let _ = std::fs::remove_file(path);
assert!(loaded.diagnostics.is_empty(), "{:?}", loaded.diagnostics);
assert_eq!(loaded.config.terminal.default_shell, "pwsh.exe");
}
}
|