This repository was archived by the owner on Aug 31, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 658
/
Copy pathAbsoluteFilePath.ts
404 lines (338 loc) · 9.44 KB
/
AbsoluteFilePath.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
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
import {normalizeRelativeSegments, parseRelativePathSegments} from "../parse";
import {FilePathMemo, ReadableBasePath} from "../bases";
import {
FilePath,
ParsedPath,
ParsedPathAbsolute,
Path,
PathFormatOptions,
PathSegments,
} from "../types";
import RelativePath from "./RelativePath";
import {createFilePath} from "../factories";
import {FSWatcher} from "@internal/fs";
import {AbsoluteFilePathSet, MixedPathMap} from "../collections";
import fs = require("fs");
import {toDataView, toUintArray8} from "@internal/binary";
export default class AbsoluteFilePath
extends ReadableBasePath<ParsedPathAbsolute, AbsoluteFilePath> {
constructor(
parsed: ParsedPathAbsolute,
memo: FilePathMemo<AbsoluteFilePath> = {},
) {
super(parsed, memo);
this.memoizedRelative = undefined;
}
public [Symbol.toStringTag] = "AbsoluteFilePath";
// We do not always initialize it to save on a bunch of allocations if relative() isn't used
private memoizedRelative:
| undefined
| MixedPathMap<AbsoluteFilePath | RelativePath>;
protected _assert(): AbsoluteFilePath {
return this;
}
protected _fork(
parsed: ParsedPathAbsolute,
opts?: FilePathMemo<AbsoluteFilePath>,
): AbsoluteFilePath {
return new AbsoluteFilePath(parsed, opts);
}
protected _getUnique(): AbsoluteFilePath {
return this;
}
protected _equalAbsolute(other: ParsedPath): boolean {
const {parsed} = this;
switch (parsed.type) {
case "absolute-windows-drive":
return (
other.type === "absolute-windows-drive" &&
other.letter === parsed.letter
);
case "absolute-windows-unc":
return (
other.type === "absolute-windows-unc" &&
other.servername === parsed.servername
);
case "absolute-unix":
return other.type === "absolute-unix";
default:
return false;
}
}
protected _join() {
const relative = this.getDisplaySegments();
const {parsed} = this;
switch (parsed.type) {
case "absolute-windows-drive":
return [`${parsed.letter}:`, ...relative].join("\\");
case "absolute-windows-unc":
return [`\\\\${parsed.servername}`, ...relative].join("\\");
case "absolute-unix":
return `/${relative.join("/")}`;
}
}
protected _format({cwd, home}: PathFormatOptions = {}): string {
const filename = this.join();
const names: string[] = [];
names.push(filename);
// Get a path relative to HOME
if (home !== undefined && this.isRelativeTo(home)) {
// Path starts with the home directory, so let's trim it off
const relativeToHome = home.relative(this._assert());
// Add tilde and push it as a possible name
// We construct this manually to get around the segment normalization which would explode ~
names.push(
new RelativePath({
type: "relative",
explicitRelative: false,
explicitDirectory: this.parsed.explicitDirectory,
relativeSegments: ["~", ...relativeToHome.getSegments()],
}).join(),
);
}
// Get a path relative to the cwd
if (cwd !== undefined) {
names.push(cwd.relative(this).join());
}
// Get the shortest name
const human = names.sort((a, b) => a.length - b.length)[0];
if (human === "") {
return "./";
} else {
return human;
}
}
public isFilePath(): this is FilePath {
return true;
}
public assertFilePath(): FilePath {
return this;
}
public isAbsolute(): this is AbsoluteFilePath {
return true;
}
public assertAbsolute(): AbsoluteFilePath {
return this;
}
public assertReadable(): AbsoluteFilePath {
return this;
}
public isReadable(): this is AbsoluteFilePath {
return true;
}
public *getChain(reverse: boolean = false): Iterable<AbsoluteFilePath> {
if (!reverse) {
yield this;
}
if (!this.isRoot()) {
yield* this.getParent().getChain(reverse);
}
if (reverse) {
yield this;
}
}
public resolve(other: string | FilePath): AbsoluteFilePath;
public resolve(other: Path): Exclude<Path, RelativePath>;
public resolve(
other: string | Path,
): AbsoluteFilePath | Exclude<Path, RelativePath>;
public resolve(
other: string | Path,
): AbsoluteFilePath | Exclude<Path, RelativePath> {
if (typeof other === "string") {
other = createFilePath(other);
}
if (!other.isRelative()) {
return other;
}
return new AbsoluteFilePath({
...this.parsed,
...normalizeRelativeSegments([
...this.relativeSegments,
...other.getSegments(),
]),
explicitDirectory: other.isExplicitDirectory(),
});
}
public relativeForce(otherRaw: AbsoluteFilePath | RelativePath): RelativePath {
return this.relative(otherRaw).assertRelative();
}
public relative(
otherRaw: AbsoluteFilePath | RelativePath,
): AbsoluteFilePath | RelativePath {
if (this.memoizedRelative !== undefined) {
const memoized = this.memoizedRelative.get(otherRaw);
if (memoized !== undefined) {
return memoized;
}
}
const other = this.resolve(otherRaw);
if (other.equal(this)) {
return new RelativePath({
type: "relative",
explicitDirectory: false,
explicitRelative: true,
relativeSegments: [],
});
}
// Impossible to relativize two absolute paths with different absolute targets
if (!this.equalAbsolute(other)) {
return other;
}
const absolute = this.getSegments().slice();
const relative = other.getSegments().slice();
// Remove common starting segments
while (absolute[0] === relative[0]) {
absolute.shift();
relative.shift();
}
let finalSegments: PathSegments = [];
for (let i = 0; i < absolute.length; i++) {
finalSegments.push("..");
}
finalSegments = finalSegments.concat(relative);
const path = new RelativePath(parseRelativePathSegments(finalSegments));
// Store in memoize map
if (this.memoizedRelative === undefined) {
this.memoizedRelative = new MixedPathMap();
}
this.memoizedRelative.set(otherRaw, path);
return path;
}
public watch(
options:
| {
encoding?: BufferEncoding | null;
persistent?: boolean;
recursive?: boolean;
}
| undefined,
listener?: (event: string, filename: null | string) => void,
): FSWatcher {
return fs.watch(this.join(), options, listener);
}
public async readFile(): Promise<DataView> {
const buff = await fs.promises.readFile(this.join());
return toDataView(buff);
}
public async readFileText(): Promise<string> {
return fs.promises.readFile(this.join(), "utf8");
}
public async writeFile(
content: string | ArrayBuffer | ArrayBufferView | fs.ReadStream,
): Promise<void> {
if (content instanceof fs.ReadStream) {
return new Promise((resolve, reject) => {
const writeStream = this.createWriteStream();
content.pipe(writeStream);
writeStream.on(
"error",
(err) => {
reject(err);
},
);
writeStream.on(
"close",
() => {
resolve();
},
);
});
} else {
let buff;
if (typeof content === "string") {
buff = content;
} else {
buff = toUintArray8(content);
}
await fs.promises.writeFile(this.join(), buff);
}
}
public copyFileTo(dest: AbsoluteFilePath): Promise<void> {
return fs.promises.copyFile(this.join(), dest.join());
}
public async readDirectory(): Promise<AbsoluteFilePathSet> {
const files = await fs.promises.readdir(this.join());
return new AbsoluteFilePathSet(
files.sort().map((basename) => {
return this.append(basename);
}),
);
}
public lstat(): Promise<fs.BigIntStats> {
return fs.promises.lstat(this.join(), {bigint: true});
}
// Wrapping await in parens is gross so offer this to make other code nicer
public async notExists(): Promise<boolean> {
return !(await this.exists());
}
public async exists(): Promise<boolean> {
try {
await fs.promises.access(this.join());
return true;
} catch (err) {
return false;
}
}
public async removeFile(): Promise<void> {
try {
await fs.promises.unlink(this.join());
} catch (err) {
if (err.code !== "ENOENT") {
throw err;
}
}
}
// We previously just use fs.rmdir with the `recursive: true` flag but it was added in Node 12.10 and we need to support 12.8.1
// NB: There are probably race conditions, we could switch to openFile and openDirectory if it's a problem
// https://github.com/rome/tools/issues/1001
public async removeDirectory(): Promise<void> {
if (await this.notExists()) {
return;
}
// Delete all inner files
for (const subpath of await this.readDirectory()) {
const stats = await subpath.lstat();
if (stats.isDirectory()) {
await subpath.removeDirectory();
} else {
await subpath.removeFile();
}
}
// Remove directory with all files deleted
await fs.promises.rmdir(this.join());
}
public async createDirectory(): Promise<void> {
if (await this.notExists()) {
await fs.promises.mkdir(
this.join(),
{
recursive: true,
},
);
}
}
public openFile(
flags: fs.OpenMode = "r",
mode?: fs.Mode,
): Promise<fs.promises.FileHandle> {
return fs.promises.open(this.join(), flags, mode);
}
public openDirectory(opts: fs.OpenDirOptions = {}): Promise<fs.Dir> {
return fs.promises.opendir(this.join(), opts);
}
public createWriteStream(): fs.WriteStream {
return fs.createWriteStream(this.join());
}
public createReadStream(): fs.ReadStream {
return fs.createReadStream(this.join());
}
// Super special sync methods that we should only use sparingly if there's absolutely no way to do them async
public readFileTextSync(): string {
return fs.readFileSync(this.join(), "utf8");
}
public lstatSync(): fs.Stats {
return fs.lstatSync(this.join());
}
}
AbsoluteFilePath.prototype[Symbol.toStringTag] = "AbsoluteFilePath";