Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
171 changes: 161 additions & 10 deletions README.md

Large diffs are not rendered by default.

24 changes: 16 additions & 8 deletions src/checks/comments.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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<VerifyConfig['comments']> = {}): 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.'))
Expand Down
19 changes: 16 additions & 3 deletions src/checks/complexity.ts
Original file line number Diff line number Diff line change
@@ -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
Expand All @@ -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<VerifyConfig['complexity']> = {}): 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'))
Expand Down
20 changes: 20 additions & 0 deletions src/checks/configFailure.ts
Original file line number Diff line number Diff line change
@@ -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)
}
69 changes: 42 additions & 27 deletions src/checks/external.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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'

Expand Down Expand Up @@ -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. */
Expand Down Expand Up @@ -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 }
Expand Down Expand Up @@ -127,33 +130,45 @@ export function defineExternalCheck(spec: ExternalCheckSpec): Check {
fix: spec.fixCommand ? formatShellCommand(spec.fixCommand) : undefined,
}
},
async runDefault({ extraArgs = [], maxWarnings }: RunDefaultOptions = {}): Promise<CheckResult> {
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<CheckResult> {
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<CheckResult> => {
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<CheckResult> {
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<CheckResult> => {
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))
}
Loading
Loading