Skip to content

Commit cff9485

Browse files
du: count subdirectories in --total with --separate-dirs, print time on total line (#15455)
* du: count subdirectories in --total with --separate-dirs, print time on total line --separate-dirs was leaving subdirectory usage out of the grand total, and --time omitted the timestamp on that line. The total now adds every directory under --separate-dirs (file sizes stay in their parent, so -a does not count them twice), and with --time the total line shows the newest time seen, never moving back before 1970-01-01. The total time and subdirectory sizes are only tracked when --total is given, so other invocations keep the previous code path. Refs #15254 Found with behave (https://github.com/emirmrkaljevic/behave). Co-authored-by: CodSpeed Bot <no-reply@codspeed.io> * du: drop unneeded is_dir local in Stat::new * du: drop the extra touch loop in the time column test --------- Co-authored-by: CodSpeed Bot <no-reply@codspeed.io>
1 parent ce58468 commit cff9485

2 files changed

Lines changed: 278 additions & 9 deletions

File tree

‎src/uu/du/src/du.rs‎

Lines changed: 41 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -101,6 +101,7 @@ struct StatPrinter {
101101
time_format: String,
102102
line_ending: LineEnding,
103103
summarize: bool,
104+
separate_dirs: bool,
104105
total_text: String,
105106
}
106107

@@ -618,6 +619,7 @@ fn safe_du(
618619
print_tx.send(Ok(StatPrintInfo {
619620
stat: this_stat,
620621
depth: depth + 1,
622+
is_dir: true,
621623
}))?;
622624
} else {
623625
my_stat.size += this_stat.size;
@@ -632,6 +634,7 @@ fn safe_du(
632634
print_tx.send(Ok(StatPrintInfo {
633635
stat: this_stat,
634636
depth: depth + 1,
637+
is_dir: false,
635638
}))?;
636639
}
637640
}
@@ -780,6 +783,7 @@ fn du_regular(
780783
print_tx.send(Ok(StatPrintInfo {
781784
stat: this_stat,
782785
depth: depth + 1,
786+
is_dir: true,
783787
}))?;
784788
} else {
785789
my_stat.size += this_stat.size;
@@ -795,6 +799,7 @@ fn du_regular(
795799
print_tx.send(Ok(StatPrintInfo {
796800
stat: this_stat,
797801
depth: depth + 1,
802+
is_dir: false,
798803
}))?;
799804
}
800805
}
@@ -882,6 +887,8 @@ fn build_exclude_patterns(matches: &ArgMatches) -> UResult<Vec<Pattern>> {
882887
struct StatPrintInfo {
883888
stat: Stat,
884889
depth: usize,
890+
/// Real directory bit; safe traversal leaves a placeholder metadata on children.
891+
is_dir: bool,
885892
}
886893

887894
/// Add the locale grouping requested by a leading apostrophe in SIZE.
@@ -929,14 +936,22 @@ impl StatPrinter {
929936

930937
fn print_stats(&self, rx: &mpsc::Receiver<UResult<StatPrintInfo>>) -> UResult<()> {
931938
let mut grand_total = 0;
939+
// Depth 0 already includes children, except with --separate-dirs.
940+
let count_separate_dirs = self.total && self.separate_dirs;
941+
// Total time starts at 1970-01-01 and moves forward only.
942+
let track_total_time = self.total && self.time.is_some();
943+
let mut grand_time = SystemTime::UNIX_EPOCH;
932944
while let Ok(received) = rx.recv() {
933945
match received {
934946
Ok(stat_info) => {
935947
let size = self.choose_size(&stat_info.stat);
936948

937-
if stat_info.depth == 0 {
949+
if stat_info.depth == 0 || (count_separate_dirs && stat_info.is_dir) {
938950
grand_total += size;
939951
}
952+
if track_total_time && let Some(time) = stat_info.stat.latest_time {
953+
grand_time = grand_time.max(time);
954+
}
940955

941956
if !self
942957
.threshold
@@ -954,8 +969,9 @@ impl StatPrinter {
954969
}
955970

956971
if self.total {
957-
stdout().write_all(&self.convert_size(grand_total))?;
958-
write!(stdout(), "\t{}{}", self.total_text, self.line_ending)?;
972+
let time = track_total_time.then_some(grand_time);
973+
self.write_size_and_time(grand_total, time)?;
974+
write!(stdout(), "{}{}", self.total_text, self.line_ending)?;
959975
}
960976

961977
Ok(())
@@ -995,11 +1011,19 @@ impl StatPrinter {
9951011
}
9961012

9971013
fn print_stat(&self, stat: &Stat, size: u64) -> UResult<()> {
1014+
self.write_size_and_time(size, stat.latest_time)?;
1015+
print_verbatim(&stat.path)?;
1016+
write!(stdout(), "{}", self.line_ending)?;
1017+
1018+
Ok(())
1019+
}
1020+
1021+
fn write_size_and_time(&self, size: u64, time: Option<SystemTime>) -> UResult<()> {
9981022
stdout().write_all(&self.convert_size(size))?;
9991023
write!(stdout(), "\t")?;
10001024

10011025
if self.time.is_some() {
1002-
if let Some(time) = stat.latest_time {
1026+
if let Some(time) = time {
10031027
format_system_time(
10041028
&mut stdout(),
10051029
time,
@@ -1012,9 +1036,6 @@ impl StatPrinter {
10121036
}
10131037
}
10141038

1015-
print_verbatim(&stat.path)?;
1016-
write!(stdout(), "{}", self.line_ending)?;
1017-
10181039
Ok(())
10191040
}
10201041
}
@@ -1229,6 +1250,7 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
12291250
time,
12301251
time_format,
12311252
line_ending: LineEnding::from_zero_flag(matches.get_flag(options::NULL)),
1253+
separate_dirs: matches.get_flag(options::SEPARATE_DIRS),
12321254
total_text: translate!("du-total"),
12331255
};
12341256

@@ -1296,8 +1318,13 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
12961318
Some(stat),
12971319
) {
12981320
Ok(stat) => {
1321+
let is_dir = stat.metadata.is_dir();
12991322
print_tx
1300-
.send(Ok(StatPrintInfo { stat, depth: 0 }))
1323+
.send(Ok(StatPrintInfo {
1324+
stat,
1325+
depth: 0,
1326+
is_dir,
1327+
}))
13011328
.map_err(|e| USimpleError::new(1, e.to_string()))?;
13021329
}
13031330
Err(e) => {
@@ -1326,8 +1353,13 @@ pub fn uumain(args: impl uucore::Args) -> UResult<()> {
13261353
)
13271354
.map_err(|e| USimpleError::new(1, e.to_string()))?;
13281355

1356+
let is_dir = stat.metadata.is_dir();
13291357
print_tx
1330-
.send(Ok(StatPrintInfo { stat, depth: 0 }))
1358+
.send(Ok(StatPrintInfo {
1359+
stat,
1360+
depth: 0,
1361+
is_dir,
1362+
}))
13311363
.map_err(|e| USimpleError::new(1, e.to_string()))?;
13321364
} else {
13331365
#[cfg(unix)]

‎tests/by-util/test_du.rs‎

Lines changed: 237 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1459,6 +1459,243 @@ fn test_du_time_unaffected_by_exclude() {
14591459
assert!(stdout.contains("\td\n"), "missing dir entry: {stdout}");
14601460
}
14611461

1462+
/// `du -S -c` still totals every directory. `--separate-dirs` only changes
1463+
/// the per-directory figure; the grand total keeps subdirectory usage.
1464+
#[test]
1465+
fn test_du_total_separate_dirs_includes_subdirectories() {
1466+
let ts = TestScenario::new(util_name!());
1467+
let at = &ts.fixtures;
1468+
1469+
at.mkdir_all("d/sub");
1470+
at.write("d/a.txt", "aaaaaaaa");
1471+
at.write("d/sub/nested.txt", "bbbb");
1472+
1473+
#[cfg(not(windows))]
1474+
let sub = "d/sub";
1475+
#[cfg(windows)]
1476+
let sub = "d\\sub";
1477+
1478+
let args = ["-b", "--separate-dirs", "--total", "d"];
1479+
ts.ucmd()
1480+
.args(&args)
1481+
.succeeds()
1482+
.stdout_only(format!("4\t{sub}\n8\td\n12\ttotal\n"));
1483+
assert_du_matches_gnu(&ts, &args);
1484+
1485+
// `--max-depth=0` hides the subdirectory line, but its bytes stay in the total.
1486+
let args = ["-b", "-S", "-c", "-d", "0", "d"];
1487+
ts.ucmd()
1488+
.args(&args)
1489+
.succeeds()
1490+
.stdout_only("8\td\n12\ttotal\n");
1491+
assert_du_matches_gnu(&ts, &args);
1492+
1493+
// Without -S the top entry already includes the subdirectory, so the total
1494+
// must not add it a second time.
1495+
let args = ["-b", "--total", "d"];
1496+
ts.ucmd()
1497+
.args(&args)
1498+
.succeeds()
1499+
.stdout_only(format!("4\t{sub}\n12\td\n12\ttotal\n"));
1500+
assert_du_matches_gnu(&ts, &args);
1501+
1502+
// `-a` lists files, which are already counted in their directory.
1503+
let args = ["-b", "-S", "-a", "-c", "d"];
1504+
let result = ts.ucmd().args(&args).succeeds();
1505+
let total = result.stdout_str().lines().next_back().unwrap();
1506+
assert_eq!(
1507+
total,
1508+
"12\ttotal",
1509+
"file lines double-counted: {}",
1510+
result.stdout_str()
1511+
);
1512+
assert_du_matches_gnu(&ts, &args);
1513+
}
1514+
1515+
/// Block size is applied to the summed byte count, not to each directory line.
1516+
#[test]
1517+
fn test_du_total_separate_dirs_block_size() {
1518+
let ts = TestScenario::new(util_name!());
1519+
let at = &ts.fixtures;
1520+
1521+
at.mkdir_all("d/sub");
1522+
at.write("d/a.txt", "aa");
1523+
at.write("d/sub/nested.txt", "bb");
1524+
1525+
#[cfg(not(windows))]
1526+
let sub = "d/sub";
1527+
#[cfg(windows)]
1528+
let sub = "d\\sub";
1529+
1530+
// ceil(2/3) = 1 per directory, ceil(4/3) = 2 for the total.
1531+
let args = ["--apparent-size", "-B", "3", "-S", "-c", "d"];
1532+
ts.ucmd()
1533+
.args(&args)
1534+
.succeeds()
1535+
.stdout_only(format!("1\t{sub}\n1\td\n2\ttotal\n"));
1536+
assert_du_matches_gnu(&ts, &args);
1537+
}
1538+
1539+
#[cfg(not(windows))]
1540+
fn assert_du_matches_gnu(ts: &TestScenario, args: &[&str]) {
1541+
let result = ts.ucmd().args(args).succeeds();
1542+
let reference = unwrap_or_return!(expected_result(ts, args));
1543+
if reference.succeeded() {
1544+
assert_eq!(result.stdout_str(), reference.stdout_str());
1545+
assert_eq!(result.stderr_str(), reference.stderr_str());
1546+
}
1547+
}
1548+
1549+
#[cfg(windows)]
1550+
fn assert_du_matches_gnu(_ts: &TestScenario, _args: &[&str]) {}
1551+
1552+
#[cfg(feature = "touch")]
1553+
#[test]
1554+
fn test_du_total_time_column() {
1555+
let ts = TestScenario::new(util_name!());
1556+
let at = &ts.fixtures;
1557+
1558+
at.mkdir_all("d/sub");
1559+
at.write("d/old.txt", "a");
1560+
at.write("d/sub/new.txt", "b");
1561+
1562+
for path in ["d/old.txt", "d", "d/sub"] {
1563+
ts.ccmd("touch")
1564+
.env("TZ", "UTC")
1565+
.args(&["-m", "-t", "202001010000"])
1566+
.arg(at.plus(path))
1567+
.succeeds();
1568+
}
1569+
ts.ccmd("touch")
1570+
.env("TZ", "UTC")
1571+
.args(&["-m", "-t", "202403011800"])
1572+
.arg(at.plus("d/sub/new.txt"))
1573+
.succeeds();
1574+
1575+
#[cfg(not(windows))]
1576+
let sub = "d/sub";
1577+
#[cfg(windows)]
1578+
let sub = "d\\sub";
1579+
1580+
let args = ["-b", "--time", "--total", "d"];
1581+
ts.ucmd()
1582+
.env("TZ", "UTC")
1583+
.args(&args)
1584+
.succeeds()
1585+
.stdout_only(format!(
1586+
"1\t2024-03-01 18:00\t{sub}\n2\t2024-03-01 18:00\td\n2\t2024-03-01 18:00\ttotal\n"
1587+
));
1588+
assert_du_matches_gnu(&ts, &args);
1589+
1590+
let args = ["-b", "--time", "--time-style=iso", "-c", "d"];
1591+
ts.ucmd()
1592+
.env("TZ", "UTC")
1593+
.args(&args)
1594+
.succeeds()
1595+
.stdout_only(format!(
1596+
"1\t2024-03-01\t{sub}\n2\t2024-03-01\td\n2\t2024-03-01\ttotal\n"
1597+
));
1598+
assert_du_matches_gnu(&ts, &args);
1599+
1600+
let args = ["-b", "--time", "--time-style=full-iso", "-c", "d"];
1601+
ts.ucmd()
1602+
.env("TZ", "UTC")
1603+
.args(&args)
1604+
.succeeds()
1605+
.stdout_only(format!(
1606+
"1\t2024-03-01 18:00:00.000000000 +0000\t{sub}\n\
1607+
2\t2024-03-01 18:00:00.000000000 +0000\td\n\
1608+
2\t2024-03-01 18:00:00.000000000 +0000\ttotal\n"
1609+
));
1610+
assert_du_matches_gnu(&ts, &args);
1611+
1612+
// -S keeps the subdirectory's newer mtime off the top line, but the total
1613+
// still uses the newest time in the tree. `--max-depth=0` hides the sub line.
1614+
let args = ["-b", "--time", "-S", "-c", "-d", "0", "d"];
1615+
ts.ucmd()
1616+
.env("TZ", "UTC")
1617+
.args(&args)
1618+
.succeeds()
1619+
.stdout_only("1\t2020-01-01 00:00\td\n2\t2024-03-01 18:00\ttotal\n");
1620+
assert_du_matches_gnu(&ts, &args);
1621+
}
1622+
1623+
#[cfg(feature = "touch")]
1624+
#[test]
1625+
fn test_du_total_time_atime_ctime() {
1626+
let ts = TestScenario::new(util_name!());
1627+
let at = &ts.fixtures;
1628+
1629+
at.write("file", "z");
1630+
ts.ccmd("touch")
1631+
.env("TZ", "UTC")
1632+
.args(&["-a", "-t", "201505150000"])
1633+
.arg(at.plus("file"))
1634+
.succeeds();
1635+
ts.ccmd("touch")
1636+
.env("TZ", "UTC")
1637+
.args(&["-m", "-t", "201606160000"])
1638+
.arg(at.plus("file"))
1639+
.succeeds();
1640+
1641+
let args = ["-b", "--time=atime", "--total", "file"];
1642+
ts.ucmd()
1643+
.env("TZ", "UTC")
1644+
.args(&args)
1645+
.succeeds()
1646+
.stdout_only("1\t2015-05-15 00:00\tfile\n1\t2015-05-15 00:00\ttotal\n");
1647+
assert_du_matches_gnu(&ts, &args);
1648+
1649+
// ctime cannot be set from touch. The total line carries the same stamp.
1650+
let args = ["-b", "--time=ctime", "-c", "file"];
1651+
let result = ts.ucmd().env("TZ", "UTC").args(&args).succeeds();
1652+
#[cfg(windows)]
1653+
result.stdout_only("1\t???\tfile\n1\t1970-01-01 00:00\ttotal\n");
1654+
#[cfg(not(windows))]
1655+
{
1656+
let lines: Vec<&str> = result.stdout_str().lines().collect();
1657+
assert_eq!(lines.len(), 2, "{}", result.stdout_str());
1658+
let file_time = lines[0].split('\t').nth(1).unwrap();
1659+
assert_eq!(
1660+
lines[1].split('\t').collect::<Vec<_>>(),
1661+
["1", file_time, "total"],
1662+
"{}",
1663+
result.stdout_str()
1664+
);
1665+
assert_du_matches_gnu(&ts, &args);
1666+
}
1667+
}
1668+
1669+
#[cfg(feature = "touch")]
1670+
#[test]
1671+
fn test_du_total_time_before_epoch() {
1672+
let ts = TestScenario::new(util_name!());
1673+
let at = &ts.fixtures;
1674+
1675+
// The file keeps its pre-1970 mtime. The total does not move backward.
1676+
at.write("old", "x");
1677+
ts.ccmd("touch")
1678+
.env("TZ", "UTC")
1679+
.args(&["-m", "-t", "196001011200"])
1680+
.arg(at.plus("old"))
1681+
.succeeds();
1682+
let args = ["-b", "--time", "-c", "old"];
1683+
ts.ucmd()
1684+
.env("TZ", "UTC")
1685+
.args(&args)
1686+
.succeeds()
1687+
.stdout_only("1\t1960-01-01 12:00\told\n1\t1970-01-01 00:00\ttotal\n");
1688+
assert_du_matches_gnu(&ts, &args);
1689+
1690+
// A path that cannot be statted still prints the epoch on the total line.
1691+
ts.ucmd()
1692+
.env("TZ", "UTC")
1693+
.args(&["--time", "-c", "missing"])
1694+
.fails()
1695+
.stdout_is("0\t1970-01-01 00:00\ttotal\n")
1696+
.stderr_contains("cannot access 'missing'");
1697+
}
1698+
14621699
#[cfg(not(any(windows, target_os = "openbsd")))]
14631700
#[cfg(feature = "chmod")]
14641701
#[test]

0 commit comments

Comments
 (0)