From 223284c964164cd5e07dbbfb763925922fbcb598 Mon Sep 17 00:00:00 2001 From: Jens Schmidt Date: Thu, 19 Oct 2023 23:00:32 +0200 Subject: [PATCH 2/2] Better handle errors when writing r-o files without backup * lisp/files.el (basic-save-buffer-2): Restore file permissions when writing read-only files without backup fails. (Bug#66546) --- lisp/files.el | 32 +++++++++++++++++++++++--------- 1 file changed, 23 insertions(+), 9 deletions(-) diff --git a/lisp/files.el b/lisp/files.el index adfe8bd44b9..9fc2f5f376a 100644 --- a/lisp/files.el +++ b/lisp/files.el @@ -5934,10 +5934,13 @@ basic-save-buffer-2 t)) ;; If file not writable, see if we can make it writable ;; temporarily while we write it (its original modes will be - ;; restored in 'basic-save-buffer'). But no need to do so if - ;; we have just backed it up (setmodes is set) because that - ;; says we're superseding. + ;; restored in 'basic-save-buffer' or, in case of an error, in + ;; the `unwind-protect' below). But no need to do so if we + ;; have just backed it up (setmodes is set) because that says + ;; we're superseding. (cond ((and tempsetmodes (not setmodes)) + ;; Remember we made the file writable. + (setq tempsetmodes 'u+w) ;; Change the mode back, after writing. (setq setmodes (list (file-modes buffer-file-name) @@ -5963,12 +5966,23 @@ basic-save-buffer-2 buffer-file-name nil t buffer-file-truename) (when save-silently (message nil)) (setq success t)) - ;; If we get an error writing the new file, and we made - ;; the backup by renaming, undo the backing-up. - (and setmodes (not success) - (progn - (rename-file (nth 2 setmodes) buffer-file-name t) - (setq buffer-backed-up nil))))))) + (cond + ;; If we get an error writing the file which we + ;; previously made writable, attempt to undo the + ;; write-access. + ((and (eq tempsetmodes 'u+w) (not success)) + (condition-case () + (unless + (with-demoted-errors "Error setting file modes: %S" + (set-file-modes buffer-file-name (car setmodes))) + (set-file-extended-attributes buffer-file-name + (nth 1 setmodes))) + (error nil))) + ;; If we get an error writing the new file, and we made + ;; the backup by renaming, undo the backing-up. + ((and setmodes (not success)) + (rename-file (nth 2 setmodes) buffer-file-name t) + (setq buffer-backed-up nil))))))) setmodes)) (declare-function diff-no-select "diff" -- 2.30.2