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/src/format.js ADDED
@@ -0,0 +1,153 @@
1
+ // 輸出:給人看的表格式文字,以及給 AI 讀的 JSON。
2
+ import { data } from './data.js';
3
+
4
+ const UI = {
5
+ 'zh-TW': {
6
+ type: '專案類型',
7
+ lang: 'README 語言',
8
+ detected: '自動判斷',
9
+ byOption: '由 --type 指定',
10
+ langByOption: '由 --lang 指定輸出語言',
11
+ noEvidence: '沒有找到其他類型的特徵,用預設值;可以用 --type 指定',
12
+ evidenceJoin: '、',
13
+ langName: { 'zh-TW': '繁體中文', en: '英文' },
14
+ skipped: (n, ids) => `只找到 README,沒有其他專案檔案,跳過 ${n} 條要對照專案檔案的規則:${ids}`,
15
+ ok: '✔ 沒有發現問題(0 個錯誤、0 個警告)',
16
+ summary: (total, e, w) => `✖ ${total} 個問題(${e} 個錯誤、${w} 個警告)`,
17
+ summaryWarn: (total, w) => `⚠ ${total} 個問題(0 個錯誤、${w} 個警告)`,
18
+ wholeFile: '全文',
19
+ outside: '八塊以外',
20
+ },
21
+ en: {
22
+ type: 'Project type',
23
+ lang: 'README language',
24
+ detected: 'detected',
25
+ byOption: 'set by --type',
26
+ langByOption: 'output language set by --lang',
27
+ noEvidence: 'no signs of another type, using the default; set it with --type',
28
+ evidenceJoin: ', ',
29
+ langName: { 'zh-TW': 'Traditional Chinese', en: 'English' },
30
+ skipped: (n, ids) => `Only a README was found, no other project files, so ${n} rules that compare against project files were skipped: ${ids}`,
31
+ ok: '✔ No problems found (0 errors, 0 warnings)',
32
+ summary: (total, e, w) => `✖ ${total} ${total === 1 ? 'problem' : 'problems'} (${e} ${e === 1 ? 'error' : 'errors'}, ${w} ${w === 1 ? 'warning' : 'warnings'})`,
33
+ summaryWarn: (total, w) => `⚠ ${total} ${total === 1 ? 'problem' : 'problems'} (0 errors, ${w} ${w === 1 ? 'warning' : 'warnings'})`,
34
+ wholeFile: 'whole file',
35
+ outside: 'outside the eight blocks',
36
+ },
37
+ };
38
+
39
+ /** 終端機裡的顯示寬度:中日韓文字與全形符號算兩格 */
40
+ export function displayWidth(text) {
41
+ let width = 0;
42
+ for (const ch of text) {
43
+ const code = ch.codePointAt(0);
44
+ const wide =
45
+ (code >= 0x1100 && code <= 0x115f) ||
46
+ (code >= 0x2e80 && code <= 0xa4cf) ||
47
+ (code >= 0xac00 && code <= 0xd7a3) ||
48
+ (code >= 0xf900 && code <= 0xfaff) ||
49
+ (code >= 0xfe30 && code <= 0xfe4f) ||
50
+ (code >= 0xff00 && code <= 0xff60) ||
51
+ (code >= 0xffe0 && code <= 0xffe6) ||
52
+ (code >= 0x1f300 && code <= 0x1faff);
53
+ width += wide ? 2 : 1;
54
+ }
55
+ return width;
56
+ }
57
+
58
+ function pad(text, width) {
59
+ return text + ' '.repeat(Math.max(0, width - displayWidth(text)));
60
+ }
61
+
62
+ function colors(enabled) {
63
+ const wrap = (code) => (s) => (enabled ? `\u001b[${code}m${s}\u001b[0m` : s);
64
+ return { red: wrap('31'), yellow: wrap('33'), dim: wrap('2'), bold: wrap('1'), underline: wrap('4'), green: wrap('32') };
65
+ }
66
+
67
+ /**
68
+ * 給人看的輸出。
69
+ * @param {string} file 顯示用的檔名
70
+ * @param {ReturnType<import('./lint.js').lintReadme>} result
71
+ * @param {{color?: boolean}} [options]
72
+ */
73
+ export function formatHuman(file, result, { color = false } = {}) {
74
+ const lang = result.language.output;
75
+ const t = UI[lang];
76
+ const c = colors(color);
77
+ const out = [];
78
+ out.push(c.bold(c.underline(file)));
79
+
80
+ const labelLine = (label, value, note) => (lang === 'en' ? `${label}: ${value} (${note})` : `${label}:${value}(${note})`);
81
+ const sep = lang === 'en' ? ': ' : ':';
82
+ let typeNote;
83
+ if (result.type.source === 'option') typeNote = t.byOption;
84
+ else if (result.type.evidence.length) typeNote = `${t.detected}${sep}${result.type.evidence.map((e) => e[lang]).join(t.evidenceJoin)}`;
85
+ else typeNote = `${t.detected}${sep}${t.noEvidence}`;
86
+ out.push(c.dim(labelLine(t.type, result.type.name[lang], typeNote)));
87
+ const langNote = result.language.source === 'option' ? t.langByOption : t.detected;
88
+ out.push(c.dim(labelLine(t.lang, t.langName[result.language.readme], langNote)));
89
+ if (result.skippedRules.length) out.push(c.dim(t.skipped(result.skippedRules.length, result.skippedRules.join(lang === 'en' ? ', ' : '、'))));
90
+ out.push('');
91
+
92
+ if (!result.problems.length) {
93
+ out.push(c.green(t.ok));
94
+ return out.join('\n');
95
+ }
96
+
97
+ const rows = result.problems.map((p) => ({
98
+ pos: p.line ? `${p.line}:${p.column ?? 1}` : '—',
99
+ level: data.rules.severities[p.severity][lang],
100
+ severity: p.severity,
101
+ message: p.message,
102
+ block: p.block ? `${p.block.number} ${p.block.name}` : `— ${p.line ? t.outside : t.wholeFile}`,
103
+ number: p.block?.number ?? '—',
104
+ blockName: p.block ? p.block.name : p.line ? t.outside : t.wholeFile,
105
+ rule: p.ruleId,
106
+ }));
107
+ const posWidth = Math.max(...rows.map((r) => displayWidth(r.pos)));
108
+ const levelWidth = Math.max(...rows.map((r) => displayWidth(r.level)));
109
+ const messageWidth = Math.min(64, Math.max(...rows.map((r) => displayWidth(r.message))));
110
+ const blockWidth = Math.max(...rows.map((r) => displayWidth(r.block)));
111
+ for (const r of rows) {
112
+ const level = pad(r.level, levelWidth);
113
+ const blockText = `${r.number} ${c.dim(pad(r.blockName, blockWidth - displayWidth(r.number) - 1))}`;
114
+ out.push(
115
+ [
116
+ ` ${c.dim(pad(r.pos, posWidth))}`,
117
+ r.severity === 'error' ? c.red(level) : c.yellow(level),
118
+ pad(r.message, messageWidth),
119
+ r.number === '—' ? c.dim(pad(r.block, blockWidth)) : blockText,
120
+ c.dim(r.rule),
121
+ ].join(' '),
122
+ );
123
+ }
124
+ out.push('');
125
+ const total = result.problems.length;
126
+ const { errors, warnings } = result.summary;
127
+ out.push(errors ? c.red(c.bold(t.summary(total, errors, warnings))) : c.yellow(c.bold(t.summaryWarn(total, warnings))));
128
+ return out.join('\n');
129
+ }
130
+
131
+ /**
132
+ * 給 AI 讀的 JSON 輸出。
133
+ * @param {string} file
134
+ * @param {string} projectDir
135
+ * @param {ReturnType<import('./lint.js').lintReadme>} result
136
+ */
137
+ export function formatJson(file, projectDir, result) {
138
+ const lang = result.language.output;
139
+ return JSON.stringify(
140
+ {
141
+ file,
142
+ projectDir,
143
+ type: { id: result.type.id, name: result.type.name[lang], source: result.type.source, evidence: result.type.evidence.map((e) => e[lang]) },
144
+ language: result.language,
145
+ projectFilesFound: result.projectFilesFound,
146
+ skippedRules: result.skippedRules,
147
+ summary: result.summary,
148
+ problems: result.problems,
149
+ },
150
+ null,
151
+ 2,
152
+ );
153
+ }
package/src/lint.js ADDED
@@ -0,0 +1,142 @@
1
+ // 檢查流程:解析 README → 判斷類型與語言 → 依 rules/rules.json 逐條執行已實作的規則。
2
+ import path from 'node:path';
3
+ import { data, projectType, ruleById, TYPE_IDS } from './data.js';
4
+ import { parseMarkdown } from './markdown.js';
5
+ import { blockInfo, blockOfLine, buildSections } from './sections.js';
6
+ import { detectLanguage, detectType } from './detect.js';
7
+ import { hasProjectFiles, readPackageJson } from './project.js';
8
+ import { checks as structure } from './checks/structure.js';
9
+ import { checks as commands } from './checks/commands.js';
10
+ import { checks as versions } from './checks/versions.js';
11
+ import { checks as env } from './checks/env.js';
12
+ import { checks as media } from './checks/media.js';
13
+ import { checks as license } from './checks/license.js';
14
+ import { checks as ai } from './checks/ai.js';
15
+ import { checks as types } from './checks/types.js';
16
+ import { checks as folders } from './checks/folders.js';
17
+
18
+ /** 規則代號對到實作 */
19
+ export const implementations = { ...structure, ...commands, ...versions, ...env, ...media, ...license, ...ai, ...types, ...folders };
20
+
21
+ /**
22
+ * 檢查一份 README。
23
+ * @param {object} options
24
+ * @param {string} options.text README 內容
25
+ * @param {object|null} [options.project] 專案(fsProject 或 memoryProject);null 表示只有 README
26
+ * @param {string} [options.readmePath] README 相對於專案根目錄的路徑
27
+ * @param {string} [options.type] 指定專案類型;不給就自動判斷
28
+ * @param {'zh-TW'|'en'} [options.lang] 輸出語言;不給就跟 README 一樣
29
+ */
30
+ export function lintReadme({ text, project = null, readmePath = 'README.md', type, lang }) {
31
+ if (type && !TYPE_IDS.includes(type)) throw new Error(`unknown type: ${type}`);
32
+ const md = parseMarkdown(text);
33
+ const sections = buildSections(md);
34
+ const docLang = detectLanguage(md);
35
+ const outputLang = lang ?? docLang;
36
+ const projectMode = Boolean(project) && hasProjectFiles(project);
37
+ const activeProject = projectMode ? project : null;
38
+
39
+ const prose = md.lines.filter((l) => l.kind === 'text').map((l) => l.prose).join('\n');
40
+ const code = md.codeBlocks.flatMap((b) => b.lines.map((l) => l.text)).join('\n');
41
+ const detected = type ? null : detectType({ sections, prose, code, project: activeProject });
42
+ const typeId = type ?? detected.id;
43
+ const typeDef = projectType(typeId);
44
+
45
+ const ctx = {
46
+ md,
47
+ sections,
48
+ docLang,
49
+ type: typeId,
50
+ typeDef,
51
+ project: activeProject,
52
+ pkg: activeProject ? readPackageJson(activeProject) : null,
53
+ readmeDir: readmeDirOf(readmePath),
54
+ };
55
+
56
+ const problems = [];
57
+ const skipped = [];
58
+ for (const rule of data.rules.rules) {
59
+ if (rule.status !== 'implemented' || !rule.types.includes(typeId)) continue;
60
+ if (rule.needsProject && !projectMode) {
61
+ skipped.push(rule.id);
62
+ continue;
63
+ }
64
+ const impl = implementations[rule.id];
65
+ if (!impl) throw new Error(`rule ${rule.id} is marked implemented but has no implementation`);
66
+ for (const found of impl(ctx)) problems.push(toProblem(rule, found, sections, outputLang));
67
+ }
68
+
69
+ // 照行號排;沒有行號的(例如缺少的章節)放在那一塊應該出現的位置
70
+ const sortLine = (p) => p.line ?? anchorLine(sections, p.block?.slug);
71
+ problems.sort((a, b) => sortLine(a) - sortLine(b) || (a.line === null) - (b.line === null) || (a.column ?? 0) - (b.column ?? 0));
72
+
73
+ return {
74
+ type: {
75
+ id: typeId,
76
+ name: typeDef.name,
77
+ source: type ? 'option' : 'detected',
78
+ evidence: detected?.evidence ?? [],
79
+ },
80
+ language: { output: outputLang, readme: docLang, source: lang ? 'option' : 'detected' },
81
+ projectFilesFound: projectMode,
82
+ skippedRules: skipped,
83
+ summary: {
84
+ errors: problems.filter((p) => p.severity === 'error').length,
85
+ warnings: problems.filter((p) => p.severity === 'warning').length,
86
+ },
87
+ problems,
88
+ };
89
+ }
90
+
91
+ /**
92
+ * README 所在的資料夾(相對於專案根目錄),README 裡的相對路徑從這裡算。
93
+ * README 不在專案資料夾裡(例如用 --project 指到別的地方)時,從專案根目錄算。
94
+ */
95
+ export function readmeDirOf(readmePath) {
96
+ const normalized = path.posix.normalize(String(readmePath).replace(/\\/g, '/'));
97
+ if (normalized.startsWith('../') || normalized === '..' || path.posix.isAbsolute(normalized) || /^[A-Za-z]:\//.test(normalized)) return '.';
98
+ return path.posix.dirname(normalized);
99
+ }
100
+
101
+ /** 某一塊在文件裡的位置:那一塊第一個二級標題;還沒有的話,用它後面那一塊的位置 */
102
+ function anchorLine(sections, slug) {
103
+ if (!slug) return Infinity;
104
+ const index = blockInfo(slug).index;
105
+ const h2 = sections.filter((s) => s.level === 2 && s.block);
106
+ const own = h2.find((s) => s.block === slug);
107
+ if (own) return own.line;
108
+ const later = h2.find((s) => blockInfo(s.block).index > index);
109
+ return later ? later.line - 0.5 : Infinity;
110
+ }
111
+
112
+ /** 把參數換成輸出語言的文字 */
113
+ function localize(value, lang) {
114
+ if (value && typeof value === 'object') return value[lang] ?? value.en ?? '';
115
+ return String(value);
116
+ }
117
+
118
+ function format(template, params, lang) {
119
+ return template.replace(/\{(\w+)\}/g, (m, key) => (key in params ? localize(params[key], lang) : m));
120
+ }
121
+
122
+ function toProblem(rule, found, sections, lang) {
123
+ // 有行號的問題依所在位置標塊;沒有行號(例如缺少的章節)才用規則本身所屬的塊
124
+ const blockSlug = found.block ?? (found.line ? blockOfLine(sections, found.line) ?? rule.block : rule.block);
125
+ const block = blockSlug ? blockInfo(blockSlug) : null;
126
+ const template = rule.messages[found.messageKey];
127
+ if (!template) throw new Error(`rule ${rule.id} has no message "${found.messageKey}"`);
128
+ const params = found.params ?? {};
129
+ return {
130
+ ruleId: rule.id,
131
+ severity: rule.severity,
132
+ line: found.line ?? null,
133
+ column: found.column ?? null,
134
+ block: block ? { slug: block.slug, number: block.number, name: localize(block.name, lang) } : null,
135
+ message: format(localize(template, lang), params, lang),
136
+ title: localize(rule.title, lang),
137
+ fix: localize(rule.fix, lang),
138
+ needsProject: rule.needsProject,
139
+ };
140
+ }
141
+
142
+ export { ruleById };