]> gitweb.factorcode.org Git - factor.git/blob - basis/io/directories/unix/unix.factor
3cc0b549e824df2befc5d5d1b5ba7058d2688ff9
[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.data alien.strings assocs
4 classes.struct continuations fry io.backend io.backend.unix
5 io.directories io.files io.files.info io.files.info.unix
6 io.files.types kernel libc literals math sequences system unix
7 unix.ffi vocabs ;
8 IN: io.directories.unix
9
10 CONSTANT: touch-mode flags{ O_WRONLY O_APPEND O_CREAT O_EXCL }
11
12 CONSTANT: mkdir-mode flags{ USER-ALL GROUP-ALL OTHER-ALL } ! 0o777
13
14 M: unix touch-file ( path -- )
15     normalize-path
16     dup exists? [ touch ] [
17         touch-mode file-mode open-file close-file
18     ] if ;
19
20 M: unix move-file ( from to -- )
21     [ normalize-path ] bi@ [ rename ] unix-system-call drop ;
22
23 M: unix delete-file ( path -- ) normalize-path unlink-file ;
24
25 M: unix make-directory ( path -- )
26     normalize-path mkdir-mode [ mkdir ] unix-system-call drop ;
27
28 M: unix delete-directory ( path -- )
29     normalize-path [ rmdir ] unix-system-call drop ;
30
31 M: unix copy-file ( from to -- )
32     [ call-next-method ]
33     [ [ file-permissions ] dip swap set-file-permissions ] 2bi ;
34
35 : with-unix-directory ( path quot -- )
36     dupd '[ _ _
37         [ opendir dup [ throw-errno ] unless ] dip
38         dupd curry swap '[ _ closedir io-error ] [ ] cleanup
39     ] with-directory ; inline
40
41 : dirent-type>file-type ( type -- file-type )
42     H{
43         { $ DT_BLK  +block-device+ }
44         { $ DT_CHR  +character-device+ }
45         { $ DT_DIR  +directory+ }
46         { $ DT_LNK  +symbolic-link+ }
47         { $ DT_SOCK +socket+ }
48         { $ DT_FIFO +fifo+ }
49         { $ DT_REG  +regular-file+ }
50         { $ DT_WHT  +whiteout+ }
51     } at* [ drop +unknown+ ] unless ;
52
53 ! An easy way to return +unknown+ is to mount a .iso on OSX and
54 ! call directory-entries on the mount point.
55
56 : next-dirent ( DIR* dirent* -- dirent* ? )
57     f void* <ref> [
58         readdir_r [ (throw-errno) ] unless-zero
59     ] 2keep void* deref ; inline
60
61 : >directory-entry ( dirent* -- directory-entry )
62     [ d_name>> alien>native-string ]
63     [ d_type>> dirent-type>file-type ] bi
64     dup +unknown+ = [ drop dup file-info type>> ] when
65     <directory-entry> ; inline
66
67 M: unix (directory-entries) ( path -- seq )
68     [
69         dirent <struct>
70         '[ _ _ next-dirent ] [ >directory-entry ] produce nip
71     ] with-unix-directory ;
72
73 os linux? [ "io.directories.unix.linux" require ] when