Subject: bug#58721: 28.2; dired with delete-by-moving-to-trash can't trash directory twice

From: Mike Kupfer <[email-masked]>
Date: Sun, 30 Oct 2022 10:40:24 -0700

Eli Zaretskii wrote:

> I just thought you'd be able to call copy-directory, similarly (but
> differently) to what rename-file does, instead of using your
> lambda-function.

Ah, of course.  Thanks, yes, that's cleaner.  How does the attached
patch look?

mike

>From e8fdbeb44dbea9ebf5679c23bf3ad5c5a61141ec Mon Sep 17 00:00:00 2001
From: Mike Kupfer <[email-masked]>
Date: Sun, 30 Oct 2022 10:31:11 -0700
Subject: [PATCH] Fix cross-filesystem directory trashing (Bug#58721)

* lisp/files.el (move-file-to-trash): When trashing a directory,
copy it into the trash folder and then delete it, rather than
using rename-file.
---
 lisp/files.el | 14 ++++++++++++--
 1 file changed, 12 insertions(+), 2 deletions(-)

diff --git a/lisp/files.el b/lisp/files.el
index 1e1ec6127d..b347815314 100644
--- a/lisp/files.el
+++ b/lisp/files.el
@@ -8565,10 +8565,20 @@ move-file-to-trash
 		    (setq files-base (substring (file-name-nondirectory info-fn)
                                                 0 (- (length ".trashinfo"))))
 		    (write-region nil nil info-fn nil 'quiet info-fn)))
-		 ;; Finally, try to move the file to the trashcan.
+		 ;; Finally, try to move the item to the trashcan.  If
+                 ;; it's a file, just move it.  If it's a directory,
+                 ;; rename-file will not work across filesystems, so
+                 ;; copy the directory tree and then delete it.
 		 (let ((delete-by-moving-to-trash nil)
 		       (new-fn (file-name-concat trash-files-dir files-base)))
-		   (rename-file fn new-fn overwrite)))))))))
+                   (if (not (file-directory-p fn))
+                       (rename-file fn new-fn overwrite)
+                     (make-directory new-fn)
+                     (copy-directory fn
+                                     (file-name-as-directory new-fn)
+                                     t nil t)
+                     (delete-directory fn t))))))))))
+
 
 
 (defsubst file-attribute-type (attributes)
-- 
2.30.2