{{ message }}
Repository navigation
Expand file tree
/
Copy pathgenerate-plugins-json.js
More file actions
524 lines (448 loc) · 14.7 KB
/
Copy pathgenerate-plugins-json.js
File metadata and controls
524 lines (448 loc) · 14.7 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
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
#!/usr/bin/env node
import { readdirSync, readFileSync, writeFileSync, existsSync, mkdirSync, createReadStream, statSync } from 'fs';
import { join, extname, resolve } from 'path';
import { pathToFileURL } from 'url';
import { execSync } from 'child_process';
import sharp from 'sharp';
import { Extract } from 'unzipper';
import { pipeline } from 'stream/promises';
const RELEASE_DIR = 'release';
const TEMP_DIR = join(RELEASE_DIR, 'temp');
const BUILD_INFO_FILE = join(RELEASE_DIR, 'build-info.json');
const PREVIOUS_MANIFEST_FILE = join(RELEASE_DIR, 'plugins.previous.json');
const CATEGORIES_MAPPING_FILE = 'categories-mapping.json';
/**
* 比较两个版本号
* @returns {number} 1 if v1 > v2, -1 if v1 < v2, 0 if equal
*/
function compareVersions(v1, v2) {
const parts1 = v1.split('.').map(Number);
const parts2 = v2.split('.').map(Number);
const maxLen = Math.max(parts1.length, parts2.length);
for (let i = 0; i < maxLen; i++) {
const num1 = parts1[i] || 0;
const num2 = parts2[i] || 0;
if (num1 > num2) return 1;
if (num1 < num2) return -1;
}
return 0;
}
/**
* 获取仓库信息
*/
function getRepoInfo() {
const remoteUrl = process.env.GITHUB_REPOSITORY || '';
if (remoteUrl) {
const [owner, repo] = remoteUrl.split('/');
return { owner, repo };
}
try {
const remote = execSync('git remote get-url origin', { encoding: 'utf-8' }).trim();
const match = remote.match(/github\.com[:/](.+?)\/(.+?)(\.git)?$/);
if (match) {
return { owner: match[1], repo: match[2] };
}
} catch (error) {
console.error('无法获取仓库信息');
}
throw new Error('无法确定GitHub仓库信息');
}
/**
* 获取release版本号
*/
function getReleaseVersion() {
if (existsSync(BUILD_INFO_FILE)) {
const buildInfo = JSON.parse(readFileSync(BUILD_INFO_FILE, 'utf-8'));
return buildInfo.releaseVersion;
}
return 'latest';
}
/**
* 规范化插件分类
*/
function normalizePluginCategories(categories) {
if (Array.isArray(categories)) {
return categories
.filter(category => typeof category === 'string')
.map(category => category.trim())
.filter(Boolean);
}
if (typeof categories === 'string') {
const category = categories.trim();
return category ? [category] : [];
}
return [];
}
/**
* 生成分类数据
*/
function generateCategoriesData(plugins) {
if (!existsSync(CATEGORIES_MAPPING_FILE)) {
throw new Error(`找不到分类映射文件: ${CATEGORIES_MAPPING_FILE}`);
}
const categoriesMapping = JSON.parse(readFileSync(CATEGORIES_MAPPING_FILE, 'utf-8'));
const categoriesData = categoriesMapping.map(category => ({
...category,
list: []
}));
const categoryMap = new Map(categoriesData.map(category => [category.key, category]));
const fallbackCategoryMap = new Map();
categoriesMapping.forEach(category => {
(category.list || []).forEach(pluginName => {
if (!fallbackCategoryMap.has(pluginName)) {
fallbackCategoryMap.set(pluginName, []);
}
fallbackCategoryMap.get(pluginName).push(category.key);
});
});
plugins.forEach(plugin => {
const explicitCategories = normalizePluginCategories(plugin.categories);
const pluginCategories = explicitCategories.length > 0
? explicitCategories
: (fallbackCategoryMap.get(plugin.name) || []);
const uniqueCategories = [...new Set(pluginCategories)];
let assigned = false;
uniqueCategories.forEach(categoryKey => {
const category = categoryMap.get(categoryKey);
if (category) {
category.list.push(plugin.name);
assigned = true;
} else {
console.warn(` ⚠ 未知分类 "${categoryKey}",插件 ${plugin.name} 将归入 other`);
}
});
if (!assigned) {
const otherCategory = categoryMap.get('other');
if (otherCategory) {
otherCategory.list.push(plugin.name);
}
}
});
return categoriesData.map(category => ({
...category,
list: [...new Set(category.list)]
}));
}
/**
* 解压zip文件
*/
async function extractZip(zipPath, destDir) {
if (!existsSync(destDir)) {
mkdirSync(destDir, { recursive: true });
}
// 优先使用系统unzip命令(更可靠)
try {
execSync(`unzip -q -o "${zipPath}" -d "${destDir}"`, {
stdio: 'pipe'
});
await new Promise(resolve => setTimeout(resolve, 100));
return;
} catch (sysError) {
console.log(` 系统unzip失败,尝试使用unzipper库...`);
}
// 备用方案:使用unzipper库
try {
await pipeline(
createReadStream(zipPath),
Extract({ path: destDir })
);
await new Promise(resolve => setTimeout(resolve, 100));
} catch (error) {
throw new Error(`解压失败: ${error.message}`);
}
}
/**
* 在解压的目录中查找plugin.json
*/
function findPluginJson(dir) {
const possiblePaths = [
join(dir, 'plugin.json'),
join(dir, 'public', 'plugin.json'),
];
for (const path of possiblePaths) {
if (existsSync(path)) {
return path;
}
}
// 递归查找
const files = readdirSync(dir);
for (const file of files) {
const fullPath = join(dir, file);
try {
const stat = statSync(fullPath);
if (stat.isDirectory()) {
const found = findPluginJson(fullPath);
if (found) return found;
}
} catch (e) {
// 忽略错误
}
}
return null;
}
/**
* 在解压的目录中查找logo文件
*/
function findLogoFile(dir, logoFileName) {
const possiblePaths = [
join(dir, logoFileName),
join(dir, 'public', logoFileName),
join(dir, 'assets', logoFileName),
];
for (const path of possiblePaths) {
if (existsSync(path)) {
return path;
}
}
// 递归查找
const files = readdirSync(dir);
for (const file of files) {
const fullPath = join(dir, file);
try {
const stat = statSync(fullPath);
if (stat.isDirectory() && !file.includes('node_modules')) {
const found = findLogoFile(fullPath, logoFileName);
if (found) return found;
}
} catch (e) {
// 忽略错误
}
}
return null;
}
/**
* 将图片压缩为64x64并转为base64
*/
async function imageToBase64(imagePath) {
try {
const buffer = await sharp(imagePath)
.resize(64, 64, {
fit: 'cover',
position: 'center'
})
.png()
.toBuffer();
return `data:image/png;base64,${buffer.toString('base64')}`;
} catch (error) {
throw new Error(`处理图片失败: ${imagePath}: ${error.message}`, { cause: error });
}
}
/**
* 处理单个zip文件
*/
async function processZipFile(zipFileName) {
const zipPath = join(RELEASE_DIR, zipFileName);
// 修复:匹配最后一个版本号部分,版本号格式为 数字.数字...
// 例如:json-editor-1.7.1.zip -> json-editor
// port-use-1.0.0.zip -> port-use
const pluginName = zipFileName.replace(/-[\d.]+\.zip$/, '');
const extractDir = join(TEMP_DIR, pluginName);
console.log(`\n处理: ${zipFileName}`);
try {
// 解压
console.log(' 解压中...');
await extractZip(zipPath, extractDir);
// 查找plugin.json
const pluginJsonPath = findPluginJson(extractDir);
if (!pluginJsonPath) {
console.error(` ✗ 找不到plugin.json`);
return null;
}
console.log(` 找到plugin.json: ${pluginJsonPath}`);
const pluginInfo = JSON.parse(readFileSync(pluginJsonPath, 'utf-8'));
// 查找并处理logo
let logoBase64 = null;
if (pluginInfo.logo) {
const logoPath = findLogoFile(extractDir, pluginInfo.logo);
if (logoPath) {
console.log(` 找到logo: ${logoPath}`);
try {
logoBase64 = await imageToBase64(logoPath);
} catch (error) {
const logoError = new Error(
`插件 ${pluginInfo.name || pluginName} 的 logo 无法转换为Base64: ${error.message}`,
{ cause: error }
);
logoError.code = 'PLUGIN_LOGO_PROCESSING_FAILED';
throw logoError;
}
console.log(` ✓ logo已转换为base64`);
} else {
console.warn(` ⚠ 找不到logo文件: ${pluginInfo.logo}`);
}
}
// 获取zip文件大小(字节)
const zipStats = statSync(zipPath);
const sizeInBytes = zipStats.size;
// 生成下载URL
const { owner, repo } = getRepoInfo();
const version = getReleaseVersion();
const downloadUrl = `https://github.com/${owner}/${repo}/releases/download/v${version}/${zipFileName}`;
// 合并信息
const result = {
...pluginInfo,
downloadUrl,
logo: logoBase64 || pluginInfo.logo,
size: sizeInBytes
};
console.log(` ✓ 处理完成`);
return result;
} catch (error) {
console.error(` ✗ 处理失败: ${error.message}`);
if (error.code === 'PLUGIN_LOGO_PROCESSING_FAILED') {
throw error;
}
return null;
}
}
/**
* 清理临时目录
*/
function cleanupTemp() {
if (existsSync(TEMP_DIR)) {
execSync(`rm -rf "${TEMP_DIR}"`);
}
}
function extractPluginsList(manifest) {
if (Array.isArray(manifest)) {
return manifest;
}
if (manifest && Array.isArray(manifest.plugins)) {
return manifest.plugins;
}
throw new Error('plugins.json 格式不正确,期望为插件数组或包含 plugins 数组的对象');
}
function readPreviousManifest() {
if (!existsSync(PREVIOUS_MANIFEST_FILE)) {
return null;
}
try {
return extractPluginsList(JSON.parse(readFileSync(PREVIOUS_MANIFEST_FILE, 'utf-8')));
} catch (error) {
throw new Error(`读取历史 plugins.json 失败: ${error.message}`);
}
}
function normalizePluginName(name) {
return typeof name === 'string' ? name.trim().toLowerCase() : '';
}
/**
* 以历史完整 manifest 为基线,仅替换本次构建的插件。
* 历史条目保留原 Release 地址,避免 main Release 再次携带所有 ZIP。
*/
function mergePluginManifests(currentPlugins, previousPlugins, buildInfo) {
if (!previousPlugins) {
return currentPlugins;
}
const deletedNames = new Set((buildInfo.deletedPlugins || []).map(normalizePluginName));
const currentNames = new Set(currentPlugins.map(plugin => normalizePluginName(plugin.name)));
// 当前条目均来自本次构建的 ZIP,必须优先于历史数据。
// changedPlugins 使用目录名,不能用它与 plugin.json 的 name 判断是否更新。
const merged = [...currentPlugins];
// 保留历史中未参与本次构建的插件;显式删除的插件不会被带回。
for (const plugin of previousPlugins) {
const key = normalizePluginName(plugin.name);
if (key && !currentNames.has(key) && !deletedNames.has(key) && !buildInfo.buildAll) {
merged.push(plugin);
}
}
return merged;
}
/**
* 主函数
*/
async function main() {
console.log('开始生成plugins.json 和 categories.json...\n');
// 确保临时目录存在
if (!existsSync(TEMP_DIR)) {
mkdirSync(TEMP_DIR, { recursive: true });
}
try {
// 获取所有zip文件
const zipFiles = readdirSync(RELEASE_DIR)
.filter(file => extname(file) === '.zip')
.sort();
console.log(`找到 ${zipFiles.length} 个插件包\n`);
const buildInfo = existsSync(BUILD_INFO_FILE)
? JSON.parse(readFileSync(BUILD_INFO_FILE, 'utf-8'))
: { changedPlugins: [], deletedPlugins: [] };
const previousPlugins = readPreviousManifest();
if (zipFiles.length === 0 && !previousPlugins) {
throw new Error('没有找到任何zip文件,且不存在历史 plugins.json,无法生成完整 manifest');
}
// 处理所有zip文件
const plugins = [];
for (const zipFile of zipFiles) {
const pluginInfo = await processZipFile(zipFile);
if (pluginInfo) {
plugins.push(pluginInfo);
}
}
if (plugins.length !== zipFiles.length) {
throw new Error(`有 ${zipFiles.length - plugins.length} 个当前构建 ZIP 未能生成插件条目,已停止发布`);
}
if (plugins.length === 0 && !previousPlugins) {
throw new Error('没有成功处理任何插件,无法生成 manifest');
}
const mergedPlugins = mergePluginManifests(plugins, previousPlugins, buildInfo);
if (mergedPlugins.length === 0) {
throw new Error('合并后的插件清单为空');
}
// 生成plugins.json
const outputPath = join(RELEASE_DIR, 'plugins.json');
writeFileSync(outputPath, JSON.stringify(mergedPlugins, null, 2));
// 生成categories.json
const categories = generateCategoriesData(mergedPlugins);
const categoriesOutputPath = join(RELEASE_DIR, 'categories.json');
writeFileSync(categoriesOutputPath, JSON.stringify(categories, null, 2));
console.log(`\n========== 生成结果 ==========`);
console.log(`本次处理: ${plugins.length} 个插件,合并后: ${mergedPlugins.length} 个插件`);
console.log(`输出文件: ${outputPath}`);
console.log(`文件大小: ${(readFileSync(outputPath).length / 1024).toFixed(2)} KB`);
console.log(`输出文件: ${categoriesOutputPath}`);
console.log(`文件大小: ${(readFileSync(categoriesOutputPath).length / 1024).toFixed(2)} KB`);
// 输出插件列表
console.log('\n插件列表:');
mergedPlugins.forEach(p => {
console.log(` - ${p.name} v${p.version}: ${p.description}`);
});
// 生成变更日志(用于 GitHub Release)
const changedPluginNames = buildInfo.changedPlugins || [];
const changedPluginsInfo = mergedPlugins.filter(p =>
changedPluginNames.some(name =>
p.name === name || p.name.toLowerCase() === name.toLowerCase()
)
);
// 对同名插件去重,只保留版本号最高的
const latestChangedPlugins = {};
for (const plugin of changedPluginsInfo) {
const existing = latestChangedPlugins[plugin.name];
if (!existing || compareVersions(plugin.version, existing.version) > 0) {
latestChangedPlugins[plugin.name] = plugin;
}
}
const changeLog = Object.keys(latestChangedPlugins).length > 0
? Object.values(latestChangedPlugins).map(p => `${p.name} v${p.version}: ${p.description}`).join('\n')
: '无变更插件信息';
// 保存变更日志到文件
const changeLogPath = join(RELEASE_DIR, 'changelog.txt');
writeFileSync(changeLogPath, changeLog + '\n');
console.log(`\n变更日志已保存到: ${changeLogPath}`);
console.log('变更内容:');
console.log(changeLog);
console.log('\n✓ plugins.json 和 categories.json 生成完成');
} finally {
// 清理临时目录
console.log('\n清理临时文件...');
cleanupTemp();
}
}
export { mergePluginManifests };
const isMainModule = process.argv[1]
&& import.meta.url === pathToFileURL(resolve(process.argv[1])).href;
if (isMainModule) {
main().catch(error => {
console.error('执行失败:', error);
cleanupTemp();
process.exit(1);
});
}
You can’t perform that action at this time.
