Skip to content

Find the largest files in a folder

fs.walk lists everything below a folder, and fs.metadata tells files from folders and gives their size. Links are listed but not followed, so a link pointing back up cannot send the walk in circles.

The example builds a small folder first, inside a temporary folder that is removed again when tmp goes away.

import fs
let tmp = try fs.temp_dir()
try fs.create_dir_all(&tmp.join(&"src/parser"))
try fs.write(&tmp.join(&"README.md"), &"hello".repeat(10))
try fs.write(&tmp.join(&"src/main.brass"), &"x".repeat(300))
try fs.write(&tmp.join(&"src/parser/lexer.brass"), &"y".repeat(1200))
let root = tmp.path()
let mut sizes: Vec<(i64, Str)> = []
for p in try fs.walk(&root) {
let info = try fs.metadata(&p)
if info.is_file() {
sizes.push((info.size, p.strip_prefix(root + "/").unwrap_or(p.clone())))
}
}
sizes.sort_by(fn(a: &(i64, Str), b: &(i64, Str)) -> i64 => b.0.compare(&a.0))
for (size, name) in &sizes {
print(f"{size:>6} {name}")
}
1200 src/parser/lexer.brass
300 src/main.brass
50 README.md

Outside the main file, the same code takes a permission, files: &fs.Files, and calls files.walk(...) and files.metadata(...). A permission narrowed with within(dir) refuses paths outside that folder.