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