Skip to content

Commit 448ae54

Browse files
rhishi99claude
andcommitted
fix(system): print per-directory headers in native Windows ls
native_ls already emitted `DIR:` headers for 2+ operands, but compact_ls treated them as unparsable lines, filed them under "filtered" and merged the entries of every directory into one list. Compact each header-delimited block separately and keep its header, with a blank line between blocks. Also list non-directory operands first, headerless, and still list other operands when one is missing (exit 2), matching GNU ls. Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
1 parent c21ba9e commit 448ae54

2 files changed

Lines changed: 149 additions & 14 deletions

File tree

‎src/cmds/system/ls.rs‎

Lines changed: 121 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -558,6 +558,58 @@ fn compact_ls(
558558
raw: &str,
559559
show_all: bool,
560560
show_long: bool,
561+
) -> (String, usize, Vec<String>, Vec<String>) {
562+
// `ls A B` and `ls -R` print a `DIR:` header before each directory. Compact each
563+
// block on its own and keep its header, or entries of different directories run together.
564+
let mut sections: Vec<(Option<&str>, Vec<&str>)> = vec![(None, Vec::new())];
565+
for line in raw.lines() {
566+
if is_dir_header(line) {
567+
sections.push((Some(line), Vec::new()));
568+
} else if let Some((_, body)) = sections.last_mut() {
569+
body.push(line);
570+
}
571+
}
572+
if sections.len() == 1 {
573+
return compact_block(raw, show_all, show_long);
574+
}
575+
576+
let mut out = String::new();
577+
let mut parsed_total = 0;
578+
let mut truncated_all = Vec::new();
579+
let mut filtered_all = Vec::new();
580+
for (header, body) in sections {
581+
// Nothing before the first header: no file operands were given.
582+
if header.is_none() && body.iter().all(|l| l.is_empty()) {
583+
continue;
584+
}
585+
let (entries, parsed, truncated, filtered) =
586+
compact_block(&body.join("\n"), show_all, show_long);
587+
if !out.is_empty() {
588+
out.push('\n');
589+
}
590+
if let Some(header) = header {
591+
out.push_str(header);
592+
out.push('\n');
593+
}
594+
out.push_str(&entries);
595+
parsed_total += parsed;
596+
truncated_all.extend(truncated);
597+
filtered_all.extend(filtered);
598+
}
599+
(out, parsed_total, truncated_all, filtered_all)
600+
}
601+
602+
/// A `DIR:` line that `ls` prints above each directory when given several operands or `-R`.
603+
/// A long-format entry line always carries a date, so a line without one cannot be an entry.
604+
fn is_dir_header(line: &str) -> bool {
605+
line.ends_with(':') && LS_DATE_RE.find(line).is_none()
606+
}
607+
608+
/// Compact one block of `ls -la` lines (a single directory's listing).
609+
fn compact_block(
610+
raw: &str,
611+
show_all: bool,
612+
show_long: bool,
561613
) -> (String, usize, Vec<String>, Vec<String>) {
562614
let mut dirs: Vec<(String, Option<String>)> = Vec::new(); // (name, octal_perms)
563615
let mut files: Vec<(String, String, Option<String>)> = Vec::new(); // (name, size, octal_perms)
@@ -1556,4 +1608,73 @@ mod tests {
15561608
assert_eq!(parsed_count, 0);
15571609
assert!(entries.is_empty());
15581610
}
1611+
1612+
// --- multi-operand listings: per-directory headers (native ls on Windows) ---
1613+
1614+
fn native_render(operands: &[&str]) -> (String, crate::core::runner::NativeOutput) {
1615+
let mut argv = vec!["-l".to_string(), "--".to_string()];
1616+
argv.extend(operands.iter().map(|s| s.to_string()));
1617+
let out = native_ls(&argv, 0).unwrap();
1618+
(render(&out.stdout, None, false, false, 0), out)
1619+
}
1620+
1621+
fn fixture() -> (tempfile::TempDir, String, String, String) {
1622+
let temp = tempfile::tempdir().unwrap();
1623+
let a = temp.path().join("alpha");
1624+
let b = temp.path().join("beta");
1625+
std::fs::create_dir(&a).unwrap();
1626+
std::fs::create_dir(&b).unwrap();
1627+
std::fs::write(a.join("a1.txt"), "x").unwrap();
1628+
std::fs::write(b.join("b1.txt"), "x").unwrap();
1629+
let a = a.to_string_lossy().into_owned();
1630+
let b = b.to_string_lossy().into_owned();
1631+
let f = temp.path().join("top.txt");
1632+
std::fs::write(&f, "x").unwrap();
1633+
let f = f.to_string_lossy().into_owned();
1634+
(temp, a, b, f)
1635+
}
1636+
1637+
#[test]
1638+
fn test_one_dir_has_no_header() {
1639+
let (_t, a, _b, _f) = fixture();
1640+
let (shown, _) = native_render(&[&a]);
1641+
assert_eq!(shown, "a1.txt\n");
1642+
}
1643+
1644+
#[test]
1645+
fn test_two_dirs_get_headers_and_blank_separator() {
1646+
let (_t, a, b, _f) = fixture();
1647+
let (shown, out) = native_render(&[&a, &b]);
1648+
assert_eq!(out.exit_code, 0);
1649+
assert_eq!(shown, format!("{a}:\na1.txt\n\n{b}:\nb1.txt\n"));
1650+
}
1651+
1652+
#[test]
1653+
fn test_file_operand_listed_first_without_header() {
1654+
let (_t, a, _b, f) = fixture();
1655+
// Directory given first, file second: the file still prints first, as in ls.
1656+
let (shown, _) = native_render(&[&a, &f]);
1657+
assert_eq!(shown, format!("{f}\n\n{a}:\na1.txt\n"));
1658+
}
1659+
1660+
#[test]
1661+
fn test_missing_operand_errors_but_others_still_listed() {
1662+
let (t, a, b, _f) = fixture();
1663+
let missing = t.path().join("nope").to_string_lossy().into_owned();
1664+
let (shown, out) = native_render(&[&a, &missing, &b]);
1665+
assert_eq!(out.exit_code, 2);
1666+
assert!(out.stderr.contains("cannot access"), "{}", out.stderr);
1667+
assert!(out.stderr.contains("nope"), "{}", out.stderr);
1668+
assert_eq!(shown, format!("{a}:\na1.txt\n\n{b}:\nb1.txt\n"));
1669+
}
1670+
1671+
#[test]
1672+
fn test_compact_keeps_recursive_headers() {
1673+
let input = "src:\ntotal 1\n-rw-r--r-- 1 u g 1 Jan 01 12:00 a.rs\n\n\
1674+
src/sub:\ntotal 1\n-rw-r--r-- 1 u g 1 Jan 01 12:00 b.rs\n";
1675+
let (entries, parsed, _t, filtered) = compact_ls(input, false, false);
1676+
assert_eq!(entries, "src:\na.rs\n\nsrc/sub:\nb.rs\n");
1677+
assert_eq!(parsed, 2);
1678+
assert!(filtered.is_empty(), "{filtered:?}");
1679+
}
15591680
}

‎src/cmds/system/native_ls.rs‎

Lines changed: 28 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -241,35 +241,49 @@ pub fn native_ls(args: &[String], verbose: u8) -> Result<NativeOutput> {
241241
let mut exit_code = 0;
242242
let many = config.paths.len() > 1;
243243

244-
let mut first = true;
244+
// Like `ls`, report missing operands first, list non-directory operands
245+
// together with no header, then each directory under its own `DIR:` header.
246+
let mut files: Vec<(&String, PathBuf)> = Vec::new();
247+
let mut dirs: Vec<(&String, PathBuf)> = Vec::new();
245248
for path_str in &config.paths {
246249
let path = PathBuf::from(path_str);
247-
let meta = match fs::metadata(&path) {
248-
Ok(m) => m,
250+
match fs::metadata(&path) {
251+
Ok(m) if m.is_dir() && !config.directory => dirs.push((path_str, path)),
252+
Ok(_) => files.push((path_str, path)),
249253
Err(_) => {
250254
stderr.push_str(&format!(
251255
"ls: cannot access '{}': No such file or directory\n",
252256
path_str
253257
));
254258
exit_code = 2;
255-
continue;
256259
}
257-
};
260+
}
261+
}
258262

259-
if !first {
263+
for (path_str, path) in &files {
264+
if let Ok(entry) = LsEntry::from_path((*path_str).clone(), path) {
265+
stdout.push_str(&entry.line());
260266
stdout.push('\n');
261267
}
262-
first = false;
268+
}
263269

264-
if meta.is_dir() && !config.directory {
265-
let header = (many || config.recursive).then_some(path_str.as_str());
266-
if let Err(e) = list_dir(&path, header, &config, &mut stdout) {
267-
stderr.push_str(&format!("ls: cannot open directory '{}': {}\n", path_str, e));
270+
for (path_str, path) in &dirs {
271+
let header = (many || config.recursive).then_some(path_str.as_str());
272+
let mut block = String::new();
273+
match list_dir(path, header, &config, &mut block) {
274+
Ok(()) => {
275+
if !stdout.is_empty() {
276+
stdout.push('\n');
277+
}
278+
stdout.push_str(&block);
279+
}
280+
Err(e) => {
281+
stderr.push_str(&format!(
282+
"ls: cannot open directory '{}': {}\n",
283+
path_str, e
284+
));
268285
exit_code = 2;
269286
}
270-
} else if let Ok(entry) = LsEntry::from_path(path_str.clone(), &path) {
271-
stdout.push_str(&entry.line());
272-
stdout.push('\n');
273287
}
274288
}
275289

0 commit comments

Comments
 (0)