Repository navigation
Expand file tree
/
Copy pathsearcher.js
More file actions
72 lines (59 loc) · 1.62 KB
/
Copy pathsearcher.js
File metadata and controls
72 lines (59 loc) · 1.62 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
import path from "node:path";
import iterateDirectoryUp from "iterate-directory-up";
class Searcher {
#names;
#filter;
#stopDirectory;
#cache = new Map();
/**
* @param {{
* names: string[],
* filter: (fileOrDirectory: {name: string, path: string}) => Promise<boolean>,
* stopDirectory?: string,
* }} param0
*/
constructor({ names, filter, stopDirectory }) {
this.#names = names;
this.#filter = filter;
this.#stopDirectory = stopDirectory;
}
async #searchInDirectory(directory, shouldCache) {
const cache = this.#cache;
if (shouldCache && cache.has(directory)) {
return cache.get(directory);
}
for (const name of this.#names) {
const fileOrDirectory = path.join(directory, name);
if (await this.#filter({ name, path: fileOrDirectory })) {
return fileOrDirectory;
}
}
}
async search(startDirectory, { shouldCache }) {
const cache = this.#cache;
if (shouldCache && cache.has(startDirectory)) {
return cache.get(startDirectory);
}
const searchedDirectories = [];
let result;
for (const directory of iterateDirectoryUp(
startDirectory,
this.#stopDirectory,
)) {
searchedDirectories.push(directory);
result = await this.#searchInDirectory(directory, shouldCache);
if (result) {
break;
}
}
// Always cache the result, so we can use it when `useCache` is set to true
for (const directory of searchedDirectories) {
cache.set(directory, result);
}
return result;
}
clearCache() {
this.#cache.clear();
}
}
export default Searcher;