freshl 0.20260603.1

Modern ls replacement with git awareness
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
// Copyright © 2026 Michael Shields
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#[cfg(not(unix))]
compile_error!("freshl targets POSIX file metadata and only builds on Unix.");

use std::collections::{HashMap, VecDeque};
use std::ffi::OsString;
use std::io::{self, Write};
use std::os::unix::ffi::OsStrExt;
use std::os::unix::fs::MetadataExt;
use std::path::{Path, PathBuf};
use std::process::ExitCode;
use std::time::SystemTime;

/// `(dev, ino)` — uniquely identifies a filesystem object across mounts.
/// Used by `list_recursive` to break self-referential cycles formed by
/// directory symlinks pointing back into their own ancestor chain.
type Inode = (u64, u64);

pub mod args;
pub mod case;
pub mod collect;
pub mod entry;
pub mod error;
pub mod format;
pub mod git;
pub mod owner;
pub mod sort;

use args::{Action, ListOptions, parse};
use case::{DetectorCache, ProbeDetector};
use entry::{Entry, EntryKind};
use error::Error;
use format::palette::Palette;
use format::{Row, build_row, compute_widths, render_row};
use git::{PorcelainCode, Snapshot, SnapshotCache};
use owner::{OwnerCache, SystemDirectory};

struct Caches {
    owners: OwnerCache<SystemDirectory>,
    sensitivity: DetectorCache<ProbeDetector>,
    snapshots: SnapshotCache,
    palette: Palette,
    /// Captured once per invocation so every row's mtime is dimmed against the
    /// same reference point — no skew if a long listing crosses a minute/hour
    /// boundary mid-render.
    now: SystemTime,
    /// Process umask captured at startup, used to decide which file/dir
    /// permissions are "boring" and should be dimmed.
    umask: u32,
}

impl Caches {
    fn new() -> Self {
        Self {
            owners: OwnerCache::new(SystemDirectory),
            sensitivity: DetectorCache::new(ProbeDetector),
            snapshots: SnapshotCache::new(),
            palette: Palette::from_env(),
            now: SystemTime::now(),
            umask: read_umask(),
        }
    }
}

/// POSIX `umask(2)` only has a set-and-return form, so read the current value
/// by setting it to a known mask and immediately restoring. Safe for freshl
/// because this runs once at startup before any thread is spawned that could
/// race a concurrent `open(2)`.
#[cfg_attr(
    target_os = "linux",
    expect(
        clippy::useless_conversion,
        reason = "`RawMode` is u32 on Linux but u16 on macOS/BSD; `.into()` widens uniformly across platforms"
    )
)]
fn read_umask() -> u32 {
    use rustix::fs::Mode;
    use rustix::process::umask;
    let prev = umask(Mode::from_bits_truncate(0o022));
    let _ = umask(prev);
    prev.bits().into()
}

#[must_use]
pub fn run<I>(raw: I, stdout: &mut dyn Write, stderr: &mut dyn Write) -> ExitCode
where
    I: IntoIterator<Item = OsString>,
{
    match dispatch(raw, stdout, stderr) {
        Ok(code) => code,
        Err(err) => {
            let _ = writeln!(stderr, "{err}");
            err.exit_code()
        }
    }
}

fn dispatch<I>(raw: I, stdout: &mut dyn Write, stderr: &mut dyn Write) -> Result<ExitCode, Error>
where
    I: IntoIterator<Item = OsString>,
{
    let action = parse(raw).map_err(|e| Error::Usage(e.message))?;
    match action {
        Action::Help => write_stdout(stdout, args::HELP.as_bytes()).map(|()| ExitCode::SUCCESS),
        Action::Version => write_stdout(stdout, format!("{}\n", args::version_line()).as_bytes())
            .map(|()| ExitCode::SUCCESS),
        Action::List { paths, options } => list(stdout, stderr, &paths, options),
    }
}

fn write_stdout(stdout: &mut dyn Write, bytes: &[u8]) -> Result<(), Error> {
    stdout.write_all(bytes).map_err(stdout_io)
}

fn list(
    stdout: &mut dyn Write,
    stderr: &mut dyn Write,
    paths: &[PathBuf],
    options: ListOptions,
) -> Result<ExitCode, Error> {
    let fallback = [PathBuf::from(".")];
    let targets: &[PathBuf] = if paths.is_empty() { &fallback } else { paths };
    // Under -R every directory gets a label so each block is identifiable in
    // the depth-first stream; otherwise only multi-target listings label.
    let label_dirs = options.recursive || targets.len() > 1;
    let mut had_error = false;
    let mut caches = Caches::new();

    // Split into a batch of files and a list of directories. Files render
    // together so column widths span all file arguments (matching `ls -l
    // file1 file2 …`); each directory then renders as its own block with
    // its own widths. With -d, directories are not expanded — they all go
    // into the files batch so they render as plain rows alongside any file
    // arguments.
    let mut files: Vec<Entry> = Vec::new();
    let mut dirs: Vec<Entry> = Vec::new();
    for target in targets {
        match collect::entry_for_path(target) {
            Ok(mut entry) => {
                // Display the user-supplied path so a `freshl /etc/passwd`
                // row reads `… /etc/passwd`, not just `passwd`, and so the
                // dir labels under -R / multi-target match what was typed.
                entry.name = target.as_os_str().to_os_string();
                if entry.kind == EntryKind::Directory && !options.directory {
                    dirs.push(entry);
                } else {
                    files.push(entry);
                }
            }
            Err(source) => {
                let _ = writeln!(
                    stderr,
                    "{}",
                    Error::Io {
                        path: target.clone(),
                        source,
                    }
                );
                had_error = true;
            }
        }
    }
    // Apply the requested sort key to top-level CLI args within each split.
    // No filesystem to probe for top-level args (they can span filesystems);
    // Sensitive is the natural default and only matters for the natural-name
    // tie-breaker.
    sort::sort_with(
        &mut files,
        case::Sensitivity::Sensitive,
        options.sort_key,
        options.reverse,
    );
    sort::sort_with(
        &mut dirs,
        case::Sensitivity::Sensitive,
        options.sort_key,
        options.reverse,
    );

    let mut have_output = !files.is_empty();
    if have_output {
        render_files(stdout, &files, &mut caches)?;
    }
    for dir_entry in &dirs {
        if have_output {
            writeln!(stdout).map_err(stdout_io)?;
        }
        let target = &dir_entry.path;
        let result = if options.recursive {
            list_recursive(stdout, stderr, target, options, &mut caches)
        } else {
            list_directory(stdout, stderr, target, label_dirs, options, &mut caches)
        };
        match result {
            Ok(target_had_error) => {
                had_error |= target_had_error;
                have_output = true;
            }
            Err(e @ Error::StdoutIo(_)) => return Err(e),
            Err(e) => {
                let _ = writeln!(stderr, "{e}");
                had_error = true;
            }
        }
    }
    Ok(if had_error {
        ExitCode::from(1)
    } else {
        ExitCode::SUCCESS
    })
}

fn list_directory(
    stdout: &mut dyn Write,
    stderr: &mut dyn Write,
    target: &Path,
    show_label: bool,
    options: ListOptions,
    caches: &mut Caches,
) -> Result<bool, Error> {
    let listing = collect::collect_directory(target).map_err(|source| Error::Io {
        path: target.to_path_buf(),
        source,
    })?;
    if show_label {
        write_path_with_suffix(stdout, target, b":\n")?;
    }
    let mut entries = listing.entries;
    let sense = {
        let names: Vec<&std::ffi::OsStr> = entries.iter().map(|e| e.name.as_os_str()).collect();
        caches.sensitivity.sensitivity(target, &names)
    };
    sort::sort_with(&mut entries, sense, options.sort_key, options.reverse);
    let snapshot = caches.snapshots.for_target(target);
    render_entries(
        stdout,
        &entries,
        &mut caches.owners,
        &caches.palette,
        snapshot,
        caches.now,
        caches.umask,
        listing.owner_uid,
    )?;
    Ok(report_listing_errors(stderr, &listing.errors))
}

fn report_listing_errors(stderr: &mut dyn Write, errors: &[(PathBuf, io::Error)]) -> bool {
    for (path, source) in errors {
        let _ = writeln!(
            stderr,
            "{}",
            Error::Io {
                path: path.clone(),
                source: io::Error::new(source.kind(), source.to_string()),
            }
        );
    }
    !errors.is_empty()
}

/// Walk `root` depth-first, rendering each directory as its own labeled
/// block. Subdirectory descent is gated on the unrestricted level: hidden
/// (dot-prefix) and gitignored directories are skipped by default and
/// progressively un-skipped at `-u` (gitignored) and `-uu` (hidden too).
///
/// Symlinks-to-directories are reclassified as `Directory` by
/// `entry_for_path` and descended into like real dirs. A per-path
/// ancestor-inode set keeps a symlink that resolves back into its own
/// ancestor chain from forming an infinite loop; non-ancestor revisits
/// (two siblings linking to the same target) are still listed, matching
/// `ls -LR`.
fn list_recursive(
    stdout: &mut dyn Write,
    stderr: &mut dyn Write,
    root: &Path,
    options: ListOptions,
    caches: &mut Caches,
) -> Result<bool, Error> {
    let mut stack: VecDeque<(PathBuf, Vec<Inode>)> = VecDeque::new();
    // Best-effort: a stat failure here would also fail `collect_directory`
    // below, where the error is already reported with full context.
    let root_ancestors = std::fs::metadata(root)
        .ok()
        .map(|m| vec![(m.dev(), m.ino())])
        .unwrap_or_default();
    stack.push_back((root.to_path_buf(), root_ancestors));
    let mut had_error = false;
    let mut first = true;
    while let Some((target, ancestors)) = stack.pop_front() {
        let listing = match collect::collect_directory(&target) {
            Ok(listing) => listing,
            Err(source) => {
                // If the root itself fails, surface the error to the caller
                // exactly like the non-recursive `list_directory` does — that
                // way the outer `list` loop can keep `have_output` correct
                // and not emit a blank-line separator for an empty block.
                if first {
                    return Err(Error::Io {
                        path: target,
                        source,
                    });
                }
                let _ = writeln!(
                    stderr,
                    "{}",
                    Error::Io {
                        path: target.clone(),
                        source,
                    }
                );
                had_error = true;
                continue;
            }
        };
        // Separator goes between *rendered* blocks; failed targets above
        // don't count, so we don't leave an orphan blank line behind them.
        if !first {
            writeln!(stdout).map_err(stdout_io)?;
        }
        first = false;
        write_path_with_suffix(stdout, &target, b":\n")?;
        let mut entries = listing.entries;
        let sense = {
            let names: Vec<&std::ffi::OsStr> = entries.iter().map(|e| e.name.as_os_str()).collect();
            caches.sensitivity.sensitivity(&target, &names)
        };
        sort::sort_with(&mut entries, sense, options.sort_key, options.reverse);
        let snapshot = caches.snapshots.for_target(&target);
        // Decide descent BEFORE rendering so we don't have to revisit the
        // snapshot lookup later (it can canonicalize, so each call has cost).
        let mut to_push: Vec<(PathBuf, Vec<Inode>)> = Vec::new();
        for entry in &entries {
            if entry.kind == EntryKind::Directory && should_descend(entry, snapshot, options) {
                let key = (entry.dev, entry.ino);
                if ancestors.contains(&key) {
                    continue;
                }
                let mut child_ancestors = ancestors.clone();
                child_ancestors.push(key);
                to_push.push((entry.path.clone(), child_ancestors));
            }
        }
        render_entries(
            stdout,
            &entries,
            &mut caches.owners,
            &caches.palette,
            snapshot,
            caches.now,
            caches.umask,
            listing.owner_uid,
        )?;
        had_error |= report_listing_errors(stderr, &listing.errors);
        // Push in reverse so the first sorted subdir pops next: depth-first
        // in the order rendered, matching GNU `ls -R`.
        for child in to_push.into_iter().rev() {
            stack.push_front(child);
        }
    }
    Ok(had_error)
}

fn should_descend(entry: &Entry, snapshot: Option<&Snapshot>, options: ListOptions) -> bool {
    let is_hidden = entry.name.as_bytes().first() == Some(&b'.');
    if is_hidden && options.unrestricted < 2 {
        return false;
    }
    // Pass `is_real_dir(entry)`, not a hard `true` — a symlink-to-directory
    // (which `collect` reclassifies as kind=Directory) is a *file* from
    // git's perspective, so trailing-slash exclude rules like `vendor/`
    // must not match it.
    if options.unrestricted < 1
        && snapshot.is_some_and(|s| s.is_ignored_with_kind(&entry.path, is_real_dir(entry)))
    {
        return false;
    }
    true
}

/// `true` only for a real directory inode — symlinks-to-directories are
/// reclassified as `Directory` by `entry_for_path`, but git treats them as
/// files for ignore matching (see gitignore(5): "Symbolic links to
/// directories are not considered directories for the purpose of matching").
fn is_real_dir(entry: &Entry) -> bool {
    entry.kind == EntryKind::Directory && entry.follow_chain.is_empty()
}

#[expect(
    clippy::too_many_arguments,
    reason = "owners (mut) and palette/snapshot (shared) must stay split — snapshot is a live borrow of caches.snapshots held across this call — alongside per-block context (now, umask, dir owner)"
)]
fn render_entries(
    stdout: &mut dyn Write,
    entries: &[Entry],
    owners: &mut OwnerCache<SystemDirectory>,
    palette: &Palette,
    snapshot: Option<&Snapshot>,
    now: SystemTime,
    umask: u32,
    dir_owner_uid: Option<u32>,
) -> Result<(), Error> {
    let mut rows: Vec<Row> = entries
        .iter()
        .map(|e| build_row(e, owners, palette, now, umask, dir_owner_uid))
        .collect();
    for (row, entry) in rows.iter_mut().zip(entries.iter()) {
        enrich_row(row, entry, palette, snapshot);
    }
    let git_width = if snapshot.is_some() {
        format::git_col::WIDTH
    } else {
        0
    };
    write_rows(stdout, &rows, git_width)
}

fn render_files(
    stdout: &mut dyn Write,
    entries: &[Entry],
    caches: &mut Caches,
) -> Result<(), Error> {
    // Each file argument may live in a different repository (or none); look
    // up its snapshot one entry at a time so we don't hold multiple cache
    // borrows at once, then render everything with shared widths.
    let mut rows: Vec<Row> = Vec::with_capacity(entries.len());
    let mut any_git = false;
    let now = caches.now;
    let umask = caches.umask;
    // Each argument may sit in a different directory, so its owner is dimmed
    // against the owner of its containing directory. Cache by directory so a
    // glob of same-directory arguments costs one stat, not one per file.
    let mut dir_owners: HashMap<PathBuf, Option<u32>> = HashMap::new();
    for entry in entries {
        let dir_owner_uid = *dir_owners
            .entry(containing_dir(&entry.path))
            .or_insert_with_key(|dir| std::fs::metadata(dir).ok().map(|m| m.uid()));
        let mut row = build_row(
            entry,
            &mut caches.owners,
            &caches.palette,
            now,
            umask,
            dir_owner_uid,
        );
        let snap = caches.snapshots.for_target(&entry.path);
        if snap.is_some() {
            any_git = true;
        }
        enrich_row(&mut row, entry, &caches.palette, snap);
        rows.push(row);
    }
    let git_width = if any_git { format::git_col::WIDTH } else { 0 };
    write_rows(stdout, &rows, git_width)
}

/// The directory that contains `path`, for owner-column dimming.
///
/// When the trailing component is a real name — a file or a named directory —
/// the container is the lexical parent, and a bare name (empty parent) lives in
/// the current directory. When it is `.`, `..`, `/`, or a trailing `.`/`..` —
/// which have no usable lexical parent — append `..` and let the kernel resolve
/// the real container when the path is stat'd. Lexical `Path::parent` would
/// wrongly yield `.` for `.` (so `.` would always match its own owner and dim)
/// or the path itself.
fn containing_dir(path: &Path) -> PathBuf {
    use std::path::Component;
    if let Some(Component::Normal(_)) = path.components().next_back() {
        match path.parent() {
            Some(p) if !p.as_os_str().is_empty() => p.to_path_buf(),
            _ => PathBuf::from("."),
        }
    } else {
        path.join("..")
    }
}

fn enrich_row(row: &mut Row, entry: &Entry, palette: &Palette, snapshot: Option<&Snapshot>) {
    let code = snapshot.map(|s| s.display_code_for(&entry.path, is_real_dir(entry)));
    if let Some(c) = code {
        row.git = Some(format::git_col::render(c));
    }
    // `build_row` already rendered the name (including the broken-link arrow and
    // dimmed columns, which it derives from the entry's kind). Only the
    // git-derived "ignored" dimming is unknown until now, so re-render for that.
    if code == Some(PorcelainCode::IGNORED) {
        row.name = format::name::format_name(palette, entry, true);
    }
}

fn write_rows(stdout: &mut dyn Write, rows: &[Row], git_width: usize) -> Result<(), Error> {
    let widths = compute_widths(rows);
    for row in rows {
        let line = render_row(row, widths, git_width);
        stdout.write_all(&line).map_err(stdout_io)?;
        stdout.write_all(b"\n").map_err(stdout_io)?;
    }
    Ok(())
}

// Write the path's raw OS bytes followed by `suffix`. Filenames on Unix are
// arbitrary byte sequences; using `Display` (which goes through
// `to_string_lossy`) would replace invalid UTF-8 with U+FFFD and break
// pipelines. TTY-aware quoting/escaping of control characters in names is a
// separate concern from byte-fidelity and is not part of this chunk.
fn write_path_with_suffix(stdout: &mut dyn Write, path: &Path, suffix: &[u8]) -> Result<(), Error> {
    stdout
        .write_all(path.as_os_str().as_bytes())
        .map_err(stdout_io)?;
    stdout.write_all(suffix).map_err(stdout_io)
}

const fn stdout_io(source: std::io::Error) -> Error {
    Error::StdoutIo(source)
}

#[cfg(test)]
mod tests {
    use super::run;
    use std::ffi::OsString;
    use std::fs;
    use std::io::{self, Write};
    use tempfile::tempdir;

    fn os(items: &[&str]) -> Vec<OsString> {
        items.iter().map(OsString::from).collect()
    }

    fn code_repr(code: std::process::ExitCode) -> String {
        format!("{code:?}")
    }

    struct FailingWriter;

    impl Write for FailingWriter {
        fn write(&mut self, _: &[u8]) -> io::Result<usize> {
            Err(io::Error::other("nope"))
        }
        fn flush(&mut self) -> io::Result<()> {
            Ok(())
        }
    }

    struct FailOnNewline {
        seen: usize,
        fail_after: usize,
    }

    impl FailOnNewline {
        const fn new(fail_after: usize) -> Self {
            Self {
                seen: 0,
                fail_after,
            }
        }
    }

    impl Write for FailOnNewline {
        fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
            for b in buf {
                if *b == b'\n' {
                    self.seen += 1;
                    if self.seen > self.fail_after {
                        return Err(io::Error::other("nope"));
                    }
                }
            }
            Ok(buf.len())
        }
        fn flush(&mut self) -> io::Result<()> {
            Ok(())
        }
    }

    #[test]
    fn failing_writer_flush_is_a_noop() {
        FailingWriter.flush().unwrap();
    }

    #[test]
    #[expect(
        clippy::unused_io_amount,
        reason = "exercises the Write impl's Ok/Err discrimination, not stream byte counts"
    )]
    fn fail_on_newline_writer_eventually_errors() {
        let mut w = FailOnNewline::new(1);
        w.write(b"first\n").unwrap();
        w.write(b"second\n").unwrap_err();
        w.flush().unwrap();
    }

    #[test]
    fn help_writes_to_stdout_and_returns_success() {
        let mut out = Vec::new();
        let mut err = Vec::new();
        let code = run(os(&["--help"]), &mut out, &mut err);
        assert_eq!(code_repr(code), code_repr(std::process::ExitCode::SUCCESS));
        let text = String::from_utf8(out).unwrap();
        assert!(text.contains("Usage: freshl"));
        assert!(err.is_empty());
    }

    #[test]
    fn version_writes_to_stdout() {
        let mut out = Vec::new();
        let mut err = Vec::new();
        let code = run(os(&["--version"]), &mut out, &mut err);
        assert_eq!(code_repr(code), code_repr(std::process::ExitCode::SUCCESS));
        let text = String::from_utf8(out).unwrap();
        assert!(text.starts_with("freshl "));
    }

    #[test]
    fn unknown_flag_writes_to_stderr_and_returns_two() {
        let mut out = Vec::new();
        let mut err = Vec::new();
        let code = run(os(&["--bogus"]), &mut out, &mut err);
        assert_eq!(code_repr(code), code_repr(std::process::ExitCode::from(2)));
        assert!(out.is_empty());
    }

    #[test]
    fn listing_no_args_lists_current_directory() {
        let mut out = Vec::new();
        let mut err = Vec::new();
        let code = run(os(&[]), &mut out, &mut err);
        assert_eq!(code_repr(code), code_repr(std::process::ExitCode::SUCCESS));
    }

    #[test]
    fn listing_directory_arg_prints_rows() {
        let dir = tempdir().unwrap();
        fs::write(dir.path().join("file"), b"hi").unwrap();
        let mut out = Vec::new();
        let mut err = Vec::new();
        let code = run(os(&[dir.path().to_str().unwrap()]), &mut out, &mut err);
        assert_eq!(code_repr(code), code_repr(std::process::ExitCode::SUCCESS));
        let text = String::from_utf8(out).unwrap();
        assert!(text.contains("file"));
        // Match kind+mode bytes only; the row may include surrounding ANSI escapes.
        assert!(text.contains(" 644"));
    }

    #[test]
    fn listing_file_arg_prints_one_row_with_full_path() {
        let dir = tempdir().unwrap();
        let file = dir.path().join("only");
        fs::write(&file, b"hi").unwrap();
        let mut out = Vec::new();
        let mut err = Vec::new();
        let code = run(os(&[file.to_str().unwrap()]), &mut out, &mut err);
        assert_eq!(code_repr(code), code_repr(std::process::ExitCode::SUCCESS));
        let text = String::from_utf8(out).unwrap();
        assert_eq!(text.lines().count(), 1);
        assert!(text.contains(file.to_str().unwrap()));
    }

    #[test]
    fn listing_multiple_paths_emits_labels_and_separator() {
        let dir = tempdir().unwrap();
        let a = dir.path().join("a");
        let b = dir.path().join("b");
        fs::create_dir(&a).unwrap();
        fs::create_dir(&b).unwrap();
        fs::write(a.join("inside"), b"x").unwrap();
        fs::write(b.join("other"), b"y").unwrap();

        let mut out = Vec::new();
        let mut err = Vec::new();
        let code = run(
            os(&[a.to_str().unwrap(), b.to_str().unwrap()]),
            &mut out,
            &mut err,
        );
        assert_eq!(code_repr(code), code_repr(std::process::ExitCode::SUCCESS));
        let text = String::from_utf8(out).unwrap();
        assert!(text.contains(':'));
        assert!(text.contains("inside"));
        assert!(text.contains("other"));
    }

    #[test]
    fn listing_nonexistent_path_returns_one() {
        let dir = tempdir().unwrap();
        let missing = dir.path().join("ghost");
        let mut out = Vec::new();
        let mut err = Vec::new();
        let code = run(os(&[missing.to_str().unwrap()]), &mut out, &mut err);
        assert_eq!(code_repr(code), code_repr(std::process::ExitCode::from(1)));
        let stderr_text = String::from_utf8(err).unwrap();
        assert!(stderr_text.contains("ghost"));
    }

    #[test]
    fn listing_unreadable_directory_returns_one() {
        use std::os::unix::fs::PermissionsExt;
        let dir = tempdir().unwrap();
        let locked = dir.path().join("locked");
        fs::create_dir(&locked).unwrap();
        let mut perms = fs::metadata(&locked).unwrap().permissions();
        perms.set_mode(0o000);
        fs::set_permissions(&locked, perms).unwrap();

        let mut out = Vec::new();
        let mut err = Vec::new();
        let code = run(os(&[locked.to_str().unwrap()]), &mut out, &mut err);

        let mut perms = fs::metadata(&locked).unwrap().permissions();
        perms.set_mode(0o755);
        fs::set_permissions(&locked, perms).unwrap();

        assert_eq!(code_repr(code), code_repr(std::process::ExitCode::from(1)));
    }

    #[test]
    fn listing_reports_per_child_stat_failures_and_returns_one() {
        use std::os::unix::fs::PermissionsExt;
        let dir = tempdir().unwrap();
        let inner = dir.path().join("inner");
        fs::create_dir(&inner).unwrap();
        fs::write(inner.join("a"), b"hi").unwrap();
        let mut p = fs::metadata(&inner).unwrap().permissions();
        p.set_mode(0o400);
        fs::set_permissions(&inner, p).unwrap();

        let mut out = Vec::new();
        let mut err = Vec::new();
        let code = run(os(&[inner.to_str().unwrap()]), &mut out, &mut err);

        let mut p = fs::metadata(&inner).unwrap().permissions();
        p.set_mode(0o755);
        fs::set_permissions(&inner, p).unwrap();

        assert_eq!(code_repr(code), code_repr(std::process::ExitCode::from(1)));
        let stderr_text = String::from_utf8(err).unwrap();
        assert!(stderr_text.contains('a'));
    }

    #[test]
    fn broken_symlink_renders_with_red_target_indicator() {
        let dir = tempdir().unwrap();
        let link = dir.path().join("dangling");
        std::os::unix::fs::symlink(dir.path().join("nope"), &link).unwrap();
        let mut out = Vec::new();
        let mut err = Vec::new();
        let code = run(os(&[dir.path().to_str().unwrap()]), &mut out, &mut err);
        assert_eq!(code_repr(code), code_repr(std::process::ExitCode::SUCCESS));
        // The target painted red embeds the AnsiColor::Red SGR sequence.
        assert!(out.windows(2).any(|w| w == b"31"));
    }

    #[test]
    fn relative_broken_symlink_resolves_relative_to_parent() {
        let dir = tempdir().unwrap();
        let link = dir.path().join("rellink");
        std::os::unix::fs::symlink("does-not-exist", &link).unwrap();
        let mut out = Vec::new();
        let mut err = Vec::new();
        let code = run(os(&[dir.path().to_str().unwrap()]), &mut out, &mut err);
        assert_eq!(code_repr(code), code_repr(std::process::ExitCode::SUCCESS));
        let text = String::from_utf8_lossy(&out);
        assert!(text.contains("rellink"));
        assert!(text.contains("does-not-exist"));
    }

    #[test]
    fn is_real_dir_distinguishes_directory_from_symlink_to_dir() {
        use super::is_real_dir;
        use crate::entry::{Entry, EntryKind};
        use std::ffi::OsString;
        use std::path::PathBuf;
        use std::time::SystemTime;
        let mut e = Entry {
            name: OsString::from("d"),
            path: PathBuf::from("d"),
            kind: EntryKind::Directory,
            mode: 0,
            nlink: 0,
            uid: 0,
            gid: 0,
            size: 0,
            rdev: 0,
            mtime: SystemTime::UNIX_EPOCH,
            dev: 0,
            ino: 0,
            follow_chain: Vec::new(),
        };
        // A real directory has no follow chain.
        assert!(is_real_dir(&e));
        // A symlink-to-directory is reclassified to `Directory` but carries a
        // follow chain; gitignore(5) matches it as a file, not a directory, so
        // it must not count as a "real" dir.
        e.follow_chain = vec![PathBuf::from("target")];
        assert!(!is_real_dir(&e));
    }

    #[test]
    fn containing_dir_resolves_parent_including_dot_and_root() {
        use super::containing_dir;
        use std::path::{Path, PathBuf};
        // A real trailing component: the lexical parent is the real container.
        assert_eq!(
            containing_dir(Path::new("/etc/passwd")),
            PathBuf::from("/etc")
        );
        assert_eq!(containing_dir(Path::new("a/b")), PathBuf::from("a"));
        // A bare relative name has no parent component; it lives in the cwd.
        assert_eq!(containing_dir(Path::new("bar.txt")), PathBuf::from("."));
        // `.`, `..`, `/` have no usable lexical parent, so we append `..` and
        // let the kernel resolve the real container: `stat("./..")` is the
        // parent of the cwd, not the cwd itself.
        assert_eq!(containing_dir(Path::new(".")), PathBuf::from("./.."));
        assert_eq!(containing_dir(Path::new("..")), PathBuf::from("../.."));
        assert_eq!(containing_dir(Path::new("/")), PathBuf::from("/.."));
    }

    #[test]
    fn listing_continues_past_missing_paths() {
        let dir = tempdir().unwrap();
        let good = dir.path().join("good");
        fs::create_dir(&good).unwrap();
        fs::write(good.join("inside"), b"x").unwrap();
        let missing = dir.path().join("missing");

        let mut out = Vec::new();
        let mut err = Vec::new();
        let code = run(
            os(&[missing.to_str().unwrap(), good.to_str().unwrap()]),
            &mut out,
            &mut err,
        );
        assert_eq!(code_repr(code), code_repr(std::process::ExitCode::from(1)));
        let stderr_text = String::from_utf8(err).unwrap();
        assert!(stderr_text.contains("missing"));
        let stdout_text = String::from_utf8(out).unwrap();
        assert!(stdout_text.contains("inside"));
    }

    #[test]
    fn stdout_write_failure_surfaces_io_error() {
        let mut out = FailingWriter;
        let mut err = Vec::new();
        let code = run(os(&["--help"]), &mut out, &mut err);
        assert_eq!(code_repr(code), code_repr(std::process::ExitCode::from(1)));
        let text = String::from_utf8(err).unwrap();
        assert!(text.contains("<stdout>"));
    }

    #[test]
    fn list_dir_write_failure_surfaces_io_error() {
        let dir = tempdir().unwrap();
        fs::write(dir.path().join("x"), b"hi").unwrap();
        let mut out = FailingWriter;
        let mut err = Vec::new();
        let code = run(os(&[dir.path().to_str().unwrap()]), &mut out, &mut err);
        assert_eq!(code_repr(code), code_repr(std::process::ExitCode::from(1)));
    }

    #[test]
    fn list_file_write_failure_surfaces_io_error() {
        let dir = tempdir().unwrap();
        let file = dir.path().join("solo");
        fs::write(&file, b"hi").unwrap();
        let mut out = FailingWriter;
        let mut err = Vec::new();
        let code = run(os(&[file.to_str().unwrap()]), &mut out, &mut err);
        assert_eq!(code_repr(code), code_repr(std::process::ExitCode::from(1)));
    }

    #[test]
    fn list_label_write_failure_surfaces_io_error() {
        let dir = tempdir().unwrap();
        let a = dir.path().join("a");
        let b = dir.path().join("b");
        fs::create_dir(&a).unwrap();
        fs::create_dir(&b).unwrap();
        let mut out = FailingWriter;
        let mut err = Vec::new();
        let code = run(
            os(&[a.to_str().unwrap(), b.to_str().unwrap()]),
            &mut out,
            &mut err,
        );
        assert_eq!(code_repr(code), code_repr(std::process::ExitCode::from(1)));
    }

    #[test]
    fn list_row_trailing_newline_write_failure_surfaces_io_error() {
        let dir = tempdir().unwrap();
        fs::write(dir.path().join("only"), b"hi").unwrap();
        let mut out = FailOnNewline::new(0);
        let mut err = Vec::new();
        let code = run(os(&[dir.path().to_str().unwrap()]), &mut out, &mut err);
        assert_eq!(code_repr(code), code_repr(std::process::ExitCode::from(1)));
    }

    #[test]
    fn list_separator_write_failure_surfaces_io_error() {
        let dir = tempdir().unwrap();
        let a = dir.path().join("a");
        let b = dir.path().join("b");
        fs::create_dir(&a).unwrap();
        fs::create_dir(&b).unwrap();
        let mut out = FailOnNewline::new(1);
        let mut err = Vec::new();
        let code = run(
            os(&[a.to_str().unwrap(), b.to_str().unwrap()]),
            &mut out,
            &mut err,
        );
        assert_eq!(code_repr(code), code_repr(std::process::ExitCode::from(1)));
    }

    #[test]
    fn recursive_label_write_failure_surfaces_io_error() {
        // Exercises the `?` on write_path_with_suffix in list_recursive.
        let dir = tempdir().unwrap();
        fs::write(dir.path().join("only"), b"hi").unwrap();
        let mut out = FailingWriter;
        let mut err = Vec::new();
        let code = run(
            os(&["-R", dir.path().to_str().unwrap()]),
            &mut out,
            &mut err,
        );
        assert_eq!(code_repr(code), code_repr(std::process::ExitCode::from(1)));
    }

    #[test]
    fn recursive_render_failure_surfaces_io_error() {
        // The label write succeeds (one newline budget) but the first row
        // newline trips FailOnNewline, exercising the `?` on render_entries
        // inside list_recursive — the non-recursive path has its own test.
        let dir = tempdir().unwrap();
        fs::write(dir.path().join("only"), b"hi").unwrap();
        let mut out = FailOnNewline::new(1);
        let mut err = Vec::new();
        let code = run(
            os(&["-R", dir.path().to_str().unwrap()]),
            &mut out,
            &mut err,
        );
        assert_eq!(code_repr(code), code_repr(std::process::ExitCode::from(1)));
    }

    #[test]
    fn recursive_separator_write_failure_surfaces_io_error() {
        // First iteration writes label + 1 row (2 newlines). Second iteration
        // hits the inter-block separator writeln (3rd newline) and fails,
        // exercising the `?` on the separator inside list_recursive.
        let dir = tempdir().unwrap();
        fs::create_dir(dir.path().join("sub")).unwrap();
        let mut out = FailOnNewline::new(2);
        let mut err = Vec::new();
        let code = run(
            os(&["-R", dir.path().to_str().unwrap()]),
            &mut out,
            &mut err,
        );
        assert_eq!(code_repr(code), code_repr(std::process::ExitCode::from(1)));
    }

    #[test]
    fn recursive_unreadable_root_surfaces_io_error() {
        // Exercises the `first` branch in list_recursive that returns Err
        // when the root itself fails to read on the first iteration.
        use std::os::unix::fs::PermissionsExt;
        // Restore perms on drop so an assert panic doesn't leak a 0o000
        // directory that tempdir's cleanup can't remove.
        struct Restore(std::path::PathBuf);
        impl Drop for Restore {
            fn drop(&mut self) {
                use std::os::unix::fs::PermissionsExt;
                let _ = fs::set_permissions(&self.0, fs::Permissions::from_mode(0o755));
            }
        }
        let dir = tempdir().unwrap();
        let locked = dir.path().join("locked");
        fs::create_dir(&locked).unwrap();
        fs::set_permissions(&locked, fs::Permissions::from_mode(0o000)).unwrap();
        let _restore = Restore(locked.clone());
        let mut out = Vec::new();
        let mut err = Vec::new();
        let code = run(os(&["-R", locked.to_str().unwrap()]), &mut out, &mut err);
        assert_eq!(code_repr(code), code_repr(std::process::ExitCode::from(1)));
    }

    #[test]
    fn recursive_lists_nested_directories_depth_first_with_labels() {
        let dir = tempdir().unwrap();
        let a = dir.path().join("a");
        let b = a.join("b");
        fs::create_dir(&a).unwrap();
        fs::create_dir(&b).unwrap();
        fs::write(a.join("leaf"), b"x").unwrap();
        fs::write(b.join("deep"), b"y").unwrap();

        let mut out = Vec::new();
        let mut err = Vec::new();
        let code = run(
            os(&["-R", dir.path().to_str().unwrap()]),
            &mut out,
            &mut err,
        );
        assert_eq!(code_repr(code), code_repr(std::process::ExitCode::SUCCESS));
        let text = String::from_utf8(out).unwrap();
        let root_label = format!("{}:", dir.path().display());
        let a_label = format!("{}:", a.display());
        let b_label = format!("{}:", b.display());
        let root_at = text.find(&root_label).expect("root label present");
        let a_at = text.find(&a_label).expect("a label present");
        let b_at = text.find(&b_label).expect("b label present");
        assert!(root_at < a_at, "root must precede a:\n{text}");
        assert!(a_at < b_at, "a must precede b (depth first):\n{text}");
        assert!(text.contains("leaf"));
        assert!(text.contains("deep"));
    }

    #[test]
    fn recursive_skips_hidden_directory_by_default_but_lists_it() {
        let dir = tempdir().unwrap();
        let hidden = dir.path().join(".secret");
        fs::create_dir(&hidden).unwrap();
        fs::write(hidden.join("inside"), b"x").unwrap();

        let mut out = Vec::new();
        let mut err = Vec::new();
        let code = run(
            os(&["-R", dir.path().to_str().unwrap()]),
            &mut out,
            &mut err,
        );
        assert_eq!(code_repr(code), code_repr(std::process::ExitCode::SUCCESS));
        let text = String::from_utf8(out).unwrap();
        // The hidden directory row is listed (always-hidden rule), but its
        // contents are NOT recursed into.
        assert!(text.contains(".secret"));
        assert!(!text.contains("inside"), "should not recurse: {text}");
    }

    #[test]
    fn double_unrestricted_recurses_into_hidden_directories() {
        let dir = tempdir().unwrap();
        let hidden = dir.path().join(".secret");
        fs::create_dir(&hidden).unwrap();
        fs::write(hidden.join("inside"), b"x").unwrap();

        let mut out = Vec::new();
        let mut err = Vec::new();
        let code = run(
            os(&["-Ruu", dir.path().to_str().unwrap()]),
            &mut out,
            &mut err,
        );
        assert_eq!(code_repr(code), code_repr(std::process::ExitCode::SUCCESS));
        let text = String::from_utf8(out).unwrap();
        assert!(text.contains("inside"));
    }

    #[test]
    fn recursive_reports_subdirectory_error_and_continues() {
        use std::os::unix::fs::PermissionsExt;
        let dir = tempdir().unwrap();
        let good = dir.path().join("good");
        let locked = dir.path().join("locked");
        fs::create_dir(&good).unwrap();
        fs::create_dir(&locked).unwrap();
        fs::write(good.join("inside"), b"x").unwrap();
        let mut p = fs::metadata(&locked).unwrap().permissions();
        p.set_mode(0o000);
        fs::set_permissions(&locked, p).unwrap();

        let mut out = Vec::new();
        let mut err = Vec::new();
        let code = run(
            os(&["-R", dir.path().to_str().unwrap()]),
            &mut out,
            &mut err,
        );

        let mut p = fs::metadata(&locked).unwrap().permissions();
        p.set_mode(0o755);
        fs::set_permissions(&locked, p).unwrap();

        assert_eq!(code_repr(code), code_repr(std::process::ExitCode::from(1)));
        let err_text = String::from_utf8(err).unwrap();
        assert!(err_text.contains("locked"));
        let out_text = String::from_utf8(out).unwrap();
        assert!(
            out_text.contains("inside"),
            "sibling content still rendered: {out_text}"
        );
    }

    #[test]
    fn recursive_skips_gitignored_directory_by_default() {
        use std::process::Command;
        let dir = tempdir().unwrap();
        // Set up a tiny repo with an ignored subdirectory.
        for args in [
            vec!["init", "-q", "-b", "main"],
            vec!["config", "user.email", "t@example.com"],
            vec!["config", "user.name", "t"],
        ] {
            let status = Command::new("git")
                .arg("-C")
                .arg(dir.path())
                .args(args)
                .env("GIT_CONFIG_GLOBAL", "/dev/null")
                .env("GIT_CONFIG_SYSTEM", "/dev/null")
                .env("HOME", dir.path())
                .status()
                .unwrap();
            assert!(status.success());
        }
        let ignored = dir.path().join("ignored_dir");
        fs::create_dir(&ignored).unwrap();
        fs::write(ignored.join("buried"), b"x").unwrap();
        fs::write(dir.path().join(".gitignore"), b"ignored_dir/\n").unwrap();

        let mut out = Vec::new();
        let mut err = Vec::new();
        let code = run(
            os(&["-R", dir.path().to_str().unwrap()]),
            &mut out,
            &mut err,
        );
        assert_eq!(code_repr(code), code_repr(std::process::ExitCode::SUCCESS));
        let text = String::from_utf8(out).unwrap();
        assert!(text.contains("ignored_dir"), "row still listed: {text}");
        assert!(
            !text.contains("buried"),
            "must not recurse into ignored: {text}"
        );

        // With -Ru we should descend into the gitignored directory.
        let mut out2 = Vec::new();
        let mut err2 = Vec::new();
        let code2 = run(
            os(&["-Ru", dir.path().to_str().unwrap()]),
            &mut out2,
            &mut err2,
        );
        assert_eq!(code_repr(code2), code_repr(std::process::ExitCode::SUCCESS));
        let text2 = String::from_utf8(out2).unwrap();
        assert!(text2.contains("buried"), "-Ru must recurse: {text2}");
    }

    #[test]
    fn recursive_reverse_keeps_dfs_between_blocks() {
        let dir = tempdir().unwrap();
        let a = dir.path().join("a");
        let b = dir.path().join("b");
        fs::create_dir(&a).unwrap();
        fs::create_dir(&b).unwrap();
        fs::write(a.join("inner"), b"x").unwrap();
        fs::write(b.join("inner"), b"y").unwrap();

        let mut out = Vec::new();
        let mut err = Vec::new();
        let code = run(
            os(&["-Rr", dir.path().to_str().unwrap()]),
            &mut out,
            &mut err,
        );
        assert_eq!(code_repr(code), code_repr(std::process::ExitCode::SUCCESS));
        let text = String::from_utf8(out).unwrap();
        let a_label = format!("{}:", a.display());
        let b_label = format!("{}:", b.display());
        let a_at = text.find(&a_label).unwrap();
        let b_at = text.find(&b_label).unwrap();
        // Within the root block, -r reverses → b row precedes a row → b: block
        // is visited first when we pop the DFS stack.
        assert!(b_at < a_at, "reverse should put b: before a:\n{text}");
    }

    #[test]
    fn sort_by_size_puts_largest_at_bottom() {
        let dir = tempdir().unwrap();
        fs::write(dir.path().join("small"), b"x").unwrap();
        fs::write(dir.path().join("big"), vec![b'x'; 5_000]).unwrap();
        fs::write(dir.path().join("mid"), vec![b'x'; 500]).unwrap();

        let mut out = Vec::new();
        let mut err = Vec::new();
        let code = run(
            os(&["-S", dir.path().to_str().unwrap()]),
            &mut out,
            &mut err,
        );
        assert_eq!(code_repr(code), code_repr(std::process::ExitCode::SUCCESS));
        let text = String::from_utf8(out).unwrap();
        let small_at = text.find("small").unwrap();
        let mid_at = text.find("mid").unwrap();
        let big_at = text.find("big").unwrap();
        assert!(small_at < mid_at && mid_at < big_at, "order:\n{text}");
    }

    #[test]
    fn recursive_per_child_stat_failure_is_reported_and_continues() {
        use std::os::unix::fs::PermissionsExt;
        let dir = tempdir().unwrap();
        let inner = dir.path().join("inner");
        fs::create_dir(&inner).unwrap();
        fs::write(inner.join("child"), b"hi").unwrap();
        // r-- on the directory itself: readdir returns names, but `lstat` of
        // each child fails because of the missing +x bit. That feeds the
        // `listing.errors` accumulation in list_recursive.
        let mut p = fs::metadata(&inner).unwrap().permissions();
        p.set_mode(0o400);
        fs::set_permissions(&inner, p).unwrap();

        let mut out = Vec::new();
        let mut err = Vec::new();
        let code = run(
            os(&["-R", dir.path().to_str().unwrap()]),
            &mut out,
            &mut err,
        );

        let mut p = fs::metadata(&inner).unwrap().permissions();
        p.set_mode(0o755);
        fs::set_permissions(&inner, p).unwrap();

        assert_eq!(code_repr(code), code_repr(std::process::ExitCode::from(1)));
        let err_text = String::from_utf8(err).unwrap();
        assert!(
            err_text.contains("child"),
            "error mentions child: {err_text}"
        );
    }

    #[test]
    fn file_arg_inside_git_repo_shows_git_column() {
        use std::process::Command;
        let dir = tempdir().unwrap();
        for cmd_args in [
            vec!["init", "-q", "-b", "main"],
            vec!["config", "user.email", "t@example.com"],
            vec!["config", "user.name", "t"],
        ] {
            let status = Command::new("git")
                .arg("-C")
                .arg(dir.path())
                .args(cmd_args)
                .env("GIT_CONFIG_GLOBAL", "/dev/null")
                .env("GIT_CONFIG_SYSTEM", "/dev/null")
                .env("HOME", dir.path())
                .status()
                .unwrap();
            assert!(status.success());
        }
        let file = dir.path().join("tracked");
        fs::write(&file, b"hi").unwrap();
        let status = Command::new("git")
            .arg("-C")
            .arg(dir.path())
            .args(["add", "tracked"])
            .env("GIT_CONFIG_GLOBAL", "/dev/null")
            .env("GIT_CONFIG_SYSTEM", "/dev/null")
            .env("HOME", dir.path())
            .status()
            .unwrap();
        assert!(status.success());

        let mut out = Vec::new();
        let mut err = Vec::new();
        let code = run(os(&[file.to_str().unwrap()]), &mut out, &mut err);
        assert_eq!(code_repr(code), code_repr(std::process::ExitCode::SUCCESS));
        let text = String::from_utf8(out).unwrap();
        // Staged addition gets `+`; covers the `any_git = true` branch in
        // render_files.
        assert!(
            text.contains('+'),
            "expected git column for staged add: {text}"
        );
    }

    #[test]
    fn renders_target_kind_for_symlink_to_file() {
        let dir = tempdir().unwrap();
        let target = dir.path().join("target");
        fs::write(&target, b"contents").unwrap();
        let link = dir.path().join("link");
        std::os::unix::fs::symlink(&target, &link).unwrap();
        let mut out = Vec::new();
        let mut err = Vec::new();
        let code = run(os(&[link.to_str().unwrap()]), &mut out, &mut err);
        assert_eq!(code_repr(code), code_repr(std::process::ExitCode::SUCCESS));
        let text = String::from_utf8(out).unwrap();
        assert!(text.contains(link.to_str().unwrap()));
        assert!(
            text.contains(''),
            "symlink should render with forward arrow: {text}"
        );
    }

    #[test]
    fn renders_chain_forward_to_target_name() {
        let dir = tempdir().unwrap();
        fs::write(dir.path().join("AGENTS.md"), b"x").unwrap();
        std::os::unix::fs::symlink("AGENTS.md", dir.path().join("CLAUDE.md")).unwrap();

        let mut out = Vec::new();
        let mut err = Vec::new();
        let code = run(os(&[dir.path().to_str().unwrap()]), &mut out, &mut err);
        assert_eq!(code_repr(code), code_repr(std::process::ExitCode::SUCCESS));
        let text = String::from_utf8(out).unwrap();
        // Each segment carries its own ANSI style with explicit resets, so
        // the name/arrow/target are sandwiched between control sequences
        // rather than forming a contiguous substring. Find the symlink
        // row's CLAUDE.md and confirm an arrow + AGENTS.md follow it.
        assert!(text.contains(''), "no arrow: {text}");
        let arrow = text.find('').unwrap();
        let (pre, post) = text.split_at(arrow);
        assert!(
            pre.contains("CLAUDE.md"),
            "link name must precede arrow: {text}"
        );
        assert!(
            post.contains("AGENTS.md"),
            "target must follow arrow: {text}"
        );
    }

    #[test]
    fn expands_symlink_to_directory_arg() {
        let dir = tempdir().unwrap();
        let target = dir.path().join("real");
        fs::create_dir(&target).unwrap();
        fs::write(target.join("inside"), b"x").unwrap();
        let link = dir.path().join("link");
        std::os::unix::fs::symlink(&target, &link).unwrap();

        let mut out = Vec::new();
        let mut err = Vec::new();
        let code = run(os(&[link.to_str().unwrap()]), &mut out, &mut err);
        assert_eq!(code_repr(code), code_repr(std::process::ExitCode::SUCCESS));
        let text = String::from_utf8(out).unwrap();
        assert!(text.contains("inside"), "expanded contents: {text}");
    }

    #[test]
    fn falls_back_on_broken_symlink() {
        let dir = tempdir().unwrap();
        let link = dir.path().join("dangling");
        std::os::unix::fs::symlink(dir.path().join("nope"), &link).unwrap();
        let mut out = Vec::new();
        let mut err = Vec::new();
        let code = run(os(&[dir.path().to_str().unwrap()]), &mut out, &mut err);
        assert_eq!(code_repr(code), code_repr(std::process::ExitCode::SUCCESS));
        let text = String::from_utf8_lossy(&out);
        assert!(text.contains("dangling"));
        assert!(text.contains(''), "broken link still shows arrow: {text}");
    }

    #[test]
    fn recursive_descends_into_linked_directory() {
        let dir = tempdir().unwrap();
        let real = dir.path().join("real");
        fs::create_dir(&real).unwrap();
        fs::write(real.join("inside"), b"x").unwrap();
        let link = dir.path().join("link");
        std::os::unix::fs::symlink(&real, &link).unwrap();

        let mut out = Vec::new();
        let mut err = Vec::new();
        let code = run(
            os(&["-R", dir.path().to_str().unwrap()]),
            &mut out,
            &mut err,
        );
        assert_eq!(code_repr(code), code_repr(std::process::ExitCode::SUCCESS));
        let text = String::from_utf8(out).unwrap();
        let link_label = format!("{}:", link.display());
        assert!(
            text.contains(&link_label),
            "symlink dir should be descended into: {text}"
        );
    }

    #[test]
    fn recursive_breaks_self_referential_symlink_cycle() {
        let dir = tempdir().unwrap();
        let inner = dir.path().join("inner");
        fs::create_dir(&inner).unwrap();
        let cycle = inner.join("loop");
        std::os::unix::fs::symlink(&inner, &cycle).unwrap();

        let mut out = Vec::new();
        let mut err = Vec::new();
        let code = run(
            os(&["-R", dir.path().to_str().unwrap()]),
            &mut out,
            &mut err,
        );
        assert_eq!(code_repr(code), code_repr(std::process::ExitCode::SUCCESS));
        let text = String::from_utf8(out).unwrap();
        // The cycle link is listed once (under inner:) but its own block
        // (which would re-render inner's contents) must not appear.
        let loop_label = format!("{}:", cycle.display());
        assert!(
            !text.contains(&loop_label),
            "self-loop must not produce its own block: {text}"
        );
    }

    #[test]
    fn directory_flag_lists_directory_itself_not_contents() {
        let dir = tempdir().unwrap();
        fs::write(dir.path().join("inside"), b"x").unwrap();
        let mut out = Vec::new();
        let mut err = Vec::new();
        let code = run(
            os(&["-d", dir.path().to_str().unwrap()]),
            &mut out,
            &mut err,
        );
        assert_eq!(code_repr(code), code_repr(std::process::ExitCode::SUCCESS));
        let text = String::from_utf8(out).unwrap();
        assert_eq!(text.lines().count(), 1, "expected one row: {text}");
        assert!(text.contains(dir.path().to_str().unwrap()));
        assert!(!text.contains("inside"), "should not list contents: {text}");
    }

    #[test]
    fn directory_flag_with_recursive_does_not_recurse() {
        let dir = tempdir().unwrap();
        let sub = dir.path().join("sub");
        fs::create_dir(&sub).unwrap();
        fs::write(sub.join("deep"), b"x").unwrap();
        let mut out = Vec::new();
        let mut err = Vec::new();
        let code = run(
            os(&["-dR", dir.path().to_str().unwrap()]),
            &mut out,
            &mut err,
        );
        assert_eq!(code_repr(code), code_repr(std::process::ExitCode::SUCCESS));
        let text = String::from_utf8(out).unwrap();
        assert_eq!(text.lines().count(), 1, "expected one row: {text}");
        assert!(!text.contains("deep"), "must not recurse with -d: {text}");
        assert!(!text.contains("sub"), "must not list children: {text}");
    }

    #[test]
    fn directory_flag_mixes_files_and_dirs_in_one_block() {
        let dir = tempdir().unwrap();
        let sub = dir.path().join("sub");
        let file = dir.path().join("file");
        fs::create_dir(&sub).unwrap();
        fs::write(&file, b"x").unwrap();
        let mut out = Vec::new();
        let mut err = Vec::new();
        let code = run(
            os(&["-d", sub.to_str().unwrap(), file.to_str().unwrap()]),
            &mut out,
            &mut err,
        );
        assert_eq!(code_repr(code), code_repr(std::process::ExitCode::SUCCESS));
        let text = String::from_utf8(out).unwrap();
        assert_eq!(text.lines().count(), 2, "expected two rows: {text}");
        // No `<path>:` label lines under -d — both args render as plain rows
        // with shared widths, like a multi-file `ls -l`.
        assert!(
            !text.lines().any(|l| l.ends_with(':')),
            "no labels expected: {text}"
        );
    }
}