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 math math.bitwise math.parser namespaces random
6 sequences system vocabs.loader ;
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-letter ( -- ch )
29 26 random { CHAR: a CHAR: A } random + ;
33 [ 10 random CHAR: 0 + ] [ random-letter ] if ;
35 : random-name ( -- string )
36 unique-length get [ random-ch ] "" replicate-as ;
38 : (make-unique-file) ( path prefix suffix -- path )
40 _ _ _ random-name glue append-path
42 ] unique-retries get retry ;
46 : make-unique-file ( prefix suffix -- path )
47 [ current-temporary-directory get ] 2dip (make-unique-file) ;
49 : cleanup-unique-file ( prefix suffix quot: ( path -- ) -- )
50 [ make-unique-file ] dip [ delete-file ] bi ; inline
52 : unique-directory ( -- path )
54 current-temporary-directory get
55 random-name append-path
57 ] unique-retries get retry ;
59 : with-unique-directory ( quot -- path )
60 [ unique-directory ] dip
61 [ with-temporary-directory ] [ drop ] 2bi ; inline
63 : cleanup-unique-directory ( quot: ( -- ) -- )
64 [ unique-directory ] dip
65 '[ _ with-temporary-directory ] [ delete-tree ] bi ; inline
67 : unique-file ( path -- path' )
71 { [ os unix? ] [ "io.files.unique.unix" ] }
72 { [ os windows? ] [ "io.files.unique.windows" ] }
75 default-temporary-directory current-temporary-directory set-global