]> gitweb.factorcode.org Git - factor.git/blob - core/io/files/files.factor
Merge branch 'master' of github.com:mrjbq7/factor
[factor.git] / core / io / files / files.factor
1 ! Copyright (C) 2004, 2009 Slava Pestov, Daniel Ehrenberg.
2 ! See http://factorcode.org/license.txt for BSD license.
3 USING: kernel kernel.private sequences init namespaces system io
4 io.encodings.utf8 io.backend io.pathnames io.encodings io.files.private
5 alien.strings splitting ;
6 IN: io.files
7
8 MIXIN: file-reader
9 MIXIN: file-writer
10
11 M: file-reader stream-element-type drop +byte+ ; inline
12 M: file-writer stream-element-type drop +byte+ ; inline
13
14 HOOK: (file-reader) io-backend ( path -- stream )
15
16 HOOK: (file-writer) io-backend ( path -- stream )
17
18 HOOK: (file-appender) io-backend ( path -- stream )
19
20 : <file-reader> ( path encoding -- stream )
21     [ normalize-path (file-reader) { file-reader } declare ] dip <decoder> ; inline
22
23 : <file-writer> ( path encoding -- stream )
24     [ normalize-path (file-writer) { file-writer } declare ] dip <encoder> ; inline
25
26 : <file-appender> ( path encoding -- stream )
27     [ normalize-path (file-appender) { file-writer } declare ] dip <encoder> ; inline
28
29 : file-lines ( path encoding -- seq )
30     <file-reader> stream-lines ;
31
32 : with-file-reader ( path encoding quot -- )
33     [ <file-reader> ] dip with-input-stream ; inline
34
35 : file-contents ( path encoding -- seq )
36     <file-reader> stream-contents ;
37
38 : with-file-writer ( path encoding quot -- )
39     [ <file-writer> ] dip with-output-stream ; inline
40
41 : set-file-lines ( seq path encoding -- )
42     [ [ print ] each ] with-file-writer ;
43
44 : set-file-contents ( seq path encoding -- )
45     [ write ] with-file-writer ;
46
47 : with-file-appender ( path encoding quot -- )
48     [ <file-appender> ] dip with-output-stream ; inline
49
50 : exists? ( path -- ? )
51     normalize-path native-string>alien (exists?) ;
52
53 ! Current directory
54 <PRIVATE
55
56 HOOK: cd io-backend ( path -- )
57
58 HOOK: cwd io-backend ( -- path )
59
60 M: object cwd ( -- path ) "." ;
61
62 PRIVATE>
63
64 : init-resource-path ( -- )
65     OBJ-ARGS special-object
66     [ utf8 alien>string "-resource-path=" ?head [ drop f ] unless ] map-find drop
67     [ image parent-directory ] unless* "resource-path" set-global ;
68
69 [
70     cwd current-directory set-global
71     OBJ-IMAGE special-object alien>native-string cwd prepend-path \ image set-global
72     OBJ-EXECUTABLE special-object alien>native-string cwd prepend-path \ vm set-global
73     init-resource-path
74 ] "io.files" add-startup-hook