readme-guide 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +46 -2
- package/bin/readme-guide.mjs +125 -0
- package/package.json +43 -4
- package/rules/blocks.json +123 -0
- package/rules/conventions.json +39 -0
- package/rules/headings.json +556 -0
- package/rules/project-types.json +37 -0
- package/rules/rules.json +3575 -0
- package/src/checks/ai.js +41 -0
- package/src/checks/commands.js +248 -0
- package/src/checks/env.js +112 -0
- package/src/checks/folders.js +138 -0
- package/src/checks/license.js +137 -0
- package/src/checks/media.js +110 -0
- package/src/checks/structure.js +248 -0
- package/src/checks/types.js +55 -0
- package/src/checks/util.js +148 -0
- package/src/checks/versions.js +109 -0
- package/src/data.js +76 -0
- package/src/detect.js +83 -0
- package/src/explain.js +150 -0
- package/src/format.js +153 -0
- package/src/lint.js +142 -0
- package/src/markdown.js +424 -0
- package/src/project.js +86 -0
- package/src/sections.js +167 -0
- package/src/semver.js +104 -0
|
@@ -0,0 +1,148 @@
|
|
|
1
|
+
// 規則共用的小工具。
|
|
2
|
+
import { isShellLanguage } from '../markdown.js';
|
|
3
|
+
import { stripPlaceholders } from '../data.js';
|
|
4
|
+
|
|
5
|
+
export const CJK_LETTER = /[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}]/u;
|
|
6
|
+
|
|
7
|
+
/** 跳脫成可以放進比對式的文字 */
|
|
8
|
+
export function escapeRegExp(text) {
|
|
9
|
+
return text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* 一般文字行(不含程式碼、註解、參照定義)。prose 是遮掉行內程式碼後的文字。
|
|
14
|
+
* @param {ReturnType<import('../markdown.js').parseMarkdown>} md
|
|
15
|
+
*/
|
|
16
|
+
export function proseLines(md) {
|
|
17
|
+
return md.lines.filter((l) => l.kind === 'text' && !l.definition && (!l.heading || l.heading.line === l.line));
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/** 一般文字行,保留行內程式碼的內容、只拿掉反引號 */
|
|
21
|
+
export function readableText(line) {
|
|
22
|
+
return line.raw.replace(/`/g, ' ');
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** 示範 Markdown 寫法的區塊(四個反引號,或裡面還有圍欄),內容不是真的指令 */
|
|
26
|
+
export function isDemoBlock(block) {
|
|
27
|
+
return (block.fence?.length ?? 3) > 3 || block.lines.some(({ text }) => /^\s*(?:`{3,}|~{3,})/.test(text));
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/** 會被貼到終端機執行的程式碼區塊 */
|
|
31
|
+
export function shellBlocks(md) {
|
|
32
|
+
return md.codeBlocks.filter((b) => isShellLanguage(b.lang) && !isDemoBlock(b));
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** 可能放指令的程式碼區塊:shell 類語言或沒標語言 */
|
|
36
|
+
export function commandBlocks(md) {
|
|
37
|
+
return md.codeBlocks.filter((b) => (isShellLanguage(b.lang) || b.lang === '') && !isDemoBlock(b));
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** 去掉行首的提示符號 */
|
|
41
|
+
export function stripPrompt(text) {
|
|
42
|
+
return text.replace(/^\s*(?:\$|PS[^>]*>|>)\s+/, '');
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* 把程式碼區塊拆成一行一行的指令:合併行尾反斜線的續行、去掉提示符號、略過註解。
|
|
47
|
+
* @returns {Array<{line:number, text:string}>}
|
|
48
|
+
*/
|
|
49
|
+
export function commandLinesOf(block) {
|
|
50
|
+
const result = [];
|
|
51
|
+
let pending = null;
|
|
52
|
+
for (const { line, text } of block.lines) {
|
|
53
|
+
const clean = stripPrompt(stripPlaceholders(text));
|
|
54
|
+
if (pending) {
|
|
55
|
+
pending.text += ` ${clean.replace(/\\\s*$/, '').trim()}`;
|
|
56
|
+
if (!/\\\s*$/.test(clean)) {
|
|
57
|
+
result.push(pending);
|
|
58
|
+
pending = null;
|
|
59
|
+
}
|
|
60
|
+
continue;
|
|
61
|
+
}
|
|
62
|
+
if (clean.trim() === '' || /^\s*#/.test(clean)) continue;
|
|
63
|
+
if (/\\\s*$/.test(clean)) {
|
|
64
|
+
pending = { line, text: clean.replace(/\\\s*$/, '').trim() };
|
|
65
|
+
continue;
|
|
66
|
+
}
|
|
67
|
+
result.push({ line, text: clean.trim() });
|
|
68
|
+
}
|
|
69
|
+
if (pending) result.push(pending);
|
|
70
|
+
return result;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/** 依 &&、||、;、| 拆開一行裡的多個指令(引號裡的不拆) */
|
|
74
|
+
export function splitSegments(text) {
|
|
75
|
+
const segments = [];
|
|
76
|
+
let current = '';
|
|
77
|
+
let quote = null;
|
|
78
|
+
for (let i = 0; i < text.length; i++) {
|
|
79
|
+
const c = text[i];
|
|
80
|
+
if (quote) {
|
|
81
|
+
if (c === quote) quote = null;
|
|
82
|
+
current += c;
|
|
83
|
+
continue;
|
|
84
|
+
}
|
|
85
|
+
if (c === '"' || c === "'") {
|
|
86
|
+
quote = c;
|
|
87
|
+
current += c;
|
|
88
|
+
continue;
|
|
89
|
+
}
|
|
90
|
+
if (c === '#' && (i === 0 || /\s/.test(text[i - 1]))) break;
|
|
91
|
+
if (c === ';' || c === '|' || (c === '&' && text[i + 1] === '&')) {
|
|
92
|
+
segments.push(current);
|
|
93
|
+
current = '';
|
|
94
|
+
if ((c === '&' && text[i + 1] === '&') || (c === '|' && text[i + 1] === '|')) i++;
|
|
95
|
+
continue;
|
|
96
|
+
}
|
|
97
|
+
current += c;
|
|
98
|
+
}
|
|
99
|
+
segments.push(current);
|
|
100
|
+
return segments.map((s) => s.trim()).filter(Boolean);
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/** 拆成單字(引號包住的算一個) */
|
|
104
|
+
export function tokenize(segment) {
|
|
105
|
+
const tokens = [];
|
|
106
|
+
for (const m of segment.matchAll(/"([^"]*)"|'([^']*)'|(\S+)/g)) tokens.push(m[1] ?? m[2] ?? m[3]);
|
|
107
|
+
// 去掉前面的環境變數設定與 sudo
|
|
108
|
+
while (tokens.length && (/^[A-Za-z_][A-Za-z0-9_]*=/.test(tokens[0]) || tokens[0] === 'sudo')) tokens.shift();
|
|
109
|
+
return tokens;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/** 去掉引號包住的內容與行尾註解,用來找「不該出現在指令裡」的字 */
|
|
113
|
+
export function stripQuotedAndComment(text) {
|
|
114
|
+
return text
|
|
115
|
+
.replace(/"(?:[^"\\]|\\.)*"|'[^']*'/g, (m) => ' '.repeat(m.length))
|
|
116
|
+
.replace(/(^|\s)#.*$/, (m, pre) => pre + ' '.repeat(m.length - pre.length));
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/** 範圍內的二級以上章節(含子章節)的文字 */
|
|
120
|
+
export function textBetween(md, from, to) {
|
|
121
|
+
return md.lines
|
|
122
|
+
.filter((l) => l.line > from && l.line < to && l.kind !== 'comment')
|
|
123
|
+
.map((l) => l.raw)
|
|
124
|
+
.join('\n');
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/** 一級標題到第一個二級標題之間(第 1 塊) */
|
|
128
|
+
export function introRange(md) {
|
|
129
|
+
const h1 = md.headings.find((h) => h.level === 1);
|
|
130
|
+
const start = h1 ? h1.line : 0;
|
|
131
|
+
const next = md.headings.find((h) => h.line > start && h.level <= 2);
|
|
132
|
+
return { h1, start, end: next ? next.line : md.lines.length + 1 };
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/** 是不是徽章圖片 */
|
|
136
|
+
export function isBadge(src) {
|
|
137
|
+
return /img\.shields\.io|badgen\.net|badge\.fury\.io|\/badge(?:\.svg)?(?:[?#]|$)|\/badges?\/|codecov\.io\/.+\/(?:badge|graph)|coveralls\.io\/repos\/.+\/badge|deploy-status|\/status\.svg/i.test(src);
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
/** 網址的主機名稱 */
|
|
141
|
+
export function hostOf(url) {
|
|
142
|
+
return url.match(/^(?:https?:)?\/\/([^/?#:]+)/i)?.[1]?.toLowerCase() ?? null;
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/** 是不是外部網址或特殊連結(不是相對路徑) */
|
|
146
|
+
export function isExternal(href) {
|
|
147
|
+
return /^[a-z][a-z0-9+.-]*:/i.test(href) || href.startsWith('//');
|
|
148
|
+
}
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
// 版本類規則:README 寫的 Node.js 版本跟專案設定比對、模糊的版本說法。
|
|
2
|
+
import { parseRange, parseVersion } from '../semver.js';
|
|
3
|
+
import { findSection } from '../sections.js';
|
|
4
|
+
import { proseLines, readableText } from './util.js';
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* 專案設定裡的 Node.js 版本。
|
|
8
|
+
* @returns {Array<{source:string, value:string, kind:'exact'|'range', test:(v)=>boolean}>}
|
|
9
|
+
*/
|
|
10
|
+
export function projectNodeSources(project, pkg) {
|
|
11
|
+
const sources = [];
|
|
12
|
+
for (const file of ['.nvmrc', '.node-version']) {
|
|
13
|
+
const text = project.readText(file);
|
|
14
|
+
if (text === null) continue;
|
|
15
|
+
const value = text.trim().split(/\s+/)[0] ?? '';
|
|
16
|
+
const v = parseVersion(value);
|
|
17
|
+
if (v) sources.push({ source: file, value, kind: 'exact', version: v });
|
|
18
|
+
}
|
|
19
|
+
const tool = project.readText('.tool-versions')?.match(/^nodejs\s+(\S+)/m)?.[1];
|
|
20
|
+
if (tool && parseVersion(tool)) sources.push({ source: '.tool-versions', value: tool, kind: 'exact', version: parseVersion(tool) });
|
|
21
|
+
if (typeof pkg?.volta?.node === 'string' && parseVersion(pkg.volta.node)) {
|
|
22
|
+
sources.push({ source: 'package.json volta', value: pkg.volta.node, kind: 'exact', version: parseVersion(pkg.volta.node) });
|
|
23
|
+
}
|
|
24
|
+
if (typeof pkg?.engines?.node === 'string') {
|
|
25
|
+
const test = parseRange(pkg.engines.node);
|
|
26
|
+
if (test) sources.push({ source: 'package.json engines', value: pkg.engines.node, kind: 'range', test });
|
|
27
|
+
}
|
|
28
|
+
return sources;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
const NODE_CLAIM =
|
|
32
|
+
/\bnode(?:\.?js)?\b(?![-_/.]\w)([^\n\d。;;!?!?]{0,20}?)(>=|≥|>|\^|~|=)?\s*v?(\d{1,2}(?:\.(?:\d+|x))?(?:\.(?:\d+|x))?)(\+)?(\s*(?:以上|及以上|或以上|或更新|or (?:later|higher|newer|above)|and (?:later|above)))?/gi;
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* README 裡提到的 Node.js 版本(程式碼區塊以外)。
|
|
36
|
+
* @returns {Array<{line:number, column:number, text:string, kind:'min'|'exact'|'major', version}>}
|
|
37
|
+
*/
|
|
38
|
+
export function readmeNodeClaims(md) {
|
|
39
|
+
const claims = [];
|
|
40
|
+
for (const line of proseLines(md)) {
|
|
41
|
+
const text = readableText(line).replace(/\]\([^)]*\)/g, '] ').replace(/https?:\/\/\S+/g, (m) => ' '.repeat(m.length));
|
|
42
|
+
for (const m of text.matchAll(NODE_CLAIM)) {
|
|
43
|
+
const version = parseVersion(m[3]);
|
|
44
|
+
if (!version) continue;
|
|
45
|
+
const min = m[2] && m[2] !== '=' ? true : Boolean(m[4] || m[5]);
|
|
46
|
+
const kind = min ? 'min' : version.minor === null || version.patch === null ? 'major' : 'exact';
|
|
47
|
+
const shown = `${m[2] ?? ''}${m[3]}${m[4] ?? ''}${m[5] ? ` ${m[5].trim()}` : ''}`.trim();
|
|
48
|
+
claims.push({ line: line.line, column: m.index + 1, text: shown, kind, version });
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
return claims;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
function consistent(claim, source) {
|
|
55
|
+
const v = claim.version;
|
|
56
|
+
const lower = { major: v.major, minor: v.minor ?? 0, patch: v.patch ?? 0 };
|
|
57
|
+
if (source.kind === 'exact') {
|
|
58
|
+
const s = source.version;
|
|
59
|
+
if (claim.kind === 'min') return s.major > lower.major || (s.major === lower.major && (s.minor === null || s.minor >= lower.minor));
|
|
60
|
+
return s.major === v.major;
|
|
61
|
+
}
|
|
62
|
+
if (claim.kind === 'major') {
|
|
63
|
+
return source.test(lower) || source.test({ major: v.major, minor: v.minor ?? 999, patch: 999 });
|
|
64
|
+
}
|
|
65
|
+
return source.test(lower);
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
export const checks = {
|
|
69
|
+
VER002(ctx) {
|
|
70
|
+
const sources = projectNodeSources(ctx.project, ctx.pkg);
|
|
71
|
+
if (!sources.length) return [];
|
|
72
|
+
const out = [];
|
|
73
|
+
const seen = new Set();
|
|
74
|
+
for (const claim of readmeNodeClaims(ctx.md)) {
|
|
75
|
+
if (seen.has(claim.text)) continue;
|
|
76
|
+
seen.add(claim.text);
|
|
77
|
+
const conflict = sources.find((s) => !consistent(claim, s));
|
|
78
|
+
if (conflict) {
|
|
79
|
+
out.push({ messageKey: 'mismatch', params: { readme: claim.text, source: conflict.source, project: conflict.value }, line: claim.line, column: claim.column });
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
return out;
|
|
83
|
+
},
|
|
84
|
+
|
|
85
|
+
VER007(ctx) {
|
|
86
|
+
if (!ctx.pkg) return [];
|
|
87
|
+
const sources = projectNodeSources(ctx.project, ctx.pkg);
|
|
88
|
+
if (!sources.length || readmeNodeClaims(ctx.md).length) return [];
|
|
89
|
+
const anchor = findSection(ctx.sections, 'requirements') ?? findSection(ctx.sections, 'getting-started');
|
|
90
|
+
return [{ messageKey: 'missing', params: { project: sources[0].value, source: sources[0].source }, line: anchor?.line ?? null, column: anchor ? 1 : null }];
|
|
91
|
+
},
|
|
92
|
+
|
|
93
|
+
VER005(ctx) {
|
|
94
|
+
const ranges = ['getting-started', 'requirements']
|
|
95
|
+
.map((id) => findSection(ctx.sections, id))
|
|
96
|
+
.filter(Boolean);
|
|
97
|
+
if (!ranges.length) return [];
|
|
98
|
+
const inRange = (n) => ranges.some((s) => n > s.line && n < s.endLine);
|
|
99
|
+
const VAGUE = /最新版本?|最新的版本|較新的?版本|新一點的版本|(?:latest|newest|newer|a recent) version|以上\s*(?:\.{2,}|…+)|or (?:later|above)\s*(?:\.{2,}|…+)/gi;
|
|
100
|
+
const out = [];
|
|
101
|
+
for (const line of proseLines(ctx.md)) {
|
|
102
|
+
if (!inRange(line.line)) continue;
|
|
103
|
+
for (const m of readableText(line).matchAll(VAGUE)) {
|
|
104
|
+
out.push({ messageKey: 'vague', params: { text: m[0].trim() }, line: line.line, column: m.index + 1 });
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
return out;
|
|
108
|
+
},
|
|
109
|
+
};
|
package/src/data.js
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
// 讀取規則資料。所有塊的順序、標題名稱、類型必填表都從這裡來。
|
|
2
|
+
//
|
|
3
|
+
// 規則的單一來源是 repo 根目錄的 rules/。發佈成 npm 套件時,打包前(prepack)會把它複製到套件裡的 rules/,
|
|
4
|
+
// 打包後(postpack)再刪掉。讀取的順序刻意寫死,避免兩個陷阱:
|
|
5
|
+
// 1. 在 repo 裡一律讀根目錄的 rules/,就算 lint/rules/ 殘留舊複本也不會蓋過它。
|
|
6
|
+
// 2. 裝在別人的專案時,只讀套件自己帶的 rules/,不往上找 ../../rules/(那裡可能是 node_modules/rules 這種不相干的套件)。
|
|
7
|
+
import { existsSync, readFileSync } from 'node:fs';
|
|
8
|
+
import path from 'node:path';
|
|
9
|
+
import { fileURLToPath } from 'node:url';
|
|
10
|
+
|
|
11
|
+
/** 套件的根目錄(package.json 所在的資料夾) */
|
|
12
|
+
export const packageDir = fileURLToPath(new URL('..', import.meta.url));
|
|
13
|
+
|
|
14
|
+
/** 這份程式是不是在 README Guide 的 repo 裡面(lint/ 資料夾,旁邊有 rules/ 與 pnpm-workspace.yaml) */
|
|
15
|
+
function inRepository(dir) {
|
|
16
|
+
const parent = path.dirname(path.resolve(dir));
|
|
17
|
+
return path.basename(path.resolve(dir)) === 'lint'
|
|
18
|
+
&& existsSync(path.join(parent, 'rules', 'rules.json'))
|
|
19
|
+
&& existsSync(path.join(parent, 'pnpm-workspace.yaml'));
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/** 規則資料所在的資料夾與來源 */
|
|
23
|
+
export const rulesSource = inRepository(packageDir)
|
|
24
|
+
? { dir: path.join(path.dirname(path.resolve(packageDir)), 'rules'), from: 'repository' }
|
|
25
|
+
: { dir: path.join(packageDir, 'rules'), from: 'package' };
|
|
26
|
+
|
|
27
|
+
function load(name) {
|
|
28
|
+
const file = path.join(rulesSource.dir, name);
|
|
29
|
+
if (!existsSync(file)) {
|
|
30
|
+
throw new Error(`readme-guide: rules file not found: ${file}. The package may be incomplete; reinstall it.`);
|
|
31
|
+
}
|
|
32
|
+
return JSON.parse(readFileSync(file, 'utf8'));
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export const data = {
|
|
36
|
+
blocks: load('blocks.json'),
|
|
37
|
+
headings: load('headings.json'),
|
|
38
|
+
projectTypes: load('project-types.json'),
|
|
39
|
+
rules: load('rules.json'),
|
|
40
|
+
conventions: load('conventions.json'),
|
|
41
|
+
};
|
|
42
|
+
|
|
43
|
+
export const LANGS = ['zh-TW', 'en'];
|
|
44
|
+
export const TYPE_IDS = data.projectTypes.types.map((t) => t.id);
|
|
45
|
+
|
|
46
|
+
/** 依代號取得專案類型 */
|
|
47
|
+
export function projectType(id) {
|
|
48
|
+
return data.projectTypes.types.find((t) => t.id === id);
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** 依代號取得規則 */
|
|
52
|
+
export function ruleById(id) {
|
|
53
|
+
return data.rules.rules.find((r) => r.id === id);
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** 範本待填文字的比對方式(每次都建新的,避免共用 lastIndex) */
|
|
57
|
+
export function placeholderPattern() {
|
|
58
|
+
const { pattern, flags } = data.conventions.placeholder;
|
|
59
|
+
return new RegExp(pattern, flags);
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** 說明只有刪節號的待填寫法({{請填:…}}):是在介紹寫法本身,不是還沒填的地方 */
|
|
63
|
+
export function isSyntaxMention(text) {
|
|
64
|
+
const { pattern, flags } = data.conventions.placeholder.syntaxMention;
|
|
65
|
+
return new RegExp(pattern, flags).test(text);
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** 把待填文字換成等長空白,讓其他規則不要重複抓 */
|
|
69
|
+
export function stripPlaceholders(text) {
|
|
70
|
+
return text.replace(placeholderPattern(), (m) => ' '.repeat(m.length));
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/** 是否含有待填文字 */
|
|
74
|
+
export function hasPlaceholder(text) {
|
|
75
|
+
return placeholderPattern().test(text);
|
|
76
|
+
}
|
package/src/detect.js
ADDED
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
// 自動判斷 README 的語言與專案類型。
|
|
2
|
+
import { data } from './data.js';
|
|
3
|
+
import { readPackageJson } from './project.js';
|
|
4
|
+
|
|
5
|
+
const HAN = /\p{Script=Han}/gu;
|
|
6
|
+
const LATIN_WORD = /[A-Za-z]+(?:'[A-Za-z]+)?/g;
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* 判斷 README 的語言:程式碼以外的文字,漢字數不少於英文單字數就算繁體中文。
|
|
10
|
+
* @param {ReturnType<import('./markdown.js').parseMarkdown>} md
|
|
11
|
+
* @returns {'zh-TW'|'en'}
|
|
12
|
+
*/
|
|
13
|
+
export function detectLanguage(md) {
|
|
14
|
+
let han = 0;
|
|
15
|
+
let words = 0;
|
|
16
|
+
for (const line of md.lines) {
|
|
17
|
+
if (line.kind !== 'text') continue;
|
|
18
|
+
const prose = line.prose.replace(/\]\([^)]*\)/g, ']').replace(/https?:\/\/\S+/g, '');
|
|
19
|
+
han += (prose.match(HAN) ?? []).length;
|
|
20
|
+
words += (prose.match(LATIN_WORD) ?? []).length;
|
|
21
|
+
}
|
|
22
|
+
return han > 0 && han >= words ? 'zh-TW' : 'en';
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
const BACKEND_DEPS = ['express', 'fastify', 'koa', '@nestjs/core', 'hono', '@hapi/hapi', 'restify', '@adonisjs/core'];
|
|
26
|
+
const FRONTEND_DEPS = ['vue', 'react', 'react-dom', 'svelte', 'next', 'nuxt', '@angular/core', 'solid-js', 'astro', 'preact', '@sveltejs/kit'];
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* 依 README 的章節與專案檔案猜專案類型。
|
|
30
|
+
* @param {object} ctx
|
|
31
|
+
* @param {ReturnType<import('./sections.js').buildSections>} ctx.sections
|
|
32
|
+
* @param {string} ctx.prose 程式碼以外的文字
|
|
33
|
+
* @param {string} ctx.code 程式碼區塊的文字
|
|
34
|
+
* @param {object|null} ctx.project 專案(只有 README 時為 null)
|
|
35
|
+
* @returns {{id:string, evidence: Array<{'zh-TW':string,en:string}>}}
|
|
36
|
+
*/
|
|
37
|
+
export function detectType({ sections, prose, code, project }) {
|
|
38
|
+
const has = (id) => sections.some((s) => s.ids.includes(id));
|
|
39
|
+
const scores = { 'course-example': 0, portfolio: 0, 'backend-api': 0 };
|
|
40
|
+
const evidence = { 'course-example': [], portfolio: [], 'backend-api': [] };
|
|
41
|
+
// 有沒有「確定」的訊號:章節標題或專案檔案。只有內文提到(「提到作品集」「提到課程」「有 curl」)不能決定類型,
|
|
42
|
+
// 因為介紹文字很容易順便提到其他類型(例如「提供網頁專案、作品集等四種範本」)。
|
|
43
|
+
const strong = { 'course-example': false, portfolio: false, 'backend-api': false };
|
|
44
|
+
const note = (type, points, zh, en, isStrong = false) => {
|
|
45
|
+
scores[type] += points;
|
|
46
|
+
if (isStrong) strong[type] = true;
|
|
47
|
+
evidence[type].push({ 'zh-TW': zh, en });
|
|
48
|
+
};
|
|
49
|
+
const title = (id) => data.headings.sections.find((s) => s.id === id).title;
|
|
50
|
+
|
|
51
|
+
for (const id of ['learning-objectives', 'course-unit', 'start-finish']) {
|
|
52
|
+
if (has(id)) note('course-example', 3, `有「${title(id)['zh-TW']}」章節`, `has a "${title(id).en}" section`, true);
|
|
53
|
+
}
|
|
54
|
+
if (/課程|課堂|作業|第\s*[0-9一二三四五六七八九十]+\s*(?:週|堂|單元)|\bLesson\s*\d+|\bWeek\s*\d+|\bcourse\b/i.test(prose)) {
|
|
55
|
+
note('course-example', 1, '提到課程或單元', 'mentions a course or lesson');
|
|
56
|
+
}
|
|
57
|
+
for (const id of ['my-role', 'design-decisions']) {
|
|
58
|
+
if (has(id)) note('portfolio', 3, `有「${title(id)['zh-TW']}」章節`, `has a "${title(id).en}" section`, true);
|
|
59
|
+
}
|
|
60
|
+
if (/作品集|\bportfolio\b/i.test(prose)) note('portfolio', 2, '提到作品集', 'mentions a portfolio');
|
|
61
|
+
for (const id of ['api-docs', 'database']) {
|
|
62
|
+
if (has(id)) note('backend-api', 3, `有「${title(id)['zh-TW']}」章節`, `has a "${title(id).en}" section`, true);
|
|
63
|
+
}
|
|
64
|
+
if (/\bcurl\b/.test(code)) note('backend-api', 1, '有 curl 請求範例', 'has a curl example');
|
|
65
|
+
|
|
66
|
+
if (project) {
|
|
67
|
+
const pkg = readPackageJson(project);
|
|
68
|
+
const deps = pkg ? { ...pkg.dependencies, ...pkg.devDependencies } : {};
|
|
69
|
+
const backend = BACKEND_DEPS.filter((d) => d in deps);
|
|
70
|
+
const frontend = FRONTEND_DEPS.filter((d) => d in deps);
|
|
71
|
+
if (backend.length && !frontend.length) {
|
|
72
|
+
note('backend-api', 2, `package.json 用了 ${backend.join('、')},沒有前端框架`, `package.json uses ${backend.join(', ')} and no front-end framework`, true);
|
|
73
|
+
}
|
|
74
|
+
if (project.isDir('prisma') || project.isDir('migrations')) note('backend-api', 1, '有資料庫設定資料夾', 'has a database setup folder', true);
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
let best = null;
|
|
78
|
+
for (const [type, score] of Object.entries(scores)) {
|
|
79
|
+
if (strong[type] && score >= 2 && (!best || score > scores[best])) best = type;
|
|
80
|
+
}
|
|
81
|
+
if (!best) return { id: data.projectTypes.default, evidence: [] };
|
|
82
|
+
return { id: best, evidence: evidence[best] };
|
|
83
|
+
}
|
package/src/explain.js
ADDED
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
// explain 子指令:查一條規則的完整說明,不用把整份 rules.json 讀進來。
|
|
2
|
+
import { data, projectType } from './data.js';
|
|
3
|
+
import { blockInfo } from './sections.js';
|
|
4
|
+
|
|
5
|
+
const TEXT = {
|
|
6
|
+
'zh-TW': {
|
|
7
|
+
block: '塊',
|
|
8
|
+
anywhere: '依問題出現的位置',
|
|
9
|
+
related: '最相關',
|
|
10
|
+
severity: '嚴重度',
|
|
11
|
+
error: '錯誤',
|
|
12
|
+
warning: '警告',
|
|
13
|
+
status: '狀態',
|
|
14
|
+
implemented: '已實作',
|
|
15
|
+
planned: '規劃中(檢查工具還不會檢查)',
|
|
16
|
+
needsProject: '要對照專案檔案',
|
|
17
|
+
readmeOnly: '只看 README',
|
|
18
|
+
types: '適用類型',
|
|
19
|
+
description: '說明',
|
|
20
|
+
fix: '怎麼修',
|
|
21
|
+
example: '例子',
|
|
22
|
+
before: '改之前',
|
|
23
|
+
after: '改成',
|
|
24
|
+
missingBefore: '(原本缺了這一段)',
|
|
25
|
+
unknown: (id) => `找不到規則「${id}」。`,
|
|
26
|
+
similar: (ids) => `相近的規則:${ids.join('、')}`,
|
|
27
|
+
list: '用 readme-guide explain <規則代號> 查詢,規則代號例如 CMD004。',
|
|
28
|
+
},
|
|
29
|
+
en: {
|
|
30
|
+
block: 'Block',
|
|
31
|
+
anywhere: 'wherever the problem appears',
|
|
32
|
+
related: 'most related',
|
|
33
|
+
severity: 'Severity',
|
|
34
|
+
error: 'Error',
|
|
35
|
+
warning: 'Warning',
|
|
36
|
+
status: 'Status',
|
|
37
|
+
implemented: 'implemented',
|
|
38
|
+
planned: 'planned (not checked yet)',
|
|
39
|
+
needsProject: 'compares against project files',
|
|
40
|
+
readmeOnly: 'README only',
|
|
41
|
+
types: 'Project types',
|
|
42
|
+
description: 'Description',
|
|
43
|
+
fix: 'How to fix',
|
|
44
|
+
example: 'Example',
|
|
45
|
+
before: 'Before',
|
|
46
|
+
after: 'After',
|
|
47
|
+
missingBefore: '(this part was missing)',
|
|
48
|
+
unknown: (id) => `No rule called "${id}".`,
|
|
49
|
+
similar: (ids) => `Similar rules: ${ids.join(', ')}`,
|
|
50
|
+
list: 'Run readme-guide explain <RULE_ID>, for example CMD004.',
|
|
51
|
+
},
|
|
52
|
+
};
|
|
53
|
+
|
|
54
|
+
const normalize = (id) => String(id).toUpperCase().replace(/[^A-Z0-9]/g, '');
|
|
55
|
+
|
|
56
|
+
/** 兩個字串的編輯距離 */
|
|
57
|
+
function distance(a, b) {
|
|
58
|
+
const row = Array.from({ length: b.length + 1 }, (_, i) => i);
|
|
59
|
+
for (let i = 1; i <= a.length; i++) {
|
|
60
|
+
let prev = row[0];
|
|
61
|
+
row[0] = i;
|
|
62
|
+
for (let j = 1; j <= b.length; j++) {
|
|
63
|
+
const tmp = row[j];
|
|
64
|
+
row[j] = Math.min(row[j] + 1, row[j - 1] + 1, prev + (a[i - 1] === b[j - 1] ? 0 : 1));
|
|
65
|
+
prev = tmp;
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
return row[b.length];
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** 依代號找規則(不分大小寫,可以省略連字號,例如 type-api001、typeapi001) */
|
|
72
|
+
export function findRule(id) {
|
|
73
|
+
const key = normalize(id);
|
|
74
|
+
return data.rules.rules.find((r) => normalize(r.id) === key) ?? null;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/** 找不到時列出相近的代號:編輯距離 2 以內,或同一個字首加上相同數字 */
|
|
78
|
+
export function similarRules(id, limit = 5) {
|
|
79
|
+
const key = normalize(id);
|
|
80
|
+
const digits = key.replace(/\D/g, '');
|
|
81
|
+
return data.rules.rules
|
|
82
|
+
.map((r) => ({ id: r.id, score: distance(key, normalize(r.id)) }))
|
|
83
|
+
.filter(({ id: other, score }) => score <= 2 || (digits && normalize(other).endsWith(digits) && normalize(other)[0] === key[0]))
|
|
84
|
+
.sort((a, b) => a.score - b.score || a.id.localeCompare(b.id))
|
|
85
|
+
.slice(0, limit)
|
|
86
|
+
.map((x) => x.id);
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/** 規則換成指定語言的物件(給 --json 用) */
|
|
90
|
+
export function describeRule(rule, lang) {
|
|
91
|
+
const block = rule.block ? blockInfo(rule.block) : null;
|
|
92
|
+
const blockOut = (b) => ({ slug: b.slug, number: b.number, name: b.name[lang] ?? b.name });
|
|
93
|
+
return {
|
|
94
|
+
id: rule.id,
|
|
95
|
+
block: block ? blockOut(block) : null,
|
|
96
|
+
relatedBlocks: (rule.relatedBlocks ?? []).map((slug) => blockOut(blockInfo(slug))),
|
|
97
|
+
category: rule.category,
|
|
98
|
+
severity: rule.severity,
|
|
99
|
+
status: rule.status,
|
|
100
|
+
needsProject: rule.needsProject,
|
|
101
|
+
types: rule.types,
|
|
102
|
+
title: rule.title[lang],
|
|
103
|
+
description: rule.description[lang],
|
|
104
|
+
fix: rule.fix[lang],
|
|
105
|
+
example: rule.example ? rule.example[lang] : null,
|
|
106
|
+
};
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
const indent = (text, spaces = 2) => text.split('\n').map((line) => (line ? `${' '.repeat(spaces)}${line}` : line)).join('\n');
|
|
110
|
+
|
|
111
|
+
/** 給人看的說明 */
|
|
112
|
+
export function formatRule(rule, lang) {
|
|
113
|
+
const t = TEXT[lang];
|
|
114
|
+
const en = lang === 'en';
|
|
115
|
+
const colon = en ? ': ' : ':';
|
|
116
|
+
const list = (items) => items.join(en ? ', ' : '、');
|
|
117
|
+
const paren = (text) => (en ? ` (${text})` : `(${text})`);
|
|
118
|
+
const d = describeRule(rule, lang);
|
|
119
|
+
const typeNames = list(d.types.map((id) => projectType(id).name[lang]));
|
|
120
|
+
const blockLine = d.block
|
|
121
|
+
? `${d.block.number} ${d.block.name}`
|
|
122
|
+
: `${t.anywhere}${d.relatedBlocks.length ? paren(`${t.related}${colon}${list(d.relatedBlocks.map((b) => `${b.number} ${b.name}`))}`) : ''}`;
|
|
123
|
+
const lines = [
|
|
124
|
+
`${d.id} ${d.title}`,
|
|
125
|
+
'',
|
|
126
|
+
`${t.block}${colon}${blockLine}`,
|
|
127
|
+
`${t.severity}${colon}${t[d.severity]}`,
|
|
128
|
+
`${t.status}${colon}${t[d.status]}${en ? ' | ' : '|'}${d.needsProject ? t.needsProject : t.readmeOnly}`,
|
|
129
|
+
`${t.types}${colon}${typeNames}`,
|
|
130
|
+
'',
|
|
131
|
+
`${t.description}${colon.trim()}`,
|
|
132
|
+
indent(d.description),
|
|
133
|
+
'',
|
|
134
|
+
`${t.fix}${colon.trim()}`,
|
|
135
|
+
indent(d.fix),
|
|
136
|
+
];
|
|
137
|
+
if (d.example) {
|
|
138
|
+
lines.push('', `${t.example}${colon.trim()}`, ` ${t.before}${colon.trim()}`);
|
|
139
|
+
lines.push(d.example.before.length ? indent(d.example.before.join('\n'), 4) : ` ${t.missingBefore}`);
|
|
140
|
+
lines.push(` ${t.after}${colon.trim()}`, indent(d.example.after.join('\n'), 4));
|
|
141
|
+
}
|
|
142
|
+
return lines.join('\n');
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/** 找不到規則時的訊息 */
|
|
146
|
+
export function unknownRuleMessage(id, lang) {
|
|
147
|
+
const t = TEXT[lang];
|
|
148
|
+
const similar = similarRules(id);
|
|
149
|
+
return [t.unknown(id), similar.length ? t.similar(similar) : t.list].join('\n');
|
|
150
|
+
}
|