tess-cli 0.33.1

A less-style terminal pager for files, pipes, and live logs — with structured-log filtering, pretty-printing (JSON/YAML/TOML/XML/HTML/CSV), ANSI passthrough, multi-file navigation, and ctags jumping. Rust, macOS + Linux.
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
use std::collections::HashMap;
use std::path::PathBuf;

use regex::Regex;
use serde::Deserialize;

use crate::config_path;

/// A named log format: a regex with named capture groups identifying the
/// fields of one log line. Used by filtering to look up field values by name.
#[derive(Debug)]
pub struct LogFormat {
    pub name: String,
    pub regex: Regex,
    /// Capture group names declared in the regex, in declaration order.
    /// Used by `--list-formats` to show users what fields are available.
    pub field_names: Vec<String>,
    /// Optional default display template (`display` key in formats.toml).
    /// When set and no CLI override is given, the viewer / batch output
    /// renders each parsed line through this template instead of the raw line.
    pub display: Option<DisplayTemplate>,
    pub record_start: Option<Regex>,
    /// Optional default status-line prompt template (`prompt` key in formats.toml).
    /// When set and no `--prompt` CLI flag is given, the viewport renders the
    /// status line through this template instead of the built-in default.
    pub prompt: Option<crate::prompt::ParsedPrompt>,
    /// Optional default style for the status row when this format's prompt
    /// is active. Per-format value; CLI `--prompt-style` overrides.
    pub prompt_style: Option<crate::ansi::Style>,
    pub(crate) source: crate::config_path::ConfigSource,
    pub(crate) overrides: Option<crate::config_path::ConfigSource>,
}

impl LogFormat {
    pub fn compile(name: &str, pattern: &str) -> Result<Self, String> {
        Self::compile_full(name, pattern, None, None, None)
    }

    pub fn compile_with_display(
        name: &str,
        pattern: &str,
        display: Option<&str>,
    ) -> Result<Self, String> {
        Self::compile_full(name, pattern, display, None, None)
    }

    pub fn compile_full(
        name: &str,
        pattern: &str,
        display: Option<&str>,
        record_start: Option<&str>,
        prompt: Option<&str>,
    ) -> Result<Self, String> {
        let regex = Regex::new(pattern).map_err(|e| format!("format `{name}`: {e}"))?;
        let field_names: Vec<String> = regex
            .capture_names()
            .flatten()
            .map(|s| s.to_string())
            .collect();
        if field_names.is_empty() {
            return Err(format!(
                "format `{name}`: regex must declare at least one named capture group"
            ));
        }
        let display = display
            .map(|s| {
                DisplayTemplate::compile(s, &field_names)
                    .map_err(|e| format!("format `{name}`: display: {e}"))
            })
            .transpose()?;
        let record_start = record_start
            .map(|s| Regex::new(s).map_err(|e| format!("format `{name}`: record_start: {e}")))
            .transpose()?;
        let prompt = prompt
            .map(|s| crate::prompt::ParsedPrompt::parse(s)
                .map_err(|e| format!("format `{name}`: prompt: {e}")))
            .transpose()?;
        Ok(Self {
            name: name.to_string(),
            regex,
            field_names,
            display,
            record_start,
            prompt,
            prompt_style: None,
            source: crate::config_path::ConfigSource::Builtin,
            overrides: None,
        })
    }
}

/// Parsed display template (`display = '[<ts>] <level> <msg>'`).
///
/// Syntax:
/// - `<fieldname>` — replaced with the field's captured value (empty if
///   the regex didn't capture it on this line).
/// - `\<` — literal `<`.
/// - `\\` — literal `\`.
/// - Anything else — literal.
#[derive(Debug, Clone)]
pub struct DisplayTemplate {
    segments: Vec<DisplaySegment>,
    source: String,
}

#[derive(Debug, Clone)]
enum DisplaySegment {
    Literal(String),
    Field(String),
}

impl DisplayTemplate {
    pub fn compile(source: &str, field_names: &[String]) -> Result<Self, String> {
        if source.is_empty() {
            return Err("template is empty (would render every line as nothing)".to_string());
        }
        let mut segments: Vec<DisplaySegment> = Vec::new();
        let mut buf = String::new();
        let mut chars = source.chars().peekable();
        while let Some(c) = chars.next() {
            match c {
                '\\' => match chars.next() {
                    Some('<') => buf.push('<'),
                    Some('\\') => buf.push('\\'),
                    Some('n') => buf.push('\n'),
                    Some('t') => buf.push('\t'),
                    Some('r') => buf.push('\r'),
                    Some('e') => buf.push('\x1b'),
                    Some('x') => {
                        let h1 = chars.next().ok_or_else(|| "incomplete `\\xHH` escape".to_string())?;
                        let h2 = chars.next().ok_or_else(|| "incomplete `\\xHH` escape".to_string())?;
                        let hex: String = [h1, h2].iter().collect();
                        let byte = u8::from_str_radix(&hex, 16)
                            .map_err(|_| format!("invalid `\\x{hex}` escape"))?;
                        buf.push(byte as char);
                    }
                    Some('0') => {
                        let d1 = chars.next().ok_or_else(|| "incomplete `\\NNN` escape".to_string())?;
                        let d2 = chars.next().ok_or_else(|| "incomplete `\\NNN` escape".to_string())?;
                        let oct: String = ['0', d1, d2].iter().collect();
                        let byte = u8::from_str_radix(&oct, 8)
                            .map_err(|_| format!("invalid `\\{oct}` escape"))?;
                        buf.push(byte as char);
                    }
                    Some(other) => {
                        // Unknown escape: keep both bytes literally so users
                        // don't have to escape every backslash in regex-like
                        // strings.
                        buf.push('\\');
                        buf.push(other);
                    }
                    None => return Err("template ends with a lone `\\`".to_string()),
                },
                '<' => {
                    if !buf.is_empty() {
                        segments.push(DisplaySegment::Literal(std::mem::take(&mut buf)));
                    }
                    let mut name = String::new();
                    let mut closed = false;
                    while let Some(&nc) = chars.peek() {
                        chars.next();
                        if nc == '>' { closed = true; break; }
                        name.push(nc);
                    }
                    if !closed {
                        return Err(format!("unterminated `<` (expected `<{name}>`)"));
                    }
                    if name.is_empty() {
                        return Err("empty field reference `<>`".to_string());
                    }
                    if !field_names.iter().any(|n| n == &name) {
                        return Err(format!(
                            "unknown field `{name}` (available: {})",
                            field_names.join(", ")
                        ));
                    }
                    segments.push(DisplaySegment::Field(name));
                }
                _ => buf.push(c),
            }
        }
        if !buf.is_empty() {
            segments.push(DisplaySegment::Literal(buf));
        }
        Ok(Self { segments, source: source.to_string() })
    }

    /// Render the template against a captures-lookup closure. Returns the
    /// rendered string. Missing fields render as empty.
    pub fn render(&self, lookup: impl Fn(&str) -> Option<String>) -> String {
        let mut out = String::new();
        for seg in &self.segments {
            match seg {
                DisplaySegment::Literal(s) => out.push_str(s),
                DisplaySegment::Field(name) => {
                    if let Some(v) = lookup(name) { out.push_str(&v); }
                }
            }
        }
        out
    }

    pub fn source(&self) -> &str { &self.source }
}

/// Pairs a `DisplayTemplate` with the format's regex so callers can render
/// any single line in one call. Owns its inputs so it's `Send`-friendly.
#[derive(Debug, Clone)]
pub struct DisplayRenderer {
    template: DisplayTemplate,
    regex: Regex,
}

impl DisplayRenderer {
    pub fn new(template: DisplayTemplate, regex: Regex) -> Self {
        Self { template, regex }
    }

    pub fn template(&self) -> &DisplayTemplate { &self.template }

    /// Render `line` (raw bytes) through the template. If the line doesn't
    /// parse against the format regex, returns `None` — the caller decides
    /// whether to fall back to the raw line, skip it, or show an error.
    pub fn render_line(&self, line: &[u8]) -> Option<String> {
        let s = std::str::from_utf8(line).ok()?;
        let caps = self.regex.captures(s)?;
        Some(self.template.render(|name| {
            caps.name(name).map(|m| m.as_str().to_string())
        }))
    }
}

/// TOML schema for `~/.config/tess/formats.toml`:
///
/// ```toml
/// [format.myapp]
/// regex = "..."
///
/// [group.errorlog]
/// format = "myapp"
/// file = "/var/log/app.log"
/// follow = true
/// filter = ["level=ERROR"]
/// ```
#[derive(Debug, Default, Deserialize)]
struct UserConfig {
    #[serde(default)]
    format: HashMap<String, FormatEntry>,
    #[serde(default)]
    group: HashMap<String, GroupEntry>,
}

#[derive(Debug, Deserialize)]
struct FormatEntry {
    regex: String,
    #[serde(default)]
    display: Option<String>,
    #[serde(default)]
    record_start: Option<String>,
    #[serde(default)]
    prompt: Option<String>,
    /// Optional style for the status row when this format is active and a
    /// custom prompt is rendered. Parsed via `crate::style_spec`. CLI
    /// `--prompt-style` overrides this.
    #[serde(default)]
    prompt_style: Option<String>,
}

/// Raw group entry as deserialized from TOML. Promoted to `Group` after
/// validation.
#[derive(Debug, Deserialize, Default)]
struct GroupEntry {
    format: Option<String>,
    file: Option<String>,
    follow: Option<bool>,
    tail: Option<usize>,
    head: Option<usize>,
    dim: Option<bool>,
    line_numbers: Option<bool>,
    chop: Option<bool>,
    tab_width: Option<u8>,
    #[serde(default)]
    filter: Vec<String>,
    #[serde(default)]
    grep: Vec<String>,
}

/// A user-defined CLI shortcut. When `tess --<group_name>` appears in argv,
/// the group's flags are expanded inline and remaining positionals become
/// `--filter` arguments.
#[derive(Debug, Clone, Default)]
pub struct Group {
    pub name: String,
    pub format: Option<String>,
    pub file: Option<String>,
    pub follow: bool,
    pub tail: Option<usize>,
    pub head: Option<usize>,
    pub dim: bool,
    pub line_numbers: bool,
    pub chop: bool,
    pub tab_width: Option<u8>,
    pub filter: Vec<String>,
    pub grep: Vec<String>,
    // Populated by the layered loader to track which config layer a group came
    // from (and what it overrode); reserved for group source annotation in
    // `--list-formats`. Not yet read, hence the allow.
    #[allow(dead_code)]
    pub(crate) source: crate::config_path::ConfigSource,
    #[allow(dead_code)]
    pub(crate) overrides: Option<crate::config_path::ConfigSource>,
}

/// Long-form names of every built-in clap flag. A group cannot reuse one of
/// these names — it would shadow the real flag at expansion time.
const RESERVED_LONG_FLAGS: &[&str] = &[
    "format",
    "filter",
    "grep",
    "dim",
    "head",
    "tail",
    "follow",
    "LINE-NUMBERS",
    "chop-long-lines",
    "tab-width",
    "list-formats",
    "live",
    "manual",
    "examples",
    "prettify",
    "content-type",
    "help",
    "version",
    "record-start",
    "hex",
    "prompt",
    "preprocess",
    "no-preprocess",
    "no-color",
    "raw-control-chars",
    "tag",
    "tag-file",
];

/// Built-in formats compiled from this list of (name, pattern). Patterns use
/// raw strings so backslashes don't need escaping.
const BUILTINS: &[(&str, &str)] = &[
    (
        "apache-common",
        r#"^(?P<ip>\S+) \S+ (?P<user>\S+) \[(?P<time>[^\]]+)\] "(?P<method>\S+) (?P<url>\S+) (?P<protocol>[^"]+)" (?P<status>\d+) (?P<size>\S+)$"#,
    ),
    (
        "apache-combined",
        r#"^(?P<ip>\S+) \S+ (?P<user>\S+) \[(?P<time>[^\]]+)\] "(?P<method>\S+) (?P<url>\S+) (?P<protocol>[^"]+)" (?P<status>\d+) (?P<size>\S+) "(?P<referer>[^"]*)" "(?P<agent>[^"]*)"$"#,
    ),
    (
        "nginx-combined",
        r#"^(?P<ip>\S+) - (?P<user>\S+) \[(?P<time>[^\]]+)\] "(?P<method>\S+) (?P<url>\S+) (?P<protocol>[^"]+)" (?P<status>\d+) (?P<size>\S+) "(?P<referer>[^"]*)" "(?P<agent>[^"]*)"$"#,
    ),
];

fn formats_path_in(dir: &std::path::Path) -> PathBuf {
    dir.join("formats.toml")
}

/// Parsed contents of both global and local `formats.toml`. Empty
/// `UserConfig` represents "layer absent or unreadable".
#[derive(Debug, Default)]
struct LayeredConfig {
    global: UserConfig,
    local: UserConfig,
}

fn read_formats_toml(path: &std::path::Path) -> Result<UserConfig, String> {
    let text = std::fs::read_to_string(path)
        .map_err(|e| format!("reading {}: {e}", path.display()))?;
    toml::from_str(&text)
        .map_err(|e| format!("parsing {}: {e}", path.display()))
}

fn load_layered_config() -> Result<LayeredConfig, String> {
    let mut layered = LayeredConfig::default();

    // Global: warn-and-continue on parse error.
    if let Some(dir) = config_path::global_config_dir() {
        let path = formats_path_in(&dir);
        if path.exists() {
            match read_formats_toml(&path) {
                Ok(cfg) => layered.global = cfg,
                Err(e) => eprintln!(
                    "tess: warning: {e}; ignoring global config"
                ),
            }
        }
    }

    // Local: fail-startup on parse error (unchanged behavior).
    if let Some(dir) = config_path::user_config_dir() {
        let path = formats_path_in(&dir);
        if path.exists() {
            layered.local = read_formats_toml(&path)?;
        }
    }

    Ok(layered)
}

struct FormatSource {
    regex: String,
    display: Option<String>,
    record_start: Option<String>,
    prompt: Option<String>,
    prompt_style: Option<String>,
    source: crate::config_path::ConfigSource,
    overrides: Option<crate::config_path::ConfigSource>,
}

fn load_user_formats() -> Result<HashMap<String, FormatSource>, String> {
    let cfg = load_layered_config()?;
    let mut out: HashMap<String, FormatSource> = HashMap::new();
    for (k, v) in cfg.global.format {
        out.insert(k, FormatSource {
            regex: v.regex,
            display: v.display,
            record_start: v.record_start,
            prompt: v.prompt,
            prompt_style: v.prompt_style,
            source: crate::config_path::ConfigSource::Global,
            overrides: None,
        });
    }
    for (k, v) in cfg.local.format {
        let overrides = out.get(&k).map(|prev| prev.source);
        out.insert(k, FormatSource {
            regex: v.regex,
            display: v.display,
            record_start: v.record_start,
            prompt: v.prompt,
            prompt_style: v.prompt_style,
            source: crate::config_path::ConfigSource::Local,
            overrides,
        });
    }
    Ok(out)
}

/// Load all user-defined groups from global and local `formats.toml`. Built-ins
/// are not provided — groups are entirely user-defined. Validates that group
/// names don't shadow built-in flag names.
pub fn load_groups() -> Result<HashMap<String, Group>, String> {
    let cfg = load_layered_config()?;

    struct StagedGroup {
        entry: GroupEntry,
        source: crate::config_path::ConfigSource,
        overrides: Option<crate::config_path::ConfigSource>,
    }

    let mut staged: HashMap<String, StagedGroup> = HashMap::new();
    for (k, v) in cfg.global.group {
        staged.insert(k, StagedGroup {
            entry: v,
            source: crate::config_path::ConfigSource::Global,
            overrides: None,
        });
    }
    for (k, v) in cfg.local.group {
        let overrides = staged.get(&k).map(|prev| prev.source);
        staged.insert(k, StagedGroup {
            entry: v,
            source: crate::config_path::ConfigSource::Local,
            overrides,
        });
    }

    let mut out = HashMap::with_capacity(staged.len());
    for (name, sg) in staged {
        if RESERVED_LONG_FLAGS.contains(&name.as_str()) {
            return Err(format!(
                "group `{name}`: name collides with built-in --{name} flag"
            ));
        }
        out.insert(
            name.clone(),
            Group {
                name,
                format: sg.entry.format,
                file: sg.entry.file,
                follow: sg.entry.follow.unwrap_or(false),
                tail: sg.entry.tail,
                head: sg.entry.head,
                dim: sg.entry.dim.unwrap_or(false),
                line_numbers: sg.entry.line_numbers.unwrap_or(false),
                chop: sg.entry.chop.unwrap_or(false),
                tab_width: sg.entry.tab_width,
                filter: sg.entry.filter,
                grep: sg.entry.grep,
                source: sg.source,
                overrides: sg.overrides,
            },
        );
    }
    Ok(out)
}

/// Load all formats: built-ins first, then any in `~/.config/tess/formats.toml`
/// (which override built-ins of the same name). Returns the compiled map keyed
/// by format name.
pub fn load_all() -> Result<HashMap<String, LogFormat>, String> {
    let mut sources: HashMap<String, FormatSource> = HashMap::new();
    for (name, pat) in BUILTINS {
        sources.insert(name.to_string(), FormatSource {
            regex: pat.to_string(),
            display: None,
            record_start: None,
            prompt: None,
            prompt_style: None,
            source: crate::config_path::ConfigSource::Builtin,
            overrides: None,
        });
    }
    let user = load_user_formats()?;
    for (name, mut src) in user {
        // load_user_formats doesn't know about built-ins, so we detect
        // direct built-in shadowing here. If `src.overrides` is already
        // set, local was shadowing global — leave that alone.
        if src.overrides.is_none() && sources.contains_key(&name) {
            src.overrides = Some(crate::config_path::ConfigSource::Builtin);
        }
        sources.insert(name, src);
    }
    let mut compiled = HashMap::new();
    for (name, src) in sources {
        let mut fmt = LogFormat::compile_full(
            &name,
            &src.regex,
            src.display.as_deref(),
            src.record_start.as_deref(),
            src.prompt.as_deref(),
        )?;
        if let Some(spec) = src.prompt_style.as_deref() {
            fmt.prompt_style = Some(
                crate::style_spec::parse(spec)
                    .map_err(|e| format!("format `{name}`: prompt_style: {e}"))?,
            );
        }
        fmt.source = src.source;
        fmt.overrides = src.overrides;
        compiled.insert(name, fmt);
    }
    Ok(compiled)
}

/// Pre-process an argv vector before clap sees it. For every `--<name>`
/// token that matches a defined group, expand the group's flags inline and
/// switch into "filter mode" — bare positionals after the group token become
/// `--filter <arg>` pairs. Group tokens before any flag still expand
/// correctly; positionals before a group remain as-is.
///
/// CLI flags coming after the expansion override the group's values for
/// `Option<T>` flags (clap takes the last occurrence) and add to repeatable
/// flags like `--filter` (clap accumulates the `Vec<String>`).
/// Long flags that take a separate value as the next argv token (e.g.
/// `--tail 1000` rather than `--tail=1000`). Used by `expand_argv` so it
/// doesn't mistake a flag's value for a positional.
const VALUE_TAKING_LONG_FLAGS: &[&str] = &[
    "--format",
    "--filter",
    "--grep",
    "--head",
    "--tail",
    "--tab-width",
    "--record-start",
];

pub fn expand_argv(argv: Vec<String>, groups: &HashMap<String, Group>) -> Vec<String> {
    if argv.is_empty() {
        return argv;
    }
    let mut out = Vec::with_capacity(argv.len() * 2);
    let mut iter = argv.into_iter();
    out.push(iter.next().unwrap()); // argv[0] = program name
    let mut filter_mode = false;
    let mut pass_next = false;
    for arg in iter {
        if pass_next {
            pass_next = false;
            out.push(arg);
            continue;
        }
        if let Some(name) = arg.strip_prefix("--") {
            // `--flag=value` is a single token: don't try to match groups
            // against `flag=value`.
            if !name.contains('=') {
                if let Some(g) = groups.get(name) {
                    expand_group(g, &mut out);
                    filter_mode = true;
                    continue;
                }
                if VALUE_TAKING_LONG_FLAGS.contains(&arg.as_str()) {
                    // The next token is this flag's value; pass it through
                    // even in filter mode.
                    out.push(arg);
                    pass_next = true;
                    continue;
                }
            }
        }
        if filter_mode && !arg.starts_with('-') {
            out.push("--filter".into());
            out.push(arg);
            continue;
        }
        out.push(arg);
    }
    out
}

fn expand_group(g: &Group, out: &mut Vec<String>) {
    if let Some(format) = &g.format {
        out.push("--format".into());
        out.push(format.clone());
    }
    if g.follow {
        out.push("--follow".into());
    }
    if let Some(t) = g.tail {
        out.push("--tail".into());
        out.push(t.to_string());
    }
    if let Some(h) = g.head {
        out.push("--head".into());
        out.push(h.to_string());
    }
    if g.dim {
        out.push("--dim".into());
    }
    if g.line_numbers {
        out.push("-N".into());
    }
    if g.chop {
        out.push("-S".into());
    }
    if let Some(t) = g.tab_width {
        out.push("--tab-width".into());
        out.push(t.to_string());
    }
    for f in &g.filter {
        out.push("--filter".into());
        out.push(f.clone());
    }
    for g_pat in &g.grep {
        out.push("--grep".into());
        out.push(g_pat.clone());
    }
    if let Some(file) = &g.file {
        out.push(file.clone());
    }
}

/// Render the bracketed source annotation for a format. The `overrides`
/// argument is the immediately-replaced layer produced by `load_all`.
fn format_source_label(
    source: crate::config_path::ConfigSource,
    overrides: Option<crate::config_path::ConfigSource>,
) -> String {
    use crate::config_path::ConfigSource::*;
    let layer = match source {
        Builtin => "built-in",
        Global => "global",
        Local => "local",
    };
    match overrides {
        None => format!("[{layer}]"),
        Some(Builtin) => format!("[{layer}, overrides built-in]"),
        Some(Global) => format!("[{layer}, overrides global]"),
        // Lower layers can't replace local; this arm is unreachable in
        // practice but kept for total-match completeness.
        Some(Local) => format!("[{layer}, overrides local]"),
    }
}

/// Print one line per format, with the named field list and source
/// label, to stdout. Used by `--list-formats`.
pub fn print_format_list(formats: &HashMap<String, LogFormat>) {
    let mut names: Vec<&String> = formats.keys().collect();
    names.sort();

    // Column-align names for readability when field lists vary.
    let name_width = names.iter().map(|n| n.len()).max().unwrap_or(0);

    for name in names {
        let fmt = &formats[name];
        let fields: Vec<&str> = fmt.field_names.iter().map(|s| s.as_str()).collect();
        let label = format_source_label(fmt.source, fmt.overrides);
        println!(
            "{:<width$}  {}  {}",
            name,
            label,
            fields.join(", "),
            width = name_width
        );
    }
}

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

    /// Serializes tests that mutate the `HOME` env var; otherwise they
    /// trample each other when cargo runs tests in parallel.
    static HOME_LOCK: Mutex<()> = Mutex::new(());

    #[test]
    fn builtins_all_compile() {
        for (name, pat) in BUILTINS {
            LogFormat::compile(name, pat)
                .unwrap_or_else(|e| panic!("built-in {name} should compile: {e}"));
        }
    }

    // ----- DisplayTemplate -----

    fn fields() -> Vec<String> {
        vec!["ts".into(), "level".into(), "msg".into()]
    }

    #[test]
    fn display_template_compiles_basic() {
        let t = DisplayTemplate::compile("[<ts>] <level> <msg>", &fields()).unwrap();
        assert_eq!(t.source(), "[<ts>] <level> <msg>");
    }

    #[test]
    fn display_template_renders_substitutions() {
        let t = DisplayTemplate::compile("<level>: <msg>", &fields()).unwrap();
        let mut map = std::collections::HashMap::new();
        map.insert("level".to_string(), "ERROR".to_string());
        map.insert("msg".to_string(), "boom".to_string());
        let out = t.render(|n| map.get(n).cloned());
        assert_eq!(out, "ERROR: boom");
    }

    #[test]
    fn display_template_missing_field_renders_empty() {
        let t = DisplayTemplate::compile("<level>:<msg>", &fields()).unwrap();
        let mut map = std::collections::HashMap::new();
        map.insert("level".to_string(), "ERROR".to_string());
        // msg is absent
        let out = t.render(|n| map.get(n).cloned());
        assert_eq!(out, "ERROR:");
    }

    #[test]
    fn display_template_escape_sequences() {
        // Only `\<` and `\\` are recognized escapes; `>` is always literal
        // (a stray `>` outside `<...>` is fine).
        let t = DisplayTemplate::compile(r"\<not a field> <level>", &fields()).unwrap();
        let mut map = std::collections::HashMap::new();
        map.insert("level".to_string(), "X".to_string());
        let out = t.render(|n| map.get(n).cloned());
        assert_eq!(out, "<not a field> X");
    }

    #[test]
    fn display_template_escape_backslash() {
        let t = DisplayTemplate::compile(r"a\\b <level>", &fields()).unwrap();
        let mut map = std::collections::HashMap::new();
        map.insert("level".to_string(), "X".to_string());
        let out = t.render(|n| map.get(n).cloned());
        assert_eq!(out, r"a\b X");
    }

    #[test]
    fn display_template_escape_e_emits_esc() {
        let t = DisplayTemplate::compile(r"\e[31m<level>\e[0m", &fields()).unwrap();
        let mut map = std::collections::HashMap::new();
        map.insert("level".to_string(), "X".to_string());
        let out = t.render(|n| map.get(n).cloned());
        assert_eq!(out, "\x1b[31mX\x1b[0m");
    }

    #[test]
    fn display_template_escape_x1b_emits_esc() {
        let t = DisplayTemplate::compile(r"\x1b[1m<level>", &fields()).unwrap();
        let out = t.render(|_| Some("Y".to_string()));
        assert_eq!(out, "\x1b[1mY");
    }

    #[test]
    fn display_template_escape_octal_emits_esc() {
        let t = DisplayTemplate::compile(r"\033[1m<level>", &fields()).unwrap();
        let out = t.render(|_| Some("Z".to_string()));
        assert_eq!(out, "\x1b[1mZ");
    }

    #[test]
    fn display_template_escape_n_t_r() {
        let t = DisplayTemplate::compile(r"\n\t\r<level>", &fields()).unwrap();
        let out = t.render(|_| Some("Q".to_string()));
        assert_eq!(out, "\n\t\rQ");
    }

    #[test]
    fn display_template_escape_unknown_preserves_backslash() {
        let t = DisplayTemplate::compile(r"\q<level>", &fields()).unwrap();
        let out = t.render(|_| Some("Q".to_string()));
        assert_eq!(out, r"\qQ");
    }

    #[test]
    fn display_template_escape_x_incomplete_errors() {
        let err = DisplayTemplate::compile(r"\x1", &fields()).unwrap_err();
        assert!(err.contains("incomplete"), "{err}");
    }

    #[test]
    fn display_template_escape_invalid_hex_errors() {
        let err = DisplayTemplate::compile(r"\xZZ", &fields()).unwrap_err();
        assert!(err.contains("invalid"), "{err}");
    }

    #[test]
    fn display_template_rejects_empty() {
        let err = DisplayTemplate::compile("", &fields()).unwrap_err();
        assert!(err.contains("empty"), "{err}");
    }

    #[test]
    fn display_template_rejects_unknown_field() {
        let err = DisplayTemplate::compile("<bogus>", &fields()).unwrap_err();
        assert!(err.contains("unknown field"), "{err}");
    }

    #[test]
    fn display_template_rejects_unterminated() {
        let err = DisplayTemplate::compile("<level", &fields()).unwrap_err();
        assert!(err.contains("unterminated"), "{err}");
    }

    #[test]
    fn display_template_rejects_empty_ref() {
        let err = DisplayTemplate::compile("<>", &fields()).unwrap_err();
        assert!(err.contains("empty field reference"), "{err}");
    }

    #[test]
    fn apache_common_extracts_fields() {
        let fmt = LogFormat::compile("apache-common", BUILTINS[0].1).unwrap();
        let line = r#"127.0.0.1 - alice [10/Oct/2023:13:55:36 +0000] "GET /index.html HTTP/1.1" 200 2326"#;
        let caps = fmt.regex.captures(line).expect("should match");
        assert_eq!(&caps["ip"], "127.0.0.1");
        assert_eq!(&caps["user"], "alice");
        assert_eq!(&caps["method"], "GET");
        assert_eq!(&caps["url"], "/index.html");
        assert_eq!(&caps["status"], "200");
        assert_eq!(&caps["size"], "2326");
    }

    #[test]
    fn apache_combined_extracts_referer_and_agent() {
        let fmt = LogFormat::compile("apache-combined", BUILTINS[1].1).unwrap();
        let line = r#"10.1.2.3 - bob [10/Oct/2023:13:55:36 +0000] "POST /api/login HTTP/1.1" 401 512 "https://example.com/" "Mozilla/5.0""#;
        let caps = fmt.regex.captures(line).expect("should match");
        assert_eq!(&caps["status"], "401");
        assert_eq!(&caps["url"], "/api/login");
        assert_eq!(&caps["referer"], "https://example.com/");
        assert_eq!(&caps["agent"], "Mozilla/5.0");
    }

    #[test]
    fn field_names_listed_in_order() {
        let fmt = LogFormat::compile("apache-common", BUILTINS[0].1).unwrap();
        assert_eq!(
            fmt.field_names,
            vec!["ip", "user", "time", "method", "url", "protocol", "status", "size"]
        );
    }

    #[test]
    fn compile_rejects_regex_without_named_groups() {
        let err = LogFormat::compile("bare", r"^\d+$").unwrap_err();
        assert!(err.contains("at least one named capture"), "{err}");
    }

    #[test]
    fn compile_rejects_invalid_regex() {
        let err = LogFormat::compile("bad", r"(?P<x>[").unwrap_err();
        assert!(err.contains("bad"), "{err}");
    }

    #[test]
    fn load_groups_reads_user_config() {
        let _g = HOME_LOCK.lock().unwrap();
        let tmp = tempfile::tempdir().unwrap();
        let cfg_dir = tmp.path().join(".config").join("tess");
        std::fs::create_dir_all(&cfg_dir).unwrap();
        std::fs::write(
            cfg_dir.join("formats.toml"),
            r#"
[group.errorlog]
format = "apache-combined"
file = "/var/log/access.log"
follow = true
tail = 1000
filter = ["status~^5"]

[group.minimal]
file = "/tmp/x.log"
"#,
        )
        .unwrap();
        let saved = std::env::var_os("HOME");
        std::env::set_var("HOME", tmp.path());
        let result = load_groups();
        if let Some(h) = saved { std::env::set_var("HOME", h); } else { std::env::remove_var("HOME"); }
        let groups = result.unwrap();
        let err = &groups["errorlog"];
        assert_eq!(err.format.as_deref(), Some("apache-combined"));
        assert_eq!(err.file.as_deref(), Some("/var/log/access.log"));
        assert!(err.follow);
        assert_eq!(err.tail, Some(1000));
        assert_eq!(err.filter, vec!["status~^5".to_string()]);
        let min = &groups["minimal"];
        assert!(!min.follow);
        assert!(min.tail.is_none());
        assert_eq!(min.filter, Vec::<String>::new());
    }

    fn group(name: &str) -> Group {
        Group { name: name.into(), ..Group::default() }
    }

    fn argv(parts: &[&str]) -> Vec<String> {
        parts.iter().map(|s| s.to_string()).collect()
    }

    #[test]
    fn expand_argv_passes_through_when_no_group_matches() {
        let groups: HashMap<String, Group> = HashMap::new();
        let out = expand_argv(argv(&["tess", "-f", "log.txt"]), &groups);
        assert_eq!(out, argv(&["tess", "-f", "log.txt"]));
    }

    #[test]
    fn expand_argv_inserts_group_flags_and_file() {
        let mut groups: HashMap<String, Group> = HashMap::new();
        groups.insert(
            "errorlog".into(),
            Group {
                name: "errorlog".into(),
                format: Some("apache-combined".into()),
                file: Some("/var/log/access.log".into()),
                follow: true,
                tail: Some(1000),
                filter: vec!["status~^5".into()],
                ..Group::default()
            },
        );
        let out = expand_argv(argv(&["tess", "--errorlog"]), &groups);
        assert_eq!(
            out,
            argv(&[
                "tess",
                "--format", "apache-combined",
                "--follow",
                "--tail", "1000",
                "--filter", "status~^5",
                "/var/log/access.log",
            ])
        );
    }

    #[test]
    fn expand_argv_converts_positionals_to_filters_after_group() {
        let mut groups: HashMap<String, Group> = HashMap::new();
        groups.insert(
            "errorlog".into(),
            Group {
                name: "errorlog".into(),
                format: Some("apache-combined".into()),
                file: Some("/log".into()),
                ..Group::default()
            },
        );
        let out = expand_argv(
            argv(&["tess", "--errorlog", "msg~test", "url~/api/"]),
            &groups,
        );
        assert_eq!(
            out,
            argv(&[
                "tess",
                "--format", "apache-combined",
                "/log",
                "--filter", "msg~test",
                "--filter", "url~/api/",
            ])
        );
    }

    #[test]
    fn expand_argv_leaves_flags_alone_after_group() {
        let mut groups: HashMap<String, Group> = HashMap::new();
        groups.insert("errorlog".into(), group("errorlog"));
        let out = expand_argv(
            argv(&["tess", "--errorlog", "--tail", "50", "msg=hi"]),
            &groups,
        );
        // Group is empty so no insertion; --tail 50 stays; "msg=hi" becomes a filter.
        assert_eq!(
            out,
            argv(&["tess", "--tail", "50", "--filter", "msg=hi"])
        );
    }

    #[test]
    fn expand_argv_user_flag_after_group_can_override_tail() {
        // Group sets tail=1000, user passes --tail 50 after; clap takes last,
        // so user's 50 wins.
        let mut groups: HashMap<String, Group> = HashMap::new();
        groups.insert(
            "errorlog".into(),
            Group { name: "errorlog".into(), tail: Some(1000), ..Group::default() },
        );
        let out = expand_argv(argv(&["tess", "--errorlog", "--tail", "50"]), &groups);
        // --tail 1000 from group, then --tail 50 from user. Order preserved.
        assert!(out.windows(2).any(|w| w == ["--tail", "1000"]));
        assert!(out.windows(2).any(|w| w == ["--tail", "50"]));
        let pos_1000 = out.iter().position(|x| x == "1000").unwrap();
        let pos_50 = out.iter().position(|x| x == "50").unwrap();
        assert!(pos_1000 < pos_50, "user's value must come after group's");
    }

    #[test]
    fn expand_argv_treats_grep_value_as_flag_arg_not_filter() {
        let mut groups: HashMap<String, Group> = HashMap::new();
        groups.insert("errorlog".into(), group("errorlog"));
        let out = expand_argv(
            argv(&["tess", "--errorlog", "--grep", "timeout", "msg=hi"]),
            &groups,
        );
        // `timeout` is --grep's value, not a positional → not converted to --filter.
        assert_eq!(
            out,
            argv(&["tess", "--grep", "timeout", "--filter", "msg=hi"])
        );
    }

    #[test]
    fn expand_argv_unknown_double_dash_passes_through() {
        let groups: HashMap<String, Group> = HashMap::new();
        let out = expand_argv(argv(&["tess", "--unknown"]), &groups);
        assert_eq!(out, argv(&["tess", "--unknown"]));
    }

    #[test]
    fn load_groups_rejects_reserved_name() {
        let _g = HOME_LOCK.lock().unwrap();
        let tmp = tempfile::tempdir().unwrap();
        let cfg_dir = tmp.path().join(".config").join("tess");
        std::fs::create_dir_all(&cfg_dir).unwrap();
        std::fs::write(
            cfg_dir.join("formats.toml"),
            r#"
[group.follow]
file = "/x.log"
"#,
        )
        .unwrap();
        let saved = std::env::var_os("HOME");
        std::env::set_var("HOME", tmp.path());
        let result = load_groups();
        if let Some(h) = saved { std::env::set_var("HOME", h); } else { std::env::remove_var("HOME"); }
        let err = result.unwrap_err();
        assert!(err.contains("collides with built-in --follow"), "{err}");
    }

    #[test]
    fn user_config_overrides_builtin_via_load_all() {
        let _g = HOME_LOCK.lock().unwrap();
        // Use a temp HOME to avoid touching the real user's config.
        let tmp = tempfile::tempdir().unwrap();
        let cfg_dir = tmp.path().join(".config").join("tess");
        std::fs::create_dir_all(&cfg_dir).unwrap();
        let cfg_file = cfg_dir.join("formats.toml");
        std::fs::write(
            &cfg_file,
            r#"
[format.apache-common]
regex = "^(?P<custom>\\S+)$"
"#,
        )
        .unwrap();
        // Save and replace HOME for the duration of this test.
        let saved = std::env::var_os("HOME");
        std::env::set_var("HOME", tmp.path());
        let result = load_all();
        if let Some(h) = saved { std::env::set_var("HOME", h); } else { std::env::remove_var("HOME"); }
        let formats = result.unwrap();
        let common = &formats["apache-common"];
        assert_eq!(common.field_names, vec!["custom"], "user config should win");
    }

    #[test]
    fn format_entry_parses_record_start() {
        let toml_text = r#"
            [format.myapp]
            regex = '^(?P<line>.*)$'
            record_start = '^\['
        "#;
        let cfg: UserConfig = toml::from_str(toml_text).expect("parse");
        let entry = cfg.format.get("myapp").expect("myapp present");
        assert_eq!(entry.regex, "^(?P<line>.*)$");
        assert_eq!(entry.record_start.as_deref(), Some("^\\["));
    }

    #[test]
    fn format_entry_record_start_optional() {
        let toml_text = r#"
            [format.myapp]
            regex = '^(?P<line>.*)$'
        "#;
        let cfg: UserConfig = toml::from_str(toml_text).expect("parse");
        let entry = cfg.format.get("myapp").expect("myapp present");
        assert!(entry.record_start.is_none());
    }

    #[test]
    fn layered_loader_local_overrides_global() {
        let _guard = HOME_LOCK.lock().unwrap();
        let prev_home = std::env::var_os("HOME");
        let prev_global = std::env::var_os("TESS_GLOBAL_CONFIG_DIR");

        let home = tempfile::tempdir().unwrap();
        let global = tempfile::tempdir().unwrap();

        std::env::set_var("HOME", home.path());
        std::env::set_var("TESS_GLOBAL_CONFIG_DIR", global.path());

        std::fs::write(
            global.path().join("formats.toml"),
            r#"
[format.shared]
regex = "^GLOBAL (?P<msg>.+)$"

[format.both]
regex = "^GLOBAL_BOTH (?P<msg>.+)$"
"#,
        )
        .unwrap();

        let cfg_dir = home.path().join(".config").join("tess");
        std::fs::create_dir_all(&cfg_dir).unwrap();
        std::fs::write(
            cfg_dir.join("formats.toml"),
            r#"
[format.both]
regex = "^LOCAL_BOTH (?P<msg>.+)$"

[format.local-only]
regex = "^LOCAL (?P<msg>.+)$"
"#,
        )
        .unwrap();

        let cfg = load_layered_config().unwrap();

        // Global-only format survives.
        assert!(cfg.global.format.contains_key("shared"));
        assert!(!cfg.local.format.contains_key("shared"));

        // Same-name format: both layers carry it, merge step (next task)
        // is responsible for resolving. Here we just verify both files
        // parsed correctly.
        assert_eq!(
            cfg.global.format.get("both").unwrap().regex,
            "^GLOBAL_BOTH (?P<msg>.+)$"
        );
        assert_eq!(
            cfg.local.format.get("both").unwrap().regex,
            "^LOCAL_BOTH (?P<msg>.+)$"
        );

        // Local-only format present.
        assert!(cfg.local.format.contains_key("local-only"));

        match prev_home {
            Some(v) => std::env::set_var("HOME", v),
            None => std::env::remove_var("HOME"),
        }
        match prev_global {
            Some(v) => std::env::set_var("TESS_GLOBAL_CONFIG_DIR", v),
            None => std::env::remove_var("TESS_GLOBAL_CONFIG_DIR"),
        }
    }

    #[test]
    fn layered_loader_warns_on_bad_global_toml() {
        let _guard = HOME_LOCK.lock().unwrap();
        let prev_home = std::env::var_os("HOME");
        let prev_global = std::env::var_os("TESS_GLOBAL_CONFIG_DIR");

        let home = tempfile::tempdir().unwrap();
        let global = tempfile::tempdir().unwrap();

        std::env::set_var("HOME", home.path());
        std::env::set_var("TESS_GLOBAL_CONFIG_DIR", global.path());

        std::fs::write(
            global.path().join("formats.toml"),
            "this is not valid toml = = =",
        )
        .unwrap();

        // Should NOT error — global parse failures are warnings, not errors.
        let cfg = load_layered_config().unwrap();
        assert!(cfg.global.format.is_empty());
        assert!(cfg.global.group.is_empty());

        match prev_home {
            Some(v) => std::env::set_var("HOME", v),
            None => std::env::remove_var("HOME"),
        }
        match prev_global {
            Some(v) => std::env::set_var("TESS_GLOBAL_CONFIG_DIR", v),
            None => std::env::remove_var("TESS_GLOBAL_CONFIG_DIR"),
        }
    }

    #[test]
    fn layered_loader_fails_on_bad_local_toml() {
        let _guard = HOME_LOCK.lock().unwrap();
        let prev_home = std::env::var_os("HOME");
        let prev_global = std::env::var_os("TESS_GLOBAL_CONFIG_DIR");

        let home = tempfile::tempdir().unwrap();
        std::env::set_var("HOME", home.path());
        std::env::remove_var("TESS_GLOBAL_CONFIG_DIR");

        let cfg_dir = home.path().join(".config").join("tess");
        std::fs::create_dir_all(&cfg_dir).unwrap();
        std::fs::write(
            cfg_dir.join("formats.toml"),
            "this is not valid toml = = =",
        )
        .unwrap();

        let err = load_layered_config().unwrap_err();
        assert!(err.contains("formats.toml"), "got: {err}");

        match prev_home {
            Some(v) => std::env::set_var("HOME", v),
            None => std::env::remove_var("HOME"),
        }
        match prev_global {
            Some(v) => std::env::set_var("TESS_GLOBAL_CONFIG_DIR", v),
            None => std::env::remove_var("TESS_GLOBAL_CONFIG_DIR"),
        }
    }

    #[test]
    fn log_format_compile_full_with_record_start() {
        let fmt = LogFormat::compile_full(
            "test",
            r"^(?P<msg>.+)$",
            None,
            Some(r"^\["),
            None,
        ).expect("compile");
        assert!(fmt.record_start.is_some());
        assert!(fmt.record_start.as_ref().unwrap().is_match("[2026-05-15"));
        assert!(!fmt.record_start.as_ref().unwrap().is_match("  continuation"));
    }

    #[test]
    fn log_format_compile_full_bad_record_start_errors() {
        let err = LogFormat::compile_full(
            "test",
            r"^(?P<msg>.+)$",
            None,
            Some(r"["),  // unclosed bracket
            None,
        ).expect_err("should fail");
        assert!(err.contains("record_start"), "error mentions record_start: {err}");
    }

    #[test]
    fn group_with_grep_field_deserializes() {
        let toml_text = r#"
            [group.errorlog]
            format = "app"
            grep = ["timeout", "deadlock"]
        "#;
        let cfg: UserConfig = toml::from_str(toml_text).expect("parse");
        let entry = cfg.group.get("errorlog").expect("errorlog present");
        assert_eq!(entry.grep, vec!["timeout".to_string(), "deadlock".to_string()]);
    }

    #[test]
    fn expand_argv_emits_group_grep_flags() {
        let mut groups = HashMap::new();
        groups.insert("errorlog".to_string(), Group {
            name: "errorlog".to_string(),
            grep: vec!["timeout".to_string(), "deadlock".to_string()],
            ..Default::default()
        });
        let out = expand_argv(
            argv(&["tess", "--errorlog", "logs.txt"]),
            &groups,
        );
        let joined = out.join(" ");
        assert!(joined.contains("--grep timeout"), "got: {joined}");
        assert!(joined.contains("--grep deadlock"), "got: {joined}");
    }

    #[test]
    fn user_grep_after_group_accumulates() {
        let mut groups = HashMap::new();
        groups.insert("errorlog".to_string(), Group {
            name: "errorlog".to_string(),
            grep: vec!["timeout".to_string()],
            ..Default::default()
        });
        let out = expand_argv(
            argv(&["tess", "--errorlog", "--grep", "extra", "logs.txt"]),
            &groups,
        );
        let joined = out.join(" ");
        assert!(joined.contains("--grep timeout"));
        assert!(joined.contains("--grep extra"));
    }

    #[test]
    fn format_entry_parses_prompt() {
        let toml_text = r#"
            [format.myapp]
            regex = '^(?P<line>.*)$'
            prompt = '<label> <pct>%'
        "#;
        let cfg: UserConfig = toml::from_str(toml_text).expect("parse");
        let entry = cfg.format.get("myapp").expect("myapp present");
        assert_eq!(entry.prompt.as_deref(), Some("<label> <pct>%"));
    }

    #[test]
    fn load_all_tags_source_correctly() {
        let _guard = HOME_LOCK.lock().unwrap();
        let prev_home = std::env::var_os("HOME");
        let prev_global = std::env::var_os("TESS_GLOBAL_CONFIG_DIR");

        let home = tempfile::tempdir().unwrap();
        let global = tempfile::tempdir().unwrap();

        std::env::set_var("HOME", home.path());
        std::env::set_var("TESS_GLOBAL_CONFIG_DIR", global.path());

        std::fs::write(
            global.path().join("formats.toml"),
            r#"
[format.global-only]
regex = "^G (?P<msg>.+)$"

[format.both]
regex = "^GLOBAL (?P<msg>.+)$"
"#,
        )
        .unwrap();

        let cfg_dir = home.path().join(".config").join("tess");
        std::fs::create_dir_all(&cfg_dir).unwrap();
        std::fs::write(
            cfg_dir.join("formats.toml"),
            r#"
[format.local-only]
regex = "^L (?P<msg>.+)$"

[format.both]
regex = "^LOCAL (?P<msg>.+)$"
"#,
        )
        .unwrap();

        let all = load_all().unwrap();

        // Built-in still tagged builtin.
        assert_eq!(
            all["apache-common"].source,
            crate::config_path::ConfigSource::Builtin
        );
        assert!(all["apache-common"].overrides.is_none());

        // Global-only.
        assert_eq!(
            all["global-only"].source,
            crate::config_path::ConfigSource::Global
        );
        assert!(all["global-only"].overrides.is_none());

        // Local-only.
        assert_eq!(
            all["local-only"].source,
            crate::config_path::ConfigSource::Local
        );
        assert!(all["local-only"].overrides.is_none());

        // Same-name: local wins, marked as overriding global.
        assert_eq!(
            all["both"].source,
            crate::config_path::ConfigSource::Local
        );
        assert_eq!(
            all["both"].overrides,
            Some(crate::config_path::ConfigSource::Global)
        );

        match prev_home {
            Some(v) => std::env::set_var("HOME", v),
            None => std::env::remove_var("HOME"),
        }
        match prev_global {
            Some(v) => std::env::set_var("TESS_GLOBAL_CONFIG_DIR", v),
            None => std::env::remove_var("TESS_GLOBAL_CONFIG_DIR"),
        }
    }

    #[test]
    fn source_label_renders_correctly() {
        use crate::config_path::ConfigSource;
        assert_eq!(format_source_label(ConfigSource::Builtin, None), "[built-in]");
        assert_eq!(format_source_label(ConfigSource::Global, None), "[global]");
        assert_eq!(format_source_label(ConfigSource::Local, None), "[local]");
        assert_eq!(
            format_source_label(ConfigSource::Local, Some(ConfigSource::Global)),
            "[local, overrides global]"
        );
        assert_eq!(
            format_source_label(ConfigSource::Local, Some(ConfigSource::Builtin)),
            "[local, overrides built-in]"
        );
        assert_eq!(
            format_source_label(ConfigSource::Global, Some(ConfigSource::Builtin)),
            "[global, overrides built-in]"
        );
    }
}