Elffuss BraidHub

kikocis/continue public

627d7d0d1f85 · 10.0 KiBRawPermalink
1import ignore, { Ignore } from "ignore";
2
3import type { FileType, IDE } from "..";
4
5import { joinPathsToUri } from "../util/uri";
6import {
7 defaultIgnoreFileAndDir,
8 getGlobalContinueIgArray,
9 gitIgArrayFromFile,
10} from "./ignore";
11
12export interface WalkerOptions {
13 include?: "dirs" | "files" | "both";
14 returnRelativeUrisPaths?: boolean;
15 source?: string;
16 overrideDefaultIgnores?: Ignore;
17 recursive?: boolean;
18}
19
20type Entry = [string, FileType];
21
22const LIST_DIR_CACHE_TIME = 30_000; // 30 seconds
23const IGNORE_FILE_CACHE_TIME = 30_000; // 30 seconds
24
25// helper struct used for the DFS walk
26type WalkableEntry = {
27 name: string;
28 relativeUriPath: string;
29 uri: string;
30 type: FileType;
31 entry: Entry;
32};
33
34// helper struct used for the DFS walk
35type WalkContext = {
36 walkableEntry: WalkableEntry;
37 ignoreContexts: IgnoreContext[];
38};
39
40type IgnoreContext = {
41 ignore: Ignore;
42 dirname: string;
43};
44
45class WalkDirCache {
46 dirListCache: Map<
47 string,
48 {
49 time: number;
50 entries: Promise<[string, FileType][]>;
51 }
52 > = new Map();
53 dirIgnoreCache: Map<
54 string,
55 {
56 time: number;
57 ignore: Promise<Ignore>;
58 }
59 > = new Map();
60 // The super safe approach for now
61 invalidate() {
62 this.dirListCache.clear();
63 this.dirIgnoreCache.clear();
64 }
65 // invalidateIgnore(uri: string) {
66 // this.dirIgnoreCache.delete(uri);
67 // }
68 // invalidateParent(uri: string) {
69 // const splitUri = fileUri.split("/");
70 // splitUri.pop();
71 // const parent = splitUri.join("/");
72 // this.dirListCache.delete(uri);
73 // }
74}
75export const walkDirCache = new WalkDirCache(); // TODO - singleton approach better?
76
77class DFSWalker {
78 constructor(
79 private readonly uri: string,
80 private readonly ide: IDE,
81 private readonly options: WalkerOptions,
82 ) {}
83
84 // walk is a depth-first search implementation
85 public async *walk(): AsyncGenerator<string> {
86 const start = Date.now();
87 let ignoreFileTime = 0;
88 let ignoreTime = 0;
89 let listDirTime = 0;
90 let dirs = 0;
91 let listDirCacheHits = 0;
92 let ignoreCacheHits = 0;
93
94 let section = Date.now();
95 const defaultAndGlobalIgnores = ignore()
96 .add(this.options.overrideDefaultIgnores ?? defaultIgnoreFileAndDir)
97 .add(getGlobalContinueIgArray());
98 ignoreFileTime += Date.now() - section;
99
100 const rootContext: WalkContext = {
101 walkableEntry: {
102 name: "",
103 relativeUriPath: "",
104 uri: this.uri,
105 type: 2 as FileType.Directory,
106 entry: ["", 2 as FileType.Directory],
107 },
108 ignoreContexts: [],
109 };
110 const stack = [rootContext];
111
112 for (let cur = stack.pop(); cur; cur = stack.pop()) {
113 // Previous no caching approach:
114 // const entries = await this.ide.listDir(cur.walkableEntry.uri);
115 // const newIgnore = await getIgnoreContext(
116 // cur.walkableEntry.uri,
117 // entries,
118 // this.ide,
119 // defaultAndGlobalIgnores,
120 // );
121
122 // Only directories will be added to the stack
123 dirs++;
124
125 section = Date.now();
126 let entries: [string, FileType][] = [];
127 const cachedListdir = walkDirCache.dirListCache.get(
128 cur.walkableEntry.uri,
129 );
130 if (
131 cachedListdir &&
132 cachedListdir.time > Date.now() - LIST_DIR_CACHE_TIME
133 ) {
134 entries = await cachedListdir.entries;
135 listDirCacheHits++;
136 } else {
137 const promise = this.ide.listDir(cur.walkableEntry.uri);
138 walkDirCache.dirListCache.set(cur.walkableEntry.uri, {
139 time: Date.now(),
140 entries: promise,
141 });
142 entries = await promise;
143 }
144 listDirTime += Date.now() - section;
145
146 section = Date.now();
147 let newIgnore: Ignore;
148 const cachedIgnore = walkDirCache.dirIgnoreCache.get(
149 cur.walkableEntry.uri,
150 );
151 if (
152 cachedIgnore &&
153 cachedIgnore.time > Date.now() - IGNORE_FILE_CACHE_TIME
154 ) {
155 newIgnore = await cachedIgnore.ignore;
156 ignoreCacheHits++;
157 } else {
158 const ignorePromise = getIgnoreContext(
159 cur.walkableEntry.uri,
160 entries,
161 this.ide,
162 defaultAndGlobalIgnores,
163 );
164 walkDirCache.dirIgnoreCache.set(cur.walkableEntry.uri, {
165 time: Date.now(),
166 ignore: ignorePromise,
167 });
168 newIgnore = await ignorePromise;
169 }
170
171 const ignoreContexts = [
172 ...cur.ignoreContexts,
173 {
174 ignore: newIgnore,
175 dirname: cur.walkableEntry.relativeUriPath,
176 },
177 ];
178 ignoreFileTime += Date.now() - section;
179
180 for (const entry of entries) {
181 if (this.entryIsSymlink(entry)) {
182 // If called from the root, a symlink either links to a real file in this repository,
183 // and therefore will be walked OR it links to something outside of the repository and
184 // we do not want to index it
185 continue;
186 }
187 const walkableEntry = {
188 name: entry[0],
189 relativeUriPath: `${cur.walkableEntry.relativeUriPath}${cur.walkableEntry.relativeUriPath ? "/" : ""}${entry[0]}`,
190 uri: joinPathsToUri(cur.walkableEntry.uri, entry[0]),
191 type: entry[1],
192 entry: entry,
193 };
194
195 let relPath = walkableEntry.relativeUriPath;
196 if (this.entryIsDirectory(entry)) {
197 relPath = `${relPath}/`;
198 } else {
199 if (this.options.include === "dirs") {
200 continue;
201 }
202 }
203 let shouldIgnore = false;
204 for (const ig of ignoreContexts) {
205 if (shouldIgnore) {
206 continue;
207 }
208 // remove the directory name and path separator from the match path, unless this an ignore file
209 // in the root directory
210 const prefixLength =
211 ig.dirname.length === 0 ? 0 : ig.dirname.length + 1;
212 // The ignore library expects a path relative to the ignore file location
213 const matchPath = relPath.substring(prefixLength);
214 section = Date.now();
215 if (ig.ignore.ignores(matchPath)) {
216 shouldIgnore = true;
217 }
218 ignoreTime += Date.now() - section;
219 }
220 if (shouldIgnore) {
221 continue;
222 }
223
224 if (this.entryIsDirectory(entry)) {
225 if (this.options.recursive) {
226 stack.push({
227 walkableEntry,
228 ignoreContexts,
229 });
230 }
231 if (this.options.include !== "files") {
232 // if yielding dirs or both, walker includes relative paths
233 const trailingSlash = this.options.include === "dirs" ? "" : "/";
234 if (this.options.returnRelativeUrisPaths) {
235 yield walkableEntry.relativeUriPath + trailingSlash;
236 } else {
237 yield walkableEntry.uri + trailingSlash;
238 }
239 }
240 } else if (this.options.include !== "dirs") {
241 if (this.options.returnRelativeUrisPaths) {
242 yield walkableEntry.relativeUriPath;
243 } else {
244 yield walkableEntry.uri;
245 }
246 }
247 }
248 }
249 // console.log(
250 // `Walk Dir Result:\nSource: ${this.options.source ?? "unknown"}\nDir: ${this.uri}\nDuration: ${Date.now() - start}ms:\n\tList dir: ${listDirTime}ms (${listDirCacheHits}/${dirs} cache hits)\n\tIgnore files: ${ignoreFileTime}ms (${ignoreCacheHits}/${dirs} cache hits)\n\tIgnoring: ${ignoreTime}ms`,
251 // );
252 }
253
254 private entryIsDirectory(entry: Entry) {
255 return entry[1] === (2 as FileType.Directory);
256 }
257
258 private entryIsSymlink(entry: Entry) {
259 return entry[1] === (64 as FileType.SymbolicLink);
260 }
261}
262
263const defaultOptions: WalkerOptions = {
264 include: "files",
265 returnRelativeUrisPaths: false,
266 recursive: true,
267};
268
269export async function* walkDirAsync(
270 path: string,
271 ide: IDE,
272 _optionOverrides?: WalkerOptions,
273): AsyncGenerator<string> {
274 const options = { ...defaultOptions, ..._optionOverrides };
275 yield* new DFSWalker(path, ide, options).walk();
276}
277
278export async function walkDir(
279 uri: string,
280 ide: IDE,
281 _optionOverrides?: WalkerOptions,
282): Promise<string[]> {
283 let urisOrRelativePaths: string[] = [];
284 for await (const p of walkDirAsync(uri, ide, _optionOverrides)) {
285 urisOrRelativePaths.push(p);
286 }
287 return urisOrRelativePaths;
288}
289
290export async function walkDirs(
291 ide: IDE,
292 _optionOverrides?: WalkerOptions,
293 dirs?: string[], // Can pass dirs to prevent duplicate calls
294): Promise<string[]> {
295 const workspaceDirs = dirs ?? (await ide.getWorkspaceDirs());
296 const results = await Promise.all(
297 workspaceDirs.map((dir) => walkDir(dir, ide, _optionOverrides)),
298 );
299 return results.flat();
300}
301
302export async function getIgnoreContext(
303 currentDir: string,
304 currentDirEntries: Entry[],
305 ide: IDE,
306 defaultAndGlobalIgnores: Ignore,
307) {
308 const dirFiles = currentDirEntries
309 .filter(([_, entryType]) => entryType === (1 as FileType.File))
310 .map(([name, _]) => name);
311
312 // Find ignore files and get ignore arrays from their contexts
313 // These are done separately so that .continueignore can override .gitignore
314 const gitIgnoreFile = dirFiles.find((name) => name === ".gitignore");
315 const continueIgnoreFile = dirFiles.find(
316 (name) => name === ".continueignore",
317 );
318
319 const getGitIgnorePatterns = async () => {
320 if (gitIgnoreFile) {
321 const contents = await ide.readFile(`${currentDir}/.gitignore`);
322 return gitIgArrayFromFile(contents);
323 }
324 return [];
325 };
326 const getContinueIgnorePatterns = async () => {
327 if (continueIgnoreFile) {
328 const contents = await ide.readFile(`${currentDir}/.continueignore`);
329 return gitIgArrayFromFile(contents);
330 }
331 return [];
332 };
333
334 const ignoreArrays = await Promise.all([
335 getGitIgnorePatterns(),
336 getContinueIgnorePatterns(),
337 ]);
338
339 if (ignoreArrays[0].length === 0 && ignoreArrays[1].length === 0) {
340 return defaultAndGlobalIgnores;
341 }
342
343 // Note precedence here!
344 const ignoreContext = ignore()
345 .add(ignoreArrays[0]) // gitignore
346 .add(defaultAndGlobalIgnores) // default file/folder ignores followed by global .continueignore - this is combined for speed
347 .add(ignoreArrays[1]); // local .continueignore
348
349 return ignoreContext;
350}