From d1c568030290ef8644a5888aa6f54d6679faee10 Mon Sep 17 00:00:00 2001 From: Stafford Williams Date: Tue, 10 Nov 2026 15:37:06 +1100 Subject: [PATCH] feat: read check options from config --- README.md | 171 +++++++++++++++++++++-- src/checks/comments.ts | 24 ++-- src/checks/complexity.ts | 19 ++- src/checks/configFailure.ts | 20 +++ src/checks/external.ts | 69 ++++++---- src/checks/externalConfig.test.ts | 204 +++++++++++++++++++++++++++ src/checks/externalConfig.ts | 30 ++++ src/checks/forbidden-strings.ts | 8 +- src/checks/hardcoded-colors.ts | 12 +- src/checks/invalidConfig.test.ts | 221 ++++++++++++++++++++++++++++++ src/checks/nativeConfig.test.ts | 219 +++++++++++++++++++++++++++++ src/checks/registry.ts | 15 +- src/commands/registerChecks.ts | 3 + src/index.ts | 2 +- src/shared/config.ts | 61 +++++++-- src/shared/configSchema.ts | 69 ++++++++++ 16 files changed, 1075 insertions(+), 72 deletions(-) create mode 100644 src/checks/configFailure.ts create mode 100644 src/checks/externalConfig.test.ts create mode 100644 src/checks/externalConfig.ts create mode 100644 src/checks/invalidConfig.test.ts create mode 100644 src/checks/nativeConfig.test.ts create mode 100644 src/shared/configSchema.ts diff --git a/README.md b/README.md index 38e462b..ba5472e 100644 --- a/README.md +++ b/README.md @@ -146,13 +146,13 @@ Because checks are named for their function, **on failure** an external check pr **Passing extra arguments through.** When you run an external check directly, anything after `--` is forwarded as literal argv entries to the underlying tool, so you can tweak an invocation without ejecting it: `verifyx circular-deps -- src/index.ts` asks skott to start at that file, while `verifyx lint -- --quiet` passes `--quiet` to oxlint. With no entrypoint, skott scans the current project, so `verifyx init` scaffolds the cross-platform default `verifyx circular-deps` without a shell glob. -Each external check is configured through its **tool's own config file**, exactly as you would use that tool standalone: +Each external check is configured through its **tool's own config file**, exactly as you would use that tool standalone. `unused-code`, `duplicate-code` and `circular-deps` also read a few named settings from your [verify config](#configuration), described under [External check settings](#external-check-settings) below. - `lint`: [`.oxlintrc.json`](https://oxc.rs/docs/guide/usage/linter.html) - `format`: [oxfmt configuration](https://oxc.rs) - `check-types`: your [`tsconfig.json`](https://www.typescriptlang.org/tsconfig) - `unused-code`: [`knip.json`](https://knip.dev/reference/configuration) -- `circular-deps`: [skott options](https://github.com/antoine-coulon/skott) +- `circular-deps`: skott has no config file, so its settings live in the verify config under `circularDeps` - `duplicate-code`: [`.jscpd.json` or `package.json#jscpd`](https://github.com/kucherenko/jscpd/tree/master/apps/jscpd#config) ### `--max-warnings` @@ -167,6 +167,38 @@ verifyx unused-code --max-warnings 5 verifyx duplicate-code --max-warnings 10 ``` +The budget can live in your [verify config](#configuration) instead, as `unusedCode.maxWarnings` and `duplicateCode.maxWarnings`. `--max-warnings` on the command line wins over the config value. + +### External check settings + +`unused-code`, `duplicate-code` and `circular-deps` read named settings from your [verify config](#configuration). verifyx translates each one into the tool's own flags; there is no raw argument list in the config. + +```jsonc +{ + "unusedCode": { "maxWarnings": 226 }, + "duplicateCode": { + "maxWarnings": 137, + "paths": ["app", "features", "scripts"], + "ignore": ["**/*.test.*", "**/generated/**"], + }, + "circularDeps": { + "extensions": [".ts", ".tsx"], + "ignore": ["**/*.test.*", "features/logging/offline-provider.ts"], + "ignoreTypeImports": true, + }, +} +``` + +- `unusedCode.maxWarnings`: the findings budget, passed to knip as `--max-issues`. Everything else stays in `knip.json`. +- `duplicateCode.maxWarnings`: the budget of distinct duplicated regions. +- `duplicateCode.paths`: the directories jscpd scans. Replaces the default `src`. +- `duplicateCode.ignore`: globs jscpd skips, one `--ignore` each. Replaces the default `**/*.test.*`, so list it again if you still want test files skipped. jscpd splits an ignore value on commas, so a brace glob such as `**/*.{test,spec}.*` does not work; list each glob separately. +- `circularDeps.extensions`: the file extensions skott follows (`--fileExtensions`). Defaults to skott's own list. +- `circularDeps.ignore`: globs skott leaves out of the graph, one `--ignorePattern` each. +- `circularDeps.ignoreTypeImports`: when `true`, `import type` statements don't count as dependencies (`--no-trackTypeOnlyDependencies`). + +Args after `--` are still appended after the flags built from config. `lint`, `format` and `check-types` have no verify-config settings; their tool's config file covers everything. + ### `complexity` ```sh @@ -177,6 +209,18 @@ verifyx complexity --threshold 50 "src/**/*.ts" - `--threshold `: fail when any file's minimum maintainability index is below `n`. - `--ignore `: exclude files (repeatable; appended to the default `**/*test.ts*`). +Each of these can live in your [verify config](#configuration) instead, under `complexity`: `threshold`, `pattern` and `ignore`. A value given on the command line wins over the config value. + +```jsonc +{ + "complexity": { + "threshold": 50, + "pattern": "{app,features}/**/*.{ts,tsx}", + "ignore": ["features/graphql/generated/**"], + }, +} +``` + It parses your `.ts`/`.tsx` sources with the TypeScript compiler API and, for every function, computes three metrics: **cyclomatic complexity** (independent paths through the code), **Halstead volume** (a size measure derived from the operators and operands used), and **SLOC** (source lines of code, excluding blanks and comments). It then combines them into a single **maintainability index (MI)**, a 0–100 score where lower means harder to maintain: ``` @@ -200,11 +244,25 @@ Capable coding models (Opus 4.8 very much included) love to narrate their work: - `--pushback`: reframe the failure message as back-pressure aimed at an AI agent (see below). - `--warn`: report the long-block violations without failing the run. - `--block-new-comments`: also fail on any comment on a changed line (vs `HEAD` locally, the PR base in CI; see below). -- `--ignore `: exclude files (repeatable; the `--block-new-comments` gate also reads `comments.ignore` from your [verify config](#configuration)). +- `--ignore `: exclude files (repeatable; appended to the default `**/*test.ts*`). Applies to both the long-block check and the `--block-new-comments` gate. + +Each of these can live in your [verify config](#configuration) instead, under `comments`: `maxLines`, `pattern`, `ignore`, `pushback`, `warn` and `blockNewComments`. A value given on the command line wins over the config value, and `--no-pushback`, `--no-warn` and `--no-block-new-comments` turn off a setting the config turned on. + +```jsonc +{ + "comments": { + "maxLines": 10, + "ignore": ["features/graphql/generated/**"], + "blockNewComments": true, + }, +} +``` + +`verifyx all` runs this check with pushback on unless the config sets `"pushback": false`. **`--pushback` is the clever bit.** An AI agent that hits a failing check will often take the path of least resistance and just delete or weaken the check to make the run pass. So rather than a dry error, the pushback message tells the agent that the _only_ sanctioned way to keep the comment is to prefix it with `context:`, and that doing so **pages a human to approve it**. Confronted with a real person's time on the line, the agent tends to reconsider and remove the low-value comment instead of gaming the gate. It is a small piece of prompt-engineering baked into a lint failure, and in practice it stops agents silencing the check far more reliably than a plain error does. -If you want to go further and block **new** comments outright, override the `verify:comments` script and add `--block-new-comments`. That turns on a stricter, diff-based gate on top of the long-block check: any comment sitting on a changed line fails, whether you added or merely edited it. Machine directives (`eslint-disable`, `@ts-expect-error`, and friends) stay exempt, as does anything marked `context:`. +If you want to go further and block **new** comments outright, set `comments.blockNewComments` in your verify config (or pass `--block-new-comments`). That turns on a stricter, diff-based gate on top of the long-block check: any comment sitting on a changed line fails, whether you added or merely edited it. Machine directives (`eslint-disable`, `@ts-expect-error`, and friends) stay exempt, as does anything marked `context:`. The "changed lines" are resolved per environment so the gate works the same locally and in CI. Locally it diffs the working tree against `HEAD` (your uncommitted changes). In CI (`CI` set) a clean checkout has nothing uncommitted, so it diffs against the **merge base with the PR base branch** instead, read from `GITHUB_BASE_REF` (GitHub Actions). Set `VERIFY_DIFF_BASE` to a ref to override the base explicitly; if no base can be resolved it falls back to `HEAD`. For CI, make sure the base branch is fetched (`actions/checkout` with `fetch-depth: 0`), or the merge base won't be found and the gate silently passes. @@ -311,23 +369,116 @@ verifyx eject circular-deps # verify:circular-deps → skott --displayMode=raw verifyx eject lint # verify:lint → oxlint . AND verify:lint:fix → oxlint --fix . ``` +The ejected command includes the flags built from your [verify config](#configuration) (`circularDeps`, and `duplicateCode.paths` / `duplicateCode.ignore`), so it scans the same files as before. A `maxWarnings` budget is not carried over, because an ejected script no longer runs through `verifyx`. + For a fixable check (`lint`, `format`) it writes both the base `verify:` (check-mode) and the `verify::fix` variant, which is exactly the [fix-locally / check-in-CI](#fix-locally-check-in-ci) pairing `verifyx` already understands — so an ejected check keeps auto-fixing locally and only checking in CI. Ejecting **overwrites** the existing `verify:` script (that's the point — it hands you the raw command to edit), and leaves every other script untouched. Only external checks can be ejected; native checks (`complexity`, `comments`, …) run in-process and have no shell command to hand over. ## Configuration -The **native** checks that take persistent settings read them from a `verify.config.json` file, or a `verify` key in `package.json` (the standalone file wins if both are present). Each option is documented alongside its check above; collected here for reference: +Built-in checks that take persistent settings read them from a `verify.config.json` file, or a `verify` key in `package.json` (the standalone file wins if both are present). Both `verifyx ` and `verifyx all` pick the settings up, so a check configured here needs no `verify:` script. ```jsonc +// verify.config.json { - "verify": { - "comments": { "ignore": ["**/*.generated.ts"] }, - "hardcodedColors": { "root": "src", "ignore": ["**/tokens.ts"] }, - "forbiddenStrings": [{ "file": "app.json", "paths": ["env.LOG_LEVEL"], "disallowed": "debug" }], + "complexity": { + "threshold": 50, + "pattern": "{app,features}/**/*.{ts,tsx}", + "ignore": ["features/graphql/generated/**"], + }, + "comments": { + "maxLines": 10, + "pattern": "{app,features}/**/*.{ts,tsx}", + "ignore": ["**/*.generated.ts"], + "pushback": true, + "warn": false, + "blockNewComments": true, + }, + "unusedCode": { "maxWarnings": 226 }, + "duplicateCode": { + "maxWarnings": 137, + "paths": ["app", "features", "scripts"], + "ignore": ["**/*.test.*", "**/generated/**"], }, + "circularDeps": { + "extensions": [".ts", ".tsx"], + "ignore": ["**/*.test.*", "features/logging/offline-provider.ts"], + "ignoreTypeImports": true, + }, + "hardcodedColors": { "root": "src", "ignore": ["**/tokens.ts"] }, + "forbiddenStrings": [{ "file": "app.json", "paths": ["env.LOG_LEVEL"], "disallowed": "debug" }], } ``` -**External** checks don't use this file; each is configured through its own tool's config (`.oxlintrc.json`, `tsconfig.json`, `knip.json`, and so on), listed under [Built-in checks](#built-in-checks). +In `package.json` the same object goes under a `verify` key. + +| Key | Type | Default | Equivalent flag | +| -------------------------------- | ---------- | ----------------------------- | ---------------------- | +| `complexity.threshold` | number | `50` | `--threshold ` | +| `complexity.pattern` | string | `{src,server,shared}/**/*.ts` | `[pattern]` argument | +| `complexity.ignore` | string[] | none | `--ignore ` | +| `comments.maxLines` | number | `2` | `--max-lines ` | +| `comments.pattern` | string | `{src,server,shared}/**/*.ts` | `[pattern]` argument | +| `comments.ignore` | string[] | none | `--ignore ` | +| `comments.pushback` | boolean | `false` (`true` under `all`) | `--pushback` | +| `comments.warn` | boolean | `false` | `--warn` | +| `comments.blockNewComments` | boolean | `false` | `--block-new-comments` | +| `unusedCode.maxWarnings` | number | none | `--max-warnings ` | +| `duplicateCode.maxWarnings` | number | none | `--max-warnings ` | +| `duplicateCode.paths` | string[] | `["src"]` | none (config only) | +| `duplicateCode.ignore` | string[] | `["**/*.test.*"]` | none (config only) | +| `circularDeps.extensions` | string[] | skott's default | none (config only) | +| `circularDeps.ignore` | string[] | none | none (config only) | +| `circularDeps.ignoreTypeImports` | boolean | `false` | none (config only) | +| `hardcodedColors.root` | string | `src` | `--root ` | +| `hardcodedColors.ignore` | string[] | none | `--ignore ` | +| `forbiddenStrings` | rule array | none | none (config only) | + +**Precedence** is command-line flag, then config, then the built-in default. A flag given on the command line replaces the config value for that option. Lists are replaced, not merged: passing any `--ignore` drops the whole config `ignore` list for that run. The `complexity` and `comments` ignore lists are always added on top of the built-in `**/*test.ts*`, while `duplicateCode.paths` and `duplicateCode.ignore` replace their defaults. For an external check, args after `--` are still appended to the command built from config. + +**A bad config fails the check.** A verify config that is not valid JSON, has a key that is not in the table above (there is no raw `args` key), or has a setting of the wrong type fails every check that reads the verify config, both as `verifyx ` and under `verifyx all`. Nothing falls back to defaults. The message names the file and the key: + +``` +complexity: invalid verify config +verify.config.json: unknown key "complexity.args" (allowed: threshold, pattern, ignore) +verify.config.json: "complexity.threshold" must be a number +``` + +For a config under the `verify` key of `package.json`, the file is `package.json` and the key is prefixed, as in `verify.complexity.threshold`. `lint`, `format`, `check-types` and `github-actions` read nothing from the verify config, so they still run. `verifyx eject` also refuses to write a command built from a bad config. With no verify config at all, every check uses its built-in defaults. + +**External** checks keep the rest of their configuration in their own tool's config (`.oxlintrc.json`, `tsconfig.json`, `knip.json`, and so on), listed under [Built-in checks](#built-in-checks). Only the settings above come from the verify config; `lint`, `format` and `check-types` read nothing from it. + +### Before and after + +Without the config, every option is a flag in a `verify:*` script, and the lines grow long: + +```jsonc +// package.json +{ + "scripts": { + "verify:circular-deps": "verifyx circular-deps -- --fileExtensions=.ts,.tsx --ignorePattern=**/*.test.* --ignorePattern=features/logging/offline-provider.ts --no-trackTypeOnlyDependencies", + "verify:duplicate-code": "jscpd --format typescript,tsx --exit-code 1 --ignore \"**/*.test.*\" --ignore \"**/generated/**\" -r consoleFull app features scripts", + "verify:unused-code": "verifyx unused-code --max-warnings 226", + }, +} +``` + +With the settings in `verify.config.json`, those scripts are no longer needed. `verifyx all` picks the settings up on its own, and if you keep a script it shrinks to `verifyx `: + +```jsonc +// verify.config.json +{ + "circularDeps": { + "extensions": [".ts", ".tsx"], + "ignore": ["**/*.test.*", "features/logging/offline-provider.ts"], + "ignoreTypeImports": true, + }, + "duplicateCode": { + "paths": ["app", "features", "scripts"], + "ignore": ["**/*.test.*", "**/generated/**"], + }, + "unusedCode": { "maxWarnings": 226 }, +} +``` ## CI/CD diff --git a/src/checks/comments.ts b/src/checks/comments.ts index 501d6b8..e977ce0 100644 --- a/src/checks/comments.ts +++ b/src/checks/comments.ts @@ -7,9 +7,10 @@ import { findLongCommentBlocks } from '../comments.ts' import { printCommentBlockReport } from '../report.ts' import { color } from '../shared/color.ts' import { scanFileComments } from '../shared/comment-scan.ts' -import { loadVerifyConfig } from '../shared/config.ts' +import { resolveList, type VerifyConfig } from '../shared/config.ts' import { parseDiffAddedLines } from '../shared/diff.ts' import { gitDiffAgainstBase } from '../shared/git.ts' +import { withVerifyConfig } from './configFailure.ts' import type { CheckResult } from './types.ts' const DEFAULT_MAX_COMMENT_BLOCK_LINES = 2 @@ -90,24 +91,31 @@ export type CommentsOptions = { /** * Native check: flag comment blocks longer than `maxLines` (JSDoc and `context:`-prefixed blocks exempt). * With `blockNewComments`, additionally fail on any comment on a line changed against HEAD. + * Each option resolves as the given value, then `comments` in the verify config, then the built-in default. */ export function runComments(opts: CommentsOptions = {}): CheckResult { - const maxLines = opts.maxLines ?? DEFAULT_MAX_COMMENT_BLOCK_LINES - const pattern = opts.pattern ?? DEFAULT_PATTERN - const files = findSourceFiles(resolvePattern(pattern), [...DEFAULT_IGNORE, ...(opts.ignore ?? [])]) + return withVerifyConfig('comments', ({ comments }) => checkComments(opts, comments)) +} + +function checkComments(opts: CommentsOptions, config: NonNullable = {}): CheckResult { + const maxLines = opts.maxLines ?? config.maxLines ?? DEFAULT_MAX_COMMENT_BLOCK_LINES + const pattern = opts.pattern ?? config.pattern ?? DEFAULT_PATTERN + const ignoreGlobs = resolveList(opts.ignore, config.ignore) + const pushback = opts.pushback ?? config.pushback ?? false + const warn = opts.warn ?? config.warn ?? false + const files = findSourceFiles(resolvePattern(pattern), [...DEFAULT_IGNORE, ...ignoreGlobs]) const blocks = findLongCommentBlocks(files, maxLines) let blocksOk = true if (blocks.length === 0) { console.log(color.green(`No comment block over ${maxLines} line(s)`)) } else { - printCommentBlockReport(blocks, maxLines, { pushback: !!opts.pushback, warn: !!opts.warn }) - blocksOk = !!opts.warn + printCommentBlockReport(blocks, maxLines, { pushback, warn }) + blocksOk = warn } let changedLinesOk = true - if (opts.blockNewComments) { - const ignoreGlobs = opts.ignore?.length ? opts.ignore : (loadVerifyConfig().comments?.ignore ?? []) + if (opts.blockNewComments ?? config.blockNewComments) { const findings = findCommentsOnChangedLines(ignoreGlobs) if (findings.length === 0) { console.log(color.green('No comments on changed lines.')) diff --git a/src/checks/complexity.ts b/src/checks/complexity.ts index 6444114..09ffeb4 100644 --- a/src/checks/complexity.ts +++ b/src/checks/complexity.ts @@ -1,6 +1,8 @@ import { analyzeComplexity } from '../analyze.ts' import { printFailure, printFileDetail, printMaintainabilityReport } from '../report.ts' import { color } from '../shared/color.ts' +import { resolveList, type VerifyConfig } from '../shared/config.ts' +import { withVerifyConfig } from './configFailure.ts' import type { CheckResult } from './types.ts' const DEFAULT_THRESHOLD = 50 @@ -11,10 +13,21 @@ export type ComplexityOptions = { threshold?: number } -/** Native maintainability-index check. A single matched file prints a per-metric breakdown instead of the gate. */ +/** + * Native maintainability-index check. A single matched file prints a per-metric breakdown instead of the gate. + * Each option resolves as the given value, then `complexity` in the verify config, then the built-in default. + */ export function runComplexity(opts: ComplexityOptions = {}): CheckResult { - const threshold = opts.threshold ?? DEFAULT_THRESHOLD - const analysis = analyzeComplexity({ pattern: opts.pattern, ignore: opts.ignore, threshold }) + return withVerifyConfig('complexity', ({ complexity }) => checkComplexity(opts, complexity)) +} + +function checkComplexity(opts: ComplexityOptions, config: NonNullable = {}): CheckResult { + const threshold = opts.threshold ?? config.threshold ?? DEFAULT_THRESHOLD + const analysis = analyzeComplexity({ + pattern: opts.pattern ?? config.pattern, + ignore: resolveList(opts.ignore, config.ignore), + threshold, + }) if (analysis.files.length === 0) { console.log(color.yellow('complexity: no files matched — skipping')) diff --git a/src/checks/configFailure.ts b/src/checks/configFailure.ts new file mode 100644 index 0000000..e7f051a --- /dev/null +++ b/src/checks/configFailure.ts @@ -0,0 +1,20 @@ +import { color } from '../shared/color.ts' +import { loadVerifyConfig, type VerifyConfig, VerifyConfigError } from '../shared/config.ts' +import type { CheckResult } from './types.ts' + +export function configFailure(name: string, error: unknown): CheckResult { + if (!(error instanceof VerifyConfigError)) throw error + console.error(color.red(`${name}: invalid verify config`)) + console.error(error.message) + return { name, ok: false } +} + +export function withVerifyConfig(name: string, run: (config: VerifyConfig) => CheckResult): CheckResult { + let config: VerifyConfig + try { + config = loadVerifyConfig() + } catch (error) { + return configFailure(name, error) + } + return run(config) +} diff --git a/src/checks/external.ts b/src/checks/external.ts index 2847909..cc9cb33 100644 --- a/src/checks/external.ts +++ b/src/checks/external.ts @@ -6,6 +6,7 @@ import { resolveMode } from '../shared/mode.ts' import { emit } from '../shared/output.ts' import { detectPackageManager, PACKAGE_MANAGER_COMMANDS } from '../shared/packageManager.ts' import { appendArgv, formatArgv, formatShellCommand, runArgvCommand } from '../shared/spawn.ts' +import { configFailure } from './configFailure.ts' import { type MaxWarningsSupport, withinBudget } from './maxWarnings.ts' import type { Check, CheckMode, CheckResult, RunDefaultOptions } from './types.ts' @@ -52,6 +53,8 @@ export type ExternalCheckSpec = { /** Rewrite the tool's captured output before it is printed, e.g. to strip a tool's own hardcoded colouring. */ transformOutput?: (output: string) => string maxWarnings?: MaxWarningsSupport + /** The findings budget from the verify config, used when no `--max-warnings` is given on the command line. */ + configMaxWarnings?: () => number | undefined } /** Pick the command for the run mode: the fix command only in fix mode and only when the check is fixable. */ @@ -99,7 +102,7 @@ export async function runCountedBudget( if (withinBudget(count, maxWarnings)) return { name: spec.name, ok: true } const unit = count === 1 ? budget.unit : `${budget.unit}s` - console.error(color.dim(`↳ ${spec.name}: ${count} ${unit} found, exceeds --max-warnings ${maxWarnings}.`)) + console.error(color.dim(`↳ ${spec.name}: ${count} ${unit} found, exceeds the max-warnings budget of ${maxWarnings}.`)) if (report) emit(spec.transformOutput ? spec.transformOutput(report) : report) console.error(color.dim(externalFailureHint(spec, argv))) return { name: spec.name, ok: false } @@ -127,33 +130,45 @@ export function defineExternalCheck(spec: ExternalCheckSpec): Check { fix: spec.fixCommand ? formatShellCommand(spec.fixCommand) : undefined, } }, - async runDefault({ extraArgs = [], maxWarnings }: RunDefaultOptions = {}): Promise { - if (!hasLocalBin(spec.bin)) { - const cli = PACKAGE_MANAGER_COMMANDS[detectPackageManager(process.cwd())].runCli - console.log(color.dim(`${spec.name}: ${spec.bin} not installed — skipping (add it with \`${cli} init\`)`)) - return { name: spec.name, ok: true, skipped: true } + async runDefault(options: RunDefaultOptions = {}): Promise { + try { + return await runExternal(spec, options) + } catch (error) { + return configFailure(spec.name, error) } - if (spec.canRun && !spec.canRun()) { - console.log(color.dim(`${spec.name}: not applicable here — skipping`)) - return { name: spec.name, ok: true, skipped: true } - } - const blocked = spec.preflight?.() - if (blocked) { - console.error(blocked) - return { name: spec.name, ok: false } - } - // quiet: buffer the tool's output and flush only on failure (streamed live under --verbose). - const runReport = async (argv: string[]): Promise => { - const code = await runArgvCommand(argv, { env: envWithLocalBin(), quiet: true, transform: spec.transformOutput }) - if (code !== 0) console.error(color.dim(externalFailureHint(spec, argv))) - return { name: spec.name, ok: code === 0 } - } - if (maxWarnings !== undefined && spec.maxWarnings) { - const budget = spec.maxWarnings - if (budget.strategy === 'count') return runCountedBudget(spec, budget, maxWarnings, extraArgs, envWithLocalBin()) - return runReport(appendArgv(selectCommand(spec, resolveMode()), [...extraArgs, ...budget.toArgs(maxWarnings)])) - } - return runReport(appendArgv(selectCommand(spec, resolveMode()), extraArgs)) }, } } + +async function runExternal( + spec: ExternalCheckSpec, + { extraArgs = [], maxWarnings: givenMaxWarnings }: RunDefaultOptions, +): Promise { + if (!hasLocalBin(spec.bin)) { + const cli = PACKAGE_MANAGER_COMMANDS[detectPackageManager(process.cwd())].runCli + console.log(color.dim(`${spec.name}: ${spec.bin} not installed — skipping (add it with \`${cli} init\`)`)) + return { name: spec.name, ok: true, skipped: true } + } + if (spec.canRun && !spec.canRun()) { + console.log(color.dim(`${spec.name}: not applicable here — skipping`)) + return { name: spec.name, ok: true, skipped: true } + } + const blocked = spec.preflight?.() + if (blocked) { + console.error(blocked) + return { name: spec.name, ok: false } + } + // quiet: buffer the tool's output and flush only on failure (streamed live under --verbose). + const runReport = async (argv: string[]): Promise => { + const code = await runArgvCommand(argv, { env: envWithLocalBin(), quiet: true, transform: spec.transformOutput }) + if (code !== 0) console.error(color.dim(externalFailureHint(spec, argv))) + return { name: spec.name, ok: code === 0 } + } + const maxWarnings = givenMaxWarnings ?? spec.configMaxWarnings?.() + if (maxWarnings !== undefined && spec.maxWarnings) { + const budget = spec.maxWarnings + if (budget.strategy === 'count') return runCountedBudget(spec, budget, maxWarnings, extraArgs, envWithLocalBin()) + return runReport(appendArgv(selectCommand(spec, resolveMode()), [...extraArgs, ...budget.toArgs(maxWarnings)])) + } + return runReport(appendArgv(selectCommand(spec, resolveMode()), extraArgs)) +} diff --git a/src/checks/externalConfig.test.ts b/src/checks/externalConfig.test.ts new file mode 100644 index 0000000..f5d49fd --- /dev/null +++ b/src/checks/externalConfig.test.ts @@ -0,0 +1,204 @@ +import fs from 'node:fs' +import os from 'node:os' +import path from 'node:path' + +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' + +const spawned = vi.hoisted(() => ({ runArgvCommand: vi.fn(), captureArgvCommand: vi.fn() })) + +vi.mock('../shared/spawn.ts', async (importOriginal) => ({ ...(await importOriginal()), ...spawned })) + +import { circularDepsCommand, duplicateCodeCommand } from './externalConfig.ts' +import { getCheck } from './registry.ts' + +const SKOTT = ['skott', '--displayMode=raw', '--showCircularDependencies', '--exitCodeOnCircularDependencies=1'] +const JSCPD_HEAD = ['jscpd', '--format', 'typescript,tsx', '--exit-code', '1'] +const JSCPD_REPORTER = ['-r', 'consoleFull'] +const JSCPD_DEFAULT = [...JSCPD_HEAD, '--ignore', '**/*.test.*', ...JSCPD_REPORTER, 'src'] + +let dir: string +let originalCwd: string + +beforeEach(() => { + originalCwd = process.cwd() + dir = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), 'verify-external-config-'))) + process.chdir(dir) + fs.mkdirSync(path.join('node_modules', '.bin'), { recursive: true }) + for (const bin of ['knip', 'skott', 'jscpd']) { + for (const ext of ['', '.cmd']) fs.writeFileSync(path.join('node_modules', '.bin', bin + ext), '') + } + for (const method of ['log', 'warn', 'error'] as const) vi.spyOn(console, method).mockImplementation(() => {}) + spawned.runArgvCommand.mockResolvedValue(0) +}) +afterEach(() => { + process.chdir(originalCwd) + fs.rmSync(dir, { recursive: true, force: true }) + vi.restoreAllMocks() + spawned.runArgvCommand.mockReset() + spawned.captureArgvCommand.mockReset() +}) + +function writeConfig(config: unknown): void { + fs.writeFileSync('verify.config.json', JSON.stringify(config)) +} + +function ranArgv(): string[] { + expect(spawned.runArgvCommand).toHaveBeenCalledTimes(1) + return spawned.runArgvCommand.mock.calls[0]?.[0] as string[] +} + +function mockJscpdClones(count: number): void { + spawned.captureArgvCommand.mockImplementation(async (argv: readonly string[]) => { + const outputDir = argv[argv.indexOf('--output') + 1] as string + const duplicates = Array.from({ length: count }, (_, i) => ({ + firstFile: { name: `a${i}.ts`, start: 1, end: 5 }, + secondFile: { name: `b${i}.ts`, start: 1, end: 5 }, + })) + fs.writeFileSync(path.join(outputDir, 'jscpd-report.json'), JSON.stringify({ duplicates })) + return { code: count > 0 ? 1 : 0, stdout: '', stderr: '' } + }) +} + +function countedArgv(): string[] { + expect(spawned.captureArgvCommand).toHaveBeenCalledTimes(1) + return spawned.captureArgvCommand.mock.calls[0]?.[0] as string[] +} + +describe('circularDepsCommand', () => { + it('is the plain skott command with no config', () => { + expect(circularDepsCommand(undefined)).toEqual(SKOTT) + expect(circularDepsCommand({})).toEqual(SKOTT) + }) + + it('joins extensions into one --fileExtensions flag', () => { + expect(circularDepsCommand({ extensions: ['.ts', '.tsx'] })).toEqual([...SKOTT, '--fileExtensions=.ts,.tsx']) + }) + + it('passes each ignore glob as its own --ignorePattern flag', () => { + expect(circularDepsCommand({ ignore: ['**/*.test.*', 'features/logging/offline-provider.ts'] })).toEqual([ + ...SKOTT, + '--ignorePattern=**/*.test.*', + '--ignorePattern=features/logging/offline-provider.ts', + ]) + }) + + it('turns ignoreTypeImports into --no-trackTypeOnlyDependencies, and adds nothing when false', () => { + expect(circularDepsCommand({ ignoreTypeImports: true })).toEqual([...SKOTT, '--no-trackTypeOnlyDependencies']) + expect(circularDepsCommand({ ignoreTypeImports: false })).toEqual(SKOTT) + }) + + it('adds no flag for empty lists', () => { + expect(circularDepsCommand({ extensions: [], ignore: [] })).toEqual(SKOTT) + }) +}) + +describe('duplicateCodeCommand', () => { + it('scans src and ignores test files with no config', () => { + expect(duplicateCodeCommand(undefined)).toEqual(JSCPD_DEFAULT) + expect(duplicateCodeCommand({ maxWarnings: 3 })).toEqual(JSCPD_DEFAULT) + }) + + it('replaces the default src with the config paths', () => { + expect(duplicateCodeCommand({ paths: ['app', 'features', 'scripts'] })).toEqual([ + ...JSCPD_HEAD, + '--ignore', + '**/*.test.*', + ...JSCPD_REPORTER, + 'app', + 'features', + 'scripts', + ]) + }) + + it('replaces the default ignore with the config globs, one --ignore each', () => { + expect(duplicateCodeCommand({ ignore: ['**/*.spec.*', '**/generated/**'] })).toEqual([ + ...JSCPD_HEAD, + '--ignore', + '**/*.spec.*', + '--ignore', + '**/generated/**', + ...JSCPD_REPORTER, + 'src', + ]) + }) + + it('ignores nothing when the config ignore list is empty', () => { + expect(duplicateCodeCommand({ ignore: [] })).toEqual([...JSCPD_HEAD, ...JSCPD_REPORTER, 'src']) + }) + + it('keeps the default src when the config paths list is empty', () => { + expect(duplicateCodeCommand({ paths: [] })).toEqual(JSCPD_DEFAULT) + }) +}) + +describe('external checks read the verify config through runDefault, the path `verifyx all` uses', () => { + it('runs the built-in commands unchanged with no config', async () => { + await getCheck('circular-deps')?.runDefault() + expect(ranArgv()).toEqual(SKOTT) + spawned.runArgvCommand.mockClear() + + await getCheck('duplicate-code')?.runDefault() + expect(ranArgv()).toEqual(JSCPD_DEFAULT) + spawned.runArgvCommand.mockClear() + + await getCheck('unused-code')?.runDefault() + expect(ranArgv()).toEqual(['knip', '--no-progress', '--treat-config-hints-as-errors']) + }) + + it('builds the skott command from circularDeps and still appends passthrough args', async () => { + writeConfig({ circularDeps: { extensions: ['.ts', '.tsx'], ignore: ['**/*.test.*'], ignoreTypeImports: true } }) + await getCheck('circular-deps')?.runDefault({ extraArgs: ['src/index.ts'] }) + expect(ranArgv()).toEqual([ + ...SKOTT, + '--fileExtensions=.ts,.tsx', + '--ignorePattern=**/*.test.*', + '--no-trackTypeOnlyDependencies', + 'src/index.ts', + ]) + }) + + it('builds the jscpd command from duplicateCode paths and ignore', async () => { + writeConfig({ duplicateCode: { paths: ['app', 'features'], ignore: ['**/generated/**'] } }) + await getCheck('duplicate-code')?.runDefault() + expect(ranArgv()).toEqual([...JSCPD_HEAD, '--ignore', '**/generated/**', ...JSCPD_REPORTER, 'app', 'features']) + }) + + it('reads the same settings from a verify key in package.json', async () => { + fs.writeFileSync('package.json', JSON.stringify({ verify: { circularDeps: { ignoreTypeImports: true } } })) + await getCheck('circular-deps')?.runDefault() + expect(ranArgv()).toEqual([...SKOTT, '--no-trackTypeOnlyDependencies']) + }) + + it('passes unusedCode.maxWarnings to knip as --max-issues (flag strategy)', async () => { + writeConfig({ unusedCode: { maxWarnings: 226 } }) + await getCheck('unused-code')?.runDefault({ extraArgs: ['--production'] }) + expect(ranArgv()).toEqual(['knip', '--no-progress', '--treat-config-hints-as-errors', '--production', '--max-issues', '226']) + }) + + it('lets a command-line max-warnings win over unusedCode.maxWarnings', async () => { + writeConfig({ unusedCode: { maxWarnings: 226 } }) + await getCheck('unused-code')?.runDefault({ maxWarnings: 0 }) + expect(ranArgv().slice(-2)).toEqual(['--max-issues', '0']) + }) + + it('tolerates duplicateCode.maxWarnings findings by counting (count strategy)', async () => { + writeConfig({ duplicateCode: { maxWarnings: 2, paths: ['app'] } }) + mockJscpdClones(2) + expect((await getCheck('duplicate-code')?.runDefault())?.ok).toBe(true) + expect(countedArgv().slice(0, 10)).toEqual([...JSCPD_HEAD, '--ignore', '**/*.test.*', ...JSCPD_REPORTER, 'app']) + expect(spawned.runArgvCommand).not.toHaveBeenCalled() + }) + + it('fails when findings exceed duplicateCode.maxWarnings', async () => { + writeConfig({ duplicateCode: { maxWarnings: 2 } }) + mockJscpdClones(3) + expect((await getCheck('duplicate-code')?.runDefault())?.ok).toBe(false) + }) + + it('lets a command-line max-warnings win over duplicateCode.maxWarnings', async () => { + writeConfig({ duplicateCode: { maxWarnings: 2 } }) + mockJscpdClones(3) + expect((await getCheck('duplicate-code')?.runDefault({ maxWarnings: 3 }))?.ok).toBe(true) + expect((await getCheck('duplicate-code')?.runDefault({ maxWarnings: 1 }))?.ok).toBe(false) + }) +}) diff --git a/src/checks/externalConfig.ts b/src/checks/externalConfig.ts new file mode 100644 index 0000000..5ebb1c8 --- /dev/null +++ b/src/checks/externalConfig.ts @@ -0,0 +1,30 @@ +import { loadVerifyConfig, type VerifyConfig } from '../shared/config.ts' + +const DEFAULT_DUPLICATE_PATHS = ['src'] +const DEFAULT_DUPLICATE_IGNORE = ['**/*.test.*'] + +/** skott argv for `circular-deps`, with the `circularDeps` verify-config settings translated into skott flags. */ +export function circularDepsCommand(config: VerifyConfig['circularDeps'] = loadVerifyConfig().circularDeps): string[] { + const argv = ['skott', '--displayMode=raw', '--showCircularDependencies', '--exitCodeOnCircularDependencies=1'] + if (config?.extensions?.length) argv.push(`--fileExtensions=${config.extensions.join(',')}`) + for (const glob of config?.ignore ?? []) argv.push(`--ignorePattern=${glob}`) + if (config?.ignoreTypeImports) argv.push('--no-trackTypeOnlyDependencies') + return argv +} + +/** jscpd argv for `duplicate-code`. Config `paths` and `ignore` replace the defaults rather than adding to them. */ +export function duplicateCodeCommand(config: VerifyConfig['duplicateCode'] = loadVerifyConfig().duplicateCode): string[] { + const paths = config?.paths?.length ? config.paths : DEFAULT_DUPLICATE_PATHS + const ignore = config?.ignore ?? DEFAULT_DUPLICATE_IGNORE + return [ + 'jscpd', + '--format', + 'typescript,tsx', + '--exit-code', + '1', + ...ignore.flatMap((glob) => ['--ignore', glob]), + '-r', + 'consoleFull', + ...paths, + ] +} diff --git a/src/checks/forbidden-strings.ts b/src/checks/forbidden-strings.ts index 441ddd7..3c6ff90 100644 --- a/src/checks/forbidden-strings.ts +++ b/src/checks/forbidden-strings.ts @@ -3,7 +3,8 @@ import fs from 'node:fs' import { minimatch } from 'minimatch' import { color } from '../shared/color.ts' -import { type ForbiddenStringsRule, loadVerifyConfig } from '../shared/config.ts' +import type { ForbiddenStringsRule } from '../shared/config.ts' +import { withVerifyConfig } from './configFailure.ts' import type { CheckResult } from './types.ts' type ForbiddenStringViolation = { file: string; path: string; value: string } @@ -46,7 +47,10 @@ export type ForbiddenStringsOptions = { rules?: readonly ForbiddenStringsRule[] /** Fail when configured JSON values match a `disallowed` glob. Rules come from verify config. */ export function runForbiddenStrings(opts: ForbiddenStringsOptions = {}): CheckResult { - const rules = opts.rules ?? loadVerifyConfig().forbiddenStrings ?? [] + return withVerifyConfig('forbidden-strings', ({ forbiddenStrings }) => checkForbiddenStrings(opts.rules ?? forbiddenStrings ?? [])) +} + +function checkForbiddenStrings(rules: readonly ForbiddenStringsRule[]): CheckResult { if (rules.length === 0) { console.log(color.dim('forbidden-strings: no rules configured — skipping')) return { name: 'forbidden-strings', ok: true } diff --git a/src/checks/hardcoded-colors.ts b/src/checks/hardcoded-colors.ts index b470793..4b19b91 100644 --- a/src/checks/hardcoded-colors.ts +++ b/src/checks/hardcoded-colors.ts @@ -4,7 +4,8 @@ import path from 'node:path' import { minimatch } from 'minimatch' import { color } from '../shared/color.ts' -import { loadVerifyConfig } from '../shared/config.ts' +import type { VerifyConfig } from '../shared/config.ts' +import { withVerifyConfig } from './configFailure.ts' import type { CheckResult } from './types.ts' const COLOR_PATTERN = /0x[0-9a-fA-F]{6}|#[0-9a-fA-F]{3,8}/ @@ -26,9 +27,12 @@ export type HardcodedColorsOptions = { root?: string; ignore?: readonly string[] /** Fail on literal hex / 0x colours in source. Cross-platform (no `grep`); suggests the design-token path. */ export function runHardcodedColors(opts: HardcodedColorsOptions = {}): CheckResult { - const config = loadVerifyConfig() - const root = opts.root ?? config.hardcodedColors?.root ?? 'src' - const ignoreGlobs = opts.ignore?.length ? opts.ignore : (config.hardcodedColors?.ignore ?? []) + return withVerifyConfig('hardcoded-colors', ({ hardcodedColors }) => checkHardcodedColors(opts, hardcodedColors)) +} + +function checkHardcodedColors(opts: HardcodedColorsOptions, config: NonNullable = {}): CheckResult { + const root = opts.root ?? config.root ?? 'src' + const ignoreGlobs = opts.ignore?.length ? opts.ignore : (config.ignore ?? []) const files: string[] = [] walk(root, files) diff --git a/src/checks/invalidConfig.test.ts b/src/checks/invalidConfig.test.ts new file mode 100644 index 0000000..95ad845 --- /dev/null +++ b/src/checks/invalidConfig.test.ts @@ -0,0 +1,221 @@ +import fs from 'node:fs' +import os from 'node:os' +import path from 'node:path' + +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' + +const spawned = vi.hoisted(() => ({ runArgvCommand: vi.fn(), captureArgvCommand: vi.fn() })) + +vi.mock('../shared/spawn.ts', async (importOriginal) => ({ ...(await importOriginal()), ...spawned })) + +import { ejectScripts } from '../scaffold/eject.ts' +import { loadVerifyConfig, VerifyConfigError } from '../shared/config.ts' +import { runComments } from './comments.ts' +import { runComplexity } from './complexity.ts' +import { runForbiddenStrings } from './forbidden-strings.ts' +import { runHardcodedColors } from './hardcoded-colors.ts' +import { CHECKS, getCheck } from './registry.ts' + +const CONFIG_READERS = [ + 'complexity', + 'comments', + 'hardcoded-colors', + 'forbidden-strings', + 'unused-code', + 'circular-deps', + 'duplicate-code', +] as const +const EXTERNAL_BINS = ['oxlint', 'oxfmt', 'tsc', 'knip', 'skott', 'jscpd'] + +let dir: string +let originalCwd: string +let spies: ReturnType[] + +beforeEach(() => { + originalCwd = process.cwd() + dir = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), 'verify-invalid-config-'))) + process.chdir(dir) + fs.mkdirSync(path.join('node_modules', '.bin'), { recursive: true }) + for (const bin of EXTERNAL_BINS) { + for (const ext of ['', '.cmd']) fs.writeFileSync(path.join('node_modules', '.bin', bin + ext), '') + } + spies = (['log', 'warn', 'error'] as const).map((method) => vi.spyOn(console, method).mockImplementation(() => {})) + spawned.runArgvCommand.mockResolvedValue(0) +}) +afterEach(() => { + process.chdir(originalCwd) + fs.rmSync(dir, { recursive: true, force: true }) + vi.restoreAllMocks() + spawned.runArgvCommand.mockReset() + spawned.captureArgvCommand.mockReset() +}) + +function writeConfig(config: unknown): void { + fs.writeFileSync('verify.config.json', JSON.stringify(config)) +} + +function printed(): string { + return spies.flatMap((spy) => spy.mock.calls.flat()).join('\n') +} + +function loadError(): string { + try { + loadVerifyConfig() + } catch (error) { + expect(error).toBeInstanceOf(VerifyConfigError) + return (error as Error).message + } + throw new Error('expected loadVerifyConfig to throw') +} + +describe('loadVerifyConfig validation', () => { + it('returns an empty config when there is no verify config', () => { + expect(loadVerifyConfig()).toEqual({}) + fs.writeFileSync('package.json', JSON.stringify({ name: 'x', scripts: { verify: 'verifyx all' } })) + expect(loadVerifyConfig()).toEqual({}) + }) + + it('accepts every documented key', () => { + const config = { + complexity: { threshold: 10, pattern: 'src/**/*.ts', ignore: ['a/**'] }, + comments: { maxLines: 10, pattern: 'src/**/*.ts', ignore: ['a/**'], pushback: true, warn: false, blockNewComments: true }, + unusedCode: { maxWarnings: 0 }, + duplicateCode: { maxWarnings: 137, paths: ['app'], ignore: ['**/*.test.*'] }, + circularDeps: { extensions: ['.ts'], ignore: ['a/**'], ignoreTypeImports: true }, + hardcodedColors: { root: 'src', ignore: ['**/tokens.ts'] }, + forbiddenStrings: [{ file: 'app.json', paths: ['env.LOG_LEVEL'], disallowed: 'debug' }], + } + writeConfig(config) + expect(loadVerifyConfig()).toEqual(config) + }) + + it('names the file when verify.config.json is not valid JSON', () => { + fs.writeFileSync('verify.config.json', '{ "complexity": ') + expect(loadError()).toMatch(/^verify\.config\.json: not valid JSON/) + }) + + it('rejects invalid JSON rather than falling back to package.json', () => { + fs.writeFileSync('verify.config.json', 'nope') + fs.writeFileSync('package.json', JSON.stringify({ verify: { complexity: { threshold: 10 } } })) + expect(loadError()).toContain('verify.config.json: not valid JSON') + }) + + it('rejects a config that is not an object', () => { + writeConfig(['complexity']) + expect(loadError()).toBe('verify.config.json: the config must be a JSON object') + }) + + it('names an unknown top-level key', () => { + writeConfig({ complexty: { threshold: 10 } }) + expect(loadError()).toContain('verify.config.json: unknown key "complexty"') + }) + + it('names an unknown key inside a check, listing the allowed ones', () => { + writeConfig({ complexity: { treshold: 10 } }) + expect(loadError()).toBe('verify.config.json: unknown key "complexity.treshold" (allowed: threshold, pattern, ignore)') + }) + + it.each(['complexity', 'comments', 'unusedCode', 'duplicateCode', 'circularDeps', 'hardcodedColors'])( + 'rejects a raw args key under %s', + (section) => { + writeConfig({ [section]: { args: ['--flag'] } }) + expect(loadError()).toContain(`verify.config.json: unknown key "${section}.args"`) + }, + ) + + it('rejects a top-level args key', () => { + writeConfig({ args: ['--flag'] }) + expect(loadError()).toContain('verify.config.json: unknown key "args"') + }) + + it.each([ + [{ complexity: { threshold: '10' } }, '"complexity.threshold" must be a number'], + [{ complexity: { pattern: ['src'] } }, '"complexity.pattern" must be a string'], + [{ complexity: { ignore: 'a/**' } }, '"complexity.ignore" must be an array of strings'], + [{ comments: { ignore: ['a', 1] } }, '"comments.ignore" must be an array of strings'], + [{ comments: { pushback: 'true' } }, '"comments.pushback" must be a boolean'], + [{ unusedCode: { maxWarnings: -1 } }, '"unusedCode.maxWarnings" must be a non-negative integer'], + [{ duplicateCode: { maxWarnings: 1.5 } }, '"duplicateCode.maxWarnings" must be a non-negative integer'], + [{ duplicateCode: { paths: 'src' } }, '"duplicateCode.paths" must be an array of strings'], + [{ circularDeps: { ignoreTypeImports: 1 } }, '"circularDeps.ignoreTypeImports" must be a boolean'], + [{ circularDeps: null }, '"circularDeps" must be an object'], + [{ hardcodedColors: { root: 1 } }, '"hardcodedColors.root" must be a string'], + [{ forbiddenStrings: {} }, '"forbiddenStrings" must be an array of rules'], + [{ forbiddenStrings: [{ file: 'a.json', paths: ['x'] }] }, '"forbiddenStrings[0].disallowed" must be a string'], + ])('names the key of a wrong-typed setting: %j', (config, problem) => { + writeConfig(config) + expect(loadError()).toBe(`verify.config.json: ${problem}`) + }) + + it('reports every problem, one per line', () => { + writeConfig({ complexity: { threshold: 'x', args: [] }, nope: 1 }) + expect(loadError().split('\n')).toEqual([ + 'verify.config.json: unknown key "complexity.args" (allowed: threshold, pattern, ignore)', + 'verify.config.json: "complexity.threshold" must be a number', + expect.stringContaining('verify.config.json: unknown key "nope"'), + ]) + }) + + it('names package.json and the verify-prefixed key for a bad package.json config', () => { + fs.writeFileSync('package.json', JSON.stringify({ verify: { complexity: { threshold: '10', args: [] } } })) + expect(loadError().split('\n')).toEqual([ + 'package.json: unknown key "verify.complexity.args" (allowed: threshold, pattern, ignore)', + 'package.json: "verify.complexity.threshold" must be a number', + ]) + }) + + it('rejects a package.json verify key that is not an object', () => { + fs.writeFileSync('package.json', JSON.stringify({ verify: true })) + expect(loadError()).toBe('package.json: "verify" must be an object') + }) +}) + +describe('checks fail on a bad config instead of falling back to defaults', () => { + beforeEach(() => { + writeConfig({ complexity: { args: ['--threshold', '10'] } }) + }) + + it.each([ + ['complexity', () => runComplexity()], + ['comments', () => runComments()], + ['hardcoded-colors', () => runHardcodedColors()], + ['forbidden-strings', () => runForbiddenStrings()], + ])('fails the %s subcommand, naming the file and key', (name, run) => { + expect(run()).toEqual({ name, ok: false }) + expect(printed()).toContain(`${name}: invalid verify config`) + expect(printed()).toContain('verify.config.json: unknown key "complexity.args"') + }) + + it.each(CONFIG_READERS)('fails %s through runDefault, the path `verifyx all` uses', async (name) => { + expect(await getCheck(name)?.runDefault()).toEqual({ name, ok: false }) + expect(printed()).toContain('verify.config.json: unknown key "complexity.args"') + expect(spawned.runArgvCommand).not.toHaveBeenCalled() + expect(spawned.captureArgvCommand).not.toHaveBeenCalled() + }) + + it('prints the error once for comments under runDefault', async () => { + await getCheck('comments')?.runDefault() + expect(printed().match(/invalid verify config/g)).toHaveLength(1) + }) + + it('fails with a command-line max-warnings too, since the command is still built from config', async () => { + expect(await getCheck('duplicate-code')?.runDefault({ maxWarnings: 5 })).toEqual({ name: 'duplicate-code', ok: false }) + expect(spawned.captureArgvCommand).not.toHaveBeenCalled() + }) + + it('still runs the checks that read nothing from the verify config', async () => { + fs.writeFileSync('tsconfig.json', '{}') + for (const name of ['lint', 'format', 'check-types', 'github-actions']) { + expect(await getCheck(name)?.runDefault()).toMatchObject({ name, ok: true }) + } + expect(spawned.runArgvCommand).toHaveBeenCalledTimes(3) + }) + + it('covers every built-in check in one of the two groups above', () => { + expect(CHECKS.map((check) => check.name).sort()).toEqual([...CONFIG_READERS, 'lint', 'format', 'check-types', 'github-actions'].sort()) + }) + + it('refuses to eject a command built from a bad config', () => { + expect(() => ejectScripts('circular-deps')).toThrow('verify.config.json: unknown key "complexity.args"') + }) +}) diff --git a/src/checks/nativeConfig.test.ts b/src/checks/nativeConfig.test.ts new file mode 100644 index 0000000..3ecd222 --- /dev/null +++ b/src/checks/nativeConfig.test.ts @@ -0,0 +1,219 @@ +import { execFileSync } from 'node:child_process' +import fs from 'node:fs' +import os from 'node:os' +import path from 'node:path' + +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' + +import { runComments } from './comments.ts' +import { runComplexity } from './complexity.ts' +import { getCheck } from './registry.ts' + +let dir: string +let originalCwd: string +let spies: ReturnType[] + +beforeEach(() => { + originalCwd = process.cwd() + dir = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), 'verify-native-config-'))) + process.chdir(dir) + spies = (['log', 'warn', 'error'] as const).map((method) => vi.spyOn(console, method).mockImplementation(() => {})) +}) +afterEach(() => { + process.chdir(originalCwd) + fs.rmSync(dir, { recursive: true, force: true }) + vi.restoreAllMocks() + vi.unstubAllEnvs() +}) + +function write(name: string, content: string): void { + fs.mkdirSync(path.dirname(name), { recursive: true }) + fs.writeFileSync(name, content) +} + +function writeConfig(config: unknown): void { + write('verify.config.json', JSON.stringify(config)) +} + +function printed(): string { + return spies.flatMap((spy) => spy.mock.calls.flat()).join('\n') +} + +function clearPrinted(): void { + for (const spy of spies) spy.mockClear() +} + +const FN = 'export function f(a: number): number {\n return a + 1\n}\n' +const LONG_BLOCK = ['// one', '// two', '// three', 'export const a = 1', ''].join('\n') + +// context: maintainability index is clamped to 0-100, so a threshold of 101 fails every scored file and 0 fails none. +const FAIL_ALL = 101 +const PASS_ALL = 0 + +describe('runComplexity config', () => { + beforeEach(() => { + write('src/a.ts', FN) + write('src/b.ts', FN) + }) + + it('uses the built-in defaults with no config', () => { + expect(runComplexity()).toEqual({ name: 'complexity', ok: true }) + }) + + it('reads threshold from config', () => { + writeConfig({ complexity: { threshold: FAIL_ALL } }) + expect(runComplexity().ok).toBe(false) + }) + + it('lets a given threshold win over config', () => { + writeConfig({ complexity: { threshold: FAIL_ALL } }) + expect(runComplexity({ threshold: PASS_ALL }).ok).toBe(true) + }) + + it('reads pattern from config', () => { + write('app/c.ts', FN) + write('app/d.ts', FN) + writeConfig({ complexity: { threshold: FAIL_ALL, pattern: 'app/**/*.ts' } }) + expect(runComplexity().ok).toBe(false) + expect(printed()).toContain('app/c.ts') + expect(printed()).not.toContain('src/a.ts') + }) + + it('lets a given pattern win over config', () => { + write('app/c.ts', FN) + write('app/d.ts', FN) + writeConfig({ complexity: { threshold: FAIL_ALL, pattern: 'app/**/*.ts' } }) + runComplexity({ pattern: 'src/**/*.ts' }) + expect(printed()).toContain('src/a.ts') + expect(printed()).not.toContain('app/c.ts') + }) + + it('reads ignore from config', () => { + write('src/c.ts', FN) + writeConfig({ complexity: { threshold: FAIL_ALL, ignore: ['src/c.ts'] } }) + runComplexity() + expect(printed()).toContain('src/a.ts') + expect(printed()).not.toContain('src/c.ts') + }) + + it('replaces the config ignore list with a given one rather than merging', () => { + write('src/c.ts', FN) + writeConfig({ complexity: { threshold: FAIL_ALL, ignore: ['src/c.ts'] } }) + runComplexity({ ignore: ['src/a.ts'] }) + expect(printed()).toContain('src/c.ts') + expect(printed()).not.toContain('src/a.ts') + }) + + it('treats an empty ignore list, as an unused --ignore flag gives, as not given', () => { + write('src/c.ts', FN) + writeConfig({ complexity: { threshold: FAIL_ALL, ignore: ['src/c.ts'] } }) + runComplexity({ ignore: [] }) + expect(printed()).not.toContain('src/c.ts') + }) + + it('reads the same settings from a verify key in package.json', () => { + write('package.json', JSON.stringify({ verify: { complexity: { threshold: FAIL_ALL } } })) + expect(runComplexity().ok).toBe(false) + }) + + it('applies config through the runDefault path used by `verifyx all`', async () => { + writeConfig({ complexity: { threshold: FAIL_ALL } }) + expect((await getCheck('complexity')?.runDefault())?.ok).toBe(false) + }) +}) + +describe('runComments config', () => { + beforeEach(() => { + write('src/a.ts', LONG_BLOCK) + }) + + it('uses the built-in max-lines of 2 with no config', () => { + expect(runComments()).toEqual({ name: 'comments', ok: false }) + }) + + it('reads maxLines from config', () => { + writeConfig({ comments: { maxLines: 3 } }) + expect(runComments().ok).toBe(true) + }) + + it('lets a given maxLines win over config', () => { + writeConfig({ comments: { maxLines: 3 } }) + expect(runComments({ maxLines: 2 }).ok).toBe(false) + }) + + it('applies config ignore to the long-block check', () => { + writeConfig({ comments: { ignore: ['src/a.ts'] } }) + expect(runComments().ok).toBe(true) + }) + + it('replaces the config ignore list with a given one rather than merging', () => { + writeConfig({ comments: { ignore: ['src/a.ts'] } }) + expect(runComments({ ignore: ['src/other.ts'] }).ok).toBe(false) + }) + + it('reads pattern from config, and lets a given pattern win', () => { + write('app/clean.ts', 'export const a = 1\n') + writeConfig({ comments: { pattern: 'app/**/*.ts' } }) + expect(runComments().ok).toBe(true) + expect(runComments({ pattern: 'src/**/*.ts' }).ok).toBe(false) + }) + + it('reads warn from config, and lets a given warn win', () => { + writeConfig({ comments: { warn: true } }) + expect(runComments().ok).toBe(true) + expect(runComments({ warn: false }).ok).toBe(false) + }) + + it('reads pushback from config, and lets a given pushback win', () => { + runComments() + const plain = printed() + clearPrinted() + + writeConfig({ comments: { pushback: true } }) + runComments() + expect(printed()).not.toBe(plain) + clearPrinted() + + runComments({ pushback: false }) + expect(printed()).toBe(plain) + }) + + it('keeps pushback on by default through runDefault, and lets config turn it off', async () => { + runComments({ pushback: true }) + const pushed = printed() + clearPrinted() + + await getCheck('comments')?.runDefault() + expect(printed()).toBe(pushed) + clearPrinted() + + writeConfig({ comments: { pushback: false } }) + await getCheck('comments')?.runDefault() + expect(printed()).not.toBe(pushed) + }) + + it('reads blockNewComments from config, and lets a given blockNewComments win', () => { + vi.stubEnv('CI', '') + vi.stubEnv('VERIFY_DIFF_BASE', '') + const git = (...args: string[]): void => { + execFileSync('git', ['-c', 'user.name=t', '-c', 'user.email=t@example.com', '-c', 'commit.gpgsign=false', ...args], { + stdio: 'ignore', + }) + } + write('src/a.ts', 'export const a = 1\n') + git('init') + git('add', '.') + git('commit', '-m', 'init') + write('src/a.ts', '// a new comment\nexport const a = 1\n') + + expect(runComments().ok).toBe(true) + writeConfig({ comments: { blockNewComments: true } }) + expect(runComments().ok).toBe(false) + expect(runComments({ blockNewComments: false }).ok).toBe(true) + }) + + it('applies config through the runDefault path used by `verifyx all`', async () => { + writeConfig({ comments: { maxLines: 3 } }) + expect((await getCheck('comments')?.runDefault())?.ok).toBe(true) + }) +}) diff --git a/src/checks/registry.ts b/src/checks/registry.ts index a2cfdd3..240f2c1 100644 --- a/src/checks/registry.ts +++ b/src/checks/registry.ts @@ -1,9 +1,12 @@ import fs from 'node:fs' import { withoutRed } from '../shared/color.ts' +import { loadVerifyConfig } from '../shared/config.ts' import { runComments } from './comments.ts' import { runComplexity } from './complexity.ts' +import { withVerifyConfig } from './configFailure.ts' import { defineExternalCheck } from './external.ts' +import { circularDepsCommand, duplicateCodeCommand } from './externalConfig.ts' import { runForbiddenStrings } from './forbidden-strings.ts' import { runGithubActions } from './github-actions.ts' import { runHardcodedColors } from './hardcoded-colors.ts' @@ -30,7 +33,7 @@ export const CHECKS: Check[] = [ 'comments', 'Flag long comment blocks (JSDoc / context: exempt); --block-new-comments also fails comments on changed lines', true, - () => runComments({ pushback: true }), + () => withVerifyConfig('comments', ({ comments }) => runComments({ pushback: comments?.pushback ?? true })), 'verifyx comments --pushback', ), nativeCheck('hardcoded-colors', 'Fail on literal hex / 0x colour values in source', false, () => runHardcodedColors()), @@ -80,12 +83,15 @@ export const CHECKS: Check[] = [ failureAdvice: 'An "unused" finding can be a false positive when the file is loaded dynamically (directory scan + require(), glob-registered ORM entities) or a script calls a system binary. Verify before deleting: suppress genuinely runtime-loaded files via knip `entry` globs and system tools via `ignoreBinaries` — never delete a file to satisfy this check without checking how it is loaded.', maxWarnings: { strategy: 'flag', toArgs: (n) => ['--max-issues', String(n)] }, + configMaxWarnings: () => loadVerifyConfig().unusedCode?.maxWarnings, }), defineExternalCheck({ name: 'circular-deps', description: 'Circular dependency detection', bin: 'skott', - checkCommand: ['skott', '--displayMode=raw', '--showCircularDependencies', '--exitCodeOnCircularDependencies=1'], + get checkCommand() { + return circularDepsCommand() + }, devDeps: ['skott'], pnpmDenyBuilds: ['@parcel/watcher'], docs: 'https://github.com/antoine-coulon/skott', @@ -94,13 +100,16 @@ export const CHECKS: Check[] = [ name: 'duplicate-code', description: 'Copy-paste / duplicate-code detection', bin: 'jscpd', - checkCommand: ['jscpd', '--format', 'typescript,tsx', '--exit-code', '1', '--ignore', '**/*.test.*', '-r', 'consoleFull', 'src'], + get checkCommand() { + return duplicateCodeCommand() + }, devDeps: ['jscpd'], // jscpd hardcodes red header cells in its stats table (even on a clean run) — reads like a failure. It ignores // NO_COLOR/FORCE_COLOR, so strip the red foreground from its output; the table renders in the default colour. transformOutput: withoutRed, docs: 'https://github.com/kucherenko/jscpd/tree/master/apps/jscpd#config', maxWarnings: { strategy: 'count', unit: 'duplicated region', count: jscpdCount }, + configMaxWarnings: () => loadVerifyConfig().duplicateCode?.maxWarnings, }), ] diff --git a/src/commands/registerChecks.ts b/src/commands/registerChecks.ts index 886c3ca..7144344 100644 --- a/src/commands/registerChecks.ts +++ b/src/commands/registerChecks.ts @@ -41,8 +41,11 @@ export function registerChecks(program: Command): void { .argument('[pattern]', 'glob, directory, or file to scan') .option('--max-lines ', 'maximum comment-block length', Number) .option('--pushback', 'add AI back-pressure framing to the failure message') + .option('--no-pushback', 'turn off pushback set in the verify config') .option('--warn', 'report without failing the run') + .option('--no-warn', 'turn off warn set in the verify config') .option('--block-new-comments', 'also fail on any comment on a line changed against HEAD') + .option('--no-block-new-comments', 'turn off blockNewComments set in the verify config') .option('--ignore ', 'ignore glob (repeatable)', collect, []) .action( ( diff --git a/src/index.ts b/src/index.ts index f94b59d..c9facd6 100644 --- a/src/index.ts +++ b/src/index.ts @@ -29,4 +29,4 @@ export { orchestrate } from './orchestrator/run.ts' export { runAll } from './orchestrator/runAll.ts' export { applyEject, type EjectResult, ejectScripts } from './scaffold/eject.ts' export { applyInit, type InitOptions, type InitResult } from './scaffold/init.ts' -export { type ForbiddenStringsRule, loadVerifyConfig, type VerifyConfig } from './shared/config.ts' +export { type ForbiddenStringsRule, loadVerifyConfig, type VerifyConfig, VerifyConfigError } from './shared/config.ts' diff --git a/src/shared/config.ts b/src/shared/config.ts index b277c81..84e7e6a 100644 --- a/src/shared/config.ts +++ b/src/shared/config.ts @@ -1,6 +1,8 @@ import fs from 'node:fs' import path from 'node:path' +import { findConfigProblems } from './configSchema.ts' + /** A rule for the forbidden-strings check: JSON values at `paths` in `file` must not match `disallowed`. */ export type ForbiddenStringsRule = { file: string @@ -9,31 +11,62 @@ export type ForbiddenStringsRule = { } export type VerifyConfig = { - comments?: { ignore?: string[] } + complexity?: { threshold?: number; pattern?: string; ignore?: string[] } + comments?: { + maxLines?: number + pattern?: string + ignore?: string[] + pushback?: boolean + warn?: boolean + blockNewComments?: boolean + } + unusedCode?: { maxWarnings?: number } + duplicateCode?: { maxWarnings?: number; paths?: string[]; ignore?: string[] } + circularDeps?: { extensions?: string[]; ignore?: string[]; ignoreTypeImports?: boolean } hardcodedColors?: { ignore?: string[]; root?: string } forbiddenStrings?: ForbiddenStringsRule[] } const CONFIG_FILE = 'verify.config.json' -function readJsonIfExists(file: string): unknown { - if (!fs.existsSync(file)) return undefined +export class VerifyConfigError extends Error { + constructor(file: string, problems: readonly string[]) { + super(problems.map((problem) => `${file}: ${problem}`).join('\n')) + this.name = 'VerifyConfigError' + } +} + +function readJsonIfExists(cwd: string, file: string): unknown { + const full = path.join(cwd, file) + if (!fs.existsSync(full)) return undefined try { - return JSON.parse(fs.readFileSync(file, 'utf-8')) - } catch { - return undefined + return JSON.parse(fs.readFileSync(full, 'utf-8')) + } catch (error) { + throw new VerifyConfigError(file, [`not valid JSON (${(error as Error).message})`]) } } -/** Load per-repo check configuration from `verify.config.json`, falling back to a `verify` key in package.json. */ +function validated(config: unknown, file: string, prefix?: string): VerifyConfig { + const problems = findConfigProblems(config, prefix) + if (problems.length > 0) throw new VerifyConfigError(file, problems) + return config as VerifyConfig +} + +/** + * Load per-repo check configuration from `verify.config.json`, falling back to a `verify` key in package.json. + * Throws a `VerifyConfigError` naming the file and key when the config is not valid JSON, has an unknown key, or + * has a setting of the wrong type. + */ export function loadVerifyConfig(cwd: string = process.cwd()): VerifyConfig { - const fromFile = readJsonIfExists(path.join(cwd, CONFIG_FILE)) - if (fromFile && typeof fromFile === 'object') return fromFile as VerifyConfig + const fromFile = readJsonIfExists(cwd, CONFIG_FILE) + if (fromFile !== undefined) return validated(fromFile, CONFIG_FILE) - const pkg = readJsonIfExists(path.join(cwd, 'package.json')) - if (pkg && typeof pkg === 'object' && 'verify' in pkg) { - const verify = (pkg as { verify?: unknown }).verify - if (verify && typeof verify === 'object') return verify as VerifyConfig - } + const pkg = readJsonIfExists(cwd, 'package.json') + if (pkg && typeof pkg === 'object' && 'verify' in pkg) return validated((pkg as { verify?: unknown }).verify, 'package.json', 'verify.') return {} } + +/** A repeatable CLI list flag that was not given arrives as an empty array, so empty falls through to the config list. */ +export function resolveList(cli: readonly string[] | undefined, config: readonly string[] | undefined): readonly string[] { + return cli?.length ? cli : (config ?? []) +} diff --git a/src/shared/configSchema.ts b/src/shared/configSchema.ts new file mode 100644 index 0000000..f565bcb --- /dev/null +++ b/src/shared/configSchema.ts @@ -0,0 +1,69 @@ +type SettingKind = 'number' | 'count' | 'string' | 'boolean' | 'string[]' + +const SETTING_CHECKS: Record boolean }> = { + number: { label: 'a number', test: (value) => typeof value === 'number' && Number.isFinite(value) }, + count: { label: 'a non-negative integer', test: (value) => Number.isSafeInteger(value) && (value as number) >= 0 }, + string: { label: 'a string', test: (value) => typeof value === 'string' }, + boolean: { label: 'a boolean', test: (value) => typeof value === 'boolean' }, + 'string[]': { + label: 'an array of strings', + test: (value) => Array.isArray(value) && value.every((item) => typeof item === 'string'), + }, +} + +const SECTIONS: Record> = { + complexity: { threshold: 'number', pattern: 'string', ignore: 'string[]' }, + comments: { + maxLines: 'number', + pattern: 'string', + ignore: 'string[]', + pushback: 'boolean', + warn: 'boolean', + blockNewComments: 'boolean', + }, + unusedCode: { maxWarnings: 'count' }, + duplicateCode: { maxWarnings: 'count', paths: 'string[]', ignore: 'string[]' }, + circularDeps: { extensions: 'string[]', ignore: 'string[]', ignoreTypeImports: 'boolean' }, + hardcodedColors: { ignore: 'string[]', root: 'string' }, +} + +const FORBIDDEN_STRINGS_RULE: Record = { file: 'string', paths: 'string[]', disallowed: 'string' } + +const TOP_LEVEL_KEYS = [...Object.keys(SECTIONS), 'forbiddenStrings'] + +function isPlainObject(value: unknown): value is Record { + return typeof value === 'object' && value !== null && !Array.isArray(value) +} + +function unknownKey(key: string, allowed: readonly string[]): string { + return `unknown key "${key}" (allowed: ${allowed.join(', ')})` +} + +function validateSettings(value: unknown, key: string, schema: Record, required: boolean): string[] { + if (!isPlainObject(value)) return [`"${key}" must be an object`] + const problems: string[] = [] + for (const name of Object.keys(value)) { + if (!(name in schema)) problems.push(unknownKey(`${key}.${name}`, Object.keys(schema))) + } + for (const [name, kind] of Object.entries(schema)) { + if (value[name] === undefined && !required) continue + const check = SETTING_CHECKS[kind] + if (!check.test(value[name])) problems.push(`"${key}.${name}" must be ${check.label}`) + } + return problems +} + +function validateForbiddenStrings(value: unknown, key: string): string[] { + if (!Array.isArray(value)) return [`"${key}" must be an array of rules`] + return value.flatMap((rule, index) => validateSettings(rule, `${key}[${index}]`, FORBIDDEN_STRINGS_RULE, true)) +} + +export function findConfigProblems(config: unknown, keyPrefix = ''): string[] { + if (!isPlainObject(config)) return [keyPrefix ? `"${keyPrefix.slice(0, -1)}" must be an object` : 'the config must be a JSON object'] + return Object.entries(config).flatMap(([name, value]) => { + const key = `${keyPrefix}${name}` + if (name === 'forbiddenStrings') return validateForbiddenStrings(value, key) + const schema = SECTIONS[name] + return schema ? validateSettings(value, key, schema, false) : [unknownKey(key, TOP_LEVEL_KEYS)] + }) +}