Skip to content

Commit 01fc911

Browse files
committed
fix: discover each file once when includeFolders overlap
discoverFiles() walked every includeFolders entry independently and concatenated the results, so a file under two entries ("." next to "src", "src" next to "src/core", duplicate or differently spelled entries) was returned, and then processed with its git lookups, once per entry. slothlet's include list discovered 1920 paths for 963 files. Each root is now stat'ed and canonicalized (realpath) up front, and a root is dropped before any walk when another root already covers it: the same folder, or a folder inside it that the outer walk actually descends into. A folder the outer walk never enters (under node_modules or a root build folder) keeps being walked on its own, as before. Surviving roots are walked in input order, so non-overlapping inputs keep their existing output order, and the result is de-duplicated by path as a final guard. Fixes #59
1 parent 0de081f commit 01fc911

4 files changed

Lines changed: 393 additions & 13 deletions

File tree

‎README.md‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -93,7 +93,7 @@ Important options:
9393
- `enabledDetectors?: string[]` - detector ids to enable (defaults to all)
9494
- `disabledDetectors?: string[]` - detector ids to disable
9595
- `detectorSyntaxOverrides?: Record<string, { linePrefix?: string, lineSeparator?: string, blockStart?: string, blockLinePrefix?: string, blockEnd?: string }>` - override detector comment syntax tokens
96-
- `includeFolders?: string[]` - project-relative folders to scan
96+
- `includeFolders?: string[]` - project-relative folders to scan. Overlapping entries are collapsed, so every file is scanned once however the folders nest or are spelled (`"."` next to `"src"`, `"src"` next to `"src/core"`, `"./src"` next to `"src/"`)
9797
- `excludeFolders?: string[]` - folder names or relative paths to exclude
9898
- `gitignore?: boolean | string | string[]` - respect `.gitignore` during discovery. `false` disables; a path or array of paths loads those ignore files; anything else / omitted auto-detects `<projectRoot>/.gitignore`. Matched files and directories are skipped.
9999
- `projectName?: string`
@@ -138,6 +138,7 @@ const result = await fixHeaders({
138138
## Notes
139139

140140
- `excludeFolders` supports both folder-name and nested path matching.
141+
- `includeFolders` entries never double-count a file. A folder that lies inside another include is not walked a second time; the exception is a folder the outer walk never enters (for example one under `node_modules` or under a root build folder such as `dist`), which keeps being walked on its own because it was named explicitly.
141142
- Built-in ignores are scoped: `.git` and `node_modules` are skipped at **any depth**, while build/cache directories (`dist`, `build`, `coverage`, `tmp`, `.next`, `.turbo`) are skipped **only at the project root** — so a source directory that happens to share a name (for example `tools/build`) is still processed.
142143
- With `gitignore` enabled (the default, auto-detecting the project's `.gitignore`), anything the project ignores is skipped during discovery — generated paths are excluded by the project's own rules without hard-coding names. Pass `gitignore: false` to disable, or a path/array to use specific ignore files.
143144
- For monorepos, each file resolves metadata from the closest detector config in its parent tree.

‎src/core/file-discovery.mjs‎

Lines changed: 75 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -11,8 +11,8 @@
1111
* @Copyright: Copyright (c) 2013-2026 Catalyzed Motivation Inc. All rights reserved.
1212
*/
1313

14-
import { join, relative, resolve } from "node:path";
15-
import { readFile, stat } from "node:fs/promises";
14+
import { join, relative, resolve, sep } from "node:path";
15+
import { readFile, realpath, stat } from "node:fs/promises";
1616
import ignore from "ignore";
1717
import { ALWAYS_IGNORE_FOLDERS, ROOT_IGNORE_FOLDERS } from "../constants.mjs";
1818
import { getAllowedExtensions } from "../detectors/index.mjs";
@@ -134,9 +134,11 @@ function buildExclusionMatcher(projectRoot, excludeFolders) {
134134
* includeFolders?: string[],
135135
* excludeFolders?: string[],
136136
* gitignore?: boolean | string | string[]
137-
* }} options - File discovery options. `gitignore`: `false` disables; a path or array of
138-
* paths loads those ignore files; anything else / omitted auto-detects `<projectRoot>/.gitignore`.
139-
* @returns {Promise<string[]>} Absolute file paths.
137+
* }} options - File discovery options. `includeFolders`: overlapping entries are collapsed, so
138+
* each file is returned once however the folders nest or are spelled.
139+
* `gitignore`: `false` disables; a path or array of paths loads those ignore files; anything
140+
* else / omitted auto-detects `<projectRoot>/.gitignore`.
141+
* @returns {Promise<string[]>} Absolute file paths, each listed once.
140142
*/
141143
export async function discoverFiles(options) {
142144
const allowedExtensions = resolveExtensions(options);
@@ -179,13 +181,14 @@ export async function discoverFiles(options) {
179181
};
180182
const shouldSkipDirectory = (targetPath, targetName) =>
181183
rootIgnorePaths.has(resolve(targetPath)) || exclusionMatcher(targetPath, targetName) || isGitignored(targetPath);
182-
const roots =
184+
const requestedRoots =
183185
includeFolders.length > 0
184186
? includeFolders.map((includeFolder) => ({ includeFolder, rootPath: join(options.projectRoot, includeFolder) }))
185187
: [{ includeFolder: ".", rootPath: options.projectRoot }];
186188

187-
const files = [];
188-
for (const root of roots) {
189+
/** @type {Array<{ includeFolder: string, rootPath: string, realRoot: string }>} */
190+
const roots = [];
191+
for (const root of requestedRoots) {
189192
const rootStats = await stat(root.rootPath).catch((error) => error);
190193
if (rootStats instanceof Error) {
191194
if (/** @type {{ code?: string }} */ (rootStats).code === "ENOENT") {
@@ -201,6 +204,65 @@ export async function discoverFiles(options) {
201204
continue;
202205
}
203206

207+
// The canonical (symlink-resolved) path is only used to detect overlapping roots. If the folder
208+
// vanishes between the stat above and this call, fall back to the lexical path; the walk below
209+
// then fails on it exactly as it did before overlap detection existed.
210+
const realRoot = await realpath(root.rootPath).catch(() => resolve(root.rootPath));
211+
roots.push({ ...root, realRoot });
212+
}
213+
214+
/**
215+
* Whether walking `container` already yields every file that walking `candidate` would.
216+
* @param {{ rootPath: string, realRoot: string }} container - Root that may cover the candidate.
217+
* @param {{ realRoot: string }} candidate - Root that may be redundant.
218+
* @returns {boolean} True when the candidate's walk is redundant.
219+
*/
220+
const covers = (container, candidate) => {
221+
if (container.realRoot === candidate.realRoot) {
222+
return true;
223+
}
224+
225+
const containerPrefix = container.realRoot.endsWith(sep) ? container.realRoot : `${container.realRoot}${sep}`;
226+
if (!candidate.realRoot.startsWith(containerPrefix)) {
227+
return false;
228+
}
229+
230+
// The container's walk only reaches the candidate if it descends through every directory in
231+
// between. A directory it skips (node_modules, a root build folder, an exclusion, a .gitignore
232+
// match) hides the candidate's files from it, so an explicitly listed folder under such a
233+
// directory keeps being walked on its own, as it always was.
234+
let current = container.rootPath;
235+
for (const segment of candidate.realRoot.slice(containerPrefix.length).split(sep)) {
236+
current = join(current, segment);
237+
if (ALWAYS_IGNORED_FOLDERS.has(segment) || shouldSkipDirectory(current, segment)) {
238+
return false;
239+
}
240+
}
241+
242+
return true;
243+
};
244+
245+
// Drop every root another root already covers (nested includes, "." next to its subfolders,
246+
// duplicate or differently spelled entries), so no directory is walked twice. Roots are
247+
// considered shallowest-first, then in input order (the sort is stable), so any covering root
248+
// has already been kept by the time the roots it covers are checked.
249+
const byContainment = [...roots].sort((left, right) => left.realRoot.length - right.realRoot.length);
250+
/** @type {typeof roots} */
251+
const keptRoots = [];
252+
for (const root of byContainment) {
253+
if (!keptRoots.some((kept) => covers(kept, root))) {
254+
keptRoots.push(root);
255+
}
256+
}
257+
258+
const files = [];
259+
// Walk the surviving roots in their original input order, so non-overlapping inputs keep the
260+
// output order they have always had.
261+
for (const root of roots) {
262+
if (!keptRoots.includes(root)) {
263+
continue;
264+
}
265+
204266
const discovered = await walkFiles(root.rootPath, {
205267
allowedExtensions,
206268
ignoreFolders: ALWAYS_IGNORED_FOLDERS,
@@ -209,5 +271,9 @@ export async function discoverFiles(options) {
209271
files.push(...discovered);
210272
}
211273

212-
return files.filter((filePath) => !exclusionMatcher(filePath, filePath.split("/").at(-1) || "") && !isGitignored(filePath));
274+
// The kept roots never overlap, so this is a guard rather than the mechanism: each path is
275+
// returned once, in first-seen order.
276+
return Array.from(new Set(files)).filter(
277+
(filePath) => !exclusionMatcher(filePath, filePath.split("/").at(-1) || "") && !isGitignored(filePath)
278+
);
213279
}

0 commit comments

Comments
 (0)