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.backend io.directories io.encodings.utf8
6 io.files io.files.info io.files.info.unix io.files.trash
7 io.files.types io.pathnames kernel math math.parser sequences
8 system unix.stat unix.users xdg ;
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 symbolic-link? not ]
31 } 1&& [ "invalid trash path" throw ] unless ;
33 : trash-home ( -- path )
34 xdg-data-home "Trash" append-path dup check-trash-path ;
36 : trash-1 ( root -- path )
37 ".Trash" append-path dup check-trash-path
38 real-user-id number>string append-path ;
40 : trash-2 ( root -- path )
41 real-user-id ".Trash-%d" sprintf append-path ;
43 : trash-path ( path -- path' )
44 top-directory dup trash-home top-directory = [
47 dup ".Trash" append-path file-exists?
48 [ trash-1 ] [ trash-2 ] if
49 [ make-user-directory ] keep
52 : (safe-file-name) ( path counter -- path' )
56 [ file-extension dup [ "." prepend ] when ] tri
57 ] dip swap "%s%s %s%s" sprintf ;
59 : safe-file-name ( path -- path' )
60 dup 0 [ over file-exists? ] [
61 [ parent-directory to-directory ] [ 1 + ] bi*
62 [ (safe-file-name) ] keep
67 M: unix send-to-trash ( path -- )
68 normalize-path dup trash-path [
69 "files" append-path [ make-user-directory ] keep
70 to-directory safe-file-name
72 "info" append-path [ make-user-directory ] keep
73 to-directory ".trashinfo" append overd utf8 [
74 "[Trash Info]" write nl
75 "Path=" write write nl
77 now "%Y-%m-%dT%H:%M:%S" strftime write nl