Cross platform move to trash

Viewed 174

Is there a cross-platform way to move files to trash? file delete deletes the file completely and is not undoable on unixen. Even on Linux alone it's not straight forward to figure out the trash directory because it often depends on the file manager.

I've resorted to doing:

exec gio trash $file

The problem is that this only works on Gnome so even on Linux it is not cross-platform.

And as I don't have a Windows machine, figuring out how trash/recycle bin works in Windows is even more difficult

2 Answers

The FreeDesktop.org Trash specification says:

For every user a "home trash" directory MUST be available. Its name and location are $XDG_DATA_HOME/Trash; $XDG_DATA_HOME is the base directory for user-specific data, as defined in the Desktop Base Directory Specification.

If $XDG_DATA_HOME is unset or empty, it defaults to $HOME/.local/share.

However, you can't just move files in and out of ~/.local/share/Trash. There are some metadata files involved that store the original location and timestamps. These metadata files are plain text, so they can be easily handled in Tcl.

So this sounds like it could be quite easily implemented in a Tcl module. But if such a module already exists, I'm not aware of it. It could be a nice project for someone learning Tcl.

ADDED INFORMATION:

As usual, TWAPI to the rescue for Windows. The twapi_shell package has a recycle_file command.

Here's how to do it on macOS. This requires the Tclapplescript extension package:

package require Tclapplescript

proc trash args {
    set TRASH_CMD {
        tell application "Finder" to delete POSIX file "%s"
    }
    foreach file $args {
        set fullFilename [file normalize $file]
        set quoted [string map {\\ \\\\ \\" \\\\"} $fullFilename]
        AppleScript execute [format $TRASH_CMD $quoted]
    }
}

On recent versions of macOS, you'll need to grant appropriate permissions at runtime to let this work (or at least I had to when testing it).

See also:

Related