withr icon indicating copy to clipboard operation
withr copied to clipboard

consider 'with_backup' helper?

Open kevinushey opened this issue 7 years ago • 3 comments

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)
}

kevinushey avatar Aug 30 '17 23:08 kevinushey

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

krlmlr avatar Aug 31 '17 05:08 krlmlr

Yeah that seems reasonable, we can use a similar approach to with_tempfile(), which hasn't yet made it to master...

jimhester avatar Aug 31 '17 13:08 jimhester

I think a good name for the behavior suggested by @krlmlr would be with_atomic_file.

DarwinAwardWinner avatar Dec 06 '17 19:12 DarwinAwardWinner