1 ! Copyright (C) 2010 John Benediktsson
2 ! See http://factorcode.org/license.txt for BSD license
4 USING: accessors calendar combinators.short-circuit environment
5 formatting io io.directories io.encodings.utf8 io.files
6 io.files.info io.files.info.unix io.files.trash io.files.types
7 io.pathnames kernel math math.parser sequences system unix.stat
10 IN: io.files.trash.unix
12 ! Implements the FreeDesktop.org Trash Specification 0.7
16 : top-directory? ( path -- ? )
17 dup ".." append-path [ link-status ] bi@
18 [ [ st_dev>> ] same? not ] [ [ st_ino>> ] same? ] 2bi or ;
20 : top-directory ( path -- path' )
21 [ dup top-directory? not ] [ ".." append-path ] while ;
23 : make-user-directory ( path -- )
24 [ make-directories ] [ 0o700 set-file-permissions ] bi ;
26 : check-trash-path ( path -- )
28 [ file-info directory? ]
30 [ link-info type>> +symbolic-link+ = not ]
31 } 1&& [ "invalid trash path" throw ] unless ;
33 : trash-home ( -- path )
34 "XDG_DATA_HOME" os-env
35 home ".local/share" append-path or
36 "Trash" append-path dup check-trash-path ;
38 : trash-1 ( root -- path )
39 ".Trash" append-path dup check-trash-path
40 real-user-id number>string append-path ;
42 : trash-2 ( root -- path )
43 real-user-id ".Trash-%d" sprintf append-path ;
45 : trash-path ( path -- path' )
46 top-directory dup trash-home top-directory = [
49 dup ".Trash" append-path exists?
50 [ trash-1 ] [ trash-2 ] if
51 [ make-user-directory ] keep
54 : (safe-file-name) ( path counter -- path' )
58 [ file-extension dup [ "." prepend ] when ] tri
59 ] dip swap "%s%s %s%s" sprintf ;
61 : safe-file-name ( path -- path' )
62 dup 0 [ over exists? ] [
63 [ parent-directory to-directory ] [ 1 + ] bi*
64 [ (safe-file-name) ] keep
69 M: unix send-to-trash ( path -- )
71 "files" append-path [ make-user-directory ] keep
72 to-directory safe-file-name
74 "info" append-path [ make-user-directory ] keep
75 to-directory ".trashinfo" append [ over ] dip utf8 [
76 "[Trash Info]" write nl
77 "Path=" write write nl
79 now "%Y-%m-%dT%H:%M:%S" strftime write nl