-
Notifications
You must be signed in to change notification settings - Fork 4
/
file-system.ralph
93 lines (82 loc) · 2.83 KB
/
file-system.ralph
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
(define-module ralph/file-system
import: ((path only: (dirname resolve))
(fs rename: ("existsSync" exists-sync
"mkdirSync" mkdir-sync
"statSync" stat-sync
"lstatSync" lstat-sync
"openSync" open-sync
"closeSync" close-sync
"readSync" read-sync
"writeSync" write-sync
"readFileSync" read-file-sync
"writeFileSync" write-file-sync
"appendFileSync" append-file-sync)))
export: (ensure-directories-exist
path-directory
path-parent-directory
resolve-path
file-properties
file-type
read-file
write-file
file-exists?))
(define resolve-path resolve)
(define file-exists? exists-sync)
(define-function path-directory (path)
(concatenate
(dirname (if (== (last path) "/")
(concatenate path "/")
path))
"/"))
(define-function strip-trailing-slashes (path)
(while (== (last path) "/")
(set! path (but-last path)))
path)
(define-function path-parent-directory (path)
(concatenate (dirname (if (== (last path "/"))
path
(dirname path)))
"/"))
(define-function ensure-directories-exist (path)
(bind ((directory (path-directory path))
(parent (path-parent-directory directory)))
(unless (file-exists? parent)
(ensure-directories-exist parent))
(unless (file-exists? directory)
(mkdir-sync directory))
path))
(define *file-properties-mapping*
[["modification-date" "mtime"]
["creation-date" "ctime"]
["access-date" "atime"]])
;; TODO: lstat?
(define-function file-properties (path)
(when (file-exists? path)
(bind ((stats (stat-sync path))
(result (make-object)))
(for-each ((mapping *file-properties-mapping*))
()
(destructuring-bind (setter getter) mapping
(set! (get result setter)
(get stats getter))))
result)))
(define-function file-type (path)
(when (file-exists? path)
(bind ((stat (lstat-sync path)))
(cond
((. stat ("isFile")) "file")
((. stat ("isDirectory")) "directory" )
((. stat ("isSymbolicLink")) "link")
((. stat ("isBlockDevice")) "block-device")
((. stat ("isCharacterDevice")) "character-device")
((. stat ("isFIFO")) "fifo")
((. stat ("isSocket")) "socket")))))
(define-function read-file (path)
(when (file-exists? path)
(as-string (read-file-sync path))))
(define-function write-file (path content #key append?)
(ensure-directories-exist path)
((if append?
append-file-sync
write-file-sync)
path content))