Skip to content

Commit bbe4c54

Browse files
committed
feat: include a folder non-recursively with { path, recursive: false }
includeFolders entries may now be objects, { path: string, recursive?: boolean }. recursive: false includes only that folder's own files, so { path: ".", recursive: false } means the project-root files without the whole tree. Plain string entries keep their recursive meaning, and an entry that is neither a string nor { path } now throws a TypeError instead of failing inside path.join. Overlap handling covers the new form: a non-recursive root is dropped when the same folder is also listed recursively or lies inside a recursive root, so every file is still returned once. The CLI gains a repeatable --include-folder-non-recursive <path> flag that appends { path, recursive: false } alongside --include-folder. walkFiles takes a matching recursive option. README, JSDoc and the generated types document the entry shape. Refs #59
1 parent 01fc911 commit bbe4c54

9 files changed

Lines changed: 296 additions & 34 deletions

File tree

‎README.md‎

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,7 @@ Common CLI options:
5959
- `--cwd <path>`
6060
- `--input <path>`
6161
- `--include-folder <path>` (repeatable)
62+
- `--include-folder-non-recursive <path>` (repeatable) - include only that folder's own files, not its subfolders
6263
- `--exclude-folder <path>` (repeatable)
6364
- `--include-extension <ext>` (repeatable)
6465
- `--enable-detector <id>` / `--disable-detector <id>` (repeatable)
@@ -93,7 +94,7 @@ Important options:
9394
- `enabledDetectors?: string[]` - detector ids to enable (defaults to all)
9495
- `disabledDetectors?: string[]` - detector ids to disable
9596
- `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. 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/"`)
97+
- `includeFolders?: Array<string | { path: string, recursive?: boolean }>` - project-relative folders to scan. A string entry is scanned recursively; `{ path, recursive: false }` includes only that folder's own files (for example `{ path: ".", recursive: false }` for the project-root files without the whole tree). 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/"`)
9798
- `excludeFolders?: string[]` - folder names or relative paths to exclude
9899
- `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.
99100
- `projectName?: string`
@@ -116,7 +117,7 @@ const result = await fixHeaders({
116117
cwd: process.cwd(),
117118
dryRun: false,
118119
configFile: "fix-headers.config.json",
119-
includeFolders: ["src", "scripts"],
120+
includeFolders: ["src", "scripts", { path: ".", recursive: false }],
120121
excludeFolders: ["src/generated", "dist"],
121122
detectorSyntaxOverrides: {
122123
node: {
@@ -138,7 +139,7 @@ const result = await fixHeaders({
138139
## Notes
139140

140141
- `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.
142+
- `includeFolders` entries never double-count a file. A folder that lies inside another recursive 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.
142143
- 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.
143144
- 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.
144145
- For monorepos, each file resolves metadata from the closest detector config in its parent tree.

‎src/cli.mjs‎

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@ import fixHeaders from "./fix-header.mjs";
2323
* @module fix-headers/cli
2424
*/
2525

26-
const HELP_TEXT = `fix-headers CLI\n\nUsage:\n fix-headers [options]\n\nOptions:\n -h, --help Show help\n --dry-run Compute changes without writing files\n --json Print JSON output\n --verbose Print updated file paths in summary mode\n --sample-output Show previous/new header sample for changed files\n --force-author-update Always update @Author/@Email to detected/current values\n --force-last-modified-author-update Always update @Last modified by to detected/current values\n --use-gpg-signer-author Use signed-commit UID (%GS) for detected @Author\n --cwd <path> Working directory for project detection\n --input <path> Single file or folder input\n --include-folder <path> Include folder (repeatable)\n --exclude-folder <path> Exclude folder name/path (repeatable)\n --include-extension <ext> Include extension (repeatable)\n --enable-detector <id> Enable only specific detector (repeatable)\n --disable-detector <id> Disable detector by id (repeatable)\n --project-name <name> Override project name\n --language <id> Override language id\n --project-root <path> Override project root\n --marker <name|null> Override marker filename\n --author-name <name> Override author name\n --author-email <email> Override author email\n --company <name> Append company suffix to @Author (Name <Company>)\n --company-name <name> Override company name\n --copyright-start-year <year> Override copyright start year\n --config <path> Load JSON options file\n\nExamples:\n fix-headers --dry-run --include-folder src\n fix-headers --project-name @scope/pkg --company-name "Catalyzed Motivation Inc."\n`;
26+
const HELP_TEXT = `fix-headers CLI\n\nUsage:\n fix-headers [options]\n\nOptions:\n -h, --help Show help\n --dry-run Compute changes without writing files\n --json Print JSON output\n --verbose Print updated file paths in summary mode\n --sample-output Show previous/new header sample for changed files\n --force-author-update Always update @Author/@Email to detected/current values\n --force-last-modified-author-update Always update @Last modified by to detected/current values\n --use-gpg-signer-author Use signed-commit UID (%GS) for detected @Author\n --cwd <path> Working directory for project detection\n --input <path> Single file or folder input\n --include-folder <path> Include folder (repeatable)\n --include-folder-non-recursive <path> Include only a folder's own files, not its subfolders (repeatable)\n --exclude-folder <path> Exclude folder name/path (repeatable)\n --include-extension <ext> Include extension (repeatable)\n --enable-detector <id> Enable only specific detector (repeatable)\n --disable-detector <id> Disable detector by id (repeatable)\n --project-name <name> Override project name\n --language <id> Override language id\n --project-root <path> Override project root\n --marker <name|null> Override marker filename\n --author-name <name> Override author name\n --author-email <email> Override author email\n --company <name> Append company suffix to @Author (Name <Company>)\n --company-name <name> Override company name\n --copyright-start-year <year> Override copyright start year\n --config <path> Load JSON options file\n\nExamples:\n fix-headers --dry-run --include-folder src\n fix-headers --project-name @scope/pkg --company-name "Catalyzed Motivation Inc."\n`;
2727

2828
/**
2929
* Converts CLI flag token to camelCase key.
@@ -108,6 +108,17 @@ export function parseCliArgs(argv) {
108108
}
109109

110110
const flag = arg.slice(2);
111+
if (flag === "include-folder-non-recursive") {
112+
const value = argv[index + 1];
113+
if (!value || value.startsWith("--")) {
114+
throw new Error(`Missing value for --${flag}`);
115+
}
116+
index += 1;
117+
const list = Array.isArray(options.includeFolders) ? options.includeFolders : [];
118+
options.includeFolders = [...list, { path: value, recursive: false }];
119+
continue;
120+
}
121+
111122
if (multiMap[flag]) {
112123
const value = argv[index + 1];
113124
if (!value || value.startsWith("--")) {

‎src/core/file-discovery.mjs‎

Lines changed: 46 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -48,16 +48,33 @@ function normalizeFolderPath(folderPath) {
4848
}
4949

5050
/**
51-
* Determines include roots from explicit include folders.
52-
* @param {string[] | undefined} includeFolders - Include folder option.
53-
* @returns {string[]} Effective include roots.
51+
* An `includeFolders` entry: a project-relative folder path (walked recursively), or an object
52+
* form that can switch recursion off so only the folder's own files are included.
53+
* @typedef {string | { path: string, recursive?: boolean }} IncludeFolderEntry
54+
*/
55+
56+
/**
57+
* Normalizes `includeFolders` entries to `{ path, recursive }` records.
58+
* @param {IncludeFolderEntry[] | undefined} includeFolders - Include folder option.
59+
* @returns {Array<{ path: string, recursive: boolean }>} Effective include roots, in input order.
60+
* @throws {TypeError} When an entry is neither a string nor an object with a string `path`.
5461
*/
5562
function resolveIncludeFolders(includeFolders) {
56-
if (Array.isArray(includeFolders) && includeFolders.length > 0) {
57-
return includeFolders;
63+
if (!Array.isArray(includeFolders)) {
64+
return [];
5865
}
5966

60-
return [];
67+
return includeFolders.map((entry) => {
68+
if (typeof entry === "string") {
69+
return { path: entry, recursive: true };
70+
}
71+
72+
if (entry && typeof entry === "object" && typeof entry.path === "string") {
73+
return { path: entry.path, recursive: entry.recursive !== false };
74+
}
75+
76+
throw new TypeError(`Invalid includeFolders entry: ${JSON.stringify(entry)} (expected a path string or { path, recursive? })`);
77+
});
6178
}
6279

6380
/**
@@ -131,11 +148,12 @@ function buildExclusionMatcher(projectRoot, excludeFolders) {
131148
* includeExtensions?: string[],
132149
* enabledDetectors?: string[],
133150
* disabledDetectors?: string[],
134-
* includeFolders?: string[],
151+
* includeFolders?: IncludeFolderEntry[],
135152
* excludeFolders?: string[],
136153
* gitignore?: boolean | string | string[]
137-
* }} options - File discovery options. `includeFolders`: overlapping entries are collapsed, so
138-
* each file is returned once however the folders nest or are spelled.
154+
* }} options - File discovery options. `includeFolders`: a string entry is walked recursively;
155+
* `{ path, recursive: false }` includes only that folder's own files. Overlapping entries are
156+
* collapsed, so each file is returned once however the folders nest or are spelled.
139157
* `gitignore`: `false` disables; a path or array of paths loads those ignore files; anything
140158
* else / omitted auto-detects `<projectRoot>/.gitignore`.
141159
* @returns {Promise<string[]>} Absolute file paths, each listed once.
@@ -183,10 +201,14 @@ export async function discoverFiles(options) {
183201
rootIgnorePaths.has(resolve(targetPath)) || exclusionMatcher(targetPath, targetName) || isGitignored(targetPath);
184202
const requestedRoots =
185203
includeFolders.length > 0
186-
? includeFolders.map((includeFolder) => ({ includeFolder, rootPath: join(options.projectRoot, includeFolder) }))
187-
: [{ includeFolder: ".", rootPath: options.projectRoot }];
204+
? includeFolders.map((entry) => ({
205+
includeFolder: entry.path,
206+
rootPath: join(options.projectRoot, entry.path),
207+
recursive: entry.recursive
208+
}))
209+
: [{ includeFolder: ".", rootPath: options.projectRoot, recursive: true }];
188210

189-
/** @type {Array<{ includeFolder: string, rootPath: string, realRoot: string }>} */
211+
/** @type {Array<{ includeFolder: string, rootPath: string, recursive: boolean, realRoot: string }>} */
190212
const roots = [];
191213
for (const root of requestedRoots) {
192214
const rootStats = await stat(root.rootPath).catch((error) => error);
@@ -213,17 +235,17 @@ export async function discoverFiles(options) {
213235

214236
/**
215237
* 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.
238+
* @param {{ rootPath: string, recursive: boolean, realRoot: string }} container - Root that may cover the candidate.
239+
* @param {{ recursive: boolean, realRoot: string }} candidate - Root that may be redundant.
218240
* @returns {boolean} True when the candidate's walk is redundant.
219241
*/
220242
const covers = (container, candidate) => {
221243
if (container.realRoot === candidate.realRoot) {
222-
return true;
244+
return container.recursive || !candidate.recursive;
223245
}
224246

225247
const containerPrefix = container.realRoot.endsWith(sep) ? container.realRoot : `${container.realRoot}${sep}`;
226-
if (!candidate.realRoot.startsWith(containerPrefix)) {
248+
if (!container.recursive || !candidate.realRoot.startsWith(containerPrefix)) {
227249
return false;
228250
}
229251

@@ -244,9 +266,12 @@ export async function discoverFiles(options) {
244266

245267
// Drop every root another root already covers (nested includes, "." next to its subfolders,
246268
// 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);
269+
// considered shallowest-first — recursive before non-recursive for the same folder, then in
270+
// input order (the sort is stable) — so any covering root has already been kept by the time
271+
// the roots it covers are checked.
272+
const byContainment = [...roots].sort(
273+
(left, right) => left.realRoot.length - right.realRoot.length || Number(right.recursive) - Number(left.recursive)
274+
);
250275
/** @type {typeof roots} */
251276
const keptRoots = [];
252277
for (const root of byContainment) {
@@ -266,7 +291,8 @@ export async function discoverFiles(options) {
266291
const discovered = await walkFiles(root.rootPath, {
267292
allowedExtensions,
268293
ignoreFolders: ALWAYS_IGNORED_FOLDERS,
269-
shouldSkipDirectory
294+
shouldSkipDirectory,
295+
recursive: root.recursive
270296
});
271297
files.push(...discovered);
272298
}

‎src/core/fix-headers.mjs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,7 @@ import { toDatePayload } from "../utils/time.mjs";
3434
* enabledDetectors?: string[],
3535
* disabledDetectors?: string[],
3636
* detectorSyntaxOverrides?: Record<string, { linePrefix?: string, lineSeparator?: string, blockStart?: string, blockLinePrefix?: string, blockEnd?: string }>,
37-
* includeFolders?: string[],
37+
* includeFolders?: Array<string | { path: string, recursive?: boolean }>,
3838
* excludeFolders?: string[],
3939
* includeExtensions?: string[],
4040
* gitignore?: boolean | string | string[],

‎src/utils/fs.mjs‎

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -79,8 +79,9 @@ export async function readTextIfExists(filePath) {
7979
* @param {{
8080
* allowedExtensions: Set<string>,
8181
* ignoreFolders: Set<string>,
82-
* shouldSkipDirectory?: (directoryPath: string, directoryName: string) => boolean
83-
* }} options - Scan options.
82+
* shouldSkipDirectory?: (directoryPath: string, directoryName: string) => boolean,
83+
* recursive?: boolean
84+
* }} options - Scan options. `recursive: false` lists only the directory's own files.
8485
* @returns {Promise<string[]>} Matching file paths.
8586
*/
8687
export async function walkFiles(dirPath, options) {
@@ -90,6 +91,10 @@ export async function walkFiles(dirPath, options) {
9091
for (const entry of entries) {
9192
const fullPath = join(dirPath, entry.name);
9293

94+
if (entry.isDirectory() && options.recursive === false) {
95+
continue;
96+
}
97+
9398
if (entry.isDirectory() && options.ignoreFolders.has(entry.name)) {
9499
continue;
95100
}

0 commit comments

Comments
 (0)