code-gauge 4.1.2 → 4.2.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,9 +1,10 @@
1
1
  # code-gauge
2
2
 
3
- [![Test rust](https://github.com/WillBooster/code-gauge/actions/workflows/test-rust.yml/badge.svg)](https://github.com/WillBooster/code-gauge/actions/workflows/test-rust.yml)
3
+ [![npm version](https://img.shields.io/npm/v/code-gauge.svg)](https://www.npmjs.com/package/code-gauge)
4
4
  [![Test](https://github.com/WillBooster/code-gauge/actions/workflows/test.yml/badge.svg)](https://github.com/WillBooster/code-gauge/actions/workflows/test.yml)
5
+ [![Test rust](https://github.com/WillBooster/code-gauge/actions/workflows/test-rust.yml/badge.svg)](https://github.com/WillBooster/code-gauge/actions/workflows/test-rust.yml)
5
6
  [![semantic-release](https://img.shields.io/badge/%20%20%F0%9F%93%A6%F0%9F%9A%80-semantic--release-e10079.svg)](https://github.com/semantic-release/semantic-release)
6
- [![wbfy](https://img.shields.io/badge/wbfy-19.2.0-1e90ff.svg)](https://github.com/WillBooster/shared/tree/main/packages/wbfy)
7
+ [![wbfy](https://img.shields.io/badge/wbfy-20.3.0-1e90ff.svg)](https://github.com/WillBooster/shared/tree/main/packages/wbfy)
7
8
 
8
9
  A command-line tool that ranks the files of a project by refactoring priority and gates changes
9
10
  against metric regressions, built for AI-agent workflows: an agent asked to "refactor this
@@ -24,9 +25,9 @@ npm install -g code-gauge
24
25
  code-gauge path/to/project
25
26
  ```
26
27
 
27
- The CLI scans JavaScript, JSX, TypeScript, TSX, Python, Go, Rust, Java, Ruby, C, and C++ files. By
28
- default it skips generated, vendor, test, and tool directories and prints the top 10 refactoring
29
- candidates:
28
+ The CLI scans JavaScript, JSX, TypeScript, TSX, Python, Go, Rust, Java, Kotlin, C#, Ruby, C, and
29
+ C++ files. By default it skips generated, vendor, test, and tool directories and prints the top 10
30
+ refactoring candidates:
30
31
 
31
32
  ```
32
33
  Measured 123 files under /path/to/project (code LOC 45678, NCSS 23456, functions 1789)
@@ -191,9 +192,9 @@ maintainability index, and similar) are intentionally not measured; see
191
192
 
192
193
  ## Supported languages
193
194
 
194
- Built-in parsers cover JavaScript, JSX, TypeScript, TSX, Python, Go, Rust, Java, Ruby, C, and C++.
195
- The language set is fixed by design: every metric is calibrated per grammar, and supporting
196
- arbitrary grammars would mean shipping incomplete metrics for them.
195
+ Built-in parsers cover JavaScript, JSX, TypeScript, TSX, Python, Go, Rust, Java, Kotlin, C#, Ruby,
196
+ C, and C++. The language set is fixed by design: every metric is calibrated per grammar, and
197
+ supporting arbitrary grammars would mean shipping incomplete metrics for them.
197
198
 
198
199
  ## Native (Rust) engine
199
200
 
@@ -1,2 +1,2 @@
1
- "use strict";const e=[{name:`javascript`,aliases:[`js`,`mjs`,`cjs`]},{name:`jsx`},{name:`typescript`,aliases:[`ts`]},{name:`tsx`},{name:`python`,aliases:[`py`]},{name:`go`},{name:`rust`,aliases:[`rs`]},{name:`java`},{name:`ruby`,aliases:[`rb`]},{name:`c`},{name:`cpp`,aliases:[`c++`,`cxx`]}];function t(t=e){let n=new Map;for(let e of t){n.set(e.name,e);for(let t of e.aliases??[])n.set(t,e)}return n}const n=e.map(e=>e.name);exports.createLanguageRegistry=t,exports.defaultLanguages=e,exports.supportedLanguages=n;
1
+ "use strict";const e=[{name:`javascript`,aliases:[`js`,`mjs`,`cjs`]},{name:`jsx`},{name:`typescript`,aliases:[`ts`]},{name:`tsx`},{name:`python`,aliases:[`py`]},{name:`go`},{name:`rust`,aliases:[`rs`]},{name:`java`},{name:`ruby`,aliases:[`rb`]},{name:`c`},{name:`cpp`,aliases:[`c++`,`cxx`]},{name:`csharp`,aliases:[`cs`,`c#`]},{name:`kotlin`,aliases:[`kt`,`kts`]}];function t(t=e){let n=new Map;for(let e of t){n.set(e.name,e);for(let t of e.aliases??[])n.set(t,e)}return n}const n=e.map(e=>e.name);exports.createLanguageRegistry=t,exports.defaultLanguages=e,exports.supportedLanguages=n;
2
2
  //# sourceMappingURL=languages.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"languages.cjs","names":[],"sources":["../src/languages.ts"],"sourcesContent":["import type { LanguageDefinition, LanguageName } from './types.js';\n\n/**\n * The built-in languages. Grammars and per-language node-type configuration live in the Rust\n * addon (native/src/languages.rs); this list only names the languages and their aliases so the\n * CLI and API can resolve and enumerate them without crossing the N-API boundary.\n */\nexport const defaultLanguages: readonly LanguageDefinition[] = [\n { name: 'javascript', aliases: ['js', 'mjs', 'cjs'] },\n { name: 'jsx' },\n { name: 'typescript', aliases: ['ts'] },\n { name: 'tsx' },\n { name: 'python', aliases: ['py'] },\n { name: 'go' },\n { name: 'rust', aliases: ['rs'] },\n { name: 'java' },\n { name: 'ruby', aliases: ['rb'] },\n { name: 'c' },\n { name: 'cpp', aliases: ['c++', 'cxx'] },\n];\n\nexport function createLanguageRegistry(\n languages: readonly LanguageDefinition[] = defaultLanguages\n): Map<LanguageName, LanguageDefinition> {\n const registry = new Map<LanguageName, LanguageDefinition>();\n\n for (const language of languages) {\n registry.set(language.name, language);\n for (const alias of language.aliases ?? []) {\n registry.set(alias, language);\n }\n }\n\n return registry;\n}\n\nexport const supportedLanguages = defaultLanguages.map((language) => language.name);\n"],"mappings":"aAOA,MAAa,EAAkD,CAC7D,CAAE,KAAM,aAAc,QAAS,CAAC,KAAM,MAAO,KAAK,CAAE,EACpD,CAAE,KAAM,KAAM,EACd,CAAE,KAAM,aAAc,QAAS,CAAC,IAAI,CAAE,EACtC,CAAE,KAAM,KAAM,EACd,CAAE,KAAM,SAAU,QAAS,CAAC,IAAI,CAAE,EAClC,CAAE,KAAM,IAAK,EACb,CAAE,KAAM,OAAQ,QAAS,CAAC,IAAI,CAAE,EAChC,CAAE,KAAM,MAAO,EACf,CAAE,KAAM,OAAQ,QAAS,CAAC,IAAI,CAAE,EAChC,CAAE,KAAM,GAAI,EACZ,CAAE,KAAM,MAAO,QAAS,CAAC,MAAO,KAAK,CAAE,CACzC,EAEA,SAAgB,EACd,EAA2C,EACJ,CACvC,IAAM,EAAW,IAAI,IAErB,IAAK,IAAM,KAAY,EAAW,CAChC,EAAS,IAAI,EAAS,KAAM,CAAQ,EACpC,IAAK,IAAM,KAAS,EAAS,SAAW,CAAC,EACvC,EAAS,IAAI,EAAO,CAAQ,CAEhC,CAEA,OAAO,CACT,CAEA,MAAa,EAAqB,EAAiB,IAAK,GAAa,EAAS,IAAI"}
1
+ {"version":3,"file":"languages.cjs","names":[],"sources":["../src/languages.ts"],"sourcesContent":["import type { LanguageDefinition, LanguageName } from './types.js';\n\n/**\n * The built-in languages. Grammars and per-language node-type configuration live in the Rust\n * addon (native/src/languages.rs); this list only names the languages and their aliases so the\n * CLI and API can resolve and enumerate them without crossing the N-API boundary.\n */\nexport const defaultLanguages: readonly LanguageDefinition[] = [\n { name: 'javascript', aliases: ['js', 'mjs', 'cjs'] },\n { name: 'jsx' },\n { name: 'typescript', aliases: ['ts'] },\n { name: 'tsx' },\n { name: 'python', aliases: ['py'] },\n { name: 'go' },\n { name: 'rust', aliases: ['rs'] },\n { name: 'java' },\n { name: 'ruby', aliases: ['rb'] },\n { name: 'c' },\n { name: 'cpp', aliases: ['c++', 'cxx'] },\n { name: 'csharp', aliases: ['cs', 'c#'] },\n { name: 'kotlin', aliases: ['kt', 'kts'] },\n];\n\nexport function createLanguageRegistry(\n languages: readonly LanguageDefinition[] = defaultLanguages\n): Map<LanguageName, LanguageDefinition> {\n const registry = new Map<LanguageName, LanguageDefinition>();\n\n for (const language of languages) {\n registry.set(language.name, language);\n for (const alias of language.aliases ?? []) {\n registry.set(alias, language);\n }\n }\n\n return registry;\n}\n\nexport const supportedLanguages = defaultLanguages.map((language) => language.name);\n"],"mappings":"aAOA,MAAa,EAAkD,CAC7D,CAAE,KAAM,aAAc,QAAS,CAAC,KAAM,MAAO,KAAK,CAAE,EACpD,CAAE,KAAM,KAAM,EACd,CAAE,KAAM,aAAc,QAAS,CAAC,IAAI,CAAE,EACtC,CAAE,KAAM,KAAM,EACd,CAAE,KAAM,SAAU,QAAS,CAAC,IAAI,CAAE,EAClC,CAAE,KAAM,IAAK,EACb,CAAE,KAAM,OAAQ,QAAS,CAAC,IAAI,CAAE,EAChC,CAAE,KAAM,MAAO,EACf,CAAE,KAAM,OAAQ,QAAS,CAAC,IAAI,CAAE,EAChC,CAAE,KAAM,GAAI,EACZ,CAAE,KAAM,MAAO,QAAS,CAAC,MAAO,KAAK,CAAE,EACvC,CAAE,KAAM,SAAU,QAAS,CAAC,KAAM,IAAI,CAAE,EACxC,CAAE,KAAM,SAAU,QAAS,CAAC,KAAM,KAAK,CAAE,CAC3C,EAEA,SAAgB,EACd,EAA2C,EACJ,CACvC,IAAM,EAAW,IAAI,IAErB,IAAK,IAAM,KAAY,EAAW,CAChC,EAAS,IAAI,EAAS,KAAM,CAAQ,EACpC,IAAK,IAAM,KAAS,EAAS,SAAW,CAAC,EACvC,EAAS,IAAI,EAAO,CAAQ,CAEhC,CAEA,OAAO,CACT,CAEA,MAAa,EAAqB,EAAiB,IAAK,GAAa,EAAS,IAAI"}
package/dist/languages.js CHANGED
@@ -1,2 +1,2 @@
1
- const e=[{name:`javascript`,aliases:[`js`,`mjs`,`cjs`]},{name:`jsx`},{name:`typescript`,aliases:[`ts`]},{name:`tsx`},{name:`python`,aliases:[`py`]},{name:`go`},{name:`rust`,aliases:[`rs`]},{name:`java`},{name:`ruby`,aliases:[`rb`]},{name:`c`},{name:`cpp`,aliases:[`c++`,`cxx`]}];function t(t=e){let n=new Map;for(let e of t){n.set(e.name,e);for(let t of e.aliases??[])n.set(t,e)}return n}const n=e.map(e=>e.name);export{t as createLanguageRegistry,e as defaultLanguages,n as supportedLanguages};
1
+ const e=[{name:`javascript`,aliases:[`js`,`mjs`,`cjs`]},{name:`jsx`},{name:`typescript`,aliases:[`ts`]},{name:`tsx`},{name:`python`,aliases:[`py`]},{name:`go`},{name:`rust`,aliases:[`rs`]},{name:`java`},{name:`ruby`,aliases:[`rb`]},{name:`c`},{name:`cpp`,aliases:[`c++`,`cxx`]},{name:`csharp`,aliases:[`cs`,`c#`]},{name:`kotlin`,aliases:[`kt`,`kts`]}];function t(t=e){let n=new Map;for(let e of t){n.set(e.name,e);for(let t of e.aliases??[])n.set(t,e)}return n}const n=e.map(e=>e.name);export{t as createLanguageRegistry,e as defaultLanguages,n as supportedLanguages};
2
2
  //# sourceMappingURL=languages.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"languages.js","names":[],"sources":["../src/languages.ts"],"sourcesContent":["import type { LanguageDefinition, LanguageName } from './types.js';\n\n/**\n * The built-in languages. Grammars and per-language node-type configuration live in the Rust\n * addon (native/src/languages.rs); this list only names the languages and their aliases so the\n * CLI and API can resolve and enumerate them without crossing the N-API boundary.\n */\nexport const defaultLanguages: readonly LanguageDefinition[] = [\n { name: 'javascript', aliases: ['js', 'mjs', 'cjs'] },\n { name: 'jsx' },\n { name: 'typescript', aliases: ['ts'] },\n { name: 'tsx' },\n { name: 'python', aliases: ['py'] },\n { name: 'go' },\n { name: 'rust', aliases: ['rs'] },\n { name: 'java' },\n { name: 'ruby', aliases: ['rb'] },\n { name: 'c' },\n { name: 'cpp', aliases: ['c++', 'cxx'] },\n];\n\nexport function createLanguageRegistry(\n languages: readonly LanguageDefinition[] = defaultLanguages\n): Map<LanguageName, LanguageDefinition> {\n const registry = new Map<LanguageName, LanguageDefinition>();\n\n for (const language of languages) {\n registry.set(language.name, language);\n for (const alias of language.aliases ?? []) {\n registry.set(alias, language);\n }\n }\n\n return registry;\n}\n\nexport const supportedLanguages = defaultLanguages.map((language) => language.name);\n"],"mappings":"AAOA,MAAa,EAAkD,CAC7D,CAAE,KAAM,aAAc,QAAS,CAAC,KAAM,MAAO,KAAK,CAAE,EACpD,CAAE,KAAM,KAAM,EACd,CAAE,KAAM,aAAc,QAAS,CAAC,IAAI,CAAE,EACtC,CAAE,KAAM,KAAM,EACd,CAAE,KAAM,SAAU,QAAS,CAAC,IAAI,CAAE,EAClC,CAAE,KAAM,IAAK,EACb,CAAE,KAAM,OAAQ,QAAS,CAAC,IAAI,CAAE,EAChC,CAAE,KAAM,MAAO,EACf,CAAE,KAAM,OAAQ,QAAS,CAAC,IAAI,CAAE,EAChC,CAAE,KAAM,GAAI,EACZ,CAAE,KAAM,MAAO,QAAS,CAAC,MAAO,KAAK,CAAE,CACzC,EAEA,SAAgB,EACd,EAA2C,EACJ,CACvC,IAAM,EAAW,IAAI,IAErB,IAAK,IAAM,KAAY,EAAW,CAChC,EAAS,IAAI,EAAS,KAAM,CAAQ,EACpC,IAAK,IAAM,KAAS,EAAS,SAAW,CAAC,EACvC,EAAS,IAAI,EAAO,CAAQ,CAEhC,CAEA,OAAO,CACT,CAEA,MAAa,EAAqB,EAAiB,IAAK,GAAa,EAAS,IAAI"}
1
+ {"version":3,"file":"languages.js","names":[],"sources":["../src/languages.ts"],"sourcesContent":["import type { LanguageDefinition, LanguageName } from './types.js';\n\n/**\n * The built-in languages. Grammars and per-language node-type configuration live in the Rust\n * addon (native/src/languages.rs); this list only names the languages and their aliases so the\n * CLI and API can resolve and enumerate them without crossing the N-API boundary.\n */\nexport const defaultLanguages: readonly LanguageDefinition[] = [\n { name: 'javascript', aliases: ['js', 'mjs', 'cjs'] },\n { name: 'jsx' },\n { name: 'typescript', aliases: ['ts'] },\n { name: 'tsx' },\n { name: 'python', aliases: ['py'] },\n { name: 'go' },\n { name: 'rust', aliases: ['rs'] },\n { name: 'java' },\n { name: 'ruby', aliases: ['rb'] },\n { name: 'c' },\n { name: 'cpp', aliases: ['c++', 'cxx'] },\n { name: 'csharp', aliases: ['cs', 'c#'] },\n { name: 'kotlin', aliases: ['kt', 'kts'] },\n];\n\nexport function createLanguageRegistry(\n languages: readonly LanguageDefinition[] = defaultLanguages\n): Map<LanguageName, LanguageDefinition> {\n const registry = new Map<LanguageName, LanguageDefinition>();\n\n for (const language of languages) {\n registry.set(language.name, language);\n for (const alias of language.aliases ?? []) {\n registry.set(alias, language);\n }\n }\n\n return registry;\n}\n\nexport const supportedLanguages = defaultLanguages.map((language) => language.name);\n"],"mappings":"AAOA,MAAa,EAAkD,CAC7D,CAAE,KAAM,aAAc,QAAS,CAAC,KAAM,MAAO,KAAK,CAAE,EACpD,CAAE,KAAM,KAAM,EACd,CAAE,KAAM,aAAc,QAAS,CAAC,IAAI,CAAE,EACtC,CAAE,KAAM,KAAM,EACd,CAAE,KAAM,SAAU,QAAS,CAAC,IAAI,CAAE,EAClC,CAAE,KAAM,IAAK,EACb,CAAE,KAAM,OAAQ,QAAS,CAAC,IAAI,CAAE,EAChC,CAAE,KAAM,MAAO,EACf,CAAE,KAAM,OAAQ,QAAS,CAAC,IAAI,CAAE,EAChC,CAAE,KAAM,GAAI,EACZ,CAAE,KAAM,MAAO,QAAS,CAAC,MAAO,KAAK,CAAE,EACvC,CAAE,KAAM,SAAU,QAAS,CAAC,KAAM,IAAI,CAAE,EACxC,CAAE,KAAM,SAAU,QAAS,CAAC,KAAM,KAAK,CAAE,CAC3C,EAEA,SAAgB,EACd,EAA2C,EACJ,CACvC,IAAM,EAAW,IAAI,IAErB,IAAK,IAAM,KAAY,EAAW,CAChC,EAAS,IAAI,EAAS,KAAM,CAAQ,EACpC,IAAK,IAAM,KAAS,EAAS,SAAW,CAAC,EACvC,EAAS,IAAI,EAAO,CAAQ,CAEhC,CAEA,OAAO,CACT,CAEA,MAAa,EAAqB,EAAiB,IAAK,GAAa,EAAS,IAAI"}
package/dist/scan.cjs CHANGED
@@ -1,2 +1,2 @@
1
- "use strict";const e=require("./_virtual/_rolldown/runtime.cjs"),t=require("./crossFileDuplication.cjs"),n=require("./nativeMetrics.cjs"),r=require("./metrics.cjs");let i=require("node:fs/promises"),a=require("node:path");a=e.__toESM(a,1);let o=require("node:os");o=e.__toESM(o,1);const s=new Map([[`.c`,`c`],[`.c++`,`cpp`],[`.cc`,`cpp`],[`.cjs`,`javascript`],[`.cp`,`cpp`],[`.cpp`,`cpp`],[`.tcc`,`cpp`],[`.cts`,`typescript`],[`.cxx`,`cpp`],[`.go`,`go`],[`.h`,`cpp`],[`.hh`,`cpp`],[`.hpp`,`cpp`],[`.hxx`,`cpp`],[`.java`,`java`],[`.js`,`javascript`],[`.jsx`,`jsx`],[`.mjs`,`javascript`],[`.mts`,`typescript`],[`.py`,`python`],[`.rb`,`ruby`],[`.rs`,`rust`],[`.ts`,`typescript`],[`.tsx`,`tsx`]]),c=new Set([`.agents`,`.claude`,`.cursor`,`.git`,`.next`,`.playwright-cli`,`.tox`,`.tmp`,`.turbo`,`.venv`,`.yarn`,`__fixtures__`,`__generated__`,`__pycache__`,`coverage`,`dist`,`fixtures`,`generated`,`node_modules`,`target`,`test-fixtures`,`vendor`,`venv`]),l=new Set([`__tests__`,`test`,`tests`,`spec`]),u=/(?:^test(?:[_-].*)?|\.(?:spec|test)|[_-](?:test|spec))\.[^.]+$/iu,d=/Test\.java$/u;function f(e){return e===`~`?o.default.homedir():e.startsWith(`~/`)?a.default.join(o.default.homedir(),e.slice(2)):a.default.resolve(e)}async function p(e){try{return(await(0,i.stat)(e)).isDirectory()?e:a.default.dirname(e)}catch{return a.default.dirname(e)}}async function m(e,t){let n=[],r=[],o=[],s=e;try{s=await(0,i.realpath)(e)}catch{}let c=a.default.dirname(s),l;try{l=await(0,i.stat)(s)}catch(e){let t=`${A(s,c)}: ${N(e)}`;return{displayRoot:c,files:n,errors:[t],warnings:o,fatalError:t}}if(l.isFile()){let e=a.default.dirname(s),i=k(s,t,!0);if(!i){let t=`${A(s,e)}: unsupported file type`;return{displayRoot:e,files:n,errors:[t],warnings:o,fatalError:t}}let c=_(t,n,r,o,e);try{await C(s,i,`single-file`,c,s)}catch(t){return g(t,e,n,r,o)}return{displayRoot:e,files:n,errors:r,warnings:o}}try{await b(s,_(t,n,r,o,s))}catch(e){return g(e,s,n,r,o)}return{displayRoot:s,files:n,errors:r,warnings:o}}async function h(e,t,n){let r=[],o=[],s=[],c=_(n,r,o,s,e);for(let l of t){let t=O(l,n)?k(l,n):void 0;if(!t)continue;let u=a.default.join(e,l);if(!(await(0,i.lstat)(u).catch(()=>{}))?.isSymbolicLink())try{await C(u,t,`directory`,c)}catch(t){return g(t,e,r,o,s)}}return{displayRoot:e,files:r,errors:o,warnings:s}}function g(e,t,r,i,a){if(!(e instanceof n.NativeAddonError))throw e;let o=N(e);return{displayRoot:t,files:r,errors:[...i,o],warnings:a,fatalError:o}}function _(e,t,n,r,i){return{options:e,files:t,errors:n,warnings:r,visitedDirectories:new Set,visitedFiles:new Set,rootDirectory:i}}async function v(e,t,n){try{return await e()}catch(e){n.errors.push(`${A(t,n.rootDirectory)}: ${N(e)}`);return}}async function y(e,t){let n=await v(()=>(0,i.realpath)(e),e,t);return n!==void 0&&D(n,t.rootDirectory)?n:void 0}async function b(e,t){let n=await y(e,t);if(n===void 0||t.visitedDirectories.has(n))return;t.visitedDirectories.add(n);let r=await v(()=>(0,i.readdir)(e,{withFileTypes:!0}),e,t);if(r!==void 0)for(let n of r){let r=a.default.join(e,n.name);if(n.isSymbolicLink()){await x(n.name,r,t);continue}if(n.isDirectory()){if(E(n.name,t.options))continue;await b(r,t);continue}n.isFile()&&await S(r,t)}}async function x(e,t,n){let r=await y(t,n);if(r===void 0)return;let o=await v(()=>(0,i.stat)(t),t,n);if(o!==void 0){if(o.isDirectory()){if(E(e,n.options)||E(a.default.basename(r),n.options))return;await b(t,n);return}o.isFile()&&await S(t,n,r,r)}}async function S(e,t,n=e,r){let i=k(n,t.options);i&&await C(e,i,`directory`,t,r)}async function C(e,t,a,o,s){try{let n=s??await(0,i.realpath)(e);if(o.visitedFiles.has(n))return;o.visitedFiles.add(n);let c=await(0,i.readFile)(e,`utf8`),l={language:t,duplication:o.options.duplication},u={file:e,metrics:r.measureCode(c,l)};if(a===`directory`)try{u.duplicationCandidates=r.collectCrossFileDuplicationFileData(c,l)}catch(t){o.warnings.push(`${A(e,o.rootDirectory)}: cross-file duplication candidates unavailable: ${N(t)}`)}o.files.push(u)}catch(t){if(t instanceof n.NativeAddonError)throw t;o.errors.push(`${A(e,o.rootDirectory)}: ${N(t)}`)}}function w(e,n){if(e.fatalError||e.files.length<2)return;let r=e.files.flatMap(({file:t,duplicationCandidates:n})=>n?[{file:A(t,e.displayRoot),...n}]:[]);r.length<2||(e.crossFileDuplication=t.measureCrossFileDuplication(r,n.duplication))}function T(e,t,n){let r=new Set(e?.duplication.duplicateLineNumbers),i=t&&Object.hasOwn(t.duplicateLineNumbersByFile,n)?t.duplicateLineNumbersByFile[n]??[]:[];for(let e of i)r.add(e);return r}function E(e,t){return c.has(e)?!0:!t.includeTests&&l.has(e)}function D(e,t){let n=a.default.relative(t,e);return n===``||n!==`..`&&!n.startsWith(`..${a.default.sep}`)&&!a.default.isAbsolute(n)}function O(e,t){let n=e.split(`/`);for(let e of n.slice(0,-1))if(c.has(e)||!t.includeTests&&l.has(e))return!1;return k(e,t)!==void 0}function k(e,t,n=!1){let r=e.toLowerCase();if(!(!n&&(r.endsWith(`.d.ts`)||r.endsWith(`.d.mts`)||r.endsWith(`.d.cts`)||r.endsWith(`.min.js`)||r.endsWith(`.pnp.cjs`)))&&!(!n&&!t.includeTests&&(u.test(a.default.basename(e))||d.test(a.default.basename(e)))))return a.default.extname(e)===`.C`?`cpp`:s.get(a.default.extname(r))}function A(e,t){return a.default.relative(t,e)||a.default.basename(e)}function j(e){process.stdout.write(e)}function M(e){process.stderr.write(e)}function N(e){return e instanceof Error?e.message:String(e)}exports.addCrossFileDuplication=w,exports.collectDuplicatedLineNumbers=T,exports.configSearchDirectory=p,exports.formatError=N,exports.formatPath=A,exports.getLanguage=k,exports.isScannedPath=O,exports.resolveTarget=f,exports.scanListedFiles=h,exports.scanTarget=m,exports.writeStderr=M,exports.writeStdout=j;
1
+ "use strict";const e=require("./_virtual/_rolldown/runtime.cjs"),t=require("./crossFileDuplication.cjs"),n=require("./nativeMetrics.cjs"),r=require("./metrics.cjs");let i=require("node:fs/promises"),a=require("node:path");a=e.__toESM(a,1);let o=require("node:os");o=e.__toESM(o,1);const s=new Map([[`.c`,`c`],[`.c++`,`cpp`],[`.cc`,`cpp`],[`.cjs`,`javascript`],[`.cp`,`cpp`],[`.cpp`,`cpp`],[`.cs`,`csharp`],[`.tcc`,`cpp`],[`.cts`,`typescript`],[`.cxx`,`cpp`],[`.go`,`go`],[`.h`,`cpp`],[`.hh`,`cpp`],[`.hpp`,`cpp`],[`.hxx`,`cpp`],[`.java`,`java`],[`.js`,`javascript`],[`.jsx`,`jsx`],[`.kt`,`kotlin`],[`.kts`,`kotlin`],[`.mjs`,`javascript`],[`.mts`,`typescript`],[`.py`,`python`],[`.rb`,`ruby`],[`.rs`,`rust`],[`.ts`,`typescript`],[`.tsx`,`tsx`]]),c=new Set([`.agents`,`.claude`,`.cursor`,`.git`,`.next`,`.playwright-cli`,`.tox`,`.tmp`,`.turbo`,`.venv`,`.yarn`,`__fixtures__`,`__generated__`,`__pycache__`,`coverage`,`dist`,`fixtures`,`generated`,`node_modules`,`obj`,`target`,`test-fixtures`,`vendor`,`venv`]),l=new Set([`__tests__`,`test`,`tests`,`spec`]),u=/(?:^test(?:[_-].*)?|\.(?:spec|test)|[_-](?:test|spec))\.[^.]+$/iu,d=/Tests?\.(?:java|kt|cs)$/u;function f(e){return e===`~`?o.default.homedir():e.startsWith(`~/`)?a.default.join(o.default.homedir(),e.slice(2)):a.default.resolve(e)}async function p(e){try{return(await(0,i.stat)(e)).isDirectory()?e:a.default.dirname(e)}catch{return a.default.dirname(e)}}async function m(e,t){let n=[],r=[],o=[],s=e;try{s=await(0,i.realpath)(e)}catch{}let c=a.default.dirname(s),l;try{l=await(0,i.stat)(s)}catch(e){let t=`${A(s,c)}: ${N(e)}`;return{displayRoot:c,files:n,errors:[t],warnings:o,fatalError:t}}if(l.isFile()){let e=a.default.dirname(s),i=k(s,t,!0);if(!i){let t=`${A(s,e)}: unsupported file type`;return{displayRoot:e,files:n,errors:[t],warnings:o,fatalError:t}}let c=_(t,n,r,o,e);try{await C(s,i,`single-file`,c,s)}catch(t){return g(t,e,n,r,o)}return{displayRoot:e,files:n,errors:r,warnings:o}}try{await b(s,_(t,n,r,o,s))}catch(e){return g(e,s,n,r,o)}return{displayRoot:s,files:n,errors:r,warnings:o}}async function h(e,t,n){let r=[],o=[],s=[],c=_(n,r,o,s,e);for(let l of t){let t=O(l,n)?k(l,n):void 0;if(!t)continue;let u=a.default.join(e,l);if(!(await(0,i.lstat)(u).catch(()=>{}))?.isSymbolicLink())try{await C(u,t,`directory`,c)}catch(t){return g(t,e,r,o,s)}}return{displayRoot:e,files:r,errors:o,warnings:s}}function g(e,t,r,i,a){if(!(e instanceof n.NativeAddonError))throw e;let o=N(e);return{displayRoot:t,files:r,errors:[...i,o],warnings:a,fatalError:o}}function _(e,t,n,r,i){return{options:e,files:t,errors:n,warnings:r,visitedDirectories:new Set,visitedFiles:new Set,rootDirectory:i}}async function v(e,t,n){try{return await e()}catch(e){n.errors.push(`${A(t,n.rootDirectory)}: ${N(e)}`);return}}async function y(e,t){let n=await v(()=>(0,i.realpath)(e),e,t);return n!==void 0&&D(n,t.rootDirectory)?n:void 0}async function b(e,t){let n=await y(e,t);if(n===void 0||t.visitedDirectories.has(n))return;t.visitedDirectories.add(n);let r=await v(()=>(0,i.readdir)(e,{withFileTypes:!0}),e,t);if(r!==void 0)for(let n of r){let r=a.default.join(e,n.name);if(n.isSymbolicLink()){await x(n.name,r,t);continue}if(n.isDirectory()){if(E(n.name,t.options))continue;await b(r,t);continue}n.isFile()&&await S(r,t)}}async function x(e,t,n){let r=await y(t,n);if(r===void 0)return;let o=await v(()=>(0,i.stat)(t),t,n);if(o!==void 0){if(o.isDirectory()){if(E(e,n.options)||E(a.default.basename(r),n.options))return;await b(t,n);return}o.isFile()&&await S(t,n,r,r)}}async function S(e,t,n=e,r){let i=k(n,t.options);i&&await C(e,i,`directory`,t,r)}async function C(e,t,a,o,s){try{let n=s??await(0,i.realpath)(e);if(o.visitedFiles.has(n))return;o.visitedFiles.add(n);let c=await(0,i.readFile)(e,`utf8`),l={language:t,duplication:o.options.duplication},u={file:e,metrics:r.measureCode(c,l)};if(a===`directory`)try{u.duplicationCandidates=r.collectCrossFileDuplicationFileData(c,l)}catch(t){o.warnings.push(`${A(e,o.rootDirectory)}: cross-file duplication candidates unavailable: ${N(t)}`)}o.files.push(u)}catch(t){if(t instanceof n.NativeAddonError)throw t;o.errors.push(`${A(e,o.rootDirectory)}: ${N(t)}`)}}function w(e,n){if(e.fatalError||e.files.length<2)return;let r=e.files.flatMap(({file:t,duplicationCandidates:n})=>n?[{file:A(t,e.displayRoot),...n}]:[]);r.length<2||(e.crossFileDuplication=t.measureCrossFileDuplication(r,n.duplication))}function T(e,t,n){let r=new Set(e?.duplication.duplicateLineNumbers),i=t&&Object.hasOwn(t.duplicateLineNumbersByFile,n)?t.duplicateLineNumbersByFile[n]??[]:[];for(let e of i)r.add(e);return r}function E(e,t){return c.has(e)?!0:!t.includeTests&&l.has(e)}function D(e,t){let n=a.default.relative(t,e);return n===``||n!==`..`&&!n.startsWith(`..${a.default.sep}`)&&!a.default.isAbsolute(n)}function O(e,t){let n=e.split(`/`);for(let e of n.slice(0,-1))if(c.has(e)||!t.includeTests&&l.has(e))return!1;return k(e,t)!==void 0}function k(e,t,n=!1){let r=e.toLowerCase();if(!(!n&&(r.endsWith(`.d.ts`)||r.endsWith(`.d.mts`)||r.endsWith(`.d.cts`)||r.endsWith(`.min.js`)||r.endsWith(`.pnp.cjs`)))&&!(!n&&!t.includeTests&&(u.test(a.default.basename(e))||d.test(a.default.basename(e)))))return a.default.extname(e)===`.C`?`cpp`:s.get(a.default.extname(r))}function A(e,t){return a.default.relative(t,e)||a.default.basename(e)}function j(e){process.stdout.write(e)}function M(e){process.stderr.write(e)}function N(e){return e instanceof Error?e.message:String(e)}exports.addCrossFileDuplication=w,exports.collectDuplicatedLineNumbers=T,exports.configSearchDirectory=p,exports.formatError=N,exports.formatPath=A,exports.getLanguage=k,exports.isScannedPath=O,exports.resolveTarget=f,exports.scanListedFiles=h,exports.scanTarget=m,exports.writeStderr=M,exports.writeStdout=j;
2
2
  //# sourceMappingURL=scan.cjs.map
package/dist/scan.cjs.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"scan.cjs","names":["os","path","stat","realpath","lstat","NativeAddonError","readdir","readFile","measureCode","collectCrossFileDuplicationFileData","measureCrossFileDuplication"],"sources":["../src/scan.ts"],"sourcesContent":["import { lstat, readdir, readFile, realpath, stat } from 'node:fs/promises';\nimport os from 'node:os';\nimport path from 'node:path';\nimport { measureCrossFileDuplication, type CrossFileDuplicationMetrics } from './crossFileDuplication.js';\nimport type { CrossFileDuplicationFileData } from './duplication.js';\nimport { collectCrossFileDuplicationFileData, measureCode } from './metrics.js';\nimport { NativeAddonError } from './nativeMetrics.js';\nimport type { CodeMetrics, DuplicationOptions, LanguageName } from './types.js';\n\n/** The scan settings shared by every command (a structural subset of each command's options). */\nexport interface ScanOptions {\n duplication: Required<DuplicationOptions>;\n includeTests: boolean;\n}\n\nexport interface FileMetrics {\n file: string;\n metrics: CodeMetrics;\n /** Cross-file duplicate candidates and token/statement data, collected only for directory scans. */\n duplicationCandidates?: CrossFileDuplicationFileData;\n}\n\nexport interface ScanResult {\n crossFileDuplication?: CrossFileDuplicationMetrics;\n displayRoot: string;\n errors: string[];\n /** Non-fatal degradations (e.g. cross-file candidates unavailable); the file is still measured. */\n warnings: string[];\n fatalError?: string;\n files: FileMetrics[];\n}\n\nconst languageByExtension = new Map<string, LanguageName>([\n ['.c', 'c'],\n ['.c++', 'cpp'],\n ['.cc', 'cpp'],\n ['.cjs', 'javascript'],\n ['.cp', 'cpp'],\n ['.cpp', 'cpp'],\n ['.tcc', 'cpp'],\n ['.cts', 'typescript'],\n ['.cxx', 'cpp'],\n ['.go', 'go'],\n // Headers may be C or C++; the C++ grammar parses both.\n ['.h', 'cpp'],\n ['.hh', 'cpp'],\n ['.hpp', 'cpp'],\n ['.hxx', 'cpp'],\n ['.java', 'java'],\n ['.js', 'javascript'],\n ['.jsx', 'jsx'],\n ['.mjs', 'javascript'],\n ['.mts', 'typescript'],\n ['.py', 'python'],\n ['.rb', 'ruby'],\n ['.rs', 'rust'],\n ['.ts', 'typescript'],\n ['.tsx', 'tsx'],\n]);\n\nconst ignoredDirectoryNames = new Set([\n '.agents',\n '.claude',\n '.cursor',\n '.git',\n '.next',\n '.playwright-cli',\n '.tox',\n '.tmp',\n '.turbo',\n '.venv',\n '.yarn',\n '__fixtures__',\n '__generated__',\n '__pycache__',\n 'coverage',\n 'dist',\n 'fixtures',\n 'generated',\n 'node_modules',\n 'target',\n 'test-fixtures',\n 'vendor',\n 'venv',\n]);\n\nconst testDirectoryNames = new Set(['__tests__', 'test', 'tests', 'spec']);\nconst testFilePattern = /(?:^test(?:[_-].*)?|\\.(?:spec|test)|[_-](?:test|spec))\\.[^.]+$/iu;\n// JUnit tests use a case-sensitive `Test.java` suffix; case-insensitive matching would catch\n// production files like `contest.java`.\nconst javaTestFilePattern = /Test\\.java$/u;\n\nexport function resolveTarget(target: string): string {\n if (target === '~') {\n return os.homedir();\n }\n\n if (target.startsWith('~/')) {\n return path.join(os.homedir(), target.slice(2));\n }\n\n return path.resolve(target);\n}\n\n/** Returns the directory from which the config file search should start (the target itself if it is a directory). */\nexport async function configSearchDirectory(target: string): Promise<string> {\n try {\n const targetStat = await stat(target);\n return targetStat.isDirectory() ? target : path.dirname(target);\n } catch {\n return path.dirname(target);\n }\n}\n\n/** Shared state of one scan, threaded through the directory walk instead of positional plumbing. */\ninterface ScanContext {\n options: ScanOptions;\n files: FileMetrics[];\n errors: string[];\n warnings: string[];\n visitedDirectories: Set<string>;\n visitedFiles: Set<string>;\n /** Scan root: paths are displayed relative to it, and symbolic links may not escape it. */\n rootDirectory: string;\n}\n\nexport async function scanTarget(target: string, options: ScanOptions): Promise<ScanResult> {\n const files: FileMetrics[] = [];\n const errors: string[] = [];\n const warnings: string[] = [];\n let canonicalTarget = target;\n try {\n canonicalTarget = await realpath(target);\n } catch {\n // stat below reports missing targets with the original path.\n }\n\n const fallbackDisplayRoot = path.dirname(canonicalTarget);\n let targetStat;\n\n try {\n targetStat = await stat(canonicalTarget);\n } catch (error) {\n const fatalError = `${formatPath(canonicalTarget, fallbackDisplayRoot)}: ${formatError(error)}`;\n return { displayRoot: fallbackDisplayRoot, files, errors: [fatalError], warnings, fatalError };\n }\n\n if (targetStat.isFile()) {\n const displayRoot = path.dirname(canonicalTarget);\n const language = getLanguage(canonicalTarget, options, true);\n if (!language) {\n const fatalError = `${formatPath(canonicalTarget, displayRoot)}: unsupported file type`;\n return { displayRoot, files, errors: [fatalError], warnings, fatalError };\n }\n\n const context = makeScanContext(options, files, errors, warnings, displayRoot);\n try {\n await measureFile(canonicalTarget, language, 'single-file', context, canonicalTarget);\n } catch (error) {\n return toFatalResult(error, displayRoot, files, errors, warnings);\n }\n return { displayRoot, files, errors, warnings };\n }\n\n try {\n await scanDirectory(canonicalTarget, makeScanContext(options, files, errors, warnings, canonicalTarget));\n } catch (error) {\n return toFatalResult(error, canonicalTarget, files, errors, warnings);\n }\n return { displayRoot: canonicalTarget, files, errors, warnings };\n}\n\n/**\n * Measures an explicit list of repository-relative files (the diff gate's git-visible allowlist)\n * instead of walking the directory tree, so ignored artifact directories are never parsed. Paths\n * outside the scan scope (ignored/test directories, unsupported or test file names) are skipped\n * with the same rules as the walk.\n */\nexport async function scanListedFiles(\n rootDirectory: string,\n relativePaths: Iterable<string>,\n options: ScanOptions\n): Promise<ScanResult> {\n const files: FileMetrics[] = [];\n const errors: string[] = [];\n const warnings: string[] = [];\n const context = makeScanContext(options, files, errors, warnings, rootDirectory);\n for (const relativePath of relativePaths) {\n const language = isScannedPath(relativePath, options) ? getLanguage(relativePath, options) : undefined;\n if (!language) {\n continue;\n }\n const absolutePath = path.join(rootDirectory, relativePath);\n // Symbolic links are not source files: git stores only their target string, so measuring\n // through them would diverge from what any revision of the repository actually contains.\n const stats = await lstat(absolutePath).catch(() => {});\n if (stats?.isSymbolicLink()) {\n continue;\n }\n try {\n await measureFile(absolutePath, language, 'directory', context);\n } catch (error) {\n return toFatalResult(error, rootDirectory, files, errors, warnings);\n }\n }\n return { displayRoot: rootDirectory, files, errors, warnings };\n}\n\n/** A run-wide failure (a missing native addon) as a fatal result; anything else keeps throwing. */\nfunction toFatalResult(\n error: unknown,\n displayRoot: string,\n files: FileMetrics[],\n errors: string[],\n warnings: string[]\n): ScanResult {\n if (!(error instanceof NativeAddonError)) {\n throw error;\n }\n const fatalError = formatError(error);\n // Errors the walk accumulated before the fatal failure stay reported alongside it.\n return { displayRoot, files, errors: [...errors, fatalError], warnings, fatalError };\n}\n\nfunction makeScanContext(\n options: ScanOptions,\n files: FileMetrics[],\n errors: string[],\n warnings: string[],\n rootDirectory: string\n): ScanContext {\n return { options, files, errors, warnings, visitedDirectories: new Set(), visitedFiles: new Set(), rootDirectory };\n}\n\n/** Runs a filesystem operation, recording a scan error and returning undefined when it fails. */\nasync function tryFileSystem<T>(\n operation: () => Promise<T>,\n target: string,\n context: ScanContext\n): Promise<T | undefined> {\n try {\n return await operation();\n } catch (error) {\n context.errors.push(`${formatPath(target, context.rootDirectory)}: ${formatError(error)}`);\n return undefined;\n }\n}\n\n/** Resolves the path (recording errors); undefined when that fails or the result escapes the root. */\nasync function resolveWithinRoot(target: string, context: ScanContext): Promise<string | undefined> {\n const resolved = await tryFileSystem(() => realpath(target), target, context);\n return resolved !== undefined && isWithinDirectory(resolved, context.rootDirectory) ? resolved : undefined;\n}\n\nasync function scanDirectory(directory: string, context: ScanContext): Promise<void> {\n const resolvedDirectory = await resolveWithinRoot(directory, context);\n if (resolvedDirectory === undefined || context.visitedDirectories.has(resolvedDirectory)) {\n return;\n }\n context.visitedDirectories.add(resolvedDirectory);\n\n const entries = await tryFileSystem(() => readdir(directory, { withFileTypes: true }), directory, context);\n if (entries === undefined) {\n return;\n }\n\n for (const entry of entries) {\n const entryPath = path.join(directory, entry.name);\n if (entry.isSymbolicLink()) {\n await scanSymbolicLink(entry.name, entryPath, context);\n continue;\n }\n\n if (entry.isDirectory()) {\n if (shouldSkipDirectory(entry.name, context.options)) {\n continue;\n }\n await scanDirectory(entryPath, context);\n continue;\n }\n\n if (entry.isFile()) {\n await measureScannableFile(entryPath, context);\n }\n }\n}\n\nasync function scanSymbolicLink(name: string, entryPath: string, context: ScanContext): Promise<void> {\n const resolvedPath = await resolveWithinRoot(entryPath, context);\n if (resolvedPath === undefined) {\n return;\n }\n\n const entryStat = await tryFileSystem(() => stat(entryPath), entryPath, context);\n if (entryStat === undefined) {\n return;\n }\n\n if (entryStat.isDirectory()) {\n if (\n shouldSkipDirectory(name, context.options) ||\n shouldSkipDirectory(path.basename(resolvedPath), context.options)\n ) {\n return;\n }\n await scanDirectory(entryPath, context);\n return;\n }\n\n if (entryStat.isFile()) {\n await measureScannableFile(entryPath, context, resolvedPath, resolvedPath);\n }\n}\n\nasync function measureScannableFile(\n file: string,\n context: ScanContext,\n languageFile = file,\n realFile?: string\n): Promise<void> {\n const language = getLanguage(languageFile, context.options);\n if (language) {\n await measureFile(file, language, 'directory', context, realFile);\n }\n}\n\nasync function measureFile(\n file: string,\n language: LanguageName,\n mode: 'single-file' | 'directory',\n context: ScanContext,\n realFile?: string\n): Promise<void> {\n try {\n const resolvedFile = realFile ?? (await realpath(file));\n if (context.visitedFiles.has(resolvedFile)) {\n return;\n }\n context.visitedFiles.add(resolvedFile);\n\n const code = await readFile(file, 'utf8');\n const measureOptions = { language, duplication: context.options.duplication };\n const fileMetrics: FileMetrics = { file, metrics: measureCode(code, measureOptions) };\n // Only directory scans compare files against each other; a single-file target has no peers.\n // Candidate collection is an auxiliary pass: if it fails where measureCode succeeded (an\n // addon error specific to this pass), that must not discard the measured metrics.\n if (mode === 'directory') {\n try {\n fileMetrics.duplicationCandidates = collectCrossFileDuplicationFileData(code, measureOptions);\n } catch (error) {\n // A warning, not an error: the file's metrics are complete, only its participation in\n // cross-file matching is lost, so it is not \"skipped\" and must not fail --fail-on-error.\n context.warnings.push(\n `${formatPath(file, context.rootDirectory)}: cross-file duplication candidates unavailable: ${formatError(error)}`\n );\n }\n }\n context.files.push(fileMetrics);\n } catch (error) {\n // A missing native addon fails every file identically: propagate it once as a fatal scan\n // error instead of recording one \"skipped\" entry per file behind a successful exit code.\n if (error instanceof NativeAddonError) {\n throw error;\n }\n context.errors.push(`${formatPath(file, context.rootDirectory)}: ${formatError(error)}`);\n }\n}\n\n/** Runs after the scan so every measured file's candidates participate. */\nexport function addCrossFileDuplication(result: ScanResult, options: ScanOptions): void {\n if (result.fatalError || result.files.length < 2) {\n return;\n }\n const sourceFiles = result.files.flatMap(({ file, duplicationCandidates }) =>\n duplicationCandidates ? [{ file: formatPath(file, result.displayRoot), ...duplicationCandidates }] : []\n );\n if (sourceFiles.length < 2) {\n return;\n }\n result.crossFileDuplication = measureCrossFileDuplication(sourceFiles, options.duplication);\n}\n\n/**\n * Distinct 1-based code lines covered by within-file or cross-file duplicated content. Both\n * sources expose the exact lines carrying matched tokens (never block bounding ranges, which\n * would over-count comment/blank lines and the unmatched gap of a merged clone), so the union is\n * a subset of the file's code lines and a ratio derived over code lines can never exceed 1.\n */\nexport function collectDuplicatedLineNumbers(\n metrics: CodeMetrics | undefined,\n crossFileDuplication: CrossFileDuplicationMetrics | undefined,\n formattedFile: string\n): Set<number> {\n const lines = new Set(metrics?.duplication.duplicateLineNumbers);\n // Object.hasOwn: a file named like an Object.prototype member must not read an inherited value.\n const crossFileLines =\n crossFileDuplication && Object.hasOwn(crossFileDuplication.duplicateLineNumbersByFile, formattedFile)\n ? (crossFileDuplication.duplicateLineNumbersByFile[formattedFile] ?? [])\n : [];\n for (const line of crossFileLines) {\n lines.add(line);\n }\n return lines;\n}\n\nfunction shouldSkipDirectory(name: string, options: ScanOptions): boolean {\n if (ignoredDirectoryNames.has(name)) {\n return true;\n }\n\n if (options.includeTests) {\n return false;\n }\n\n return testDirectoryNames.has(name);\n}\n\nfunction isWithinDirectory(candidate: string, directory: string): boolean {\n const relative = path.relative(directory, candidate);\n return relative === '' || (relative !== '..' && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative));\n}\n\n/**\n * Whether a repository-relative path would be scanned: no ignored or excluded-test directory\n * segment and a supported, non-test file name. The diff gate uses this for base-revision\n * eligibility, so code renamed into scan scope gates as new code instead of ratcheting against\n * a blob the scanner would never have measured.\n */\nexport function isScannedPath(relativePath: string, options: ScanOptions): boolean {\n const segments = relativePath.split('/');\n for (const segment of segments.slice(0, -1)) {\n if (ignoredDirectoryNames.has(segment) || (!options.includeTests && testDirectoryNames.has(segment))) {\n return false;\n }\n }\n return getLanguage(relativePath, options) !== undefined;\n}\n\nexport function getLanguage(file: string, options: ScanOptions, explicitTarget = false): LanguageName | undefined {\n const lowerFile = file.toLowerCase();\n if (\n !explicitTarget &&\n (lowerFile.endsWith('.d.ts') ||\n lowerFile.endsWith('.d.mts') ||\n lowerFile.endsWith('.d.cts') ||\n lowerFile.endsWith('.min.js') ||\n lowerFile.endsWith('.pnp.cjs'))\n ) {\n return undefined;\n }\n\n if (\n !explicitTarget &&\n !options.includeTests &&\n (testFilePattern.test(path.basename(file)) || javaTestFilePattern.test(path.basename(file)))\n ) {\n return undefined;\n }\n\n // GCC treats an uppercase `.C` as C++; lowercasing first would misparse it with the C grammar.\n if (path.extname(file) === '.C') {\n return 'cpp';\n }\n\n return languageByExtension.get(path.extname(lowerFile));\n}\n\nexport function formatPath(file: string, base: string): string {\n return path.relative(base, file) || path.basename(file);\n}\n\nexport function writeStdout(message: string): void {\n process.stdout.write(message);\n}\n\nexport function writeStderr(message: string): void {\n process.stderr.write(message);\n}\n\nexport function formatError(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n"],"mappings":"yRAgCA,MAAM,EAAsB,IAAI,IAA0B,CACxD,CAAC,KAAM,GAAG,EACV,CAAC,OAAQ,KAAK,EACd,CAAC,MAAO,KAAK,EACb,CAAC,OAAQ,YAAY,EACrB,CAAC,MAAO,KAAK,EACb,CAAC,OAAQ,KAAK,EACd,CAAC,OA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AEA,SAAgB,EAAY,EAAuB,CACjD,QAAQ,OAAO,MAAM,CAAO,CAC9B,CAEA,SAAgB,EAAY,EAAuB,CACjD,QAAQ,OAAO,MAAM,CAAO,CAC9B,CAEA,SAAgB,EAAY,EAAwB,CAClD,OAAO,aAAiB,MAAQ,EAAM,QAAU,OAAO,CAAK,CAC9D"}
1
+ {"version":3,"file":"scan.cjs","names":["os","path","stat","realpath","lstat","NativeAddonError","readdir","readFile","measureCode","collectCrossFileDuplicationFileData","measureCrossFileDuplication"],"sources":["../src/scan.ts"],"sourcesContent":["import { lstat, readdir, readFile, realpath, stat } from 'node:fs/promises';\nimport os from 'node:os';\nimport path from 'node:path';\nimport { measureCrossFileDuplication, type CrossFileDuplicationMetrics } from './crossFileDuplication.js';\nimport type { CrossFileDuplicationFileData } from './duplication.js';\nimport { collectCrossFileDuplicationFileData, measureCode } from './metrics.js';\nimport { NativeAddonError } from './nativeMetrics.js';\nimport type { CodeMetrics, DuplicationOptions, LanguageName } from './types.js';\n\n/** The scan settings shared by every command (a structural subset of each command's options). */\nexport interface ScanOptions {\n duplication: Required<DuplicationOptions>;\n includeTests: boolean;\n}\n\nexport interface FileMetrics {\n file: string;\n metrics: CodeMetrics;\n /** Cross-file duplicate candidates and token/statement data, collected only for directory scans. */\n duplicationCandidates?: CrossFileDuplicationFileData;\n}\n\nexport interface ScanResult {\n crossFileDuplication?: CrossFileDuplicationMetrics;\n displayRoot: string;\n errors: string[];\n /** Non-fatal degradations (e.g. cross-file candidates unavailable); the file is still measured. */\n warnings: string[];\n fatalError?: string;\n files: FileMetrics[];\n}\n\nconst languageByExtension = new Map<string, LanguageName>([\n ['.c', 'c'],\n ['.c++', 'cpp'],\n ['.cc', 'cpp'],\n ['.cjs', 'javascript'],\n ['.cp', 'cpp'],\n ['.cpp', 'cpp'],\n ['.cs', 'csharp'],\n ['.tcc', 'cpp'],\n ['.cts', 'typescript'],\n ['.cxx', 'cpp'],\n ['.go', 'go'],\n // Headers may be C or C++; the C++ grammar parses both.\n ['.h', 'cpp'],\n ['.hh', 'cpp'],\n ['.hpp', 'cpp'],\n ['.hxx', 'cpp'],\n ['.java', 'java'],\n ['.js', 'javascript'],\n ['.jsx', 'jsx'],\n ['.kt', 'kotlin'],\n ['.kts', 'kotlin'],\n ['.mjs', 'javascript'],\n ['.mts', 'typescript'],\n ['.py', 'python'],\n ['.rb', 'ruby'],\n ['.rs', 'rust'],\n ['.ts', 'typescript'],\n ['.tsx', 'tsx'],\n]);\n\nconst ignoredDirectoryNames = new Set([\n '.agents',\n '.claude',\n '.cursor',\n '.git',\n '.next',\n '.playwright-cli',\n '.tox',\n '.tmp',\n '.turbo',\n '.venv',\n '.yarn',\n '__fixtures__',\n '__generated__',\n '__pycache__',\n 'coverage',\n 'dist',\n 'fixtures',\n 'generated',\n 'node_modules',\n // .NET SDK intermediate output (generated sources such as `*.GlobalUsings.g.cs`).\n 'obj',\n 'target',\n 'test-fixtures',\n 'vendor',\n 'venv',\n]);\n\nconst testDirectoryNames = new Set(['__tests__', 'test', 'tests', 'spec']);\nconst testFilePattern = /(?:^test(?:[_-].*)?|\\.(?:spec|test)|[_-](?:test|spec))\\.[^.]+$/iu;\n// JUnit (Java/Kotlin) and xUnit/NUnit (C#) tests use case-sensitive `Test`/`Tests` class-name\n// suffixes; case-insensitive matching would catch production files like `contest.java`.\nconst suffixTestFilePattern = /Tests?\\.(?:java|kt|cs)$/u;\n\nexport function resolveTarget(target: string): string {\n if (target === '~') {\n return os.homedir();\n }\n\n if (target.startsWith('~/')) {\n return path.join(os.homedir(), target.slice(2));\n }\n\n return path.resolve(target);\n}\n\n/** Returns the directory from which the config file search should start (the target itself if it is a directory). */\nexport async function configSearchDirectory(target: string): Promise<string> {\n try {\n const targetStat = await stat(target);\n return targetStat.isDirectory() ? target : path.dirname(target);\n } catch {\n return path.dirname(target);\n }\n}\n\n/** Shared state of one scan, threaded through the directory walk instead of positional plumbing. */\ninterface ScanContext {\n options: ScanOptions;\n files: FileMetrics[];\n errors: string[];\n warnings: string[];\n visitedDirectories: Set<string>;\n visitedFiles: Set<string>;\n /** Scan root: paths are displayed relative to it, and symbolic links may not escape it. */\n rootDirectory: string;\n}\n\nexport async function scanTarget(target: string, options: ScanOptions): Promise<ScanResult> {\n const files: FileMetrics[] = [];\n const errors: string[] = [];\n const warnings: string[] = [];\n let canonicalTarget = target;\n try {\n canonicalTarget = await realpath(target);\n } catch {\n // stat below reports missing targets with the original path.\n }\n\n const fallbackDisplayRoot = path.dirname(canonicalTarget);\n let targetStat;\n\n try {\n targetStat = await stat(canonicalTarget);\n } catch (error) {\n const fatalError = `${formatPath(canonicalTarget, fallbackDisplayRoot)}: ${formatError(error)}`;\n return { displayRoot: fallbackDisplayRoot, files, errors: [fatalError], warnings, fatalError };\n }\n\n if (targetStat.isFile()) {\n const displayRoot = path.dirname(canonicalTarget);\n const language = getLanguage(canonicalTarget, options, true);\n if (!language) {\n const fatalError = `${formatPath(canonicalTarget, displayRoot)}: unsupported file type`;\n return { displayRoot, files, errors: [fatalError], warnings, fatalError };\n }\n\n const context = makeScanContext(options, files, errors, warnings, displayRoot);\n try {\n await measureFile(canonicalTarget, language, 'single-file', context, canonicalTarget);\n } catch (error) {\n return toFatalResult(error, displayRoot, files, errors, warnings);\n }\n return { displayRoot, files, errors, warnings };\n }\n\n try {\n await scanDirectory(canonicalTarget, makeScanContext(options, files, errors, warnings, canonicalTarget));\n } catch (error) {\n return toFatalResult(error, canonicalTarget, files, errors, warnings);\n }\n return { displayRoot: canonicalTarget, files, errors, warnings };\n}\n\n/**\n * Measures an explicit list of repository-relative files (the diff gate's git-visible allowlist)\n * instead of walking the directory tree, so ignored artifact directories are never parsed. Paths\n * outside the scan scope (ignored/test directories, unsupported or test file names) are skipped\n * with the same rules as the walk.\n */\nexport async function scanListedFiles(\n rootDirectory: string,\n relativePaths: Iterable<string>,\n options: ScanOptions\n): Promise<ScanResult> {\n const files: FileMetrics[] = [];\n const errors: string[] = [];\n const warnings: string[] = [];\n const context = makeScanContext(options, files, errors, warnings, rootDirectory);\n for (const relativePath of relativePaths) {\n const language = isScannedPath(relativePath, options) ? getLanguage(relativePath, options) : undefined;\n if (!language) {\n continue;\n }\n const absolutePath = path.join(rootDirectory, relativePath);\n // Symbolic links are not source files: git stores only their target string, so measuring\n // through them would diverge from what any revision of the repository actually contains.\n const stats = await lstat(absolutePath).catch(() => {});\n if (stats?.isSymbolicLink()) {\n continue;\n }\n try {\n await measureFile(absolutePath, language, 'directory', context);\n } catch (error) {\n return toFatalResult(error, rootDirectory, files, errors, warnings);\n }\n }\n return { displayRoot: rootDirectory, files, errors, warnings };\n}\n\n/** A run-wide failure (a missing native addon) as a fatal result; anything else keeps throwing. */\nfunction toFatalResult(\n error: unknown,\n displayRoot: string,\n files: FileMetrics[],\n errors: string[],\n warnings: string[]\n): ScanResult {\n if (!(error instanceof NativeAddonError)) {\n throw error;\n }\n const fatalError = formatError(error);\n // Errors the walk accumulated before the fatal failure stay reported alongside it.\n return { displayRoot, files, errors: [...errors, fatalError], warnings, fatalError };\n}\n\nfunction makeScanContext(\n options: ScanOptions,\n files: FileMetrics[],\n errors: string[],\n warnings: string[],\n rootDirectory: string\n): ScanContext {\n return { options, files, errors, warnings, visitedDirectories: new Set(), visitedFiles: new Set(), rootDirectory };\n}\n\n/** Runs a filesystem operation, recording a scan error and returning undefined when it fails. */\nasync function tryFileSystem<T>(\n operation: () => Promise<T>,\n target: string,\n context: ScanContext\n): Promise<T | undefined> {\n try {\n return await operation();\n } catch (error) {\n context.errors.push(`${formatPath(target, context.rootDirectory)}: ${formatError(error)}`);\n return undefined;\n }\n}\n\n/** Resolves the path (recording errors); undefined when that fails or the result escapes the root. */\nasync function resolveWithinRoot(target: string, context: ScanContext): Promise<string | undefined> {\n const resolved = await tryFileSystem(() => realpath(target), target, context);\n return resolved !== undefined && isWithinDirectory(resolved, context.rootDirectory) ? resolved : undefined;\n}\n\nasync function scanDirectory(directory: string, context: ScanContext): Promise<void> {\n const resolvedDirectory = await resolveWithinRoot(directory, context);\n if (resolvedDirectory === undefined || context.visitedDirectories.has(resolvedDirectory)) {\n return;\n }\n context.visitedDirectories.add(resolvedDirectory);\n\n const entries = await tryFileSystem(() => readdir(directory, { withFileTypes: true }), directory, context);\n if (entries === undefined) {\n return;\n }\n\n for (const entry of entries) {\n const entryPath = path.join(directory, entry.name);\n if (entry.isSymbolicLink()) {\n await scanSymbolicLink(entry.name, entryPath, context);\n continue;\n }\n\n if (entry.isDirectory()) {\n if (shouldSkipDirectory(entry.name, context.options)) {\n continue;\n }\n await scanDirectory(entryPath, context);\n continue;\n }\n\n if (entry.isFile()) {\n await measureScannableFile(entryPath, context);\n }\n }\n}\n\nasync function scanSymbolicLink(name: string, entryPath: string, context: ScanContext): Promise<void> {\n const resolvedPath = await resolveWithinRoot(entryPath, context);\n if (resolvedPath === undefined) {\n return;\n }\n\n const entryStat = await tryFileSystem(() => stat(entryPath), entryPath, context);\n if (entryStat === undefined) {\n return;\n }\n\n if (entryStat.isDirectory()) {\n if (\n shouldSkipDirectory(name, context.options) ||\n shouldSkipDirectory(path.basename(resolvedPath), context.options)\n ) {\n return;\n }\n await scanDirectory(entryPath, context);\n return;\n }\n\n if (entryStat.isFile()) {\n await measureScannableFile(entryPath, context, resolvedPath, resolvedPath);\n }\n}\n\nasync function measureScannableFile(\n file: string,\n context: ScanContext,\n languageFile = file,\n realFile?: string\n): Promise<void> {\n const language = getLanguage(languageFile, context.options);\n if (language) {\n await measureFile(file, language, 'directory', context, realFile);\n }\n}\n\nasync function measureFile(\n file: string,\n language: LanguageName,\n mode: 'single-file' | 'directory',\n context: ScanContext,\n realFile?: string\n): Promise<void> {\n try {\n const resolvedFile = realFile ?? (await realpath(file));\n if (context.visitedFiles.has(resolvedFile)) {\n return;\n }\n context.visitedFiles.add(resolvedFile);\n\n const code = await readFile(file, 'utf8');\n const measureOptions = { language, duplication: context.options.duplication };\n const fileMetrics: FileMetrics = { file, metrics: measureCode(code, measureOptions) };\n // Only directory scans compare files against each other; a single-file target has no peers.\n // Candidate collection is an auxiliary pass: if it fails where measureCode succeeded (an\n // addon error specific to this pass), that must not discard the measured metrics.\n if (mode === 'directory') {\n try {\n fileMetrics.duplicationCandidates = collectCrossFileDuplicationFileData(code, measureOptions);\n } catch (error) {\n // A warning, not an error: the file's metrics are complete, only its participation in\n // cross-file matching is lost, so it is not \"skipped\" and must not fail --fail-on-error.\n context.warnings.push(\n `${formatPath(file, context.rootDirectory)}: cross-file duplication candidates unavailable: ${formatError(error)}`\n );\n }\n }\n context.files.push(fileMetrics);\n } catch (error) {\n // A missing native addon fails every file identically: propagate it once as a fatal scan\n // error instead of recording one \"skipped\" entry per file behind a successful exit code.\n if (error instanceof NativeAddonError) {\n throw error;\n }\n context.errors.push(`${formatPath(file, context.rootDirectory)}: ${formatError(error)}`);\n }\n}\n\n/** Runs after the scan so every measured file's candidates participate. */\nexport function addCrossFileDuplication(result: ScanResult, options: ScanOptions): void {\n if (result.fatalError || result.files.length < 2) {\n return;\n }\n const sourceFiles = result.files.flatMap(({ file, duplicationCandidates }) =>\n duplicationCandidates ? [{ file: formatPath(file, result.displayRoot), ...duplicationCandidates }] : []\n );\n if (sourceFiles.length < 2) {\n return;\n }\n result.crossFileDuplication = measureCrossFileDuplication(sourceFiles, options.duplication);\n}\n\n/**\n * Distinct 1-based code lines covered by within-file or cross-file duplicated content. Both\n * sources expose the exact lines carrying matched tokens (never block bounding ranges, which\n * would over-count comment/blank lines and the unmatched gap of a merged clone), so the union is\n * a subset of the file's code lines and a ratio derived over code lines can never exceed 1.\n */\nexport function collectDuplicatedLineNumbers(\n metrics: CodeMetrics | undefined,\n crossFileDuplication: CrossFileDuplicationMetrics | undefined,\n formattedFile: string\n): Set<number> {\n const lines = new Set(metrics?.duplication.duplicateLineNumbers);\n // Object.hasOwn: a file named like an Object.prototype member must not read an inherited value.\n const crossFileLines =\n crossFileDuplication && Object.hasOwn(crossFileDuplication.duplicateLineNumbersByFile, formattedFile)\n ? (crossFileDuplication.duplicateLineNumbersByFile[formattedFile] ?? [])\n : [];\n for (const line of crossFileLines) {\n lines.add(line);\n }\n return lines;\n}\n\nfunction shouldSkipDirectory(name: string, options: ScanOptions): boolean {\n if (ignoredDirectoryNames.has(name)) {\n return true;\n }\n\n if (options.includeTests) {\n return false;\n }\n\n return testDirectoryNames.has(name);\n}\n\nfunction isWithinDirectory(candidate: string, directory: string): boolean {\n const relative = path.relative(directory, candidate);\n return relative === '' || (relative !== '..' && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative));\n}\n\n/**\n * Whether a repository-relative path would be scanned: no ignored or excluded-test directory\n * segment and a supported, non-test file name. The diff gate uses this for base-revision\n * eligibility, so code renamed into scan scope gates as new code instead of ratcheting against\n * a blob the scanner would never have measured.\n */\nexport function isScannedPath(relativePath: string, options: ScanOptions): boolean {\n const segments = relativePath.split('/');\n for (const segment of segments.slice(0, -1)) {\n if (ignoredDirectoryNames.has(segment) || (!options.includeTests && testDirectoryNames.has(segment))) {\n return false;\n }\n }\n return getLanguage(relativePath, options) !== undefined;\n}\n\nexport function getLanguage(file: string, options: ScanOptions, explicitTarget = false): LanguageName | undefined {\n const lowerFile = file.toLowerCase();\n if (\n !explicitTarget &&\n (lowerFile.endsWith('.d.ts') ||\n lowerFile.endsWith('.d.mts') ||\n lowerFile.endsWith('.d.cts') ||\n lowerFile.endsWith('.min.js') ||\n lowerFile.endsWith('.pnp.cjs'))\n ) {\n return undefined;\n }\n\n if (\n !explicitTarget &&\n !options.includeTests &&\n (testFilePattern.test(path.basename(file)) || suffixTestFilePattern.test(path.basename(file)))\n ) {\n return undefined;\n }\n\n // GCC treats an uppercase `.C` as C++; lowercasing first would misparse it with the C grammar.\n if (path.extname(file) === '.C') {\n return 'cpp';\n }\n\n return languageByExtension.get(path.extname(lowerFile));\n}\n\nexport function formatPath(file: string, base: string): string {\n return path.relative(base, file) || path.basename(file);\n}\n\nexport function writeStdout(message: string): void {\n process.stdout.write(message);\n}\n\nexport function writeStderr(message: string): void {\n process.stderr.write(message);\n}\n\nexport function formatError(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n"],"mappings":"yRAgCA,MAAM,EAAsB,IAAI,IAA0B,CACxD,CAAC,KAAM,GAAG,EACV,CAAC,OAAQ,KAAK,EACd,CAAC,MAAO,KAAK,EACb,CAAC,OAAQ,YAAY,EACrB,CAAC,MAAO,KAAK,EACb,CAAC,OAAQ,KAAK,EACd,CAAC,MAAO,QAAQ,EAChB,CAAC,OAAQ,KAAK,EACd,CAAC,OAAQ,YAAY,EACrB,CAAC,OAAQ,KAAK,EACd,CAAC,MAAO,IAAI,EAEZ,CAAC,KAAM,KAAK,EACZ,CAAC,MAAO,KAAK,EACb,CAAC,OAAQ,KAAK,EACd,CAAC,OAAQ,KAAK,EACd,CAAC,QAAS,MAAM,EAChB,CAAC,MAAO,YAAY,EACpB,CAAC,OAAQ,KAAK,EACd,CAAC,MAAO,QAAQ,EAChB,CAAC,OAAQ,QAAQ,EACjB,CAAC,OAAQ,YAAY,EACrB,CAAC,OAAQ,YAAY,EACrB,CAAC,MAAO,QAAQ,EAChB,CAAC,MAAO,MAAM,EACd,CAAC,MAAO,MAAM,EACd,CAAC,MAAO,YAAY,EACpB,CAAC,OAAQ,KAAK,CAChB,CAAC,EAEK,EAAwB,IAAI,IAAI,CACpC,UACA,UACA,UACA,OACA,QACA,kBACA,OACA,OACA,SACA,QACA,QACA,eACA,gBACA,cACA,WACA,OACA,WACA,YACA,eAEA,MACA,SACA,gBACA,SACA,MACF,CAAC,EAEK,EAAqB,IAAI,IAAI,CAAC,YAAa,OAAQ,QAAS,MAAM,CAAC,EACnE,EAAkB,mEAGlB,EAAwB,2BAE9B,SAAgB,EAAc,EAAwB,CASpD,OARI,IAAW,IACNA,EAAAA,QAAG,QAAQ,EAGhB,EAAO,WAAW,IAAI,EACjBC,EAAAA,QAAK,KAAKD,EAAAA,QAAG,QAAQ,EAAG,EAAO,MAAM,CAAC,CAAC,EAGzCC,EAAAA,QAAK,QAA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AAC,GACD,CAAC,EAAQ,eACR,EAAgB,KAAKA,EAAAA,QAAK,SAAS,CAAI,CAAC,GAAK,EAAsB,KAAKA,EAAAA,QAAK,SAAS,CAAI,CAAC,IAU9F,OAJIA,EAAAA,QAAK,QAAQ,CAAI,IAAM,KAClB,MAGF,EAAoB,IAAIA,EAAAA,QAAK,QAAQ,CAAS,CAAC,CACxD,CAEA,SAAgB,EAAW,EAAc,EAAsB,CAC7D,OAAOA,EAAAA,QAAK,SAAS,EAAM,CAAI,GAAKA,EAAAA,QAAK,SAAS,CAAI,CACxD,CAEA,SAAgB,EAAY,EAAuB,CACjD,QAAQ,OAAO,MAAM,CAAO,CAC9B,CAEA,SAAgB,EAAY,EAAuB,CACjD,QAAQ,OAAO,MAAM,CAAO,CAC9B,CAEA,SAAgB,EAAY,EAAwB,CAClD,OAAO,aAAiB,MAAQ,EAAM,QAAU,OAAO,CAAK,CAC9D"}
package/dist/scan.js CHANGED
@@ -1,2 +1,2 @@
1
- import{measureCrossFileDuplication as e}from"./crossFileDuplication.js";import{NativeAddonError as t}from"./nativeMetrics.js";import{collectCrossFileDuplicationFileData as n,measureCode as r}from"./metrics.js";import{lstat as i,readFile as a,readdir as o,realpath as s,stat as c}from"node:fs/promises";import l from"node:path";import u from"node:os";const d=new Map([[`.c`,`c`],[`.c++`,`cpp`],[`.cc`,`cpp`],[`.cjs`,`javascript`],[`.cp`,`cpp`],[`.cpp`,`cpp`],[`.tcc`,`cpp`],[`.cts`,`typescript`],[`.cxx`,`cpp`],[`.go`,`go`],[`.h`,`cpp`],[`.hh`,`cpp`],[`.hpp`,`cpp`],[`.hxx`,`cpp`],[`.java`,`java`],[`.js`,`javascript`],[`.jsx`,`jsx`],[`.mjs`,`javascript`],[`.mts`,`typescript`],[`.py`,`python`],[`.rb`,`ruby`],[`.rs`,`rust`],[`.ts`,`typescript`],[`.tsx`,`tsx`]]),f=new Set([`.agents`,`.claude`,`.cursor`,`.git`,`.next`,`.playwright-cli`,`.tox`,`.tmp`,`.turbo`,`.venv`,`.yarn`,`__fixtures__`,`__generated__`,`__pycache__`,`coverage`,`dist`,`fixtures`,`generated`,`node_modules`,`target`,`test-fixtures`,`vendor`,`venv`]),p=new Set([`__tests__`,`test`,`tests`,`spec`]),m=/(?:^test(?:[_-].*)?|\.(?:spec|test)|[_-](?:test|spec))\.[^.]+$/iu,h=/Test\.java$/u;function g(e){return e===`~`?u.homedir():e.startsWith(`~/`)?l.join(u.homedir(),e.slice(2)):l.resolve(e)}async function _(e){try{return(await c(e)).isDirectory()?e:l.dirname(e)}catch{return l.dirname(e)}}async function v(e,t){let n=[],r=[],i=[],a=e;try{a=await s(e)}catch{}let o=l.dirname(a),u;try{u=await c(a)}catch(e){let t=`${P(a,o)}: ${L(e)}`;return{displayRoot:o,files:n,errors:[t],warnings:i,fatalError:t}}if(u.isFile()){let e=l.dirname(a),o=N(a,t,!0);if(!o){let t=`${P(a,e)}: unsupported file type`;return{displayRoot:e,files:n,errors:[t],warnings:i,fatalError:t}}let s=x(t,n,r,i,e);try{await D(a,o,`single-file`,s,a)}catch(t){return b(t,e,n,r,i)}return{displayRoot:e,files:n,errors:r,warnings:i}}try{await w(a,x(t,n,r,i,a))}catch(e){return b(e,a,n,r,i)}return{displayRoot:a,files:n,errors:r,warnings:i}}async function y(e,t,n){let r=[],a=[],o=[],s=x(n,r,a,o,e);for(let c of t){let t=M(c,n)?N(c,n):void 0;if(!t)continue;let u=l.join(e,c);if(!(await i(u).catch(()=>{}))?.isSymbolicLink())try{await D(u,t,`directory`,s)}catch(t){return b(t,e,r,a,o)}}return{displayRoot:e,files:r,errors:a,warnings:o}}function b(e,n,r,i,a){if(!(e instanceof t))throw e;let o=L(e);return{displayRoot:n,files:r,errors:[...i,o],warnings:a,fatalError:o}}function x(e,t,n,r,i){return{options:e,files:t,errors:n,warnings:r,visitedDirectories:new Set,visitedFiles:new Set,rootDirectory:i}}async function S(e,t,n){try{return await e()}catch(e){n.errors.push(`${P(t,n.rootDirectory)}: ${L(e)}`);return}}async function C(e,t){let n=await S(()=>s(e),e,t);return n!==void 0&&j(n,t.rootDirectory)?n:void 0}async function w(e,t){let n=await C(e,t);if(n===void 0||t.visitedDirectories.has(n))return;t.visitedDirectories.add(n);let r=await S(()=>o(e,{withFileTypes:!0}),e,t);if(r!==void 0)for(let n of r){let r=l.join(e,n.name);if(n.isSymbolicLink()){await T(n.name,r,t);continue}if(n.isDirectory()){if(A(n.name,t.options))continue;await w(r,t);continue}n.isFile()&&await E(r,t)}}async function T(e,t,n){let r=await C(t,n);if(r===void 0)return;let i=await S(()=>c(t),t,n);if(i!==void 0){if(i.isDirectory()){if(A(e,n.options)||A(l.basename(r),n.options))return;await w(t,n);return}i.isFile()&&await E(t,n,r,r)}}async function E(e,t,n=e,r){let i=N(n,t.options);i&&await D(e,i,`directory`,t,r)}async function D(e,i,o,c,l){try{let t=l??await s(e);if(c.visitedFiles.has(t))return;c.visitedFiles.add(t);let u=await a(e,`utf8`),d={language:i,duplication:c.options.duplication},f={file:e,metrics:r(u,d)};if(o===`directory`)try{f.duplicationCandidates=n(u,d)}catch(t){c.warnings.push(`${P(e,c.rootDirectory)}: cross-file duplication candidates unavailable: ${L(t)}`)}c.files.push(f)}catch(n){if(n instanceof t)throw n;c.errors.push(`${P(e,c.rootDirectory)}: ${L(n)}`)}}function O(t,n){if(t.fatalError||t.files.length<2)return;let r=t.files.flatMap(({file:e,duplicationCandidates:n})=>n?[{file:P(e,t.displayRoot),...n}]:[]);r.length<2||(t.crossFileDuplication=e(r,n.duplication))}function k(e,t,n){let r=new Set(e?.duplication.duplicateLineNumbers),i=t&&Object.hasOwn(t.duplicateLineNumbersByFile,n)?t.duplicateLineNumbersByFile[n]??[]:[];for(let e of i)r.add(e);return r}function A(e,t){return f.has(e)?!0:!t.includeTests&&p.has(e)}function j(e,t){let n=l.relative(t,e);return n===``||n!==`..`&&!n.startsWith(`..${l.sep}`)&&!l.isAbsolute(n)}function M(e,t){let n=e.split(`/`);for(let e of n.slice(0,-1))if(f.has(e)||!t.includeTests&&p.has(e))return!1;return N(e,t)!==void 0}function N(e,t,n=!1){let r=e.toLowerCase();if(!(!n&&(r.endsWith(`.d.ts`)||r.endsWith(`.d.mts`)||r.endsWith(`.d.cts`)||r.endsWith(`.min.js`)||r.endsWith(`.pnp.cjs`)))&&!(!n&&!t.includeTests&&(m.test(l.basename(e))||h.test(l.basename(e)))))return l.extname(e)===`.C`?`cpp`:d.get(l.extname(r))}function P(e,t){return l.relative(t,e)||l.basename(e)}function F(e){process.stdout.write(e)}function I(e){process.stderr.write(e)}function L(e){return e instanceof Error?e.message:String(e)}export{O as addCrossFileDuplication,k as collectDuplicatedLineNumbers,_ as configSearchDirectory,L as formatError,P as formatPath,N as getLanguage,M as isScannedPath,g as resolveTarget,y as scanListedFiles,v as scanTarget,I as writeStderr,F as writeStdout};
1
+ import{measureCrossFileDuplication as e}from"./crossFileDuplication.js";import{NativeAddonError as t}from"./nativeMetrics.js";import{collectCrossFileDuplicationFileData as n,measureCode as r}from"./metrics.js";import{lstat as i,readFile as a,readdir as o,realpath as s,stat as c}from"node:fs/promises";import l from"node:path";import u from"node:os";const d=new Map([[`.c`,`c`],[`.c++`,`cpp`],[`.cc`,`cpp`],[`.cjs`,`javascript`],[`.cp`,`cpp`],[`.cpp`,`cpp`],[`.cs`,`csharp`],[`.tcc`,`cpp`],[`.cts`,`typescript`],[`.cxx`,`cpp`],[`.go`,`go`],[`.h`,`cpp`],[`.hh`,`cpp`],[`.hpp`,`cpp`],[`.hxx`,`cpp`],[`.java`,`java`],[`.js`,`javascript`],[`.jsx`,`jsx`],[`.kt`,`kotlin`],[`.kts`,`kotlin`],[`.mjs`,`javascript`],[`.mts`,`typescript`],[`.py`,`python`],[`.rb`,`ruby`],[`.rs`,`rust`],[`.ts`,`typescript`],[`.tsx`,`tsx`]]),f=new Set([`.agents`,`.claude`,`.cursor`,`.git`,`.next`,`.playwright-cli`,`.tox`,`.tmp`,`.turbo`,`.venv`,`.yarn`,`__fixtures__`,`__generated__`,`__pycache__`,`coverage`,`dist`,`fixtures`,`generated`,`node_modules`,`obj`,`target`,`test-fixtures`,`vendor`,`venv`]),p=new Set([`__tests__`,`test`,`tests`,`spec`]),m=/(?:^test(?:[_-].*)?|\.(?:spec|test)|[_-](?:test|spec))\.[^.]+$/iu,h=/Tests?\.(?:java|kt|cs)$/u;function g(e){return e===`~`?u.homedir():e.startsWith(`~/`)?l.join(u.homedir(),e.slice(2)):l.resolve(e)}async function _(e){try{return(await c(e)).isDirectory()?e:l.dirname(e)}catch{return l.dirname(e)}}async function v(e,t){let n=[],r=[],i=[],a=e;try{a=await s(e)}catch{}let o=l.dirname(a),u;try{u=await c(a)}catch(e){let t=`${P(a,o)}: ${L(e)}`;return{displayRoot:o,files:n,errors:[t],warnings:i,fatalError:t}}if(u.isFile()){let e=l.dirname(a),o=N(a,t,!0);if(!o){let t=`${P(a,e)}: unsupported file type`;return{displayRoot:e,files:n,errors:[t],warnings:i,fatalError:t}}let s=x(t,n,r,i,e);try{await D(a,o,`single-file`,s,a)}catch(t){return b(t,e,n,r,i)}return{displayRoot:e,files:n,errors:r,warnings:i}}try{await w(a,x(t,n,r,i,a))}catch(e){return b(e,a,n,r,i)}return{displayRoot:a,files:n,errors:r,warnings:i}}async function y(e,t,n){let r=[],a=[],o=[],s=x(n,r,a,o,e);for(let c of t){let t=M(c,n)?N(c,n):void 0;if(!t)continue;let u=l.join(e,c);if(!(await i(u).catch(()=>{}))?.isSymbolicLink())try{await D(u,t,`directory`,s)}catch(t){return b(t,e,r,a,o)}}return{displayRoot:e,files:r,errors:a,warnings:o}}function b(e,n,r,i,a){if(!(e instanceof t))throw e;let o=L(e);return{displayRoot:n,files:r,errors:[...i,o],warnings:a,fatalError:o}}function x(e,t,n,r,i){return{options:e,files:t,errors:n,warnings:r,visitedDirectories:new Set,visitedFiles:new Set,rootDirectory:i}}async function S(e,t,n){try{return await e()}catch(e){n.errors.push(`${P(t,n.rootDirectory)}: ${L(e)}`);return}}async function C(e,t){let n=await S(()=>s(e),e,t);return n!==void 0&&j(n,t.rootDirectory)?n:void 0}async function w(e,t){let n=await C(e,t);if(n===void 0||t.visitedDirectories.has(n))return;t.visitedDirectories.add(n);let r=await S(()=>o(e,{withFileTypes:!0}),e,t);if(r!==void 0)for(let n of r){let r=l.join(e,n.name);if(n.isSymbolicLink()){await T(n.name,r,t);continue}if(n.isDirectory()){if(A(n.name,t.options))continue;await w(r,t);continue}n.isFile()&&await E(r,t)}}async function T(e,t,n){let r=await C(t,n);if(r===void 0)return;let i=await S(()=>c(t),t,n);if(i!==void 0){if(i.isDirectory()){if(A(e,n.options)||A(l.basename(r),n.options))return;await w(t,n);return}i.isFile()&&await E(t,n,r,r)}}async function E(e,t,n=e,r){let i=N(n,t.options);i&&await D(e,i,`directory`,t,r)}async function D(e,i,o,c,l){try{let t=l??await s(e);if(c.visitedFiles.has(t))return;c.visitedFiles.add(t);let u=await a(e,`utf8`),d={language:i,duplication:c.options.duplication},f={file:e,metrics:r(u,d)};if(o===`directory`)try{f.duplicationCandidates=n(u,d)}catch(t){c.warnings.push(`${P(e,c.rootDirectory)}: cross-file duplication candidates unavailable: ${L(t)}`)}c.files.push(f)}catch(n){if(n instanceof t)throw n;c.errors.push(`${P(e,c.rootDirectory)}: ${L(n)}`)}}function O(t,n){if(t.fatalError||t.files.length<2)return;let r=t.files.flatMap(({file:e,duplicationCandidates:n})=>n?[{file:P(e,t.displayRoot),...n}]:[]);r.length<2||(t.crossFileDuplication=e(r,n.duplication))}function k(e,t,n){let r=new Set(e?.duplication.duplicateLineNumbers),i=t&&Object.hasOwn(t.duplicateLineNumbersByFile,n)?t.duplicateLineNumbersByFile[n]??[]:[];for(let e of i)r.add(e);return r}function A(e,t){return f.has(e)?!0:!t.includeTests&&p.has(e)}function j(e,t){let n=l.relative(t,e);return n===``||n!==`..`&&!n.startsWith(`..${l.sep}`)&&!l.isAbsolute(n)}function M(e,t){let n=e.split(`/`);for(let e of n.slice(0,-1))if(f.has(e)||!t.includeTests&&p.has(e))return!1;return N(e,t)!==void 0}function N(e,t,n=!1){let r=e.toLowerCase();if(!(!n&&(r.endsWith(`.d.ts`)||r.endsWith(`.d.mts`)||r.endsWith(`.d.cts`)||r.endsWith(`.min.js`)||r.endsWith(`.pnp.cjs`)))&&!(!n&&!t.includeTests&&(m.test(l.basename(e))||h.test(l.basename(e)))))return l.extname(e)===`.C`?`cpp`:d.get(l.extname(r))}function P(e,t){return l.relative(t,e)||l.basename(e)}function F(e){process.stdout.write(e)}function I(e){process.stderr.write(e)}function L(e){return e instanceof Error?e.message:String(e)}export{O as addCrossFileDuplication,k as collectDuplicatedLineNumbers,_ as configSearchDirectory,L as formatError,P as formatPath,N as getLanguage,M as isScannedPath,g as resolveTarget,y as scanListedFiles,v as scanTarget,I as writeStderr,F as writeStdout};
2
2
  //# sourceMappingURL=scan.js.map
package/dist/scan.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"scan.js","names":[],"sources":["../src/scan.ts"],"sourcesContent":["import { lstat, readdir, readFile, realpath, stat } from 'node:fs/promises';\nimport os from 'node:os';\nimport path from 'node:path';\nimport { measureCrossFileDuplication, type CrossFileDuplicationMetrics } from './crossFileDuplication.js';\nimport type { CrossFileDuplicationFileData } from './duplication.js';\nimport { collectCrossFileDuplicationFileData, measureCode } from './metrics.js';\nimport { NativeAddonError } from './nativeMetrics.js';\nimport type { CodeMetrics, DuplicationOptions, LanguageName } from './types.js';\n\n/** The scan settings shared by every command (a structural subset of each command's options). */\nexport interface ScanOptions {\n duplication: Required<DuplicationOptions>;\n includeTests: boolean;\n}\n\nexport interface FileMetrics {\n file: string;\n metrics: CodeMetrics;\n /** Cross-file duplicate candidates and token/statement data, collected only for directory scans. */\n duplicationCandidates?: CrossFileDuplicationFileData;\n}\n\nexport interface ScanResult {\n crossFileDuplication?: CrossFileDuplicationMetrics;\n displayRoot: string;\n errors: string[];\n /** Non-fatal degradations (e.g. cross-file candidates unavailable); the file is still measured. */\n warnings: string[];\n fatalError?: string;\n files: FileMetrics[];\n}\n\nconst languageByExtension = new Map<string, LanguageName>([\n ['.c', 'c'],\n ['.c++', 'cpp'],\n ['.cc', 'cpp'],\n ['.cjs', 'javascript'],\n ['.cp', 'cpp'],\n ['.cpp', 'cpp'],\n ['.tcc', 'cpp'],\n ['.cts', 'typescript'],\n ['.cxx', 'cpp'],\n ['.go', 'go'],\n // Headers may be C or C++; the C++ grammar parses both.\n ['.h', 'cpp'],\n ['.hh', 'cpp'],\n ['.hpp', 'cpp'],\n ['.hxx', 'cpp'],\n ['.java', 'java'],\n ['.js', 'javascript'],\n ['.jsx', 'jsx'],\n ['.mjs', 'javascript'],\n ['.mts', 'typescript'],\n ['.py', 'python'],\n ['.rb', 'ruby'],\n ['.rs', 'rust'],\n ['.ts', 'typescript'],\n ['.tsx', 'tsx'],\n]);\n\nconst ignoredDirectoryNames = new Set([\n '.agents',\n '.claude',\n '.cursor',\n '.git',\n '.next',\n '.playwright-cli',\n '.tox',\n '.tmp',\n '.turbo',\n '.venv',\n '.yarn',\n '__fixtures__',\n '__generated__',\n '__pycache__',\n 'coverage',\n 'dist',\n 'fixtures',\n 'generated',\n 'node_modules',\n 'target',\n 'test-fixtures',\n 'vendor',\n 'venv',\n]);\n\nconst testDirectoryNames = new Set(['__tests__', 'test', 'tests', 'spec']);\nconst testFilePattern = /(?:^test(?:[_-].*)?|\\.(?:spec|test)|[_-](?:test|spec))\\.[^.]+$/iu;\n// JUnit tests use a case-sensitive `Test.java` suffix; case-insensitive matching would catch\n// production files like `contest.java`.\nconst javaTestFilePattern = /Test\\.java$/u;\n\nexport function resolveTarget(target: string): string {\n if (target === '~') {\n return os.homedir();\n }\n\n if (target.startsWith('~/')) {\n return path.join(os.homedir(), target.slice(2));\n }\n\n return path.resolve(target);\n}\n\n/** Returns the directory from which the config file search should start (the target itself if it is a directory). */\nexport async function configSearchDirectory(target: string): Promise<string> {\n try {\n const targetStat = await stat(target);\n return targetStat.isDirectory() ? target : path.dirname(target);\n } catch {\n return path.dirname(target);\n }\n}\n\n/** Shared state of one scan, threaded through the directory walk instead of positional plumbing. */\ninterface ScanContext {\n options: ScanOptions;\n files: FileMetrics[];\n errors: string[];\n warnings: string[];\n visitedDirectories: Set<string>;\n visitedFiles: Set<string>;\n /** Scan root: paths are displayed relative to it, and symbolic links may not escape it. */\n rootDirectory: string;\n}\n\nexport async function scanTarget(target: string, options: ScanOptions): Promise<ScanResult> {\n const files: FileMetrics[] = [];\n const errors: string[] = [];\n const warnings: string[] = [];\n let canonicalTarget = target;\n try {\n canonicalTarget = await realpath(target);\n } catch {\n // stat below reports missing targets with the original path.\n }\n\n const fallbackDisplayRoot = path.dirname(canonicalTarget);\n let targetStat;\n\n try {\n targetStat = await stat(canonicalTarget);\n } catch (error) {\n const fatalError = `${formatPath(canonicalTarget, fallbackDisplayRoot)}: ${formatError(error)}`;\n return { displayRoot: fallbackDisplayRoot, files, errors: [fatalError], warnings, fatalError };\n }\n\n if (targetStat.isFile()) {\n const displayRoot = path.dirname(canonicalTarget);\n const language = getLanguage(canonicalTarget, options, true);\n if (!language) {\n const fatalError = `${formatPath(canonicalTarget, displayRoot)}: unsupported file type`;\n return { displayRoot, files, errors: [fatalError], warnings, fatalError };\n }\n\n const context = makeScanContext(options, files, errors, warnings, displayRoot);\n try {\n await measureFile(canonicalTarget, language, 'single-file', context, canonicalTarget);\n } catch (error) {\n return toFatalResult(error, displayRoot, files, errors, warnings);\n }\n return { displayRoot, files, errors, warnings };\n }\n\n try {\n await scanDirectory(canonicalTarget, makeScanContext(options, files, errors, warnings, canonicalTarget));\n } catch (error) {\n return toFatalResult(error, canonicalTarget, files, errors, warnings);\n }\n return { displayRoot: canonicalTarget, files, errors, warnings };\n}\n\n/**\n * Measures an explicit list of repository-relative files (the diff gate's git-visible allowlist)\n * instead of walking the directory tree, so ignored artifact directories are never parsed. Paths\n * outside the scan scope (ignored/test directories, unsupported or test file names) are skipped\n * with the same rules as the walk.\n */\nexport async function scanListedFiles(\n rootDirectory: string,\n relativePaths: Iterable<string>,\n options: ScanOptions\n): Promise<ScanResult> {\n const files: FileMetrics[] = [];\n const errors: string[] = [];\n const warnings: string[] = [];\n const context = makeScanContext(options, files, errors, warnings, rootDirectory);\n for (const relativePath of relativePaths) {\n const language = isScannedPath(relativePath, options) ? getLanguage(relativePath, options) : undefined;\n if (!language) {\n continue;\n }\n const absolutePath = path.join(rootDirectory, relativePath);\n // Symbolic links are not source files: git stores only their target string, so measuring\n // through them would diverge from what any revision of the repository actually contains.\n const stats = await lstat(absolutePath).catch(() => {});\n if (stats?.isSymbolicLink()) {\n continue;\n }\n try {\n await measureFile(absolutePath, language, 'directory', context);\n } catch (error) {\n return toFatalResult(error, rootDirectory, files, errors, warnings);\n }\n }\n return { displayRoot: rootDirectory, files, errors, warnings };\n}\n\n/** A run-wide failure (a missing native addon) as a fatal result; anything else keeps throwing. */\nfunction toFatalResult(\n error: unknown,\n displayRoot: string,\n files: FileMetrics[],\n errors: string[],\n warnings: string[]\n): ScanResult {\n if (!(error instanceof NativeAddonError)) {\n throw error;\n }\n const fatalError = formatError(error);\n // Errors the walk accumulated before the fatal failure stay reported alongside it.\n return { displayRoot, files, errors: [...errors, fatalError], warnings, fatalError };\n}\n\nfunction makeScanContext(\n options: ScanOptions,\n files: FileMetrics[],\n errors: string[],\n warnings: string[],\n rootDirectory: string\n): ScanContext {\n return { options, files, errors, warnings, visitedDirectories: new Set(), visitedFiles: new Set(), rootDirectory };\n}\n\n/** Runs a filesystem operation, recording a scan error and returning undefined when it fails. */\nasync function tryFileSystem<T>(\n operation: () => Promise<T>,\n target: string,\n context: ScanContext\n): Promise<T | undefined> {\n try {\n return await operation();\n } catch (error) {\n context.errors.push(`${formatPath(target, context.rootDirectory)}: ${formatError(error)}`);\n return undefined;\n }\n}\n\n/** Resolves the path (recording errors); undefined when that fails or the result escapes the root. */\nasync function resolveWithinRoot(target: string, context: ScanContext): Promise<string | undefined> {\n const resolved = await tryFileSystem(() => realpath(target), target, context);\n return resolved !== undefined && isWithinDirectory(resolved, context.rootDirectory) ? resolved : undefined;\n}\n\nasync function scanDirectory(directory: string, context: ScanContext): Promise<void> {\n const resolvedDirectory = await resolveWithinRoot(directory, context);\n if (resolvedDirectory === undefined || context.visitedDirectories.has(resolvedDirectory)) {\n return;\n }\n context.visitedDirectories.add(resolvedDirectory);\n\n const entries = await tryFileSystem(() => readdir(directory, { withFileTypes: true }), directory, context);\n if (entries === undefined) {\n return;\n }\n\n for (const entry of entries) {\n const entryPath = path.join(directory, entry.name);\n if (entry.isSymbolicLink()) {\n await scanSymbolicLink(entry.name, entryPath, context);\n continue;\n }\n\n if (entry.isDirectory()) {\n if (shouldSkipDirectory(entry.name, context.options)) {\n continue;\n }\n await scanDirectory(entryPath, context);\n continue;\n }\n\n if (entry.isFile()) {\n await measureScannableFile(entryPath, context);\n }\n }\n}\n\nasync function scanSymbolicLink(name: string, entryPath: string, context: ScanContext): Promise<void> {\n const resolvedPath = await resolveWithinRoot(entryPath, context);\n if (resolvedPath === undefined) {\n return;\n }\n\n const entryStat = await tryFileSystem(() => stat(entryPath), entryPath, context);\n if (entryStat === undefined) {\n return;\n }\n\n if (entryStat.isDirectory()) {\n if (\n shouldSkipDirectory(name, context.options) ||\n shouldSkipDirectory(path.basename(resolvedPath), context.options)\n ) {\n return;\n }\n await scanDirectory(entryPath, context);\n return;\n }\n\n if (entryStat.isFile()) {\n await measureScannableFile(entryPath, context, resolvedPath, resolvedPath);\n }\n}\n\nasync function measureScannableFile(\n file: string,\n context: ScanContext,\n languageFile = file,\n realFile?: string\n): Promise<void> {\n const language = getLanguage(languageFile, context.options);\n if (language) {\n await measureFile(file, language, 'directory', context, realFile);\n }\n}\n\nasync function measureFile(\n file: string,\n language: LanguageName,\n mode: 'single-file' | 'directory',\n context: ScanContext,\n realFile?: string\n): Promise<void> {\n try {\n const resolvedFile = realFile ?? (await realpath(file));\n if (context.visitedFiles.has(resolvedFile)) {\n return;\n }\n context.visitedFiles.add(resolvedFile);\n\n const code = await readFile(file, 'utf8');\n const measureOptions = { language, duplication: context.options.duplication };\n const fileMetrics: FileMetrics = { file, metrics: measureCode(code, measureOptions) };\n // Only directory scans compare files against each other; a single-file target has no peers.\n // Candidate collection is an auxiliary pass: if it fails where measureCode succeeded (an\n // addon error specific to this pass), that must not discard the measured metrics.\n if (mode === 'directory') {\n try {\n fileMetrics.duplicationCandidates = collectCrossFileDuplicationFileData(code, measureOptions);\n } catch (error) {\n // A warning, not an error: the file's metrics are complete, only its participation in\n // cross-file matching is lost, so it is not \"skipped\" and must not fail --fail-on-error.\n context.warnings.push(\n `${formatPath(file, context.rootDirectory)}: cross-file duplication candidates unavailable: ${formatError(error)}`\n );\n }\n }\n context.files.push(fileMetrics);\n } catch (error) {\n // A missing native addon fails every file identically: propagate it once as a fatal scan\n // error instead of recording one \"skipped\" entry per file behind a successful exit code.\n if (error instanceof NativeAddonError) {\n throw error;\n }\n context.errors.push(`${formatPath(file, context.rootDirectory)}: ${formatError(error)}`);\n }\n}\n\n/** Runs after the scan so every measured file's candidates participate. */\nexport function addCrossFileDuplication(result: ScanResult, options: ScanOptions): void {\n if (result.fatalError || result.files.length < 2) {\n return;\n }\n const sourceFiles = result.files.flatMap(({ file, duplicationCandidates }) =>\n duplicationCandidates ? [{ file: formatPath(file, result.displayRoot), ...duplicationCandidates }] : []\n );\n if (sourceFiles.length < 2) {\n return;\n }\n result.crossFileDuplication = measureCrossFileDuplication(sourceFiles, options.duplication);\n}\n\n/**\n * Distinct 1-based code lines covered by within-file or cross-file duplicated content. Both\n * sources expose the exact lines carrying matched tokens (never block bounding ranges, which\n * would over-count comment/blank lines and the unmatched gap of a merged clone), so the union is\n * a subset of the file's code lines and a ratio derived over code lines can never exceed 1.\n */\nexport function collectDuplicatedLineNumbers(\n metrics: CodeMetrics | undefined,\n crossFileDuplication: CrossFileDuplicationMetrics | undefined,\n formattedFile: string\n): Set<number> {\n const lines = new Set(metrics?.duplication.duplicateLineNumbers);\n // Object.hasOwn: a file named like an Object.prototype member must not read an inherited value.\n const crossFileLines =\n crossFileDuplication && Object.hasOwn(crossFileDuplication.duplicateLineNumbersByFile, formattedFile)\n ? (crossFileDuplication.duplicateLineNumbersByFile[formattedFile] ?? [])\n : [];\n for (const line of crossFileLines) {\n lines.add(line);\n }\n return lines;\n}\n\nfunction shouldSkipDirectory(name: string, options: ScanOptions): boolean {\n if (ignoredDirectoryNames.has(name)) {\n return true;\n }\n\n if (options.includeTests) {\n return false;\n }\n\n return testDirectoryNames.has(name);\n}\n\nfunction isWithinDirectory(candidate: string, directory: string): boolean {\n const relative = path.relative(directory, candidate);\n return relative === '' || (relative !== '..' && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative));\n}\n\n/**\n * Whether a repository-relative path would be scanned: no ignored or excluded-test directory\n * segment and a supported, non-test file name. The diff gate uses this for base-revision\n * eligibility, so code renamed into scan scope gates as new code instead of ratcheting against\n * a blob the scanner would never have measured.\n */\nexport function isScannedPath(relativePath: string, options: ScanOptions): boolean {\n const segments = relativePath.split('/');\n for (const segment of segments.slice(0, -1)) {\n if (ignoredDirectoryNames.has(segment) || (!options.includeTests && testDirectoryNames.has(segment))) {\n return false;\n }\n }\n return getLanguage(relativePath, options) !== undefined;\n}\n\nexport function getLanguage(file: string, options: ScanOptions, explicitTarget = false): LanguageName | undefined {\n const lowerFile = file.toLowerCase();\n if (\n !explicitTarget &&\n (lowerFile.endsWith('.d.ts') ||\n lowerFile.endsWith('.d.mts') ||\n lowerFile.endsWith('.d.cts') ||\n lowerFile.endsWith('.min.js') ||\n lowerFile.endsWith('.pnp.cjs'))\n ) {\n return undefined;\n }\n\n if (\n !explicitTarget &&\n !options.includeTests &&\n (testFilePattern.test(path.basename(file)) || javaTestFilePattern.test(path.basename(file)))\n ) {\n return undefined;\n }\n\n // GCC treats an uppercase `.C` as C++; lowercasing first would misparse it with the C grammar.\n if (path.extname(file) === '.C') {\n return 'cpp';\n }\n\n return languageByExtension.get(path.extname(lowerFile));\n}\n\nexport function formatPath(file: string, base: string): string {\n return path.relative(base, file) || path.basename(file);\n}\n\nexport function writeStdout(message: string): void {\n process.stdout.write(message);\n}\n\nexport function writeStderr(message: string): void {\n process.stderr.write(message);\n}\n\nexport function formatError(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n"],"mappings":"8VAgCA,MAAM,EAAsB,IAAI,IAA0B,CACxD,CAAC,KAAM,GAAG,EACV,CAAC,OAAQ,KAAK,EACd,CAAC,MAAO,KAAK,EACb,CAAC,OAAQ,YAAY,EACrB,CAAC,MAAO,KAAK,EACb,CAAC,OAAQ,KAAK,EACd,CAAC,OAAQ,KAAK,EACd,CAAC,OAAQ,YAAY,EACrB,CAAC,OAAQ,KAAK,EACd,CAAC,MAAO,IAAI,EAEZ,CAAC,KAAM,KAAK,EACZ,CAAC,MAAO,KAAK,EACb,CAAC,OAAQ,KAAK,EACd,CAAC,OAAQ,KAAK,EACd,CAAC,QAAS,MAAM,EAChB,CAAC,MAAO,YAAY,EACpB,CAAC,OAAQ,KAAK,EACd,CAAC,OAAQ,YAAY,EACrB,CAAC,OAAQ,YAAY,EACrB,CAAC,MAAO,QAAQ,EAChB,CAAC,MAAO,MAAM,EACd,CAAC,MAAO,MAAM,EACd,CAAC,MAAO,YAAY,EACpB,CAAC,OAAQ,KAAK,CAChB,CAAC,EAEK,EAAwB,IAAI,IAAI,CACpC,UACA,UACA,UACA,OACA,QACA,kBACA,OACA,OACA,SACA,QACA,QACA,eACA,gBACA,cACA,WACA,OACA,WACA,YACA,eACA,SACA,gBACA,SACA,MACF,CAAC,EAEK,EAAqB,IAAI,IAAI,CAAC,YAAa,OAAQ,QAAS,MAAM,CAAC,EACnE,EAAkB,mEAGlB,EAAsB,eAE5B,SAAgB,EAAc,EAAwB,CASpD,OARI,IAAW,IACN,EAAG,QAAQ,EAGhB,EAAO,WAAW,IAAI,EACjB,EAAK,KAAK,EAAG,QAAQ,EAAG,EAAO,MAAM,CAAC,CAAC,EAGzC,EAAK,QAAQ,CA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B,CACjD,QAAQ,OAAO,MAAM,CAAO,CAC9B,CAEA,SAAgB,EAAY,EAAuB,CACjD,QAAQ,OAAO,MAAM,CAAO,CAC9B,CAEA,SAAgB,EAAY,EAAwB,CAClD,OAAO,aAAiB,MAAQ,EAAM,QAAU,OAAO,CAAK,CAC9D"}
1
+ {"version":3,"file":"scan.js","names":[],"sources":["../src/scan.ts"],"sourcesContent":["import { lstat, readdir, readFile, realpath, stat } from 'node:fs/promises';\nimport os from 'node:os';\nimport path from 'node:path';\nimport { measureCrossFileDuplication, type CrossFileDuplicationMetrics } from './crossFileDuplication.js';\nimport type { CrossFileDuplicationFileData } from './duplication.js';\nimport { collectCrossFileDuplicationFileData, measureCode } from './metrics.js';\nimport { NativeAddonError } from './nativeMetrics.js';\nimport type { CodeMetrics, DuplicationOptions, LanguageName } from './types.js';\n\n/** The scan settings shared by every command (a structural subset of each command's options). */\nexport interface ScanOptions {\n duplication: Required<DuplicationOptions>;\n includeTests: boolean;\n}\n\nexport interface FileMetrics {\n file: string;\n metrics: CodeMetrics;\n /** Cross-file duplicate candidates and token/statement data, collected only for directory scans. */\n duplicationCandidates?: CrossFileDuplicationFileData;\n}\n\nexport interface ScanResult {\n crossFileDuplication?: CrossFileDuplicationMetrics;\n displayRoot: string;\n errors: string[];\n /** Non-fatal degradations (e.g. cross-file candidates unavailable); the file is still measured. */\n warnings: string[];\n fatalError?: string;\n files: FileMetrics[];\n}\n\nconst languageByExtension = new Map<string, LanguageName>([\n ['.c', 'c'],\n ['.c++', 'cpp'],\n ['.cc', 'cpp'],\n ['.cjs', 'javascript'],\n ['.cp', 'cpp'],\n ['.cpp', 'cpp'],\n ['.cs', 'csharp'],\n ['.tcc', 'cpp'],\n ['.cts', 'typescript'],\n ['.cxx', 'cpp'],\n ['.go', 'go'],\n // Headers may be C or C++; the C++ grammar parses both.\n ['.h', 'cpp'],\n ['.hh', 'cpp'],\n ['.hpp', 'cpp'],\n ['.hxx', 'cpp'],\n ['.java', 'java'],\n ['.js', 'javascript'],\n ['.jsx', 'jsx'],\n ['.kt', 'kotlin'],\n ['.kts', 'kotlin'],\n ['.mjs', 'javascript'],\n ['.mts', 'typescript'],\n ['.py', 'python'],\n ['.rb', 'ruby'],\n ['.rs', 'rust'],\n ['.ts', 'typescript'],\n ['.tsx', 'tsx'],\n]);\n\nconst ignoredDirectoryNames = new Set([\n '.agents',\n '.claude',\n '.cursor',\n '.git',\n '.next',\n '.playwright-cli',\n '.tox',\n '.tmp',\n '.turbo',\n '.venv',\n '.yarn',\n '__fixtures__',\n '__generated__',\n '__pycache__',\n 'coverage',\n 'dist',\n 'fixtures',\n 'generated',\n 'node_modules',\n // .NET SDK intermediate output (generated sources such as `*.GlobalUsings.g.cs`).\n 'obj',\n 'target',\n 'test-fixtures',\n 'vendor',\n 'venv',\n]);\n\nconst testDirectoryNames = new Set(['__tests__', 'test', 'tests', 'spec']);\nconst testFilePattern = /(?:^test(?:[_-].*)?|\\.(?:spec|test)|[_-](?:test|spec))\\.[^.]+$/iu;\n// JUnit (Java/Kotlin) and xUnit/NUnit (C#) tests use case-sensitive `Test`/`Tests` class-name\n// suffixes; case-insensitive matching would catch production files like `contest.java`.\nconst suffixTestFilePattern = /Tests?\\.(?:java|kt|cs)$/u;\n\nexport function resolveTarget(target: string): string {\n if (target === '~') {\n return os.homedir();\n }\n\n if (target.startsWith('~/')) {\n return path.join(os.homedir(), target.slice(2));\n }\n\n return path.resolve(target);\n}\n\n/** Returns the directory from which the config file search should start (the target itself if it is a directory). */\nexport async function configSearchDirectory(target: string): Promise<string> {\n try {\n const targetStat = await stat(target);\n return targetStat.isDirectory() ? target : path.dirname(target);\n } catch {\n return path.dirname(target);\n }\n}\n\n/** Shared state of one scan, threaded through the directory walk instead of positional plumbing. */\ninterface ScanContext {\n options: ScanOptions;\n files: FileMetrics[];\n errors: string[];\n warnings: string[];\n visitedDirectories: Set<string>;\n visitedFiles: Set<string>;\n /** Scan root: paths are displayed relative to it, and symbolic links may not escape it. */\n rootDirectory: string;\n}\n\nexport async function scanTarget(target: string, options: ScanOptions): Promise<ScanResult> {\n const files: FileMetrics[] = [];\n const errors: string[] = [];\n const warnings: string[] = [];\n let canonicalTarget = target;\n try {\n canonicalTarget = await realpath(target);\n } catch {\n // stat below reports missing targets with the original path.\n }\n\n const fallbackDisplayRoot = path.dirname(canonicalTarget);\n let targetStat;\n\n try {\n targetStat = await stat(canonicalTarget);\n } catch (error) {\n const fatalError = `${formatPath(canonicalTarget, fallbackDisplayRoot)}: ${formatError(error)}`;\n return { displayRoot: fallbackDisplayRoot, files, errors: [fatalError], warnings, fatalError };\n }\n\n if (targetStat.isFile()) {\n const displayRoot = path.dirname(canonicalTarget);\n const language = getLanguage(canonicalTarget, options, true);\n if (!language) {\n const fatalError = `${formatPath(canonicalTarget, displayRoot)}: unsupported file type`;\n return { displayRoot, files, errors: [fatalError], warnings, fatalError };\n }\n\n const context = makeScanContext(options, files, errors, warnings, displayRoot);\n try {\n await measureFile(canonicalTarget, language, 'single-file', context, canonicalTarget);\n } catch (error) {\n return toFatalResult(error, displayRoot, files, errors, warnings);\n }\n return { displayRoot, files, errors, warnings };\n }\n\n try {\n await scanDirectory(canonicalTarget, makeScanContext(options, files, errors, warnings, canonicalTarget));\n } catch (error) {\n return toFatalResult(error, canonicalTarget, files, errors, warnings);\n }\n return { displayRoot: canonicalTarget, files, errors, warnings };\n}\n\n/**\n * Measures an explicit list of repository-relative files (the diff gate's git-visible allowlist)\n * instead of walking the directory tree, so ignored artifact directories are never parsed. Paths\n * outside the scan scope (ignored/test directories, unsupported or test file names) are skipped\n * with the same rules as the walk.\n */\nexport async function scanListedFiles(\n rootDirectory: string,\n relativePaths: Iterable<string>,\n options: ScanOptions\n): Promise<ScanResult> {\n const files: FileMetrics[] = [];\n const errors: string[] = [];\n const warnings: string[] = [];\n const context = makeScanContext(options, files, errors, warnings, rootDirectory);\n for (const relativePath of relativePaths) {\n const language = isScannedPath(relativePath, options) ? getLanguage(relativePath, options) : undefined;\n if (!language) {\n continue;\n }\n const absolutePath = path.join(rootDirectory, relativePath);\n // Symbolic links are not source files: git stores only their target string, so measuring\n // through them would diverge from what any revision of the repository actually contains.\n const stats = await lstat(absolutePath).catch(() => {});\n if (stats?.isSymbolicLink()) {\n continue;\n }\n try {\n await measureFile(absolutePath, language, 'directory', context);\n } catch (error) {\n return toFatalResult(error, rootDirectory, files, errors, warnings);\n }\n }\n return { displayRoot: rootDirectory, files, errors, warnings };\n}\n\n/** A run-wide failure (a missing native addon) as a fatal result; anything else keeps throwing. */\nfunction toFatalResult(\n error: unknown,\n displayRoot: string,\n files: FileMetrics[],\n errors: string[],\n warnings: string[]\n): ScanResult {\n if (!(error instanceof NativeAddonError)) {\n throw error;\n }\n const fatalError = formatError(error);\n // Errors the walk accumulated before the fatal failure stay reported alongside it.\n return { displayRoot, files, errors: [...errors, fatalError], warnings, fatalError };\n}\n\nfunction makeScanContext(\n options: ScanOptions,\n files: FileMetrics[],\n errors: string[],\n warnings: string[],\n rootDirectory: string\n): ScanContext {\n return { options, files, errors, warnings, visitedDirectories: new Set(), visitedFiles: new Set(), rootDirectory };\n}\n\n/** Runs a filesystem operation, recording a scan error and returning undefined when it fails. */\nasync function tryFileSystem<T>(\n operation: () => Promise<T>,\n target: string,\n context: ScanContext\n): Promise<T | undefined> {\n try {\n return await operation();\n } catch (error) {\n context.errors.push(`${formatPath(target, context.rootDirectory)}: ${formatError(error)}`);\n return undefined;\n }\n}\n\n/** Resolves the path (recording errors); undefined when that fails or the result escapes the root. */\nasync function resolveWithinRoot(target: string, context: ScanContext): Promise<string | undefined> {\n const resolved = await tryFileSystem(() => realpath(target), target, context);\n return resolved !== undefined && isWithinDirectory(resolved, context.rootDirectory) ? resolved : undefined;\n}\n\nasync function scanDirectory(directory: string, context: ScanContext): Promise<void> {\n const resolvedDirectory = await resolveWithinRoot(directory, context);\n if (resolvedDirectory === undefined || context.visitedDirectories.has(resolvedDirectory)) {\n return;\n }\n context.visitedDirectories.add(resolvedDirectory);\n\n const entries = await tryFileSystem(() => readdir(directory, { withFileTypes: true }), directory, context);\n if (entries === undefined) {\n return;\n }\n\n for (const entry of entries) {\n const entryPath = path.join(directory, entry.name);\n if (entry.isSymbolicLink()) {\n await scanSymbolicLink(entry.name, entryPath, context);\n continue;\n }\n\n if (entry.isDirectory()) {\n if (shouldSkipDirectory(entry.name, context.options)) {\n continue;\n }\n await scanDirectory(entryPath, context);\n continue;\n }\n\n if (entry.isFile()) {\n await measureScannableFile(entryPath, context);\n }\n }\n}\n\nasync function scanSymbolicLink(name: string, entryPath: string, context: ScanContext): Promise<void> {\n const resolvedPath = await resolveWithinRoot(entryPath, context);\n if (resolvedPath === undefined) {\n return;\n }\n\n const entryStat = await tryFileSystem(() => stat(entryPath), entryPath, context);\n if (entryStat === undefined) {\n return;\n }\n\n if (entryStat.isDirectory()) {\n if (\n shouldSkipDirectory(name, context.options) ||\n shouldSkipDirectory(path.basename(resolvedPath), context.options)\n ) {\n return;\n }\n await scanDirectory(entryPath, context);\n return;\n }\n\n if (entryStat.isFile()) {\n await measureScannableFile(entryPath, context, resolvedPath, resolvedPath);\n }\n}\n\nasync function measureScannableFile(\n file: string,\n context: ScanContext,\n languageFile = file,\n realFile?: string\n): Promise<void> {\n const language = getLanguage(languageFile, context.options);\n if (language) {\n await measureFile(file, language, 'directory', context, realFile);\n }\n}\n\nasync function measureFile(\n file: string,\n language: LanguageName,\n mode: 'single-file' | 'directory',\n context: ScanContext,\n realFile?: string\n): Promise<void> {\n try {\n const resolvedFile = realFile ?? (await realpath(file));\n if (context.visitedFiles.has(resolvedFile)) {\n return;\n }\n context.visitedFiles.add(resolvedFile);\n\n const code = await readFile(file, 'utf8');\n const measureOptions = { language, duplication: context.options.duplication };\n const fileMetrics: FileMetrics = { file, metrics: measureCode(code, measureOptions) };\n // Only directory scans compare files against each other; a single-file target has no peers.\n // Candidate collection is an auxiliary pass: if it fails where measureCode succeeded (an\n // addon error specific to this pass), that must not discard the measured metrics.\n if (mode === 'directory') {\n try {\n fileMetrics.duplicationCandidates = collectCrossFileDuplicationFileData(code, measureOptions);\n } catch (error) {\n // A warning, not an error: the file's metrics are complete, only its participation in\n // cross-file matching is lost, so it is not \"skipped\" and must not fail --fail-on-error.\n context.warnings.push(\n `${formatPath(file, context.rootDirectory)}: cross-file duplication candidates unavailable: ${formatError(error)}`\n );\n }\n }\n context.files.push(fileMetrics);\n } catch (error) {\n // A missing native addon fails every file identically: propagate it once as a fatal scan\n // error instead of recording one \"skipped\" entry per file behind a successful exit code.\n if (error instanceof NativeAddonError) {\n throw error;\n }\n context.errors.push(`${formatPath(file, context.rootDirectory)}: ${formatError(error)}`);\n }\n}\n\n/** Runs after the scan so every measured file's candidates participate. */\nexport function addCrossFileDuplication(result: ScanResult, options: ScanOptions): void {\n if (result.fatalError || result.files.length < 2) {\n return;\n }\n const sourceFiles = result.files.flatMap(({ file, duplicationCandidates }) =>\n duplicationCandidates ? [{ file: formatPath(file, result.displayRoot), ...duplicationCandidates }] : []\n );\n if (sourceFiles.length < 2) {\n return;\n }\n result.crossFileDuplication = measureCrossFileDuplication(sourceFiles, options.duplication);\n}\n\n/**\n * Distinct 1-based code lines covered by within-file or cross-file duplicated content. Both\n * sources expose the exact lines carrying matched tokens (never block bounding ranges, which\n * would over-count comment/blank lines and the unmatched gap of a merged clone), so the union is\n * a subset of the file's code lines and a ratio derived over code lines can never exceed 1.\n */\nexport function collectDuplicatedLineNumbers(\n metrics: CodeMetrics | undefined,\n crossFileDuplication: CrossFileDuplicationMetrics | undefined,\n formattedFile: string\n): Set<number> {\n const lines = new Set(metrics?.duplication.duplicateLineNumbers);\n // Object.hasOwn: a file named like an Object.prototype member must not read an inherited value.\n const crossFileLines =\n crossFileDuplication && Object.hasOwn(crossFileDuplication.duplicateLineNumbersByFile, formattedFile)\n ? (crossFileDuplication.duplicateLineNumbersByFile[formattedFile] ?? [])\n : [];\n for (const line of crossFileLines) {\n lines.add(line);\n }\n return lines;\n}\n\nfunction shouldSkipDirectory(name: string, options: ScanOptions): boolean {\n if (ignoredDirectoryNames.has(name)) {\n return true;\n }\n\n if (options.includeTests) {\n return false;\n }\n\n return testDirectoryNames.has(name);\n}\n\nfunction isWithinDirectory(candidate: string, directory: string): boolean {\n const relative = path.relative(directory, candidate);\n return relative === '' || (relative !== '..' && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative));\n}\n\n/**\n * Whether a repository-relative path would be scanned: no ignored or excluded-test directory\n * segment and a supported, non-test file name. The diff gate uses this for base-revision\n * eligibility, so code renamed into scan scope gates as new code instead of ratcheting against\n * a blob the scanner would never have measured.\n */\nexport function isScannedPath(relativePath: string, options: ScanOptions): boolean {\n const segments = relativePath.split('/');\n for (const segment of segments.slice(0, -1)) {\n if (ignoredDirectoryNames.has(segment) || (!options.includeTests && testDirectoryNames.has(segment))) {\n return false;\n }\n }\n return getLanguage(relativePath, options) !== undefined;\n}\n\nexport function getLanguage(file: string, options: ScanOptions, explicitTarget = false): LanguageName | undefined {\n const lowerFile = file.toLowerCase();\n if (\n !explicitTarget &&\n (lowerFile.endsWith('.d.ts') ||\n lowerFile.endsWith('.d.mts') ||\n lowerFile.endsWith('.d.cts') ||\n lowerFile.endsWith('.min.js') ||\n lowerFile.endsWith('.pnp.cjs'))\n ) {\n return undefined;\n }\n\n if (\n !explicitTarget &&\n !options.includeTests &&\n (testFilePattern.test(path.basename(file)) || suffixTestFilePattern.test(path.basename(file)))\n ) {\n return undefined;\n }\n\n // GCC treats an uppercase `.C` as C++; lowercasing first would misparse it with the C grammar.\n if (path.extname(file) === '.C') {\n return 'cpp';\n }\n\n return languageByExtension.get(path.extname(lowerFile));\n}\n\nexport function formatPath(file: string, base: string): string {\n return path.relative(base, file) || path.basename(file);\n}\n\nexport function writeStdout(message: string): void {\n process.stdout.write(message);\n}\n\nexport function writeStderr(message: string): void {\n process.stderr.write(message);\n}\n\nexport function formatError(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n"],"mappings":"8VAgCA,MAAM,EAAsB,I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B,CAClD,OAAO,aAAiB,MAAQ,EAAM,QAAU,OAAO,CAAK,CAC9D"}
package/dist/types.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- export type SupportedLanguage = 'c' | 'cpp' | 'go' | 'java' | 'javascript' | 'jsx' | 'python' | 'ruby' | 'rust' | 'typescript' | 'tsx';
1
+ export type SupportedLanguage = 'c' | 'cpp' | 'csharp' | 'go' | 'java' | 'javascript' | 'jsx' | 'kotlin' | 'python' | 'ruby' | 'rust' | 'typescript' | 'tsx';
2
2
  export type LanguageName = SupportedLanguage | (string & {});
3
3
  /**
4
4
  * A built-in language as enumerated by the API. Grammars and per-language node-type configuration
package/native/Cargo.lock CHANGED
@@ -42,10 +42,12 @@ dependencies = [
42
42
  "serde_json",
43
43
  "tree-sitter",
44
44
  "tree-sitter-c",
45
+ "tree-sitter-c-sharp",
45
46
  "tree-sitter-cpp",
46
47
  "tree-sitter-go",
47
48
  "tree-sitter-java",
48
49
  "tree-sitter-javascript",
50
+ "tree-sitter-kotlin",
49
51
  "tree-sitter-python",
50
52
  "tree-sitter-ruby",
51
53
  "tree-sitter-rust",
@@ -418,6 +420,16 @@ dependencies = [
418
420
  "tree-sitter",
419
421
  ]
420
422
 
423
+ [[package]]
424
+ name = "tree-sitter-c-sharp"
425
+ version = "0.21.3"
426
+ source = "registry+https://github.com/rust-lang/crates.io-index"
427
+ checksum = "8997ad04502208449025114e434c9024a33a74e700513c702a9d2cac6522a771"
428
+ dependencies = [
429
+ "cc",
430
+ "tree-sitter",
431
+ ]
432
+
421
433
  [[package]]
422
434
  name = "tree-sitter-cpp"
423
435
  version = "0.22.3"
@@ -458,6 +470,16 @@ dependencies = [
458
470
  "tree-sitter",
459
471
  ]
460
472
 
473
+ [[package]]
474
+ name = "tree-sitter-kotlin"
475
+ version = "0.3.8"
476
+ source = "registry+https://github.com/rust-lang/crates.io-index"
477
+ checksum = "54ff60aeb036f5762515ceb31404512ea4f9599764bcd3857074bb82867bdd34"
478
+ dependencies = [
479
+ "cc",
480
+ "tree-sitter",
481
+ ]
482
+
461
483
  [[package]]
462
484
  name = "tree-sitter-python"
463
485
  version = "0.21.0"
package/native/Cargo.toml CHANGED
@@ -25,9 +25,11 @@ regex = "1"
25
25
  # ts_node_field_name_for_child — is compensated in util::find_children_by_field_name.
26
26
  tree-sitter = "=0.22.6"
27
27
  tree-sitter-c = "=0.21.4"
28
+ tree-sitter-c-sharp = "=0.21.3"
28
29
  tree-sitter-cpp = "=0.22.3"
29
30
  tree-sitter-go = "=0.21.2"
30
31
  tree-sitter-java = "=0.21.0"
32
+ tree-sitter-kotlin = "=0.3.8"
31
33
  tree-sitter-javascript = "=0.21.4"
32
34
  tree-sitter-python = "=0.21.0"
33
35
  tree-sitter-ruby = "=0.21.0"
@@ -31,7 +31,16 @@ impl LanguageSets {
31
31
 
32
32
  const BOOLEAN_OPERATORS: &[&str] = &["&&", "||", "and", "or"];
33
33
  /// Parents under which `&&`/`||`/`and`/`or` tokens are actual boolean operators.
34
- const BOOLEAN_OPERATOR_PARENT_TYPES: &[&str] = &["binary_expression", "binary", "boolean_operator"];
34
+ const BOOLEAN_OPERATOR_PARENT_TYPES: &[&str] = &[
35
+ "binary_expression",
36
+ "binary",
37
+ "boolean_operator",
38
+ "conjunction_expression",
39
+ "disjunction_expression",
40
+ // C# pattern combinators (`is > 0 and <= 10`) sequence like `&&`/`||` (SonarC#).
41
+ "and_pattern",
42
+ "or_pattern",
43
+ ];
35
44
 
36
45
  /// A Ruby stabby lambda's body block is part of the lambda, not a separate function.
37
46
  pub fn is_lambda_body_block(node: Node<'_>) -> bool {
@@ -41,8 +50,13 @@ pub fn is_lambda_body_block(node: Node<'_>) -> bool {
41
50
  .is_some_and(|parent| parent.kind() == "lambda")
42
51
  }
43
52
 
53
+ /// A function node with a body of its own: bodyless declarations (abstract methods, auto-property
54
+ /// accessors, accessor-list properties) open no nesting frame, so members inside them are not
55
+ /// charged as nested functions.
44
56
  pub fn is_function_boundary(node: Node<'_>, function_nodes: &HashSet<&'static str>) -> bool {
45
- function_nodes.contains(node.kind()) && !is_lambda_body_block(node)
57
+ function_nodes.contains(node.kind())
58
+ && !is_lambda_body_block(node)
59
+ && crate::functions::is_implemented_function(node)
46
60
  }
47
61
 
48
62
  // Sonar cognitive complexity charges a switch/match once as a whole, not per case label. Only
@@ -55,6 +69,7 @@ const SWITCH_LIKE_NODE_TYPES: &[&str] = &[
55
69
  "select_statement",
56
70
  "match_expression",
57
71
  "match_statement",
72
+ "when_expression",
58
73
  "case",
59
74
  "case_match",
60
75
  ];
@@ -70,6 +85,9 @@ const CASE_CLAUSE_NODE_TYPES: &[&str] = &[
70
85
  "type_case",
71
86
  "communication_case",
72
87
  "match_arm",
88
+ "switch_section",
89
+ "switch_expression_arm",
90
+ "when_entry",
73
91
  "when",
74
92
  "in_clause",
75
93
  ];
@@ -444,6 +462,11 @@ fn count_plain_else_branches(current: Node<'_>) -> u64 {
444
462
  if kind != "if_statement" && kind != "if_expression" {
445
463
  return 0;
446
464
  }
465
+ // Kotlin's `else` is a bare keyword token followed by the branch body (no clause wrapper and
466
+ // no grammar field); an `else if` continuation is charged on the nested if instead.
467
+ if let Some(else_body) = crate::util::kotlin_else_body(current) {
468
+ return u64::from(!crate::util::is_kotlin_else_if_body(else_body));
469
+ }
447
470
  // Extras (comments) inherit the preceding sibling's field in find_children_by_field_name, so a
448
471
  // comment between an `elif_clause` and `else_clause` must not be miscounted as a bare branch.
449
472
  crate::util::find_children_by_field_name(current, "alternative")
@@ -472,6 +495,13 @@ fn is_flow_breaking_jump(node: Node<'_>) -> bool {
472
495
  .iter()
473
496
  .any(|child| child.kind() == "label" || child.kind() == "loop_label");
474
497
  }
498
+ // Kotlin folds every jump into `jump_expression`; the grammar tokenizes a labeled break or
499
+ // continue as `break@`/`continue@` followed by the label (`return@label` is a plain return).
500
+ if node.kind() == "jump_expression" {
501
+ return node
502
+ .child(0)
503
+ .is_some_and(|keyword| keyword.kind() == "break@" || keyword.kind() == "continue@");
504
+ }
475
505
  // Comments are named children too (`break /* done */;`), so only non-comment children mark a
476
506
  // label.
477
507
  (node.kind() == "break_statement" || node.kind() == "continue_statement")
@@ -482,7 +512,11 @@ fn is_flow_breaking_jump(node: Node<'_>) -> bool {
482
512
 
483
513
  /// Wrappers that are transparent when locating the enclosing boolean operation: PMD/Sonar keep a
484
514
  /// sequence continuous across parentheses (`a && (b && c)` costs one point).
485
- const PARENTHESIZED_NODE_TYPES: &[&str] = &["parenthesized_expression", "parenthesized_statements"];
515
+ const PARENTHESIZED_NODE_TYPES: &[&str] = &[
516
+ "parenthesized_expression",
517
+ "parenthesized_statements",
518
+ "parenthesized_pattern",
519
+ ];
486
520
 
487
521
  /// Whether this boolean operator token starts a new sequence, i.e. its binary node is the root of a
488
522
  /// run of same-operator binaries (possibly through parentheses). Only the root operator counts one
@@ -528,13 +562,21 @@ fn find_boolean_operator_text<'a>(binary_node: Node<'_>, code: &Source<'a>) -> O
528
562
  .map(|child| node_text(child, code))
529
563
  }
530
564
 
531
- /// Java `guard`, Ruby `if_guard`, Python `if_clause`, and Rust guards inside `match_pattern`.
565
+ /// Java `guard`, C# `when_clause`, Ruby `if_guard`, Python `if_clause`, and Rust guards inside
566
+ /// `match_pattern`. A C# exception filter (`catch (E e) when (...)`, a `catch_filter_clause`) is
567
+ /// deliberately not charged: the catch itself already counts, and the filter is part of the same
568
+ /// handler condition rather than an extra path (SonarC# does not charge it either).
532
569
  fn is_pattern_guard(node: Node<'_>) -> bool {
533
570
  if !node.is_named() {
534
571
  return false;
535
572
  }
536
573
  let kind = node.kind();
537
- if kind == "guard" || kind == "if_guard" || kind == "unless_guard" || kind == "if_clause" {
574
+ if kind == "guard"
575
+ || kind == "when_clause"
576
+ || kind == "if_guard"
577
+ || kind == "unless_guard"
578
+ || kind == "if_clause"
579
+ {
538
580
  return true;
539
581
  }
540
582
  kind == "match_pattern"
@@ -555,7 +597,14 @@ fn is_flat_chain_continuation(node: Node<'_>) -> bool {
555
597
  let Some(parent) = node.parent() else {
556
598
  return false;
557
599
  };
558
- // JS/C/C++/Rust wrap `else if` in an else clause; Java/Go put it directly in `alternative`.
600
+ // Kotlin puts a braceless `else if` directly in the else branch's control_structure_body.
601
+ if parent.kind() == "control_structure_body" {
602
+ return parent
603
+ .parent()
604
+ .and_then(crate::util::kotlin_else_body)
605
+ .is_some_and(|else_body| else_body.id() == parent.id());
606
+ }
607
+ // JS/C/C++/Rust/C# wrap `else if` in an else clause or put it directly in `alternative`.
559
608
  parent.kind() == "else_clause"
560
609
  || parent
561
610
  .child_by_field_name("alternative")