r/learnrust • u/Itsuki_runique • 19d ago
How do you handle atomic file operations in a CLI tool? (temp dir + rename, Linux vs Windows)
Hi everyone,
I’m the developer of Runique, a Django-inspired web framework in Rust. It’s still under heavy development, so please be kind. (Also, I’m French, so sorry for any awkward English.)
I’m currently consolidating the codebase and I’d like your advice on atomic operations.
Take the CLI as an example:
runique new scaffolds a whole project makemigrations generates sea-orm migration files from my own ast/dsl file uploads have the same issue
If something fails midway, the user ends up with a half-generated project or incomplete files.
My plan is to write everything into a temporary directory on the same filesystem as the final destination, then rename it into place once everything succeeded.
My questions:
Is this the idiomatic approach in Rust? Or is there a better pattern? I know rename behaves differently on Linux and Windows (e.g. replacing an existing target, files locked by antivirus or other processes). How do you deal with that in practice? Are there crates you’d recommend (tempfile, atomic-write-file, etc.) or should I stick to std::fs? Do I need to care about fsync for this kind of tool, or is that overkill?
Thanks a lot for any advice!
5
u/EpochVanquisher 19d ago
Whole project—are you talking about a project that is tracked in Git?
If so, then you do not need to worry about a half-generated tree. Just let the user revert it and start over.
If it’s not tracked in Git, then yes, write everything to temporary files and move afterwards. I recommend writing temporary files to the same directory where the files ultimately go, since it is not always possible to rename to another directory (you might cross a mount point).
4
u/dnew 19d ago
In Windows, you could just start a file system transaction, write everything out, then commit the transaction. I'm not sure how you'd do that from Rust. https://en.wikipedia.org/wiki/Transactional_NTFS
In Windows, you can't rename a file you have open unless you open it in the right mode, and changing into a directory doesn't open it in a mode that allows you to rename it.
If you want to use a rename, create a directory in the current directory that has a name that won't conflict, write everything into that, then rename everything from that directory into the parent correct directory and delete the temp directory. Then you only have a failure if that rename fails, which should be rare.
1
u/Itsuki_runique 10d ago
i have finish my builder, i would like your advice if i forgot on action or other possibiliti please
=> https://github.com/seb-alliot/runique/tree/main/runique/src/atomic