Template
把模板自带的 11 篇初版规则换成从知物项目(Trace)回迁的 19 篇 128 条基线, 并把配套工具链版本化,使规则一致性可被机器校验。 - 结构:采用 frontmatter + 四要素骨架,废弃每篇「更新记录」表,历史统一进 CHANGELOG - 三层分离:rules/ 仅模板可写、project.json 存项目参数、local-rules/ 放本地扩展 - 参数化 15 条:包名、主干分支、临时目录、日志 domain/tag、DevEco 路径、语言集等外置到 project.json - 删除 ENG-008(云函数凭据切换,模板无云函数),以 frontmatter retired 标记、编号不复用 - 工具链:INDEX 改由 frontmatter + 正文标题生成;校验器新增来源词表、退役编号、local-rules 登记一致性;pre-commit 改走 core.hooksPath - 无 ArkTS 源码时代码规则检查显式跳过,verify-doc-ids 环境不可用即中止且不回写白名单 校验:gen + check 零错误零告警;check --diff 通过;check-code-rules 按预期跳过。
180 lines
7.5 KiB
JavaScript
180 lines
7.5 KiB
JavaScript
#!/usr/bin/env node
|
||
/**
|
||
* 规则即测试(policy as code):把可静态检测的红线直接扫代码,不依赖 agent 自觉。
|
||
*
|
||
* 只覆盖**高精度、低误报**的条款;其余条款仍由 rules/ 文档 + Code Review 承担。
|
||
* 检测项:
|
||
* ATY-001 禁止 any / unknown / as unknown as
|
||
* ARK-006 禁止 var / for..in / delete / #私有字段 / @ts-ignore / @ts-nocheck
|
||
* LOG-002 生产代码禁止 console.*(排除 test/ohosTest/mock)
|
||
* CMP-002 禁止使用不存在的枚举 SwipeItemState(应为 SwipeActionState)
|
||
* SM-003 同一组件内禁止 V1/V2 装饰器混用
|
||
* NET-001 使用 @kit.NetworkKit 时必须在 module.json5 声明 ohos.permission.INTERNET
|
||
*
|
||
* 用法:
|
||
* node tools/check-code-rules.mjs [--paths entry/src/main/ets] [--quiet]
|
||
* 默认扫描目录取自 project.json 的 codeScanDirs;目录不存在时打印跳过并 exit 0
|
||
* (模板仓库本身不含 ArkTS 源码,克隆为项目后才需要它生效)。
|
||
* 退出码:0 = 无违规或无需检查;1 = 存在违规(供 pre-commit / CI 使用)。
|
||
*/
|
||
import { readFileSync, readdirSync, statSync, existsSync } from 'node:fs';
|
||
import { join, dirname, extname } from 'node:path';
|
||
import { fileURLToPath } from 'node:url';
|
||
|
||
const ROOT = dirname(dirname(fileURLToPath(import.meta.url)));
|
||
const argv = process.argv.slice(2);
|
||
const QUIET = argv.includes('--quiet');
|
||
|
||
/** 项目参数(project.json):包名、扫描目录等一律从这里取,脚本内不写死 */
|
||
const PROJECT_FILE = join(ROOT, 'project.json');
|
||
let project = {};
|
||
if (existsSync(PROJECT_FILE)) {
|
||
try {
|
||
project = JSON.parse(readFileSync(PROJECT_FILE, 'utf8'));
|
||
} catch (e) {
|
||
console.error(`[fatal] project.json 解析失败:${e.message}`);
|
||
process.exit(1);
|
||
}
|
||
}
|
||
const DEFAULT_SCAN_DIRS = (Array.isArray(project.codeScanDirs) && project.codeScanDirs.length)
|
||
? project.codeScanDirs
|
||
: ['entry/src/main/ets'];
|
||
|
||
const pathsIdx = argv.indexOf('--paths');
|
||
const SCAN_DIRS = (pathsIdx >= 0 && argv[pathsIdx + 1] ? argv[pathsIdx + 1].split(',') : DEFAULT_SCAN_DIRS)
|
||
.map(p => join(ROOT, p));
|
||
|
||
const SKIP_DIR = /[\\/](build|oh_modules|node_modules|\.git|\.preview|test|ohosTest|mock)[\\/]/;
|
||
|
||
/** 逐行规则:{ id, hint, re, skipComment } */
|
||
const LINE_RULES = [
|
||
{ id: 'ATY-001', hint: '禁止 any / unknown;改用具体类型、Object 或联合类型', re: /(:\s*(any|unknown)\b)|(as\s+unknown\s+as\b)|(<\s*(any|unknown)\s*>)/ },
|
||
{ id: 'ARK-006', hint: '禁止 var / for..in / delete / # 私有字段 / @ts-ignore;改用 let、Object.keys、private、显式类型', re: /(\bvar\s+[A-Za-z_$])|(for\s*\(\s*(const|let)\s+[A-Za-z_$][\w$]*\s+in\s)|(\bdelete\s+[A-Za-z_$][\w$]*\s*\.)|(^\s*#\w+\s*[:=])|(@ts-ignore|@ts-nocheck)/ },
|
||
{ id: 'CMP-002', hint: 'SwipeItemState 不存在,应为 SwipeActionState(且 onStateChange 属 swipeAction 配置项)', re: /\bSwipeItemState\b/ },
|
||
];
|
||
|
||
/** 全文件规则:{ id, hint, test(src) } */
|
||
const FILE_RULES = [
|
||
{
|
||
id: 'LOG-002',
|
||
hint: '生产代码禁止 console.*;改用 hilog(自定义 domain/tag)',
|
||
test: (src) => {
|
||
const hits = [];
|
||
src.split(/\r?\n/).forEach((line, i) => {
|
||
if (/^\s*(\/\/|\*|\/\*)/.test(line)) return;
|
||
if (/console\.(log|info|warn|error|debug|trace)\s*\(/.test(line)) hits.push({ line: i + 1, text: line.trim() });
|
||
});
|
||
return hits;
|
||
},
|
||
},
|
||
{
|
||
id: 'SM-003',
|
||
hint: '禁止 V1/V2 装饰器混用:@Component 内不得出现 V2 装饰器,@ComponentV2 内不得出现 V1 装饰器',
|
||
test: (src) => {
|
||
const V2 = /@(Local|Param|Event|Monitor|Computed|Provider|Consumer)\b/;
|
||
const V1 = /@(State|Prop|Link|Watch|Provide|Consume|ObjectLink|Observed|Reusable)\b(?!V2)/;
|
||
const lines = src.split(/\r?\n/);
|
||
// 装饰器跨行:定位每个组件声明,扫描到下一个组件声明(或文件末尾)为"该组件块"
|
||
const marks = [];
|
||
lines.forEach((l, i) => {
|
||
if (/^\s*(\/\/|\*|\/\*)/.test(l)) return;
|
||
if (/@ComponentV2\b/.test(l)) marks.push({ line: i, kind: 'V2' });
|
||
else if (/@Component\b/.test(l)) marks.push({ line: i, kind: 'V1' });
|
||
});
|
||
const hits = [];
|
||
marks.forEach((m, k) => {
|
||
const end = (k + 1 < marks.length) ? marks[k + 1].line : lines.length;
|
||
const forbid = m.kind === 'V2' ? V1 : V2;
|
||
for (let i = m.line + 1; i < end; i++) {
|
||
const l = lines[i];
|
||
if (/^\s*(\/\/|\*|\/\*)/.test(l)) continue;
|
||
if (forbid.test(l)) {
|
||
hits.push({
|
||
line: i + 1,
|
||
text: `${m.kind === 'V2' ? 'V2 组件内出现 V1 装饰器' : 'V1 组件内出现 V2 装饰器'}:` + l.trim(),
|
||
});
|
||
}
|
||
}
|
||
});
|
||
return hits;
|
||
},
|
||
},
|
||
];
|
||
|
||
function walk(dir) {
|
||
if (!existsSync(dir)) return [];
|
||
const out = [];
|
||
for (const n of readdirSync(dir)) {
|
||
const p = join(dir, n);
|
||
if (SKIP_DIR.test(p + '\\')) continue;
|
||
if (statSync(p).isDirectory()) out.push(...walk(p));
|
||
else if (extname(p) === '.ets' || extname(p) === '.ts') out.push(p);
|
||
}
|
||
return out;
|
||
}
|
||
|
||
const findings = [];
|
||
|
||
/* 无源码目录时显式跳过:模板仓库不含 ArkTS 源码,本项检查对它是空转 */
|
||
const existingDirs = SCAN_DIRS.filter(d => existsSync(d));
|
||
if (existingDirs.length === 0) {
|
||
if (!QUIET) {
|
||
const shown = SCAN_DIRS.map(d => d.slice(ROOT.length + 1).replace(/\\/g, '/')).join(', ');
|
||
console.log(`[skip] 未找到源码目录(codeScanDirs: ${shown})——模板仓库不含 ArkTS 源码,跳过代码规则检查。`);
|
||
}
|
||
process.exit(0);
|
||
}
|
||
|
||
const files = SCAN_DIRS.flatMap(walk);
|
||
|
||
for (const abs of files) {
|
||
const rel = abs.slice(ROOT.length + 1).replace(/\\/g, '/');
|
||
const src = readFileSync(abs, 'utf8');
|
||
const lines = src.split(/\r?\n/);
|
||
|
||
lines.forEach((line, i) => {
|
||
if (/^\s*(\/\/|\*|\/\*)/.test(line)) return; // 跳过注释行(示例/说明不违规)
|
||
for (const r of LINE_RULES) {
|
||
if (r.re.test(line)) findings.push({ rel, line: i + 1, id: r.id, hint: r.hint, text: line.trim().slice(0, 100) });
|
||
}
|
||
});
|
||
|
||
for (const r of FILE_RULES) {
|
||
if (r.id === 'LOG-002' && SKIP_DIR.test(abs)) continue;
|
||
for (const h of r.test(src)) {
|
||
findings.push({ rel, line: h.line, id: r.id, hint: r.hint, text: h.text.slice(0, 100) });
|
||
}
|
||
}
|
||
}
|
||
|
||
/* NET-001:使用 NetworkKit 时必须声明 INTERNET 权限 */
|
||
const usesNet = files.some(f => /from\s+'@kit\.NetworkKit'/.test(readFileSync(f, 'utf8')));
|
||
if (usesNet) {
|
||
const modCandidates = [
|
||
...SCAN_DIRS.map(d => join(d, '..', 'module.json5')),
|
||
...SCAN_DIRS.map(d => join(d, 'module.json5')),
|
||
join(ROOT, 'entry/src/main/module.json5'),
|
||
];
|
||
const modJson = modCandidates.find(p => existsSync(p));
|
||
const declared = modJson ? /ohos\.permission\.INTERNET/.test(readFileSync(modJson, 'utf8')) : false;
|
||
if (!declared) {
|
||
findings.push({
|
||
rel: modJson ? modJson.slice(ROOT.length + 1).replace(/\\/g, '/') : 'entry/src/main/module.json5',
|
||
line: 1, id: 'NET-001', hint: '使用了 @kit.NetworkKit 但未声明 ohos.permission.INTERNET', text: '',
|
||
});
|
||
}
|
||
}
|
||
|
||
/* 输出 */
|
||
if (findings.length === 0) {
|
||
if (!QUIET) console.log(`[ok] 代码规则检查通过(扫描 ${files.length} 个文件)。`);
|
||
process.exit(0);
|
||
}
|
||
console.error(`代码规则检查发现 ${findings.length} 处违规(扫描 ${files.length} 个文件):`);
|
||
for (const f of findings) {
|
||
console.error(` [${f.id}] ${f.rel}:${f.line} ${f.text}`);
|
||
console.error(` → ${f.hint}`);
|
||
}
|
||
console.error('\n提示:这些条款已可由工具判定,修复后重跑;确认误报请提 issue 调整规则。');
|
||
process.exit(1);
|