#!/usr/bin/env node const fs = require('fs') const path = require('path') const { execFileSync } = require('child_process') const ROOT = path.resolve(__dirname, '..') const BASELINE = path.join(ROOT, '.comment-baseline.json') const ts = require( require.resolve('typescript', { paths: [ROOT, process.env.TS_PATH].filter(Boolean) }) ) const SOURCE_GLOBS = ['*.ts', '*.tsx', '*.js', '*.jsx', '*.mjs', '*.cjs'] const GENERATED = [ /^packages\/sdk\/src\/sdk\/api\/generated\//, /^packages\/docs\/build\//, /^packages\/sql-ts\/res\//, /\/public\//, /\.min\.js$/ ] const PUBLIC_API_DOCS = /^packages\/(sdk|harmony|fixed-decimal|spl)\// const TUTORIAL = /\/examples\// const DIRECTIVE = /^\s*(\/\/|\/\*+)\s*(eslint|@ts-|prettier-ignore|istanbul|c8 |webpackChunkName|webpackIgnore|@vite-ignore|globals? |jshint|@jsx|@refresh|#region|#endregion|biome-ignore|\/\s* DIRECTIVE.test(body) || LICENSE.test(body.slice(0, 200)) || (body.startsWith('/**') && PUBLIC_API_DOCS.test(file)) || body.startsWith('#!') || /@deprecated\b/.test(body) || /DO NOT EDIT|auto-?generated by/i.test(body) || /^\/\*+\s*\*?\s*@format\b/.test(body) || (/\.[cm]?jsx?$/.test(file) && /@(type|typedef|param|returns?|satisfies)\s*\{/.test(body)) || TUTORIAL.test(file) const scriptKind = (file) => { if (file.endsWith('.tsx')) return ts.ScriptKind.TSX if (file.endsWith('.ts')) return ts.ScriptKind.TS return ts.ScriptKind.JSX } const extractComments = (file, text) => { const sf = ts.createSourceFile( file, text, ts.ScriptTarget.Latest, false, scriptKind(file) ) const ranges = new Map() const add = (rs) => rs && rs.forEach((r) => ranges.set(r.pos, r)) const visit = (node) => { add(ts.getLeadingCommentRanges(text, node.pos)) add(ts.getTrailingCommentRanges(text, node.end)) if (ts.isJsxExpression(node) && !node.expression) { add(ts.getLeadingCommentRanges(text, node.pos + 1)) } node.forEachChild(visit) } visit(sf) add(ts.getLeadingCommentRanges(text, sf.endOfFileToken.pos)) const comments = [] let prev = null for (const r of [...ranges.values()].sort((a, b) => a.pos - b.pos)) { const body = text.slice(r.pos, r.end) const line = sf.getLineAndCharacterOfPosition(r.pos).line + 1 const endLine = sf.getLineAndCharacterOfPosition(r.end).line + 1 const lineStart = text.lastIndexOf('\n', r.pos - 1) + 1 const ownLine = /^\s*\{?\s*$/.test(text.slice(lineStart, r.pos)) const isLine = body.startsWith('//') const directive = DIRECTIVE.test(body) if ( prev && isLine && !directive && !prev.directive && ownLine && prev.isLine && prev.ownLine && line === prev.endLine + 1 ) { prev.body += '\n' + body prev.endLine = line prev.end = r.end continue } prev = { file, line, endLine, pos: r.pos, end: r.end, ownLine, isLine, directive, body } comments.push(prev) } return comments .filter((c) => !isExempt(file, c.body)) .map(({ directive, ...c }) => c) } const listFiles = (pathspecs) => execFileSync( 'git', ['ls-files', '--', ...(pathspecs.length ? pathspecs : ['.'])], { cwd: ROOT, maxBuffer: 1 << 28 } ) .toString() .split('\n') .filter( (f) => f && SOURCE_GLOBS.some((g) => f.endsWith(g.slice(1))) && !GENERATED.some((re) => re.test(f)) && fs.existsSync(path.join(ROOT, f)) ) const scan = (pathspecs) => { const byFile = {} for (const file of listFiles(pathspecs)) { const text = fs.readFileSync(path.join(ROOT, file), 'utf8') const comments = extractComments(file, text) if (comments.length) byFile[file] = comments } return byFile } const readBaseline = () => fs.existsSync(BASELINE) ? JSON.parse(fs.readFileSync(BASELINE, 'utf8')) : {} const writeBaseline = (baseline) => { const sorted = Object.fromEntries( Object.entries(baseline) .filter(([, n]) => n > 0) .sort(([a], [b]) => a.localeCompare(b)) ) fs.writeFileSync(BASELINE, JSON.stringify(sorted, null, 2) + '\n') } const lineCount = (comments) => comments.reduce((n, c) => n + c.endLine - c.line + 1, 0) const main = () => { const args = process.argv.slice(2) const flags = new Set(args.filter((a) => a.startsWith('--'))) const pathspecs = args.filter((a) => !a.startsWith('--')) if (flags.has('--list')) { const byFile = scan(pathspecs) for (const comments of Object.values(byFile)) { for (const c of comments) process.stdout.write(JSON.stringify(c) + '\n') } return } if (flags.has('--stats')) { const byFile = scan(pathspecs) const all = Object.values(byFile).flat() console.log( JSON.stringify( { files: Object.keys(byFile).length, comments: all.length, lines: lineCount(all) }, null, 2 ) ) return } const byFile = scan([]) const current = Object.fromEntries( Object.entries(byFile).map(([f, cs]) => [f, cs.length]) ) if (flags.has('--init')) { writeBaseline(current) console.log(`Wrote budgets for ${Object.keys(current).length} files`) return } const baseline = readBaseline() if (flags.has('--update')) { const next = {} for (const [file, budget] of Object.entries(baseline)) { next[file] = Math.min(budget, current[file] || 0) } writeBaseline(next) console.log('Lowered comment budgets to current counts') return } const over = [] const stale = [] for (const [file, count] of Object.entries(current)) { const budget = baseline[file] || 0 if (count > budget) over.push({ file, count, budget }) } for (const [file, budget] of Object.entries(baseline)) { if ((current[file] || 0) < budget) stale.push(file) } for (const { file, count, budget } of over) { console.error(`${file}: ${count} comments, budget ${budget}`) const fresh = byFile[file].slice(budget) for (const c of fresh) { console.error( ` ${file}:${c.line} ${c.body.split('\n')[0].slice(0, 100)}` ) } } if (over.length) { console.error( `\n${over.length} file(s) gained comments. Code should explain itself; ` + 'record non-obvious decisions in docs/adr/ instead. ' + 'Directives (eslint-disable, @ts-expect-error, ...) are allowed.' ) } if (stale.length) { console.error( `\n${stale.length} file(s) now have fewer comments than their budget. ` + 'Run `npm run lint:comments:update` and commit .comment-baseline.json.' ) } if (over.length || stale.length) process.exit(1) const total = Object.values(current).reduce((a, b) => a + b, 0) console.log(`Comment ratchet OK (${total} comments left in budget)`) } if (require.main === module) main() module.exports = { ROOT, extractComments, scan }