I wrote a small Rust CLI called fileforge that tidies a folder into per-extension subfolders. The actual move is one line:
fs::rename(path, &destination)?;
Everything else in the program exists because of what can go wrong before that line runs. Four of those things cost me a test each, and none of them are Rust quirks — they're the filesystem telling you what it actually does, as opposed to what the API name suggests.
1. rename replaces the destination
POSIX rename(2) does not fail when the target exists. It unlinks it and puts yours in its place. So "organize my Downloads folder" is one repeated filename away from "delete the file that was already there."
The check has to happen before the call, and it has to use symlink_metadata:
fn destination_taken(path: &Path) -> io::Result<bool> {
match fs::symlink_metadata(path) {
Ok(_) => Ok(true),
Err(err) if err.kind() == io::ErrorKind::NotFound => Ok(false),
Err(err) => Err(err),
}
}
Path::exists() would be shorter and wrong twice. It follows symlinks, so a dangling link at the destination reads as "free" and then gets replaced — the link is gone and nobody was told. And it answers false for every error, including permission denied, which turns "I couldn't look" into "nothing's there." Only NotFound means free; everything else gets reported.
2. An empty extension is not an extension
Path::extension() on foo. returns Some(""). I checked, because I didn't believe it the first time:
foo. extension=Some("")
.tar.gz extension=Some("gz")
a.PDF extension=Some("PDF")
README extension=None
dir.join("") is dir, so the destination for foo. is the file itself, in the folder it's already sitting in. The fix is a filter, not a special case:
path.extension()
.and_then(|ext| ext.to_str())
.map(str::to_lowercase)
.filter(|ext| !ext.is_empty())
.unwrap_or_else(|| "misc".to_string())
Extensionless files and dotfiles end up in misc/ together, which is the honest answer: nothing about README says where it belongs.
3. backup.tar.gz should not go in gz/
A single extension() call puts backup.tar.gz next to plain.gz, and the archive is not a gzip log. A short list of compound suffixes, longest first, handles it:
const COMPOUND_SUFFIXES: [&str; 5] = ["tar.bz2", "tar.zst", "tar.gz", "tar.xz", "tar.z"];
fn extension_for(path: &Path) -> String {
if let Some(name) = path.file_name() {
let lower = name.to_string_lossy().to_lowercase();
for suffix in COMPOUND_SUFFIXES {
if lower.len() > suffix.len() + 1
&& lower.ends_with(suffix)
&& lower.as_bytes()[lower.len() - suffix.len() - 1] == b'.'
{
return (*suffix).to_string();
}
}
}
// single extension, or "misc"
}
Two details are load-bearing. The lower.len() > suffix.len() + 1 guard keeps a file literally named .tar.gz — a dotfile, not a tarball — out of tar.gz/; it goes to gz/ with the rest. And to_string_lossy rather than to_str means a filename that isn't valid UTF-8 still sorts, because only the ASCII suffix has to match; the replacement characters can't spell a dot or a letter, so the check stays as strict as before.
Running it on a folder of odd names, --dry-run:
would move .../backup.tar.gz -> tar.gz/
would move .../plain.gz -> gz/
would move .../.tar.gz -> gz/
would move .../notes.TXT -> txt/
would move .../trailing. -> misc/
would move .../README -> misc/
4. is_file() drops what it cannot read
Path::is_file() answers false when the metadata call fails, so an entry you can't inspect just disappears from the count. The folder ends up half-organized and the summary says everything was fine. fs::metadata hands back the error instead:
match fs::metadata(&path) {
Ok(meta) if meta.is_file() => {}
Ok(_) => continue, // a directory: not ours to touch
Err(err) => { /* report it, count it, carry on */ }
}
It also follows symlinks, which is exactly the view rename will take.
Skips are not failures; failed moves are
--dry-run has to walk the same code path as the real run, or the preview is a different program that happens to share a CLI. When the plan and the run disagree, the run is right and the preview is the bug. That's why the collision check sits above the if dry_run branch instead of inside it.
Exit status: a name collision is a decision, not an error, so it exits 0. A move that threw is an error and exits 1 — after the rest of the folder still gets organized, because one bad file shouldn't stop the other nine hundred. And the failure line names both ends, since Permission denied with no paths in it is not a bug report.
Fourteen tests, four of them building real symlinks in temp dirs, green on my machine this evening. The tool is unglamorous and does one thing. That's the point.
Top comments (5)
there's still a race between
symlink_metadata(destination)andfs::rename: another process can create the target after the check, and rename will overwrite it anyway. on Linux,renameat2(RENAME_NOREPLACE)would make the no-clobber step atomic. on other platforms i'd document the check as best-effort rather than a guarantee."I couldn't look" turning into "nothing's there" got me in a scheduled job. My daily ad-attribution pull kept exiting as a success while the provider refused every single call, because of one header it didn't accept. Nothing alerted.
It exits non-zero now when most lookups fail, so the scheduler records a failed run. And an answer it couldn't save counts as failed, not as checked.
The replace-on-rename is the same behaviour I lean on in my notes app, just from the other side. Every save writes a ...tmp next to the file, fsyncs it, then renames over the real one, so a crash leaves the old note or the new one, never half of each. The cost is the temp files a crash leaves behind, so opening the folder sweeps any temp older than 5 minutes.
Tested your sweep rule; it can eat a live save. Same pattern as yours: tmp beside the target, write half, fsync, then go quiet. I aged the tmp's mtime to 301s to stand in for a slow save, ran the folder-open sweep, then wrote the rest and renamed. Result: rename fails ENOENT (errno 2), the target still says the old text, the tmp is gone. The sweep unlinked an inode that was still open and still being written, and nothing left in the folder shows it.
Two cheap fixes: put the pid in the tmp name and sweep only temps whose pid is dead (/proc/), or sweep at app start instead of on every folder open. And the writer has to treat a failed rename as a failed save, not best effort. Old text sitting there looks exactly like success.
20 lines of python, receipt stands if you want it.
The exit status rule is where I'd push back. A collision skip exits 0 and a failed move exits 1, so a wrapper script can't tell "organized everything" from "organized some of it and deliberately refused the rest" — that distinction survives only in prose on stdout, which scripts don't read. From the caller's side that is the same shape of lie as
Path::exists(): one answer, "fine", overloaded over two different states. A third exit code, or a--jsonsummary carryingskipped: N, would make the difference countable.Everything above it holds.
symlink_metadatawith NotFound-only-means-free is the honest pair, and the dry-run walking the real code path is the part most tools get wrong.