1 ! Copyright (C) 2008 Doug Coleman.
2 ! See http://factorcode.org/license.txt for BSD license.
3 USING: arrays combinators continuations fry io io.backend
4 io.directories io.directories.hierarchy io.files io.pathnames
5 kernel locals math math.bitwise math.parser namespaces random
6 sequences system vocabs random.data ;
9 HOOK: (touch-unique-file) io-backend ( path -- )
10 : touch-unique-file ( path -- )
11 normalize-path (touch-unique-file) ;
13 HOOK: default-temporary-directory io-backend ( -- path )
15 SYMBOL: current-temporary-directory
18 SYMBOL: unique-retries
20 10 unique-length set-global
21 10 unique-retries set-global
23 : with-temporary-directory ( path quot -- )
24 [ current-temporary-directory ] dip with-variable ; inline
28 : random-file-name ( -- string )
29 unique-length get random-string ;
31 : retry ( quot: ( -- ? ) n -- )
32 iota swap [ drop ] prepose attempt-all ; inline
34 : (make-unique-file) ( path prefix suffix -- path )
36 _ _ _ random-file-name glue append-path
38 ] unique-retries get retry ;
42 : make-unique-file ( prefix suffix -- path )
43 [ current-temporary-directory get ] 2dip (make-unique-file) ;
45 : cleanup-unique-file ( prefix suffix quot: ( path -- ) -- )
46 [ make-unique-file ] dip [ delete-file ] bi ; inline
48 : unique-directory ( -- path )
50 current-temporary-directory get
51 random-file-name append-path
53 ] unique-retries get retry ;
55 : with-unique-directory ( quot -- path )
56 [ unique-directory ] dip
57 [ with-temporary-directory ] [ drop ] 2bi ; inline
59 : cleanup-unique-directory ( quot: ( -- ) -- )
60 [ unique-directory ] dip
61 '[ _ with-temporary-directory ] [ delete-tree ] bi ; inline
63 : unique-file ( prefix -- path )
66 : move-file-unique ( path prefix suffix -- path' )
67 make-unique-file [ move-file ] keep ;
69 : copy-file-unique ( path prefix suffix -- path' )
70 make-unique-file [ copy-file ] keep ;
72 : temporary-file ( -- path ) "" unique-file ;
74 :: cleanup-unique-working-directory ( quot -- )
75 unique-directory :> path
76 path [ path quot with-temporary-directory ] with-directory
77 path delete-tree ; inline
80 { [ os unix? ] [ "io.files.unique.unix" ] }
81 { [ os windows? ] [ "io.files.unique.windows" ] }
84 default-temporary-directory current-temporary-directory set-global