Skip to content

Instantly share code, notes, and snippets.

@m2ym
Created August 26, 2011 13:16
Show Gist options
  • Save m2ym/1173374 to your computer and use it in GitHub Desktop.
Save m2ym/1173374 to your computer and use it in GitHub Desktop.
WITH-OPEN-FILE-ATOMICALLY
(defmacro with-open-file-atomically-1 ((var filename . args) &body body)
(alexandria:once-only (filename)
(alexandria:with-gensyms (tempfile stream done)
`(let ((,tempfile (merge-pathnames ".tem" ,filename)) ,stream ,done)
(unwind-protect
(multiple-value-prog1
(let ((,var (setq ,stream (open ,tempfile :if-exists :error ,@args))))
,@body)
(setq ,done t))
(when ,stream
(close ,stream :abort (null ,done))
(if ,done
(osicat-posix:rename ,tempfile ,filename)
(osicat-posix:unlink ,tempfile))))))))
(defmacro with-open-file-atomically ((var filename . args) &body body)
(destructuring-bind (&key direction if-exists &allow-other-keys) args
(if (and (member direction '(:io :output))
(eq if-exists :supersede))
`(with-open-file-atomically-1 (,var ,filename ,@args) ,@body)
`(with-open-file (,var ,filename ,@args) ,@body))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment