Menu

fs::rename overwrites without a word. Four checks my file organizer runs first.
πŸ“°

fs::rename overwrites without a word. Four checks my file organizer runs first.

DEV Community: rustΒ·Marcus BeauregardΒ·13 days ago
#gDFsXqC6
#devtorust#devto#dev#path#extension
Long article (980 words) β€” no AI summary yet.
Reading 0:00
15s threshold

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 ) ? ;

Enter fullscreen mode

Exit fullscreen mode

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 .…

Continue reading β€” create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.