-
Notifications
You must be signed in to change notification settings - Fork 71
Expand file tree
/
Copy pathfdir.test.ts
More file actions
525 lines (467 loc) · 16.8 KB
/
Copy pathfdir.test.ts
File metadata and controls
525 lines (467 loc) · 16.8 KB
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
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
import { fdir } from "../src/index";
import fs from "fs";
import mock from "mock-fs";
import { test, beforeEach, vi } from "vitest";
import path, { sep } from "path";
import { convertSlashes } from "../src/utils";
import picomatch from "picomatch";
import { apiTypes, APITypes, cwd, restricted, root, execute } from "./utils";
// AbortController is not present on Node v14
const hasAbortController = "AbortController" in globalThis;
beforeEach(() => {
mock.restore();
});
test(`crawl single depth directory with callback`, (t) => {
const api = new fdir().crawl("__tests__");
return new Promise<void>((resolve, reject) => {
api.withCallback((err, files) => {
if (err) return reject(err);
t.expect(files[0]).toBeDefined();
t.expect(files.every((t) => t)).toBeTruthy();
t.expect(files[0].length).toBeGreaterThan(0);
resolve();
});
});
});
async function crawl(type: APITypes, path: string) {
const api = new fdir().crawl(path);
return execute(api, type);
}
for (const type of apiTypes) {
test(`[${type}] crawl directory`, async (t) => {
const files = await crawl(type, "__tests__");
t.expect(files[0]).toBeDefined();
t.expect(files.every((t) => t)).toBeTruthy();
t.expect(files[0].length).toBeGreaterThan(0);
});
test(`[${type}] crawl directory with options`, async (t) => {
const api = new fdir({ includeBasePath: true }).crawl("__tests__");
const files = await execute(api, type);
t.expect(files.every((file) => file.startsWith("__tests__"))).toBeTruthy();
});
test("crawl single depth directory with options", async (t) => {
const api = new fdir({
maxDepth: 0,
includeBasePath: true,
}).crawl("node_modules");
const files = await execute(api, type);
t.expect(files).not.toHaveLength(0);
t.expect(files.every((file) => file.split(path.sep).length === 2)).toBe(
true
);
});
test(`[${type}] crawl multi depth directory with options`, async (t) => {
const api = new fdir({
maxDepth: 1,
includeBasePath: true,
}).crawl("node_modules");
const files = await execute(api, type);
t.expect(files.some((file) => file.split(path.sep).length === 3)).toBe(
true
);
t.expect(files.every((file) => file.split(path.sep).length <= 3)).toBe(
true
);
});
test(`[${type}] crawl multi depth directory`, async (t) => {
const files = await crawl(type, "node_modules");
t.expect(files[0]).toBeDefined();
t.expect(files.every((t) => t)).toBeTruthy();
t.expect(files[0].length).toBeGreaterThan(0);
});
test(`[${type}] crawl directory & limit files to 10`, async (t) => {
const api = new fdir().withMaxFiles(10).crawl("node_modules");
const files = await execute(api, type);
t.expect(files).toHaveLength(10);
});
test(`[${type}] crawl and get both files and directories (withDirs)`, async (t) => {
const api = new fdir().withDirs().crawl("node_modules");
const files = await execute(api, type);
t.expect(files[0]).toBeDefined();
t.expect(files.every((t) => t)).toBeTruthy();
t.expect(files[0].length).toBeGreaterThan(0);
t.expect(files[0].endsWith(path.normalize("node_modules/"))).toBeTruthy();
});
test(`[${type}] crawl and get all files (withMaxDepth = 1)`, async (t) => {
const api = new fdir().withMaxDepth(1).withBasePath().crawl("node_modules");
const files = await execute(api, type);
t.expect(
files.every((file) => file.split(path.sep).length <= 3)
).toBeTruthy();
});
test(`[${type}] crawl and get all files (withMaxDepth = -1)`, async (t) => {
const api = new fdir()
.withMaxDepth(-1)
.withBasePath()
.crawl("node_modules");
const files = await execute(api, type);
t.expect(files.length).toBe(0);
});
test(`[${type}] crawl and get files that match a glob pattern`, async (t) => {
const api = new fdir()
.withBasePath()
.glob("**/*.js")
.glob("**/*.js")
.crawl("node_modules");
const files = await execute(api, type);
t.expect(files.every((file) => file.endsWith(".js"))).toBeTruthy();
});
test(`[${type}] crawl but exclude node_modules dir`, async (t) => {
const api = new fdir()
.withBasePath()
.exclude((dir) => dir.includes("node_modules"))
.crawl(cwd());
const files = await execute(api, type);
t.expect(
files.every((file) => !file.includes("node_modules"))
).toBeTruthy();
});
test(`[${type}] crawl all files with filter`, async (t) => {
const api = new fdir()
.withBasePath()
.filter((file) => file.includes(".git"))
.crawl(cwd());
const files = await execute(api, type);
t.expect(files.every((file) => file.includes(".git"))).toBeTruthy();
});
test(`[${type}] crawl all files with multifilter`, async (t) => {
const api = new fdir()
.withBasePath()
.filter((file) => file.includes(".git"))
.filter((file) => file.includes(".js"))
.crawl(cwd());
const files = await execute(api, type);
t.expect(
files.every((file) => file.includes(".git") || file.includes(".js"))
).toBeTruthy();
});
test(`[${type}] crawl all files in a directory (with base path)`, async (t) => {
const api = new fdir()
.withBasePath()
.crawl(path.join(cwd(), "node_modules"));
const files = await execute(api, type);
t.expect(
files.every((file) => file.startsWith("node_modules"))
).toBeTruthy();
});
test(`[${type}] get all files in a directory and output full paths (withFullPaths)`, async (t) => {
const api = new fdir().withFullPaths().crawl(cwd());
const files = await execute(api, type);
t.expect(files.every((file) => file.startsWith(root()))).toBeTruthy();
});
test(`[${type}] getting files from restricted directory should throw`, async (t) => {
const api = new fdir().withErrors().crawl(restricted());
t.expect(async () => await execute(api, type)).rejects.toThrowError();
});
test(`[${type}] getting files from restricted directory shouldn't throw (suppressErrors)`, async (t) => {
const api = new fdir().crawl(restricted());
const files = await execute(api, type);
t.expect(files.length).toBeGreaterThanOrEqual(0);
});
test(`[${type}] recurse root (files should not contain multiple /)`, async (t) => {
mock({
"/etc": {
hosts: "dooone",
},
});
const api = new fdir().withBasePath().normalize().crawl("/");
const files = await execute(api, type);
t.expect(files.every((file) => !file.includes("//"))).toBeTruthy();
mock.restore();
});
if (type !== "withIterator") {
test(`[${type}] crawl all files with only counts`, async (t) => {
const api = new fdir().onlyCounts().crawl("node_modules");
const result = await api[type]();
t.expect(result.files).toBeGreaterThan(0);
});
}
test(`[${type}] crawl and return only directories`, async (t) => {
const api = new fdir().onlyDirs().crawl("node_modules");
const result = await execute(api, type);
t.expect(result.length).toBeGreaterThan(0);
t.expect(
result.every((dir) => {
return fs.statSync(dir).isDirectory;
})
).toBeTruthy();
});
test(`[${type}] crawl with options and return only directories`, async (t) => {
const api = new fdir({
excludeFiles: true,
includeDirs: true,
}).crawl("node_modules");
const result = await execute(api, type);
t.expect(result.length).toBeGreaterThan(0);
t.expect(
result.every((dir) => {
return fs.statSync(dir).isDirectory;
})
).toBeTruthy();
});
if (type !== "withIterator") {
test(`[${type}] crawl and filter all files and get only counts`, async (t) => {
const api = new fdir()
.withBasePath()
.filter((file) => file.includes("node_modules"))
.onlyCounts()
.crawl(cwd());
const result = await api[type]();
t.expect(result.files).toBeGreaterThan(0);
});
}
test("crawl all files in a directory (path with trailing slash)", async (t) => {
const api = new fdir().normalize().crawl("node_modules/");
const files = await execute(api, type);
const res = files.every((file) => !file.includes("/"));
t.expect(res).toBeDefined();
});
test(`[${type}] crawl all files and group them by directory`, async (t) => {
const api = new fdir().withBasePath().group().crawl("node_modules");
const result = await execute(api, type);
t.expect(result.length).toBeGreaterThan(0);
});
test(`[${type}] crawl and filter only directories`, async (t) => {
const api = new fdir()
.onlyDirs()
.filter((path) => path.includes("api"))
.crawl("./src");
const result = await execute(api, type);
t.expect(result).toHaveLength(2);
});
test(`[${type}] crawl and return relative paths`, async (t) => {
const api = new fdir()
.withRelativePaths()
.crawl(path.normalize(`node_modules/`));
const paths = await execute(api, type);
t.expect(paths.every((p) => !p.startsWith("node_modules"))).toBeTruthy();
});
test(`[${type}] crawl and return relative paths with only dirs`, async (t) => {
mock({
"/some/dir/dir1": {
file: "some file",
},
"/some/dir/dir2": {
file: "some file",
},
"/some/dir/dir2/dir3": {
file: "some file",
},
});
const api = new fdir({ excludeFiles: true, excludeSymlinks: true })
.withDirs()
.withRelativePaths()
.crawl("/some");
const paths = await execute(api, type);
t.expect(paths.length).toBe(5);
t.expect(paths.filter((p) => p === ".").length).toBe(1);
t.expect(paths.filter((p) => p === "").length).toBe(0);
mock.restore();
});
test(`[${type}] crawl and return relative paths with filters and only dirs`, async (t) => {
mock({
"/some/dir/dir1": {
file: "some file",
},
"/some/dir/dir2": {
file: "some file",
},
"/some/dir/dir2/dir3": {
file: "some file",
},
});
const api = new fdir({ excludeFiles: true, excludeSymlinks: true })
.withDirs()
.withRelativePaths()
.filter((p) => p !== path.join("dir", "dir1/"))
.crawl("/some");
const paths = await execute(api, type);
t.expect(paths.length).toBe(4);
t.expect(paths.includes(path.join("dir", "dir1/"))).toBe(false);
t.expect(paths.filter((p) => p === ".").length).toBe(1);
t.expect(paths.filter((p) => p === "").length).toBe(0);
mock.restore();
});
test(`[${type}] crawl and return relative paths that end with /`, async (t) => {
const api = new fdir().withRelativePaths().crawl("./node_modules/");
const paths = await execute(api, type);
t.expect(
paths.every((p) => !p.startsWith("node_modules") && !p.includes("//"))
).toBeTruthy();
});
test(`[${type}] crawl all files and invert path separator`, async (t) => {
const api = new fdir()
.withPathSeparator(sep === "/" ? "\\" : "/")
.crawl("node_modules");
const files = await execute(api, type);
t.expect(files.every((f) => !f.includes(sep))).toBeTruthy();
});
test(`[${type}] crawl files that match using a custom glob`, async (t) => {
const globFunction = vi.fn((glob: string | string[]) => {
return (test: string): boolean => test.endsWith(".js");
});
const api = new fdir({ globFunction })
.withBasePath()
.glob("**/*.js")
.crawl("node_modules");
const files = await execute(api, type);
t.expect(globFunction).toHaveBeenCalled();
t.expect(files.every((file) => file.endsWith(".js"))).toBeTruthy();
});
test(`[${type}] crawl files that match using a custom glob with options`, async (t) => {
const globFunction = vi.fn(
(glob: string | string[], options?: { foo: number }) => {
return (test: string): boolean => test.endsWith(".js");
}
);
const api = new fdir({ globFunction })
.withBasePath()
.globWithOptions(["**/*.js"], { foo: 5 })
.crawl("node_modules");
const files = await execute(api, type);
t.expect(globFunction).toHaveBeenCalled();
t.expect(files.every((file) => file.endsWith(".js"))).toBeTruthy();
});
test(`[${type}] crawl files that match using a picomatch`, async (t) => {
const globFunction = picomatch;
const api = new fdir({ globFunction })
.withBasePath()
.glob("**/*.js")
.crawl("node_modules");
const files = await execute(api, type);
t.expect(files.every((file) => file.endsWith(".js"))).toBeTruthy();
});
test(`[${type}] using withGlobFunction to set glob`, async (t) => {
const globFunction = vi.fn((glob: string | string[], input: string) => {
return (test: string): boolean => test === input;
});
new fdir()
.withBasePath()
.withGlobFunction(globFunction)
.globWithOptions(["**/*.js"], "bleep")
.crawl("node_modules");
t.expect(globFunction).toHaveBeenCalledWith(["**/*.js"], "bleep");
});
test(`[${type}] using custom fs implementation`, async (t) => {
const readdirStub = vi.fn<Parameters<typeof fs.readdir>>(
(_path, _opts, cb) => {
cb(null, []);
}
);
const readdirSyncStub = vi.fn();
readdirSyncStub.mockReturnValue([]);
const fakeFs = {
...fs,
readdir: readdirStub,
readdirSync: readdirSyncStub,
} as unknown as typeof fs;
const api = new fdir({
fs: fakeFs,
}).crawl("node_modules");
await execute(api, type);
if (type === "withPromise" || type === "withIterator") {
t.expect(readdirStub).toHaveBeenCalled();
} else {
t.expect(readdirSyncStub).toHaveBeenCalled();
}
});
}
test.runIf(hasAbortController)(
`[async] crawl directory & use abort signal to abort`,
async (t) => {
const totalFiles = new fdir().onlyCounts().crawl("node_modules").sync();
const abortController = new AbortController();
const api = new fdir()
.withAbortSignal(abortController.signal)
.filter((p) => {
if (p.endsWith(".js")) abortController.abort();
return true;
})
.crawl("node_modules");
const files = await api.withPromise();
t.expect(files.length).toBeLessThan(totalFiles.files);
}
);
test(`paths should never start with ./`, async (t) => {
const apis = [
new fdir().withBasePath().crawl("./node_modules"),
new fdir().withBasePath().crawl("./"),
new fdir().withRelativePaths().crawl("./"),
new fdir().withRelativePaths().crawl("."),
new fdir().withDirs().crawl("."),
new fdir().onlyDirs().crawl("."),
];
for (const api of apis) {
const files = await api.withPromise();
t.expect(
files.every((file) => !file.startsWith("./") && !file.startsWith(".\\"))
).toBe(true);
}
});
test(`default to . if root is not provided`, async (t) => {
const files = await new fdir().crawl().withPromise();
const files2 = await new fdir()
.crawl(".")
.withPromise()
.then((f) => f.sort());
t.expect(files.sort().every((r, i) => r === files2[i])).toBe(true);
});
test(`ignore withRelativePath if root === ./`, async (t) => {
const relativeFiles = await new fdir()
.withRelativePaths()
.crawl("./")
.withPromise();
const files = await new fdir().crawl("./").withPromise();
t.expect(relativeFiles.every((r) => files.includes(r))).toBe(true);
});
test(`add path separator if root path does not end with one`, async (t) => {
const relativeFiles = await new fdir()
.withRelativePaths()
.crawl("node_modules")
.withPromise();
t.expect(relativeFiles.every((r) => !r.startsWith(sep))).toBe(true);
});
test(`there should be no empty directory when using withDirs`, async (t) => {
const files = await new fdir().withDirs().crawl("./").withPromise();
t.expect(files.every((r) => r.length > 0)).toBe(true);
});
test(`there should be no empty directory when using withDirs and filters`, async (t) => {
const files = await new fdir()
.withDirs()
.filter((p) => p !== "node_modules")
.crawl("./")
.withPromise();
t.expect(files.every((r) => r.length > 0)).toBe(true);
});
test(`do not convert \\\\ to \\`, async (t) => {
t.expect(convertSlashes("\\\\wsl.localhost\\Ubuntu\\home\\", "\\")).toBe(
"\\\\wsl.localhost\\Ubuntu\\home\\"
);
});
test("interrupted iterator should stop yielding results", async (t) => {
const api = new fdir().crawl("./src");
const iterator = api.withIterator();
const results: string[] = [];
let next = await iterator.next();
do {
if (!next.done) {
results.push(next.value);
}
iterator.return();
} while (next.done !== false);
t.expect(results.length).toBe(1);
});
test.runIf(hasAbortController)(
"aborted iterator should stop yielding results",
async (t) => {
const aborter = new AbortController();
const api = new fdir().withAbortSignal(aborter.signal).crawl("./src");
const iterator = api.withIterator();
const results: string[] = [];
for await (const value of iterator) {
results.push(value);
aborter.abort();
}
t.expect(results.length).toBe(1);
}
);