code-gauge 7.0.0 → 8.0.1

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/dist/cli.cjs CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- "use strict";const e=require("./thresholds.cjs"),t=require("./cliConfig.cjs"),n=require("./exclusion.cjs"),r=require("./scan.cjs"),i=require("./checkCommand.cjs");let a=require("@willbooster/shared-lib"),o=require("commander");s().catch(e=>{r.writeStderr(`Error: ${(0,a.getErrorMessage)(e)}\n`),process.exitCode=1});async function s(){let t=new o.Command().name(`code-gauge`).description(`Measure code metrics: rank refactoring candidates (the default command) or check thresholds.`);c(t.command(`rank`,{isDefault:!0}).description(`Rank the files of a project by refactoring priority`).argument(`[target]`,`file or directory to measure`,`.`)).option(`--top <number>`,`number of top-ranked files to report (default: 10)`,C).option(`--fail-on-error`,`exit with code 1 when files or directories cannot be scanned`).action(d);let n=c(t.command(`check`).description(`Report every exceeded threshold (exit 1 on violations, 2 when files cannot be measured); with --base, only in what the change touches`).argument(`[target]`,`file or directory to check`,`.`)).option(`--base <ref>`,`check only what the working tree changed since the merge-base of this git ref and HEAD`);for(let{key:t,defaultLimit:r}of e.thresholds)n.option(`--${u(t)} <number>`,`${l(t)} (default ${r}); "off" disables it`,b);n.exitOverride(e=>process.exit(e.exitCode===0?0:2)),n.action(async(t,n)=>{let r=Object.fromEntries(e.thresholds.flatMap(({key:e})=>n[e]===void 0?[]:[[e,n[e]]]));await i.runCheckCommand(t,n,r)}),await t.parseAsync()}function c(e){return e.option(`--config <path>`,`config file to use instead of the auto-detected ${t.configFileName}`).option(`--duplication-min-tokens <number>`,`minimum normalized token count for a duplicate region (default 40)`,C).option(`--duplication-max-gap-tokens <number>`,`maximum token gap merged into one gapped clone group; 0 disables merging (default 30)`,S).option(`--duplication-min-similarity-percent <number>`,`minimum similarity percent (1-100) for near-miss (Type-3) clone blocks; 100 reports exact matches only (default 70)`,x).option(`--include-tests`,`include test files and test directories`).option(`--json`,`print JSON output`)}function l(t){if(t===e.duplicationThreshold.key)return`line count from which a duplicated block is a violation`;let n=e.fileThresholds.find(e=>e.key===t);return n?`maximum ${n.label}`:`maximum ${e.functionThresholds.find(e=>e.key===t)?.label} of a function`}function u(e){return e.replaceAll(/[A-Z]/gu,e=>`-${e.toLowerCase()}`)}async function d(e,i){let a=r.resolveTarget(e),o=await r.configSearchDirectory(a),s=await t.loadConfig(i.config,o),c=t.resolveOptions(i,s),l=await r.scanTarget(a,{...c,loadExclusion:e=>n.loadExclusion(o,c.exclude,e)});r.addCrossFileDuplication(l,c);let u=f(l,c.top);c.json?g(l,u,c):_(a,l,u,c),(l.fatalError||c.failOnError&&l.errors.length>0)&&(process.exitCode=1)}function f(e,t){let n=e.files.map(({file:t,metrics:n})=>{let i=r.formatPath(t,e.displayRoot),a=r.collectDuplicatedLineNumbers(n,e.crossFileDuplication,i);return{file:i,worstFunction:h(n.functions),duplicatedLineCount:a.size,duplicatedLineRatio:n.lines.code===0?0:a.size/n.lines.code,crossFilePartners:[],ncss:n.ncssCount,codeLines:n.lines.code}}),i=m(n.map(e=>e.worstFunction?.cognitiveComplexity??0)),a=m(n.map(e=>e.duplicatedLineCount)),o=m(n.map(e=>e.ncss)),s=n.map(e=>({...e,score:i(e.worstFunction?.cognitiveComplexity??0)+a(e.duplicatedLineCount)+o(e.ncss)})).toSorted((e,t)=>t.score-e.score||t.ncss-e.ncss||e.file.localeCompare(t.file));return p(s.slice(0,t),e.crossFileDuplication),s}function p(e,t){if(!t)return;let n=new Map(e.map(e=>[e.file,/* @__PURE__ */ new Set]));for(let e of t.groups)for(let t of e.files){let r=n.get(t);if(r)for(let n of e.files)n!==t&&r.add(n)}for(let t of e)t.crossFilePartners=[...n.get(t.file)??[]].toSorted()}function m(e){let t=e.toSorted((e,t)=>e-t);return e=>{let n=0,r=t.length;for(;n<r;){let i=n+r>>1;t[i]<e?n=i+1:r=i}return t.length===0?0:n/t.length}}function h(e){let t;for(let n of e)(!t||n.cognitiveComplexity>t.cognitiveComplexity||n.cognitiveComplexity===t.cognitiveComplexity&&n.ncss>t.ncss)&&(t=n);if(t)return{name:t.name??`<anonymous>`,startLine:t.startLine,endLine:t.endLine,cognitiveComplexity:t.cognitiveComplexity,ncss:t.ncss,nestingDepth:t.nestingDepth}}function g(e,t,n){let i=t.slice(0,n.top);r.writeStdout(JSON.stringify({summary:y(e.files),totalRankedFiles:t.length,truncated:i.length<t.length,files:i,errors:e.errors,warnings:e.warnings},void 0,2)+`
2
+ "use strict";const e=require("./thresholds.cjs"),t=require("./cliConfig.cjs"),n=require("./exclusion.cjs"),r=require("./scan.cjs"),i=require("./checkCommand.cjs");let a=require("@willbooster/shared-lib"),o=require("commander");s().catch(e=>{r.writeStderr(`Error: ${(0,a.getErrorMessage)(e)}\n`),process.exitCode=1});async function s(){let t=new o.Command().name(`code-gauge`).description(`Measure code metrics: rank refactoring candidates (the default command) or check thresholds.`);c(t.command(`rank`,{isDefault:!0}).description(`Rank the files of a project by refactoring priority`).argument(`[target]`,`file or directory to measure`,`.`)).option(`--top <number>`,`number of top-ranked files to report (default: 10)`,C).option(`--fail-on-error`,`exit with code 1 when files or directories cannot be scanned`).action(d);let n=c(t.command(`check`).description(`Report every exceeded threshold as a warning or an error (exit 1 on errors, 2 when files cannot be measured); with --base, only in what the change touches`).argument(`[target]`,`file or directory to check`,`.`)).option(`--base <ref>`,`check only what the working tree changed since the merge-base of this git ref and HEAD`);for(let t of e.levels)for(let{key:r,defaultLimits:i}of e.thresholds){let e=i[t];n.option(`--${t}-${u(r)} <number>`,`${l(r,t)} (default ${Number.isFinite(e)?e:`off`}); "off" disables it`,b)}n.exitOverride(e=>process.exit(e.exitCode===0?0:2)),n.action(async(t,n)=>{let r=t=>Object.fromEntries(e.thresholds.flatMap(({key:e})=>{let r=n[`${t}${e.charAt(0).toUpperCase()}${e.slice(1)}`];return r===void 0?[]:[[e,r]]}));await i.runCheckCommand(t,n,{warning:r(`warning`),error:r(`error`)})}),await t.parseAsync()}function c(e){return e.option(`--config <path>`,`config file to use instead of the auto-detected ${t.configFileName}`).option(`--duplication-min-tokens <number>`,`minimum normalized token count for a duplicate region (default 40)`,C).option(`--duplication-max-gap-tokens <number>`,`maximum token gap merged into one gapped clone group; 0 disables merging (default 30)`,S).option(`--duplication-min-similarity-percent <number>`,`minimum similarity percent (1-100) for near-miss (Type-3) clone blocks; 100 reports exact matches only (default 70)`,x).option(`--include-tests`,`include test files and test directories`).option(`--json`,`print JSON output`)}function l(t,n){if(t===e.duplicationThreshold.key)return`line count from which a duplicated block is ${n===`error`?`an error`:`a warning`}`;let r=e.fileThresholds.find(e=>e.key===t);return`maximum ${r?r.label:`${e.functionThresholds.find(e=>e.key===t)?.label} of a function`} without ${n===`error`?`an error`:`a warning`}`}function u(e){return e.replaceAll(/[A-Z]/gu,e=>`-${e.toLowerCase()}`)}async function d(e,i){let a=r.resolveTarget(e),o=await r.configSearchDirectory(a),s=await t.loadConfig(i.config,o),c=t.resolveOptions(i,s),l=await r.scanTarget(a,{...c,loadExclusion:e=>n.loadExclusion(o,c.exclude,e)});r.addCrossFileDuplication(l,c);let u=f(l,c.top);c.json?g(l,u,c):_(a,l,u,c),(l.fatalError||c.failOnError&&l.errors.length>0)&&(process.exitCode=1)}function f(e,t){let n=e.files.map(({file:t,metrics:n})=>{let i=r.formatPath(t,e.displayRoot),a=r.collectDuplicatedLineNumbers(n,e.crossFileDuplication,i);return{file:i,worstFunction:h(n.functions),duplicatedLineCount:a.size,duplicatedLineRatio:n.lines.code===0?0:a.size/n.lines.code,crossFilePartners:[],ncss:n.ncssCount,codeLines:n.lines.code}}),i=m(n.map(e=>e.worstFunction?.cognitiveComplexity??0)),a=m(n.map(e=>e.duplicatedLineCount)),o=m(n.map(e=>e.ncss)),s=n.map(e=>({...e,score:i(e.worstFunction?.cognitiveComplexity??0)+a(e.duplicatedLineCount)+o(e.ncss)})).toSorted((e,t)=>t.score-e.score||t.ncss-e.ncss||e.file.localeCompare(t.file));return p(s.slice(0,t),e.crossFileDuplication),s}function p(e,t){if(!t)return;let n=new Map(e.map(e=>[e.file,/* @__PURE__ */ new Set]));for(let e of t.groups)for(let t of e.files){let r=n.get(t);if(r)for(let n of e.files)n!==t&&r.add(n)}for(let t of e)t.crossFilePartners=[...n.get(t.file)??[]].toSorted()}function m(e){let t=e.toSorted((e,t)=>e-t);return e=>{let n=0,r=t.length;for(;n<r;){let i=n+r>>1;t[i]<e?n=i+1:r=i}return t.length===0?0:n/t.length}}function h(e){let t;for(let n of e)(!t||n.cognitiveComplexity>t.cognitiveComplexity||n.cognitiveComplexity===t.cognitiveComplexity&&n.ncss>t.ncss)&&(t=n);if(t)return{name:t.name??`<anonymous>`,startLine:t.startLine,endLine:t.endLine,cognitiveComplexity:t.cognitiveComplexity,ncss:t.ncss,nestingDepth:t.nestingDepth}}function g(e,t,n){let i=t.slice(0,n.top);r.writeStdout(JSON.stringify({summary:y(e.files),totalRankedFiles:t.length,truncated:i.length<t.length,files:i,errors:e.errors,warnings:e.warnings},void 0,2)+`
3
3
  `)}function _(e,t,n,i){if(t.fatalError){r.writeStderr(`Error: ${t.fatalError}\n`);return}let a=y(t.files);if(r.writeStdout(`Measured ${a.fileCount} files under ${e} (code LOC ${a.linesOfCode}, NCSS ${a.ncssCount}, functions ${a.functionCount})\n`),n.length===0)r.writeStdout(`No measurable files found.
4
4
  `);else{let e=n.slice(0,i.top),t=n.length>e.length?` of ${n.length}`:``;r.writeStdout(`\nRefactoring candidates (top ${e.length}${t}):\n`);for(let[t,n]of e.entries())r.writeStdout(`${t+1}. ${v(n)}\n`)}if(t.warnings.length>0){r.writeStderr(`\nDegraded ${t.warnings.length} files (measured, but excluded from cross-file matching):\n`);for(let e of t.warnings.slice(0,10))r.writeStderr(`- ${e}\n`);t.warnings.length>10&&r.writeStderr(`- ... ${t.warnings.length-10} more\n`)}if(t.errors.length>0){r.writeStderr(`\nSkipped ${t.errors.length} files or directories:\n`);for(let e of t.errors.slice(0,10))r.writeStderr(`- ${e}\n`);t.errors.length>10&&r.writeStderr(`- ... ${t.errors.length-10} more\n`)}}function v(e){let t=[];if(e.worstFunction){let n=e.worstFunction;t.push(`worst function ${n.name} (L${n.startLine}-${n.endLine}) cognitive ${n.cognitiveComplexity}, NCSS ${n.ncss}, nesting ${n.nestingDepth}`)}if(e.duplicatedLineCount>0){let n=e.crossFilePartners.length>0?`, shared with ${e.crossFilePartners.slice(0,3).join(`, `)}${e.crossFilePartners.length>3?`, ...`:``}`:``;t.push(`duplicated lines ${e.duplicatedLineCount} (${Math.round(e.duplicatedLineRatio*100)}%${n})`)}return t.push(`file NCSS ${e.ncss}`),`${e.file} (score ${e.score.toFixed(2)}): ${t.join(`; `)}`}function y(e){let t=0,n=0,r=0,i=0;for(let a of e)t+=a.metrics.functions.length,n+=a.metrics.lines.code,r=Math.max(r,a.metrics.maxCognitiveComplexity),i+=a.metrics.ncssCount;return{fileCount:e.length,functionCount:t,linesOfCode:n,maxCognitiveComplexity:r,ncssCount:i}}function b(e){if(e===`off`)return 1/0;let t=e.trim()===``?NaN:Number(e);if(!Number.isFinite(t)||t<0)throw new o.InvalidArgumentError(`Expected a non-negative number or "off".`);return t}function x(e){let t=C(e);if(t>100)throw new o.InvalidArgumentError(`Expected an integer between 1 and 100.`);return t}function S(e){if(!/^\d+$/u.test(e))throw new o.InvalidArgumentError(`Expected a non-negative integer.`);let t=Number(e);if(!Number.isSafeInteger(t)||t<0)throw new o.InvalidArgumentError(`Expected a non-negative integer.`);return t}function C(e){let t=(0,a.parsePositiveInteger)(e);if(t===void 0)throw new o.InvalidArgumentError(`Expected a positive integer.`);return t}
5
5
  //# sourceMappingURL=cli.cjs.map
package/dist/cli.cjs.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"cli.cjs","names":["getErrorMessage","Command","thresholds","runCheckCommand","configFileName","duplicationThreshold","fileThresholds","functionThresholds","resolveTarget","configSearchDirectory","loadConfig","resolveOptions","scanTarget","loadExclusion","formatPath","collectDuplicatedLineNumbers","InvalidArgumentError","parsePositiveInteger"],"sources":["../src/cli.ts"],"sourcesContent":["#!/usr/bin/env node\n\nimport { Command, InvalidArgumentError } from 'commander';\nimport { getErrorMessage, parsePositiveInteger } from '@willbooster/shared-lib';\nimport { type CliOptions, configFileName, loadConfig, type ResolvedOptions, resolveOptions } from './cliConfig.js';\nimport type { CrossFileDuplicationMetrics } from './crossFileDuplication.js';\nimport { runCheckCommand, type CheckCliOptions } from './checkCommand.js';\nimport { loadExclusion } from './exclusion.js';\nimport {\n addCrossFileDuplication,\n collectDuplicatedLineNumbers,\n configSearchDirectory,\n formatPath,\n resolveTarget,\n scanTarget,\n writeStderr,\n writeStdout,\n type FileMetrics,\n type ScanResult,\n} from './scan.js';\nimport { duplicationThreshold, fileThresholds, functionThresholds, thresholds } from './thresholds.js';\nimport type { FunctionMetrics } from './types.js';\n\n/** The worst (highest-cognitive-complexity) function of a file, reported as the ranking evidence. */\ninterface WorstFunction {\n name: string;\n startLine: number;\n endLine: number;\n cognitiveComplexity: number;\n ncss: number;\n nestingDepth: number;\n}\n\n/**\n * One ranked refactoring candidate. The score is the sum of the file's repo-relative percentile\n * ranks (each in [0, 1)) over three dimensions: worst-function cognitive complexity, duplicated\n * lines (within-file and cross-file combined), and file NCSS. Ranking is relative to the scanned\n * project, so no absolute threshold is involved.\n */\ninterface RankedFile {\n file: string;\n score: number;\n worstFunction?: WorstFunction;\n /** Distinct lines covered by within-file duplicate blocks or cross-file duplicate occurrences. */\n duplicatedLineCount: number;\n /** duplicatedLineCount / code lines (0 when the file has no code). */\n duplicatedLineRatio: number;\n /** Other files sharing cross-file duplicate blocks; filled only for the reported top files. */\n crossFilePartners: string[];\n ncss: number;\n codeLines: number;\n}\n\n/** Caps how many cross-file partners a ranked file lists so the report stays scannable. */\nconst maxCrossFilePartners = 3;\n\n// oxlint-disable-next-line unicorn/prefer-top-level-await -- CommonJS build output cannot preserve top-level await.\nvoid main().catch((error: unknown) => {\n writeStderr(`Error: ${getErrorMessage(error)}\\n`);\n process.exitCode = 1;\n});\n\nasync function main(): Promise<void> {\n const program = new Command()\n .name('code-gauge')\n .description('Measure code metrics: rank refactoring candidates (the default command) or check thresholds.');\n\n addSharedOptions(\n program\n .command('rank', { isDefault: true })\n .description('Rank the files of a project by refactoring priority')\n .argument('[target]', 'file or directory to measure', '.')\n )\n .option('--top <number>', 'number of top-ranked files to report (default: 10)', parsePositiveIntegerOption)\n .option('--fail-on-error', 'exit with code 1 when files or directories cannot be scanned')\n .action(runRankCommand);\n\n const check = addSharedOptions(\n program\n .command('check')\n .description(\n 'Report every exceeded threshold (exit 1 on violations, 2 when files cannot be measured); with --base, only in what the change touches'\n )\n .argument('[target]', 'file or directory to check', '.')\n ).option('--base <ref>', 'check only what the working tree changed since the merge-base of this git ref and HEAD');\n for (const { key, defaultLimit } of thresholds) {\n check.option(\n `--${toKebabCase(key)} <number>`,\n `${describeLimit(key)} (default ${defaultLimit}); \"off\" disables it`,\n parseLimit\n );\n }\n // Exit code 1 means violations, so a rejected command line must not use it.\n check.exitOverride((error) => process.exit(error.exitCode === 0 ? 0 : 2));\n check.action(async (target: string, cliOptions: CheckCliOptions & Record<string, unknown>) => {\n const cliLimits = Object.fromEntries(\n thresholds.flatMap(({ key }) => (cliOptions[key] === undefined ? [] : [[key, cliOptions[key] as number]]))\n );\n await runCheckCommand(target, cliOptions, cliLimits);\n });\n\n await program.parseAsync();\n}\n\n/** Registers the options shared by the ranking and check commands. */\nfunction addSharedOptions(command: Command): Command {\n return command\n .option('--config <path>', `config file to use instead of the auto-detected ${configFileName}`)\n .option(\n '--duplication-min-tokens <number>',\n 'minimum normalized token count for a duplicate region (default 40)',\n parsePositiveIntegerOption\n )\n .option(\n '--duplication-max-gap-tokens <number>',\n 'maximum token gap merged into one gapped clone group; 0 disables merging (default 30)',\n parseNonNegativeInteger\n )\n .option(\n '--duplication-min-similarity-percent <number>',\n 'minimum similarity percent (1-100) for near-miss (Type-3) clone blocks; 100 reports exact matches only (default 70)',\n parsePercentInteger\n )\n .option('--include-tests', 'include test files and test directories')\n .option('--json', 'print JSON output');\n}\n\nfunction describeLimit(key: string): string {\n if (key === duplicationThreshold.key) {\n return 'line count from which a duplicated block is a violation';\n }\n const fileThreshold = fileThresholds.find((threshold) => threshold.key === key);\n return fileThreshold\n ? `maximum ${fileThreshold.label}`\n : `maximum ${functionThresholds.find((threshold) => threshold.key === key)?.label} of a function`;\n}\n\nfunction toKebabCase(key: string): string {\n return key.replaceAll(/[A-Z]/gu, (letter) => `-${letter.toLowerCase()}`);\n}\n\nasync function runRankCommand(target: string, cliOptions: CliOptions): Promise<void> {\n const resolvedTarget = resolveTarget(target);\n const searchDirectory = await configSearchDirectory(resolvedTarget);\n const config = await loadConfig(cliOptions.config, searchDirectory);\n const options = resolveOptions(cliOptions, config);\n const result = await scanTarget(resolvedTarget, {\n ...options,\n loadExclusion: (absolutePaths) => loadExclusion(searchDirectory, options.exclude, absolutePaths),\n });\n addCrossFileDuplication(result, options);\n const rankedFiles = rankFiles(result, options.top);\n\n if (options.json) {\n printJson(result, rankedFiles, options);\n } else {\n printTextReport(resolvedTarget, result, rankedFiles, options);\n }\n\n if (result.fatalError || (options.failOnError && result.errors.length > 0)) {\n process.exitCode = 1;\n }\n}\n\nfunction rankFiles(result: ScanResult, top: number): RankedFile[] {\n const candidates = result.files.map(({ file, metrics }) => {\n const formattedFile = formatPath(file, result.displayRoot);\n const duplicatedLines = collectDuplicatedLineNumbers(metrics, result.crossFileDuplication, formattedFile);\n return {\n file: formattedFile,\n worstFunction: findWorstFunction(metrics.functions),\n duplicatedLineCount: duplicatedLines.size,\n duplicatedLineRatio: metrics.lines.code === 0 ? 0 : duplicatedLines.size / metrics.lines.code,\n crossFilePartners: [] as string[],\n ncss: metrics.ncssCount,\n codeLines: metrics.lines.code,\n };\n });\n\n const cognitivePercentile = makePercentile(candidates.map((c) => c.worstFunction?.cognitiveComplexity ?? 0));\n const duplicationPercentile = makePercentile(candidates.map((c) => c.duplicatedLineCount));\n const ncssPercentile = makePercentile(candidates.map((c) => c.ncss));\n\n const ranked = candidates\n .map((candidate) => ({\n ...candidate,\n score:\n cognitivePercentile(candidate.worstFunction?.cognitiveComplexity ?? 0) +\n duplicationPercentile(candidate.duplicatedLineCount) +\n ncssPercentile(candidate.ncss),\n }))\n .toSorted(\n (left, right) => right.score - left.score || right.ncss - left.ncss || left.file.localeCompare(right.file)\n );\n // Partner evidence is attached only to the files that will be reported: expanding partners for\n // every scanned file first would retain TH(F^2) strings when one clone group spans F files, and\n // rescanning all groups per file would be O(files x groups) on the post-scan ranking step.\n attachCrossFilePartners(ranked.slice(0, top), result.crossFileDuplication);\n return ranked;\n}\n\n/** One pass over the groups fills the reported files' partner lists (other files sharing a group). */\nfunction attachCrossFilePartners(\n reportedFiles: RankedFile[],\n crossFileDuplication: CrossFileDuplicationMetrics | undefined\n): void {\n if (!crossFileDuplication) {\n return;\n }\n const partnersByFile = new Map(reportedFiles.map((ranked) => [ranked.file, new Set<string>()]));\n for (const group of crossFileDuplication.groups) {\n for (const file of group.files) {\n const partners = partnersByFile.get(file);\n if (!partners) {\n continue;\n }\n for (const partner of group.files) {\n if (partner !== file) {\n partners.add(partner);\n }\n }\n }\n }\n for (const ranked of reportedFiles) {\n ranked.crossFilePartners = [...(partnersByFile.get(ranked.file) ?? [])].toSorted();\n }\n}\n\n/**\n * Percentile rank within the scanned project: the fraction of files with a strictly smaller\n * value, in [0, 1). Relative ranking needs no absolute threshold, which sidesteps the metric\n * calibration problem entirely — the top of the list is worth refactoring first regardless of\n * where any cutoff would sit.\n */\nfunction makePercentile(values: number[]): (value: number) => number {\n const sorted = values.toSorted((left, right) => left - right);\n return (value: number) => {\n let low = 0;\n let high = sorted.length;\n while (low < high) {\n const middle = (low + high) >> 1;\n if ((sorted[middle] as number) < value) {\n low = middle + 1;\n } else {\n high = middle;\n }\n }\n return sorted.length === 0 ? 0 : low / sorted.length;\n };\n}\n\n/** The highest-cognitive-complexity function; NCSS breaks ties so the larger body is reported. */\nfunction findWorstFunction(functions: FunctionMetrics[]): WorstFunction | undefined {\n let worst: FunctionMetrics | undefined;\n for (const fn of functions) {\n if (\n !worst ||\n fn.cognitiveComplexity > worst.cognitiveComplexity ||\n (fn.cognitiveComplexity === worst.cognitiveComplexity && fn.ncss > worst.ncss)\n ) {\n worst = fn;\n }\n }\n if (!worst) {\n return undefined;\n }\n return {\n name: worst.name ?? '<anonymous>',\n startLine: worst.startLine,\n endLine: worst.endLine,\n cognitiveComplexity: worst.cognitiveComplexity,\n ncss: worst.ncss,\n nestingDepth: worst.nestingDepth,\n };\n}\n\nfunction printJson(result: ScanResult, rankedFiles: RankedFile[], options: ResolvedOptions): void {\n const reportedFiles = rankedFiles.slice(0, options.top);\n writeStdout(\n JSON.stringify(\n {\n summary: summarize(result.files),\n totalRankedFiles: rankedFiles.length,\n truncated: reportedFiles.length < rankedFiles.length,\n files: reportedFiles,\n errors: result.errors,\n warnings: result.warnings,\n },\n undefined,\n 2\n ) + '\\n'\n );\n}\n\nfunction printTextReport(\n target: string,\n result: ScanResult,\n rankedFiles: RankedFile[],\n options: ResolvedOptions\n): void {\n if (result.fatalError) {\n writeStderr(`Error: ${result.fatalError}\\n`);\n return;\n }\n\n const summary = summarize(result.files);\n writeStdout(\n `Measured ${summary.fileCount} files under ${target} (code LOC ${summary.linesOfCode}, NCSS ${summary.ncssCount}, functions ${summary.functionCount})\\n`\n );\n\n if (rankedFiles.length === 0) {\n writeStdout('No measurable files found.\\n');\n } else {\n const reportedFiles = rankedFiles.slice(0, options.top);\n const totalSuffix = rankedFiles.length > reportedFiles.length ? ` of ${rankedFiles.length}` : '';\n writeStdout(`\\nRefactoring candidates (top ${reportedFiles.length}${totalSuffix}):\\n`);\n for (const [index, ranked] of reportedFiles.entries()) {\n writeStdout(`${index + 1}. ${formatRankedFile(ranked)}\\n`);\n }\n }\n\n if (result.warnings.length > 0) {\n writeStderr(`\\nDegraded ${result.warnings.length} files (measured, but excluded from cross-file matching):\\n`);\n for (const warning of result.warnings.slice(0, 10)) {\n writeStderr(`- ${warning}\\n`);\n }\n if (result.warnings.length > 10) {\n writeStderr(`- ... ${result.warnings.length - 10} more\\n`);\n }\n }\n\n if (result.errors.length > 0) {\n writeStderr(`\\nSkipped ${result.errors.length} files or directories:\\n`);\n for (const error of result.errors.slice(0, 10)) {\n writeStderr(`- ${error}\\n`);\n }\n if (result.errors.length > 10) {\n writeStderr(`- ... ${result.errors.length - 10} more\\n`);\n }\n }\n}\n\n/** One ranked file as a single line: the location, the evidence, and where the duplication points. */\nfunction formatRankedFile(ranked: RankedFile): string {\n const reasons: string[] = [];\n if (ranked.worstFunction) {\n const fn = ranked.worstFunction;\n reasons.push(\n `worst function ${fn.name} (L${fn.startLine}-${fn.endLine}) cognitive ${fn.cognitiveComplexity}, NCSS ${fn.ncss}, nesting ${fn.nestingDepth}`\n );\n }\n if (ranked.duplicatedLineCount > 0) {\n const partnersSuffix =\n ranked.crossFilePartners.length > 0\n ? `, shared with ${ranked.crossFilePartners.slice(0, maxCrossFilePartners).join(', ')}${ranked.crossFilePartners.length > maxCrossFilePartners ? ', ...' : ''}`\n : '';\n reasons.push(\n `duplicated lines ${ranked.duplicatedLineCount} (${Math.round(ranked.duplicatedLineRatio * 100)}%${partnersSuffix})`\n );\n }\n reasons.push(`file NCSS ${ranked.ncss}`);\n return `${ranked.file} (score ${ranked.score.toFixed(2)}): ${reasons.join('; ')}`;\n}\n\nfunction summarize(files: FileMetrics[]): {\n fileCount: number;\n functionCount: number;\n linesOfCode: number;\n maxCognitiveComplexity: number;\n ncssCount: number;\n} {\n let functionCount = 0;\n let linesOfCode = 0;\n let maxCognitiveComplexity = 0;\n let ncssCount = 0;\n\n for (const file of files) {\n functionCount += file.metrics.functions.length;\n linesOfCode += file.metrics.lines.code;\n maxCognitiveComplexity = Math.max(maxCognitiveComplexity, file.metrics.maxCognitiveComplexity);\n ncssCount += file.metrics.ncssCount;\n }\n\n return { fileCount: files.length, functionCount, linesOfCode, maxCognitiveComplexity, ncssCount };\n}\n\nfunction parseLimit(value: string): number {\n if (value === 'off') {\n return Infinity;\n }\n const parsed = value.trim() === '' ? Number.NaN : Number(value);\n if (!Number.isFinite(parsed) || parsed < 0) {\n throw new InvalidArgumentError('Expected a non-negative number or \"off\".');\n }\n return parsed;\n}\n\nfunction parsePercentInteger(value: string): number {\n const parsed = parsePositiveIntegerOption(value);\n if (parsed > 100) {\n throw new InvalidArgumentError('Expected an integer between 1 and 100.');\n }\n return parsed;\n}\n\nfunction parseNonNegativeInteger(value: string): number {\n if (!/^\\d+$/u.test(value)) {\n throw new InvalidArgumentError('Expected a non-negative integer.');\n }\n\n const parsed = Number(value);\n if (!Number.isSafeInteger(parsed) || parsed < 0) {\n throw new InvalidArgumentError('Expected a non-negative integer.');\n }\n return parsed;\n}\n\nfunction parsePositiveIntegerOption(value: string): number {\n const parsed = parsePositiveInteger(value);\n if (parsed === undefined) {\n throw new InvalidArgumentError('Expected a positive integer.');\n }\n return parsed;\n}\n"],"mappings":";mOAyDK,EAAK,CAAC,CAAC,MAAO,GAAmB,CACpC,EAAA,YAAY,WAAA,EAAUA,EAAAA,gBAAAA,CAAgB,CAAK,EAAE,GAAG,EAChD,QAAQ,SAAW,CACrB,CAAC,EAED,eAAe,GAAsB,CACnC,IAAM,EAAU,IAAIC,EAAAA,QAAQ,CAAC,CAC1B,KAAK,YAAY,CAAC,CAClB,YAAY,8FAA8F,EAE7G,EACE,EACG,QAAQ,OAAQ,CAAE,UAAW,EAAK,CAAC,CAAC,CACpC,YAAY,qDAAqD,CAAC,CAClE,SAAS,WAAY,+BAAgC,GAAG,CAC7D,CAAC,CACE,OAAO,iBAAkB,qDAAsD,CAA0B,CAAC,CAC1G,OAAO,kBAAmB,8DAA8D,CAAC,CACzF,OAAO,CAAc,EAExB,IAAM,EAAQ,EACZ,EACG,QAAQ,OAAO,CAAC,CAChB,YACC,uIACF,CAAC,CACA,SAAS,WAAY,6BAA8B,GAAG,CAC3D,CAAC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AuB,CACzC,GAAI,IAAU,MACZ,MAAO,KAET,IAAM,EAAS,EAAM,KAAK,IAAM,GAAK,IAAa,OAAO,CAAK,EAC9D,GAAI,CAAC,OAAO,SAAS,CAAM,GAAK,EAAS,EACvC,MAAM,IAAIC,EAAAA,qBAAqB,0CAA0C,EAE3E,OAAO,CACT,CAEA,SAAS,EAAoB,EAAuB,CAClD,IAAM,EAAS,EAA2B,CAAK,EAC/C,GAAI,EAAS,IACX,MAAM,IAAIA,EAAAA,qBAAqB,wCAAwC,EAEzE,OAAO,CACT,CAEA,SAAS,EAAwB,EAAuB,CACtD,GAAI,CAAC,SAAS,KAAK,CAAK,EACtB,MAAM,IAAIA,EAAAA,qBAAqB,kCAAkC,EAGnE,IAAM,EAAS,OAAO,CAAK,EAC3B,GAAI,CAAC,OAAO,cAAc,CAAM,GAAK,EAAS,EAC5C,MAAM,IAAIA,EAAAA,qBAAqB,kCAAkC,EAEnE,OAAO,CACT,CAEA,SAAS,EAA2B,EAAuB,CACzD,IAAM,GAAA,EAASC,EAAAA,qBAAAA,CAAqB,CAAK,EACzC,GAAI,IAAW,IAAA,GACb,MAAM,IAAID,EAAAA,qBAAqB,8BAA8B,EAE/D,OAAO,CACT"}
1
+ {"version":3,"file":"cli.cjs","names":["getErrorMessage","Command","levels","thresholds","runCheckCommand","configFileName","duplicationThreshold","fileThresholds","functionThresholds","resolveTarget","configSearchDirectory","loadConfig","resolveOptions","scanTarget","loadExclusion","formatPath","collectDuplicatedLineNumbers","InvalidArgumentError","parsePositiveInteger"],"sources":["../src/cli.ts"],"sourcesContent":["#!/usr/bin/env node\n\nimport { Command, InvalidArgumentError } from 'commander';\nimport { getErrorMessage, parsePositiveInteger } from '@willbooster/shared-lib';\nimport { type CliOptions, configFileName, loadConfig, type ResolvedOptions, resolveOptions } from './cliConfig.js';\nimport type { CrossFileDuplicationMetrics } from './crossFileDuplication.js';\nimport { runCheckCommand, type CheckCliOptions } from './checkCommand.js';\nimport { loadExclusion } from './exclusion.js';\nimport {\n addCrossFileDuplication,\n collectDuplicatedLineNumbers,\n configSearchDirectory,\n formatPath,\n resolveTarget,\n scanTarget,\n writeStderr,\n writeStdout,\n type FileMetrics,\n type ScanResult,\n} from './scan.js';\nimport {\n duplicationThreshold,\n fileThresholds,\n functionThresholds,\n levels,\n thresholds,\n type Level,\n type Limits,\n} from './thresholds.js';\nimport type { FunctionMetrics } from './types.js';\n\n/** The worst (highest-cognitive-complexity) function of a file, reported as the ranking evidence. */\ninterface WorstFunction {\n name: string;\n startLine: number;\n endLine: number;\n cognitiveComplexity: number;\n ncss: number;\n nestingDepth: number;\n}\n\n/**\n * One ranked refactoring candidate. The score is the sum of the file's repo-relative percentile\n * ranks (each in [0, 1)) over three dimensions: worst-function cognitive complexity, duplicated\n * lines (within-file and cross-file combined), and file NCSS. Ranking is relative to the scanned\n * project, so no absolute threshold is involved.\n */\ninterface RankedFile {\n file: string;\n score: number;\n worstFunction?: WorstFunction;\n /** Distinct lines covered by within-file duplicate blocks or cross-file duplicate occurrences. */\n duplicatedLineCount: number;\n /** duplicatedLineCount / code lines (0 when the file has no code). */\n duplicatedLineRatio: number;\n /** Other files sharing cross-file duplicate blocks; filled only for the reported top files. */\n crossFilePartners: string[];\n ncss: number;\n codeLines: number;\n}\n\n/** Caps how many cross-file partners a ranked file lists so the report stays scannable. */\nconst maxCrossFilePartners = 3;\n\n// oxlint-disable-next-line unicorn/prefer-top-level-await -- CommonJS build output cannot preserve top-level await.\nvoid main().catch((error: unknown) => {\n writeStderr(`Error: ${getErrorMessage(error)}\\n`);\n process.exitCode = 1;\n});\n\nasync function main(): Promise<void> {\n const program = new Command()\n .name('code-gauge')\n .description('Measure code metrics: rank refactoring candidates (the default command) or check thresholds.');\n\n addSharedOptions(\n program\n .command('rank', { isDefault: true })\n .description('Rank the files of a project by refactoring priority')\n .argument('[target]', 'file or directory to measure', '.')\n )\n .option('--top <number>', 'number of top-ranked files to report (default: 10)', parsePositiveIntegerOption)\n .option('--fail-on-error', 'exit with code 1 when files or directories cannot be scanned')\n .action(runRankCommand);\n\n const check = addSharedOptions(\n program\n .command('check')\n .description(\n 'Report every exceeded threshold as a warning or an error (exit 1 on errors, 2 when files cannot be measured); with --base, only in what the change touches'\n )\n .argument('[target]', 'file or directory to check', '.')\n ).option('--base <ref>', 'check only what the working tree changed since the merge-base of this git ref and HEAD');\n for (const level of levels) {\n for (const { key, defaultLimits } of thresholds) {\n const defaultLimit = defaultLimits[level];\n check.option(\n `--${level}-${toKebabCase(key)} <number>`,\n `${describeLimit(key, level)} (default ${Number.isFinite(defaultLimit) ? defaultLimit : 'off'}); \"off\" disables it`,\n parseLimit\n );\n }\n }\n // Exit code 1 means error-level violations, so a rejected command line must not use it.\n check.exitOverride((error) => process.exit(error.exitCode === 0 ? 0 : 2));\n check.action(async (target: string, cliOptions: CheckCliOptions & Record<string, unknown>) => {\n const readLimits = (level: Level): Limits =>\n Object.fromEntries(\n thresholds.flatMap(({ key }) => {\n const limit = cliOptions[`${level}${key.charAt(0).toUpperCase()}${key.slice(1)}`];\n return limit === undefined ? [] : [[key, limit as number]];\n })\n );\n await runCheckCommand(target, cliOptions, { warning: readLimits('warning'), error: readLimits('error') });\n });\n\n await program.parseAsync();\n}\n\n/** Registers the options shared by the ranking and check commands. */\nfunction addSharedOptions(command: Command): Command {\n return command\n .option('--config <path>', `config file to use instead of the auto-detected ${configFileName}`)\n .option(\n '--duplication-min-tokens <number>',\n 'minimum normalized token count for a duplicate region (default 40)',\n parsePositiveIntegerOption\n )\n .option(\n '--duplication-max-gap-tokens <number>',\n 'maximum token gap merged into one gapped clone group; 0 disables merging (default 30)',\n parseNonNegativeInteger\n )\n .option(\n '--duplication-min-similarity-percent <number>',\n 'minimum similarity percent (1-100) for near-miss (Type-3) clone blocks; 100 reports exact matches only (default 70)',\n parsePercentInteger\n )\n .option('--include-tests', 'include test files and test directories')\n .option('--json', 'print JSON output');\n}\n\nfunction describeLimit(key: string, level: Level): string {\n if (key === duplicationThreshold.key) {\n return `line count from which a duplicated block is ${level === 'error' ? 'an error' : 'a warning'}`;\n }\n const fileThreshold = fileThresholds.find((threshold) => threshold.key === key);\n const subject = fileThreshold\n ? fileThreshold.label\n : `${functionThresholds.find((threshold) => threshold.key === key)?.label} of a function`;\n return `maximum ${subject} without ${level === 'error' ? 'an error' : 'a warning'}`;\n}\n\nfunction toKebabCase(key: string): string {\n return key.replaceAll(/[A-Z]/gu, (letter) => `-${letter.toLowerCase()}`);\n}\n\nasync function runRankCommand(target: string, cliOptions: CliOptions): Promise<void> {\n const resolvedTarget = resolveTarget(target);\n const searchDirectory = await configSearchDirectory(resolvedTarget);\n const config = await loadConfig(cliOptions.config, searchDirectory);\n const options = resolveOptions(cliOptions, config);\n const result = await scanTarget(resolvedTarget, {\n ...options,\n loadExclusion: (absolutePaths) => loadExclusion(searchDirectory, options.exclude, absolutePaths),\n });\n addCrossFileDuplication(result, options);\n const rankedFiles = rankFiles(result, options.top);\n\n if (options.json) {\n printJson(result, rankedFiles, options);\n } else {\n printTextReport(resolvedTarget, result, rankedFiles, options);\n }\n\n if (result.fatalError || (options.failOnError && result.errors.length > 0)) {\n process.exitCode = 1;\n }\n}\n\nfunction rankFiles(result: ScanResult, top: number): RankedFile[] {\n const candidates = result.files.map(({ file, metrics }) => {\n const formattedFile = formatPath(file, result.displayRoot);\n const duplicatedLines = collectDuplicatedLineNumbers(metrics, result.crossFileDuplication, formattedFile);\n return {\n file: formattedFile,\n worstFunction: findWorstFunction(metrics.functions),\n duplicatedLineCount: duplicatedLines.size,\n duplicatedLineRatio: metrics.lines.code === 0 ? 0 : duplicatedLines.size / metrics.lines.code,\n crossFilePartners: [] as string[],\n ncss: metrics.ncssCount,\n codeLines: metrics.lines.code,\n };\n });\n\n const cognitivePercentile = makePercentile(candidates.map((c) => c.worstFunction?.cognitiveComplexity ?? 0));\n const duplicationPercentile = makePercentile(candidates.map((c) => c.duplicatedLineCount));\n const ncssPercentile = makePercentile(candidates.map((c) => c.ncss));\n\n const ranked = candidates\n .map((candidate) => ({\n ...candidate,\n score:\n cognitivePercentile(candidate.worstFunction?.cognitiveComplexity ?? 0) +\n duplicationPercentile(candidate.duplicatedLineCount) +\n ncssPercentile(candidate.ncss),\n }))\n .toSorted(\n (left, right) => right.score - left.score || right.ncss - left.ncss || left.file.localeCompare(right.file)\n );\n // Partner evidence is attached only to the files that will be reported: expanding partners for\n // every scanned file first would retain TH(F^2) strings when one clone group spans F files, and\n // rescanning all groups per file would be O(files x groups) on the post-scan ranking step.\n attachCrossFilePartners(ranked.slice(0, top), result.crossFileDuplication);\n return ranked;\n}\n\n/** One pass over the groups fills the reported files' partner lists (other files sharing a group). */\nfunction attachCrossFilePartners(\n reportedFiles: RankedFile[],\n crossFileDuplication: CrossFileDuplicationMetrics | undefined\n): void {\n if (!crossFileDuplication) {\n return;\n }\n const partnersByFile = new Map(reportedFiles.map((ranked) => [ranked.file, new Set<string>()]));\n for (const group of crossFileDuplication.groups) {\n for (const file of group.files) {\n const partners = partnersByFile.get(file);\n if (!partners) {\n continue;\n }\n for (const partner of group.files) {\n if (partner !== file) {\n partners.add(partner);\n }\n }\n }\n }\n for (const ranked of reportedFiles) {\n ranked.crossFilePartners = [...(partnersByFile.get(ranked.file) ?? [])].toSorted();\n }\n}\n\n/**\n * Percentile rank within the scanned project: the fraction of files with a strictly smaller\n * value, in [0, 1). Relative ranking needs no absolute threshold, which sidesteps the metric\n * calibration problem entirely — the top of the list is worth refactoring first regardless of\n * where any cutoff would sit.\n */\nfunction makePercentile(values: number[]): (value: number) => number {\n const sorted = values.toSorted((left, right) => left - right);\n return (value: number) => {\n let low = 0;\n let high = sorted.length;\n while (low < high) {\n const middle = (low + high) >> 1;\n if ((sorted[middle] as number) < value) {\n low = middle + 1;\n } else {\n high = middle;\n }\n }\n return sorted.length === 0 ? 0 : low / sorted.length;\n };\n}\n\n/** The highest-cognitive-complexity function; NCSS breaks ties so the larger body is reported. */\nfunction findWorstFunction(functions: FunctionMetrics[]): WorstFunction | undefined {\n let worst: FunctionMetrics | undefined;\n for (const fn of functions) {\n if (\n !worst ||\n fn.cognitiveComplexity > worst.cognitiveComplexity ||\n (fn.cognitiveComplexity === worst.cognitiveComplexity && fn.ncss > worst.ncss)\n ) {\n worst = fn;\n }\n }\n if (!worst) {\n return undefined;\n }\n return {\n name: worst.name ?? '<anonymous>',\n startLine: worst.startLine,\n endLine: worst.endLine,\n cognitiveComplexity: worst.cognitiveComplexity,\n ncss: worst.ncss,\n nestingDepth: worst.nestingDepth,\n };\n}\n\nfunction printJson(result: ScanResult, rankedFiles: RankedFile[], options: ResolvedOptions): void {\n const reportedFiles = rankedFiles.slice(0, options.top);\n writeStdout(\n JSON.stringify(\n {\n summary: summarize(result.files),\n totalRankedFiles: rankedFiles.length,\n truncated: reportedFiles.length < rankedFiles.length,\n files: reportedFiles,\n errors: result.errors,\n warnings: result.warnings,\n },\n undefined,\n 2\n ) + '\\n'\n );\n}\n\nfunction printTextReport(\n target: string,\n result: ScanResult,\n rankedFiles: RankedFile[],\n options: ResolvedOptions\n): void {\n if (result.fatalError) {\n writeStderr(`Error: ${result.fatalError}\\n`);\n return;\n }\n\n const summary = summarize(result.files);\n writeStdout(\n `Measured ${summary.fileCount} files under ${target} (code LOC ${summary.linesOfCode}, NCSS ${summary.ncssCount}, functions ${summary.functionCount})\\n`\n );\n\n if (rankedFiles.length === 0) {\n writeStdout('No measurable files found.\\n');\n } else {\n const reportedFiles = rankedFiles.slice(0, options.top);\n const totalSuffix = rankedFiles.length > reportedFiles.length ? ` of ${rankedFiles.length}` : '';\n writeStdout(`\\nRefactoring candidates (top ${reportedFiles.length}${totalSuffix}):\\n`);\n for (const [index, ranked] of reportedFiles.entries()) {\n writeStdout(`${index + 1}. ${formatRankedFile(ranked)}\\n`);\n }\n }\n\n if (result.warnings.length > 0) {\n writeStderr(`\\nDegraded ${result.warnings.length} files (measured, but excluded from cross-file matching):\\n`);\n for (const warning of result.warnings.slice(0, 10)) {\n writeStderr(`- ${warning}\\n`);\n }\n if (result.warnings.length > 10) {\n writeStderr(`- ... ${result.warnings.length - 10} more\\n`);\n }\n }\n\n if (result.errors.length > 0) {\n writeStderr(`\\nSkipped ${result.errors.length} files or directories:\\n`);\n for (const error of result.errors.slice(0, 10)) {\n writeStderr(`- ${error}\\n`);\n }\n if (result.errors.length > 10) {\n writeStderr(`- ... ${result.errors.length - 10} more\\n`);\n }\n }\n}\n\n/** One ranked file as a single line: the location, the evidence, and where the duplication points. */\nfunction formatRankedFile(ranked: RankedFile): string {\n const reasons: string[] = [];\n if (ranked.worstFunction) {\n const fn = ranked.worstFunction;\n reasons.push(\n `worst function ${fn.name} (L${fn.startLine}-${fn.endLine}) cognitive ${fn.cognitiveComplexity}, NCSS ${fn.ncss}, nesting ${fn.nestingDepth}`\n );\n }\n if (ranked.duplicatedLineCount > 0) {\n const partnersSuffix =\n ranked.crossFilePartners.length > 0\n ? `, shared with ${ranked.crossFilePartners.slice(0, maxCrossFilePartners).join(', ')}${ranked.crossFilePartners.length > maxCrossFilePartners ? ', ...' : ''}`\n : '';\n reasons.push(\n `duplicated lines ${ranked.duplicatedLineCount} (${Math.round(ranked.duplicatedLineRatio * 100)}%${partnersSuffix})`\n );\n }\n reasons.push(`file NCSS ${ranked.ncss}`);\n return `${ranked.file} (score ${ranked.score.toFixed(2)}): ${reasons.join('; ')}`;\n}\n\nfunction summarize(files: FileMetrics[]): {\n fileCount: number;\n functionCount: number;\n linesOfCode: number;\n maxCognitiveComplexity: number;\n ncssCount: number;\n} {\n let functionCount = 0;\n let linesOfCode = 0;\n let maxCognitiveComplexity = 0;\n let ncssCount = 0;\n\n for (const file of files) {\n functionCount += file.metrics.functions.length;\n linesOfCode += file.metrics.lines.code;\n maxCognitiveComplexity = Math.max(maxCognitiveComplexity, file.metrics.maxCognitiveComplexity);\n ncssCount += file.metrics.ncssCount;\n }\n\n return { fileCount: files.length, functionCount, linesOfCode, maxCognitiveComplexity, ncssCount };\n}\n\nfunction parseLimit(value: string): number {\n if (value === 'off') {\n return Infinity;\n }\n const parsed = value.trim() === '' ? Number.NaN : Number(value);\n if (!Number.isFinite(parsed) || parsed < 0) {\n throw new InvalidArgumentError('Expected a non-negative number or \"off\".');\n }\n return parsed;\n}\n\nfunction parsePercentInteger(value: string): number {\n const parsed = parsePositiveIntegerOption(value);\n if (parsed > 100) {\n throw new InvalidArgumentError('Expected an integer between 1 and 100.');\n }\n return parsed;\n}\n\nfunction parseNonNegativeInteger(value: string): number {\n if (!/^\\d+$/u.test(value)) {\n throw new InvalidArgumentError('Expected a non-negative integer.');\n }\n\n const parsed = Number(value);\n if (!Number.isSafeInteger(parsed) || parsed < 0) {\n throw new InvalidArgumentError('Expected a non-negative integer.');\n }\n return parsed;\n}\n\nfunction parsePositiveIntegerOption(value: string): number {\n const parsed = parsePositiveInteger(value);\n if (parsed === undefined) {\n throw new InvalidArgumentError('Expected a positive integer.');\n }\n return parsed;\n}\n"],"mappings":";mOAiEK,EAAK,CAAC,CAAC,MAAO,GAAmB,CACpC,EAAA,YAAY,WAAA,EAAUA,EAAAA,gBAAAA,CAAgB,CAAK,EAAE,GAAG,EAChD,QAAQ,SAAW,CACrB,CAAC,EAED,eAAe,GAAsB,CACnC,IAAM,EAAU,IAAIC,EAAAA,QAAQ,CAAC,CAC1B,KAAK,YAAY,CAAC,CAClB,YAAY,8FAA8F,EAE7G,EACE,EACG,QAAQ,OAAQ,CAAE,UAAW,EAAK,CAAC,CAAC,CACpC,YAAY,qDAAqD,CAAC,CAClE,SAAS,WAAY,+BAAgC,GAAG,CAC7D,CAAC,CACE,OAAO,iBAAkB,qDAAsD,CAA0B,CAAC,CAC1G,OAAO,kBAAmB,8DAA8D,CAAC,CACzF,OAAO,CAAc,EAExB,IAAM,EAAQ,EACZ,EACG,QAAQ,OAAO,CAAC,CAChB,YACC,4JACF,CAAC,CACA,SAAS,WAAY,6BAA8B,GAAG,CAC3D,CAAC,CAAC,OAAO,eAAgB,wFAAwF,EACjH,IAAK,IAAM,KAASC,EAAAA,OACl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EAAyB,EACzB,EAAY,EAEhB,IAAK,IAAM,KAAQ,EACjB,GAAiB,EAAK,QAAQ,UAAU,OACxC,GAAe,EAAK,QAAQ,MAAM,KAClC,EAAyB,KAAK,IAAI,EAAwB,EAAK,QAAQ,sBAAsB,EAC7F,GAAa,EAAK,QAAQ,UAG5B,MAAO,CAAE,UAAW,EAAM,OAAQ,gBAAe,cAAa,yBAAwB,WAAU,CAClG,CAEA,SAAS,EAAW,EAAuB,CACzC,GAAI,IAAU,MACZ,MAAO,KAET,IAAM,EAAS,EAAM,KAAK,IAAM,GAAK,IAAa,OAAO,CAAK,EAC9D,GAAI,CAAC,OAAO,SAAS,CAAM,GAAK,EAAS,EACvC,MAAM,IAAIC,EAAAA,qBAAqB,0CAA0C,EAE3E,OAAO,CACT,CAEA,SAAS,EAAoB,EAAuB,CAClD,IAAM,EAAS,EAA2B,CAAK,EAC/C,GAAI,EAAS,IACX,MAAM,IAAIA,EAAAA,qBAAqB,wCAAwC,EAEzE,OAAO,CACT,CAEA,SAAS,EAAwB,EAAuB,CACtD,GAAI,CAAC,SAAS,KAAK,CAAK,EACtB,MAAM,IAAIA,EAAAA,qBAAqB,kCAAkC,EAGnE,IAAM,EAAS,OAAO,CAAK,EAC3B,GAAI,CAAC,OAAO,cAAc,CAAM,GAAK,EAAS,EAC5C,MAAM,IAAIA,EAAAA,qBAAqB,kCAAkC,EAEnE,OAAO,CACT,CAEA,SAAS,EAA2B,EAAuB,CACzD,IAAM,GAAA,EAASC,EAAAA,qBAAAA,CAAqB,CAAK,EACzC,GAAI,IAAW,IAAA,GACb,MAAM,IAAID,EAAAA,qBAAqB,8BAA8B,EAE/D,OAAO,CACT"}
package/dist/cli.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import{duplicationThreshold as e,fileThresholds as t,functionThresholds as n,thresholds as r}from"./thresholds.js";import{configFileName as i,loadConfig as a,resolveOptions as o}from"./cliConfig.js";import{loadExclusion as s}from"./exclusion.js";import{addCrossFileDuplication as c,collectDuplicatedLineNumbers as l,configSearchDirectory as u,formatPath as d,resolveTarget as f,scanTarget as p,writeStderr as m,writeStdout as h}from"./scan.js";import{runCheckCommand as g}from"./checkCommand.js";import{getErrorMessage as _,parsePositiveInteger as v}from"@willbooster/shared-lib";import{Command as y,InvalidArgumentError as b}from"commander";x().catch(e=>{m(`Error: ${_(e)}\n`),process.exitCode=1});async function x(){let e=new y().name(`code-gauge`).description(`Measure code metrics: rank refactoring candidates (the default command) or check thresholds.`);S(e.command(`rank`,{isDefault:!0}).description(`Rank the files of a project by refactoring priority`).argument(`[target]`,`file or directory to measure`,`.`)).option(`--top <number>`,`number of top-ranked files to report (default: 10)`,L).option(`--fail-on-error`,`exit with code 1 when files or directories cannot be scanned`).action(T);let t=S(e.command(`check`).description(`Report every exceeded threshold (exit 1 on violations, 2 when files cannot be measured); with --base, only in what the change touches`).argument(`[target]`,`file or directory to check`,`.`)).option(`--base <ref>`,`check only what the working tree changed since the merge-base of this git ref and HEAD`);for(let{key:e,defaultLimit:n}of r)t.option(`--${w(e)} <number>`,`${C(e)} (default ${n}); "off" disables it`,P);t.exitOverride(e=>process.exit(e.exitCode===0?0:2)),t.action(async(e,t)=>{let n=Object.fromEntries(r.flatMap(({key:e})=>t[e]===void 0?[]:[[e,t[e]]]));await g(e,t,n)}),await e.parseAsync()}function S(e){return e.option(`--config <path>`,`config file to use instead of the auto-detected ${i}`).option(`--duplication-min-tokens <number>`,`minimum normalized token count for a duplicate region (default 40)`,L).option(`--duplication-max-gap-tokens <number>`,`maximum token gap merged into one gapped clone group; 0 disables merging (default 30)`,I).option(`--duplication-min-similarity-percent <number>`,`minimum similarity percent (1-100) for near-miss (Type-3) clone blocks; 100 reports exact matches only (default 70)`,F).option(`--include-tests`,`include test files and test directories`).option(`--json`,`print JSON output`)}function C(r){if(r===e.key)return`line count from which a duplicated block is a violation`;let i=t.find(e=>e.key===r);return i?`maximum ${i.label}`:`maximum ${n.find(e=>e.key===r)?.label} of a function`}function w(e){return e.replaceAll(/[A-Z]/gu,e=>`-${e.toLowerCase()}`)}async function T(e,t){let n=f(e),r=await u(n),i=await a(t.config,r),l=o(t,i),d=await p(n,{...l,loadExclusion:e=>s(r,l.exclude,e)});c(d,l);let m=E(d,l.top);l.json?A(d,m,l):j(n,d,m,l),(d.fatalError||l.failOnError&&d.errors.length>0)&&(process.exitCode=1)}function E(e,t){let n=e.files.map(({file:t,metrics:n})=>{let r=d(t,e.displayRoot),i=l(n,e.crossFileDuplication,r);return{file:r,worstFunction:k(n.functions),duplicatedLineCount:i.size,duplicatedLineRatio:n.lines.code===0?0:i.size/n.lines.code,crossFilePartners:[],ncss:n.ncssCount,codeLines:n.lines.code}}),r=O(n.map(e=>e.worstFunction?.cognitiveComplexity??0)),i=O(n.map(e=>e.duplicatedLineCount)),a=O(n.map(e=>e.ncss)),o=n.map(e=>({...e,score:r(e.worstFunction?.cognitiveComplexity??0)+i(e.duplicatedLineCount)+a(e.ncss)})).toSorted((e,t)=>t.score-e.score||t.ncss-e.ncss||e.file.localeCompare(t.file));return D(o.slice(0,t),e.crossFileDuplication),o}function D(e,t){if(!t)return;let n=new Map(e.map(e=>[e.file,/* @__PURE__ */ new Set]));for(let e of t.groups)for(let t of e.files){let r=n.get(t);if(r)for(let n of e.files)n!==t&&r.add(n)}for(let t of e)t.crossFilePartners=[...n.get(t.file)??[]].toSorted()}function O(e){let t=e.toSorted((e,t)=>e-t);return e=>{let n=0,r=t.length;for(;n<r;){let i=n+r>>1;t[i]<e?n=i+1:r=i}return t.length===0?0:n/t.length}}function k(e){let t;for(let n of e)(!t||n.cognitiveComplexity>t.cognitiveComplexity||n.cognitiveComplexity===t.cognitiveComplexity&&n.ncss>t.ncss)&&(t=n);if(t)return{name:t.name??`<anonymous>`,startLine:t.startLine,endLine:t.endLine,cognitiveComplexity:t.cognitiveComplexity,ncss:t.ncss,nestingDepth:t.nestingDepth}}function A(e,t,n){let r=t.slice(0,n.top);h(JSON.stringify({summary:N(e.files),totalRankedFiles:t.length,truncated:r.length<t.length,files:r,errors:e.errors,warnings:e.warnings},void 0,2)+`
3
- `)}function j(e,t,n,r){if(t.fatalError){m(`Error: ${t.fatalError}\n`);return}let i=N(t.files);if(h(`Measured ${i.fileCount} files under ${e} (code LOC ${i.linesOfCode}, NCSS ${i.ncssCount}, functions ${i.functionCount})\n`),n.length===0)h(`No measurable files found.
4
- `);else{let e=n.slice(0,r.top),t=n.length>e.length?` of ${n.length}`:``;h(`\nRefactoring candidates (top ${e.length}${t}):\n`);for(let[t,n]of e.entries())h(`${t+1}. ${M(n)}\n`)}if(t.warnings.length>0){m(`\nDegraded ${t.warnings.length} files (measured, but excluded from cross-file matching):\n`);for(let e of t.warnings.slice(0,10))m(`- ${e}\n`);t.warnings.length>10&&m(`- ... ${t.warnings.length-10} more\n`)}if(t.errors.length>0){m(`\nSkipped ${t.errors.length} files or directories:\n`);for(let e of t.errors.slice(0,10))m(`- ${e}\n`);t.errors.length>10&&m(`- ... ${t.errors.length-10} more\n`)}}function M(e){let t=[];if(e.worstFunction){let n=e.worstFunction;t.push(`worst function ${n.name} (L${n.startLine}-${n.endLine}) cognitive ${n.cognitiveComplexity}, NCSS ${n.ncss}, nesting ${n.nestingDepth}`)}if(e.duplicatedLineCount>0){let n=e.crossFilePartners.length>0?`, shared with ${e.crossFilePartners.slice(0,3).join(`, `)}${e.crossFilePartners.length>3?`, ...`:``}`:``;t.push(`duplicated lines ${e.duplicatedLineCount} (${Math.round(e.duplicatedLineRatio*100)}%${n})`)}return t.push(`file NCSS ${e.ncss}`),`${e.file} (score ${e.score.toFixed(2)}): ${t.join(`; `)}`}function N(e){let t=0,n=0,r=0,i=0;for(let a of e)t+=a.metrics.functions.length,n+=a.metrics.lines.code,r=Math.max(r,a.metrics.maxCognitiveComplexity),i+=a.metrics.ncssCount;return{fileCount:e.length,functionCount:t,linesOfCode:n,maxCognitiveComplexity:r,ncssCount:i}}function P(e){if(e===`off`)return 1/0;let t=e.trim()===``?NaN:Number(e);if(!Number.isFinite(t)||t<0)throw new b(`Expected a non-negative number or "off".`);return t}function F(e){let t=L(e);if(t>100)throw new b(`Expected an integer between 1 and 100.`);return t}function I(e){if(!/^\d+$/u.test(e))throw new b(`Expected a non-negative integer.`);let t=Number(e);if(!Number.isSafeInteger(t)||t<0)throw new b(`Expected a non-negative integer.`);return t}function L(e){let t=v(e);if(t===void 0)throw new b(`Expected a positive integer.`);return t}
2
+ import{duplicationThreshold as e,fileThresholds as t,functionThresholds as n,levels as r,thresholds as i}from"./thresholds.js";import{configFileName as a,loadConfig as o,resolveOptions as s}from"./cliConfig.js";import{loadExclusion as c}from"./exclusion.js";import{addCrossFileDuplication as l,collectDuplicatedLineNumbers as u,configSearchDirectory as d,formatPath as f,resolveTarget as p,scanTarget as m,writeStderr as h,writeStdout as g}from"./scan.js";import{runCheckCommand as _}from"./checkCommand.js";import{getErrorMessage as v,parsePositiveInteger as y}from"@willbooster/shared-lib";import{Command as b,InvalidArgumentError as x}from"commander";S().catch(e=>{h(`Error: ${v(e)}\n`),process.exitCode=1});async function S(){let e=new b().name(`code-gauge`).description(`Measure code metrics: rank refactoring candidates (the default command) or check thresholds.`);C(e.command(`rank`,{isDefault:!0}).description(`Rank the files of a project by refactoring priority`).argument(`[target]`,`file or directory to measure`,`.`)).option(`--top <number>`,`number of top-ranked files to report (default: 10)`,R).option(`--fail-on-error`,`exit with code 1 when files or directories cannot be scanned`).action(E);let t=C(e.command(`check`).description(`Report every exceeded threshold as a warning or an error (exit 1 on errors, 2 when files cannot be measured); with --base, only in what the change touches`).argument(`[target]`,`file or directory to check`,`.`)).option(`--base <ref>`,`check only what the working tree changed since the merge-base of this git ref and HEAD`);for(let e of r)for(let{key:n,defaultLimits:r}of i){let i=r[e];t.option(`--${e}-${T(n)} <number>`,`${w(n,e)} (default ${Number.isFinite(i)?i:`off`}); "off" disables it`,F)}t.exitOverride(e=>process.exit(e.exitCode===0?0:2)),t.action(async(e,t)=>{let n=e=>Object.fromEntries(i.flatMap(({key:n})=>{let r=t[`${e}${n.charAt(0).toUpperCase()}${n.slice(1)}`];return r===void 0?[]:[[n,r]]}));await _(e,t,{warning:n(`warning`),error:n(`error`)})}),await e.parseAsync()}function C(e){return e.option(`--config <path>`,`config file to use instead of the auto-detected ${a}`).option(`--duplication-min-tokens <number>`,`minimum normalized token count for a duplicate region (default 40)`,R).option(`--duplication-max-gap-tokens <number>`,`maximum token gap merged into one gapped clone group; 0 disables merging (default 30)`,L).option(`--duplication-min-similarity-percent <number>`,`minimum similarity percent (1-100) for near-miss (Type-3) clone blocks; 100 reports exact matches only (default 70)`,I).option(`--include-tests`,`include test files and test directories`).option(`--json`,`print JSON output`)}function w(r,i){if(r===e.key)return`line count from which a duplicated block is ${i===`error`?`an error`:`a warning`}`;let a=t.find(e=>e.key===r);return`maximum ${a?a.label:`${n.find(e=>e.key===r)?.label} of a function`} without ${i===`error`?`an error`:`a warning`}`}function T(e){return e.replaceAll(/[A-Z]/gu,e=>`-${e.toLowerCase()}`)}async function E(e,t){let n=p(e),r=await d(n),i=await o(t.config,r),a=s(t,i),u=await m(n,{...a,loadExclusion:e=>c(r,a.exclude,e)});l(u,a);let f=D(u,a.top);a.json?j(u,f,a):M(n,u,f,a),(u.fatalError||a.failOnError&&u.errors.length>0)&&(process.exitCode=1)}function D(e,t){let n=e.files.map(({file:t,metrics:n})=>{let r=f(t,e.displayRoot),i=u(n,e.crossFileDuplication,r);return{file:r,worstFunction:A(n.functions),duplicatedLineCount:i.size,duplicatedLineRatio:n.lines.code===0?0:i.size/n.lines.code,crossFilePartners:[],ncss:n.ncssCount,codeLines:n.lines.code}}),r=k(n.map(e=>e.worstFunction?.cognitiveComplexity??0)),i=k(n.map(e=>e.duplicatedLineCount)),a=k(n.map(e=>e.ncss)),o=n.map(e=>({...e,score:r(e.worstFunction?.cognitiveComplexity??0)+i(e.duplicatedLineCount)+a(e.ncss)})).toSorted((e,t)=>t.score-e.score||t.ncss-e.ncss||e.file.localeCompare(t.file));return O(o.slice(0,t),e.crossFileDuplication),o}function O(e,t){if(!t)return;let n=new Map(e.map(e=>[e.file,/* @__PURE__ */ new Set]));for(let e of t.groups)for(let t of e.files){let r=n.get(t);if(r)for(let n of e.files)n!==t&&r.add(n)}for(let t of e)t.crossFilePartners=[...n.get(t.file)??[]].toSorted()}function k(e){let t=e.toSorted((e,t)=>e-t);return e=>{let n=0,r=t.length;for(;n<r;){let i=n+r>>1;t[i]<e?n=i+1:r=i}return t.length===0?0:n/t.length}}function A(e){let t;for(let n of e)(!t||n.cognitiveComplexity>t.cognitiveComplexity||n.cognitiveComplexity===t.cognitiveComplexity&&n.ncss>t.ncss)&&(t=n);if(t)return{name:t.name??`<anonymous>`,startLine:t.startLine,endLine:t.endLine,cognitiveComplexity:t.cognitiveComplexity,ncss:t.ncss,nestingDepth:t.nestingDepth}}function j(e,t,n){let r=t.slice(0,n.top);g(JSON.stringify({summary:P(e.files),totalRankedFiles:t.length,truncated:r.length<t.length,files:r,errors:e.errors,warnings:e.warnings},void 0,2)+`
3
+ `)}function M(e,t,n,r){if(t.fatalError){h(`Error: ${t.fatalError}\n`);return}let i=P(t.files);if(g(`Measured ${i.fileCount} files under ${e} (code LOC ${i.linesOfCode}, NCSS ${i.ncssCount}, functions ${i.functionCount})\n`),n.length===0)g(`No measurable files found.
4
+ `);else{let e=n.slice(0,r.top),t=n.length>e.length?` of ${n.length}`:``;g(`\nRefactoring candidates (top ${e.length}${t}):\n`);for(let[t,n]of e.entries())g(`${t+1}. ${N(n)}\n`)}if(t.warnings.length>0){h(`\nDegraded ${t.warnings.length} files (measured, but excluded from cross-file matching):\n`);for(let e of t.warnings.slice(0,10))h(`- ${e}\n`);t.warnings.length>10&&h(`- ... ${t.warnings.length-10} more\n`)}if(t.errors.length>0){h(`\nSkipped ${t.errors.length} files or directories:\n`);for(let e of t.errors.slice(0,10))h(`- ${e}\n`);t.errors.length>10&&h(`- ... ${t.errors.length-10} more\n`)}}function N(e){let t=[];if(e.worstFunction){let n=e.worstFunction;t.push(`worst function ${n.name} (L${n.startLine}-${n.endLine}) cognitive ${n.cognitiveComplexity}, NCSS ${n.ncss}, nesting ${n.nestingDepth}`)}if(e.duplicatedLineCount>0){let n=e.crossFilePartners.length>0?`, shared with ${e.crossFilePartners.slice(0,3).join(`, `)}${e.crossFilePartners.length>3?`, ...`:``}`:``;t.push(`duplicated lines ${e.duplicatedLineCount} (${Math.round(e.duplicatedLineRatio*100)}%${n})`)}return t.push(`file NCSS ${e.ncss}`),`${e.file} (score ${e.score.toFixed(2)}): ${t.join(`; `)}`}function P(e){let t=0,n=0,r=0,i=0;for(let a of e)t+=a.metrics.functions.length,n+=a.metrics.lines.code,r=Math.max(r,a.metrics.maxCognitiveComplexity),i+=a.metrics.ncssCount;return{fileCount:e.length,functionCount:t,linesOfCode:n,maxCognitiveComplexity:r,ncssCount:i}}function F(e){if(e===`off`)return 1/0;let t=e.trim()===``?NaN:Number(e);if(!Number.isFinite(t)||t<0)throw new x(`Expected a non-negative number or "off".`);return t}function I(e){let t=R(e);if(t>100)throw new x(`Expected an integer between 1 and 100.`);return t}function L(e){if(!/^\d+$/u.test(e))throw new x(`Expected a non-negative integer.`);let t=Number(e);if(!Number.isSafeInteger(t)||t<0)throw new x(`Expected a non-negative integer.`);return t}function R(e){let t=y(e);if(t===void 0)throw new x(`Expected a positive integer.`);return t}
5
5
  //# sourceMappingURL=cli.js.map
package/dist/cli.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"cli.js","names":[],"sources":["../src/cli.ts"],"sourcesContent":["#!/usr/bin/env node\n\nimport { Command, InvalidArgumentError } from 'commander';\nimport { getErrorMessage, parsePositiveInteger } from '@willbooster/shared-lib';\nimport { type CliOptions, configFileName, loadConfig, type ResolvedOptions, resolveOptions } from './cliConfig.js';\nimport type { CrossFileDuplicationMetrics } from './crossFileDuplication.js';\nimport { runCheckCommand, type CheckCliOptions } from './checkCommand.js';\nimport { loadExclusion } from './exclusion.js';\nimport {\n addCrossFileDuplication,\n collectDuplicatedLineNumbers,\n configSearchDirectory,\n formatPath,\n resolveTarget,\n scanTarget,\n writeStderr,\n writeStdout,\n type FileMetrics,\n type ScanResult,\n} from './scan.js';\nimport { duplicationThreshold, fileThresholds, functionThresholds, thresholds } from './thresholds.js';\nimport type { FunctionMetrics } from './types.js';\n\n/** The worst (highest-cognitive-complexity) function of a file, reported as the ranking evidence. */\ninterface WorstFunction {\n name: string;\n startLine: number;\n endLine: number;\n cognitiveComplexity: number;\n ncss: number;\n nestingDepth: number;\n}\n\n/**\n * One ranked refactoring candidate. The score is the sum of the file's repo-relative percentile\n * ranks (each in [0, 1)) over three dimensions: worst-function cognitive complexity, duplicated\n * lines (within-file and cross-file combined), and file NCSS. Ranking is relative to the scanned\n * project, so no absolute threshold is involved.\n */\ninterface RankedFile {\n file: string;\n score: number;\n worstFunction?: WorstFunction;\n /** Distinct lines covered by within-file duplicate blocks or cross-file duplicate occurrences. */\n duplicatedLineCount: number;\n /** duplicatedLineCount / code lines (0 when the file has no code). */\n duplicatedLineRatio: number;\n /** Other files sharing cross-file duplicate blocks; filled only for the reported top files. */\n crossFilePartners: string[];\n ncss: number;\n codeLines: number;\n}\n\n/** Caps how many cross-file partners a ranked file lists so the report stays scannable. */\nconst maxCrossFilePartners = 3;\n\n// oxlint-disable-next-line unicorn/prefer-top-level-await -- CommonJS build output cannot preserve top-level await.\nvoid main().catch((error: unknown) => {\n writeStderr(`Error: ${getErrorMessage(error)}\\n`);\n process.exitCode = 1;\n});\n\nasync function main(): Promise<void> {\n const program = new Command()\n .name('code-gauge')\n .description('Measure code metrics: rank refactoring candidates (the default command) or check thresholds.');\n\n addSharedOptions(\n program\n .command('rank', { isDefault: true })\n .description('Rank the files of a project by refactoring priority')\n .argument('[target]', 'file or directory to measure', '.')\n )\n .option('--top <number>', 'number of top-ranked files to report (default: 10)', parsePositiveIntegerOption)\n .option('--fail-on-error', 'exit with code 1 when files or directories cannot be scanned')\n .action(runRankCommand);\n\n const check = addSharedOptions(\n program\n .command('check')\n .description(\n 'Report every exceeded threshold (exit 1 on violations, 2 when files cannot be measured); with --base, only in what the change touches'\n )\n .argument('[target]', 'file or directory to check', '.')\n ).option('--base <ref>', 'check only what the working tree changed since the merge-base of this git ref and HEAD');\n for (const { key, defaultLimit } of thresholds) {\n check.option(\n `--${toKebabCase(key)} <number>`,\n `${describeLimit(key)} (default ${defaultLimit}); \"off\" disables it`,\n parseLimit\n );\n }\n // Exit code 1 means violations, so a rejected command line must not use it.\n check.exitOverride((error) => process.exit(error.exitCode === 0 ? 0 : 2));\n check.action(async (target: string, cliOptions: CheckCliOptions & Record<string, unknown>) => {\n const cliLimits = Object.fromEntries(\n thresholds.flatMap(({ key }) => (cliOptions[key] === undefined ? [] : [[key, cliOptions[key] as number]]))\n );\n await runCheckCommand(target, cliOptions, cliLimits);\n });\n\n await program.parseAsync();\n}\n\n/** Registers the options shared by the ranking and check commands. */\nfunction addSharedOptions(command: Command): Command {\n return command\n .option('--config <path>', `config file to use instead of the auto-detected ${configFileName}`)\n .option(\n '--duplication-min-tokens <number>',\n 'minimum normalized token count for a duplicate region (default 40)',\n parsePositiveIntegerOption\n )\n .option(\n '--duplication-max-gap-tokens <number>',\n 'maximum token gap merged into one gapped clone group; 0 disables merging (default 30)',\n parseNonNegativeInteger\n )\n .option(\n '--duplication-min-similarity-percent <number>',\n 'minimum similarity percent (1-100) for near-miss (Type-3) clone blocks; 100 reports exact matches only (default 70)',\n parsePercentInteger\n )\n .option('--include-tests', 'include test files and test directories')\n .option('--json', 'print JSON output');\n}\n\nfunction describeLimit(key: string): string {\n if (key === duplicationThreshold.key) {\n return 'line count from which a duplicated block is a violation';\n }\n const fileThreshold = fileThresholds.find((threshold) => threshold.key === key);\n return fileThreshold\n ? `maximum ${fileThreshold.label}`\n : `maximum ${functionThresholds.find((threshold) => threshold.key === key)?.label} of a function`;\n}\n\nfunction toKebabCase(key: string): string {\n return key.replaceAll(/[A-Z]/gu, (letter) => `-${letter.toLowerCase()}`);\n}\n\nasync function runRankCommand(target: string, cliOptions: CliOptions): Promise<void> {\n const resolvedTarget = resolveTarget(target);\n const searchDirectory = await configSearchDirectory(resolvedTarget);\n const config = await loadConfig(cliOptions.config, searchDirectory);\n const options = resolveOptions(cliOptions, config);\n const result = await scanTarget(resolvedTarget, {\n ...options,\n loadExclusion: (absolutePaths) => loadExclusion(searchDirectory, options.exclude, absolutePaths),\n });\n addCrossFileDuplication(result, options);\n const rankedFiles = rankFiles(result, options.top);\n\n if (options.json) {\n printJson(result, rankedFiles, options);\n } else {\n printTextReport(resolvedTarget, result, rankedFiles, options);\n }\n\n if (result.fatalError || (options.failOnError && result.errors.length > 0)) {\n process.exitCode = 1;\n }\n}\n\nfunction rankFiles(result: ScanResult, top: number): RankedFile[] {\n const candidates = result.files.map(({ file, metrics }) => {\n const formattedFile = formatPath(file, result.displayRoot);\n const duplicatedLines = collectDuplicatedLineNumbers(metrics, result.crossFileDuplication, formattedFile);\n return {\n file: formattedFile,\n worstFunction: findWorstFunction(metrics.functions),\n duplicatedLineCount: duplicatedLines.size,\n duplicatedLineRatio: metrics.lines.code === 0 ? 0 : duplicatedLines.size / metrics.lines.code,\n crossFilePartners: [] as string[],\n ncss: metrics.ncssCount,\n codeLines: metrics.lines.code,\n };\n });\n\n const cognitivePercentile = makePercentile(candidates.map((c) => c.worstFunction?.cognitiveComplexity ?? 0));\n const duplicationPercentile = makePercentile(candidates.map((c) => c.duplicatedLineCount));\n const ncssPercentile = makePercentile(candidates.map((c) => c.ncss));\n\n const ranked = candidates\n .map((candidate) => ({\n ...candidate,\n score:\n cognitivePercentile(candidate.worstFunction?.cognitiveComplexity ?? 0) +\n duplicationPercentile(candidate.duplicatedLineCount) +\n ncssPercentile(candidate.ncss),\n }))\n .toSorted(\n (left, right) => right.score - left.score || right.ncss - left.ncss || left.file.localeCompare(right.file)\n );\n // Partner evidence is attached only to the files that will be reported: expanding partners for\n // every scanned file first would retain TH(F^2) strings when one clone group spans F files, and\n // rescanning all groups per file would be O(files x groups) on the post-scan ranking step.\n attachCrossFilePartners(ranked.slice(0, top), result.crossFileDuplication);\n return ranked;\n}\n\n/** One pass over the groups fills the reported files' partner lists (other files sharing a group). */\nfunction attachCrossFilePartners(\n reportedFiles: RankedFile[],\n crossFileDuplication: CrossFileDuplicationMetrics | undefined\n): void {\n if (!crossFileDuplication) {\n return;\n }\n const partnersByFile = new Map(reportedFiles.map((ranked) => [ranked.file, new Set<string>()]));\n for (const group of crossFileDuplication.groups) {\n for (const file of group.files) {\n const partners = partnersByFile.get(file);\n if (!partners) {\n continue;\n }\n for (const partner of group.files) {\n if (partner !== file) {\n partners.add(partner);\n }\n }\n }\n }\n for (const ranked of reportedFiles) {\n ranked.crossFilePartners = [...(partnersByFile.get(ranked.file) ?? [])].toSorted();\n }\n}\n\n/**\n * Percentile rank within the scanned project: the fraction of files with a strictly smaller\n * value, in [0, 1). Relative ranking needs no absolute threshold, which sidesteps the metric\n * calibration problem entirely — the top of the list is worth refactoring first regardless of\n * where any cutoff would sit.\n */\nfunction makePercentile(values: number[]): (value: number) => number {\n const sorted = values.toSorted((left, right) => left - right);\n return (value: number) => {\n let low = 0;\n let high = sorted.length;\n while (low < high) {\n const middle = (low + high) >> 1;\n if ((sorted[middle] as number) < value) {\n low = middle + 1;\n } else {\n high = middle;\n }\n }\n return sorted.length === 0 ? 0 : low / sorted.length;\n };\n}\n\n/** The highest-cognitive-complexity function; NCSS breaks ties so the larger body is reported. */\nfunction findWorstFunction(functions: FunctionMetrics[]): WorstFunction | undefined {\n let worst: FunctionMetrics | undefined;\n for (const fn of functions) {\n if (\n !worst ||\n fn.cognitiveComplexity > worst.cognitiveComplexity ||\n (fn.cognitiveComplexity === worst.cognitiveComplexity && fn.ncss > worst.ncss)\n ) {\n worst = fn;\n }\n }\n if (!worst) {\n return undefined;\n }\n return {\n name: worst.name ?? '<anonymous>',\n startLine: worst.startLine,\n endLine: worst.endLine,\n cognitiveComplexity: worst.cognitiveComplexity,\n ncss: worst.ncss,\n nestingDepth: worst.nestingDepth,\n };\n}\n\nfunction printJson(result: ScanResult, rankedFiles: RankedFile[], options: ResolvedOptions): void {\n const reportedFiles = rankedFiles.slice(0, options.top);\n writeStdout(\n JSON.stringify(\n {\n summary: summarize(result.files),\n totalRankedFiles: rankedFiles.length,\n truncated: reportedFiles.length < rankedFiles.length,\n files: reportedFiles,\n errors: result.errors,\n warnings: result.warnings,\n },\n undefined,\n 2\n ) + '\\n'\n );\n}\n\nfunction printTextReport(\n target: string,\n result: ScanResult,\n rankedFiles: RankedFile[],\n options: ResolvedOptions\n): void {\n if (result.fatalError) {\n writeStderr(`Error: ${result.fatalError}\\n`);\n return;\n }\n\n const summary = summarize(result.files);\n writeStdout(\n `Measured ${summary.fileCount} files under ${target} (code LOC ${summary.linesOfCode}, NCSS ${summary.ncssCount}, functions ${summary.functionCount})\\n`\n );\n\n if (rankedFiles.length === 0) {\n writeStdout('No measurable files found.\\n');\n } else {\n const reportedFiles = rankedFiles.slice(0, options.top);\n const totalSuffix = rankedFiles.length > reportedFiles.length ? ` of ${rankedFiles.length}` : '';\n writeStdout(`\\nRefactoring candidates (top ${reportedFiles.length}${totalSuffix}):\\n`);\n for (const [index, ranked] of reportedFiles.entries()) {\n writeStdout(`${index + 1}. ${formatRankedFile(ranked)}\\n`);\n }\n }\n\n if (result.warnings.length > 0) {\n writeStderr(`\\nDegraded ${result.warnings.length} files (measured, but excluded from cross-file matching):\\n`);\n for (const warning of result.warnings.slice(0, 10)) {\n writeStderr(`- ${warning}\\n`);\n }\n if (result.warnings.length > 10) {\n writeStderr(`- ... ${result.warnings.length - 10} more\\n`);\n }\n }\n\n if (result.errors.length > 0) {\n writeStderr(`\\nSkipped ${result.errors.length} files or directories:\\n`);\n for (const error of result.errors.slice(0, 10)) {\n writeStderr(`- ${error}\\n`);\n }\n if (result.errors.length > 10) {\n writeStderr(`- ... ${result.errors.length - 10} more\\n`);\n }\n }\n}\n\n/** One ranked file as a single line: the location, the evidence, and where the duplication points. */\nfunction formatRankedFile(ranked: RankedFile): string {\n const reasons: string[] = [];\n if (ranked.worstFunction) {\n const fn = ranked.worstFunction;\n reasons.push(\n `worst function ${fn.name} (L${fn.startLine}-${fn.endLine}) cognitive ${fn.cognitiveComplexity}, NCSS ${fn.ncss}, nesting ${fn.nestingDepth}`\n );\n }\n if (ranked.duplicatedLineCount > 0) {\n const partnersSuffix =\n ranked.crossFilePartners.length > 0\n ? `, shared with ${ranked.crossFilePartners.slice(0, maxCrossFilePartners).join(', ')}${ranked.crossFilePartners.length > maxCrossFilePartners ? ', ...' : ''}`\n : '';\n reasons.push(\n `duplicated lines ${ranked.duplicatedLineCount} (${Math.round(ranked.duplicatedLineRatio * 100)}%${partnersSuffix})`\n );\n }\n reasons.push(`file NCSS ${ranked.ncss}`);\n return `${ranked.file} (score ${ranked.score.toFixed(2)}): ${reasons.join('; ')}`;\n}\n\nfunction summarize(files: FileMetrics[]): {\n fileCount: number;\n functionCount: number;\n linesOfCode: number;\n maxCognitiveComplexity: number;\n ncssCount: number;\n} {\n let functionCount = 0;\n let linesOfCode = 0;\n let maxCognitiveComplexity = 0;\n let ncssCount = 0;\n\n for (const file of files) {\n functionCount += file.metrics.functions.length;\n linesOfCode += file.metrics.lines.code;\n maxCognitiveComplexity = Math.max(maxCognitiveComplexity, file.metrics.maxCognitiveComplexity);\n ncssCount += file.metrics.ncssCount;\n }\n\n return { fileCount: files.length, functionCount, linesOfCode, maxCognitiveComplexity, ncssCount };\n}\n\nfunction parseLimit(value: string): number {\n if (value === 'off') {\n return Infinity;\n }\n const parsed = value.trim() === '' ? Number.NaN : Number(value);\n if (!Number.isFinite(parsed) || parsed < 0) {\n throw new InvalidArgumentError('Expected a non-negative number or \"off\".');\n }\n return parsed;\n}\n\nfunction parsePercentInteger(value: string): number {\n const parsed = parsePositiveIntegerOption(value);\n if (parsed > 100) {\n throw new InvalidArgumentError('Expected an integer between 1 and 100.');\n }\n return parsed;\n}\n\nfunction parseNonNegativeInteger(value: string): number {\n if (!/^\\d+$/u.test(value)) {\n throw new InvalidArgumentError('Expected a non-negative integer.');\n }\n\n const parsed = Number(value);\n if (!Number.isSafeInteger(parsed) || parsed < 0) {\n throw new InvalidArgumentError('Expected a non-negative integer.');\n }\n return parsed;\n}\n\nfunction parsePositiveIntegerOption(value: string): number {\n const parsed = parsePositiveInteger(value);\n if (parsed === undefined) {\n throw new InvalidArgumentError('Expected a positive integer.');\n }\n return parsed;\n}\n"],"mappings":";koBAyDK,EAAK,CAAC,CAAC,MAAO,GAAmB,CACpC,EAAY,UAAU,EAAgB,CAAK,EAAE,GAAG,EAChD,QAAQ,SAAW,CACrB,CAAC,EAED,eAAe,GAAsB,CACnC,IAAM,EAAU,IAAI,EAAQ,CAAC,CAC1B,KAAK,YAAY,CAAC,CAClB,YAAY,8FAA8F,EAE7G,EACE,EACG,QAAQ,OAAQ,CAAE,UAAW,EAAK,CAAC,CAAC,CACpC,YAAY,qDAAqD,CAAC,CAClE,SAAS,WAAY,+BAAgC,GAAG,CAC7D,CAAC,CACE,OAAO,iBAAkB,qDAAsD,CAA0B,CAAC,CAC1G,OAAO,kBAAmB,8DAA8D,CAAC,CACzF,OAAO,CAAc,EAExB,IAAM,EAAQ,EACZ,EACG,QAAQ,OAAO,CAAC,CAChB,YACC,uIACF,CAAC,CACA,SAAS,WAAY,6BAA8B,GAAG,CAC3D,CAAC,CAAC,OAAO,eAAgB,wFAAwF,EACjH,IAAK,GAAM,CAAE,MAAK,kBAAkB,EAClC,EAAM,OACJ,KAAK,EAAY,CAAG,EAAE,WACtB,GAAG,EAAc,CAAG,EAAE,YAAY,EAAa,sBAC/C,CACF,EAGF,EAAM,aAAc,GAAU,QAAQ,KAAK,EAAM,WAAa,EAAI,EAAI,CAAC,CAAC,EACxE,EAAM,OAAO,MAAO,EAAgB,IAA0D,CAC5F,IAAM,EAAY,OAAO,YACvB,EAAW,SAAS,CAAE,SAAW,EAAW,KAAS,IAAA,GAAY,CAAC,EAAI,CAAC,CAAC,EAAK,EAAW,E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AAK,EACzC,GAAI,IAAW,IAAA,GACb,MAAM,IAAI,EAAqB,8BAA8B,EAE/D,OAAO,CACT"}
1
+ {"version":3,"file":"cli.js","names":[],"sources":["../src/cli.ts"],"sourcesContent":["#!/usr/bin/env node\n\nimport { Command, InvalidArgumentError } from 'commander';\nimport { getErrorMessage, parsePositiveInteger } from '@willbooster/shared-lib';\nimport { type CliOptions, configFileName, loadConfig, type ResolvedOptions, resolveOptions } from './cliConfig.js';\nimport type { CrossFileDuplicationMetrics } from './crossFileDuplication.js';\nimport { runCheckCommand, type CheckCliOptions } from './checkCommand.js';\nimport { loadExclusion } from './exclusion.js';\nimport {\n addCrossFileDuplication,\n collectDuplicatedLineNumbers,\n configSearchDirectory,\n formatPath,\n resolveTarget,\n scanTarget,\n writeStderr,\n writeStdout,\n type FileMetrics,\n type ScanResult,\n} from './scan.js';\nimport {\n duplicationThreshold,\n fileThresholds,\n functionThresholds,\n levels,\n thresholds,\n type Level,\n type Limits,\n} from './thresholds.js';\nimport type { FunctionMetrics } from './types.js';\n\n/** The worst (highest-cognitive-complexity) function of a file, reported as the ranking evidence. */\ninterface WorstFunction {\n name: string;\n startLine: number;\n endLine: number;\n cognitiveComplexity: number;\n ncss: number;\n nestingDepth: number;\n}\n\n/**\n * One ranked refactoring candidate. The score is the sum of the file's repo-relative percentile\n * ranks (each in [0, 1)) over three dimensions: worst-function cognitive complexity, duplicated\n * lines (within-file and cross-file combined), and file NCSS. Ranking is relative to the scanned\n * project, so no absolute threshold is involved.\n */\ninterface RankedFile {\n file: string;\n score: number;\n worstFunction?: WorstFunction;\n /** Distinct lines covered by within-file duplicate blocks or cross-file duplicate occurrences. */\n duplicatedLineCount: number;\n /** duplicatedLineCount / code lines (0 when the file has no code). */\n duplicatedLineRatio: number;\n /** Other files sharing cross-file duplicate blocks; filled only for the reported top files. */\n crossFilePartners: string[];\n ncss: number;\n codeLines: number;\n}\n\n/** Caps how many cross-file partners a ranked file lists so the report stays scannable. */\nconst maxCrossFilePartners = 3;\n\n// oxlint-disable-next-line unicorn/prefer-top-level-await -- CommonJS build output cannot preserve top-level await.\nvoid main().catch((error: unknown) => {\n writeStderr(`Error: ${getErrorMessage(error)}\\n`);\n process.exitCode = 1;\n});\n\nasync function main(): Promise<void> {\n const program = new Command()\n .name('code-gauge')\n .description('Measure code metrics: rank refactoring candidates (the default command) or check thresholds.');\n\n addSharedOptions(\n program\n .command('rank', { isDefault: true })\n .description('Rank the files of a project by refactoring priority')\n .argument('[target]', 'file or directory to measure', '.')\n )\n .option('--top <number>', 'number of top-ranked files to report (default: 10)', parsePositiveIntegerOption)\n .option('--fail-on-error', 'exit with code 1 when files or directories cannot be scanned')\n .action(runRankCommand);\n\n const check = addSharedOptions(\n program\n .command('check')\n .description(\n 'Report every exceeded threshold as a warning or an error (exit 1 on errors, 2 when files cannot be measured); with --base, only in what the change touches'\n )\n .argument('[target]', 'file or directory to check', '.')\n ).option('--base <ref>', 'check only what the working tree changed since the merge-base of this git ref and HEAD');\n for (const level of levels) {\n for (const { key, defaultLimits } of thresholds) {\n const defaultLimit = defaultLimits[level];\n check.option(\n `--${level}-${toKebabCase(key)} <number>`,\n `${describeLimit(key, level)} (default ${Number.isFinite(defaultLimit) ? defaultLimit : 'off'}); \"off\" disables it`,\n parseLimit\n );\n }\n }\n // Exit code 1 means error-level violations, so a rejected command line must not use it.\n check.exitOverride((error) => process.exit(error.exitCode === 0 ? 0 : 2));\n check.action(async (target: string, cliOptions: CheckCliOptions & Record<string, unknown>) => {\n const readLimits = (level: Level): Limits =>\n Object.fromEntries(\n thresholds.flatMap(({ key }) => {\n const limit = cliOptions[`${level}${key.charAt(0).toUpperCase()}${key.slice(1)}`];\n return limit === undefined ? [] : [[key, limit as number]];\n })\n );\n await runCheckCommand(target, cliOptions, { warning: readLimits('warning'), error: readLimits('error') });\n });\n\n await program.parseAsync();\n}\n\n/** Registers the options shared by the ranking and check commands. */\nfunction addSharedOptions(command: Command): Command {\n return command\n .option('--config <path>', `config file to use instead of the auto-detected ${configFileName}`)\n .option(\n '--duplication-min-tokens <number>',\n 'minimum normalized token count for a duplicate region (default 40)',\n parsePositiveIntegerOption\n )\n .option(\n '--duplication-max-gap-tokens <number>',\n 'maximum token gap merged into one gapped clone group; 0 disables merging (default 30)',\n parseNonNegativeInteger\n )\n .option(\n '--duplication-min-similarity-percent <number>',\n 'minimum similarity percent (1-100) for near-miss (Type-3) clone blocks; 100 reports exact matches only (default 70)',\n parsePercentInteger\n )\n .option('--include-tests', 'include test files and test directories')\n .option('--json', 'print JSON output');\n}\n\nfunction describeLimit(key: string, level: Level): string {\n if (key === duplicationThreshold.key) {\n return `line count from which a duplicated block is ${level === 'error' ? 'an error' : 'a warning'}`;\n }\n const fileThreshold = fileThresholds.find((threshold) => threshold.key === key);\n const subject = fileThreshold\n ? fileThreshold.label\n : `${functionThresholds.find((threshold) => threshold.key === key)?.label} of a function`;\n return `maximum ${subject} without ${level === 'error' ? 'an error' : 'a warning'}`;\n}\n\nfunction toKebabCase(key: string): string {\n return key.replaceAll(/[A-Z]/gu, (letter) => `-${letter.toLowerCase()}`);\n}\n\nasync function runRankCommand(target: string, cliOptions: CliOptions): Promise<void> {\n const resolvedTarget = resolveTarget(target);\n const searchDirectory = await configSearchDirectory(resolvedTarget);\n const config = await loadConfig(cliOptions.config, searchDirectory);\n const options = resolveOptions(cliOptions, config);\n const result = await scanTarget(resolvedTarget, {\n ...options,\n loadExclusion: (absolutePaths) => loadExclusion(searchDirectory, options.exclude, absolutePaths),\n });\n addCrossFileDuplication(result, options);\n const rankedFiles = rankFiles(result, options.top);\n\n if (options.json) {\n printJson(result, rankedFiles, options);\n } else {\n printTextReport(resolvedTarget, result, rankedFiles, options);\n }\n\n if (result.fatalError || (options.failOnError && result.errors.length > 0)) {\n process.exitCode = 1;\n }\n}\n\nfunction rankFiles(result: ScanResult, top: number): RankedFile[] {\n const candidates = result.files.map(({ file, metrics }) => {\n const formattedFile = formatPath(file, result.displayRoot);\n const duplicatedLines = collectDuplicatedLineNumbers(metrics, result.crossFileDuplication, formattedFile);\n return {\n file: formattedFile,\n worstFunction: findWorstFunction(metrics.functions),\n duplicatedLineCount: duplicatedLines.size,\n duplicatedLineRatio: metrics.lines.code === 0 ? 0 : duplicatedLines.size / metrics.lines.code,\n crossFilePartners: [] as string[],\n ncss: metrics.ncssCount,\n codeLines: metrics.lines.code,\n };\n });\n\n const cognitivePercentile = makePercentile(candidates.map((c) => c.worstFunction?.cognitiveComplexity ?? 0));\n const duplicationPercentile = makePercentile(candidates.map((c) => c.duplicatedLineCount));\n const ncssPercentile = makePercentile(candidates.map((c) => c.ncss));\n\n const ranked = candidates\n .map((candidate) => ({\n ...candidate,\n score:\n cognitivePercentile(candidate.worstFunction?.cognitiveComplexity ?? 0) +\n duplicationPercentile(candidate.duplicatedLineCount) +\n ncssPercentile(candidate.ncss),\n }))\n .toSorted(\n (left, right) => right.score - left.score || right.ncss - left.ncss || left.file.localeCompare(right.file)\n );\n // Partner evidence is attached only to the files that will be reported: expanding partners for\n // every scanned file first would retain TH(F^2) strings when one clone group spans F files, and\n // rescanning all groups per file would be O(files x groups) on the post-scan ranking step.\n attachCrossFilePartners(ranked.slice(0, top), result.crossFileDuplication);\n return ranked;\n}\n\n/** One pass over the groups fills the reported files' partner lists (other files sharing a group). */\nfunction attachCrossFilePartners(\n reportedFiles: RankedFile[],\n crossFileDuplication: CrossFileDuplicationMetrics | undefined\n): void {\n if (!crossFileDuplication) {\n return;\n }\n const partnersByFile = new Map(reportedFiles.map((ranked) => [ranked.file, new Set<string>()]));\n for (const group of crossFileDuplication.groups) {\n for (const file of group.files) {\n const partners = partnersByFile.get(file);\n if (!partners) {\n continue;\n }\n for (const partner of group.files) {\n if (partner !== file) {\n partners.add(partner);\n }\n }\n }\n }\n for (const ranked of reportedFiles) {\n ranked.crossFilePartners = [...(partnersByFile.get(ranked.file) ?? [])].toSorted();\n }\n}\n\n/**\n * Percentile rank within the scanned project: the fraction of files with a strictly smaller\n * value, in [0, 1). Relative ranking needs no absolute threshold, which sidesteps the metric\n * calibration problem entirely — the top of the list is worth refactoring first regardless of\n * where any cutoff would sit.\n */\nfunction makePercentile(values: number[]): (value: number) => number {\n const sorted = values.toSorted((left, right) => left - right);\n return (value: number) => {\n let low = 0;\n let high = sorted.length;\n while (low < high) {\n const middle = (low + high) >> 1;\n if ((sorted[middle] as number) < value) {\n low = middle + 1;\n } else {\n high = middle;\n }\n }\n return sorted.length === 0 ? 0 : low / sorted.length;\n };\n}\n\n/** The highest-cognitive-complexity function; NCSS breaks ties so the larger body is reported. */\nfunction findWorstFunction(functions: FunctionMetrics[]): WorstFunction | undefined {\n let worst: FunctionMetrics | undefined;\n for (const fn of functions) {\n if (\n !worst ||\n fn.cognitiveComplexity > worst.cognitiveComplexity ||\n (fn.cognitiveComplexity === worst.cognitiveComplexity && fn.ncss > worst.ncss)\n ) {\n worst = fn;\n }\n }\n if (!worst) {\n return undefined;\n }\n return {\n name: worst.name ?? '<anonymous>',\n startLine: worst.startLine,\n endLine: worst.endLine,\n cognitiveComplexity: worst.cognitiveComplexity,\n ncss: worst.ncss,\n nestingDepth: worst.nestingDepth,\n };\n}\n\nfunction printJson(result: ScanResult, rankedFiles: RankedFile[], options: ResolvedOptions): void {\n const reportedFiles = rankedFiles.slice(0, options.top);\n writeStdout(\n JSON.stringify(\n {\n summary: summarize(result.files),\n totalRankedFiles: rankedFiles.length,\n truncated: reportedFiles.length < rankedFiles.length,\n files: reportedFiles,\n errors: result.errors,\n warnings: result.warnings,\n },\n undefined,\n 2\n ) + '\\n'\n );\n}\n\nfunction printTextReport(\n target: string,\n result: ScanResult,\n rankedFiles: RankedFile[],\n options: ResolvedOptions\n): void {\n if (result.fatalError) {\n writeStderr(`Error: ${result.fatalError}\\n`);\n return;\n }\n\n const summary = summarize(result.files);\n writeStdout(\n `Measured ${summary.fileCount} files under ${target} (code LOC ${summary.linesOfCode}, NCSS ${summary.ncssCount}, functions ${summary.functionCount})\\n`\n );\n\n if (rankedFiles.length === 0) {\n writeStdout('No measurable files found.\\n');\n } else {\n const reportedFiles = rankedFiles.slice(0, options.top);\n const totalSuffix = rankedFiles.length > reportedFiles.length ? ` of ${rankedFiles.length}` : '';\n writeStdout(`\\nRefactoring candidates (top ${reportedFiles.length}${totalSuffix}):\\n`);\n for (const [index, ranked] of reportedFiles.entries()) {\n writeStdout(`${index + 1}. ${formatRankedFile(ranked)}\\n`);\n }\n }\n\n if (result.warnings.length > 0) {\n writeStderr(`\\nDegraded ${result.warnings.length} files (measured, but excluded from cross-file matching):\\n`);\n for (const warning of result.warnings.slice(0, 10)) {\n writeStderr(`- ${warning}\\n`);\n }\n if (result.warnings.length > 10) {\n writeStderr(`- ... ${result.warnings.length - 10} more\\n`);\n }\n }\n\n if (result.errors.length > 0) {\n writeStderr(`\\nSkipped ${result.errors.length} files or directories:\\n`);\n for (const error of result.errors.slice(0, 10)) {\n writeStderr(`- ${error}\\n`);\n }\n if (result.errors.length > 10) {\n writeStderr(`- ... ${result.errors.length - 10} more\\n`);\n }\n }\n}\n\n/** One ranked file as a single line: the location, the evidence, and where the duplication points. */\nfunction formatRankedFile(ranked: RankedFile): string {\n const reasons: string[] = [];\n if (ranked.worstFunction) {\n const fn = ranked.worstFunction;\n reasons.push(\n `worst function ${fn.name} (L${fn.startLine}-${fn.endLine}) cognitive ${fn.cognitiveComplexity}, NCSS ${fn.ncss}, nesting ${fn.nestingDepth}`\n );\n }\n if (ranked.duplicatedLineCount > 0) {\n const partnersSuffix =\n ranked.crossFilePartners.length > 0\n ? `, shared with ${ranked.crossFilePartners.slice(0, maxCrossFilePartners).join(', ')}${ranked.crossFilePartners.length > maxCrossFilePartners ? ', ...' : ''}`\n : '';\n reasons.push(\n `duplicated lines ${ranked.duplicatedLineCount} (${Math.round(ranked.duplicatedLineRatio * 100)}%${partnersSuffix})`\n );\n }\n reasons.push(`file NCSS ${ranked.ncss}`);\n return `${ranked.file} (score ${ranked.score.toFixed(2)}): ${reasons.join('; ')}`;\n}\n\nfunction summarize(files: FileMetrics[]): {\n fileCount: number;\n functionCount: number;\n linesOfCode: number;\n maxCognitiveComplexity: number;\n ncssCount: number;\n} {\n let functionCount = 0;\n let linesOfCode = 0;\n let maxCognitiveComplexity = 0;\n let ncssCount = 0;\n\n for (const file of files) {\n functionCount += file.metrics.functions.length;\n linesOfCode += file.metrics.lines.code;\n maxCognitiveComplexity = Math.max(maxCognitiveComplexity, file.metrics.maxCognitiveComplexity);\n ncssCount += file.metrics.ncssCount;\n }\n\n return { fileCount: files.length, functionCount, linesOfCode, maxCognitiveComplexity, ncssCount };\n}\n\nfunction parseLimit(value: string): number {\n if (value === 'off') {\n return Infinity;\n }\n const parsed = value.trim() === '' ? Number.NaN : Number(value);\n if (!Number.isFinite(parsed) || parsed < 0) {\n throw new InvalidArgumentError('Expected a non-negative number or \"off\".');\n }\n return parsed;\n}\n\nfunction parsePercentInteger(value: string): number {\n const parsed = parsePositiveIntegerOption(value);\n if (parsed > 100) {\n throw new InvalidArgumentError('Expected an integer between 1 and 100.');\n }\n return parsed;\n}\n\nfunction parseNonNegativeInteger(value: string): number {\n if (!/^\\d+$/u.test(value)) {\n throw new InvalidArgumentError('Expected a non-negative integer.');\n }\n\n const parsed = Number(value);\n if (!Number.isSafeInteger(parsed) || parsed < 0) {\n throw new InvalidArgumentError('Expected a non-negative integer.');\n }\n return parsed;\n}\n\nfunction parsePositiveIntegerOption(value: string): number {\n const parsed = parsePositiveInteger(value);\n if (parsed === undefined) {\n throw new InvalidArgumentError('Expected a positive integer.');\n }\n return parsed;\n}\n"],"mappings":";8oBAiEK,EAAK,CAAC,CAAC,MAAO,GAAmB,CACpC,EAAY,UAAU,EAAgB,CAAK,EAAE,GAAG,EAChD,QAAQ,SAAW,CACrB,CAAC,EAED,eAAe,GAAsB,CACnC,IAAM,EAAU,IAAI,EAAQ,CAAC,CAC1B,KAAK,YAAY,CAAC,CAClB,YAAY,8FAA8F,EAE7G,EACE,EACG,QAAQ,OAAQ,CAAE,UAAW,EAAK,CAA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,KAAK,UAAU,EAAO,MAAM,QAAQ,CAAC,EAAE,KAAK,EAAQ,KAAK,IAAI,GAChF,CAEA,SAAS,EAAU,EAMjB,CACA,IAAI,EAAgB,EAChB,EAAc,EACd,EAAyB,EACzB,EAAY,EAEhB,IAAK,IAAM,KAAQ,EACjB,GAAiB,EAAK,QAAQ,UAAU,OACxC,GAAe,EAAK,QAAQ,MAAM,KAClC,EAAyB,KAAK,IAAI,EAAwB,EAAK,QAAQ,sBAAsB,EAC7F,GAAa,EAAK,QAAQ,UAG5B,MAAO,CAAE,UAAW,EAAM,OAAQ,gBAAe,cAAa,yBAAwB,WAAU,CAClG,CAEA,SAAS,EAAW,EAAuB,CACzC,GAAI,IAAU,MACZ,MAAO,KAET,IAAM,EAAS,EAAM,KAAK,IAAM,GAAK,IAAa,OAAO,CAAK,EAC9D,GAAI,CAAC,OAAO,SAAS,CAAM,GAAK,EAAS,EACvC,MAAM,IAAI,EAAqB,0CAA0C,EAE3E,OAAO,CACT,CAEA,SAAS,EAAoB,EAAuB,CAClD,IAAM,EAAS,EAA2B,CAAK,EAC/C,GAAI,EAAS,IACX,MAAM,IAAI,EAAqB,wCAAwC,EAEzE,OAAO,CACT,CAEA,SAAS,EAAwB,EAAuB,CACtD,GAAI,CAAC,SAAS,KAAK,CAAK,EACtB,MAAM,IAAI,EAAqB,kCAAkC,EAGnE,IAAM,EAAS,OAAO,CAAK,EAC3B,GAAI,CAAC,OAAO,cAAc,CAAM,GAAK,EAAS,EAC5C,MAAM,IAAI,EAAqB,kCAAkC,EAEnE,OAAO,CACT,CAEA,SAAS,EAA2B,EAAuB,CACzD,IAAM,EAAS,EAAqB,CAAK,EACzC,GAAI,IAAW,IAAA,GACb,MAAM,IAAI,EAAqB,8BAA8B,EAE/D,OAAO,CACT"}
@@ -1,2 +1,2 @@
1
- "use strict";const e=require("./_virtual/_rolldown/runtime.cjs"),t=require("./duplication.cjs"),n=require("./languages.cjs"),r=require("./thresholds.cjs");let i=require("@willbooster/shared-lib"),a=require("node:fs/promises"),o=require("node:path");o=e.__toESM(o,1);const s=`code-gauge.config.json`;function c(e,{config:n,directory:r}){return{duplication:{minTokens:e.duplicationMinTokens??n.duplication?.minTokens??t.defaultDuplicationOptions.minTokens,maxGapTokens:e.duplicationMaxGapTokens??n.duplication?.maxGapTokens??t.defaultDuplicationOptions.maxGapTokens,minSimilarityPercent:e.duplicationMinSimilarityPercent??n.duplication?.minSimilarityPercent??t.defaultDuplicationOptions.minSimilarityPercent},exclude:{patterns:n.exclude??[],root:r},top:e.top??n.rank?.top??10,includeTests:e.includeTests??n.includeTests??!1,failOnError:e.failOnError??n.failOnError??!1,json:e.json??!1}}async function l(e,t){let n=e??await u(t);if(!n)return{config:{},directory:t};let r;try{r=await(0,a.readFile)(n,`utf8`)}catch(r){if(e)throw Error(`Cannot read config file "${n}": ${(0,i.getErrorMessage)(r)}`);return{config:{},directory:t}}let s;try{s=JSON.parse(r)}catch(e){throw Error(`Invalid JSON in config file "${n}": ${(0,i.getErrorMessage)(e)}`)}return{config:f(s,n),directory:o.default.dirname(o.default.resolve(n))}}async function u(e){let t=e;for(;;){let e=o.default.join(t,s);if(await d(e))return e;let n=o.default.dirname(t);if(n===t)return;t=n}}async function d(e){try{return(await(0,a.stat)(e)).isFile()}catch{return!1}}function f(e,t){if(!(0,i.isRecord)(e))throw Error(`Config file "${t}" must contain a JSON object.`);let n=/* @__PURE__ */ new Set([`duplication`,`rank`,`thresholds`,`exclude`,`includeTests`,`failOnError`]);for(let r of Object.keys(e))if(!n.has(r))throw Error(`Config file "${t}": unknown setting "${r}" (expected ${[...n].join(`, `)}).`);let r={};e.duplication!==void 0&&(r.duplication=v(e.duplication,t)),e.rank!==void 0&&(r.rank=m(e.rank,t)),e.thresholds!==void 0&&(r.thresholds=h(e.thresholds,t)),e.exclude!==void 0&&(r.exclude=p(e.exclude,t));for(let n of[`includeTests`,`failOnError`])e[n]!==void 0&&(r[n]=S(e[n],n,t));return r}function p(e,t){if(!Array.isArray(e)||!e.every(e=>typeof e==`string`&&e!==``))throw TypeError(`Config file "${t}": "exclude" must be an array of non-empty glob patterns.`);return e}function m(e,t){if(!(0,i.isRecord)(e))throw Error(`Config file "${t}": "rank" must be an object.`);let n={};for(let[r,i]of Object.entries(e)){if(r!==`top`)throw Error(`Config file "${t}": unknown setting "${r}" in "rank" (expected top).`);n.top=b(i,`rank.top`,t)}return n}function h(e,t){let{languages:r,...i}=_(e,`thresholds`,t);return{limits:g(i,`thresholds`,[`languages`],t),languages:Object.fromEntries(Object.entries(r===void 0?{}:_(r,`thresholds.languages`,t)).map(([e,r])=>{if(!n.supportedLanguages.includes(e))throw Error(`Config file "${t}": unknown language "${e}" in "thresholds.languages" (expected ${n.supportedLanguages.join(`, `)}).`);let i=`thresholds.languages.${e}`;return[e,g(_(r,i,t),i,[],t)]}))}}function g(e,t,n,i){let a=r.thresholds.map(({key:e})=>e);return Object.fromEntries(Object.entries(e).map(([e,r])=>{if(!a.includes(e))throw Error(`Config file "${i}": unknown setting "${e}" in "${t}" (expected ${[...a,...n].join(`, `)}).`);if(r!==null&&(typeof r!=`number`||!Number.isFinite(r)||r<0))throw Error(`Config file "${i}": "${t}.${e}" must be a non-negative number or null.`);return[e,r??1/0]}))}function _(e,t,n){if(!(0,i.isRecord)(e))throw Error(`Config file "${n}": "${t}" must be an object.`);return e}function v(e,t){if(!(0,i.isRecord)(e))throw Error(`Config file "${t}": "duplication" must be an object.`);let n={};for(let[r,i]of Object.entries(e))if(r===`minTokens`)n.minTokens=b(i,`duplication.minTokens`,t);else if(r===`maxGapTokens`)n.maxGapTokens=y(i,`duplication.maxGapTokens`,t);else if(r===`minSimilarityPercent`){let e=b(i,`duplication.minSimilarityPercent`,t);if(e>100)throw Error(`Config file "${t}": "duplication.minSimilarityPercent" must be between 1 and 100.`);n.minSimilarityPercent=e}else throw Error(`Config file "${t}": unknown setting "${r}" in "duplication" (expected minTokens, maxGapTokens, or minSimilarityPercent).`);return n}function y(e,t,n){return x(e,t,n,Number.isSafeInteger,`a non-negative integer`)}function b(e,t,n){let r=x(e,t,n,Number.isSafeInteger,`a positive integer`);if(r<1)throw Error(`Config file "${n}": "${t}" must be a positive integer.`);return r}function x(e,t,n,r,i){if(typeof e!=`number`||!r(e)||e<0)throw Error(`Config file "${n}": "${t}" must be ${i}.`);return e}function S(e,t,n){if(typeof e!=`boolean`)throw TypeError(`Config file "${n}": "${t}" must be a boolean.`);return e}exports.configFileName=s,exports.loadConfig=l,exports.resolveOptions=c;
1
+ "use strict";const e=require("./_virtual/_rolldown/runtime.cjs"),t=require("./duplication.cjs"),n=require("./languages.cjs"),r=require("./thresholds.cjs");let i=require("@willbooster/shared-lib"),a=require("node:fs/promises"),o=require("node:path");o=e.__toESM(o,1);const s=`code-gauge.config.json`;function c(e,{config:n,directory:r}){return{duplication:{minTokens:e.duplicationMinTokens??n.duplication?.minTokens??t.defaultDuplicationOptions.minTokens,maxGapTokens:e.duplicationMaxGapTokens??n.duplication?.maxGapTokens??t.defaultDuplicationOptions.maxGapTokens,minSimilarityPercent:e.duplicationMinSimilarityPercent??n.duplication?.minSimilarityPercent??t.defaultDuplicationOptions.minSimilarityPercent},exclude:{patterns:n.exclude??[],root:r},top:e.top??n.rank?.top??10,includeTests:e.includeTests??n.includeTests??!1,failOnError:e.failOnError??n.failOnError??!1,json:e.json??!1}}async function l(e,t){let n=e??await u(t);if(!n)return{config:{},directory:t};let r;try{r=await(0,a.readFile)(n,`utf8`)}catch(r){if(e)throw Error(`Cannot read config file "${n}": ${(0,i.getErrorMessage)(r)}`);return{config:{},directory:t}}let s;try{s=JSON.parse(r)}catch(e){throw Error(`Invalid JSON in config file "${n}": ${(0,i.getErrorMessage)(e)}`)}return{config:f(s,n),directory:o.default.dirname(o.default.resolve(n))}}async function u(e){let t=e;for(;;){let e=o.default.join(t,s);if(await d(e))return e;let n=o.default.dirname(t);if(n===t)return;t=n}}async function d(e){try{return(await(0,a.stat)(e)).isFile()}catch{return!1}}function f(e,t){if(!(0,i.isRecord)(e))throw Error(`Config file "${t}" must contain a JSON object.`);let n=/* @__PURE__ */ new Set([`duplication`,`rank`,`thresholds`,`exclude`,`includeTests`,`failOnError`]);for(let r of Object.keys(e))if(!n.has(r))throw Error(`Config file "${t}": unknown setting "${r}" (expected ${[...n].join(`, `)}).`);let r={};e.duplication!==void 0&&(r.duplication=y(e.duplication,t)),e.rank!==void 0&&(r.rank=m(e.rank,t)),e.thresholds!==void 0&&(r.thresholds=h(e.thresholds,t)),e.exclude!==void 0&&(r.exclude=p(e.exclude,t));for(let n of[`includeTests`,`failOnError`])e[n]!==void 0&&(r[n]=C(e[n],n,t));return r}function p(e,t){if(!Array.isArray(e)||!e.every(e=>typeof e==`string`&&e!==``))throw TypeError(`Config file "${t}": "exclude" must be an array of non-empty glob patterns.`);return e}function m(e,t){if(!(0,i.isRecord)(e))throw Error(`Config file "${t}": "rank" must be an object.`);let n={};for(let[r,i]of Object.entries(e)){if(r!==`top`)throw Error(`Config file "${t}": unknown setting "${r}" in "rank" (expected top).`);n.top=x(i,`rank.top`,t)}return n}function h(e,t){return Object.fromEntries(Object.entries(v(e,`thresholds`,t)).map(([e,n])=>{if(!r.levels.includes(e))throw Error(`Config file "${t}": unknown setting "${e}" in "thresholds" (expected ${r.levels.join(`, `)}).`);return[e,g(n,`thresholds.${e}`,t)]}))}function g(e,t,r){let{languages:i,...a}=v(e,t,r),o=`${t}.languages`;return{limits:_(a,t,[`languages`],r),languages:Object.fromEntries(Object.entries(i===void 0?{}:v(i,o,r)).map(([e,t])=>{if(!n.supportedLanguages.includes(e))throw Error(`Config file "${r}": unknown language "${e}" in "${o}" (expected ${n.supportedLanguages.join(`, `)}).`);let i=`${o}.${e}`;return[e,_(v(t,i,r),i,[],r)]}))}}function _(e,t,n,i){let a=r.thresholds.map(({key:e})=>e);return Object.fromEntries(Object.entries(e).map(([e,r])=>{if(!a.includes(e))throw Error(`Config file "${i}": unknown setting "${e}" in "${t}" (expected ${[...a,...n].join(`, `)}).`);if(r!==null&&(typeof r!=`number`||!Number.isFinite(r)||r<0))throw Error(`Config file "${i}": "${t}.${e}" must be a non-negative number or null.`);return[e,r??1/0]}))}function v(e,t,n){if(!(0,i.isRecord)(e))throw Error(`Config file "${n}": "${t}" must be an object.`);return e}function y(e,t){if(!(0,i.isRecord)(e))throw Error(`Config file "${t}": "duplication" must be an object.`);let n={};for(let[r,i]of Object.entries(e))if(r===`minTokens`)n.minTokens=x(i,`duplication.minTokens`,t);else if(r===`maxGapTokens`)n.maxGapTokens=b(i,`duplication.maxGapTokens`,t);else if(r===`minSimilarityPercent`){let e=x(i,`duplication.minSimilarityPercent`,t);if(e>100)throw Error(`Config file "${t}": "duplication.minSimilarityPercent" must be between 1 and 100.`);n.minSimilarityPercent=e}else throw Error(`Config file "${t}": unknown setting "${r}" in "duplication" (expected minTokens, maxGapTokens, or minSimilarityPercent).`);return n}function b(e,t,n){return S(e,t,n,Number.isSafeInteger,`a non-negative integer`)}function x(e,t,n){let r=S(e,t,n,Number.isSafeInteger,`a positive integer`);if(r<1)throw Error(`Config file "${n}": "${t}" must be a positive integer.`);return r}function S(e,t,n,r,i){if(typeof e!=`number`||!r(e)||e<0)throw Error(`Config file "${n}": "${t}" must be ${i}.`);return e}function C(e,t,n){if(typeof e!=`boolean`)throw TypeError(`Config file "${n}": "${t}" must be a boolean.`);return e}exports.configFileName=s,exports.loadConfig=l,exports.resolveOptions=c;
2
2
  //# sourceMappingURL=cliConfig.cjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"cliConfig.cjs","names":["defaultDuplicationOptions","readFile","getErrorMessage","path","stat","isRecord","supportedLanguages","thresholds"],"sources":["../src/cliConfig.ts"],"sourcesContent":["import { readFile, stat } from 'node:fs/promises';\nimport path from 'node:path';\nimport { getErrorMessage, isRecord } from '@willbooster/shared-lib';\nimport { defaultDuplicationOptions } from './duplication.js';\nimport type { ExcludePatterns } from './exclusion.js';\nimport { supportedLanguages } from './languages.js';\nimport { thresholds, type Limits, type ThresholdsConfig } from './thresholds.js';\nimport type { DuplicationOptions } from './types.js';\n\nexport const configFileName = 'code-gauge.config.json';\nexport const defaultTopFileCount = 10;\n\n/** Shape of the JSON configuration file. All fields are optional and fall back to the built-in defaults. */\nexport interface CodeGaugeConfig {\n /** Duplication detection settings applied to every measured file. */\n duplication?: DuplicationOptions;\n /** Refactoring-candidate ranking settings. */\n rank?: { top?: number };\n /** Limits of `code-gauge check`. */\n thresholds?: ThresholdsConfig;\n /** Glob patterns, relative to the config file's directory, of files left out of every command. */\n exclude?: string[];\n includeTests?: boolean;\n failOnError?: boolean;\n}\n\n/** A parsed configuration file and the directory its relative settings resolve against. */\nexport interface LoadedConfig {\n config: CodeGaugeConfig;\n /** The config file's directory; the search start directory when no config file was found. */\n directory: string;\n}\n\n/** Raw command-line options; every field is undefined unless the user passed the flag. */\nexport interface CliOptions {\n config?: string;\n top?: number;\n duplicationMinTokens?: number;\n duplicationMaxGapTokens?: number;\n duplicationMinSimilarityPercent?: number;\n includeTests?: boolean;\n failOnError?: boolean;\n json?: boolean;\n}\n\n/** Options after merging command-line flags, the configuration file, and the built-in defaults. */\nexport interface ResolvedOptions {\n duplication: Required<DuplicationOptions>;\n exclude: ExcludePatterns;\n /** Number of top-ranked files to report. */\n top: number;\n includeTests: boolean;\n failOnError: boolean;\n json: boolean;\n}\n\n/** Resolves options with precedence command-line flags > configuration file > built-in defaults. */\nexport function resolveOptions(cli: CliOptions, { config, directory }: LoadedConfig): ResolvedOptions {\n return {\n duplication: {\n minTokens: cli.duplicationMinTokens ?? config.duplication?.minTokens ?? defaultDuplicationOptions.minTokens,\n maxGapTokens:\n cli.duplicationMaxGapTokens ?? config.duplication?.maxGapTokens ?? defaultDuplicationOptions.maxGapTokens,\n minSimilarityPercent:\n cli.duplicationMinSimilarityPercent ??\n config.duplication?.minSimilarityPercent ??\n defaultDuplicationOptions.minSimilarityPercent,\n },\n exclude: { patterns: config.exclude ?? [], root: directory },\n top: cli.top ?? config.rank?.top ?? defaultTopFileCount,\n includeTests: cli.includeTests ?? config.includeTests ?? false,\n failOnError: cli.failOnError ?? config.failOnError ?? false,\n json: cli.json ?? false,\n };\n}\n\n/**\n * Loads the configuration file. An explicit path must exist; otherwise the nearest\n * `code-gauge.config.json` is searched by walking up from the target directory.\n */\nexport async function loadConfig(explicitPath: string | undefined, targetDirectory: string): Promise<LoadedConfig> {\n const configFile = explicitPath ?? (await findNearestConfig(targetDirectory));\n if (!configFile) {\n return { config: {}, directory: targetDirectory };\n }\n\n let content;\n try {\n content = await readFile(configFile, 'utf8');\n } catch (error) {\n if (explicitPath) {\n throw new Error(`Cannot read config file \"${configFile}\": ${getErrorMessage(error)}`);\n }\n return { config: {}, directory: targetDirectory };\n }\n\n let parsed: unknown;\n try {\n parsed = JSON.parse(content);\n } catch (error) {\n throw new Error(`Invalid JSON in config file \"${configFile}\": ${getErrorMessage(error)}`);\n }\n\n return { config: validateConfig(parsed, configFile), directory: path.dirname(path.resolve(configFile)) };\n}\n\nasync function findNearestConfig(targetDirectory: string): Promise<string | undefined> {\n let currentDirectory = targetDirectory;\n while (true) {\n const configFile = path.join(currentDirectory, configFileName);\n if (await fileExists(configFile)) {\n return configFile;\n }\n\n const parentDirectory = path.dirname(currentDirectory);\n if (parentDirectory === currentDirectory) {\n return undefined;\n }\n currentDirectory = parentDirectory;\n }\n}\n\nasync function fileExists(file: string): Promise<boolean> {\n try {\n const fileStat = await stat(file);\n return fileStat.isFile();\n } catch {\n return false;\n }\n}\n\nfunction validateConfig(value: unknown, configFile: string): CodeGaugeConfig {\n if (!isRecord(value)) {\n throw new Error(`Config file \"${configFile}\" must contain a JSON object.`);\n }\n\n const knownKeys = new Set(['duplication', 'rank', 'thresholds', 'exclude', 'includeTests', 'failOnError']);\n for (const key of Object.keys(value)) {\n if (!knownKeys.has(key)) {\n throw new Error(`Config file \"${configFile}\": unknown setting \"${key}\" (expected ${[...knownKeys].join(', ')}).`);\n }\n }\n const config: CodeGaugeConfig = {};\n\n if (value.duplication !== undefined) {\n config.duplication = validateDuplicationObject(value.duplication, configFile);\n }\n\n if (value.rank !== undefined) {\n config.rank = validateRankObject(value.rank, configFile);\n }\n\n if (value.thresholds !== undefined) {\n config.thresholds = validateThresholdsObject(value.thresholds, configFile);\n }\n\n if (value.exclude !== undefined) {\n config.exclude = validateExcludePatterns(value.exclude, configFile);\n }\n\n for (const key of ['includeTests', 'failOnError'] as const) {\n if (value[key] !== undefined) {\n config[key] = requireBoolean(value[key], key, configFile);\n }\n }\n\n return config;\n}\n\nfunction validateExcludePatterns(value: unknown, configFile: string): string[] {\n if (!Array.isArray(value) || !value.every((pattern) => typeof pattern === 'string' && pattern !== '')) {\n throw new TypeError(`Config file \"${configFile}\": \"exclude\" must be an array of non-empty glob patterns.`);\n }\n return value as string[];\n}\n\nfunction validateRankObject(value: unknown, configFile: string): { top?: number } {\n if (!isRecord(value)) {\n throw new Error(`Config file \"${configFile}\": \"rank\" must be an object.`);\n }\n const rank: { top?: number } = {};\n for (const [key, setting] of Object.entries(value)) {\n if (key !== 'top') {\n throw new Error(`Config file \"${configFile}\": unknown setting \"${key}\" in \"rank\" (expected top).`);\n }\n rank.top = requirePositiveInteger(setting, 'rank.top', configFile);\n }\n return rank;\n}\n\nfunction validateThresholdsObject(value: unknown, configFile: string): ThresholdsConfig {\n const { languages, ...limits } = requireRecord(value, 'thresholds', configFile);\n return {\n limits: validateLimits(limits, 'thresholds', ['languages'], configFile),\n languages: Object.fromEntries(\n Object.entries(languages === undefined ? {} : requireRecord(languages, 'thresholds.languages', configFile)).map(\n ([language, overrides]) => {\n if (!supportedLanguages.includes(language)) {\n throw new Error(\n `Config file \"${configFile}\": unknown language \"${language}\" in \"thresholds.languages\" (expected ${supportedLanguages.join(', ')}).`\n );\n }\n const settingName = `thresholds.languages.${language}`;\n return [\n language,\n validateLimits(requireRecord(overrides, settingName, configFile), settingName, [], configFile),\n ];\n }\n )\n ),\n };\n}\n\n/** Limits as written in the config file, where `null` disables one. */\nfunction validateLimits(\n value: Record<string, unknown>,\n settingName: string,\n otherKeys: string[],\n configFile: string\n): Limits {\n const knownKeys = thresholds.map(({ key }) => key);\n return Object.fromEntries(\n Object.entries(value).map(([key, limit]) => {\n if (!knownKeys.includes(key)) {\n throw new Error(\n `Config file \"${configFile}\": unknown setting \"${key}\" in \"${settingName}\" (expected ${[...knownKeys, ...otherKeys].join(', ')}).`\n );\n }\n if (limit !== null && (typeof limit !== 'number' || !Number.isFinite(limit) || limit < 0)) {\n throw new Error(`Config file \"${configFile}\": \"${settingName}.${key}\" must be a non-negative number or null.`);\n }\n return [key, limit ?? Infinity];\n })\n );\n}\n\nfunction requireRecord(value: unknown, settingName: string, configFile: string): Record<string, unknown> {\n if (!isRecord(value)) {\n throw new Error(`Config file \"${configFile}\": \"${settingName}\" must be an object.`);\n }\n return value;\n}\n\nfunction validateDuplicationObject(value: unknown, configFile: string): DuplicationOptions {\n if (!isRecord(value)) {\n throw new Error(`Config file \"${configFile}\": \"duplication\" must be an object.`);\n }\n const duplication: DuplicationOptions = {};\n for (const [key, setting] of Object.entries(value)) {\n if (key === 'minTokens') {\n duplication.minTokens = requirePositiveInteger(setting, 'duplication.minTokens', configFile);\n } else if (key === 'maxGapTokens') {\n // 0 is meaningful: it disables gapped-clone merging.\n duplication.maxGapTokens = requireNonNegativeInteger(setting, 'duplication.maxGapTokens', configFile);\n } else if (key === 'minSimilarityPercent') {\n const parsed = requirePositiveInteger(setting, 'duplication.minSimilarityPercent', configFile);\n if (parsed > 100) {\n throw new Error(`Config file \"${configFile}\": \"duplication.minSimilarityPercent\" must be between 1 and 100.`);\n }\n duplication.minSimilarityPercent = parsed;\n } else {\n throw new Error(\n `Config file \"${configFile}\": unknown setting \"${key}\" in \"duplication\" (expected minTokens, maxGapTokens, or minSimilarityPercent).`\n );\n }\n }\n return duplication;\n}\n\nfunction requireNonNegativeInteger(value: unknown, key: string, configFile: string): number {\n return requireNumber(value, key, configFile, Number.isSafeInteger, 'a non-negative integer');\n}\n\nfunction requirePositiveInteger(value: unknown, key: string, configFile: string): number {\n const parsed = requireNumber(value, key, configFile, Number.isSafeInteger, 'a positive integer');\n if (parsed < 1) {\n throw new Error(`Config file \"${configFile}\": \"${key}\" must be a positive integer.`);\n }\n return parsed;\n}\n\n/** Shared core of the numeric validators: the right kind of number, and never negative. */\nfunction requireNumber(\n value: unknown,\n key: string,\n configFile: string,\n isValidKind: (value: unknown) => boolean,\n description: string\n): number {\n if (typeof value !== 'number' || !isValidKind(value) || value < 0) {\n throw new Error(`Config file \"${configFile}\": \"${key}\" must be ${description}.`);\n }\n return value;\n}\n\nfunction requireBoolean(value: unknown, key: string, configFile: string): boolean {\n if (typeof value !== 'boolean') {\n throw new TypeError(`Config file \"${configFile}\": \"${key}\" must be a boolean.`);\n }\n return value;\n}\n"],"mappings":"0QASA,MAAa,EAAiB,yBAgD9B,SAAgB,EAAe,EAAiB,CAAE,SAAQ,aAA4C,CACpG,MAAO,CACL,YAAa,CACX,UAAW,EAAI,sBAAwB,EAAO,aAAa,WAAaA,EAAAA,0BAA0B,UAClG,aACE,EAAI,yBAA2B,EAAO,aAAa,cAAgBA,EAAAA,0BAA0B,aAC/F,qBACE,EAAI,iCACJ,EAAO,aAAa,sBACpBA,EAAAA,0BAA0B,oBAC9B,EACA,QAAS,CAAE,SAAU,EAAO,SAAW,CAAC,EAAG,KAAM,CAAU,EAC3D,IAAK,EAAI,KAAO,EAAO,MAAM,KAAA,GAC7B,aAAc,EAAI,cAAgB,EAAO,cAAgB,GACzD,YAAa,EAAI,aAAe,EAAO,aAAe,GACtD,KAAM,EAAI,MAAQ,EACpB,CACF,CAMA,eAAsB,EAAW,EAAkC,EAAgD,CACjH,IAAM,EAAa,GAAiB,MAAM,EAAkB,CAAe,EAC3E,GAAI,CAAC,EACH,MAAO,CAAE,OAAQ,CAAC,EAAG,UAAW,CAAgB,EAGlD,IAAI,EACJ,GAAI,CACF,EAAU,MAAA,EAAMC,EAAAA,SAAAA,CAAS,EAAY,MAAM,CAC7C,OAAS,EAAO,CAC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AAI,IAAQ,YACV,EAAY,UAAY,EAAuB,EAAS,wBAAyB,CAAU,OACtF,GAAI,IAAQ,eAEjB,EAAY,aAAe,EAA0B,EAAS,2BAA4B,CAAU,OAC/F,GAAI,IAAQ,uBAAwB,CACzC,IAAM,EAAS,EAAuB,EAAS,mCAAoC,CAAU,EAC7F,GAAI,EAAS,IACX,MAAU,MAAM,gBAAgB,EAAW,iEAAiE,EAE9G,EAAY,qBAAuB,CACrC,MACE,MAAU,MACR,gBAAgB,EAAW,sBAAsB,EAAI,gFACvD,EAGJ,OAAO,CACT,CAEA,SAAS,EAA0B,EAAgB,EAAa,EAA4B,CAC1F,OAAO,EAAc,EAAO,EAAK,EAAY,OAAO,cAAe,wBAAwB,CAC7F,CAEA,SAAS,EAAuB,EAAgB,EAAa,EAA4B,CACvF,IAAM,EAAS,EAAc,EAAO,EAAK,EAAY,OAAO,cAAe,oBAAoB,EAC/F,GAAI,EAAS,EACX,MAAU,MAAM,gBAAgB,EAAW,MAAM,EAAI,8BAA8B,EAErF,OAAO,CACT,CAGA,SAAS,EACP,EACA,EACA,EACA,EACA,EACQ,CACR,GAAI,OAAO,GAAU,UAAY,CAAC,EAAY,CAAK,GAAK,EAAQ,EAC9D,MAAU,MAAM,gBAAgB,EAAW,MAAM,EAAI,YAAY,EAAY,EAAE,EAEjF,OAAO,CACT,CAEA,SAAS,EAAe,EAAgB,EAAa,EAA6B,CAChF,GAAI,OAAO,GAAU,UACnB,MAAU,UAAU,gBAAgB,EAAW,MAAM,EAAI,qBAAqB,EAEhF,OAAO,CACT"}
1
+ {"version":3,"file":"cliConfig.cjs","names":["defaultDuplicationOptions","readFile","getErrorMessage","path","stat","isRecord","levels","supportedLanguages","thresholds"],"sources":["../src/cliConfig.ts"],"sourcesContent":["import { readFile, stat } from 'node:fs/promises';\nimport path from 'node:path';\nimport { getErrorMessage, isRecord } from '@willbooster/shared-lib';\nimport { defaultDuplicationOptions } from './duplication.js';\nimport type { ExcludePatterns } from './exclusion.js';\nimport { supportedLanguages } from './languages.js';\nimport {\n levels,\n thresholds,\n type Level,\n type LevelThresholdsConfig,\n type Limits,\n type ThresholdsConfig,\n} from './thresholds.js';\nimport type { DuplicationOptions } from './types.js';\n\nexport const configFileName = 'code-gauge.config.json';\nexport const defaultTopFileCount = 10;\n\n/** Shape of the JSON configuration file. All fields are optional and fall back to the built-in defaults. */\nexport interface CodeGaugeConfig {\n /** Duplication detection settings applied to every measured file. */\n duplication?: DuplicationOptions;\n /** Refactoring-candidate ranking settings. */\n rank?: { top?: number };\n /** Limits of `code-gauge check`. */\n thresholds?: ThresholdsConfig;\n /** Glob patterns, relative to the config file's directory, of files left out of every command. */\n exclude?: string[];\n includeTests?: boolean;\n failOnError?: boolean;\n}\n\n/** A parsed configuration file and the directory its relative settings resolve against. */\nexport interface LoadedConfig {\n config: CodeGaugeConfig;\n /** The config file's directory; the search start directory when no config file was found. */\n directory: string;\n}\n\n/** Raw command-line options; every field is undefined unless the user passed the flag. */\nexport interface CliOptions {\n config?: string;\n top?: number;\n duplicationMinTokens?: number;\n duplicationMaxGapTokens?: number;\n duplicationMinSimilarityPercent?: number;\n includeTests?: boolean;\n failOnError?: boolean;\n json?: boolean;\n}\n\n/** Options after merging command-line flags, the configuration file, and the built-in defaults. */\nexport interface ResolvedOptions {\n duplication: Required<DuplicationOptions>;\n exclude: ExcludePatterns;\n /** Number of top-ranked files to report. */\n top: number;\n includeTests: boolean;\n failOnError: boolean;\n json: boolean;\n}\n\n/** Resolves options with precedence command-line flags > configuration file > built-in defaults. */\nexport function resolveOptions(cli: CliOptions, { config, directory }: LoadedConfig): ResolvedOptions {\n return {\n duplication: {\n minTokens: cli.duplicationMinTokens ?? config.duplication?.minTokens ?? defaultDuplicationOptions.minTokens,\n maxGapTokens:\n cli.duplicationMaxGapTokens ?? config.duplication?.maxGapTokens ?? defaultDuplicationOptions.maxGapTokens,\n minSimilarityPercent:\n cli.duplicationMinSimilarityPercent ??\n config.duplication?.minSimilarityPercent ??\n defaultDuplicationOptions.minSimilarityPercent,\n },\n exclude: { patterns: config.exclude ?? [], root: directory },\n top: cli.top ?? config.rank?.top ?? defaultTopFileCount,\n includeTests: cli.includeTests ?? config.includeTests ?? false,\n failOnError: cli.failOnError ?? config.failOnError ?? false,\n json: cli.json ?? false,\n };\n}\n\n/**\n * Loads the configuration file. An explicit path must exist; otherwise the nearest\n * `code-gauge.config.json` is searched by walking up from the target directory.\n */\nexport async function loadConfig(explicitPath: string | undefined, targetDirectory: string): Promise<LoadedConfig> {\n const configFile = explicitPath ?? (await findNearestConfig(targetDirectory));\n if (!configFile) {\n return { config: {}, directory: targetDirectory };\n }\n\n let content;\n try {\n content = await readFile(configFile, 'utf8');\n } catch (error) {\n if (explicitPath) {\n throw new Error(`Cannot read config file \"${configFile}\": ${getErrorMessage(error)}`);\n }\n return { config: {}, directory: targetDirectory };\n }\n\n let parsed: unknown;\n try {\n parsed = JSON.parse(content);\n } catch (error) {\n throw new Error(`Invalid JSON in config file \"${configFile}\": ${getErrorMessage(error)}`);\n }\n\n return { config: validateConfig(parsed, configFile), directory: path.dirname(path.resolve(configFile)) };\n}\n\nasync function findNearestConfig(targetDirectory: string): Promise<string | undefined> {\n let currentDirectory = targetDirectory;\n while (true) {\n const configFile = path.join(currentDirectory, configFileName);\n if (await fileExists(configFile)) {\n return configFile;\n }\n\n const parentDirectory = path.dirname(currentDirectory);\n if (parentDirectory === currentDirectory) {\n return undefined;\n }\n currentDirectory = parentDirectory;\n }\n}\n\nasync function fileExists(file: string): Promise<boolean> {\n try {\n const fileStat = await stat(file);\n return fileStat.isFile();\n } catch {\n return false;\n }\n}\n\nfunction validateConfig(value: unknown, configFile: string): CodeGaugeConfig {\n if (!isRecord(value)) {\n throw new Error(`Config file \"${configFile}\" must contain a JSON object.`);\n }\n\n const knownKeys = new Set(['duplication', 'rank', 'thresholds', 'exclude', 'includeTests', 'failOnError']);\n for (const key of Object.keys(value)) {\n if (!knownKeys.has(key)) {\n throw new Error(`Config file \"${configFile}\": unknown setting \"${key}\" (expected ${[...knownKeys].join(', ')}).`);\n }\n }\n const config: CodeGaugeConfig = {};\n\n if (value.duplication !== undefined) {\n config.duplication = validateDuplicationObject(value.duplication, configFile);\n }\n\n if (value.rank !== undefined) {\n config.rank = validateRankObject(value.rank, configFile);\n }\n\n if (value.thresholds !== undefined) {\n config.thresholds = validateThresholdsObject(value.thresholds, configFile);\n }\n\n if (value.exclude !== undefined) {\n config.exclude = validateExcludePatterns(value.exclude, configFile);\n }\n\n for (const key of ['includeTests', 'failOnError'] as const) {\n if (value[key] !== undefined) {\n config[key] = requireBoolean(value[key], key, configFile);\n }\n }\n\n return config;\n}\n\nfunction validateExcludePatterns(value: unknown, configFile: string): string[] {\n if (!Array.isArray(value) || !value.every((pattern) => typeof pattern === 'string' && pattern !== '')) {\n throw new TypeError(`Config file \"${configFile}\": \"exclude\" must be an array of non-empty glob patterns.`);\n }\n return value as string[];\n}\n\nfunction validateRankObject(value: unknown, configFile: string): { top?: number } {\n if (!isRecord(value)) {\n throw new Error(`Config file \"${configFile}\": \"rank\" must be an object.`);\n }\n const rank: { top?: number } = {};\n for (const [key, setting] of Object.entries(value)) {\n if (key !== 'top') {\n throw new Error(`Config file \"${configFile}\": unknown setting \"${key}\" in \"rank\" (expected top).`);\n }\n rank.top = requirePositiveInteger(setting, 'rank.top', configFile);\n }\n return rank;\n}\n\nfunction validateThresholdsObject(value: unknown, configFile: string): ThresholdsConfig {\n return Object.fromEntries(\n Object.entries(requireRecord(value, 'thresholds', configFile)).map(([level, levelThresholds]) => {\n if (!levels.includes(level as Level)) {\n throw new Error(\n `Config file \"${configFile}\": unknown setting \"${level}\" in \"thresholds\" (expected ${levels.join(', ')}).`\n );\n }\n return [level, validateLevelThresholds(levelThresholds, `thresholds.${level}`, configFile)];\n })\n );\n}\n\nfunction validateLevelThresholds(value: unknown, settingName: string, configFile: string): LevelThresholdsConfig {\n const { languages, ...limits } = requireRecord(value, settingName, configFile);\n const languagesName = `${settingName}.languages`;\n return {\n limits: validateLimits(limits, settingName, ['languages'], configFile),\n languages: Object.fromEntries(\n Object.entries(languages === undefined ? {} : requireRecord(languages, languagesName, configFile)).map(\n ([language, overrides]) => {\n if (!supportedLanguages.includes(language)) {\n throw new Error(\n `Config file \"${configFile}\": unknown language \"${language}\" in \"${languagesName}\" (expected ${supportedLanguages.join(', ')}).`\n );\n }\n const languageName = `${languagesName}.${language}`;\n return [\n language,\n validateLimits(requireRecord(overrides, languageName, configFile), languageName, [], configFile),\n ];\n }\n )\n ),\n };\n}\n\n/** Limits as written in the config file, where `null` disables one. */\nfunction validateLimits(\n value: Record<string, unknown>,\n settingName: string,\n otherKeys: string[],\n configFile: string\n): Limits {\n const knownKeys = thresholds.map(({ key }) => key);\n return Object.fromEntries(\n Object.entries(value).map(([key, limit]) => {\n if (!knownKeys.includes(key)) {\n throw new Error(\n `Config file \"${configFile}\": unknown setting \"${key}\" in \"${settingName}\" (expected ${[...knownKeys, ...otherKeys].join(', ')}).`\n );\n }\n if (limit !== null && (typeof limit !== 'number' || !Number.isFinite(limit) || limit < 0)) {\n throw new Error(`Config file \"${configFile}\": \"${settingName}.${key}\" must be a non-negative number or null.`);\n }\n return [key, limit ?? Infinity];\n })\n );\n}\n\nfunction requireRecord(value: unknown, settingName: string, configFile: string): Record<string, unknown> {\n if (!isRecord(value)) {\n throw new Error(`Config file \"${configFile}\": \"${settingName}\" must be an object.`);\n }\n return value;\n}\n\nfunction validateDuplicationObject(value: unknown, configFile: string): DuplicationOptions {\n if (!isRecord(value)) {\n throw new Error(`Config file \"${configFile}\": \"duplication\" must be an object.`);\n }\n const duplication: DuplicationOptions = {};\n for (const [key, setting] of Object.entries(value)) {\n if (key === 'minTokens') {\n duplication.minTokens = requirePositiveInteger(setting, 'duplication.minTokens', configFile);\n } else if (key === 'maxGapTokens') {\n // 0 is meaningful: it disables gapped-clone merging.\n duplication.maxGapTokens = requireNonNegativeInteger(setting, 'duplication.maxGapTokens', configFile);\n } else if (key === 'minSimilarityPercent') {\n const parsed = requirePositiveInteger(setting, 'duplication.minSimilarityPercent', configFile);\n if (parsed > 100) {\n throw new Error(`Config file \"${configFile}\": \"duplication.minSimilarityPercent\" must be between 1 and 100.`);\n }\n duplication.minSimilarityPercent = parsed;\n } else {\n throw new Error(\n `Config file \"${configFile}\": unknown setting \"${key}\" in \"duplication\" (expected minTokens, maxGapTokens, or minSimilarityPercent).`\n );\n }\n }\n return duplication;\n}\n\nfunction requireNonNegativeInteger(value: unknown, key: string, configFile: string): number {\n return requireNumber(value, key, configFile, Number.isSafeInteger, 'a non-negative integer');\n}\n\nfunction requirePositiveInteger(value: unknown, key: string, configFile: string): number {\n const parsed = requireNumber(value, key, configFile, Number.isSafeInteger, 'a positive integer');\n if (parsed < 1) {\n throw new Error(`Config file \"${configFile}\": \"${key}\" must be a positive integer.`);\n }\n return parsed;\n}\n\n/** Shared core of the numeric validators: the right kind of number, and never negative. */\nfunction requireNumber(\n value: unknown,\n key: string,\n configFile: string,\n isValidKind: (value: unknown) => boolean,\n description: string\n): number {\n if (typeof value !== 'number' || !isValidKind(value) || value < 0) {\n throw new Error(`Config file \"${configFile}\": \"${key}\" must be ${description}.`);\n }\n return value;\n}\n\nfunction requireBoolean(value: unknown, key: string, configFile: string): boolean {\n if (typeof value !== 'boolean') {\n throw new TypeError(`Config file \"${configFile}\": \"${key}\" must be a boolean.`);\n }\n return value;\n}\n"],"mappings":"0QAgBA,MAAa,EAAiB,yBAgD9B,SAAgB,EAAe,EAAiB,CAAE,SAAQ,aAA4C,CACpG,MAAO,CACL,YAAa,CACX,UAAW,EAAI,sBAAwB,EAAO,aAAa,WAAaA,EAAAA,0BAA0B,UAClG,aACE,EAAI,yBAA2B,EAAO,aAAa,cAAgBA,EAAAA,0BAA0B,aAC/F,qBACE,EAAI,iCACJ,EAAO,aAAa,sBACpBA,EAAAA,0BAA0B,oBAC9B,EACA,QAAS,CAAE,SAAU,EAAO,SAAW,CAAC,EAAG,KAAM,CAAU,EAC3D,IAAK,E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OAAO,cAAe,wBAAwB,CAC7F,CAEA,SAAS,EAAuB,EAAgB,EAAa,EAA4B,CACvF,IAAM,EAAS,EAAc,EAAO,EAAK,EAAY,OAAO,cAAe,oBAAoB,EAC/F,GAAI,EAAS,EACX,MAAU,MAAM,gBAAgB,EAAW,MAAM,EAAI,8BAA8B,EAErF,OAAO,CACT,CAGA,SAAS,EACP,EACA,EACA,EACA,EACA,EACQ,CACR,GAAI,OAAO,GAAU,UAAY,CAAC,EAAY,CAAK,GAAK,EAAQ,EAC9D,MAAU,MAAM,gBAAgB,EAAW,MAAM,EAAI,YAAY,EAAY,EAAE,EAEjF,OAAO,CACT,CAEA,SAAS,EAAe,EAAgB,EAAa,EAA6B,CAChF,GAAI,OAAO,GAAU,UACnB,MAAU,UAAU,gBAAgB,EAAW,MAAM,EAAI,qBAAqB,EAEhF,OAAO,CACT"}
package/dist/cliConfig.js CHANGED
@@ -1,2 +1,2 @@
1
- import{defaultDuplicationOptions as e}from"./duplication.js";import{supportedLanguages as t}from"./languages.js";import{thresholds as n}from"./thresholds.js";import{getErrorMessage as r,isRecord as i}from"@willbooster/shared-lib";import{readFile as a,stat as o}from"node:fs/promises";import s from"node:path";const c=`code-gauge.config.json`;function l(t,{config:n,directory:r}){return{duplication:{minTokens:t.duplicationMinTokens??n.duplication?.minTokens??e.minTokens,maxGapTokens:t.duplicationMaxGapTokens??n.duplication?.maxGapTokens??e.maxGapTokens,minSimilarityPercent:t.duplicationMinSimilarityPercent??n.duplication?.minSimilarityPercent??e.minSimilarityPercent},exclude:{patterns:n.exclude??[],root:r},top:t.top??n.rank?.top??10,includeTests:t.includeTests??n.includeTests??!1,failOnError:t.failOnError??n.failOnError??!1,json:t.json??!1}}async function u(e,t){let n=e??await d(t);if(!n)return{config:{},directory:t};let i;try{i=await a(n,`utf8`)}catch(i){if(e)throw Error(`Cannot read config file "${n}": ${r(i)}`);return{config:{},directory:t}}let o;try{o=JSON.parse(i)}catch(e){throw Error(`Invalid JSON in config file "${n}": ${r(e)}`)}return{config:p(o,n),directory:s.dirname(s.resolve(n))}}async function d(e){let t=e;for(;;){let e=s.join(t,c);if(await f(e))return e;let n=s.dirname(t);if(n===t)return;t=n}}async function f(e){try{return(await o(e)).isFile()}catch{return!1}}function p(e,t){if(!i(e))throw Error(`Config file "${t}" must contain a JSON object.`);let n=/* @__PURE__ */ new Set([`duplication`,`rank`,`thresholds`,`exclude`,`includeTests`,`failOnError`]);for(let r of Object.keys(e))if(!n.has(r))throw Error(`Config file "${t}": unknown setting "${r}" (expected ${[...n].join(`, `)}).`);let r={};e.duplication!==void 0&&(r.duplication=y(e.duplication,t)),e.rank!==void 0&&(r.rank=h(e.rank,t)),e.thresholds!==void 0&&(r.thresholds=g(e.thresholds,t)),e.exclude!==void 0&&(r.exclude=m(e.exclude,t));for(let n of[`includeTests`,`failOnError`])e[n]!==void 0&&(r[n]=C(e[n],n,t));return r}function m(e,t){if(!Array.isArray(e)||!e.every(e=>typeof e==`string`&&e!==``))throw TypeError(`Config file "${t}": "exclude" must be an array of non-empty glob patterns.`);return e}function h(e,t){if(!i(e))throw Error(`Config file "${t}": "rank" must be an object.`);let n={};for(let[r,i]of Object.entries(e)){if(r!==`top`)throw Error(`Config file "${t}": unknown setting "${r}" in "rank" (expected top).`);n.top=x(i,`rank.top`,t)}return n}function g(e,n){let{languages:r,...i}=v(e,`thresholds`,n);return{limits:_(i,`thresholds`,[`languages`],n),languages:Object.fromEntries(Object.entries(r===void 0?{}:v(r,`thresholds.languages`,n)).map(([e,r])=>{if(!t.includes(e))throw Error(`Config file "${n}": unknown language "${e}" in "thresholds.languages" (expected ${t.join(`, `)}).`);let i=`thresholds.languages.${e}`;return[e,_(v(r,i,n),i,[],n)]}))}}function _(e,t,r,i){let a=n.map(({key:e})=>e);return Object.fromEntries(Object.entries(e).map(([e,n])=>{if(!a.includes(e))throw Error(`Config file "${i}": unknown setting "${e}" in "${t}" (expected ${[...a,...r].join(`, `)}).`);if(n!==null&&(typeof n!=`number`||!Number.isFinite(n)||n<0))throw Error(`Config file "${i}": "${t}.${e}" must be a non-negative number or null.`);return[e,n??1/0]}))}function v(e,t,n){if(!i(e))throw Error(`Config file "${n}": "${t}" must be an object.`);return e}function y(e,t){if(!i(e))throw Error(`Config file "${t}": "duplication" must be an object.`);let n={};for(let[r,i]of Object.entries(e))if(r===`minTokens`)n.minTokens=x(i,`duplication.minTokens`,t);else if(r===`maxGapTokens`)n.maxGapTokens=b(i,`duplication.maxGapTokens`,t);else if(r===`minSimilarityPercent`){let e=x(i,`duplication.minSimilarityPercent`,t);if(e>100)throw Error(`Config file "${t}": "duplication.minSimilarityPercent" must be between 1 and 100.`);n.minSimilarityPercent=e}else throw Error(`Config file "${t}": unknown setting "${r}" in "duplication" (expected minTokens, maxGapTokens, or minSimilarityPercent).`);return n}function b(e,t,n){return S(e,t,n,Number.isSafeInteger,`a non-negative integer`)}function x(e,t,n){let r=S(e,t,n,Number.isSafeInteger,`a positive integer`);if(r<1)throw Error(`Config file "${n}": "${t}" must be a positive integer.`);return r}function S(e,t,n,r,i){if(typeof e!=`number`||!r(e)||e<0)throw Error(`Config file "${n}": "${t}" must be ${i}.`);return e}function C(e,t,n){if(typeof e!=`boolean`)throw TypeError(`Config file "${n}": "${t}" must be a boolean.`);return e}export{c as configFileName,u as loadConfig,l as resolveOptions};
1
+ import{defaultDuplicationOptions as e}from"./duplication.js";import{supportedLanguages as t}from"./languages.js";import{levels as n,thresholds as r}from"./thresholds.js";import{getErrorMessage as i,isRecord as a}from"@willbooster/shared-lib";import{readFile as o,stat as s}from"node:fs/promises";import c from"node:path";const l=`code-gauge.config.json`;function u(t,{config:n,directory:r}){return{duplication:{minTokens:t.duplicationMinTokens??n.duplication?.minTokens??e.minTokens,maxGapTokens:t.duplicationMaxGapTokens??n.duplication?.maxGapTokens??e.maxGapTokens,minSimilarityPercent:t.duplicationMinSimilarityPercent??n.duplication?.minSimilarityPercent??e.minSimilarityPercent},exclude:{patterns:n.exclude??[],root:r},top:t.top??n.rank?.top??10,includeTests:t.includeTests??n.includeTests??!1,failOnError:t.failOnError??n.failOnError??!1,json:t.json??!1}}async function d(e,t){let n=e??await f(t);if(!n)return{config:{},directory:t};let r;try{r=await o(n,`utf8`)}catch(r){if(e)throw Error(`Cannot read config file "${n}": ${i(r)}`);return{config:{},directory:t}}let a;try{a=JSON.parse(r)}catch(e){throw Error(`Invalid JSON in config file "${n}": ${i(e)}`)}return{config:m(a,n),directory:c.dirname(c.resolve(n))}}async function f(e){let t=e;for(;;){let e=c.join(t,l);if(await p(e))return e;let n=c.dirname(t);if(n===t)return;t=n}}async function p(e){try{return(await s(e)).isFile()}catch{return!1}}function m(e,t){if(!a(e))throw Error(`Config file "${t}" must contain a JSON object.`);let n=/* @__PURE__ */ new Set([`duplication`,`rank`,`thresholds`,`exclude`,`includeTests`,`failOnError`]);for(let r of Object.keys(e))if(!n.has(r))throw Error(`Config file "${t}": unknown setting "${r}" (expected ${[...n].join(`, `)}).`);let r={};e.duplication!==void 0&&(r.duplication=x(e.duplication,t)),e.rank!==void 0&&(r.rank=g(e.rank,t)),e.thresholds!==void 0&&(r.thresholds=_(e.thresholds,t)),e.exclude!==void 0&&(r.exclude=h(e.exclude,t));for(let n of[`includeTests`,`failOnError`])e[n]!==void 0&&(r[n]=T(e[n],n,t));return r}function h(e,t){if(!Array.isArray(e)||!e.every(e=>typeof e==`string`&&e!==``))throw TypeError(`Config file "${t}": "exclude" must be an array of non-empty glob patterns.`);return e}function g(e,t){if(!a(e))throw Error(`Config file "${t}": "rank" must be an object.`);let n={};for(let[r,i]of Object.entries(e)){if(r!==`top`)throw Error(`Config file "${t}": unknown setting "${r}" in "rank" (expected top).`);n.top=C(i,`rank.top`,t)}return n}function _(e,t){return Object.fromEntries(Object.entries(b(e,`thresholds`,t)).map(([e,r])=>{if(!n.includes(e))throw Error(`Config file "${t}": unknown setting "${e}" in "thresholds" (expected ${n.join(`, `)}).`);return[e,v(r,`thresholds.${e}`,t)]}))}function v(e,n,r){let{languages:i,...a}=b(e,n,r),o=`${n}.languages`;return{limits:y(a,n,[`languages`],r),languages:Object.fromEntries(Object.entries(i===void 0?{}:b(i,o,r)).map(([e,n])=>{if(!t.includes(e))throw Error(`Config file "${r}": unknown language "${e}" in "${o}" (expected ${t.join(`, `)}).`);let i=`${o}.${e}`;return[e,y(b(n,i,r),i,[],r)]}))}}function y(e,t,n,i){let a=r.map(({key:e})=>e);return Object.fromEntries(Object.entries(e).map(([e,r])=>{if(!a.includes(e))throw Error(`Config file "${i}": unknown setting "${e}" in "${t}" (expected ${[...a,...n].join(`, `)}).`);if(r!==null&&(typeof r!=`number`||!Number.isFinite(r)||r<0))throw Error(`Config file "${i}": "${t}.${e}" must be a non-negative number or null.`);return[e,r??1/0]}))}function b(e,t,n){if(!a(e))throw Error(`Config file "${n}": "${t}" must be an object.`);return e}function x(e,t){if(!a(e))throw Error(`Config file "${t}": "duplication" must be an object.`);let n={};for(let[r,i]of Object.entries(e))if(r===`minTokens`)n.minTokens=C(i,`duplication.minTokens`,t);else if(r===`maxGapTokens`)n.maxGapTokens=S(i,`duplication.maxGapTokens`,t);else if(r===`minSimilarityPercent`){let e=C(i,`duplication.minSimilarityPercent`,t);if(e>100)throw Error(`Config file "${t}": "duplication.minSimilarityPercent" must be between 1 and 100.`);n.minSimilarityPercent=e}else throw Error(`Config file "${t}": unknown setting "${r}" in "duplication" (expected minTokens, maxGapTokens, or minSimilarityPercent).`);return n}function S(e,t,n){return w(e,t,n,Number.isSafeInteger,`a non-negative integer`)}function C(e,t,n){let r=w(e,t,n,Number.isSafeInteger,`a positive integer`);if(r<1)throw Error(`Config file "${n}": "${t}" must be a positive integer.`);return r}function w(e,t,n,r,i){if(typeof e!=`number`||!r(e)||e<0)throw Error(`Config file "${n}": "${t}" must be ${i}.`);return e}function T(e,t,n){if(typeof e!=`boolean`)throw TypeError(`Config file "${n}": "${t}" must be a boolean.`);return e}export{l as configFileName,d as loadConfig,u as resolveOptions};
2
2
  //# sourceMappingURL=cliConfig.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"cliConfig.js","names":[],"sources":["../src/cliConfig.ts"],"sourcesContent":["import { readFile, stat } from 'node:fs/promises';\nimport path from 'node:path';\nimport { getErrorMessage, isRecord } from '@willbooster/shared-lib';\nimport { defaultDuplicationOptions } from './duplication.js';\nimport type { ExcludePatterns } from './exclusion.js';\nimport { supportedLanguages } from './languages.js';\nimport { thresholds, type Limits, type ThresholdsConfig } from './thresholds.js';\nimport type { DuplicationOptions } from './types.js';\n\nexport const configFileName = 'code-gauge.config.json';\nexport const defaultTopFileCount = 10;\n\n/** Shape of the JSON configuration file. All fields are optional and fall back to the built-in defaults. */\nexport interface CodeGaugeConfig {\n /** Duplication detection settings applied to every measured file. */\n duplication?: DuplicationOptions;\n /** Refactoring-candidate ranking settings. */\n rank?: { top?: number };\n /** Limits of `code-gauge check`. */\n thresholds?: ThresholdsConfig;\n /** Glob patterns, relative to the config file's directory, of files left out of every command. */\n exclude?: string[];\n includeTests?: boolean;\n failOnError?: boolean;\n}\n\n/** A parsed configuration file and the directory its relative settings resolve against. */\nexport interface LoadedConfig {\n config: CodeGaugeConfig;\n /** The config file's directory; the search start directory when no config file was found. */\n directory: string;\n}\n\n/** Raw command-line options; every field is undefined unless the user passed the flag. */\nexport interface CliOptions {\n config?: string;\n top?: number;\n duplicationMinTokens?: number;\n duplicationMaxGapTokens?: number;\n duplicationMinSimilarityPercent?: number;\n includeTests?: boolean;\n failOnError?: boolean;\n json?: boolean;\n}\n\n/** Options after merging command-line flags, the configuration file, and the built-in defaults. */\nexport interface ResolvedOptions {\n duplication: Required<DuplicationOptions>;\n exclude: ExcludePatterns;\n /** Number of top-ranked files to report. */\n top: number;\n includeTests: boolean;\n failOnError: boolean;\n json: boolean;\n}\n\n/** Resolves options with precedence command-line flags > configuration file > built-in defaults. */\nexport function resolveOptions(cli: CliOptions, { config, directory }: LoadedConfig): ResolvedOptions {\n return {\n duplication: {\n minTokens: cli.duplicationMinTokens ?? config.duplication?.minTokens ?? defaultDuplicationOptions.minTokens,\n maxGapTokens:\n cli.duplicationMaxGapTokens ?? config.duplication?.maxGapTokens ?? defaultDuplicationOptions.maxGapTokens,\n minSimilarityPercent:\n cli.duplicationMinSimilarityPercent ??\n config.duplication?.minSimilarityPercent ??\n defaultDuplicationOptions.minSimilarityPercent,\n },\n exclude: { patterns: config.exclude ?? [], root: directory },\n top: cli.top ?? config.rank?.top ?? defaultTopFileCount,\n includeTests: cli.includeTests ?? config.includeTests ?? false,\n failOnError: cli.failOnError ?? config.failOnError ?? false,\n json: cli.json ?? false,\n };\n}\n\n/**\n * Loads the configuration file. An explicit path must exist; otherwise the nearest\n * `code-gauge.config.json` is searched by walking up from the target directory.\n */\nexport async function loadConfig(explicitPath: string | undefined, targetDirectory: string): Promise<LoadedConfig> {\n const configFile = explicitPath ?? (await findNearestConfig(targetDirectory));\n if (!configFile) {\n return { config: {}, directory: targetDirectory };\n }\n\n let content;\n try {\n content = await readFile(configFile, 'utf8');\n } catch (error) {\n if (explicitPath) {\n throw new Error(`Cannot read config file \"${configFile}\": ${getErrorMessage(error)}`);\n }\n return { config: {}, directory: targetDirectory };\n }\n\n let parsed: unknown;\n try {\n parsed = JSON.parse(content);\n } catch (error) {\n throw new Error(`Invalid JSON in config file \"${configFile}\": ${getErrorMessage(error)}`);\n }\n\n return { config: validateConfig(parsed, configFile), directory: path.dirname(path.resolve(configFile)) };\n}\n\nasync function findNearestConfig(targetDirectory: string): Promise<string | undefined> {\n let currentDirectory = targetDirectory;\n while (true) {\n const configFile = path.join(currentDirectory, configFileName);\n if (await fileExists(configFile)) {\n return configFile;\n }\n\n const parentDirectory = path.dirname(currentDirectory);\n if (parentDirectory === currentDirectory) {\n return undefined;\n }\n currentDirectory = parentDirectory;\n }\n}\n\nasync function fileExists(file: string): Promise<boolean> {\n try {\n const fileStat = await stat(file);\n return fileStat.isFile();\n } catch {\n return false;\n }\n}\n\nfunction validateConfig(value: unknown, configFile: string): CodeGaugeConfig {\n if (!isRecord(value)) {\n throw new Error(`Config file \"${configFile}\" must contain a JSON object.`);\n }\n\n const knownKeys = new Set(['duplication', 'rank', 'thresholds', 'exclude', 'includeTests', 'failOnError']);\n for (const key of Object.keys(value)) {\n if (!knownKeys.has(key)) {\n throw new Error(`Config file \"${configFile}\": unknown setting \"${key}\" (expected ${[...knownKeys].join(', ')}).`);\n }\n }\n const config: CodeGaugeConfig = {};\n\n if (value.duplication !== undefined) {\n config.duplication = validateDuplicationObject(value.duplication, configFile);\n }\n\n if (value.rank !== undefined) {\n config.rank = validateRankObject(value.rank, configFile);\n }\n\n if (value.thresholds !== undefined) {\n config.thresholds = validateThresholdsObject(value.thresholds, configFile);\n }\n\n if (value.exclude !== undefined) {\n config.exclude = validateExcludePatterns(value.exclude, configFile);\n }\n\n for (const key of ['includeTests', 'failOnError'] as const) {\n if (value[key] !== undefined) {\n config[key] = requireBoolean(value[key], key, configFile);\n }\n }\n\n return config;\n}\n\nfunction validateExcludePatterns(value: unknown, configFile: string): string[] {\n if (!Array.isArray(value) || !value.every((pattern) => typeof pattern === 'string' && pattern !== '')) {\n throw new TypeError(`Config file \"${configFile}\": \"exclude\" must be an array of non-empty glob patterns.`);\n }\n return value as string[];\n}\n\nfunction validateRankObject(value: unknown, configFile: string): { top?: number } {\n if (!isRecord(value)) {\n throw new Error(`Config file \"${configFile}\": \"rank\" must be an object.`);\n }\n const rank: { top?: number } = {};\n for (const [key, setting] of Object.entries(value)) {\n if (key !== 'top') {\n throw new Error(`Config file \"${configFile}\": unknown setting \"${key}\" in \"rank\" (expected top).`);\n }\n rank.top = requirePositiveInteger(setting, 'rank.top', configFile);\n }\n return rank;\n}\n\nfunction validateThresholdsObject(value: unknown, configFile: string): ThresholdsConfig {\n const { languages, ...limits } = requireRecord(value, 'thresholds', configFile);\n return {\n limits: validateLimits(limits, 'thresholds', ['languages'], configFile),\n languages: Object.fromEntries(\n Object.entries(languages === undefined ? {} : requireRecord(languages, 'thresholds.languages', configFile)).map(\n ([language, overrides]) => {\n if (!supportedLanguages.includes(language)) {\n throw new Error(\n `Config file \"${configFile}\": unknown language \"${language}\" in \"thresholds.languages\" (expected ${supportedLanguages.join(', ')}).`\n );\n }\n const settingName = `thresholds.languages.${language}`;\n return [\n language,\n validateLimits(requireRecord(overrides, settingName, configFile), settingName, [], configFile),\n ];\n }\n )\n ),\n };\n}\n\n/** Limits as written in the config file, where `null` disables one. */\nfunction validateLimits(\n value: Record<string, unknown>,\n settingName: string,\n otherKeys: string[],\n configFile: string\n): Limits {\n const knownKeys = thresholds.map(({ key }) => key);\n return Object.fromEntries(\n Object.entries(value).map(([key, limit]) => {\n if (!knownKeys.includes(key)) {\n throw new Error(\n `Config file \"${configFile}\": unknown setting \"${key}\" in \"${settingName}\" (expected ${[...knownKeys, ...otherKeys].join(', ')}).`\n );\n }\n if (limit !== null && (typeof limit !== 'number' || !Number.isFinite(limit) || limit < 0)) {\n throw new Error(`Config file \"${configFile}\": \"${settingName}.${key}\" must be a non-negative number or null.`);\n }\n return [key, limit ?? Infinity];\n })\n );\n}\n\nfunction requireRecord(value: unknown, settingName: string, configFile: string): Record<string, unknown> {\n if (!isRecord(value)) {\n throw new Error(`Config file \"${configFile}\": \"${settingName}\" must be an object.`);\n }\n return value;\n}\n\nfunction validateDuplicationObject(value: unknown, configFile: string): DuplicationOptions {\n if (!isRecord(value)) {\n throw new Error(`Config file \"${configFile}\": \"duplication\" must be an object.`);\n }\n const duplication: DuplicationOptions = {};\n for (const [key, setting] of Object.entries(value)) {\n if (key === 'minTokens') {\n duplication.minTokens = requirePositiveInteger(setting, 'duplication.minTokens', configFile);\n } else if (key === 'maxGapTokens') {\n // 0 is meaningful: it disables gapped-clone merging.\n duplication.maxGapTokens = requireNonNegativeInteger(setting, 'duplication.maxGapTokens', configFile);\n } else if (key === 'minSimilarityPercent') {\n const parsed = requirePositiveInteger(setting, 'duplication.minSimilarityPercent', configFile);\n if (parsed > 100) {\n throw new Error(`Config file \"${configFile}\": \"duplication.minSimilarityPercent\" must be between 1 and 100.`);\n }\n duplication.minSimilarityPercent = parsed;\n } else {\n throw new Error(\n `Config file \"${configFile}\": unknown setting \"${key}\" in \"duplication\" (expected minTokens, maxGapTokens, or minSimilarityPercent).`\n );\n }\n }\n return duplication;\n}\n\nfunction requireNonNegativeInteger(value: unknown, key: string, configFile: string): number {\n return requireNumber(value, key, configFile, Number.isSafeInteger, 'a non-negative integer');\n}\n\nfunction requirePositiveInteger(value: unknown, key: string, configFile: string): number {\n const parsed = requireNumber(value, key, configFile, Number.isSafeInteger, 'a positive integer');\n if (parsed < 1) {\n throw new Error(`Config file \"${configFile}\": \"${key}\" must be a positive integer.`);\n }\n return parsed;\n}\n\n/** Shared core of the numeric validators: the right kind of number, and never negative. */\nfunction requireNumber(\n value: unknown,\n key: string,\n configFile: string,\n isValidKind: (value: unknown) => boolean,\n description: string\n): number {\n if (typeof value !== 'number' || !isValidKind(value) || value < 0) {\n throw new Error(`Config file \"${configFile}\": \"${key}\" must be ${description}.`);\n }\n return value;\n}\n\nfunction requireBoolean(value: unknown, key: string, configFile: string): boolean {\n if (typeof value !== 'boolean') {\n throw new TypeError(`Config file \"${configFile}\": \"${key}\" must be a boolean.`);\n }\n return value;\n}\n"],"mappings":"qTASA,MAAa,EAAiB,yBAgD9B,SAAgB,EAAe,EAAiB,CAAE,SAAQ,aAA4C,CACpG,MAAO,CACL,YAAa,CACX,UAAW,EAAI,sBAAwB,EAAO,aAAa,WAAa,EAA0B,UAClG,aACE,EAAI,yBAA2B,EAAO,aAAa,cAAgB,EAA0B,aAC/F,qBACE,EAAI,iCACJ,EAAO,aAAa,sBACpB,EAA0B,oBAC9B,EACA,QAAS,CAAE,SAAU,EAAO,SAAW,CAAC,EAAG,KAAM,CAAU,EAC3D,IAAK,EAAI,KAAO,EAAO,MAAM,KAAA,GAC7B,aAAc,EAAI,cAAgB,EAAO,cAAgB,GACzD,YAAa,EAAI,aAAe,EAAO,aAAe,GACtD,KAAM,EAAI,MAAQ,EACpB,CACF,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AAQ,CAAK,EAC/C,GAAI,IAAQ,YACV,EAAY,UAAY,EAAuB,EAAS,wBAAyB,CAAU,OACtF,GAAI,IAAQ,eAEjB,EAAY,aAAe,EAA0B,EAAS,2BAA4B,CAAU,OAC/F,GAAI,IAAQ,uBAAwB,CACzC,IAAM,EAAS,EAAuB,EAAS,mCAAoC,CAAU,EAC7F,GAAI,EAAS,IACX,MAAU,MAAM,gBAAgB,EAAW,iEAAiE,EAE9G,EAAY,qBAAuB,CACrC,MACE,MAAU,MACR,gBAAgB,EAAW,sBAAsB,EAAI,gFACvD,EAGJ,OAAO,CACT,CAEA,SAAS,EAA0B,EAAgB,EAAa,EAA4B,CAC1F,OAAO,EAAc,EAAO,EAAK,EAAY,OAAO,cAAe,wBAAwB,CAC7F,CAEA,SAAS,EAAuB,EAAgB,EAAa,EAA4B,CACvF,IAAM,EAAS,EAAc,EAAO,EAAK,EAAY,OAAO,cAAe,oBAAoB,EAC/F,GAAI,EAAS,EACX,MAAU,MAAM,gBAAgB,EAAW,MAAM,EAAI,8BAA8B,EAErF,OAAO,CACT,CAGA,SAAS,EACP,EACA,EACA,EACA,EACA,EACQ,CACR,GAAI,OAAO,GAAU,UAAY,CAAC,EAAY,CAAK,GAAK,EAAQ,EAC9D,MAAU,MAAM,gBAAgB,EAAW,MAAM,EAAI,YAAY,EAAY,EAAE,EAEjF,OAAO,CACT,CAEA,SAAS,EAAe,EAAgB,EAAa,EAA6B,CAChF,GAAI,OAAO,GAAU,UACnB,MAAU,UAAU,gBAAgB,EAAW,MAAM,EAAI,qBAAqB,EAEhF,OAAO,CACT"}
1
+ {"version":3,"file":"cliConfig.js","names":[],"sources":["../src/cliConfig.ts"],"sourcesContent":["import { readFile, stat } from 'node:fs/promises';\nimport path from 'node:path';\nimport { getErrorMessage, isRecord } from '@willbooster/shared-lib';\nimport { defaultDuplicationOptions } from './duplication.js';\nimport type { ExcludePatterns } from './exclusion.js';\nimport { supportedLanguages } from './languages.js';\nimport {\n levels,\n thresholds,\n type Level,\n type LevelThresholdsConfig,\n type Limits,\n type ThresholdsConfig,\n} from './thresholds.js';\nimport type { DuplicationOptions } from './types.js';\n\nexport const configFileName = 'code-gauge.config.json';\nexport const defaultTopFileCount = 10;\n\n/** Shape of the JSON configuration file. All fields are optional and fall back to the built-in defaults. */\nexport interface CodeGaugeConfig {\n /** Duplication detection settings applied to every measured file. */\n duplication?: DuplicationOptions;\n /** Refactoring-candidate ranking settings. */\n rank?: { top?: number };\n /** Limits of `code-gauge check`. */\n thresholds?: ThresholdsConfig;\n /** Glob patterns, relative to the config file's directory, of files left out of every command. */\n exclude?: string[];\n includeTests?: boolean;\n failOnError?: boolean;\n}\n\n/** A parsed configuration file and the directory its relative settings resolve against. */\nexport interface LoadedConfig {\n config: CodeGaugeConfig;\n /** The config file's directory; the search start directory when no config file was found. */\n directory: string;\n}\n\n/** Raw command-line options; every field is undefined unless the user passed the flag. */\nexport interface CliOptions {\n config?: string;\n top?: number;\n duplicationMinTokens?: number;\n duplicationMaxGapTokens?: number;\n duplicationMinSimilarityPercent?: number;\n includeTests?: boolean;\n failOnError?: boolean;\n json?: boolean;\n}\n\n/** Options after merging command-line flags, the configuration file, and the built-in defaults. */\nexport interface ResolvedOptions {\n duplication: Required<DuplicationOptions>;\n exclude: ExcludePatterns;\n /** Number of top-ranked files to report. */\n top: number;\n includeTests: boolean;\n failOnError: boolean;\n json: boolean;\n}\n\n/** Resolves options with precedence command-line flags > configuration file > built-in defaults. */\nexport function resolveOptions(cli: CliOptions, { config, directory }: LoadedConfig): ResolvedOptions {\n return {\n duplication: {\n minTokens: cli.duplicationMinTokens ?? config.duplication?.minTokens ?? defaultDuplicationOptions.minTokens,\n maxGapTokens:\n cli.duplicationMaxGapTokens ?? config.duplication?.maxGapTokens ?? defaultDuplicationOptions.maxGapTokens,\n minSimilarityPercent:\n cli.duplicationMinSimilarityPercent ??\n config.duplication?.minSimilarityPercent ??\n defaultDuplicationOptions.minSimilarityPercent,\n },\n exclude: { patterns: config.exclude ?? [], root: directory },\n top: cli.top ?? config.rank?.top ?? defaultTopFileCount,\n includeTests: cli.includeTests ?? config.includeTests ?? false,\n failOnError: cli.failOnError ?? config.failOnError ?? false,\n json: cli.json ?? false,\n };\n}\n\n/**\n * Loads the configuration file. An explicit path must exist; otherwise the nearest\n * `code-gauge.config.json` is searched by walking up from the target directory.\n */\nexport async function loadConfig(explicitPath: string | undefined, targetDirectory: string): Promise<LoadedConfig> {\n const configFile = explicitPath ?? (await findNearestConfig(targetDirectory));\n if (!configFile) {\n return { config: {}, directory: targetDirectory };\n }\n\n let content;\n try {\n content = await readFile(configFile, 'utf8');\n } catch (error) {\n if (explicitPath) {\n throw new Error(`Cannot read config file \"${configFile}\": ${getErrorMessage(error)}`);\n }\n return { config: {}, directory: targetDirectory };\n }\n\n let parsed: unknown;\n try {\n parsed = JSON.parse(content);\n } catch (error) {\n throw new Error(`Invalid JSON in config file \"${configFile}\": ${getErrorMessage(error)}`);\n }\n\n return { config: validateConfig(parsed, configFile), directory: path.dirname(path.resolve(configFile)) };\n}\n\nasync function findNearestConfig(targetDirectory: string): Promise<string | undefined> {\n let currentDirectory = targetDirectory;\n while (true) {\n const configFile = path.join(currentDirectory, configFileName);\n if (await fileExists(configFile)) {\n return configFile;\n }\n\n const parentDirectory = path.dirname(currentDirectory);\n if (parentDirectory === currentDirectory) {\n return undefined;\n }\n currentDirectory = parentDirectory;\n }\n}\n\nasync function fileExists(file: string): Promise<boolean> {\n try {\n const fileStat = await stat(file);\n return fileStat.isFile();\n } catch {\n return false;\n }\n}\n\nfunction validateConfig(value: unknown, configFile: string): CodeGaugeConfig {\n if (!isRecord(value)) {\n throw new Error(`Config file \"${configFile}\" must contain a JSON object.`);\n }\n\n const knownKeys = new Set(['duplication', 'rank', 'thresholds', 'exclude', 'includeTests', 'failOnError']);\n for (const key of Object.keys(value)) {\n if (!knownKeys.has(key)) {\n throw new Error(`Config file \"${configFile}\": unknown setting \"${key}\" (expected ${[...knownKeys].join(', ')}).`);\n }\n }\n const config: CodeGaugeConfig = {};\n\n if (value.duplication !== undefined) {\n config.duplication = validateDuplicationObject(value.duplication, configFile);\n }\n\n if (value.rank !== undefined) {\n config.rank = validateRankObject(value.rank, configFile);\n }\n\n if (value.thresholds !== undefined) {\n config.thresholds = validateThresholdsObject(value.thresholds, configFile);\n }\n\n if (value.exclude !== undefined) {\n config.exclude = validateExcludePatterns(value.exclude, configFile);\n }\n\n for (const key of ['includeTests', 'failOnError'] as const) {\n if (value[key] !== undefined) {\n config[key] = requireBoolean(value[key], key, configFile);\n }\n }\n\n return config;\n}\n\nfunction validateExcludePatterns(value: unknown, configFile: string): string[] {\n if (!Array.isArray(value) || !value.every((pattern) => typeof pattern === 'string' && pattern !== '')) {\n throw new TypeError(`Config file \"${configFile}\": \"exclude\" must be an array of non-empty glob patterns.`);\n }\n return value as string[];\n}\n\nfunction validateRankObject(value: unknown, configFile: string): { top?: number } {\n if (!isRecord(value)) {\n throw new Error(`Config file \"${configFile}\": \"rank\" must be an object.`);\n }\n const rank: { top?: number } = {};\n for (const [key, setting] of Object.entries(value)) {\n if (key !== 'top') {\n throw new Error(`Config file \"${configFile}\": unknown setting \"${key}\" in \"rank\" (expected top).`);\n }\n rank.top = requirePositiveInteger(setting, 'rank.top', configFile);\n }\n return rank;\n}\n\nfunction validateThresholdsObject(value: unknown, configFile: string): ThresholdsConfig {\n return Object.fromEntries(\n Object.entries(requireRecord(value, 'thresholds', configFile)).map(([level, levelThresholds]) => {\n if (!levels.includes(level as Level)) {\n throw new Error(\n `Config file \"${configFile}\": unknown setting \"${level}\" in \"thresholds\" (expected ${levels.join(', ')}).`\n );\n }\n return [level, validateLevelThresholds(levelThresholds, `thresholds.${level}`, configFile)];\n })\n );\n}\n\nfunction validateLevelThresholds(value: unknown, settingName: string, configFile: string): LevelThresholdsConfig {\n const { languages, ...limits } = requireRecord(value, settingName, configFile);\n const languagesName = `${settingName}.languages`;\n return {\n limits: validateLimits(limits, settingName, ['languages'], configFile),\n languages: Object.fromEntries(\n Object.entries(languages === undefined ? {} : requireRecord(languages, languagesName, configFile)).map(\n ([language, overrides]) => {\n if (!supportedLanguages.includes(language)) {\n throw new Error(\n `Config file \"${configFile}\": unknown language \"${language}\" in \"${languagesName}\" (expected ${supportedLanguages.join(', ')}).`\n );\n }\n const languageName = `${languagesName}.${language}`;\n return [\n language,\n validateLimits(requireRecord(overrides, languageName, configFile), languageName, [], configFile),\n ];\n }\n )\n ),\n };\n}\n\n/** Limits as written in the config file, where `null` disables one. */\nfunction validateLimits(\n value: Record<string, unknown>,\n settingName: string,\n otherKeys: string[],\n configFile: string\n): Limits {\n const knownKeys = thresholds.map(({ key }) => key);\n return Object.fromEntries(\n Object.entries(value).map(([key, limit]) => {\n if (!knownKeys.includes(key)) {\n throw new Error(\n `Config file \"${configFile}\": unknown setting \"${key}\" in \"${settingName}\" (expected ${[...knownKeys, ...otherKeys].join(', ')}).`\n );\n }\n if (limit !== null && (typeof limit !== 'number' || !Number.isFinite(limit) || limit < 0)) {\n throw new Error(`Config file \"${configFile}\": \"${settingName}.${key}\" must be a non-negative number or null.`);\n }\n return [key, limit ?? Infinity];\n })\n );\n}\n\nfunction requireRecord(value: unknown, settingName: string, configFile: string): Record<string, unknown> {\n if (!isRecord(value)) {\n throw new Error(`Config file \"${configFile}\": \"${settingName}\" must be an object.`);\n }\n return value;\n}\n\nfunction validateDuplicationObject(value: unknown, configFile: string): DuplicationOptions {\n if (!isRecord(value)) {\n throw new Error(`Config file \"${configFile}\": \"duplication\" must be an object.`);\n }\n const duplication: DuplicationOptions = {};\n for (const [key, setting] of Object.entries(value)) {\n if (key === 'minTokens') {\n duplication.minTokens = requirePositiveInteger(setting, 'duplication.minTokens', configFile);\n } else if (key === 'maxGapTokens') {\n // 0 is meaningful: it disables gapped-clone merging.\n duplication.maxGapTokens = requireNonNegativeInteger(setting, 'duplication.maxGapTokens', configFile);\n } else if (key === 'minSimilarityPercent') {\n const parsed = requirePositiveInteger(setting, 'duplication.minSimilarityPercent', configFile);\n if (parsed > 100) {\n throw new Error(`Config file \"${configFile}\": \"duplication.minSimilarityPercent\" must be between 1 and 100.`);\n }\n duplication.minSimilarityPercent = parsed;\n } else {\n throw new Error(\n `Config file \"${configFile}\": unknown setting \"${key}\" in \"duplication\" (expected minTokens, maxGapTokens, or minSimilarityPercent).`\n );\n }\n }\n return duplication;\n}\n\nfunction requireNonNegativeInteger(value: unknown, key: string, configFile: string): number {\n return requireNumber(value, key, configFile, Number.isSafeInteger, 'a non-negative integer');\n}\n\nfunction requirePositiveInteger(value: unknown, key: string, configFile: string): number {\n const parsed = requireNumber(value, key, configFile, Number.isSafeInteger, 'a positive integer');\n if (parsed < 1) {\n throw new Error(`Config file \"${configFile}\": \"${key}\" must be a positive integer.`);\n }\n return parsed;\n}\n\n/** Shared core of the numeric validators: the right kind of number, and never negative. */\nfunction requireNumber(\n value: unknown,\n key: string,\n configFile: string,\n isValidKind: (value: unknown) => boolean,\n description: string\n): number {\n if (typeof value !== 'number' || !isValidKind(value) || value < 0) {\n throw new Error(`Config file \"${configFile}\": \"${key}\" must be ${description}.`);\n }\n return value;\n}\n\nfunction requireBoolean(value: unknown, key: string, configFile: string): boolean {\n if (typeof value !== 'boolean') {\n throw new TypeError(`Config file \"${configFile}\": \"${key}\" must be a boolean.`);\n }\n return value;\n}\n"],"mappings":"iUAgBA,MAAa,EAAiB,yBAgD9B,SAAgB,EAAe,EAAiB,CAAE,SAAQ,aAA4C,CACpG,MAAO,CACL,YAAa,CACX,UAAW,EAAI,sBAAwB,EAAO,aAAa,WAAa,EAA0B,UAClG,aACE,EAAI,yBAA2B,EAAO,aAAa,cAAgB,EAA0B,aAC/F,qBACE,EAAI,iCACJ,EAAO,aAAa,sBACpB,EAA0B,oBAC9B,EACA,QAAS,CAAE,SAAU,EAAO,SAAW,CAAC,EAAG,KAAM,CAAU,EAC3D,IAAK,EAAI,KAAO,EAAO,MAAM,KAAA,GAC7B,aAAc,EAAI,cAAgB,EAAO,cAAgB,GAC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Q,EAC9D,MAAU,MAAM,gBAAgB,EAAW,MAAM,EAAI,YAAY,EAAY,EAAE,EAEjF,OAAO,CACT,CAEA,SAAS,EAAe,EAAgB,EAAa,EAA6B,CAChF,GAAI,OAAO,GAAU,UACnB,MAAU,UAAU,gBAAgB,EAAW,MAAM,EAAI,qBAAqB,EAEhF,OAAO,CACT"}
@@ -1,2 +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;
1
+ "use strict";const e=require("./thresholds.cjs"),t=[`file`,`function`,`duplication`],n=new Set(e.functionThresholds.filter(({includesNestedFunctions:e})=>e).map(t=>e.metricNameOf(t)));function r(t,n,r){let s=f(n,new Set(t.map(({file:e})=>e))),u=[],d=0;for(let n of t){let{file:t,metrics:i,hunks:f}=n,m=r(i.language),h=f?.length===0?[]:l(e.fileThresholds,i,m);h.length>0&&u.push(c({file:t,startLine:1,endLine:i.lines.total},`file`,h));let g=a(n);d+=g.length;let _=g.map(t=>({fn:t,exceeded:l(e.functionThresholds,t,m)})).filter(({exceeded:e})=>e.length>0);for(let{fn:e,exceeded:n}of _){let r=n.filter(t=>!o(t,e,_));if(r.length>0){let{startLine:n,endLine:i}=e;u.push({...c({file:t,startLine:n,endLine:i},`function`,r),name:e.name??`<anonymous>`})}}u.push(...p(t,i,s.get(t)??[],f,m))}return{violations:u.toSorted(i),checkedFunctionCount:d}}function i(n,r){return e.levels.indexOf(r.level)-e.levels.indexOf(n.level)||g(n.file,r.file)||n.startLine-r.startLine||t.indexOf(n.kind)-t.indexOf(r.kind)||n.endLine-r.endLine}function a({metrics:e,hunks:t}){let n=e.language===`python`;return t?e.functions.filter(e=>t.some(t=>d(t,e.startLine,e.endLine,n))):e.functions}function o(e,t,r){return n.has(e.metric)?r.some(n=>n.fn!==t&&s(n.fn,t)&&n.exceeded.some(({metric:t})=>t===e.metric)):!1}function s(e,t){let n=e.startLine<t.startLine||e.startLine===t.startLine&&e.startColumn<=t.startColumn,r=e.endLine>t.endLine||e.endLine===t.endLine&&e.endColumn>=t.endColumn;return n&&r}function c(e,t,n){return{kind:t,level:n.some(e=>e.level===`error`)?`error`:`warning`,...e,exceeded:n}}function l(e,t,n){return e.flatMap(e=>u(e,t,n,(e,t)=>e>t))}function u(t,n,r,i){let a=t.measure(n),o=e.levels.findLast(e=>i(a,r[e][t.key]));return o?[{metric:e.metricNameOf(t),value:a,level:o,limit:r[o][t.key]}]:[]}function d(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 f(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 p(t,n,r,i,a){let o=t=>u(e.duplicationThreshold,t,a,(e,t)=>e>=t),s=[...n.duplication.duplicateBlockGroups.map(e=>e.map(e=>({...e,file:t}))),...r.map(e=>e.occurrences)],l=e=>e.file===t&&o(e).length>0&&(!i||i.some(t=>t.headCount>0&&d(t,e.startLine,e.endLine))),f=/* @__PURE__ */ new Map;for(let e of s)for(let t of e.filter(e=>l(e)))f.set(t,e);return m([...f.keys()]).map(({merged:e,sources:t})=>({...c(e,`duplication`,o(e)),partners:m(t.flatMap(e=>f.get(e)??[])).map(e=>e.merged).filter(t=>!h(t,e))}))}function m(e){let t=[],n=e.toSorted((e,t)=>g(e.file,t.file)||e.startLine-t.startLine);for(let e of n){let n=t.at(-1);if(n&&h(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 h(e,t){return e.file===t.file&&e.startLine<=t.endLine&&t.startLine<=e.endLine}function g(e,t){return e<t?-1:+(e>t)}exports.checkThresholds=r;
2
2
  //# sourceMappingURL=thresholdCheck.cjs.map