withr
withr copied to clipboard
consider 'with_backup' helper?
I'm imaging a case where you're writing a function that attempts to write a file at some location, but restores the old copy (filesystem state) if something goes wrong during update. E.g.
with_backup <- function(file, expr) {
backup <- tempfile(
pattern = sprintf(".backup-%s-", tools::file_path_sans_ext(basename(file))),
tmpdir = dirname(file),
fileext = paste0(".", tools::file_ext(file))
)
file.rename(file, backup)
on.exit({
if (file.exists(file))
unlink(backup)
else
file.rename(backup, file)
})
force(expr)
}
i'd always write to a temporary location and then substitute on success (via file rename). Even with a with_backup()
function the in-place update is unsafe if the R session terminates (e.g., when debugging).
Yeah that seems reasonable, we can use a similar approach to with_tempfile(), which hasn't yet made it to master...
I think a good name for the behavior suggested by @krlmlr would be with_atomic_file
.