index.ts
5.84 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
/**
* Publint 命令模块
* 用于检查 monorepo 中的包是否符合 publint 标准
*/
import type { CAC } from 'cac';
import type { Result } from 'publint';
import { basename, dirname, join } from 'node:path';
import {
colors,
consola,
ensureFile,
findMonorepoRoot,
generatorContentHash,
getPackages,
outputJSON,
readJSON,
UNICODE,
} from '@venus/node-utils';
import { publint } from 'publint';
import { formatMessage } from 'publint/utils';
/**
* 缓存文件路径
* 用于存储 publint 检查结果,避免重复检查未变更的包
*/
const CACHE_FILE = join(
'node_modules',
'.cache',
'publint',
'.pkglintcache.json',
);
/**
* Publint 命令选项接口
*/
interface PubLintCommandOptions {
/** 仅检查模式,不执行程序退出 */
check?: boolean;
}
/**
* 获取需要检查的文件列表
* @param files 指定的文件路径数组,如果为空则获取所有包的 package.json
* @returns 返回需要检查的 package.json 文件路径数组
*/
async function getLintFiles(files: string[] = []) {
const lintFiles: string[] = [];
// 如果指定了文件,则只检查这些文件中的 package.json
if (files?.length > 0) {
return files.filter((file) => basename(file) === 'package.json');
}
// 否则获取 monorepo 中所有包的 package.json
const { packages } = await getPackages();
for (const { dir } of packages) {
lintFiles.push(join(dir, 'package.json'));
}
return lintFiles;
}
/**
* 获取缓存文件的完整路径
* @returns 返回缓存文件的完整路径
*/
function getCacheFile() {
const root = findMonorepoRoot();
return join(root, CACHE_FILE);
}
/**
* 读取缓存数据
* @param cacheFile 缓存文件路径
* @returns 返回缓存数据对象,如果读取失败则返回空对象
*/
async function readCache(cacheFile: string) {
try {
await ensureFile(cacheFile);
return await readJSON(cacheFile);
} catch {
return {};
}
}
/**
* 执行 publint 检查
* @param files 要检查的文件路径数组
* @param options 命令选项
*/
async function runPublint(files: string[], { check }: PubLintCommandOptions) {
const lintFiles = await getLintFiles(files);
const cacheFile = getCacheFile();
const cacheData = await readCache(cacheFile);
const cache: Record<string, { hash: string; result: Result }> = cacheData;
// 并行检查所有包
const results = await Promise.all(
lintFiles.map(async (file) => {
try {
const pkgJson = await readJSON(file);
// 跳过私有包
if (pkgJson.private) {
return null;
}
// 移除依赖相关字段,避免依赖变更影响缓存命中
Reflect.deleteProperty(pkgJson, 'dependencies');
Reflect.deleteProperty(pkgJson, 'devDependencies');
Reflect.deleteProperty(pkgJson, 'peerDependencies');
const content = JSON.stringify(pkgJson);
const hash = generatorContentHash(content);
// 如果缓存中存在且 hash 匹配,则使用缓存结果,否则执行检查
const publintResult: Result =
cache?.[file]?.hash === hash
? (cache?.[file]?.result ?? [])
: await publint({
level: 'suggestion',
pkgDir: dirname(file),
strict: true,
});
// 更新缓存
cache[file] = {
hash,
result: publintResult,
};
return { pkgJson, pkgPath: file, publintResult };
} catch {
return null;
}
}),
);
// 保存缓存并打印结果
await outputJSON(cacheFile, cache);
printResult(results, check);
}
/**
* 打印检查结果
* @param results 检查结果数组
* @param check 是否为仅检查模式,如果为 true 则不会退出程序
*/
function printResult(
results: Array<null | {
pkgJson: Record<string, number | string>;
pkgPath: string;
publintResult: Result;
}>,
check?: boolean,
) {
let errorCount = 0;
let warningCount = 0;
let suggestionsCount = 0;
// 遍历所有结果并统计问题数量
for (const result of results) {
if (!result) {
continue;
}
const { pkgJson, pkgPath, publintResult } = result;
const messages = publintResult?.messages ?? [];
// 如果没有消息则跳过
if (messages?.length < 1) {
continue;
}
// 打印包路径和所有消息
consola.log('');
consola.log(pkgPath);
for (const message of messages) {
// 根据消息类型统计数量
switch (message.type) {
case 'error': {
errorCount++;
break;
}
case 'suggestion': {
suggestionsCount++;
break;
}
case 'warning': {
warningCount++;
break;
}
// 无默认分支
}
// 生成规则链接并打印格式化后的消息
const ruleUrl = `https://publint.dev/rules#${message.code.toLocaleLowerCase()}`;
consola.log(
` ${formatMessage(message, pkgJson)}${colors.dim(` ${ruleUrl}`)}`,
);
}
}
// 打印统计信息
const totalCount = warningCount + errorCount + suggestionsCount;
if (totalCount > 0) {
consola.error(
colors.red(
`${UNICODE.FAILURE} ${totalCount} problem (${errorCount} errors, ${warningCount} warnings, ${suggestionsCount} suggestions)`,
),
);
// 如果不是仅检查模式,则退出程序
!check && process.exit(1);
} else {
consola.log(colors.green(`${UNICODE.SUCCESS} No problem`));
}
}
/**
* 定义 publint 命令
* @param cac CAC 实例,用于注册命令
*/
function definePubLintCommand(cac: CAC) {
cac
.command('publint [...files]')
.usage('检查 monorepo 中的包是否符合 publint 标准。')
.option('--check', '仅检查模式,只检查错误,不执行程序退出。')
.action(runPublint);
}
export { definePubLintCommand };