]> gitweb.factorcode.org Git - factor.git/blob - extra/io/files/trash/unix/unix.factor
io.files: exists? -> file-exists? and rename primitive.
[factor.git] / extra / io / files / trash / unix / unix.factor
1 ! Copyright (C) 2010 John Benediktsson
2 ! See http://factorcode.org/license.txt for BSD license
3
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 ;
9
10 IN: io.files.trash.unix
11
12 ! Implements the FreeDesktop.org Trash Specification 0.7
13
14 <PRIVATE
15
16 : top-directory? ( path -- ? )
17     dup ".." append-path [ link-status ] bi@
18     [ [ st_dev>> ] same? not ] [ [ st_ino>> ] same? ] 2bi or ;
19
20 : top-directory ( path -- path' )
21     [ dup top-directory? not ] [ ".." append-path ] while ;
22
23 : make-user-directory ( path -- )
24     [ make-directories ] [ 0o700 set-file-permissions ] bi ;
25
26 : check-trash-path ( path -- )
27     {
28         [ file-info directory? ]
29         [ sticky? ]
30         [ link-info symbolic-link? not ]
31     } 1&& [ "invalid trash path" throw ] unless ;
32
33 : trash-home ( -- path )
34     xdg-data-home "Trash" append-path dup check-trash-path ;
35
36 : trash-1 ( root -- path )
37     ".Trash" append-path dup check-trash-path
38     real-user-id number>string append-path ;
39
40 : trash-2 ( root -- path )
41     real-user-id ".Trash-%d" sprintf append-path ;
42
43 : trash-path ( path -- path' )
44     top-directory dup trash-home top-directory = [
45         drop trash-home
46     ] [
47         dup ".Trash" append-path file-exists?
48         [ trash-1 ] [ trash-2 ] if
49         [ make-user-directory ] keep
50     ] if ;
51
52 : (safe-file-name) ( path counter -- path' )
53     [
54         [ parent-directory ]
55         [ file-stem ]
56         [ file-extension dup [ "." prepend ] when ] tri
57     ] dip swap "%s%s %s%s" sprintf ;
58
59 : safe-file-name ( path -- path' )
60     dup 0 [ over file-exists? ] [
61         [ parent-directory to-directory ] [ 1 + ] bi*
62         [ (safe-file-name) ] keep
63     ] while drop nip ;
64
65 PRIVATE>
66
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
71     ] [
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
76             "DeletionDate=" write
77             now "%Y-%m-%dT%H:%M:%S" strftime write nl
78         ] with-file-writer
79     ] bi move-file ;