import { glob } from "tinyglobby" import { Herb } from "@herb-tools/node-wasm" import { Config, addHerbExtensionRecommendation, getExtensionsJsonRelativePath } from "@herb-tools/config" import { existsSync, statSync } from "fs" import { resolve, relative } from "path" import { colorize } from "@herb-tools/highlighter" import { DIAGNOSTIC_SEVERITIES, meetsSeverityThreshold } from "@herb-tools/core" import { Linter } from "./linter.js" import { rules } from "./rules.js" import { loadCustomRules as loadCustomRulesFromDisk } from "./loader.js" import { ArgumentParser } from "./cli/argument-parser.js" import { isStructuredFormat } from "./cli/output-format.js" import { FileProcessor } from "./cli/file-processor.js" import { OutputManager } from "./cli/output-manager.js" import { version } from "../package.json" import type { DiagnosticSeverity } from "@herb-tools/core" import type { ProcessingContext } from "./cli/file-processor.js" import type { FormatOption, OutputTarget } from "./cli/output-format.js" import type { RuleFilterFlag } from "./cli/summary-reporter.js" import type { RuleClass } from "./types.js" export * from "./cli/index.js" const NOT_FAILING_TIP_THRESHOLD = 10 export class CLI { protected argumentParser = new ArgumentParser() protected fileProcessor = new FileProcessor() protected outputManager = new OutputManager() protected projectPath: string = process.cwd() protected outputs?: OutputTarget[] getProjectPath(): string { return this.projectPath } protected exitWithError(message: string, formatOption: FormatOption, exitCode: number = 1): never { this.outputManager.outputError(message, { formatOption, outputs: this.outputs, theme: 'auto', wrapLines: false, truncateLines: false, showTiming: false, useGitHubActions: false, startTime: 0, startDate: new Date() }) process.exit(exitCode || process.exitCode) } protected exitWithInfo(message: string, formatOption: FormatOption, exitCode: number = 0, timingData?: { startTime: number, startDate: Date, showTiming: boolean }): never { const outputOptions = { formatOption, outputs: this.outputs, theme: 'auto' as const, wrapLines: false, truncateLines: false, showTiming: timingData?.showTiming ?? false, useGitHubActions: false, startTime: timingData?.startTime ?? Date.now(), startDate: timingData?.startDate ?? new Date() } this.outputManager.outputInfo(message, outputOptions) process.exit(exitCode || process.exitCode) } protected determineProjectPath(patterns: string[]): void { const pattern = patterns[0] if (pattern) { const resolvedPattern = resolve(pattern) if (existsSync(resolvedPattern)) { this.projectPath = Config.findProjectRootSync(resolvedPattern) } } } protected adjustPattern(pattern: string | undefined, configGlobPatterns: string[]): string { if (!pattern) { return configGlobPatterns.length === 1 ? configGlobPatterns[0] : `{${configGlobPatterns.join(',')}}` } const resolvedPattern = resolve(pattern) if (existsSync(resolvedPattern)) { const stats = statSync(resolvedPattern) if (stats.isDirectory()) { const relativeDir = relative(this.projectPath, resolvedPattern) if (relativeDir) { const scopedPatterns = configGlobPatterns.map(pattern => `${relativeDir}/${pattern}`) return scopedPatterns.length === 1 ? scopedPatterns[0] : `{${scopedPatterns.join(',')}}` } return configGlobPatterns.length === 1 ? configGlobPatterns[0] : `{${configGlobPatterns.join(',')}}` } else if (stats.isFile()) { return relative(this.projectPath, resolvedPattern) } } return pattern } protected async resolvePatternToFiles(pattern: string, config: Config, force: boolean, formatOption: FormatOption): Promise<{ files: string[], explicitFile: string | undefined }> { const resolvedPattern = resolve(pattern) const isExplicitFile = existsSync(resolvedPattern) && statSync(resolvedPattern).isFile() let explicitFile: string | undefined if (isExplicitFile) { explicitFile = pattern } const filesConfig = config.getFilesConfigForTool('linter') const configGlobPatterns = filesConfig.include && filesConfig.include.length > 0 ? filesConfig.include : ['**/*.html.erb'] const adjustedPattern = this.adjustPattern(pattern, configGlobPatterns) let files = await glob(adjustedPattern, { cwd: this.projectPath, ignore: filesConfig.exclude || [] }) files.sort() if (explicitFile && files.length === 0) { if (!force) { this.exitWithInfo(`⚠️ File ${explicitFile} is excluded by configuration patterns. Use --force to lint it anyway.`, formatOption) } else { console.error(`⚠️ Forcing linter on excluded file: ${explicitFile}`) console.error() files = [adjustedPattern] } } return { files, explicitFile } } protected rejectUnsupportedFiles(files: string[], config: Config, force: boolean, formatOption: FormatOption): string[] { if (force) { return files } const supported = files.filter(file => config.isPathIncludedForTool(file, 'linter')) const unsupported = files.filter(file => !config.isPathIncludedForTool(file, 'linter')) if (unsupported.length > 0 && !isStructuredFormat(formatOption)) { console.error(`⚠️ Skipped ${unsupported.length} ${unsupported.length === 1 ? 'file' : 'files'} that ${unsupported.length === 1 ? "doesn't" : "don't"} match the configured file patterns:`) for (const file of unsupported) { console.error(` ${colorize(relative(process.cwd(), resolve(file)), "cyan")}`) } console.error(` Use --force to lint ${unsupported.length === 1 ? 'it' : 'them'} anyway.\n`) } return supported } protected async resolveFiles(patterns: string[], config: Config, force: boolean, formatOption: FormatOption): Promise { if (patterns.length === 0) { return await config.findFilesForTool('linter', this.projectPath) } const allFiles: string[] = [] for (const pattern of patterns) { const { files: patternFiles } = await this.resolvePatternToFiles(pattern, config, force, formatOption) if (patternFiles.length === 0) { console.error(`✗ No files found matching pattern: ${pattern}`) process.exit(1) } allFiles.push(...patternFiles) } return this.rejectUnsupportedFiles([...new Set(allFiles)], config, force, formatOption) } protected async beforeProcess(): Promise { // Hook for subclasses to add custom output before processing } protected additionalRuleNames(): string[] { return [] } protected async afterProcess(_results: any, _outputOptions: any): Promise { // Hook for subclasses to add custom output after processing } /** * Returns the severity `--only` or `--all-rules` should lower the log level to, together with the flag * that asked for it, or `undefined` when the log level stays as configured. */ protected loweredLogLevel(counts: Record, effectiveLogLevel: DiagnosticSeverity, options: { only?: string[], allRules?: boolean, logLevelFlag?: DiagnosticSeverity }): { severity: DiagnosticSeverity, flag: RuleFilterFlag } | undefined { const { only, allRules, logLevelFlag } = options const flag: RuleFilterFlag | undefined = (only && only.length > 0) ? "--only" : (allRules ? "--all-rules" : undefined) if (!flag) return undefined if (logLevelFlag !== undefined) return undefined const lowestSeverity = DIAGNOSTIC_SEVERITIES.filter(severity => counts[severity] > 0).pop() if (!lowestSeverity) return undefined if (meetsSeverityThreshold(lowestSeverity, effectiveLogLevel)) return undefined return { severity: lowestSeverity, flag } } async run() { await Herb.load() const startTime = Date.now() const startDate = new Date() const { patterns, configFile, formatOption, outputs, showTiming, theme, wrapLines, truncateLines, showFixDiff, useGitHubActions, fix, fixUnsafe, ignoreDisableComments, updateCounters, force, init, upgrade, disableFailing, loadCustomRules, failLevel, logLevel, jobs, only, allRules } = this.argumentParser.parse(process.argv) this.outputs = outputs this.determineProjectPath(patterns) if (init) { const configPath = configFile || this.projectPath if (Config.exists(configPath)) { const fullPath = configFile || Config.configPathFromProjectPath(this.projectPath) console.error(`\n✗ Configuration file already exists at ${fullPath}`) console.error(` Use --config-file to specify a different location.\n`) process.exit(1) } const config = await Config.loadForCLI(configPath, version, true) const extensionAdded = addHerbExtensionRecommendation(this.projectPath) console.log(`\n✓ Configuration initialized at ${config.path}`) if (extensionAdded) { console.log(`✓ VSCode extension recommended in ${getExtensionsJsonRelativePath()}`) } console.log(` Edit this file to customize linter and formatter settings.\n`) process.exit(0) } if (upgrade) { const configPath = configFile || this.projectPath if (!Config.exists(configPath)) { console.error(`\n✗ No .herb.yml found. Run ${colorize("herb-lint --init", "cyan")} first.\n`) process.exit(1) } const config = await Config.load(configPath, { version, exitOnError: true, createIfMissing: false, silent: true }) const configVersion = config.configVersion if (configVersion === version) { console.log(`\n✓ Your .herb.yml is already at version ${version}. Nothing to upgrade.\n`) process.exit(0) } const { skippedByVersion } = Linter.filterRulesByConfig(rules, config.linter?.rules, configVersion) let rulesToDisable: typeof skippedByVersion = [] let rulesToEnable: typeof skippedByVersion = [] const ruleOffenseCounts = new Map() if (skippedByVersion.length > 0) { console.log(`\n${colorize("↻", "cyan")} Checking ${colorize(String(skippedByVersion.length), "bold")} new ${skippedByVersion.length === 1 ? "rule" : "rules"} against your codebase...`) const skippedRulesConfig: Record = {} for (const rule of skippedByVersion) { skippedRulesConfig[rule.ruleName] = { enabled: true } } const upgradeConfig = Config.fromObject({ ...config.options, linter: { ...config.options.linter, rules: { ...config.options.linter?.rules, ...skippedRulesConfig } } }, { projectPath: this.projectPath, configVersion: version }) const upgradeContext: ProcessingContext = { projectPath: this.projectPath, config: upgradeConfig, jobs: 1, } await Herb.load() const files = await config.findFilesForTool('linter', this.projectPath) const results = await this.fileProcessor.processFiles(files, 'json', upgradeContext) for (const { offense } of results.allOffenses) { if (offense.severity !== "error" && offense.severity !== "warning") continue const ruleName = offense.code || "" ruleOffenseCounts.set(ruleName, (ruleOffenseCounts.get(ruleName) || 0) + 1) } rulesToDisable = skippedByVersion.filter(rule => ruleOffenseCounts.has(rule.ruleName)) rulesToEnable = skippedByVersion.filter(rule => !ruleOffenseCounts.has(rule.ruleName)) const rulesMutation: Record = {} for (const rule of rulesToDisable) { rulesMutation[rule.ruleName] = { enabled: false } } if (Object.keys(rulesMutation).length > 0) { await Config.mutateConfigFile(config.path, { linter: { rules: rulesMutation } }) } } const { promises: fs } = await import("fs") let content = await fs.readFile(config.path, "utf-8") content = content.replace(/^version:\s*.+$/m, `version: ${version}`) await fs.writeFile(config.path, content, "utf-8") console.log(`\n${colorize("✓", "brightGreen")} Updated ${colorize(".herb.yml", "cyan")} version from ${colorize(configVersion ?? "unversioned", "cyan")} to ${colorize(version, "cyan")}`) if (rulesToEnable.length > 0) { console.log(`\n${colorize("✓", "brightGreen")} Enabled ${colorize(String(rulesToEnable.length), "bold")} new ${rulesToEnable.length === 1 ? "rule" : "rules"} (no offenses found):\n`) for (const rule of rulesToEnable) { console.log(` ${colorize("✓", "brightGreen")} ${colorize(rule.ruleName, "white")}`) } } if (rulesToDisable.length > 0) { const totalOffenses = Array.from(ruleOffenseCounts.values()).reduce((sum, count) => sum + count, 0) console.log(`\n${colorize("!", "yellow")} Found ${colorize(String(totalOffenses), "bold")} ${totalOffenses === 1 ? "offense" : "offenses"} across ${colorize(String(rulesToDisable.length), "bold")} new ${rulesToDisable.length === 1 ? "rule" : "rules"}. Disabled to ease the upgrade:\n`) for (const rule of rulesToDisable) { const offenseCount = ruleOffenseCounts.get(rule.ruleName) || 0 console.log(` ${colorize("✗", "red")} ${colorize(rule.ruleName, "white")} ${colorize(`(${offenseCount} ${offenseCount === 1 ? "offense" : "offenses"})`, "gray")}`) } console.log(`\n When you're ready, review the disabled ${rulesToDisable.length === 1 ? "rule" : "rules"} in your ${colorize(".herb.yml", "cyan")} and re-enable them after fixing the offenses.`) } if (skippedByVersion.length === 0) { console.log(`\n${colorize("✓", "brightGreen")} No new rules to configure.`) } console.log("") process.exit(0) } if (disableFailing) { const configPath = configFile || this.projectPath if (!Config.exists(configPath)) { console.error(`\n✗ No .herb.yml found. Run ${colorize("herb-lint --init", "cyan")} first.\n`) process.exit(1) } const config = await Config.load(configPath, { version, exitOnError: true, createIfMissing: false, silent: true }) console.log(`\n${colorize("↻", "cyan")} Linting codebase to find rules with offenses...`) await Herb.load() const files = await this.resolveFiles(patterns, config, force, formatOption) const disableFailingContext: ProcessingContext = { projectPath: this.projectPath, config, jobs, } const results = await this.fileProcessor.processFiles(files, 'json', disableFailingContext) const failingRules = new Map() const PROTECTED_RULES = new Set(["parser-no-errors"]) for (const { offense } of results.allOffenses) { if (PROTECTED_RULES.has(offense.code || "")) continue if (offense.severity !== "error" && offense.severity !== "warning") continue failingRules.set(offense.code || "", (failingRules.get(offense.code || "") || 0) + 1) } if (failingRules.size === 0) { console.log(`\n${colorize("✓", "brightGreen")} No offenses found. All rules are passing!\n`) process.exit(0) } const rulesMutation: Record = {} for (const ruleName of failingRules.keys()) { rulesMutation[ruleName] = { enabled: false } } await Config.mutateConfigFile(config.path, { linter: { rules: rulesMutation } }) const totalOffenses = Array.from(failingRules.values()).reduce((sum, count) => sum + count, 0) const sortedRules = Array.from(failingRules.entries()).sort((a, b) => b[1] - a[1]) console.log(`\n${colorize("!", "yellow")} Found ${colorize(String(totalOffenses), "bold")} ${totalOffenses === 1 ? "offense" : "offenses"} across ${colorize(String(failingRules.size), "bold")} ${failingRules.size === 1 ? "rule" : "rules"}. Disabled in ${colorize(".herb.yml", "cyan")}:\n`) for (const [ruleName, count] of sortedRules) { console.log(` ${colorize("✗", "red")} ${colorize(ruleName, "white")} ${colorize(`(${count} ${count === 1 ? "offense" : "offenses"})`, "gray")}`) } console.log(`\n When you're ready, review the disabled rules in your ${colorize(".herb.yml", "cyan")} and re-enable them after fixing the offenses.\n`) process.exit(0) } if (updateCounters) { const configPath = configFile || this.projectPath if (!Config.exists(configPath)) { console.error(`\n✗ No .herb.yml found. Run ${colorize("herb-lint --init", "cyan")} first.\n`) process.exit(1) } const loadedConfig = await Config.load(configPath, { version, exitOnError: true, createIfMissing: false, silent: true }) console.log(`\n${colorize("↻", "cyan")} Reconciling file-scoped <%# herb:disable rule N %> counts...`) await Herb.load() const files = await this.resolveFiles(patterns, loadedConfig, force, formatOption) let customRules: RuleClass[] | undefined = undefined if (loadCustomRules) { try { const result = await loadCustomRulesFromDisk({ baseDir: this.projectPath, silent: true }) customRules = result.rules } catch { // Ignore custom rule loading failures — updateCounters skips unknown rules. } } const linter = Linter.from(Herb, loadedConfig, customRules, { all: false }) const { readFileSync, writeFileSync } = await import("node:fs") const { resolve } = await import("node:path") let filesTouched = 0 let totalRewritten = 0 let totalDeleted = 0 for (const filename of files) { const filePath = resolve(this.projectPath, filename) const content = readFileSync(filePath, "utf-8") const { source: updated, rewritten, deleted } = linter.updateCounters(content, { fileName: filename, projectPath: this.projectPath, }) if (updated !== content) { writeFileSync(filePath, updated, "utf-8") filesTouched++ totalRewritten += rewritten totalDeleted += deleted } } const parts: string[] = [] if (totalRewritten > 0) parts.push(`${totalRewritten} updated`) if (totalDeleted > 0) parts.push(`${totalDeleted} removed`) if (parts.length === 0) { console.log(`\n${colorize("✓", "brightGreen")} All file-scoped <%# herb:disable %> counts already match. Nothing to update.\n`) } else { console.log(`\n${colorize("✓", "brightGreen")} Reconciled ${parts.join(", ")} across ${filesTouched} ${filesTouched === 1 ? "file" : "files"}.\n`) } process.exit(0) } const silent = isStructuredFormat(formatOption) const writesReport = silent || outputs.some(output => output.path !== undefined) let config: Config try { config = await Config.load(configFile || this.projectPath, { version, exitOnError: !writesReport, createIfMissing: false, silent }) } catch (error) { this.exitWithError(`✗ ${error instanceof Error ? error.message : error}`, formatOption) } const linterConfig = config.options.linter || {} const effectiveFailLevel = failLevel || linterConfig.failLevel || "error" const effectiveLogLevel = logLevel || linterConfig.logLevel || "hint" const hasLogLevel = logLevel !== undefined || linterConfig.logLevel !== undefined const outputOptions = { formatOption, outputs, theme, wrapLines, truncateLines, showTiming, useGitHubActions, startTime, startDate, toolVersion: version, failLevel: effectiveFailLevel, logLevel: effectiveLogLevel } try { await this.beforeProcess() if (linterConfig.enabled === false && !force) { this.exitWithInfo("Linter is disabled in .herb.yml configuration. Use --force to lint anyway.", formatOption, 0, { startTime, startDate, showTiming }) } if (force && linterConfig.enabled === false) { console.error("⚠️ Forcing linter run (disabled in .herb.yml)") console.error() } if (only) { const unknownRules = await this.fileProcessor.findUnknownRules(only, { projectPath: this.projectPath, loadCustomRules }, formatOption, this.additionalRuleNames()) if (unknownRules.length > 0) { const messages = unknownRules.map(({ name, suggestion }) => { const suggestionText = suggestion ? ` Did you mean ${colorize(suggestion, "cyan")}?` : "" return `✗ Unknown rule ${colorize(name, "cyan")} passed to --only.${suggestionText}` }) this.exitWithError(messages.join("\n"), formatOption) } } let files: string[] const explicitFiles: string[] = [] if (patterns.length === 0) { files = await config.findFilesForTool('linter', this.projectPath) } else { const allFiles: string[] = [] for (const pattern of patterns) { const { files: patternFiles, explicitFile } = await this.resolvePatternToFiles(pattern, config, force, formatOption) if (patternFiles.length === 0) { this.exitWithError(`✗ No files found matching pattern: ${pattern}`, formatOption) } allFiles.push(...patternFiles) if (explicitFile) { explicitFiles.push(explicitFile) } } files = this.rejectUnsupportedFiles([...new Set(allFiles)], config, force, formatOption) } if (files.length === 0) { this.exitWithInfo(`No files found matching patterns: ${patterns.join(', ') || 'from config'}`, formatOption, 0, { startTime, startDate, showTiming }) } if (files.length > 1 && !isStructuredFormat(formatOption) && !useGitHubActions) { console.error(colorize(`Found ${files.length} files, linting...`, "gray")) } let processingConfig = config if (force && explicitFiles.length > 0) { const modifiedConfig = Object.create(Object.getPrototypeOf(config)) Object.assign(modifiedConfig, config) modifiedConfig.config = { ...config.config, linter: { ...config.config.linter, exclude: [] } } processingConfig = modifiedConfig } const hasConfigFile = Config.exists(configFile || this.projectPath) const context: ProcessingContext = { projectPath: this.projectPath, configPath: configFile, pattern: patterns.join(' '), fix, fixUnsafe, ignoreDisableComments, showFixDiff, linterConfig, config: processingConfig, hasConfigFile, loadCustomRules, jobs, only, allRules } const results = await this.fileProcessor.processFiles(files, formatOption, context) const counts: Record = { error: results.totalErrors, warning: results.totalWarnings, info: results.totalInfo, hint: results.totalHints } const lowered = this.loweredLogLevel(counts, effectiveLogLevel, { only, allRules, logLevelFlag: logLevel }) await this.outputManager.outputResults({ ...results, files }, { ...outputOptions, logLevel: lowered?.severity ?? effectiveLogLevel, logLevelLoweredFrom: lowered ? effectiveLogLevel : undefined, logLevelLoweredBy: lowered?.flag }) const showTips = !isStructuredFormat(formatOption) && !useGitHubActions if (!Config.exists(this.projectPath) && showTips) { console.log("") console.log(` ${colorize("TIP:", "bold")} Run ${colorize("herb-lint --init", "cyan")} to create a ${colorize(".herb.yml", "cyan")} and lock the ${colorize("version", "cyan")}.`) console.log(` This ensures upgrading Herb won't enable new rules until you update the ${colorize("version", "cyan")} in ${colorize(".herb.yml", "cyan")}.`) } const notFailingSeverities = DIAGNOSTIC_SEVERITIES.filter(severity => !meetsSeverityThreshold(severity, effectiveFailLevel) && counts[severity] > 0) const notFailingCount = notFailingSeverities.reduce((sum, severity) => sum + counts[severity], 0) const lowestNotFailingSeverity = notFailingSeverities[notFailingSeverities.length - 1] // TODO: once we have `yerba` and the config mutation features on the JavaScript // side, offer to write `linter.logLevel` into `.herb.yml` from here instead of // asking the user to edit it by hand. if (showTips && !hasLogLevel && notFailingCount > NOT_FAILING_TIP_THRESHOLD) { console.log("") console.log(` ${colorize("TIP:", "bold")} ${colorize(String(notFailingCount), "bold")} of the logged offenses don't fail the build.`) console.log(` Run ${colorize(`herb-lint --log-level=${effectiveFailLevel}`, "cyan")} to stop logging them, or set ${colorize("linter.logLevel", "cyan")} in your ${colorize(".herb.yml", "cyan")}.`) console.log(` To start enforcing them instead, set ${colorize("linter.failLevel", "cyan")} to ${colorize(lowestNotFailingSeverity, "cyan")} in your ${colorize(".herb.yml", "cyan")}.`) } await this.afterProcess(results, outputOptions) const shouldFail = DIAGNOSTIC_SEVERITIES.some(severity => counts[severity] > 0 && meetsSeverityThreshold(severity, effectiveFailLevel)) if (shouldFail) { process.exitCode = 1 } } catch (error) { this.exitWithError(`Error: ${error}`, formatOption) } } }