code-gauge 5.1.0 → 7.0.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 +208 -80
- package/dist/checkCommand.cjs +5 -0
- package/dist/checkCommand.cjs.map +1 -0
- package/dist/checkCommand.d.ts +12 -0
- package/dist/checkCommand.js +5 -0
- package/dist/checkCommand.js.map +1 -0
- package/dist/cli.cjs +3 -3
- package/dist/cli.cjs.map +1 -1
- package/dist/cli.js +3 -3
- package/dist/cli.js.map +1 -1
- package/dist/cliConfig.cjs +1 -1
- package/dist/cliConfig.cjs.map +1 -1
- package/dist/cliConfig.d.ts +3 -11
- package/dist/cliConfig.js +1 -1
- package/dist/cliConfig.js.map +1 -1
- package/dist/exclusion.cjs +1 -1
- package/dist/exclusion.cjs.map +1 -1
- package/dist/exclusion.d.ts +2 -2
- package/dist/exclusion.js +1 -1
- package/dist/exclusion.js.map +1 -1
- package/dist/git.cjs +1 -1
- package/dist/git.cjs.map +1 -1
- package/dist/git.d.ts +13 -12
- package/dist/git.js +1 -1
- package/dist/git.js.map +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.d.ts +0 -4
- package/dist/index.js +1 -1
- package/dist/metrics.cjs +1 -1
- package/dist/metrics.cjs.map +1 -1
- package/dist/metrics.d.ts +1 -2
- package/dist/metrics.js +1 -1
- package/dist/metrics.js.map +1 -1
- package/dist/nativeMetrics.cjs +1 -1
- package/dist/nativeMetrics.cjs.map +1 -1
- package/dist/nativeMetrics.js +1 -1
- package/dist/nativeMetrics.js.map +1 -1
- package/dist/scan.cjs +1 -1
- package/dist/scan.cjs.map +1 -1
- package/dist/scan.d.ts +10 -25
- package/dist/scan.js +1 -1
- package/dist/scan.js.map +1 -1
- package/dist/thresholdCheck.cjs +2 -0
- package/dist/thresholdCheck.cjs.map +1 -0
- package/dist/thresholdCheck.d.ts +36 -0
- package/dist/thresholdCheck.js +2 -0
- package/dist/thresholdCheck.js.map +1 -0
- package/dist/thresholds.cjs +2 -0
- package/dist/thresholds.cjs.map +1 -0
- package/dist/thresholds.d.ts +38 -0
- package/dist/thresholds.js +2 -0
- package/dist/thresholds.js.map +1 -0
- package/dist/types.d.ts +8 -4
- package/dist/worker.cjs +1 -1
- package/dist/worker.cjs.map +1 -1
- package/dist/worker.js +1 -1
- package/dist/worker.js.map +1 -1
- package/package.json +9 -12
- package/dist/diffCommand.cjs +0 -5
- package/dist/diffCommand.cjs.map +0 -1
- package/dist/diffCommand.d.ts +0 -17
- package/dist/diffCommand.js +0 -5
- package/dist/diffCommand.js.map +0 -1
- package/dist/newDuplication.cjs +0 -2
- package/dist/newDuplication.cjs.map +0 -1
- package/dist/newDuplication.d.ts +0 -40
- package/dist/newDuplication.js +0 -2
- package/dist/newDuplication.js.map +0 -1
- package/dist/regressionGate.cjs +0 -2
- package/dist/regressionGate.cjs.map +0 -1
- package/dist/regressionGate.d.ts +0 -108
- package/dist/regressionGate.js +0 -2
- package/dist/regressionGate.js.map +0 -1
- package/scripts/installNative.mjs +0 -96
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"nativeMetrics.js","names":[],"sources":["../src/nativeMetrics.ts"],"sourcesContent":["import { clamp, getErrorMessage } from '@willbooster/shared-lib';\nimport type { CrossFileDuplicateCandidate, Token, TokenRange } from './duplication.js';\nimport type { CodeMetrics, DuplicationOptions, FunctionMetrics } from './types.js';\n\n/**\n * Halstead counts measured natively; the derived float metrics (volume, effort, ...) are\n * computed in TypeScript because they involve transcendental functions (log2) whose last-bit\n * results can differ between V8 and Rust's libm, and results must not depend on the Rust side's\n * libm build.\n */\nexport interface NativeHalsteadCounts {\n distinctOperators: number;\n distinctOperands: number;\n totalOperators: number;\n totalOperands: number;\n}\n\nexport interface NativeFunctionMetricsPayload extends Omit<FunctionMetrics, 'halstead'> {\n halsteadCounts: NativeHalsteadCounts;\n}\n\nexport interface NativeMetricsPayload extends Omit<CodeMetrics, 'halstead' | 'functions' | 'syntaxTree'> {\n functions: NativeFunctionMetricsPayload[];\n halsteadCounts: NativeHalsteadCounts;\n syntaxTree?: string;\n crossFileData?: NativeCrossFileDataPayload;\n}\n\n/** One file's cross-file clone-detection contribution as serialized by the native addon. */\nexport interface NativeCrossFileDataPayload {\n candidates: CrossFileDuplicateCandidate[];\n tokens: Token[];\n containerStatements: TokenRange[][];\n nearMissBlocks: TokenRange[];\n /** 1-based lines that are neither blank nor comment-only, sorted ascending. */\n codeLineNumbers: number[];\n}\n\ntype NativeMeasureArguments = [\n code: string,\n language: string,\n includeSyntaxTree: boolean,\n minTokens: number | undefined,\n maxGapTokens: number | undefined,\n minSimilarityPercent: number | undefined,\n includeCrossFileData: boolean,\n];\n\nexport interface NativeBinding {\n measureCodeNative(...args: NativeMeasureArguments): string;\n measureCodeNativeAsync(...args: NativeMeasureArguments): Promise<string>;\n collectCrossFileDataNative(code: string, language: string, minTokens?: number): string;\n collectFunctionTokenSequencesNative(code: string, language: string): string;\n payloadVersion?(): number;\n}\n\n/**\n * Must equal `payload_version` in native/src/lib.rs. A previously built addon survives a\n * `git pull` untouched, so without this handshake it would silently return payloads missing\n * newer fields, or lack newer binding functions, instead of failing with a clear rebuild message.\n */\nexport const expectedPayloadVersion = 8;\n\n/**\n * Measures one file via the native addon, returning the raw payload for assembly in metrics.ts;\n * with `includeCrossFileData`, the payload also carries the file's cross-file contribution.\n */\nexport function measureCodeNative(\n code: string,\n language: string,\n includeSyntaxTree: boolean,\n duplication?: DuplicationOptions,\n includeCrossFileData = false\n): NativeMetricsPayload {\n return JSON.parse(\n loadBinding().measureCodeNative(\n ...toNativeMeasureArguments(code, language, includeSyntaxTree, duplication, includeCrossFileData)\n )\n ) as NativeMetricsPayload;\n}\n\n/**\n * measureCodeNative on the addon's worker threads, so several files can be measured in parallel.\n * A missing addon still throws synchronously, like measureCodeNative.\n */\nexport function measureCodeNativeAsync(\n code: string,\n language: string,\n includeSyntaxTree: boolean,\n duplication?: DuplicationOptions,\n includeCrossFileData = false\n): Promise<NativeMetricsPayload> {\n return loadBinding()\n .measureCodeNativeAsync(\n ...toNativeMeasureArguments(code, language, includeSyntaxTree, duplication, includeCrossFileData)\n )\n .then((json) => JSON.parse(json) as NativeMetricsPayload);\n}\n\n/** The binding arguments shared by the sync and async measurements, so both measure alike. */\nfunction toNativeMeasureArguments(\n code: string,\n language: string,\n includeSyntaxTree: boolean,\n duplication: DuplicationOptions | undefined,\n includeCrossFileData: boolean\n): NativeMeasureArguments {\n return [\n toWellFormed(code),\n language,\n includeSyntaxTree,\n clampToU32(duplication?.minTokens),\n clampToU32(duplication?.maxGapTokens),\n clampToU32(duplication?.minSimilarityPercent),\n includeCrossFileData,\n ];\n}\n\n/** Collects one file's cross-file clone-detection contribution via the native addon. */\nexport function collectCrossFileDataNative(\n code: string,\n language: string,\n minTokens?: number\n): NativeCrossFileDataPayload {\n return JSON.parse(\n loadBinding().collectCrossFileDataNative(toWellFormed(code), language, clampToU32(minTokens))\n ) as NativeCrossFileDataPayload;\n}\n\n/** Collects normalized token hash sequences of every function via the native addon. */\nexport function collectFunctionTokenSequencesNative(code: string, language: string): Int32Array[] {\n const sequences = JSON.parse(\n loadBinding().collectFunctionTokenSequencesNative(toWellFormed(code), language)\n ) as number[][];\n return sequences.map((sequence) => Int32Array.from(sequence));\n}\n\n/**\n * Lone surrogates cannot cross the N-API boundary losslessly, so ill-formed strings (invalid\n * UTF-16 occasionally present in real-world files) are measured with U+FFFD replacements — the\n * same code units V8's own UTF-8 conversion would substitute.\n */\nfunction toWellFormed(code: string): string {\n return code.isWellFormed() ? code : code.toWellFormed();\n}\n\n/**\n * The duplication settings cross the boundary as u32, whose JavaScript conversion wraps modulo\n * 2^32 (2 ** 32 would become 0 and match everything). The public API accepts any safe integer, so\n * out-of-range values clamp to [0, u32::MAX] — no source can hold 2^32 tokens, so a clamped\n * threshold behaves identically to the requested one. NaN (e.g. `Number(unsetEnvVariable)`)\n * survives clamping arithmetic and would also convert to 0, so it is treated as an absent setting\n * instead.\n */\nfunction clampToU32(value: number | undefined): number | undefined {\n return value === undefined || Number.isNaN(value) ? undefined : clamp(Math.trunc(value), 0, 0xFF_FF_FF_FF);\n}\n\n/**\n * Raised when no usable native addon can be loaded. Every measurement fails identically until the\n * addon is built, so callers measuring many files (the CLI scan) treat it as fatal for the whole\n * run instead of recording one \"skipped\" entry per file.\n */\nexport class NativeAddonError extends Error {}\n\nlet cachedBinding: NativeBinding | undefined;\nlet cachedFailure: NativeAddonError | undefined;\n\n/** Replaces the N-API addon, e.g. with the WebAssembly build on runtimes without N-API. */\nexport function setNativeBinding(binding: NativeBinding): void {\n cachedBinding = binding;\n}\n\nfunction loadBinding(): NativeBinding {\n if (cachedBinding) {\n return cachedBinding;\n }\n // The failure is memoized too: resolution (including platformTriplet's diagnostic-report call\n // on Linux) would otherwise repeat for every measured file of an already-failing run.\n if (cachedFailure) {\n throw cachedFailure;\n }\n // Resolved relative to this file, so both src/ (tests) and dist/ (build) find the addon.\n // node:module is loaded lazily so that runtimes without it can bundle this module.\n const requireNative = process.getBuiltinModule('node:module').createRequire(import.meta.url);\n const specifiers = [\n // A prebuilt platform package, when published for this platform.\n `code-gauge-${platformTriplet()}`,\n // A locally built addon (`bun run build-native`).\n '../native/code-gauge.node',\n ];\n const failures: string[] = [];\n for (const specifier of specifiers) {\n let binding: NativeBinding;\n try {\n binding = requireNative(specifier) as NativeBinding;\n } catch (error) {\n failures.push(` ${specifier}: ${getErrorMessage(error).split('\\n')[0]}`);\n continue;\n }\n const version = binding.payloadVersion?.();\n if (version !== expectedPayloadVersion) {\n failures.push(\n ` ${specifier}: payload version ${version ?? 'unknown'} does not match the expected ` +\n `${expectedPayloadVersion}; rebuild the addon with \\`bun run build-native\\``\n );\n continue;\n }\n cachedBinding = binding;\n return binding;\n }\n cachedFailure = new NativeAddonError(\n `The code-gauge native addon is not available for ${platformTriplet()}. Build it with ` +\n '`node scripts/buildNative.mjs` in the code-gauge package directory (requires a Rust ' +\n 'toolchain); when installing with npm, also allow install scripts for code-gauge so its ' +\n `postinstall build can run.\\n${failures.join('\\n')}`\n );\n throw cachedFailure;\n}\n\n/**\n * The platform-package suffix in the napi-rs naming convention: Linux targets are qualified by\n * libc ABI (`linux-x64-gnu` / `linux-x64-musl`) because a glibc-linked addon cannot load on\n * Alpine/musl, and Windows by toolchain ABI (`win32-x64-msvc`), matching what napi-rs tooling\n * generates. Must match scripts/installNative.mjs and the build-native workflow's target list.\n */\nfunction platformTriplet(): string {\n const base = `${process.platform}-${process.arch}`;\n if (process.platform === 'win32') {\n return `${base}-msvc`;\n }\n if (process.platform !== 'linux') {\n return base;\n }\n // Musl builds of Node report no glibc runtime version; see napi-rs's isMusl detection.\n const report = process.report?.getReport() as { header?: { glibcVersionRuntime?: string } } | undefined;\n return report?.header?.glibcVersionRuntime ? `${base}-gnu` : `${base}-musl`;\n}\n"],"mappings":"qEAmEA,SAAgB,EACd,EACA,EACA,EACA,EACA,EAAuB,GACD,CACtB,OAAO,KAAK,MACV,EAAY,CAAC,CAAC,kBACZ,GAAG,EAAyB,EAAM,EAAU,EAAmB,EAAa,CAAoB,CAClG,CACF,CACF,CAMA,SAAgB,EACd,EACA,EACA,EACA,EACA,EAAuB,GACQ,CAC/B,OAAO,EAAY,CAAC,CACjB,uBACC,GAAG,EAAyB,EAAM,EAAU,EAAmB,EAAa,CAAoB,CAClG,CAAC,CACA,KAAM,GAAS,KAAK,MAAM,CAAI,CAAyB,CAC5D,CAGA,SAAS,EACP,EACA,EACA,EACA,EACA,EACwB,CACxB,MAAO,CACL,EAAa,CAAI,EACjB,EACA,EACA,EAAW,GAAa,SAAS,EACjC,EAAW,GAAa,YAAY,EACpC,EAAW,GAAa,oBAAoB,EAC5C,CACF,CACF,CAGA,SAAgB,EACd,EACA,EACA,EAC4B,CAC5B,OAAO,KAAK,MACV,EAAY,CAAC,CAAC,2BAA2B,EAAa,CAAI,EAAG,EAAU,EAAW,CAAS,CAAC,CAC9F,CACF,CAGA,SAAgB,EAAoC,EAAc,EAAgC,CAIhG,OA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a,SAIV,QAAQ,QAAQ,UAAU,EAAA,EAC1B,QAAQ,oBAAsB,GAAG,EAAK,MAAQ,GAAG,EAAK,OAJ5D,CAKX"}
|
|
1
|
+
{"version":3,"file":"nativeMetrics.js","names":[],"sources":["../src/nativeMetrics.ts"],"sourcesContent":["import { clamp, getErrorMessage } from '@willbooster/shared-lib';\nimport type { CrossFileDuplicateCandidate, Token, TokenRange } from './duplication.js';\nimport type { CodeMetrics, DuplicationOptions, FunctionMetrics } from './types.js';\n\n/**\n * Halstead counts measured natively; the derived float metrics (volume, effort, ...) are\n * computed in TypeScript because they involve transcendental functions (log2) whose last-bit\n * results can differ between V8 and Rust's libm, and results must not depend on the Rust side's\n * libm build.\n */\nexport interface NativeHalsteadCounts {\n distinctOperators: number;\n distinctOperands: number;\n totalOperators: number;\n totalOperands: number;\n}\n\nexport interface NativeFunctionMetricsPayload extends Omit<FunctionMetrics, 'halstead'> {\n halsteadCounts: NativeHalsteadCounts;\n}\n\nexport interface NativeMetricsPayload extends Omit<CodeMetrics, 'halstead' | 'functions' | 'syntaxTree'> {\n functions: NativeFunctionMetricsPayload[];\n halsteadCounts: NativeHalsteadCounts;\n syntaxTree?: string;\n crossFileData?: NativeCrossFileDataPayload;\n}\n\n/** One file's cross-file clone-detection contribution as serialized by the native addon. */\nexport interface NativeCrossFileDataPayload {\n candidates: CrossFileDuplicateCandidate[];\n tokens: Token[];\n containerStatements: TokenRange[][];\n nearMissBlocks: TokenRange[];\n /** 1-based lines that are neither blank nor comment-only, sorted ascending. */\n codeLineNumbers: number[];\n}\n\ntype NativeMeasureArguments = [\n code: string,\n language: string,\n includeSyntaxTree: boolean,\n minTokens: number | undefined,\n maxGapTokens: number | undefined,\n minSimilarityPercent: number | undefined,\n includeCrossFileData: boolean,\n];\n\nexport interface NativeBinding {\n measureCodeNative(...args: NativeMeasureArguments): string;\n measureCodeNativeAsync(...args: NativeMeasureArguments): Promise<string>;\n collectCrossFileDataNative(code: string, language: string, minTokens?: number): string;\n collectFunctionTokenSequencesNative(code: string, language: string): string;\n payloadVersion?(): number;\n}\n\n/**\n * Must equal `payload_version` in native/src/lib.rs. A previously built addon survives a\n * `git pull` untouched, so without this handshake it would silently return payloads missing\n * newer fields, or lack newer binding functions, instead of failing with a clear rebuild message.\n */\nexport const expectedPayloadVersion = 8;\n\n/**\n * Measures one file via the native addon, returning the raw payload for assembly in metrics.ts;\n * with `includeCrossFileData`, the payload also carries the file's cross-file contribution.\n */\nexport function measureCodeNative(\n code: string,\n language: string,\n includeSyntaxTree: boolean,\n duplication?: DuplicationOptions,\n includeCrossFileData = false\n): NativeMetricsPayload {\n return JSON.parse(\n loadBinding().measureCodeNative(\n ...toNativeMeasureArguments(code, language, includeSyntaxTree, duplication, includeCrossFileData)\n )\n ) as NativeMetricsPayload;\n}\n\n/**\n * measureCodeNative on the addon's worker threads, so several files can be measured in parallel.\n * A missing addon still throws synchronously, like measureCodeNative.\n */\nexport function measureCodeNativeAsync(\n code: string,\n language: string,\n includeSyntaxTree: boolean,\n duplication?: DuplicationOptions,\n includeCrossFileData = false\n): Promise<NativeMetricsPayload> {\n return loadBinding()\n .measureCodeNativeAsync(\n ...toNativeMeasureArguments(code, language, includeSyntaxTree, duplication, includeCrossFileData)\n )\n .then((json) => JSON.parse(json) as NativeMetricsPayload);\n}\n\n/** The binding arguments shared by the sync and async measurements, so both measure alike. */\nfunction toNativeMeasureArguments(\n code: string,\n language: string,\n includeSyntaxTree: boolean,\n duplication: DuplicationOptions | undefined,\n includeCrossFileData: boolean\n): NativeMeasureArguments {\n return [\n toWellFormed(code),\n language,\n includeSyntaxTree,\n clampToU32(duplication?.minTokens),\n clampToU32(duplication?.maxGapTokens),\n clampToU32(duplication?.minSimilarityPercent),\n includeCrossFileData,\n ];\n}\n\n/** Collects one file's cross-file clone-detection contribution via the native addon. */\nexport function collectCrossFileDataNative(\n code: string,\n language: string,\n minTokens?: number\n): NativeCrossFileDataPayload {\n return JSON.parse(\n loadBinding().collectCrossFileDataNative(toWellFormed(code), language, clampToU32(minTokens))\n ) as NativeCrossFileDataPayload;\n}\n\n/** Collects normalized token hash sequences of every function via the native addon. */\nexport function collectFunctionTokenSequencesNative(code: string, language: string): Int32Array[] {\n const sequences = JSON.parse(\n loadBinding().collectFunctionTokenSequencesNative(toWellFormed(code), language)\n ) as number[][];\n return sequences.map((sequence) => Int32Array.from(sequence));\n}\n\n/**\n * Lone surrogates cannot cross the N-API boundary losslessly, so ill-formed strings (invalid\n * UTF-16 occasionally present in real-world files) are measured with U+FFFD replacements — the\n * same code units V8's own UTF-8 conversion would substitute.\n */\nfunction toWellFormed(code: string): string {\n return code.isWellFormed() ? code : code.toWellFormed();\n}\n\n/**\n * The duplication settings cross the boundary as u32, whose JavaScript conversion wraps modulo\n * 2^32 (2 ** 32 would become 0 and match everything). The public API accepts any safe integer, so\n * out-of-range values clamp to [0, u32::MAX] — no source can hold 2^32 tokens, so a clamped\n * threshold behaves identically to the requested one. NaN (e.g. `Number(unsetEnvVariable)`)\n * survives clamping arithmetic and would also convert to 0, so it is treated as an absent setting\n * instead.\n */\nfunction clampToU32(value: number | undefined): number | undefined {\n return value === undefined || Number.isNaN(value) ? undefined : clamp(Math.trunc(value), 0, 0xFF_FF_FF_FF);\n}\n\n/**\n * Raised when no usable native addon can be loaded. Every measurement fails identically until the\n * addon is built, so callers measuring many files (the CLI scan) treat it as fatal for the whole\n * run instead of recording one \"skipped\" entry per file.\n */\nexport class NativeAddonError extends Error {}\n\nlet cachedBinding: NativeBinding | undefined;\nlet cachedFailure: NativeAddonError | undefined;\n\n/** Replaces the N-API addon, e.g. with the WebAssembly build on runtimes without N-API. */\nexport function setNativeBinding(binding: NativeBinding): void {\n cachedBinding = binding;\n}\n\nfunction loadBinding(): NativeBinding {\n if (cachedBinding) {\n return cachedBinding;\n }\n // The failure is memoized too: resolution (including platformTriplet's diagnostic-report call\n // on Linux) would otherwise repeat for every measured file of an already-failing run.\n if (cachedFailure) {\n throw cachedFailure;\n }\n // Resolved relative to this file, so both src/ (tests) and dist/ (build) find the addon.\n // node:module is loaded lazily so that runtimes without it can bundle this module.\n const requireNative = process.getBuiltinModule('node:module').createRequire(import.meta.url);\n const specifiers = [\n // A prebuilt platform package, when published for this platform.\n `code-gauge-${platformTriplet()}`,\n // A locally built addon (`bun run build-native`).\n '../native/code-gauge.node',\n ];\n const failures: string[] = [];\n for (const specifier of specifiers) {\n let binding: NativeBinding;\n try {\n binding = requireNative(specifier) as NativeBinding;\n } catch (error) {\n failures.push(` ${specifier}: ${getErrorMessage(error).split('\\n')[0]}`);\n continue;\n }\n const version = binding.payloadVersion?.();\n if (version !== expectedPayloadVersion) {\n failures.push(\n ` ${specifier}: payload version ${version ?? 'unknown'} does not match the expected ` +\n `${expectedPayloadVersion}; rebuild the addon with \\`bun run build-native\\``\n );\n continue;\n }\n cachedBinding = binding;\n return binding;\n }\n cachedFailure = new NativeAddonError(\n `The code-gauge native addon is not available for ${platformTriplet()}. Build it with ` +\n '`node scripts/buildNative.mjs` in the code-gauge package directory (requires a Rust ' +\n `toolchain).\\n${failures.join('\\n')}`\n );\n throw cachedFailure;\n}\n\n/**\n * The platform-package suffix in the napi-rs naming convention: Linux targets are qualified by\n * libc ABI (`linux-x64-gnu` / `linux-x64-musl`) because a glibc-linked addon cannot load on\n * Alpine/musl, and Windows by toolchain ABI (`win32-x64-msvc`), matching what napi-rs tooling\n * generates. Must match scripts/installNative.mjs and the build-native workflow's target list.\n */\nfunction platformTriplet(): string {\n const base = `${process.platform}-${process.arch}`;\n if (process.platform === 'win32') {\n return `${base}-msvc`;\n }\n if (process.platform !== 'linux') {\n return base;\n }\n // Musl builds of Node report no glibc runtime version; see napi-rs's isMusl detection.\n const report = process.report?.getReport() as { header?: { glibcVersionRuntime?: string } } | undefined;\n return report?.header?.glibcVersionRuntime ? `${base}-gnu` : `${base}-musl`;\n}\n"],"mappings":"qEAmEA,SAAgB,EACd,EACA,EACA,EACA,EACA,EAAuB,GACD,CACtB,OAAO,KAAK,MACV,EAAY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EAAa,CAEjB,cAAc,EAAgB,IAE9B,2BACF,EACM,EAAqB,CAAC,EAC5B,IAAK,IAAM,KAAa,EAAY,CAClC,IAAI,EACJ,GAAI,CACF,EAAU,EAAc,CAAS,CACnC,OAAS,EAAO,CACd,EAAS,KAAK,KAAK,EAAU,IAAI,EAAgB,CAAK,CAAC,CAAC,MAAM;CAAI,CAAC,CAAC,IAAI,EACxE,QACF,CACA,IAAM,EAAU,EAAQ,iBAAiB,EACzC,GAAI,IAAA,EAAoC,CACtC,EAAS,KACP,KAAK,EAAU,oBAAoB,GAAW,UAAU,gFAE1D,EACA,QACF,CAEA,MADA,GAAgB,EACT,CACT,CAMA,KALA,GAAgB,IAAI,EAClB,oDAAoD,EAAgB,EAAE,qHAEpD,EAAS,KAAK;CAAI,GACtC,EACM,CACR,CAQA,SAAS,GAA0B,CACjC,IAAM,EAAO,GAAG,QAAQ,SAAS,GAAG,QAAQ,OAS5C,OARI,QAAQ,WAAa,QAChB,GAAG,EAAK,OAEb,QAAQ,WAAa,SAIV,QAAQ,QAAQ,UAAU,EAAA,EAC1B,QAAQ,oBAAsB,GAAG,EAAK,MAAQ,GAAG,EAAK,OAJ5D,CAKX"}
|
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("./languages.cjs"),r=require("./nativeMetrics.cjs"),i=require("./metrics.cjs");let a=require("@willbooster/shared-lib"),o=require("node:fs/promises"),s=require("node:path");s=e.__toESM(s,1);let c=require("node:os");c=e.__toESM(c,1);const l=/* @__PURE__ */ 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`]),u=/* @__PURE__ */ new Set([`__tests__`,`test`,`tests`,`spec`]),d=/(?:^test(?:[_-].*)?|\.(?:spec|test)|[_-](?:test|spec))\.[^.]+$/iu,f=/Tests?\.(?:java|kt|cs)$/u;function p(e){return e===`~`?c.default.homedir():e.startsWith(`~/`)?s.default.join(c.default.homedir(),e.slice(2)):s.default.resolve(e)}async function m(e){try{return(await(0,o.stat)(e)).isDirectory()?e:s.default.dirname(e)}catch{return s.default.dirname(e)}}const h=c.default.availableParallelism()*2;async function g(e,t){let n=e;try{n=await(0,o.realpath)(e)}catch{}let r=s.default.dirname(n),i;try{i=await(0,o.stat)(n)}catch(e){let t=`${L(n,r)}: ${(0,a.getErrorMessage)(e)}`;return{displayRoot:r,files:[],errors:[t],warnings:[],generatedFiles:[],fatalError:t}}if(i.isFile()){let e=s.default.dirname(n),r=I(n,t,!0);if(!r){let t=`${L(n,e)}: unsupported file type`;return{displayRoot:e,files:[],errors:[t],warnings:[],generatedFiles:[],fatalError:t}}let i=x(t,e);return await O(n,r,`single-file`,i,n),b(i,e)}let c=x(t,n);return await T(n,c),await v(c),b(c,n)}async function _(e,t,n,r=/* @__PURE__ */ new Set){let
|
|
1
|
+
"use strict";const e=require("./_virtual/_rolldown/runtime.cjs"),t=require("./crossFileDuplication.cjs"),n=require("./languages.cjs"),r=require("./nativeMetrics.cjs"),i=require("./metrics.cjs");let a=require("@willbooster/shared-lib"),o=require("node:fs/promises"),s=require("node:path");s=e.__toESM(s,1);let c=require("node:os");c=e.__toESM(c,1);const l=/* @__PURE__ */ 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`]),u=/* @__PURE__ */ new Set([`__tests__`,`test`,`tests`,`spec`]),d=/(?:^test(?:[_-].*)?|\.(?:spec|test)|[_-](?:test|spec))\.[^.]+$/iu,f=/Tests?\.(?:java|kt|cs)$/u;function p(e){return e===`~`?c.default.homedir():e.startsWith(`~/`)?s.default.join(c.default.homedir(),e.slice(2)):s.default.resolve(e)}async function m(e){try{return(await(0,o.stat)(e)).isDirectory()?e:s.default.dirname(e)}catch{return s.default.dirname(e)}}const h=c.default.availableParallelism()*2;async function g(e,t){let n=e;try{n=await(0,o.realpath)(e)}catch{}let r=s.default.dirname(n),i;try{i=await(0,o.stat)(n)}catch(e){let t=`${L(n,r)}: ${(0,a.getErrorMessage)(e)}`;return{displayRoot:r,files:[],errors:[t],warnings:[],generatedFiles:[],fatalError:t}}if(i.isFile()){let e=s.default.dirname(n),r=I(n,t,!0);if(!r){let t=`${L(n,e)}: unsupported file type`;return{displayRoot:e,files:[],errors:[t],warnings:[],generatedFiles:[],fatalError:t}}let i=x(t,e);return await O(n,r,`single-file`,i,n),b(i,e)}let c=x(t,n);return await T(n,c),await v(c),b(c,n)}async function _(e,t,n,r=/* @__PURE__ */ new Set,i=``){let a=x(n,e),c=i===``?``:`${i}/`;for(let i of t){let t=s.default.join(e,i),l=F(i.startsWith(c)?i.slice(c.length):i,n,r.has(t))?I(i,n,r.has(t)):void 0;if(!l)continue;let u=await(0,o.lstat)(t).catch(()=>{});(!u||u.isFile())&&a.candidates.push({file:t,language:l})}return await v(a),b(a,e)}async function v(e){let t=await e.options.loadExclusion?.(e.candidates.flatMap(({file:e,realFile:t})=>t===void 0?[e]:[e,t]));e.exclusion=t;let n=/* @__PURE__ */ new Map;for(let t of e.candidates){let r;try{r=t.realFile??await(0,o.realpath)(t.file)}catch(n){S(e,t.file,n);continue}n.set(r,[...n.get(r)??[],t])}for(let[r,i]of n){if(e.fatalSeen)return;let n=await y(r,i,t);n!==void 0&&await O(n.file,n.language,`directory`,e,r)}}async function y(e,t,n){if(n===void 0)return t[0];if(n.isExcludedPath(e))return;let r=t.filter(({file:e})=>!n.isExcludedPath(e)),i=r.find(({file:t})=>t===e);if(i!==void 0||r.length<=1)return i??r[0];let a=await(0,o.readFile)(e,`utf8`).catch(()=>{});return r.find(({file:e})=>a!==void 0&&!n.isGeneratedCode(e,a))??r[0]}async function b(e,t){let n=[],r=[],i=[],o=[];for(let s of e.outcomes){let e=await s;if(`fatal`in e){let s=(0,a.getErrorMessage)(e.fatal);return{displayRoot:t,files:n,errors:[...r,s],warnings:i,generatedFiles:o,fatalError:s}}if(`generatedFile`in e){o.push(e.generatedFile);continue}if(`error`in e){r.push(e.error);continue}n.push(e.file),e.warning!==void 0&&i.push(e.warning)}return{displayRoot:t,files:n,errors:r,warnings:i,generatedFiles:o}}function x(e,t){return{options:e,outcomes:[],inFlight:/* @__PURE__ */ new Set,fatalSeen:!1,visitedDirectories:/* @__PURE__ */ new Set,visitedFiles:/* @__PURE__ */ new Set,rootDirectory:t,candidates:[]}}function S(e,t,n){e.outcomes.push({error:`${L(t,e.rootDirectory)}: ${(0,a.getErrorMessage)(n)}`})}async function C(e,t,n){try{return await e()}catch(e){S(n,t,e);return}}async function w(e,t){let n=await C(()=>(0,o.realpath)(e),e,t);return n!==void 0&&P(n,t.rootDirectory)?n:void 0}async function T(e,t){let n=await w(e,t);if(n===void 0||t.visitedDirectories.has(n))return;t.visitedDirectories.add(n);let r=await C(()=>(0,o.readdir)(e,{withFileTypes:!0}),e,t);if(r!==void 0){r.sort((e,t)=>e.name<t.name?-1:+(e.name>t.name));for(let i of r){let r=s.default.join(e,i.name);if(i.isSymbolicLink()){await E(i.name,r,t);continue}if(i.isDirectory()){if(N(i.name,t.options))continue;await T(r,t);continue}i.isFile()&&D(r,t,r,n===e?void 0:s.default.join(n,i.name))}}}async function E(e,t,n){let r=await w(t,n);if(r===void 0)return;let i=await C(()=>(0,o.stat)(t),t,n);if(i!==void 0){if(i.isDirectory()){if(N(e,n.options)||N(s.default.basename(r),n.options))return;await T(t,n);return}i.isFile()&&D(t,n,r,r)}}function D(e,t,n=e,r){let i=I(n,t.options);i&&t.candidates.push({file:e,language:i,realFile:r})}async function O(e,t,n,r,i){if(r.fatalSeen)return;let a;try{a=i??await(0,o.realpath)(e)}catch(t){S(r,e,t);return}if(r.visitedFiles.has(a))return;for(r.visitedFiles.add(a);r.inFlight.size>=h;)await Promise.race(r.inFlight);let s=k(e,a,t,n,r);r.inFlight.add(s),s.then(()=>r.inFlight.delete(s)),r.outcomes.push(s)}async function k(e,t,n,s,c){try{let r=await(0,o.readFile)(e,`utf8`),a={language:n,duplication:c.options.duplication};if(s===`single-file`)return{file:{file:e,metrics:i.measureCode(r,a)}};let l=c.exclusion;if(l&&(l.isGeneratedCode(e,r)||l.isGeneratedCode(t,r)))return{generatedFile:e};let{metrics:u,crossFileData:d,crossFileError:f}=await A(r,a);return{file:{file:e,metrics:u,duplicationCandidates:d},warning:f===void 0?void 0:`${L(e,c.rootDirectory)}: cross-file duplication candidates unavailable: ${f}`}}catch(t){return t instanceof r.NativeAddonError?(c.fatalSeen=!0,{fatal:t}):{error:`${L(e,c.rootDirectory)}: ${(0,a.getErrorMessage)(t)}`}}}async function A(e,t){try{return await i.measureCodeWithCrossFileDataAsync(e,t)}catch(n){if(n instanceof r.NativeAddonError)throw n;return{metrics:i.measureCode(e,t),crossFileError:(0,a.getErrorMessage)(n)}}}function j(e,n){if(e.fatalError||e.files.length<2)return;let r=e.files.flatMap(({file:t,duplicationCandidates:n})=>n?[{file:L(t,e.displayRoot),...n}]:[]);r.length<2||(e.crossFileDuplication=t.measureCrossFileDuplication(r,n.duplication))}function M(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 N(e,t){return l.has(e)?!0:!t.includeTests&&u.has(e)}function P(e,t){let n=s.default.relative(t,e);return n===``||n!==`..`&&!n.startsWith(`..${s.default.sep}`)&&!s.default.isAbsolute(n)}function F(e,t,n=!1){if(n)return I(e,t,!0)!==void 0;let r=e.split(`/`);for(let e of r.slice(0,-1))if(l.has(e)||!t.includeTests&&u.has(e))return!1;return I(e,t)!==void 0}function I(e,t,r=!1){let i=e.toLowerCase();if(!(!r&&(i.endsWith(`.d.ts`)||i.endsWith(`.d.mts`)||i.endsWith(`.d.cts`)||i.endsWith(`.min.js`)||i.endsWith(`.pnp.cjs`)))&&(r||t.includeTests||!d.test(s.default.basename(e))&&!f.test(s.default.basename(e))))return n.detectLanguage(e)}function L(e,t){return s.default.relative(t,e).replaceAll(s.default.sep,`/`)||s.default.basename(e)}function R(e){process.stdout.write(e)}function z(e){process.stderr.write(e)}exports.addCrossFileDuplication=j,exports.collectDuplicatedLineNumbers=M,exports.configSearchDirectory=m,exports.formatPath=L,exports.getLanguage=I,exports.isWithinDirectory=P,exports.resolveTarget=p,exports.scanListedFiles=_,exports.scanTarget=g,exports.writeStderr=z,exports.writeStdout=R;
|
|
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","getErrorMessage","lstat","readFile","readdir","measureCode","NativeAddonError","measureCodeWithCrossFileDataAsync","measureCrossFileDuplication","detectLanguage"],"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 { getErrorMessage } from '@willbooster/shared-lib';\nimport { measureCrossFileDuplication, type CrossFileDuplicationMetrics } from './crossFileDuplication.js';\nimport type { CrossFileDuplicationFileData } from './duplication.js';\nimport type { Exclusion } from './exclusion.js';\nimport { detectLanguage } from './languages.js';\nimport { measureCode, measureCodeWithCrossFileDataAsync } from './metrics.js';\nimport { NativeAddonError } from './nativeMetrics.js';\nimport type { CodeMetrics, DuplicationOptions, LanguageName, MeasureOptions } 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 * Loads the exclusion covering the files a directory scan found (absolute paths); an explicitly\n * targeted file is always measured.\n */\n loadExclusion?: (absolutePaths: readonly string[]) => Promise<Exclusion>;\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 /** Files skipped because their content is generated code (see Exclusion.isGeneratedCode). */\n generatedFiles: string[];\n fatalError?: string;\n files: FileMetrics[];\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 /**\n * Outcomes in discovery order. Files are measured concurrently, so a measurement is recorded as\n * a promise here and applied in this order once all have settled, keeping results deterministic.\n */\n outcomes: (ScanOutcome | Promise<ScanOutcome>)[];\n /** Measurements in flight, bounded so file contents and payloads do not pile up. */\n inFlight: Set<Promise<ScanOutcome>>;\n /** Set once a measurement fails fatally; no further measurement starts. */\n fatalSeen: boolean;\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 /** Files the walk found, measured once the exclusion covering all of them is loaded. */\n candidates: ScanCandidate[];\n exclusion?: Exclusion;\n}\n\ninterface ScanCandidate {\n file: string;\n language: LanguageName;\n /** The resolved path when the file was reached through a symbolic link. */\n realFile?: string;\n}\n\n/**\n * A missing native addon fails every file identically, so it ends the scan as one fatal error\n * instead of one \"skipped\" entry per file behind a successful exit code.\n */\ntype ScanOutcome =\n | { file: FileMetrics; warning?: string }\n | { generatedFile: string }\n | { error: string }\n | { fatal: NativeAddonError };\n\n// Twice the addon's worker count keeps its pool busy while finished payloads are parsed.\nconst maxMeasurementsInFlight = os.availableParallelism() * 2;\n\nexport async function scanTarget(target: string, options: ScanOptions): Promise<ScanResult> {\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)}: ${getErrorMessage(error)}`;\n return {\n displayRoot: fallbackDisplayRoot,\n files: [],\n errors: [fatalError],\n warnings: [],\n generatedFiles: [],\n fatalError,\n };\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: [], generatedFiles: [], fatalError };\n }\n\n const context = makeScanContext(options, displayRoot);\n await measureFile(canonicalTarget, language, 'single-file', context, canonicalTarget);\n return settleScan(context, displayRoot);\n }\n\n const context = makeScanContext(options, canonicalTarget);\n await scanDirectory(canonicalTarget, context);\n await measureCandidates(context);\n return settleScan(context, canonicalTarget);\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 explicitFiles: ReadonlySet<string> = new Set()\n): Promise<ScanResult> {\n const context = makeScanContext(options, rootDirectory);\n for (const relativePath of relativePaths) {\n const absolutePath = path.join(rootDirectory, relativePath);\n const language = isScannedPath(relativePath, options, explicitFiles.has(absolutePath))\n ? getLanguage(relativePath, options, explicitFiles.has(absolutePath))\n : undefined;\n if (!language) {\n continue;\n }\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 context.candidates.push({ file: absolutePath, language });\n }\n }\n await measureCandidates(context);\n return settleScan(context, rootDirectory);\n}\n\nasync function measureCandidates(context: ScanContext): Promise<void> {\n const exclusion = await context.options.loadExclusion?.(\n context.candidates.flatMap(({ file, realFile }) => (realFile === undefined ? [file] : [file, realFile]))\n );\n context.exclusion = exclusion;\n // Every path reaching the same real file, in discovery order, so one alias cannot decide alone.\n const pathsByRealFile = new Map<string, ScanCandidate[]>();\n for (const candidate of context.candidates) {\n let realFile;\n try {\n realFile = candidate.realFile ?? (await realpath(candidate.file));\n } catch (error) {\n recordError(context, candidate.file, error);\n continue;\n }\n pathsByRealFile.set(realFile, [...(pathsByRealFile.get(realFile) ?? []), candidate]);\n }\n for (const [realFile, candidates] of pathsByRealFile) {\n if (context.fatalSeen) {\n return;\n }\n const chosen = await chooseMeasuredPath(realFile, candidates, exclusion);\n if (chosen !== undefined) {\n await measureFile(chosen.file, chosen.language, 'directory', context, realFile);\n }\n }\n}\n\n/**\n * The path to measure a real file through. A path is excluded when its own exclusion or the real\n * file's applies, so the real path, when the scan reached it directly, is never less measurable\n * than an alias; otherwise the first alias not excluded, preferring one whose own attributes do\n * not judge the content generated.\n */\nasync function chooseMeasuredPath(\n realFile: string,\n candidates: readonly ScanCandidate[],\n exclusion: Exclusion | undefined\n): Promise<ScanCandidate | undefined> {\n if (exclusion === undefined) {\n return candidates[0];\n }\n if (exclusion.isExcludedPath(realFile)) {\n return undefined;\n }\n const measurable = candidates.filter(({ file }) => !exclusion.isExcludedPath(file));\n const direct = measurable.find(({ file }) => file === realFile);\n if (direct !== undefined || measurable.length <= 1) {\n return direct ?? measurable[0];\n }\n const code = await readFile(realFile, 'utf8').catch(() => {});\n return measurable.find(({ file }) => code !== undefined && !exclusion.isGeneratedCode(file, code)) ?? measurable[0];\n}\n\n/** Applies the scan's outcomes in discovery order once every measurement has settled. */\nasync function settleScan(context: ScanContext, displayRoot: string): Promise<ScanResult> {\n const files: FileMetrics[] = [];\n const errors: string[] = [];\n const warnings: string[] = [];\n const generatedFiles: string[] = [];\n for (const pending of context.outcomes) {\n const outcome = await pending;\n if ('fatal' in outcome) {\n const fatalError = getErrorMessage(outcome.fatal);\n // Errors the walk recorded before the fatal failure stay reported alongside it.\n return { displayRoot, files, errors: [...errors, fatalError], warnings, generatedFiles, fatalError };\n }\n if ('generatedFile' in outcome) {\n generatedFiles.push(outcome.generatedFile);\n continue;\n }\n if ('error' in outcome) {\n errors.push(outcome.error);\n continue;\n }\n files.push(outcome.file);\n if (outcome.warning !== undefined) {\n warnings.push(outcome.warning);\n }\n }\n return { displayRoot, files, errors, warnings, generatedFiles };\n}\n\nfunction makeScanContext(options: ScanOptions, rootDirectory: string): ScanContext {\n return {\n options,\n outcomes: [],\n inFlight: new Set(),\n fatalSeen: false,\n visitedDirectories: new Set(),\n visitedFiles: new Set(),\n rootDirectory,\n candidates: [],\n };\n}\n\nfunction recordError(context: ScanContext, target: string, error: unknown): void {\n context.outcomes.push({ error: `${formatPath(target, context.rootDirectory)}: ${getErrorMessage(error)}` });\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 recordError(context, target, 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 // readdir order differs between file systems; sorting keeps which path reaches a file first,\n // and so the scan's result, the same everywhere.\n entries.sort((left, right) => (left.name < right.name ? -1 : left.name > right.name ? 1 : 0));\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 // Under a symbolically linked directory the real path differs, and exclusion checks both.\n const realFile = resolvedDirectory === directory ? undefined : path.join(resolvedDirectory, entry.name);\n collectScannableFile(entryPath, context, entryPath, realFile);\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 collectScannableFile(entryPath, context, resolvedPath, resolvedPath);\n }\n}\n\nfunction collectScannableFile(file: string, context: ScanContext, languageFile = file, realFile?: string): void {\n const language = getLanguage(languageFile, context.options);\n if (language) {\n context.candidates.push({ file, language, realFile });\n }\n}\n\n/**\n * Resolves and deduplicates the file in discovery order, then starts measuring it concurrently; its\n * outcome is recorded in discovery order (see ScanContext.outcomes).\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 if (context.fatalSeen) {\n return;\n }\n let resolvedFile;\n try {\n resolvedFile = realFile ?? (await realpath(file));\n } catch (error) {\n recordError(context, file, error);\n return;\n }\n if (context.visitedFiles.has(resolvedFile)) {\n return;\n }\n context.visitedFiles.add(resolvedFile);\n\n // Any settled measurement frees its slot (removed by the callback below, which runs before the\n // race resumes), so one slow file never idles the pool.\n while (context.inFlight.size >= maxMeasurementsInFlight) {\n await Promise.race(context.inFlight);\n }\n const outcome = readAndMeasureFile(file, resolvedFile, language, mode, context);\n context.inFlight.add(outcome);\n void outcome.then(() => context.inFlight.delete(outcome));\n context.outcomes.push(outcome);\n}\n\nasync function readAndMeasureFile(\n file: string,\n resolvedFile: string,\n language: LanguageName,\n mode: 'single-file' | 'directory',\n context: ScanContext\n): Promise<ScanOutcome> {\n try {\n const code = await readFile(file, 'utf8');\n const measureOptions = { language, duplication: context.options.duplication };\n // Only directory scans compare files against each other; a single-file target has no peers.\n if (mode === 'single-file') {\n return { file: { file, metrics: measureCode(code, measureOptions) } };\n }\n // Like path exclusion, either the scanned path or the real one can judge the code generated.\n const exclusion = context.exclusion;\n if (exclusion && (exclusion.isGeneratedCode(file, code) || exclusion.isGeneratedCode(resolvedFile, code))) {\n return { generatedFile: file };\n }\n const { metrics, crossFileData, crossFileError } = await measureWithCrossFileData(code, measureOptions);\n return {\n file: { file, metrics, duplicationCandidates: crossFileData },\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 warning:\n crossFileError === undefined\n ? undefined\n : `${formatPath(file, context.rootDirectory)}: cross-file duplication candidates unavailable: ${crossFileError}`,\n };\n } catch (error) {\n if (error instanceof NativeAddonError) {\n context.fatalSeen = true;\n return { fatal: error };\n }\n return { error: `${formatPath(file, context.rootDirectory)}: ${getErrorMessage(error)}` };\n }\n}\n\n/**\n * Measures a file together with its cross-file contribution from one parse. The contribution is\n * auxiliary: if collecting it fails where plain measurement succeeds (e.g. a payload too large to\n * cross the addon boundary), the metrics are still returned with the failure message, which\n * callers report as a warning rather than an error.\n */\nexport async function measureWithCrossFileData(\n code: string,\n measureOptions: MeasureOptions\n): Promise<{ metrics: CodeMetrics; crossFileData?: CrossFileDuplicationFileData; crossFileError?: string }> {\n try {\n return await measureCodeWithCrossFileDataAsync(code, measureOptions);\n } catch (error) {\n if (error instanceof NativeAddonError) {\n throw error;\n }\n return { metrics: measureCode(code, measureOptions), crossFileError: getErrorMessage(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. An explicitly targeted file only needs a supported\n * language, as in the ranking command.\n */\nexport function isScannedPath(relativePath: string, options: ScanOptions, explicitTarget = false): boolean {\n if (explicitTarget) {\n return getLanguage(relativePath, options, true) !== undefined;\n }\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 return detectLanguage(file);\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"],"mappings":"2VA0CA,MAAM,kBAAwB,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,kBAAqB,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,QAAQ,CAAM,CAC5B,CAGA,eAAsB,EAAsB,EAAiC,CAC3E,GAAI,CAEF,OAAO,MAAA,EADkBC,EAAAA,KAAAA,CAAK,CAAM,EAAA,CAClB,YAAY,EAAI,EAASD,EAAAA,QAAK,QAAQ,CAAM,CAChE,MAAQ,CACN,OAAOA,EAAAA,QAAK,QAAQ,CAAM,CAC5B,CACF,CAy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S,SAAS,GAC5B,EAAU,SAAS,UAAU,MAM9B,GACA,EAAQ,cACR,GAAgB,KAAKA,EAAAA,QAAK,SAAS,CAAI,CAAC,GAAK,GAAsB,KAAKA,EAAAA,QAAK,SAAS,CAAI,CAAC,GAK9F,OAAOW,EAAAA,eAAe,CAAI,CAC5B,CAEA,SAAgB,EAAW,EAAc,EAAsB,CAC7D,OAAOX,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"}
|
|
1
|
+
{"version":3,"file":"scan.cjs","names":["os","path","stat","realpath","getErrorMessage","lstat","readFile","readdir","measureCode","NativeAddonError","measureCodeWithCrossFileDataAsync","measureCrossFileDuplication","detectLanguage"],"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 { getErrorMessage } from '@willbooster/shared-lib';\nimport { measureCrossFileDuplication, type CrossFileDuplicationMetrics } from './crossFileDuplication.js';\nimport type { CrossFileDuplicationFileData } from './duplication.js';\nimport type { Exclusion } from './exclusion.js';\nimport { detectLanguage } from './languages.js';\nimport { measureCode, measureCodeWithCrossFileDataAsync } from './metrics.js';\nimport { NativeAddonError } from './nativeMetrics.js';\nimport type { CodeMetrics, DuplicationOptions, LanguageName, MeasureOptions } 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 * Loads the exclusion covering the files a directory scan found (absolute paths); an explicitly\n * targeted file is always measured.\n */\n loadExclusion?: (absolutePaths: readonly string[]) => Promise<Exclusion>;\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 /** Files skipped because their content is generated code (see Exclusion.isGeneratedCode). */\n generatedFiles: string[];\n fatalError?: string;\n files: FileMetrics[];\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 /**\n * Outcomes in discovery order. Files are measured concurrently, so a measurement is recorded as\n * a promise here and applied in this order once all have settled, keeping results deterministic.\n */\n outcomes: (ScanOutcome | Promise<ScanOutcome>)[];\n /** Measurements in flight, bounded so file contents and payloads do not pile up. */\n inFlight: Set<Promise<ScanOutcome>>;\n /** Set once a measurement fails fatally; no further measurement starts. */\n fatalSeen: boolean;\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 /** Files the walk found, measured once the exclusion covering all of them is loaded. */\n candidates: ScanCandidate[];\n exclusion?: Exclusion;\n}\n\ninterface ScanCandidate {\n file: string;\n language: LanguageName;\n /** The resolved path when the file was reached through a symbolic link. */\n realFile?: string;\n}\n\n/**\n * A missing native addon fails every file identically, so it ends the scan as one fatal error\n * instead of one \"skipped\" entry per file behind a successful exit code.\n */\ntype ScanOutcome =\n | { file: FileMetrics; warning?: string }\n | { generatedFile: string }\n | { error: string }\n | { fatal: NativeAddonError };\n\n// Twice the addon's worker count keeps its pool busy while finished payloads are parsed.\nconst maxMeasurementsInFlight = os.availableParallelism() * 2;\n\nexport async function scanTarget(target: string, options: ScanOptions): Promise<ScanResult> {\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)}: ${getErrorMessage(error)}`;\n return {\n displayRoot: fallbackDisplayRoot,\n files: [],\n errors: [fatalError],\n warnings: [],\n generatedFiles: [],\n fatalError,\n };\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: [], generatedFiles: [], fatalError };\n }\n\n const context = makeScanContext(options, displayRoot);\n await measureFile(canonicalTarget, language, 'single-file', context, canonicalTarget);\n return settleScan(context, displayRoot);\n }\n\n const context = makeScanContext(options, canonicalTarget);\n await scanDirectory(canonicalTarget, context);\n await measureCandidates(context);\n return settleScan(context, canonicalTarget);\n}\n\n/**\n * Measures an explicit list of repository-relative files (the git-visible ones of `check`) instead\n * of walking the directory tree, so ignored artifact directories are never parsed. Paths outside\n * the scan scope (ignored/test directories, unsupported or test file names) are skipped with the\n * same rules as the walk. Like the walk, which never tests the directory it starts in, the rules\n * apply to a file under `targetDirectory` (repository-relative, forward slashes) by its path below\n * that directory, so naming `vendor` or `test` as the target measures what is in it.\n */\nexport async function scanListedFiles(\n rootDirectory: string,\n relativePaths: Iterable<string>,\n options: ScanOptions,\n explicitFiles: ReadonlySet<string> = new Set(),\n targetDirectory = ''\n): Promise<ScanResult> {\n const context = makeScanContext(options, rootDirectory);\n const targetPrefix = targetDirectory === '' ? '' : `${targetDirectory}/`;\n for (const relativePath of relativePaths) {\n const absolutePath = path.join(rootDirectory, relativePath);\n const scopedPath = relativePath.startsWith(targetPrefix) ? relativePath.slice(targetPrefix.length) : relativePath;\n const language = isScannedPath(scopedPath, options, explicitFiles.has(absolutePath))\n ? getLanguage(relativePath, options, explicitFiles.has(absolutePath))\n : undefined;\n if (!language) {\n continue;\n }\n // Like the walk, only regular files are sources. A symbolic link is not one: git stores only its\n // target string, so measuring through it would diverge from what any revision of the repository\n // contains. Reading a FIFO would block forever. A path lstat cannot inspect stays a candidate so\n // that measuring it reports the error.\n const stats = await lstat(absolutePath).catch(() => {});\n if (!stats || stats.isFile()) {\n context.candidates.push({ file: absolutePath, language });\n }\n }\n await measureCandidates(context);\n return settleScan(context, rootDirectory);\n}\n\nasync function measureCandidates(context: ScanContext): Promise<void> {\n const exclusion = await context.options.loadExclusion?.(\n context.candidates.flatMap(({ file, realFile }) => (realFile === undefined ? [file] : [file, realFile]))\n );\n context.exclusion = exclusion;\n // Every path reaching the same real file, in discovery order, so one alias cannot decide alone.\n const pathsByRealFile = new Map<string, ScanCandidate[]>();\n for (const candidate of context.candidates) {\n let realFile;\n try {\n realFile = candidate.realFile ?? (await realpath(candidate.file));\n } catch (error) {\n recordError(context, candidate.file, error);\n continue;\n }\n pathsByRealFile.set(realFile, [...(pathsByRealFile.get(realFile) ?? []), candidate]);\n }\n for (const [realFile, candidates] of pathsByRealFile) {\n if (context.fatalSeen) {\n return;\n }\n const chosen = await chooseMeasuredPath(realFile, candidates, exclusion);\n if (chosen !== undefined) {\n await measureFile(chosen.file, chosen.language, 'directory', context, realFile);\n }\n }\n}\n\n/**\n * The path to measure a real file through. A path is excluded when its own exclusion or the real\n * file's applies, so the real path, when the scan reached it directly, is never less measurable\n * than an alias; otherwise the first alias not excluded, preferring one whose own attributes do\n * not judge the content generated.\n */\nasync function chooseMeasuredPath(\n realFile: string,\n candidates: readonly ScanCandidate[],\n exclusion: Exclusion | undefined\n): Promise<ScanCandidate | undefined> {\n if (exclusion === undefined) {\n return candidates[0];\n }\n if (exclusion.isExcludedPath(realFile)) {\n return undefined;\n }\n const measurable = candidates.filter(({ file }) => !exclusion.isExcludedPath(file));\n const direct = measurable.find(({ file }) => file === realFile);\n if (direct !== undefined || measurable.length <= 1) {\n return direct ?? measurable[0];\n }\n const code = await readFile(realFile, 'utf8').catch(() => {});\n return measurable.find(({ file }) => code !== undefined && !exclusion.isGeneratedCode(file, code)) ?? measurable[0];\n}\n\n/** Applies the scan's outcomes in discovery order once every measurement has settled. */\nasync function settleScan(context: ScanContext, displayRoot: string): Promise<ScanResult> {\n const files: FileMetrics[] = [];\n const errors: string[] = [];\n const warnings: string[] = [];\n const generatedFiles: string[] = [];\n for (const pending of context.outcomes) {\n const outcome = await pending;\n if ('fatal' in outcome) {\n const fatalError = getErrorMessage(outcome.fatal);\n // Errors the walk recorded before the fatal failure stay reported alongside it.\n return { displayRoot, files, errors: [...errors, fatalError], warnings, generatedFiles, fatalError };\n }\n if ('generatedFile' in outcome) {\n generatedFiles.push(outcome.generatedFile);\n continue;\n }\n if ('error' in outcome) {\n errors.push(outcome.error);\n continue;\n }\n files.push(outcome.file);\n if (outcome.warning !== undefined) {\n warnings.push(outcome.warning);\n }\n }\n return { displayRoot, files, errors, warnings, generatedFiles };\n}\n\nfunction makeScanContext(options: ScanOptions, rootDirectory: string): ScanContext {\n return {\n options,\n outcomes: [],\n inFlight: new Set(),\n fatalSeen: false,\n visitedDirectories: new Set(),\n visitedFiles: new Set(),\n rootDirectory,\n candidates: [],\n };\n}\n\nfunction recordError(context: ScanContext, target: string, error: unknown): void {\n context.outcomes.push({ error: `${formatPath(target, context.rootDirectory)}: ${getErrorMessage(error)}` });\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 recordError(context, target, 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 // readdir order differs between file systems; sorting keeps which path reaches a file first,\n // and so the scan's result, the same everywhere.\n entries.sort((left, right) => (left.name < right.name ? -1 : left.name > right.name ? 1 : 0));\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 // Under a symbolically linked directory the real path differs, and exclusion checks both.\n const realFile = resolvedDirectory === directory ? undefined : path.join(resolvedDirectory, entry.name);\n collectScannableFile(entryPath, context, entryPath, realFile);\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 collectScannableFile(entryPath, context, resolvedPath, resolvedPath);\n }\n}\n\nfunction collectScannableFile(file: string, context: ScanContext, languageFile = file, realFile?: string): void {\n const language = getLanguage(languageFile, context.options);\n if (language) {\n context.candidates.push({ file, language, realFile });\n }\n}\n\n/**\n * Resolves and deduplicates the file in discovery order, then starts measuring it concurrently; its\n * outcome is recorded in discovery order (see ScanContext.outcomes).\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 if (context.fatalSeen) {\n return;\n }\n let resolvedFile;\n try {\n resolvedFile = realFile ?? (await realpath(file));\n } catch (error) {\n recordError(context, file, error);\n return;\n }\n if (context.visitedFiles.has(resolvedFile)) {\n return;\n }\n context.visitedFiles.add(resolvedFile);\n\n // Any settled measurement frees its slot (removed by the callback below, which runs before the\n // race resumes), so one slow file never idles the pool.\n while (context.inFlight.size >= maxMeasurementsInFlight) {\n await Promise.race(context.inFlight);\n }\n const outcome = readAndMeasureFile(file, resolvedFile, language, mode, context);\n context.inFlight.add(outcome);\n void outcome.then(() => context.inFlight.delete(outcome));\n context.outcomes.push(outcome);\n}\n\nasync function readAndMeasureFile(\n file: string,\n resolvedFile: string,\n language: LanguageName,\n mode: 'single-file' | 'directory',\n context: ScanContext\n): Promise<ScanOutcome> {\n try {\n const code = await readFile(file, 'utf8');\n const measureOptions = { language, duplication: context.options.duplication };\n // Only directory scans compare files against each other; a single-file target has no peers.\n if (mode === 'single-file') {\n return { file: { file, metrics: measureCode(code, measureOptions) } };\n }\n // Like path exclusion, either the scanned path or the real one can judge the code generated.\n const exclusion = context.exclusion;\n if (exclusion && (exclusion.isGeneratedCode(file, code) || exclusion.isGeneratedCode(resolvedFile, code))) {\n return { generatedFile: file };\n }\n const { metrics, crossFileData, crossFileError } = await measureWithCrossFileData(code, measureOptions);\n return {\n file: { file, metrics, duplicationCandidates: crossFileData },\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 warning:\n crossFileError === undefined\n ? undefined\n : `${formatPath(file, context.rootDirectory)}: cross-file duplication candidates unavailable: ${crossFileError}`,\n };\n } catch (error) {\n if (error instanceof NativeAddonError) {\n context.fatalSeen = true;\n return { fatal: error };\n }\n return { error: `${formatPath(file, context.rootDirectory)}: ${getErrorMessage(error)}` };\n }\n}\n\n/**\n * Measures a file together with its cross-file contribution from one parse. The contribution is\n * auxiliary: if collecting it fails where plain measurement succeeds (e.g. a payload too large to\n * cross the addon boundary), the metrics are still returned with the failure message, which\n * callers report as a warning rather than an error.\n */\nasync function measureWithCrossFileData(\n code: string,\n measureOptions: MeasureOptions\n): Promise<{ metrics: CodeMetrics; crossFileData?: CrossFileDuplicationFileData; crossFileError?: string }> {\n try {\n return await measureCodeWithCrossFileDataAsync(code, measureOptions);\n } catch (error) {\n if (error instanceof NativeAddonError) {\n throw error;\n }\n return { metrics: measureCode(code, measureOptions), crossFileError: getErrorMessage(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\nexport function 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. An explicitly targeted file only needs a supported\n * language, as in the ranking command.\n */\nfunction isScannedPath(relativePath: string, options: ScanOptions, explicitTarget = false): boolean {\n if (explicitTarget) {\n return getLanguage(relativePath, options, true) !== undefined;\n }\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 return detectLanguage(file);\n}\n\n/** The path relative to `base` with forward slashes on every platform, so it compares equal to the paths git prints. */\nexport function formatPath(file: string, base: string): string {\n return path.relative(base, file).replaceAll(path.sep, '/') || 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"],"mappings":"2VA0CA,MAAM,kBAAwB,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,kBAAqB,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,QAAQ,CAAM,CAC5B,CAGA,eAAsB,EAAsB,EAAiC,CAC3E,GAAI,CAEF,OAAO,MAAA,EADkBC,EAAAA,KAAAA,CAAK,CAAM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CAAC,EAAQ,cAAgB,EAAmB,IAAI,CAAO,EAChG,MAAO,GAGX,OAAO,EAAY,EAAc,CAAO,IAAM,IAAA,EAChD,CAEA,SAAgB,EAAY,EAAc,EAAsB,EAAiB,GAAiC,CAChH,IAAM,EAAY,EAAK,YAAY,EAEjC,MAAC,IACA,EAAU,SAAS,OAAO,GACzB,EAAU,SAAS,QAAQ,GAC3B,EAAU,SAAS,QAAQ,GAC3B,EAAU,SAAS,SAAS,GAC5B,EAAU,SAAS,UAAU,MAM9B,GACA,EAAQ,cACR,GAAgB,KAAKA,EAAAA,QAAK,SAAS,CAAI,CAAC,GAAK,GAAsB,KAAKA,EAAAA,QAAK,SAAS,CAAI,CAAC,GAK9F,OAAOW,EAAAA,eAAe,CAAI,CAC5B,CAGA,SAAgB,EAAW,EAAc,EAAsB,CAC7D,OAAOX,EAAAA,QAAK,SAAS,EAAM,CAAI,CAAC,CAAC,WAAWA,EAAAA,QAAK,IAAK,GAAG,GAAKA,EAAAA,QAAK,SAAS,CAAI,CAClF,CAEA,SAAgB,EAAY,EAAuB,CACjD,QAAQ,OAAO,MAAM,CAAO,CAC9B,CAEA,SAAgB,EAAY,EAAuB,CACjD,QAAQ,OAAO,MAAM,CAAO,CAC9B"}
|
package/dist/scan.d.ts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { type CrossFileDuplicationMetrics } from './crossFileDuplication.js';
|
|
2
2
|
import type { CrossFileDuplicationFileData } from './duplication.js';
|
|
3
3
|
import type { Exclusion } from './exclusion.js';
|
|
4
|
-
import type { CodeMetrics, DuplicationOptions, LanguageName
|
|
4
|
+
import type { CodeMetrics, DuplicationOptions, LanguageName } from './types.js';
|
|
5
5
|
/** The scan settings shared by every command (a structural subset of each command's options). */
|
|
6
6
|
export interface ScanOptions {
|
|
7
7
|
duplication: Required<DuplicationOptions>;
|
|
@@ -34,23 +34,14 @@ export declare function resolveTarget(target: string): string;
|
|
|
34
34
|
export declare function configSearchDirectory(target: string): Promise<string>;
|
|
35
35
|
export declare function scanTarget(target: string, options: ScanOptions): Promise<ScanResult>;
|
|
36
36
|
/**
|
|
37
|
-
* Measures an explicit list of repository-relative files (the
|
|
38
|
-
*
|
|
39
|
-
*
|
|
40
|
-
*
|
|
37
|
+
* Measures an explicit list of repository-relative files (the git-visible ones of `check`) instead
|
|
38
|
+
* of walking the directory tree, so ignored artifact directories are never parsed. Paths outside
|
|
39
|
+
* the scan scope (ignored/test directories, unsupported or test file names) are skipped with the
|
|
40
|
+
* same rules as the walk. Like the walk, which never tests the directory it starts in, the rules
|
|
41
|
+
* apply to a file under `targetDirectory` (repository-relative, forward slashes) by its path below
|
|
42
|
+
* that directory, so naming `vendor` or `test` as the target measures what is in it.
|
|
41
43
|
*/
|
|
42
|
-
export declare function scanListedFiles(rootDirectory: string, relativePaths: Iterable<string>, options: ScanOptions, explicitFiles?: ReadonlySet<string
|
|
43
|
-
/**
|
|
44
|
-
* Measures a file together with its cross-file contribution from one parse. The contribution is
|
|
45
|
-
* auxiliary: if collecting it fails where plain measurement succeeds (e.g. a payload too large to
|
|
46
|
-
* cross the addon boundary), the metrics are still returned with the failure message, which
|
|
47
|
-
* callers report as a warning rather than an error.
|
|
48
|
-
*/
|
|
49
|
-
export declare function measureWithCrossFileData(code: string, measureOptions: MeasureOptions): Promise<{
|
|
50
|
-
metrics: CodeMetrics;
|
|
51
|
-
crossFileData?: CrossFileDuplicationFileData;
|
|
52
|
-
crossFileError?: string;
|
|
53
|
-
}>;
|
|
44
|
+
export declare function scanListedFiles(rootDirectory: string, relativePaths: Iterable<string>, options: ScanOptions, explicitFiles?: ReadonlySet<string>, targetDirectory?: string): Promise<ScanResult>;
|
|
54
45
|
/** Runs after the scan so every measured file's candidates participate. */
|
|
55
46
|
export declare function addCrossFileDuplication(result: ScanResult, options: ScanOptions): void;
|
|
56
47
|
/**
|
|
@@ -60,15 +51,9 @@ export declare function addCrossFileDuplication(result: ScanResult, options: Sca
|
|
|
60
51
|
* a subset of the file's code lines and a ratio derived over code lines can never exceed 1.
|
|
61
52
|
*/
|
|
62
53
|
export declare function collectDuplicatedLineNumbers(metrics: CodeMetrics | undefined, crossFileDuplication: CrossFileDuplicationMetrics | undefined, formattedFile: string): Set<number>;
|
|
63
|
-
|
|
64
|
-
* Whether a repository-relative path would be scanned: no ignored or excluded-test directory
|
|
65
|
-
* segment and a supported, non-test file name. The diff gate uses this for base-revision
|
|
66
|
-
* eligibility, so code renamed into scan scope gates as new code instead of ratcheting against
|
|
67
|
-
* a blob the scanner would never have measured. An explicitly targeted file only needs a supported
|
|
68
|
-
* language, as in the ranking command.
|
|
69
|
-
*/
|
|
70
|
-
export declare function isScannedPath(relativePath: string, options: ScanOptions, explicitTarget?: boolean): boolean;
|
|
54
|
+
export declare function isWithinDirectory(candidate: string, directory: string): boolean;
|
|
71
55
|
export declare function getLanguage(file: string, options: ScanOptions, explicitTarget?: boolean): LanguageName | undefined;
|
|
56
|
+
/** The path relative to `base` with forward slashes on every platform, so it compares equal to the paths git prints. */
|
|
72
57
|
export declare function formatPath(file: string, base: string): string;
|
|
73
58
|
export declare function writeStdout(message: string): void;
|
|
74
59
|
export declare function writeStderr(message: string): void;
|
package/dist/scan.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{measureCrossFileDuplication as e}from"./crossFileDuplication.js";import{detectLanguage as t}from"./languages.js";import{NativeAddonError as n}from"./nativeMetrics.js";import{measureCode as r,measureCodeWithCrossFileDataAsync as i}from"./metrics.js";import{getErrorMessage as a}from"@willbooster/shared-lib";import{lstat as o,readFile as s,readdir as c,realpath as l,stat as u}from"node:fs/promises";import d from"node:path";import f from"node:os";const p=/* @__PURE__ */ 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`]),m=/* @__PURE__ */ new Set([`__tests__`,`test`,`tests`,`spec`]),h=/(?:^test(?:[_-].*)?|\.(?:spec|test)|[_-](?:test|spec))\.[^.]+$/iu,g=/Tests?\.(?:java|kt|cs)$/u;function _(e){return e===`~`?f.homedir():e.startsWith(`~/`)?d.join(f.homedir(),e.slice(2)):d.resolve(e)}async function v(e){try{return(await u(e)).isDirectory()?e:d.dirname(e)}catch{return d.dirname(e)}}const y=f.availableParallelism()*2;async function b(e,t){let n=e;try{n=await l(e)}catch{}let r=d.dirname(n),i;try{i=await u(n)}catch(e){let t=`${V(n,r)}: ${a(e)}`;return{displayRoot:r,files:[],errors:[t],warnings:[],generatedFiles:[],fatalError:t}}if(i.isFile()){let e=d.dirname(n),r=B(n,t,!0);if(!r){let t=`${V(n,e)}: unsupported file type`;return{displayRoot:e,files:[],errors:[t],warnings:[],generatedFiles:[],fatalError:t}}let i=T(t,e);return await M(n,r,`single-file`,i,n),w(i,e)}let o=T(t,n);return await k(n,o),await S(o),w(o,n)}async function x(e,t,n,r=/* @__PURE__ */ new Set){let
|
|
1
|
+
import{measureCrossFileDuplication as e}from"./crossFileDuplication.js";import{detectLanguage as t}from"./languages.js";import{NativeAddonError as n}from"./nativeMetrics.js";import{measureCode as r,measureCodeWithCrossFileDataAsync as i}from"./metrics.js";import{getErrorMessage as a}from"@willbooster/shared-lib";import{lstat as o,readFile as s,readdir as c,realpath as l,stat as u}from"node:fs/promises";import d from"node:path";import f from"node:os";const p=/* @__PURE__ */ 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`]),m=/* @__PURE__ */ new Set([`__tests__`,`test`,`tests`,`spec`]),h=/(?:^test(?:[_-].*)?|\.(?:spec|test)|[_-](?:test|spec))\.[^.]+$/iu,g=/Tests?\.(?:java|kt|cs)$/u;function _(e){return e===`~`?f.homedir():e.startsWith(`~/`)?d.join(f.homedir(),e.slice(2)):d.resolve(e)}async function v(e){try{return(await u(e)).isDirectory()?e:d.dirname(e)}catch{return d.dirname(e)}}const y=f.availableParallelism()*2;async function b(e,t){let n=e;try{n=await l(e)}catch{}let r=d.dirname(n),i;try{i=await u(n)}catch(e){let t=`${V(n,r)}: ${a(e)}`;return{displayRoot:r,files:[],errors:[t],warnings:[],generatedFiles:[],fatalError:t}}if(i.isFile()){let e=d.dirname(n),r=B(n,t,!0);if(!r){let t=`${V(n,e)}: unsupported file type`;return{displayRoot:e,files:[],errors:[t],warnings:[],generatedFiles:[],fatalError:t}}let i=T(t,e);return await M(n,r,`single-file`,i,n),w(i,e)}let o=T(t,n);return await k(n,o),await S(o),w(o,n)}async function x(e,t,n,r=/* @__PURE__ */ new Set,i=``){let a=T(n,e),s=i===``?``:`${i}/`;for(let i of t){let t=d.join(e,i),c=z(i.startsWith(s)?i.slice(s.length):i,n,r.has(t))?B(i,n,r.has(t)):void 0;if(!c)continue;let l=await o(t).catch(()=>{});(!l||l.isFile())&&a.candidates.push({file:t,language:c})}return await S(a),w(a,e)}async function S(e){let t=await e.options.loadExclusion?.(e.candidates.flatMap(({file:e,realFile:t})=>t===void 0?[e]:[e,t]));e.exclusion=t;let n=/* @__PURE__ */ new Map;for(let t of e.candidates){let r;try{r=t.realFile??await l(t.file)}catch(n){E(e,t.file,n);continue}n.set(r,[...n.get(r)??[],t])}for(let[r,i]of n){if(e.fatalSeen)return;let n=await C(r,i,t);n!==void 0&&await M(n.file,n.language,`directory`,e,r)}}async function C(e,t,n){if(n===void 0)return t[0];if(n.isExcludedPath(e))return;let r=t.filter(({file:e})=>!n.isExcludedPath(e)),i=r.find(({file:t})=>t===e);if(i!==void 0||r.length<=1)return i??r[0];let a=await s(e,`utf8`).catch(()=>{});return r.find(({file:e})=>a!==void 0&&!n.isGeneratedCode(e,a))??r[0]}async function w(e,t){let n=[],r=[],i=[],o=[];for(let s of e.outcomes){let e=await s;if(`fatal`in e){let s=a(e.fatal);return{displayRoot:t,files:n,errors:[...r,s],warnings:i,generatedFiles:o,fatalError:s}}if(`generatedFile`in e){o.push(e.generatedFile);continue}if(`error`in e){r.push(e.error);continue}n.push(e.file),e.warning!==void 0&&i.push(e.warning)}return{displayRoot:t,files:n,errors:r,warnings:i,generatedFiles:o}}function T(e,t){return{options:e,outcomes:[],inFlight:/* @__PURE__ */ new Set,fatalSeen:!1,visitedDirectories:/* @__PURE__ */ new Set,visitedFiles:/* @__PURE__ */ new Set,rootDirectory:t,candidates:[]}}function E(e,t,n){e.outcomes.push({error:`${V(t,e.rootDirectory)}: ${a(n)}`})}async function D(e,t,n){try{return await e()}catch(e){E(n,t,e);return}}async function O(e,t){let n=await D(()=>l(e),e,t);return n!==void 0&&R(n,t.rootDirectory)?n:void 0}async function k(e,t){let n=await O(e,t);if(n===void 0||t.visitedDirectories.has(n))return;t.visitedDirectories.add(n);let r=await D(()=>c(e,{withFileTypes:!0}),e,t);if(r!==void 0){r.sort((e,t)=>e.name<t.name?-1:+(e.name>t.name));for(let i of r){let r=d.join(e,i.name);if(i.isSymbolicLink()){await A(i.name,r,t);continue}if(i.isDirectory()){if(L(i.name,t.options))continue;await k(r,t);continue}i.isFile()&&j(r,t,r,n===e?void 0:d.join(n,i.name))}}}async function A(e,t,n){let r=await O(t,n);if(r===void 0)return;let i=await D(()=>u(t),t,n);if(i!==void 0){if(i.isDirectory()){if(L(e,n.options)||L(d.basename(r),n.options))return;await k(t,n);return}i.isFile()&&j(t,n,r,r)}}function j(e,t,n=e,r){let i=B(n,t.options);i&&t.candidates.push({file:e,language:i,realFile:r})}async function M(e,t,n,r,i){if(r.fatalSeen)return;let a;try{a=i??await l(e)}catch(t){E(r,e,t);return}if(r.visitedFiles.has(a))return;for(r.visitedFiles.add(a);r.inFlight.size>=y;)await Promise.race(r.inFlight);let o=N(e,a,t,n,r);r.inFlight.add(o),o.then(()=>r.inFlight.delete(o)),r.outcomes.push(o)}async function N(e,t,i,o,c){try{let n=await s(e,`utf8`),a={language:i,duplication:c.options.duplication};if(o===`single-file`)return{file:{file:e,metrics:r(n,a)}};let l=c.exclusion;if(l&&(l.isGeneratedCode(e,n)||l.isGeneratedCode(t,n)))return{generatedFile:e};let{metrics:u,crossFileData:d,crossFileError:f}=await P(n,a);return{file:{file:e,metrics:u,duplicationCandidates:d},warning:f===void 0?void 0:`${V(e,c.rootDirectory)}: cross-file duplication candidates unavailable: ${f}`}}catch(t){return t instanceof n?(c.fatalSeen=!0,{fatal:t}):{error:`${V(e,c.rootDirectory)}: ${a(t)}`}}}async function P(e,t){try{return await i(e,t)}catch(i){if(i instanceof n)throw i;return{metrics:r(e,t),crossFileError:a(i)}}}function F(t,n){if(t.fatalError||t.files.length<2)return;let r=t.files.flatMap(({file:e,duplicationCandidates:n})=>n?[{file:V(e,t.displayRoot),...n}]:[]);r.length<2||(t.crossFileDuplication=e(r,n.duplication))}function I(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 L(e,t){return p.has(e)?!0:!t.includeTests&&m.has(e)}function R(e,t){let n=d.relative(t,e);return n===``||n!==`..`&&!n.startsWith(`..${d.sep}`)&&!d.isAbsolute(n)}function z(e,t,n=!1){if(n)return B(e,t,!0)!==void 0;let r=e.split(`/`);for(let e of r.slice(0,-1))if(p.has(e)||!t.includeTests&&m.has(e))return!1;return B(e,t)!==void 0}function B(e,n,r=!1){let i=e.toLowerCase();if(!(!r&&(i.endsWith(`.d.ts`)||i.endsWith(`.d.mts`)||i.endsWith(`.d.cts`)||i.endsWith(`.min.js`)||i.endsWith(`.pnp.cjs`)))&&(r||n.includeTests||!h.test(d.basename(e))&&!g.test(d.basename(e))))return t(e)}function V(e,t){return d.relative(t,e).replaceAll(d.sep,`/`)||d.basename(e)}function H(e){process.stdout.write(e)}function U(e){process.stderr.write(e)}export{F as addCrossFileDuplication,I as collectDuplicatedLineNumbers,v as configSearchDirectory,V as formatPath,B as getLanguage,R as isWithinDirectory,_ as resolveTarget,x as scanListedFiles,b as scanTarget,U as writeStderr,H 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 { getErrorMessage } from '@willbooster/shared-lib';\nimport { measureCrossFileDuplication, type CrossFileDuplicationMetrics } from './crossFileDuplication.js';\nimport type { CrossFileDuplicationFileData } from './duplication.js';\nimport type { Exclusion } from './exclusion.js';\nimport { detectLanguage } from './languages.js';\nimport { measureCode, measureCodeWithCrossFileDataAsync } from './metrics.js';\nimport { NativeAddonError } from './nativeMetrics.js';\nimport type { CodeMetrics, DuplicationOptions, LanguageName, MeasureOptions } 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 * Loads the exclusion covering the files a directory scan found (absolute paths); an explicitly\n * targeted file is always measured.\n */\n loadExclusion?: (absolutePaths: readonly string[]) => Promise<Exclusion>;\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 /** Files skipped because their content is generated code (see Exclusion.isGeneratedCode). */\n generatedFiles: string[];\n fatalError?: string;\n files: FileMetrics[];\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 /**\n * Outcomes in discovery order. Files are measured concurrently, so a measurement is recorded as\n * a promise here and applied in this order once all have settled, keeping results deterministic.\n */\n outcomes: (ScanOutcome | Promise<ScanOutcome>)[];\n /** Measurements in flight, bounded so file contents and payloads do not pile up. */\n inFlight: Set<Promise<ScanOutcome>>;\n /** Set once a measurement fails fatally; no further measurement starts. */\n fatalSeen: boolean;\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 /** Files the walk found, measured once the exclusion covering all of them is loaded. */\n candidates: ScanCandidate[];\n exclusion?: Exclusion;\n}\n\ninterface ScanCandidate {\n file: string;\n language: LanguageName;\n /** The resolved path when the file was reached through a symbolic link. */\n realFile?: string;\n}\n\n/**\n * A missing native addon fails every file identically, so it ends the scan as one fatal error\n * instead of one \"skipped\" entry per file behind a successful exit code.\n */\ntype ScanOutcome =\n | { file: FileMetrics; warning?: string }\n | { generatedFile: string }\n | { error: string }\n | { fatal: NativeAddonError };\n\n// Twice the addon's worker count keeps its pool busy while finished payloads are parsed.\nconst maxMeasurementsInFlight = os.availableParallelism() * 2;\n\nexport async function scanTarget(target: string, options: ScanOptions): Promise<ScanResult> {\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)}: ${getErrorMessage(error)}`;\n return {\n displayRoot: fallbackDisplayRoot,\n files: [],\n errors: [fatalError],\n warnings: [],\n generatedFiles: [],\n fatalError,\n };\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: [], generatedFiles: [], fatalError };\n }\n\n const context = makeScanContext(options, displayRoot);\n await measureFile(canonicalTarget, language, 'single-file', context, canonicalTarget);\n return settleScan(context, displayRoot);\n }\n\n const context = makeScanContext(options, canonicalTarget);\n await scanDirectory(canonicalTarget, context);\n await measureCandidates(context);\n return settleScan(context, canonicalTarget);\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 explicitFiles: ReadonlySet<string> = new Set()\n): Promise<ScanResult> {\n const context = makeScanContext(options, rootDirectory);\n for (const relativePath of relativePaths) {\n const absolutePath = path.join(rootDirectory, relativePath);\n const language = isScannedPath(relativePath, options, explicitFiles.has(absolutePath))\n ? getLanguage(relativePath, options, explicitFiles.has(absolutePath))\n : undefined;\n if (!language) {\n continue;\n }\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 context.candidates.push({ file: absolutePath, language });\n }\n }\n await measureCandidates(context);\n return settleScan(context, rootDirectory);\n}\n\nasync function measureCandidates(context: ScanContext): Promise<void> {\n const exclusion = await context.options.loadExclusion?.(\n context.candidates.flatMap(({ file, realFile }) => (realFile === undefined ? [file] : [file, realFile]))\n );\n context.exclusion = exclusion;\n // Every path reaching the same real file, in discovery order, so one alias cannot decide alone.\n const pathsByRealFile = new Map<string, ScanCandidate[]>();\n for (const candidate of context.candidates) {\n let realFile;\n try {\n realFile = candidate.realFile ?? (await realpath(candidate.file));\n } catch (error) {\n recordError(context, candidate.file, error);\n continue;\n }\n pathsByRealFile.set(realFile, [...(pathsByRealFile.get(realFile) ?? []), candidate]);\n }\n for (const [realFile, candidates] of pathsByRealFile) {\n if (context.fatalSeen) {\n return;\n }\n const chosen = await chooseMeasuredPath(realFile, candidates, exclusion);\n if (chosen !== undefined) {\n await measureFile(chosen.file, chosen.language, 'directory', context, realFile);\n }\n }\n}\n\n/**\n * The path to measure a real file through. A path is excluded when its own exclusion or the real\n * file's applies, so the real path, when the scan reached it directly, is never less measurable\n * than an alias; otherwise the first alias not excluded, preferring one whose own attributes do\n * not judge the content generated.\n */\nasync function chooseMeasuredPath(\n realFile: string,\n candidates: readonly ScanCandidate[],\n exclusion: Exclusion | undefined\n): Promise<ScanCandidate | undefined> {\n if (exclusion === undefined) {\n return candidates[0];\n }\n if (exclusion.isExcludedPath(realFile)) {\n return undefined;\n }\n const measurable = candidates.filter(({ file }) => !exclusion.isExcludedPath(file));\n const direct = measurable.find(({ file }) => file === realFile);\n if (direct !== undefined || measurable.length <= 1) {\n return direct ?? measurable[0];\n }\n const code = await readFile(realFile, 'utf8').catch(() => {});\n return measurable.find(({ file }) => code !== undefined && !exclusion.isGeneratedCode(file, code)) ?? measurable[0];\n}\n\n/** Applies the scan's outcomes in discovery order once every measurement has settled. */\nasync function settleScan(context: ScanContext, displayRoot: string): Promise<ScanResult> {\n const files: FileMetrics[] = [];\n const errors: string[] = [];\n const warnings: string[] = [];\n const generatedFiles: string[] = [];\n for (const pending of context.outcomes) {\n const outcome = await pending;\n if ('fatal' in outcome) {\n const fatalError = getErrorMessage(outcome.fatal);\n // Errors the walk recorded before the fatal failure stay reported alongside it.\n return { displayRoot, files, errors: [...errors, fatalError], warnings, generatedFiles, fatalError };\n }\n if ('generatedFile' in outcome) {\n generatedFiles.push(outcome.generatedFile);\n continue;\n }\n if ('error' in outcome) {\n errors.push(outcome.error);\n continue;\n }\n files.push(outcome.file);\n if (outcome.warning !== undefined) {\n warnings.push(outcome.warning);\n }\n }\n return { displayRoot, files, errors, warnings, generatedFiles };\n}\n\nfunction makeScanContext(options: ScanOptions, rootDirectory: string): ScanContext {\n return {\n options,\n outcomes: [],\n inFlight: new Set(),\n fatalSeen: false,\n visitedDirectories: new Set(),\n visitedFiles: new Set(),\n rootDirectory,\n candidates: [],\n };\n}\n\nfunction recordError(context: ScanContext, target: string, error: unknown): void {\n context.outcomes.push({ error: `${formatPath(target, context.rootDirectory)}: ${getErrorMessage(error)}` });\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 recordError(context, target, 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 // readdir order differs between file systems; sorting keeps which path reaches a file first,\n // and so the scan's result, the same everywhere.\n entries.sort((left, right) => (left.name < right.name ? -1 : left.name > right.name ? 1 : 0));\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 // Under a symbolically linked directory the real path differs, and exclusion checks both.\n const realFile = resolvedDirectory === directory ? undefined : path.join(resolvedDirectory, entry.name);\n collectScannableFile(entryPath, context, entryPath, realFile);\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 collectScannableFile(entryPath, context, resolvedPath, resolvedPath);\n }\n}\n\nfunction collectScannableFile(file: string, context: ScanContext, languageFile = file, realFile?: string): void {\n const language = getLanguage(languageFile, context.options);\n if (language) {\n context.candidates.push({ file, language, realFile });\n }\n}\n\n/**\n * Resolves and deduplicates the file in discovery order, then starts measuring it concurrently; its\n * outcome is recorded in discovery order (see ScanContext.outcomes).\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 if (context.fatalSeen) {\n return;\n }\n let resolvedFile;\n try {\n resolvedFile = realFile ?? (await realpath(file));\n } catch (error) {\n recordError(context, file, error);\n return;\n }\n if (context.visitedFiles.has(resolvedFile)) {\n return;\n }\n context.visitedFiles.add(resolvedFile);\n\n // Any settled measurement frees its slot (removed by the callback below, which runs before the\n // race resumes), so one slow file never idles the pool.\n while (context.inFlight.size >= maxMeasurementsInFlight) {\n await Promise.race(context.inFlight);\n }\n const outcome = readAndMeasureFile(file, resolvedFile, language, mode, context);\n context.inFlight.add(outcome);\n void outcome.then(() => context.inFlight.delete(outcome));\n context.outcomes.push(outcome);\n}\n\nasync function readAndMeasureFile(\n file: string,\n resolvedFile: string,\n language: LanguageName,\n mode: 'single-file' | 'directory',\n context: ScanContext\n): Promise<ScanOutcome> {\n try {\n const code = await readFile(file, 'utf8');\n const measureOptions = { language, duplication: context.options.duplication };\n // Only directory scans compare files against each other; a single-file target has no peers.\n if (mode === 'single-file') {\n return { file: { file, metrics: measureCode(code, measureOptions) } };\n }\n // Like path exclusion, either the scanned path or the real one can judge the code generated.\n const exclusion = context.exclusion;\n if (exclusion && (exclusion.isGeneratedCode(file, code) || exclusion.isGeneratedCode(resolvedFile, code))) {\n return { generatedFile: file };\n }\n const { metrics, crossFileData, crossFileError } = await measureWithCrossFileData(code, measureOptions);\n return {\n file: { file, metrics, duplicationCandidates: crossFileData },\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 warning:\n crossFileError === undefined\n ? undefined\n : `${formatPath(file, context.rootDirectory)}: cross-file duplication candidates unavailable: ${crossFileError}`,\n };\n } catch (error) {\n if (error instanceof NativeAddonError) {\n context.fatalSeen = true;\n return { fatal: error };\n }\n return { error: `${formatPath(file, context.rootDirectory)}: ${getErrorMessage(error)}` };\n }\n}\n\n/**\n * Measures a file together with its cross-file contribution from one parse. The contribution is\n * auxiliary: if collecting it fails where plain measurement succeeds (e.g. a payload too large to\n * cross the addon boundary), the metrics are still returned with the failure message, which\n * callers report as a warning rather than an error.\n */\nexport async function measureWithCrossFileData(\n code: string,\n measureOptions: MeasureOptions\n): Promise<{ metrics: CodeMetrics; crossFileData?: CrossFileDuplicationFileData; crossFileError?: string }> {\n try {\n return await measureCodeWithCrossFileDataAsync(code, measureOptions);\n } catch (error) {\n if (error instanceof NativeAddonError) {\n throw error;\n }\n return { metrics: measureCode(code, measureOptions), crossFileError: getErrorMessage(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. An explicitly targeted file only needs a supported\n * language, as in the ranking command.\n */\nexport function isScannedPath(relativePath: string, options: ScanOptions, explicitTarget = false): boolean {\n if (explicitTarget) {\n return getLanguage(relativePath, options, true) !== undefined;\n }\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 return detectLanguage(file);\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"],"mappings":"scA0CA,MAAM,kBAAwB,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,kBAAqB,IAAI,IAAI,CAAC,YAAa,OAAQ,QAAS,MAAM,CAAC,EACnE,EAAkB,mEAGlB,EAAwB,2BAE9B,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,CAAM,CAC5B,CAGA,eAAsB,EAAsB,EAAiC,CAC3E,GAAI,CAEF,OAAO,MADkB,EAAK,CAAM,EAAA,CAClB,YAAY,EAAI,EAAS,EAAK,QAAQ,CAAM,CAChE,MAAQ,CACN,OAAO,EAAK,QAAQ,CAAM,CAC5B,CACF,CAyCA,MAAM,EAA0B,EAAG,qBAAqB,EAAI,EAE5D,eAAsB,EAAW,EAAgB,EAA2C,CAC1F,IAAI,EAAkB,EACtB,GAAI,CACF,EAAkB,MAAM,EAAS,CAAM,CACzC,MAAQ,CAER,CAEA,IAAM,EAAsB,EAAK,QAAQ,CAAe,EACpD,EAEJ,GAAI,CACF,EAAa,MAAM,EAAK,CAAe,CACzC,OAAS,EAAO,CACd,IAAM,EAAa,GAAG,EAAW,EAAiB,CAAmB,EAAE,IAAI,EAAgB,CAAK,IAChG,MAAO,CACL,YAAa,EACb,MAAO,CAAC,EACR,OAAQ,CAAC,CAAU,EACnB,SAAU,CAAC,EACX,eAAgB,CAAC,EACjB,YACF,CACF,CAEA,GAAI,EAAW,OAAO,EAAG,CACvB,IAAM,EAAc,EAAK,QAAQ,CAAe,EAC1C,EAAW,E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AChG,MAAO,GAGX,OAAO,EAAY,EAAc,CAAO,IAAM,IAAA,EAChD,CAEA,SAAgB,EAAY,EAAc,EAAsB,EAAiB,GAAiC,CAChH,IAAM,EAAY,EAAK,YAAY,EAEjC,MAAC,IACA,EAAU,SAAS,OAAO,GACzB,EAAU,SAAS,QAAQ,GAC3B,EAAU,SAAS,QAAQ,GAC3B,EAAU,SAAS,SAAS,GAC5B,EAAU,SAAS,UAAU,MAM9B,GACA,EAAQ,cACR,GAAgB,KAAK,EAAK,SAAS,CAAI,CAAC,GAAK,GAAsB,KAAK,EAAK,SAAS,CAAI,CAAC,GAK9F,OAAO,EAAe,CAAI,CAC5B,CAEA,SAAgB,EAAW,EAAc,EAAsB,CAC7D,OAAO,EAAK,SAAS,EAAM,CAAI,GAAK,EAAK,SAAS,CAAI,CACxD,CAEA,SAAgB,EAAY,EAAuB,CACjD,QAAQ,OAAO,MAAM,CAAO,CAC9B,CAEA,SAAgB,EAAY,EAAuB,CACjD,QAAQ,OAAO,MAAM,CAAO,CAC9B"}
|
|
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 { getErrorMessage } from '@willbooster/shared-lib';\nimport { measureCrossFileDuplication, type CrossFileDuplicationMetrics } from './crossFileDuplication.js';\nimport type { CrossFileDuplicationFileData } from './duplication.js';\nimport type { Exclusion } from './exclusion.js';\nimport { detectLanguage } from './languages.js';\nimport { measureCode, measureCodeWithCrossFileDataAsync } from './metrics.js';\nimport { NativeAddonError } from './nativeMetrics.js';\nimport type { CodeMetrics, DuplicationOptions, LanguageName, MeasureOptions } 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 * Loads the exclusion covering the files a directory scan found (absolute paths); an explicitly\n * targeted file is always measured.\n */\n loadExclusion?: (absolutePaths: readonly string[]) => Promise<Exclusion>;\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 /** Files skipped because their content is generated code (see Exclusion.isGeneratedCode). */\n generatedFiles: string[];\n fatalError?: string;\n files: FileMetrics[];\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 /**\n * Outcomes in discovery order. Files are measured concurrently, so a measurement is recorded as\n * a promise here and applied in this order once all have settled, keeping results deterministic.\n */\n outcomes: (ScanOutcome | Promise<ScanOutcome>)[];\n /** Measurements in flight, bounded so file contents and payloads do not pile up. */\n inFlight: Set<Promise<ScanOutcome>>;\n /** Set once a measurement fails fatally; no further measurement starts. */\n fatalSeen: boolean;\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 /** Files the walk found, measured once the exclusion covering all of them is loaded. */\n candidates: ScanCandidate[];\n exclusion?: Exclusion;\n}\n\ninterface ScanCandidate {\n file: string;\n language: LanguageName;\n /** The resolved path when the file was reached through a symbolic link. */\n realFile?: string;\n}\n\n/**\n * A missing native addon fails every file identically, so it ends the scan as one fatal error\n * instead of one \"skipped\" entry per file behind a successful exit code.\n */\ntype ScanOutcome =\n | { file: FileMetrics; warning?: string }\n | { generatedFile: string }\n | { error: string }\n | { fatal: NativeAddonError };\n\n// Twice the addon's worker count keeps its pool busy while finished payloads are parsed.\nconst maxMeasurementsInFlight = os.availableParallelism() * 2;\n\nexport async function scanTarget(target: string, options: ScanOptions): Promise<ScanResult> {\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)}: ${getErrorMessage(error)}`;\n return {\n displayRoot: fallbackDisplayRoot,\n files: [],\n errors: [fatalError],\n warnings: [],\n generatedFiles: [],\n fatalError,\n };\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: [], generatedFiles: [], fatalError };\n }\n\n const context = makeScanContext(options, displayRoot);\n await measureFile(canonicalTarget, language, 'single-file', context, canonicalTarget);\n return settleScan(context, displayRoot);\n }\n\n const context = makeScanContext(options, canonicalTarget);\n await scanDirectory(canonicalTarget, context);\n await measureCandidates(context);\n return settleScan(context, canonicalTarget);\n}\n\n/**\n * Measures an explicit list of repository-relative files (the git-visible ones of `check`) instead\n * of walking the directory tree, so ignored artifact directories are never parsed. Paths outside\n * the scan scope (ignored/test directories, unsupported or test file names) are skipped with the\n * same rules as the walk. Like the walk, which never tests the directory it starts in, the rules\n * apply to a file under `targetDirectory` (repository-relative, forward slashes) by its path below\n * that directory, so naming `vendor` or `test` as the target measures what is in it.\n */\nexport async function scanListedFiles(\n rootDirectory: string,\n relativePaths: Iterable<string>,\n options: ScanOptions,\n explicitFiles: ReadonlySet<string> = new Set(),\n targetDirectory = ''\n): Promise<ScanResult> {\n const context = makeScanContext(options, rootDirectory);\n const targetPrefix = targetDirectory === '' ? '' : `${targetDirectory}/`;\n for (const relativePath of relativePaths) {\n const absolutePath = path.join(rootDirectory, relativePath);\n const scopedPath = relativePath.startsWith(targetPrefix) ? relativePath.slice(targetPrefix.length) : relativePath;\n const language = isScannedPath(scopedPath, options, explicitFiles.has(absolutePath))\n ? getLanguage(relativePath, options, explicitFiles.has(absolutePath))\n : undefined;\n if (!language) {\n continue;\n }\n // Like the walk, only regular files are sources. A symbolic link is not one: git stores only its\n // target string, so measuring through it would diverge from what any revision of the repository\n // contains. Reading a FIFO would block forever. A path lstat cannot inspect stays a candidate so\n // that measuring it reports the error.\n const stats = await lstat(absolutePath).catch(() => {});\n if (!stats || stats.isFile()) {\n context.candidates.push({ file: absolutePath, language });\n }\n }\n await measureCandidates(context);\n return settleScan(context, rootDirectory);\n}\n\nasync function measureCandidates(context: ScanContext): Promise<void> {\n const exclusion = await context.options.loadExclusion?.(\n context.candidates.flatMap(({ file, realFile }) => (realFile === undefined ? [file] : [file, realFile]))\n );\n context.exclusion = exclusion;\n // Every path reaching the same real file, in discovery order, so one alias cannot decide alone.\n const pathsByRealFile = new Map<string, ScanCandidate[]>();\n for (const candidate of context.candidates) {\n let realFile;\n try {\n realFile = candidate.realFile ?? (await realpath(candidate.file));\n } catch (error) {\n recordError(context, candidate.file, error);\n continue;\n }\n pathsByRealFile.set(realFile, [...(pathsByRealFile.get(realFile) ?? []), candidate]);\n }\n for (const [realFile, candidates] of pathsByRealFile) {\n if (context.fatalSeen) {\n return;\n }\n const chosen = await chooseMeasuredPath(realFile, candidates, exclusion);\n if (chosen !== undefined) {\n await measureFile(chosen.file, chosen.language, 'directory', context, realFile);\n }\n }\n}\n\n/**\n * The path to measure a real file through. A path is excluded when its own exclusion or the real\n * file's applies, so the real path, when the scan reached it directly, is never less measurable\n * than an alias; otherwise the first alias not excluded, preferring one whose own attributes do\n * not judge the content generated.\n */\nasync function chooseMeasuredPath(\n realFile: string,\n candidates: readonly ScanCandidate[],\n exclusion: Exclusion | undefined\n): Promise<ScanCandidate | undefined> {\n if (exclusion === undefined) {\n return candidates[0];\n }\n if (exclusion.isExcludedPath(realFile)) {\n return undefined;\n }\n const measurable = candidates.filter(({ file }) => !exclusion.isExcludedPath(file));\n const direct = measurable.find(({ file }) => file === realFile);\n if (direct !== undefined || measurable.length <= 1) {\n return direct ?? measurable[0];\n }\n const code = await readFile(realFile, 'utf8').catch(() => {});\n return measurable.find(({ file }) => code !== undefined && !exclusion.isGeneratedCode(file, code)) ?? measurable[0];\n}\n\n/** Applies the scan's outcomes in discovery order once every measurement has settled. */\nasync function settleScan(context: ScanContext, displayRoot: string): Promise<ScanResult> {\n const files: FileMetrics[] = [];\n const errors: string[] = [];\n const warnings: string[] = [];\n const generatedFiles: string[] = [];\n for (const pending of context.outcomes) {\n const outcome = await pending;\n if ('fatal' in outcome) {\n const fatalError = getErrorMessage(outcome.fatal);\n // Errors the walk recorded before the fatal failure stay reported alongside it.\n return { displayRoot, files, errors: [...errors, fatalError], warnings, generatedFiles, fatalError };\n }\n if ('generatedFile' in outcome) {\n generatedFiles.push(outcome.generatedFile);\n continue;\n }\n if ('error' in outcome) {\n errors.push(outcome.error);\n continue;\n }\n files.push(outcome.file);\n if (outcome.warning !== undefined) {\n warnings.push(outcome.warning);\n }\n }\n return { displayRoot, files, errors, warnings, generatedFiles };\n}\n\nfunction makeScanContext(options: ScanOptions, rootDirectory: string): ScanContext {\n return {\n options,\n outcomes: [],\n inFlight: new Set(),\n fatalSeen: false,\n visitedDirectories: new Set(),\n visitedFiles: new Set(),\n rootDirectory,\n candidates: [],\n };\n}\n\nfunction recordError(context: ScanContext, target: string, error: unknown): void {\n context.outcomes.push({ error: `${formatPath(target, context.rootDirectory)}: ${getErrorMessage(error)}` });\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 recordError(context, target, 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 // readdir order differs between file systems; sorting keeps which path reaches a file first,\n // and so the scan's result, the same everywhere.\n entries.sort((left, right) => (left.name < right.name ? -1 : left.name > right.name ? 1 : 0));\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 // Under a symbolically linked directory the real path differs, and exclusion checks both.\n const realFile = resolvedDirectory === directory ? undefined : path.join(resolvedDirectory, entry.name);\n collectScannableFile(entryPath, context, entryPath, realFile);\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 collectScannableFile(entryPath, context, resolvedPath, resolvedPath);\n }\n}\n\nfunction collectScannableFile(file: string, context: ScanContext, languageFile = file, realFile?: string): void {\n const language = getLanguage(languageFile, context.options);\n if (language) {\n context.candidates.push({ file, language, realFile });\n }\n}\n\n/**\n * Resolves and deduplicates the file in discovery order, then starts measuring it concurrently; its\n * outcome is recorded in discovery order (see ScanContext.outcomes).\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 if (context.fatalSeen) {\n return;\n }\n let resolvedFile;\n try {\n resolvedFile = realFile ?? (await realpath(file));\n } catch (error) {\n recordError(context, file, error);\n return;\n }\n if (context.visitedFiles.has(resolvedFile)) {\n return;\n }\n context.visitedFiles.add(resolvedFile);\n\n // Any settled measurement frees its slot (removed by the callback below, which runs before the\n // race resumes), so one slow file never idles the pool.\n while (context.inFlight.size >= maxMeasurementsInFlight) {\n await Promise.race(context.inFlight);\n }\n const outcome = readAndMeasureFile(file, resolvedFile, language, mode, context);\n context.inFlight.add(outcome);\n void outcome.then(() => context.inFlight.delete(outcome));\n context.outcomes.push(outcome);\n}\n\nasync function readAndMeasureFile(\n file: string,\n resolvedFile: string,\n language: LanguageName,\n mode: 'single-file' | 'directory',\n context: ScanContext\n): Promise<ScanOutcome> {\n try {\n const code = await readFile(file, 'utf8');\n const measureOptions = { language, duplication: context.options.duplication };\n // Only directory scans compare files against each other; a single-file target has no peers.\n if (mode === 'single-file') {\n return { file: { file, metrics: measureCode(code, measureOptions) } };\n }\n // Like path exclusion, either the scanned path or the real one can judge the code generated.\n const exclusion = context.exclusion;\n if (exclusion && (exclusion.isGeneratedCode(file, code) || exclusion.isGeneratedCode(resolvedFile, code))) {\n return { generatedFile: file };\n }\n const { metrics, crossFileData, crossFileError } = await measureWithCrossFileData(code, measureOptions);\n return {\n file: { file, metrics, duplicationCandidates: crossFileData },\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 warning:\n crossFileError === undefined\n ? undefined\n : `${formatPath(file, context.rootDirectory)}: cross-file duplication candidates unavailable: ${crossFileError}`,\n };\n } catch (error) {\n if (error instanceof NativeAddonError) {\n context.fatalSeen = true;\n return { fatal: error };\n }\n return { error: `${formatPath(file, context.rootDirectory)}: ${getErrorMessage(error)}` };\n }\n}\n\n/**\n * Measures a file together with its cross-file contribution from one parse. The contribution is\n * auxiliary: if collecting it fails where plain measurement succeeds (e.g. a payload too large to\n * cross the addon boundary), the metrics are still returned with the failure message, which\n * callers report as a warning rather than an error.\n */\nasync function measureWithCrossFileData(\n code: string,\n measureOptions: MeasureOptions\n): Promise<{ metrics: CodeMetrics; crossFileData?: CrossFileDuplicationFileData; crossFileError?: string }> {\n try {\n return await measureCodeWithCrossFileDataAsync(code, measureOptions);\n } catch (error) {\n if (error instanceof NativeAddonError) {\n throw error;\n }\n return { metrics: measureCode(code, measureOptions), crossFileError: getErrorMessage(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\nexport function 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. An explicitly targeted file only needs a supported\n * language, as in the ranking command.\n */\nfunction isScannedPath(relativePath: string, options: ScanOptions, explicitTarget = false): boolean {\n if (explicitTarget) {\n return getLanguage(relativePath, options, true) !== undefined;\n }\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 return detectLanguage(file);\n}\n\n/** The path relative to `base` with forward slashes on every platform, so it compares equal to the paths git prints. */\nexport function formatPath(file: string, base: string): string {\n return path.relative(base, file).replaceAll(path.sep, '/') || 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"],"mappings":"scA0CA,MAAM,kBAAwB,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,kBAAqB,IAAI,IAAI,CAAC,YAAa,OAAQ,QAAS,MAAM,CAAC,EACnE,EAAkB,mEAGlB,EAAwB,2BAE9B,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,CAAM,CAC5B,CAGA,eAAsB,EAAsB,EAAiC,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AI,CAC5B,CAGA,SAAgB,EAAW,EAAc,EAAsB,CAC7D,OAAO,EAAK,SAAS,EAAM,CAAI,CAAC,CAAC,WAAW,EAAK,IAAK,GAAG,GAAK,EAAK,SAAS,CAAI,CAClF,CAEA,SAAgB,EAAY,EAAuB,CACjD,QAAQ,OAAO,MAAM,CAAO,CAC9B,CAEA,SAAgB,EAAY,EAAuB,CACjD,QAAQ,OAAO,MAAM,CAAO,CAC9B"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
"use strict";const e=require("./thresholds.cjs"),t=[`file`,`function`,`duplication`];function n(t,n,o){let l=s(n,new Set(t.map(({file:e})=>e))),u=[],d=0;for(let n of t){let{file:t,metrics:r,hunks:s}=n,f=o(r.language),p=s?.length===0?[]:a(e.fileThresholds,r,f);p.length>0&&u.push({kind:`file`,file:t,startLine:1,endLine:r.lines.total,exceeded:p});let m=i(n);d+=m.length;for(let n of m){let r=a(e.functionThresholds,n,f);if(r.length>0){let{startLine:e,endLine:i}=n;u.push({kind:`function`,file:t,startLine:e,endLine:i,name:n.name??`<anonymous>`,exceeded:r})}}u.push(...c(t,r,l.get(t)??[],s,f[e.duplicationThreshold.key]))}return{violations:u.toSorted(r),checkedFunctionCount:d}}function r(e,n){return d(e.file,n.file)||e.startLine-n.startLine||t.indexOf(e.kind)-t.indexOf(n.kind)||e.endLine-n.endLine}function i({metrics:e,hunks:t}){let n=e.language===`python`;return t?e.functions.filter(e=>t.some(t=>o(t,e.startLine,e.endLine,n))):e.functions}function a(t,n,r){return t.flatMap(t=>{let i=t.measure(n),a=r[t.key];return i>a?[{metric:e.metricNameOf(t),value:i,limit:a}]:[]})}function o(e,t,n,r=!1){return e.headCount===0?e.headStart>=t&&(e.headStart<n||r&&e.headStart===n):e.headStart<=n&&e.headStart+e.headCount>t}function s(e,t){let n=/* @__PURE__ */ new Map;for(let r of e?.groups??[])for(let e of r.files)if(t.has(e)){let t=n.get(e)??[];t.push(r),n.set(e,t)}return n}function c(t,n,r,i,a){let s=[...n.duplication.duplicateBlockGroups.map(e=>e.map(e=>({...e,file:t}))),...r.map(e=>e.occurrences)],c=n=>n.file===t&&e.duplicationThreshold.measure(n)>=a&&(!i||i.some(e=>e.headCount>0&&o(e,n.startLine,n.endLine))),d=/* @__PURE__ */ new Map;for(let e of s)for(let t of e.filter(e=>c(e)))d.set(t,e);return l([...d.keys()]).map(({merged:t,sources:n})=>({kind:`duplication`,...t,exceeded:[{metric:e.metricNameOf(e.duplicationThreshold),value:e.duplicationThreshold.measure(t),limit:a}],partners:l(n.flatMap(e=>d.get(e)??[])).map(e=>e.merged).filter(e=>!u(e,t))}))}function l(e){let t=[],n=e.toSorted((e,t)=>d(e.file,t.file)||e.startLine-t.startLine);for(let e of n){let n=t.at(-1);if(n&&u(n.merged,e))n.merged.endLine=Math.max(n.merged.endLine,e.endLine),n.sources.push(e);else{let{file:n,startLine:r,endLine:i}=e;t.push({merged:{file:n,startLine:r,endLine:i},sources:[e]})}}return t}function u(e,t){return e.file===t.file&&e.startLine<=t.endLine&&t.startLine<=e.endLine}function d(e,t){return e<t?-1:+(e>t)}exports.checkThresholds=n;
|
|
2
|
+
//# sourceMappingURL=thresholdCheck.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"thresholdCheck.cjs","names":["fileThresholds","functionThresholds","duplicationThreshold","metricNameOf"],"sources":["../src/thresholdCheck.ts"],"sourcesContent":["import type { CrossFileDuplicateBlockGroup, CrossFileDuplicationMetrics } from './crossFileDuplication.js';\nimport type { LineHunk } from './git.js';\nimport {\n duplicationThreshold,\n fileThresholds,\n functionThresholds,\n metricNameOf,\n type Limits,\n type Threshold,\n} from './thresholds.js';\nimport type { CodeMetrics, FunctionMetrics } from './types.js';\n\n/** A measured file to check, under the path cross-file duplication knows it by. */\nexport interface CheckedFile {\n file: string;\n metrics: CodeMetrics;\n /** The change to the file; when set, only what the change touches is checked. */\n hunks?: readonly LineHunk[];\n}\n\nexport interface ExceededLimit {\n metric: string;\n value: number;\n /** The value is allowed up to this limit; a duplicated block is allowed below it. */\n limit: number;\n}\n\nexport interface BlockLocation {\n file: string;\n startLine: number;\n endLine: number;\n}\n\nexport interface Violation extends BlockLocation {\n kind: 'function' | 'file' | 'duplication';\n /** The function's name, for kind `function`. */\n name?: string;\n exceeded: ExceededLimit[];\n /** The other copies of the block, for kind `duplication`. */\n partners?: BlockLocation[];\n}\n\nexport interface CheckResult {\n violations: Violation[];\n checkedFunctionCount: number;\n}\n\nconst violationKinds: readonly Violation['kind'][] = ['file', 'function', 'duplication'];\n\n/** Every limit the files exceed, ordered by path, then line. */\nexport function checkThresholds(\n files: readonly CheckedFile[],\n crossFileDuplication: CrossFileDuplicationMetrics | undefined,\n limitsOf: (language: string) => Limits\n): CheckResult {\n const crossFileGroupsByFile = indexGroupsByFile(crossFileDuplication, new Set(files.map(({ file }) => file)));\n const violations: Violation[] = [];\n let checkedFunctionCount = 0;\n for (const checkedFile of files) {\n const { file, metrics, hunks } = checkedFile;\n const limits = limitsOf(metrics.language);\n // A rename or a mode change lists the file as changed without touching any of its lines.\n const fileExceeded = hunks?.length === 0 ? [] : collectExceeded(fileThresholds, metrics, limits);\n if (fileExceeded.length > 0) {\n violations.push({ kind: 'file', file, startLine: 1, endLine: metrics.lines.total, exceeded: fileExceeded });\n }\n const checkedFunctions = listCheckedFunctions(checkedFile);\n checkedFunctionCount += checkedFunctions.length;\n for (const fn of checkedFunctions) {\n const exceeded = collectExceeded(functionThresholds, fn, limits);\n if (exceeded.length > 0) {\n const { startLine, endLine } = fn;\n violations.push({ kind: 'function', file, startLine, endLine, name: fn.name ?? '<anonymous>', exceeded });\n }\n }\n violations.push(\n ...collectDuplicationViolations(\n file,\n metrics,\n crossFileGroupsByFile.get(file) ?? [],\n hunks,\n limits[duplicationThreshold.key] as number\n )\n );\n }\n return { violations: violations.toSorted(compareViolations), checkedFunctionCount };\n}\n\n// The kind is compared before the end line because a file violation's end line is corrected after\n// this ordering (to the last line that exists), and the order must not depend on that correction.\nfunction compareViolations(left: Violation, right: Violation): number {\n return (\n compareStrings(left.file, right.file) ||\n left.startLine - right.startLine ||\n violationKinds.indexOf(left.kind) - violationKinds.indexOf(right.kind) ||\n left.endLine - right.endLine\n );\n}\n\n/** The file's functions or, for a changed file, those the change touches. */\nfunction listCheckedFunctions({ metrics, hunks }: CheckedFile): FunctionMetrics[] {\n const endsByIndentation = metrics.language === 'python';\n return hunks\n ? metrics.functions.filter((fn) =>\n hunks.some((hunk) => touchesSpan(hunk, fn.startLine, fn.endLine, endsByIndentation))\n )\n : metrics.functions;\n}\n\nfunction collectExceeded<Subject>(\n thresholds: readonly Threshold<Subject>[],\n subject: Subject,\n limits: Limits\n): ExceededLimit[] {\n return thresholds.flatMap((threshold) => {\n const value = threshold.measure(subject);\n const limit = limits[threshold.key] as number;\n return value > limit ? [{ metric: metricNameOf(threshold), value, limit }] : [];\n });\n}\n\n/**\n * Whether the hunk changes the head lines [startLine, endLine]. A hunk without head lines (a pure\n * deletion) sits between its headStart line and the next one. Where indentation ends a span, its\n * last line is a statement rather than a closing delimiter, so a deletion right after that line may\n * have removed the span's tail; `endsByIndentation` counts it as touching, since the head alone\n * cannot tell it from a deletion after the span.\n */\nfunction touchesSpan(hunk: LineHunk, startLine: number, endLine: number, endsByIndentation = false): boolean {\n return hunk.headCount === 0\n ? hunk.headStart >= startLine && (hunk.headStart < endLine || (endsByIndentation && hunk.headStart === endLine))\n : hunk.headStart <= endLine && hunk.headStart + hunk.headCount > startLine;\n}\n\n/** The cross-file groups with an occurrence in each of the given files. */\nfunction indexGroupsByFile(\n crossFileDuplication: CrossFileDuplicationMetrics | undefined,\n files: ReadonlySet<string>\n): Map<string, CrossFileDuplicateBlockGroup[]> {\n const groupsByFile = new Map<string, CrossFileDuplicateBlockGroup[]>();\n for (const group of crossFileDuplication?.groups ?? []) {\n for (const file of group.files) {\n if (files.has(file)) {\n const groups = groupsByFile.get(file) ?? [];\n groups.push(group);\n groupsByFile.set(file, groups);\n }\n }\n }\n return groupsByFile;\n}\n\n/**\n * One violation per duplicated region of the file: its clone occurrences, within-file and\n * cross-file, that span at least `minLines` (with `hunks`, only those overlapping added lines),\n * with overlapping occurrences merged into one region.\n */\nfunction collectDuplicationViolations(\n file: string,\n metrics: CodeMetrics,\n crossFileGroups: readonly CrossFileDuplicateBlockGroup[],\n hunks: readonly LineHunk[] | undefined,\n minLines: number\n): Violation[] {\n const groups: BlockLocation[][] = [\n ...metrics.duplication.duplicateBlockGroups.map((group) => group.map((occurrence) => ({ ...occurrence, file }))),\n ...crossFileGroups.map((group) => group.occurrences),\n ];\n const isReported = (block: BlockLocation): boolean =>\n block.file === file &&\n duplicationThreshold.measure(block) >= minLines &&\n (!hunks || hunks.some((hunk) => hunk.headCount > 0 && touchesSpan(hunk, block.startLine, block.endLine)));\n const copiesByBlock = new Map<BlockLocation, BlockLocation[]>();\n for (const group of groups) {\n for (const block of group.filter((occurrence) => isReported(occurrence))) {\n copiesByBlock.set(block, group);\n }\n }\n return mergeOverlapping([...copiesByBlock.keys()]).map(({ merged, sources }) => ({\n kind: 'duplication',\n ...merged,\n exceeded: [\n { metric: metricNameOf(duplicationThreshold), value: duplicationThreshold.measure(merged), limit: minLines },\n ],\n // The region's own occurrences are among the copies of the groups it belongs to.\n partners: mergeOverlapping(sources.flatMap((source) => copiesByBlock.get(source) ?? []))\n .map((partner) => partner.merged)\n .filter((partner) => !overlaps(partner, merged)),\n }));\n}\n\n/** The locations with those overlapping in the same file merged, ordered by file, then line. */\nfunction mergeOverlapping(locations: readonly BlockLocation[]): { merged: BlockLocation; sources: BlockLocation[] }[] {\n const regions: { merged: BlockLocation; sources: BlockLocation[] }[] = [];\n const ordered = locations.toSorted(\n (left, right) => compareStrings(left.file, right.file) || left.startLine - right.startLine\n );\n for (const location of ordered) {\n const last = regions.at(-1);\n if (last && overlaps(last.merged, location)) {\n last.merged.endLine = Math.max(last.merged.endLine, location.endLine);\n last.sources.push(location);\n } else {\n const { file, startLine, endLine } = location;\n regions.push({ merged: { file, startLine, endLine }, sources: [location] });\n }\n }\n return regions;\n}\n\nfunction overlaps(left: BlockLocation, right: BlockLocation): boolean {\n return left.file === right.file && left.startLine <= right.endLine && right.startLine <= left.endLine;\n}\n\n/** Code-unit order, so reports do not depend on the locale. */\nfunction compareStrings(left: string, right: string): number {\n return left < right ? -1 : left > right ? 1 : 0;\n}\n"],"mappings":"iDA+CM,EAA+C,CAAC,OAAQ,WAAY,aAAa,EAGvF,SAAgB,EACd,EACA,EACA,EACa,CACb,IAAM,EAAwB,EAAkB,EAAsB,IAAI,IAAI,EAAM,KAAK,CAAE,UAAW,CAAI,CAAC,CAAC,EACtG,EAA0B,CAAC,EAC7B,EAAuB,EAC3B,IAAK,IAAM,KAAe,EAAO,CAC/B,GAAM,CAAE,OAAM,UAAS,SAAU,EAC3B,EAAS,EAAS,EAAQ,QAAQ,EAElC,EAAe,GAAO,SAAW,EAAI,CAAC,EAAI,EAAgBA,EAAAA,eAAgB,EAAS,CAAM,EAC3F,EAAa,OAAS,GACxB,EAAW,KAAK,CAAE,KAAM,OAAQ,OAAM,UAAW,EAAG,QAAS,EAAQ,MAAM,MAAO,SAAU,CAAa,CAAC,EAE5G,IAAM,EAAmB,EAAqB,CAAW,EACzD,GAAwB,EAAiB,OACzC,IAAK,IAAM,KAAM,EAAkB,CACjC,IAAM,EAAW,EAAgBC,EAAAA,mBAAoB,EAAI,CAAM,EAC/D,GAAI,EAAS,OAAS,EAAG,CACvB,GAAM,CAAE,YAAW,WAAY,EAC/B,EAAW,KAAK,CAAE,KAAM,WAAY,OAAM,YAAW,UAAS,KAAM,EAAG,MAAQ,cAAe,UAAS,CAAC,CAC1G,CACF,CACA,EAAW,KACT,GAAG,EACD,EACA,EACA,EAAsB,IAAI,CAAI,GAAK,CAAC,EACpC,EACA,EAAOC,EAAAA,qBAAqB,IAC9B,CACF,CACF,CACA,MAAO,CAAE,WAAY,EAAW,SAAS,CAAiB,EAAG,sBAAqB,CACpF,CAIA,SAAS,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,WAAY,EACrC,EAAQ,KAAK,CAAE,OAAQ,CAAE,OAAM,YAAW,SAAQ,EAAG,QAAS,CAAC,CAAQ,CAAE,CAAC,CAC5E,CACF,CACA,OAAO,CACT,CAEA,SAAS,EAAS,EAAqB,EAA+B,CACpE,OAAO,EAAK,OAAS,EAAM,MAAQ,EAAK,WAAa,EAAM,SAAW,EAAM,WAAa,EAAK,OAChG,CAGA,SAAS,EAAe,EAAc,EAAuB,CAC3D,OAAO,EAAO,EAAQ,GAAK,IAAO,EACpC"}
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
import type { CrossFileDuplicationMetrics } from './crossFileDuplication.js';
|
|
2
|
+
import type { LineHunk } from './git.js';
|
|
3
|
+
import { type Limits } from './thresholds.js';
|
|
4
|
+
import type { CodeMetrics } from './types.js';
|
|
5
|
+
/** A measured file to check, under the path cross-file duplication knows it by. */
|
|
6
|
+
export interface CheckedFile {
|
|
7
|
+
file: string;
|
|
8
|
+
metrics: CodeMetrics;
|
|
9
|
+
/** The change to the file; when set, only what the change touches is checked. */
|
|
10
|
+
hunks?: readonly LineHunk[];
|
|
11
|
+
}
|
|
12
|
+
export interface ExceededLimit {
|
|
13
|
+
metric: string;
|
|
14
|
+
value: number;
|
|
15
|
+
/** The value is allowed up to this limit; a duplicated block is allowed below it. */
|
|
16
|
+
limit: number;
|
|
17
|
+
}
|
|
18
|
+
export interface BlockLocation {
|
|
19
|
+
file: string;
|
|
20
|
+
startLine: number;
|
|
21
|
+
endLine: number;
|
|
22
|
+
}
|
|
23
|
+
export interface Violation extends BlockLocation {
|
|
24
|
+
kind: 'function' | 'file' | 'duplication';
|
|
25
|
+
/** The function's name, for kind `function`. */
|
|
26
|
+
name?: string;
|
|
27
|
+
exceeded: ExceededLimit[];
|
|
28
|
+
/** The other copies of the block, for kind `duplication`. */
|
|
29
|
+
partners?: BlockLocation[];
|
|
30
|
+
}
|
|
31
|
+
export interface CheckResult {
|
|
32
|
+
violations: Violation[];
|
|
33
|
+
checkedFunctionCount: number;
|
|
34
|
+
}
|
|
35
|
+
/** Every limit the files exceed, ordered by path, then line. */
|
|
36
|
+
export declare function checkThresholds(files: readonly CheckedFile[], crossFileDuplication: CrossFileDuplicationMetrics | undefined, limitsOf: (language: string) => Limits): CheckResult;
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{duplicationThreshold as e,fileThresholds as t,functionThresholds as n,metricNameOf as r}from"./thresholds.js";const i=[`file`,`function`,`duplication`];function a(r,i,a){let l=u(i,new Set(r.map(({file:e})=>e))),f=[],p=0;for(let i of r){let{file:r,metrics:o,hunks:u}=i,m=a(o.language),h=u?.length===0?[]:c(t,o,m);h.length>0&&f.push({kind:`file`,file:r,startLine:1,endLine:o.lines.total,exceeded:h});let g=s(i);p+=g.length;for(let e of g){let t=c(n,e,m);if(t.length>0){let{startLine:n,endLine:i}=e;f.push({kind:`function`,file:r,startLine:n,endLine:i,name:e.name??`<anonymous>`,exceeded:t})}}f.push(...d(r,o,l.get(r)??[],u,m[e.key]))}return{violations:f.toSorted(o),checkedFunctionCount:p}}function o(e,t){return m(e.file,t.file)||e.startLine-t.startLine||i.indexOf(e.kind)-i.indexOf(t.kind)||e.endLine-t.endLine}function s({metrics:e,hunks:t}){let n=e.language===`python`;return t?e.functions.filter(e=>t.some(t=>l(t,e.startLine,e.endLine,n))):e.functions}function c(e,t,n){return e.flatMap(e=>{let i=e.measure(t),a=n[e.key];return i>a?[{metric:r(e),value:i,limit:a}]:[]})}function l(e,t,n,r=!1){return e.headCount===0?e.headStart>=t&&(e.headStart<n||r&&e.headStart===n):e.headStart<=n&&e.headStart+e.headCount>t}function u(e,t){let n=/* @__PURE__ */ new Map;for(let r of e?.groups??[])for(let e of r.files)if(t.has(e)){let t=n.get(e)??[];t.push(r),n.set(e,t)}return n}function d(t,n,i,a,o){let s=[...n.duplication.duplicateBlockGroups.map(e=>e.map(e=>({...e,file:t}))),...i.map(e=>e.occurrences)],c=n=>n.file===t&&e.measure(n)>=o&&(!a||a.some(e=>e.headCount>0&&l(e,n.startLine,n.endLine))),u=/* @__PURE__ */ new Map;for(let e of s)for(let t of e.filter(e=>c(e)))u.set(t,e);return f([...u.keys()]).map(({merged:t,sources:n})=>({kind:`duplication`,...t,exceeded:[{metric:r(e),value:e.measure(t),limit:o}],partners:f(n.flatMap(e=>u.get(e)??[])).map(e=>e.merged).filter(e=>!p(e,t))}))}function f(e){let t=[],n=e.toSorted((e,t)=>m(e.file,t.file)||e.startLine-t.startLine);for(let e of n){let n=t.at(-1);if(n&&p(n.merged,e))n.merged.endLine=Math.max(n.merged.endLine,e.endLine),n.sources.push(e);else{let{file:n,startLine:r,endLine:i}=e;t.push({merged:{file:n,startLine:r,endLine:i},sources:[e]})}}return t}function p(e,t){return e.file===t.file&&e.startLine<=t.endLine&&t.startLine<=e.endLine}function m(e,t){return e<t?-1:+(e>t)}export{a as checkThresholds};
|
|
2
|
+
//# sourceMappingURL=thresholdCheck.js.map
|