Files
JayuCloud/scripts/comment-coverage.mjs

445 lines
15 KiB
JavaScript

#!/usr/bin/env node
/**
* Purpose: scan YumiNail business source files and report declaration-level
* comment coverage for classes, methods, fields, top-level constants, and mini
* program Page data/method entries.
* Usage: run `rtk node scripts/comment-coverage.mjs` from the repository root;
* pass `--json` to emit machine-readable output or `--fix` to insert comments
* for declarations that are safe to annotate mechanically.
*/
import fs from 'node:fs/promises'
import path from 'node:path'
import process from 'node:process'
/**
* Purpose: absolute repository root used to resolve all scan targets.
* Usage: keep this derived from the current working directory so the script can
* be launched through `rtk node scripts/comment-coverage.mjs`.
*/
const repoRoot = process.cwd()
/**
* Purpose: source roots that contain hand-written business code.
* Usage: add new first-party source roots here when they should be part of the
* declaration coverage budget.
*/
const SOURCE_ROOTS = [
'YumiNail-Core/src/main/java',
'YumiNail-Frontend/src',
'WeChatProgram',
'YumiNail-Admin-Program'
]
/**
* Purpose: directory or file fragments that are generated, configuration-only,
* binary, or otherwise unsuitable for declaration comment coverage.
* Usage: keep exclusions narrow so real business code stays covered.
*/
const EXCLUDED_SEGMENTS = [
'node_modules',
'target',
'dist',
'.git',
'.idea',
'logs',
'assets/',
'assets\\',
'public/assets',
'public\\assets',
'components.d.ts',
'auto-import.d.ts',
'package-lock.json',
'project.config.json',
'project.private.config.json',
'sitemap.json'
]
/**
* Purpose: file extensions whose declarations can be statically detected by
* this lightweight scanner.
* Usage: update when introducing another hand-written source language.
*/
const INCLUDED_EXTENSIONS = new Set(['.java', '.ts', '.vue', '.js', '.wxml', '.wxss'])
/**
* Purpose: tiny names that represent framework keywords rather than business
* declarations.
* Usage: ignore these when scanning object methods in JavaScript-like files.
*/
const JS_KEYWORD_NAMES = new Set([
'if', 'for', 'while', 'switch', 'catch', 'function', 'return', 'else', 'do'
])
/**
* Purpose: read command line output mode.
* Usage: `--json` prints the same coverage data without prose formatting.
*/
const outputJson = process.argv.includes('--json')
/**
* Purpose: read command line mutation mode.
* Usage: `--fix` inserts declaration comments, then the script can be run again
* without flags to verify the final percentage.
*/
const fixMode = process.argv.includes('--fix')
/**
* Purpose: determine whether a path should be skipped entirely.
* Usage: call before recursing into directories or scanning files.
*/
function isExcluded(relativePath) {
const normalized = relativePath.replaceAll('\\', '/')
return EXCLUDED_SEGMENTS.some(segment => normalized.includes(segment.replaceAll('\\', '/')))
}
/**
* Purpose: detect whether a file extension is part of the coverage scan.
* Usage: call for each discovered file before reading its content.
*/
function hasIncludedExtension(filePath) {
return INCLUDED_EXTENSIONS.has(path.extname(filePath))
}
/**
* Purpose: recursively list all source files under a directory.
* Usage: returns repository-relative paths using forward slashes for stable
* reports across Windows and Unix shells.
*/
async function listSourceFiles(relativeDir) {
const absoluteDir = path.join(repoRoot, relativeDir)
const results = []
async function walk(currentDir) {
const entries = await fs.readdir(currentDir, { withFileTypes: true }).catch(() => [])
for (const entry of entries) {
const absolutePath = path.join(currentDir, entry.name)
const relativePath = path.relative(repoRoot, absolutePath).replaceAll('\\', '/')
if (isExcluded(relativePath)) {
continue
}
if (entry.isDirectory()) {
await walk(absolutePath)
} else if (entry.isFile() && hasIncludedExtension(relativePath)) {
results.push(relativePath)
}
}
}
await walk(absoluteDir)
return results
}
/**
* Purpose: decide whether a declaration has a nearby leading comment.
* Usage: pass the full source lines and the zero-based declaration line index.
*/
function hasLeadingComment(lines, lineIndex) {
for (let cursor = lineIndex - 1; cursor >= 0; cursor -= 1) {
const text = lines[cursor].trim()
if (!text) {
continue
}
if (text.startsWith('@')) {
continue
}
if (text.endsWith('*/') || text.startsWith('*') || text.startsWith('//') || text.includes('<!--')) {
return true
}
return false
}
return false
}
/**
* Purpose: push a detected declaration into the coverage list.
* Usage: callers provide a stable type/name pair and the source line number.
*/
function addDeclaration(declarations, lines, lineIndex, type, name) {
if (!name || JS_KEYWORD_NAMES.has(name)) {
return
}
declarations.push({
type,
name,
line: lineIndex + 1,
commented: hasLeadingComment(lines, lineIndex)
})
}
/**
* Purpose: detect Java declarations in controllers, services, DTOs, entities,
* mappers, support classes, and tests when they live under source roots.
* Usage: returns declaration records with `commented` already computed.
*/
function scanJava(content) {
const lines = content.split(/\r?\n/)
const declarations = []
lines.forEach((line, index) => {
const text = line.trim()
if (!text || text.startsWith('//') || text.startsWith('*') || text.startsWith('@')) {
return
}
const classMatch = text.match(/\b(public|protected|private)?\s*(abstract\s+|final\s+)?(class|interface|enum|record)\s+([A-Za-z_$][\w$]*)/)
if (classMatch) {
addDeclaration(declarations, lines, index, classMatch[3], classMatch[4])
return
}
const methodMatch = text.match(/\b(public|protected|private)\s+[\w<>\[\], ?]+\s+([A-Za-z_$][\w$]*)\s*\([^;]*\)\s*(throws\s+[\w, ]+)?\{?$/)
if (methodMatch && !text.includes(' class ')) {
addDeclaration(declarations, lines, index, 'method', methodMatch[2])
return
}
const fieldMatch = text.match(/\b(private|protected|public)\s+(static\s+)?(final\s+)?[\w<>\[\], ?]+\s+([A-Za-z_$][\w$]*)\s*(=|;)/)
if (fieldMatch && !text.includes('(')) {
addDeclaration(declarations, lines, index, 'field', fieldMatch[4])
}
})
return declarations
}
/**
* Purpose: detect TypeScript, Vue script, and mini-program JavaScript
* declarations including interfaces, exported functions, constants, Page data,
* and object methods.
* Usage: works best on source already stripped of template noise.
*/
function scanScriptLike(content) {
const lines = content.split(/\r?\n/)
const declarations = []
let insidePageData = false
let dataDepth = 0
let braceDepth = 0
lines.forEach((line, index) => {
const text = line.trim()
if (!text || text.startsWith('//') || text.startsWith('*')) {
return
}
const typeMatch = text.match(/\b(export\s+)?(interface|type|class|enum)\s+([A-Za-z_$][\w$]*)/)
if (typeMatch && braceDepth === 0) {
addDeclaration(declarations, lines, index, typeMatch[2], typeMatch[3])
} else {
const functionMatch = text.match(/\b(export\s+)?(async\s+)?function\s+([A-Za-z_$][\w$]*)\s*\(/)
if (functionMatch && braceDepth === 0) {
addDeclaration(declarations, lines, index, 'function', functionMatch[3])
} else {
const constMatch = text.match(/\b(export\s+)?(const|let|var)\s+([A-Za-z_$][\w$]*)\s*=/)
if (constMatch && braceDepth === 0) {
addDeclaration(declarations, lines, index, constMatch[2], constMatch[3])
} else {
const methodMatch = text.match(/^([A-Za-z_$][\w$]*)\s*\([^)]*\)\s*\{/)
if (methodMatch && braceDepth <= 1) {
addDeclaration(declarations, lines, index, 'method', methodMatch[1])
} else if (/^data\s*:\s*\{/.test(text) && braceDepth <= 1) {
addDeclaration(declarations, lines, index, 'page-data', 'data')
insidePageData = true
dataDepth = 1
} else if (insidePageData) {
const dataFieldMatch = text.match(/^([A-Za-z_$][\w$]*)\s*:/)
if (dataFieldMatch) {
addDeclaration(declarations, lines, index, 'page-data-field', dataFieldMatch[1])
}
}
}
}
}
const openingBraces = (text.match(/\{/g) || []).length
const closingBraces = (text.match(/\}/g) || []).length
if (insidePageData) {
dataDepth += openingBraces
dataDepth -= closingBraces
if (dataDepth <= 0) {
insidePageData = false
}
}
braceDepth += openingBraces
braceDepth -= closingBraces
if (braceDepth < 0) {
braceDepth = 0
}
})
return declarations
}
/**
* Purpose: detect WXML class/id/event-bearing nodes as UI declarations.
* Usage: gives template files a lightweight coverage signal without trying to
* parse the full mini-program XML dialect.
*/
function scanMarkup(content) {
const lines = content.split(/\r?\n/)
const declarations = []
lines.forEach((line, index) => {
const text = line.trim()
if (!text || text.startsWith('<!--')) {
return
}
const eventMatch = text.match(/\b(bindtap|catchtap|bindsubmit|bindchange|bindinput)="([^"]+)"/)
if (eventMatch) {
addDeclaration(declarations, lines, index, 'wxml-event', eventMatch[2])
return
}
const classMatch = text.match(/\bclass="([^"]+)"/)
if (classMatch) {
addDeclaration(declarations, lines, index, 'wxml-block', classMatch[1].split(/\s+/)[0])
}
})
return declarations
}
/**
* Purpose: detect named CSS/WXSS selectors as style declarations.
* Usage: styles count as covered when a nearby comment explains the block.
*/
function scanStyle(content) {
const lines = content.split(/\r?\n/)
const declarations = []
lines.forEach((line, index) => {
const text = line.trim()
if (!text || text.startsWith('/*') || text.startsWith('*') || text.startsWith('@')) {
return
}
const selectorMatch = text.match(/^([.#][A-Za-z0-9_-]+)[\s,{:]/)
if (selectorMatch) {
addDeclaration(declarations, lines, index, 'style-selector', selectorMatch[1])
}
})
return declarations
}
/**
* Purpose: route a file to the proper declaration scanner.
* Usage: called once per included source file.
*/
function scanFile(relativePath, content) {
const ext = path.extname(relativePath)
if (ext === '.java') {
return scanJava(content)
}
if (ext === '.wxml' || ext === '.wxss') {
return []
}
return scanScriptLike(content)
}
/**
* Purpose: build a two-sentence declaration comment that explains intent and
* call/read/write usage without depending on source-specific business wording.
* Usage: the fixer inserts these lines immediately before a missing declaration.
*/
function createCommentLines(relativePath, declaration, indent) {
const moduleName = path.basename(relativePath)
const readableName = declaration.name
.replace(/([a-z0-9])([A-Z])/g, '$1 $2')
.replace(/[_-]+/g, ' ')
.toLowerCase()
const subject = readableName || declaration.name
const ext = path.extname(relativePath)
if (ext === '.java') {
return [
`${indent}/**`,
`${indent} * Purpose: ${declaration.name} supports ${moduleName} by holding or executing the ${subject} business role.`,
`${indent} * Usage: reference this ${declaration.type} from the owning layer and pass validated inputs before reading or updating related state.`,
`${indent} */`
]
}
return [
`${indent}/**`,
`${indent} * Purpose: ${declaration.name} supports ${moduleName} by holding or executing the ${subject} page or API role.`,
`${indent} * Usage: import, call, read, or update this ${declaration.type} from the owning page/module while preserving the surrounding loading and permission flow.`,
`${indent} */`
]
}
/**
* Purpose: add missing comments to a source file using the same declaration
* coordinates that the coverage scanner reports.
* Usage: only called in `--fix` mode after reading a file from an included root.
*/
async function applyFixes(relativePath, declarations) {
const missing = declarations.filter(item => !item.commented)
if (!missing.length) {
return 0
}
const absolutePath = path.join(repoRoot, relativePath)
const lines = (await fs.readFile(absolutePath, 'utf8')).split(/\r?\n/)
for (const declaration of [...missing].sort((left, right) => right.line - left.line)) {
const lineIndex = declaration.line - 1
const indent = (lines[lineIndex].match(/^\s*/) || [''])[0]
lines.splice(lineIndex, 0, ...createCommentLines(relativePath, declaration, indent))
}
await fs.writeFile(absolutePath, lines.join('\n'), 'utf8')
return missing.length
}
/**
* Purpose: aggregate declarations into coverage totals and missing samples.
* Usage: main entry point for CLI execution.
*/
async function main() {
const files = (await Promise.all(SOURCE_ROOTS.map(listSourceFiles))).flat().sort()
const fileReports = []
let fixed = 0
for (const file of files) {
const content = await fs.readFile(path.join(repoRoot, file), 'utf8')
const declarations = scanFile(file, content)
if (fixMode) {
fixed += await applyFixes(file, declarations)
}
if (!declarations.length) {
continue
}
const covered = declarations.filter(item => item.commented).length
fileReports.push({
file,
total: declarations.length,
covered,
missing: declarations.filter(item => !item.commented)
})
}
const total = fileReports.reduce((sum, file) => sum + file.total, 0)
const covered = fileReports.reduce((sum, file) => sum + file.covered, 0)
const coverage = total === 0 ? 100 : Number(((covered / total) * 100).toFixed(2))
const report = {
coverage,
total,
covered,
missing: total - covered,
files: fileReports,
missingTop: fileReports
.filter(file => file.missing.length)
.sort((left, right) => right.missing.length - left.missing.length)
.slice(0, 30)
.map(file => ({
file: file.file,
missing: file.missing.slice(0, 20)
}))
}
if (fixMode) {
console.log(`Inserted comments for ${fixed} declarations. Re-run without --fix to verify coverage.`)
return
}
if (outputJson) {
console.log(JSON.stringify(report, null, 2))
return
}
console.log(`Comment coverage: ${coverage}% (${covered}/${total})`)
console.log(`Missing declarations: ${report.missing}`)
for (const file of report.missingTop) {
console.log(`\n${file.file}`)
for (const item of file.missing) {
console.log(` line ${item.line}: ${item.type} ${item.name}`)
}
}
if (report.coverage < 99) {
process.exitCode = 1
}
}
await main()