]> gitweb.factorcode.org Git - factor.git/blob - basis/io/directories/unix/unix.factor
0cc8aaa0e43766f2e508eaebd154e4a33fa61a4e
[factor.git] / basis / io / directories / unix / unix.factor
1 ! Copyright (C) 2008 Slava Pestov.
2 ! See http://factorcode.org/license.txt for BSD license.
3 USING: accessors alien.c-types alien.strings combinators
4 continuations destructors fry io io.backend io.backend.unix
5 io.directories io.encodings.binary io.encodings.utf8 io.files
6 io.pathnames io.files.types kernel math.bitwise sequences system
7 unix unix.stat vocabs.loader classes.struct unix.ffi literals ;
8 IN: io.directories.unix
9
10 CONSTANT: touch-mode flags{ O_WRONLY O_APPEND O_CREAT O_EXCL }
11
12 M: unix touch-file ( path -- )
13     normalize-path
14     dup exists? [ touch ] [
15         touch-mode file-mode open-file close-file
16     ] if ;
17
18 M: unix move-file ( from to -- )
19     [ normalize-path ] bi@ [ rename ] unix-system-call drop ;
20
21 M: unix delete-file ( path -- ) normalize-path unlink-file ;
22
23 M: unix make-directory ( path -- )
24     normalize-path OCT: 777 [ mkdir ] unix-system-call drop ;
25
26 M: unix delete-directory ( path -- )
27     normalize-path [ rmdir ] unix-system-call drop ;
28
29 M: unix copy-file ( from to -- )
30     [ normalize-path ] bi@ call-next-method ;
31
32 : with-unix-directory ( path quot -- )
33     [ opendir dup [ (io-error) ] unless ] dip
34     dupd curry swap '[ _ closedir io-error ] [ ] cleanup ; inline
35
36 HOOK: find-next-file os ( DIR* -- byte-array )
37
38 M: unix find-next-file ( DIR* -- byte-array )
39     dirent <struct>
40     f <void*>
41     [ readdir_r 0 = [ (io-error) ] unless ] 2keep
42     *void* [ drop f ] unless ;
43
44 : dirent-type>file-type ( ch -- type )
45     {
46         { DT_BLK  [ +block-device+ ] }
47         { DT_CHR  [ +character-device+ ] }
48         { DT_DIR  [ +directory+ ] }
49         { DT_LNK  [ +symbolic-link+ ] }
50         { DT_SOCK [ +socket+ ] }
51         { DT_FIFO [ +fifo+ ] }
52         { DT_REG  [ +regular-file+ ] }
53         { DT_WHT  [ +whiteout+ ] }
54         [ drop +unknown+ ]
55     } case ;
56
57 M: unix >directory-entry ( byte-array -- directory-entry )
58     {
59         [ d_name>> underlying>> utf8 alien>string ]
60         [ d_type>> dirent-type>file-type ]
61     } cleave directory-entry boa ;
62
63 M: unix (directory-entries) ( path -- seq )
64     [
65         '[ _ find-next-file dup ]
66         [ >directory-entry ]
67         produce nip
68     ] with-unix-directory ;
69
70 os linux? [ "io.directories.unix.linux" require ] when