safely.lisp: More on the CLisp RENAME-FILE mess.
[lisp] / safely.lisp
1 ;;; -*-lisp-*-
2 ;;;
3 ;;; $Id$
4 ;;;
5 ;;; Safely modify collections of files
6 ;;;
7 ;;; (c) 2005 Straylight/Edgeware
8 ;;;
9
10 ;;;----- Licensing notice ---------------------------------------------------
11 ;;;
12 ;;; This program is free software; you can redistribute it and/or modify
13 ;;; it under the terms of the GNU General Public License as published by
14 ;;; the Free Software Foundation; either version 2 of the License, or
15 ;;; (at your option) any later version.
16 ;;;
17 ;;; This program is distributed in the hope that it will be useful,
18 ;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 ;;; GNU General Public License for more details.
21 ;;;
22 ;;; You should have received a copy of the GNU General Public License
23 ;;; along with this program; if not, write to the Free Software Foundation,
24 ;;; Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
25
26 (defpackage #:safely
27 (:use #:common-lisp #:mdw.base)
28 (:export #:safely #:safely-close #:safely-delete-file
29 #:safely-open-output-stream #:safely-bail #:safely-commit
30 #:safely-writing))
31 (in-package #:safely)
32
33 #+(or cmu sbcl)
34 (eval-when (:compile-toplevel :execute)
35 (import #+cmu '(ext:unix-namestring unix:unix-link)
36 #+sbcl '(sb-ext:native-namestring)))
37 #+cmu
38 (progn
39 (declaim (inline unix-namestring))
40 (defun native-namestring (pathname &key as-file)
41 (declare (ignore as-file))
42 (unix-namestring pathname nil)))
43
44 (defstruct (safely (:predicate safelyp))
45 "Stores information about how to commit or undo safe writes."
46 (streams nil)
47 (trail nil))
48
49 (defun safely-close (safe stream)
50 "Make sure that STREAM is closed when SAFE is finished."
51 (push stream (safely-streams safe)))
52
53 (defun safely-delete-file (safe file)
54 "Delete FILE when SAFE is committed."
55 (push `(:delete ,file) (safely-trail safe)))
56
57 (defun generate-fresh-file-name (base tag &optional func)
58 "Return a fresh file name constructed from BASE (a filespec) and TAG (some
59 short descriptive string). The generated name has the same directory and
60 type as the BASE name, but a different name.
61
62 If FUNC is non-nil, then it is a function to call on the generated file
63 name: generate-fresh-file-name runs in a loop, calling FUNC with generated
64 file names until FUNC returns non-nil, at which point generate-fresh-
65 file-name returns two values: the generated name, and the result of FUNC.
66 generate-fresh-file-name catches errors of type file-error from FUNC, and
67 just tries again with a new name.
68
69 If FUNC is nil, it's treated the same as a function which always returns
70 t.
71
72 This is inspired by a similar facility in scsh."
73 (let ((base (pathname base)))
74 (dotimes (i 256
75 (error "Gave up trying to find a temporary ~A file for ~S."
76 tag base))
77 (let* ((new (merge-pathnames
78 (make-pathname
79 :name (format nil "~A-~A-~X"
80 (pathname-name base)
81 tag
82 (random most-positive-fixnum)))
83 base))
84 (ret (and (not (probe-file new))
85 (if func
86 (handler-case (funcall func new)
87 (file-error (cond)
88 (unless (pathname-match-p
89 (file-error-pathname cond)
90 new)
91 (error cond))
92 nil))
93 t))))
94 (when ret
95 (return (values new ret)))))))
96
97 (defun safely-open-output-stream (safe file &rest open-args)
98 "Create an output stream which will be named FILE when SAFE is committed.
99 Other OPEN-ARGS are passed to open."
100 (multiple-value-bind
101 (name stream)
102 (generate-fresh-file-name file "new"
103 (lambda (name)
104 (apply #'open name
105 :direction :output
106 :if-exists nil
107 open-args)))
108 (safely-close safe stream)
109 (push `(:shunt ,name ,file)
110 (safely-trail safe))
111 stream))
112
113 #+clisp
114 (progn
115 (ffi:def-call-out %rename (:name "rename")
116 (:language :stdc)
117 (:arguments (from ffi:c-string)
118 (to ffi:c-string))
119 (:return-type ffi:int)))
120
121 (declaim (inline rename))
122 (defun rename (old new)
123 #-clisp
124 (let ((target (make-pathname :directory '(:relative)
125 :defaults new)))
126 (rename-file old target))
127
128 #+clisp
129 (let ((rc (%rename (namestring old) (namestring new))))
130 (when (= rc -1)
131 (error "Failed to rename ~S to ~S: ~A" old new (posix:strerror)))))
132
133 (defun delete-file-without-moaning (file)
134 "Delete the FILE, ignoring errors."
135 (handler-case (delete-file file)
136 (file-error () nil)))
137
138 (defun rename-file-without-moaning (old new)
139 "Rename OLD to NEW, ignoring errors, and without doing any stupid name
140 mangling."
141 (handler-case (rename old new)
142 (file-error () nil)))
143
144 (defun safely-unwind (trail)
145 "Roll back the TRAIL of operations."
146 (dolist (job trail)
147 (ecase (car job)
148 (:shunt (destructuring-bind (new file) (cdr job)
149 (declare (ignore file))
150 (delete-file-without-moaning new)))
151 (:delete)
152 (:rmtmp (destructuring-bind (file) (cdr job)
153 (delete-file-without-moaning file)))
154 (:revert (destructuring-bind (old new) (cdr job)
155 (rename-file-without-moaning old new))))))
156
157 (defun safely-reset (safe)
158 "Reset SAFE to its initial state."
159 (setf (safely-streams safe) nil)
160 (setf (safely-trail safe) nil))
161
162 (defun safely-bail (safe)
163 "Abort the operations in SAFE, unwinding all the things that have been
164 done. Streams are closed, new files are removed."
165 (dolist (stream (safely-streams safe))
166 (close stream :abort t))
167 (safely-unwind (safely-trail safe))
168 (safely-reset safe))
169
170 #+sbcl
171 (defun unix-link (from to)
172 (sb-unix::int-syscall ("link" sb-alien:c-string sb-alien:c-string)
173 from to))
174
175 (defun safe-copy (file tag)
176 "Make a copy of the FILE. Return the new name."
177
178 #+(or cmu sbcl)
179 ;; Use link(2) where available.
180 (generate-fresh-file-name file tag
181 (lambda (name)
182 (let ((from (native-namestring file
183 :as-file t))
184 (to (native-namestring name
185 :as-file t)))
186 (and from to
187 (unix-link from to)))))
188
189 #+clisp
190 (generate-fresh-file-name file tag
191 (lambda (name)
192 (posix:copy-file (namestring file)
193 (namestring name)
194 :method :hardlink
195 :if-exists nil)))
196
197 #-(or cmu sbcl clisp)
198 ;; Otherwise just copy the file contents and hope for the best.
199 (with-open-file (input file :element-type :default)
200 (multiple-value-bind
201 (copy output)
202 (generate-fresh-file-name file tag
203 (lambda (name)
204 (open name
205 :direction :output
206 :if-exists nil
207 :element-type :default)))
208 (unwind-protect
209 (progn
210 (let ((buffer (make-array 8192
211 :element-type (stream-element-type
212 input))))
213 (loop
214 (let ((read (read-sequence buffer input)))
215 (when (plusp read)
216 (write-sequence buffer output :end read))
217 (when (< read (length buffer))
218 (return copy))))))
219 (close output)))))
220
221 (defun safely-commit (safe)
222 "Commit SAFE. The files deleted by safely-delete-file are deleted; the
223 files created by safely-open-output-stream are renamed over the old
224 versions, if any. If a problem occurs during this stage, everything is
225 rewound and no changes are made."
226 (let ((trail (safely-trail safe))
227 (revert nil)
228 (cleanup nil))
229 (unwind-protect
230 (progn
231 (dolist (stream (safely-streams safe))
232 (close stream))
233 (loop
234 (unless trail
235 (return))
236 (let ((job (pop trail)))
237 (ecase (car job)
238 (:shunt (destructuring-bind (tag new file) job
239 (declare (ignore tag))
240 (push `(:rmtmp ,new) revert)
241 (if (probe-file file)
242 (let ((old (safe-copy file "old")))
243 (push `(:rmtmp ,old) cleanup)
244 (push `(:revert ,old ,file) revert))
245 (push `(:rmtmp ,file) revert))
246 (rename new file)))
247 (:delete (destructuring-bind (tag file) job
248 (declare (ignore tag))
249 (let ((old (safe-copy file "delete")))
250 (push `(:revert ,old ,file) revert)
251 (push `(:rmtmp ,old) cleanup)
252 (delete-file file)))))))
253 (setf revert nil))
254 (safely-unwind trail)
255 (safely-unwind revert)
256 (safely-unwind cleanup)
257 (safely-reset safe))))
258
259 (defmacro safely ((safe &key) &body body)
260 "Do stuff within the BODY safely. If BODY completes without errors, the
261 SAFE is committed; otherwise it's bailed."
262 `(let ((,safe (make-safely)))
263 (unwind-protect
264 (progn
265 ,@body
266 (safely-commit ,safe)
267 (setf ,safe nil))
268 (when ,safe
269 (safely-bail ,safe)))))
270
271 (defmacro safely-writing ((stream file &rest open-args) &body body)
272 "Simple macro for writing a single file safely. STREAM is opened onto a
273 temporary file, and if BODY completes, it is renamed to FILE."
274 (with-gensyms safe
275 `(safely (,safe)
276 (let ((,stream (safely-open-output-stream ,safe ,file ,@open-args)))
277 ,@body))))
278
279 ;;;----- That's all, folks --------------------------------------------------