// 在根目录调用 const fs = require('fs'); const path = require('path'); const fse = require('fs-extra'); const _ = require('lodash'); const axios = require('axios'); const { getProcessArgs } = require('./util'); const envs = getProcessArgs(); const { token, path: pluginPath, slug, ref = 'main' } = envs; const category = slug.split('/').slice(-2, -1)[0]; console.log({ category, pluginPath, ref }); const pluginMetaJsonName = 'plugin-meta.json'; const cnbBaseUrl = 'https://api.cnb.cool'; const cnbApiAxios = axios.create({ baseURL: cnbBaseUrl, method: 'get', headers: { Authorization: `Bearer ${token}`, accept: 'application/json', }, }); const getFile = (slug, ref, file) => cnbApiAxios({ url: `/${slug}/-/git/contents/${file}?ref=${ref}`, headers: { accept: 'application/vnd.cnb.api+json', }, }) .then((res) => Buffer.from(res.data.content, res.data.encoding)) .catch((e) => { throw new Error(`${slug} ${file}获取失败:${e}`) }); const run = async (pluginPath, slug, ref, additionalTags = []) => { console.log('run', pluginPath, slug, additionalTags); await fse.ensureDir(pluginPath); const meta = await getFile(slug, ref, pluginMetaJsonName) .then((content) => { try { return content ? JSON.parse(content) : null; } catch (e) { throw new Error(`parse plguin-meta.json error: ${e}`) } }); fs.writeFileSync( path.join(pluginPath, pluginMetaJsonName), JSON.stringify(meta, null, 2) ); // 下载logo到本地,然后上传cdn let { logo } = meta; if (logo) { // 兼容 ./logo.png 这种相对路径 logo = path.normalize(logo); const content = await getFile(slug, ref, logo).catch(e => { console.error(e); throw new Error(`声明了logo,但文件不存在:${logo}`); }); fs.writeFileSync(path.join(pluginPath, logo), content); } const readmeList = [(meta.readme || 'README.md'), ...Object.keys(meta.locales || {}).map(lang => meta.locales?.[lang].readme)]; console.log('readmeList', readmeList) await Promise.all(readmeList.map(item => getFile(slug, ref, item).then(content => { fs.writeFileSync(path.join(pluginPath, item), content); }))) }; const main = async () => { if (!token) { throw new Error('token is empty'); } await run(path.join(__dirname, `../plugins/${category}`, pluginPath), slug, ref) }; main().catch((e) => { console.error(e); process.exit(-1); });