-
Notifications
You must be signed in to change notification settings - Fork 0
/
fs.ts
297 lines (244 loc) · 7.83 KB
/
fs.ts
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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
import { pathUtils } from './deps.ts'
import { Json } from './json.ts'
export async function exists(file: string): Promise<boolean> {
try {
await Deno.stat(file)
return true
} catch (_) {
return false
}
}
const ensureDirExists = async (file: string) => {
const dir = pathUtils.dirname(file)
if (!(await exists(dir))) await Deno.mkdir(dir, { recursive: true })
}
/** @deprecated Will be removed in next major release. Use `writeBytes` instead */
export const writeBinary = writeBytes
/** Write `bytes` to `file`. Creates the directory if it doesn't exist */
export async function writeBytes(file: string, bytes: Uint8Array): Promise<void> {
await ensureDirExists(file)
await Deno.writeFile(file, bytes)
}
/** Write `text` to `file`. Creates the directory if it doesn't exist */
export async function writeText(file: string, text: string): Promise<void> {
await ensureDirExists(file)
await Deno.writeTextFile(file, text)
}
export interface WriteJsonOptions {
separator?: string
}
/** Write `json` to `file`. Creates the directory if it doesn't exist */
export async function writeJson(file: string, json: unknown, options: WriteJsonOptions = {}): Promise<void> {
await ensureDirExists(file)
await Deno.writeTextFile(file, JSON.stringify(json, null, options.separator))
}
/** @deprecated Will be removed in next major release. Use `readBytes` instead */
export async function readBinary(file: string): Promise<Uint8Array> {
try {
return await Deno.readFile(file)
} catch (_) {
return new Uint8Array()
}
}
/** Read a file as a Uint8Array. Returns `null` if the file doesn't exist */
export async function readBytes(file: string): Promise<Uint8Array | null> {
try {
return await Deno.readFile(file)
} catch (_) {
return null
}
}
/**
* Read a file as a string. Returns an empty string if the file doesn't exist.
*
* NOTICE: At the next major release, this will return string|null */
export async function readText(file: string): Promise<string> {
try {
return await Deno.readTextFile(file)
} catch (_) {
return ``
}
}
/**
* Read a file, parsing it as json. Returns an empty object if the file doesn't exist or can't be parsed.
*
* NOTICE: At the next major release, this will return Json|null */
export async function readJson(file: string): Promise<Json> {
try {
return JSON.parse(await Deno.readTextFile(file))
} catch (_) {
return {}
}
}
/**
* Read a file, parsing it as json. Returns an empty object if the file doesn't exist. Throws if the json can't be parsed.
*
* NOTICE: At the next major release, this will return Json|null */
export async function readJsonStrict(file: string): Promise<Json> {
let json: string
try {
json = await Deno.readTextFile(file)
} catch (_) {
return {}
}
try {
return JSON.parse(json)
} catch (error) {
throw 'Failed to parse "${file}":' + error
}
}
/** Recursively read all files in `rootDir`. Resulting paths will include `rootDir` */
export async function recursiveReadDir(rootDir: string): Promise<string[]> {
const files = await recursiveReadInsideDir(rootDir)
return files.map(({ path }) => path)
}
/** Get all entries in `dir`. Resulting paths will not include `dir`. Symlinks are ignored. */
export async function readDir(dir: string): Promise<string[]> {
if (!await exists(dir)) return []
const names: string[] = []
for await (const dirEntry of Deno.readDir(dir)) names.push(dirEntry.name)
return names
}
export interface PathPair {
/** The path to a file from inside the directory */
innerPath: string
/** The path to the file */
path: string
}
/** Recursively read all files in `rootDir`. Symlinks are ignored. */
export async function recursiveReadInsideDir(rootDir: string): Promise<PathPair[]> {
if (!await exists(rootDir)) return []
const results: PathPair[] = []
const getFiles = async (path: string, innerPath: string) => {
for await (const dirEntry of Deno.readDir(path)) {
const childPath = pathUtils.join(path, dirEntry.name)
const childInnerPath = pathUtils.join(innerPath, dirEntry.name)
if (dirEntry.isDirectory) {
await getFiles(childPath, childInnerPath)
continue
}
if (dirEntry.isFile) results.push({ path: childPath, innerPath: childInnerPath })
}
}
await getFiles(rootDir, '.')
return results
}
export interface CopyDirOptions {
/**
* If specified, `pathFilter` will be called for every `path` in `directory`.
*
* `path` will be a subpath of `directory`, and not include it. */
pathFilter?(path: string): boolean
}
/** Copy the contents of `srcDirectory` into `destDirectory`, optionally filtering with `options.pathFilter`. Symlinks are ignored. */
export async function copyDir(srcDirectory: string, destDirectory: string, options: CopyDirOptions = {}): Promise<void> {
const rawCurrentPaths = await recursiveReadInsideDir(srcDirectory)
for (const { innerPath, path } of rawCurrentPaths) {
if (options.pathFilter && !options.pathFilter(innerPath)) continue
const newPath = pathUtils.join(destDirectory, innerPath)
const currentFile = await Deno.open(path, { read: true })
const newPathDir = pathUtils.dirname(newPath)
if (!await exists(newPathDir)) await Deno.mkdir(newPathDir, { recursive: true })
const newFile = await Deno.open(newPath, { create: true, write: true, truncate: true })
await currentFile.readable.pipeTo(newFile.writable)
}
}
/**
* Read the contents of `directory` into the returned map. Symlinks are ignored.
*
* **Example**
*
* Assume an FS structure like so...
*
* ```txt
* /root
* |- foo
* |- bin
* |- bar
* |- baz
* ```
*
* ...when running with the text reader...
*
* ```ts
* console.log(await recursiveReadFiles('/root', readText))
* ```
*
* ... the output should match this:
*
* ```txt
* Map(2) {
* "foo/bin" => "...",
* "bar/baz" => "..."
* }
* ``` */
export async function recursiveReadFiles<T>(directory: string, reader: (path: string) => Promise<T>): Promise<Map<string, T>> {
const files = await recursiveReadInsideDir(directory)
const map = new Map<string, T>()
for (const { innerPath, path } of files) map.set(innerPath, await reader(path))
return map
}
export interface WatcherParams {
/** Called when a file is updated */
onUpdate(file: string): unknown
/** A signal by which the watcher can be aborted */
signal?: AbortSignal
/** The interval (in milliseconds) at which to poll files. Defaults to 1000 */
interval?: number
}
export interface Watcher {
/** Add files to the watcher. Watcher will watch these files for changes */
addFiles(files: string[]): void
}
/**
* Create a watcher that monitors a list of files for updates
*
* Example:
*
* ```ts
* const watcher = createWatcher({
* onUpdate: (file) => console.log('File changed:', file)
* })
*
* watcher.addFiles(await recursiveReadDir('.'))
* ``` */
export function createWatcher(params: WatcherParams): Watcher {
const interval = params.interval ?? 1000
const files = new Set<string>()
async function pollFiles() {
const now = Date.now()
const lastCheckedTime = now - interval + interval * 0.1
const filesToRemove: string[] = []
for (const file of files) {
const mtime = await getMtime(file)
if (mtime === null) {
filesToRemove.push(file)
continue
}
if (mtime > lastCheckedTime) {
params.onUpdate(file)
break
}
}
for (const file of filesToRemove) {
files.delete(file)
}
}
function addFiles(newFiles: string[]) {
for (const file of newFiles) files.add(file)
}
const timer = setInterval(() => pollFiles(), interval)
if (params.signal) params.signal.addEventListener('abort', () => clearInterval(timer))
return { addFiles }
}
/** Retrieves the modified time of `file`. If unsupported on this platform, or if the file doesn't exist, null is returned */
async function getMtime(file: string) {
let stat: Deno.FileInfo | null
try {
stat = await Deno.stat(file)
} catch (_) {
return null
}
if (!stat.mtime) return null
return stat.mtime.getTime()
}