@cldmv/fix-headers 1.2.2 → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,8 +1,8 @@
1
- # fix-headers
1
+ # @cldmv/fix-headers
2
2
 
3
3
  Multi-language source header normalizer for Node.js projects.
4
4
 
5
- `fix-headers` scans project files, auto-detects project metadata (language, root, project name, git author/email), and inserts or updates standard file headers.
5
+ `@cldmv/fix-headers` scans project files, auto-detects project metadata (language, root, project name, git author/email), and inserts or updates standard file headers.
6
6
 
7
7
  [![npm version]][npm_version_url] [![npm downloads]][npm_downloads_url] <!-- [![GitHub release]][github_release_url] -->[![GitHub downloads]][github_downloads_url] [![Last commit]][last_commit_url] <!-- [![Release date]][release_date_url] -->[![npm last update]][npm_last_update_url] [![Coverage]][coverage_url]
8
8
 
@@ -13,7 +13,7 @@ Multi-language source header normalizer for Node.js projects.
13
13
  - Auto-detects project type by marker files (`package.json`, `pyproject.toml`, `Cargo.toml`, `go.mod`, `composer.json`) and YAML files (`.yaml`, `.yml`)
14
14
  - Auto-detects author and email from git config/commit history
15
15
  - Supports per-run overrides for every detected value
16
- - Supports folder inclusion and exclusion configuration
16
+ - Supports folder inclusion and exclusion configuration, with project-root-scoped build/cache ignores and optional `.gitignore` respect
17
17
  - Supports detector-based monorepo scanning with nearest config resolution per file
18
18
  - Supports per-detector syntax overrides for line and block comment tokens
19
19
  - Supports both ESM and CJS consumers
@@ -21,7 +21,7 @@ Multi-language source header normalizer for Node.js projects.
21
21
  ## Install
22
22
 
23
23
  ```bash
24
- npm i fix-headers
24
+ npm i @cldmv/fix-headers
25
25
  ```
26
26
 
27
27
  ## Usage
@@ -29,7 +29,7 @@ npm i fix-headers
29
29
  ### ESM
30
30
 
31
31
  ```js
32
- import fixHeaders from "fix-headers";
32
+ import fixHeaders from "@cldmv/fix-headers";
33
33
 
34
34
  const result = await fixHeaders({ dryRun: true });
35
35
  ```
@@ -70,7 +70,7 @@ Common CLI options:
70
70
  ### CommonJS
71
71
 
72
72
  ```js
73
- const fixHeaders = require("fix-headers");
73
+ const fixHeaders = require("@cldmv/fix-headers");
74
74
 
75
75
  const result = await fixHeaders({ dryRun: true });
76
76
  ```
@@ -94,6 +94,7 @@ Important options:
94
94
  - `detectorSyntaxOverrides?: Record<string, { linePrefix?: string, lineSeparator?: string, blockStart?: string, blockLinePrefix?: string, blockEnd?: string }>` - override detector comment syntax tokens
95
95
  - `includeFolders?: string[]` - project-relative folders to scan
96
96
  - `excludeFolders?: string[]` - folder names or relative paths to exclude
97
+ - `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.
97
98
  - `projectName?: string`
98
99
  - `language?: string`
99
100
  - `projectRoot?: string`
@@ -135,6 +136,8 @@ const result = await fixHeaders({
135
136
  ## Notes
136
137
 
137
138
  - `excludeFolders` supports both folder-name and nested path matching.
139
+ - 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.
140
+ - 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.
138
141
  - For monorepos, each file resolves metadata from the closest detector config in its parent tree.
139
142
  - With `sampleOutput` enabled, each changed file includes `previousValue`, `newValue`, and `detectedValues` in results.
140
143
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cldmv/fix-headers",
3
- "version": "1.2.2",
3
+ "version": "1.3.0",
4
4
  "description": "Multi-language project header normalizer with auto-detection and override support.",
5
5
  "type": "module",
6
6
  "main": "./index.cjs",
@@ -49,8 +49,11 @@
49
49
  "license": "Apache-2.0",
50
50
  "devDependencies": {
51
51
  "@types/node": "^25.3.0",
52
+ "@vitest/coverage-v8": "^4.1.8",
52
53
  "typescript": "^5.9.3",
53
- "@vitest/coverage-v8": "^3.2.4",
54
- "vitest": "^3.2.4"
54
+ "vitest": "^4.1.8"
55
+ },
56
+ "dependencies": {
57
+ "ignore": "^7.0.5"
55
58
  }
56
59
  }
package/src/constants.mjs CHANGED
@@ -24,5 +24,25 @@ export const DEFAULT_COMPANY_NAME = "Catalyzed Motivation Inc.";
24
24
  /** @type {number} */
25
25
  export const DEFAULT_MAX_HEADER_SCAN_LINES = 40;
26
26
 
27
- /** @type {Set<string>} */
28
- export const DEFAULT_IGNORE_FOLDERS = new Set([".git", "node_modules", "dist", "build", "coverage", "tmp", ".next", ".turbo"]);
27
+ /**
28
+ * Folders skipped at ANY depth — vendored / VCS directories that are never source and can
29
+ * legitimately nest (hoisted `node_modules`, submodule `.git`).
30
+ * @type {Set<string>}
31
+ */
32
+ export const ALWAYS_IGNORE_FOLDERS = new Set([".git", "node_modules"]);
33
+
34
+ /**
35
+ * Folders skipped ONLY at the project root — build / cache output directories. Anchored to
36
+ * the root so a nested SOURCE directory that happens to share the name (e.g. `tools/build`,
37
+ * `packages/x/dist`-style source) is still processed; only the top-level `/build`, `/dist`,
38
+ * `/coverage`, … are ignored.
39
+ * @type {Set<string>}
40
+ */
41
+ export const ROOT_IGNORE_FOLDERS = new Set(["dist", "build", "coverage", "tmp", ".next", ".turbo"]);
42
+
43
+ /**
44
+ * Backward-compatible union of {@link ALWAYS_IGNORE_FOLDERS} and {@link ROOT_IGNORE_FOLDERS}.
45
+ * Discovery applies the two sets with different scoping; prefer the specific sets.
46
+ * @type {Set<string>}
47
+ */
48
+ export const DEFAULT_IGNORE_FOLDERS = new Set([...ALWAYS_IGNORE_FOLDERS, ...ROOT_IGNORE_FOLDERS]);
@@ -12,8 +12,9 @@
12
12
  */
13
13
 
14
14
  import { join, relative, resolve } from "node:path";
15
- import { stat } from "node:fs/promises";
16
- import { DEFAULT_IGNORE_FOLDERS } from "../constants.mjs";
15
+ import { readFile, stat } from "node:fs/promises";
16
+ import ignore from "ignore";
17
+ import { ALWAYS_IGNORE_FOLDERS, ROOT_IGNORE_FOLDERS } from "../constants.mjs";
17
18
  import { getAllowedExtensions } from "../detectors/index.mjs";
18
19
  import { walkFiles } from "../utils/fs.mjs";
19
20
 
@@ -35,7 +36,7 @@ function resolveExtensions(options) {
35
36
  return getAllowedExtensions(options);
36
37
  }
37
38
 
38
- const DEFAULT_IGNORED_FOLDERS = new Set(DEFAULT_IGNORE_FOLDERS);
39
+ const ALWAYS_IGNORED_FOLDERS = new Set(ALWAYS_IGNORE_FOLDERS);
39
40
 
40
41
  /**
41
42
  * Normalizes a user-provided folder path to a project-relative value.
@@ -131,8 +132,10 @@ function buildExclusionMatcher(projectRoot, excludeFolders) {
131
132
  * enabledDetectors?: string[],
132
133
  * disabledDetectors?: string[],
133
134
  * includeFolders?: string[],
134
- * excludeFolders?: string[]
135
- * }} options - File discovery options.
135
+ * excludeFolders?: string[],
136
+ * 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`.
136
139
  * @returns {Promise<string[]>} Absolute file paths.
137
140
  */
138
141
  export async function discoverFiles(options) {
@@ -140,6 +143,42 @@ export async function discoverFiles(options) {
140
143
  const includeFolders = resolveIncludeFolders(options.includeFolders);
141
144
  const excludeFolders = Array.isArray(options.excludeFolders) ? options.excludeFolders : [];
142
145
  const exclusionMatcher = buildExclusionMatcher(options.projectRoot, excludeFolders);
146
+ // Build/cache dirs (ROOT_IGNORE_FOLDERS) are ignored only at the PROJECT ROOT, so a nested
147
+ // source directory with the same name (e.g. tools/build) is still processed. node_modules /
148
+ // .git stay any-depth via walkFiles' `ignoreFolders` below.
149
+ const absoluteRoot = resolve(options.projectRoot);
150
+ const rootIgnorePaths = new Set(Array.from(ROOT_IGNORE_FOLDERS, (name) => resolve(absoluteRoot, name)));
151
+ // Optional .gitignore support: skip anything the project's .gitignore matches, so generated /
152
+ // output paths are excluded by the project's own rules without hard-coding names. `options.gitignore`
153
+ // may be `false` (disabled), a file path or array of paths, or anything else / undefined
154
+ // (auto-detect `<projectRoot>/.gitignore`).
155
+ let gitignoreMatcher = null;
156
+ if (options.gitignore !== false) {
157
+ const gitignoreFiles =
158
+ typeof options.gitignore === "string"
159
+ ? [options.gitignore]
160
+ : Array.isArray(options.gitignore)
161
+ ? options.gitignore.filter((entry) => typeof entry === "string")
162
+ : [".gitignore"];
163
+ const ig = ignore();
164
+ let loaded = false;
165
+ for (const rel of gitignoreFiles) {
166
+ try {
167
+ ig.add(await readFile(resolve(absoluteRoot, rel), "utf8"));
168
+ loaded = true;
169
+ } catch {
170
+ /* missing .gitignore — nothing to add */
171
+ }
172
+ }
173
+ gitignoreMatcher = loaded ? ig : null;
174
+ }
175
+ const isGitignored = (targetPath) => {
176
+ if (!gitignoreMatcher) return false;
177
+ const rel = relative(absoluteRoot, resolve(targetPath)).replace(/\\/g, "/");
178
+ return rel.length > 0 && !rel.startsWith("..") && gitignoreMatcher.ignores(rel);
179
+ };
180
+ const shouldSkipDirectory = (targetPath, targetName) =>
181
+ rootIgnorePaths.has(resolve(targetPath)) || exclusionMatcher(targetPath, targetName) || isGitignored(targetPath);
143
182
  const roots =
144
183
  includeFolders.length > 0
145
184
  ? includeFolders.map((includeFolder) => ({ includeFolder, rootPath: join(options.projectRoot, includeFolder) }))
@@ -164,11 +203,11 @@ export async function discoverFiles(options) {
164
203
 
165
204
  const discovered = await walkFiles(root.rootPath, {
166
205
  allowedExtensions,
167
- ignoreFolders: DEFAULT_IGNORED_FOLDERS,
168
- shouldSkipDirectory: exclusionMatcher
206
+ ignoreFolders: ALWAYS_IGNORED_FOLDERS,
207
+ shouldSkipDirectory
169
208
  });
170
209
  files.push(...discovered);
171
210
  }
172
211
 
173
- return files.filter((filePath) => !exclusionMatcher(filePath, filePath.split("/").at(-1) || ""));
212
+ return files.filter((filePath) => !exclusionMatcher(filePath, filePath.split("/").at(-1) || "") && !isGitignored(filePath));
174
213
  }
@@ -36,6 +36,7 @@ import { toDatePayload } from "../utils/time.mjs";
36
36
  * includeFolders?: string[],
37
37
  * excludeFolders?: string[],
38
38
  * includeExtensions?: string[],
39
+ * gitignore?: boolean | string | string[],
39
40
  * projectName?: string,
40
41
  * language?: string,
41
42
  * projectRoot?: string,
@@ -209,7 +210,8 @@ export async function fixHeaders(options = {}) {
209
210
  disabledDetectors: effectiveOptions.disabledDetectors,
210
211
  includeFolders: effectiveOptions.includeFolders,
211
212
  excludeFolders: effectiveOptions.excludeFolders,
212
- includeExtensions: effectiveOptions.includeExtensions
213
+ includeExtensions: effectiveOptions.includeExtensions,
214
+ gitignore: effectiveOptions.gitignore
213
215
  });
214
216
  } else {
215
217
  throw new Error(`Input path must be a file or directory: ${effectiveOptions.input}`);
@@ -222,7 +224,8 @@ export async function fixHeaders(options = {}) {
222
224
  disabledDetectors: effectiveOptions.disabledDetectors,
223
225
  includeFolders: effectiveOptions.includeFolders,
224
226
  excludeFolders: effectiveOptions.excludeFolders,
225
- includeExtensions: effectiveOptions.includeExtensions
227
+ includeExtensions: effectiveOptions.includeExtensions,
228
+ gitignore: effectiveOptions.gitignore
226
229
  });
227
230
  }
228
231
 
@@ -140,12 +140,12 @@ export function getDetectorById(id) {
140
140
  /**
141
141
  * Resolves comment syntax for a file path using detector-specific templates.
142
142
  * @param {string} filePath - File path.
143
- * @param {{ language?: string, enabledDetectors?: string[], disabledDetectors?: string[], detectorSyntaxOverrides?: Record<string, { linePrefix?: string, lineSeparator?: string, blockStart?: string, blockLinePrefix?: string, blockEnd?: string }> }} [options={}] - Runtime options.
143
+ * @param {{ language?: string, enabledDetectors?: string[], disabledDetectors?: string[], detectors?: object[], detectorSyntaxOverrides?: Record<string, { linePrefix?: string, lineSeparator?: string, blockStart?: string, blockLinePrefix?: string, blockEnd?: string }> }} [options={}] - Runtime options. `detectors` overrides the enabled-detector set (matching {@link detectProjectFromMarkers}).
144
144
  * @returns {{kind: "block" | "line" | "html", linePrefix?: string, lineSeparator?: string, blockStart?: string, blockLinePrefix?: string, blockEnd?: string}} Syntax descriptor.
145
145
  */
146
146
  export function getCommentSyntaxForFile(filePath, options = {}) {
147
147
  const extension = extname(filePath).toLowerCase();
148
- const detectors = getEnabledDetectors(options);
148
+ const detectors = Array.isArray(options.detectors) ? options.detectors : getEnabledDetectors(options);
149
149
  for (const detector of detectors) {
150
150
  if (!detector.extensions.includes(extension)) {
151
151
  continue;
@@ -66,9 +66,19 @@ function matchHeaderSegment(content, syntax) {
66
66
  return content.match(new RegExp(`^(?:${linePrefix}.*\\n)+\\n*`));
67
67
  }
68
68
 
69
- const blockStart = escapeRegex(syntax.blockStart || "/**");
70
- const blockEnd = escapeRegex(syntax.blockEnd || " */");
71
- return content.match(new RegExp(`^${blockStart}[\\s\\S]*?${blockEnd}\\n*`));
69
+ // Block comments (/* … */ family). A block comment opens with `/*` and is
70
+ // terminated by the FIRST `*/` after the opener (block comments do not nest in
71
+ // JS/JSONC/CSS/PHP). Match that real grammar rather than the detector's *styled*
72
+ // tokens: `blockStart` may be `/*` or `/**` (so anchor on `/*`, which prefixes
73
+ // both), and `blockEnd` carries a leading space (" */") that exists for GENERATION
74
+ // only. Using the styled " */" to bound an EXISTING header is the data-loss bug —
75
+ // any real closer that isn't byte-for-byte " */" (e.g. `**/`, a tab-indented `*/`,
76
+ // or `*/` at column 0) is skipped, so the lazy match runs on to the next `*/`
77
+ // downstream (inside a `//` line comment, a string literal, or another block) and
78
+ // everything in between is deleted on replace. Trim the styled space off so we stop
79
+ // at the header's own terminator.
80
+ const blockEnd = escapeRegex((syntax.blockEnd || " */").trim());
81
+ return content.match(new RegExp(`^/\\*[\\s\\S]*?${blockEnd}\\n*`));
72
82
  }
73
83
 
74
84
  /**