2023-05-30 14:31:27 +08:00
|
|
|
/**
|
|
|
|
* 将proto文件编译到 src/proto/
|
|
|
|
*/
|
|
|
|
const { readdirSync } = require('fs');
|
|
|
|
const { resolve } = require('path');
|
|
|
|
const os = require('os');
|
|
|
|
|
|
|
|
const { exec } = require('child_process');
|
|
|
|
|
|
|
|
const messageDir = resolve(__dirname, '../xian-ncc-da-message');
|
|
|
|
const protoDir = resolve(messageDir, 'protos');
|
2023-06-06 14:33:25 +08:00
|
|
|
const destDir = resolve(__dirname, '../src/protos');
|
2023-05-30 14:31:27 +08:00
|
|
|
|
|
|
|
/**
|
|
|
|
* 递归处理所有proto文件生成
|
|
|
|
* @param {*} file 文件
|
|
|
|
* @param {*} path 目录
|
|
|
|
*/
|
|
|
|
function recursiveGenerate(file, path = [], cmds = []) {
|
|
|
|
if (file.isFile()) {
|
|
|
|
// 文件,生成
|
|
|
|
if (file.name.endsWith('.proto')) {
|
|
|
|
cmds.push(buildGenerateCmd(file.name, path));
|
|
|
|
} else {
|
|
|
|
console.warn('不是proto文件', file.name);
|
|
|
|
}
|
|
|
|
} else if (file.isDirectory()) {
|
|
|
|
// 文件夹,递归
|
|
|
|
readdirSync(resolve(protoDir, ...path, file.name), {
|
|
|
|
withFileTypes: true,
|
|
|
|
}).forEach((f) => {
|
|
|
|
const subPath = [...path, file.name];
|
|
|
|
recursiveGenerate(f, subPath, cmds);
|
|
|
|
});
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
const isLinux = os.type().toLowerCase().includes('linux');
|
|
|
|
|
|
|
|
function buildGenerateCmd(name, path = []) {
|
|
|
|
const protoPath = resolve(protoDir, ...path);
|
|
|
|
const tsPath = resolve(destDir, ...path);
|
|
|
|
|
|
|
|
let cmd = ['protoc', `-I=${protoPath}`, `--ts_out=${tsPath}`, `${name}`];
|
|
|
|
let cmdStr = cmd.join(' ');
|
|
|
|
return cmdStr;
|
|
|
|
}
|
|
|
|
|
|
|
|
function main() {
|
2023-06-06 15:13:19 +08:00
|
|
|
const protocDir = resolve(messageDir, 'protoc-23.1');
|
2023-05-30 14:31:27 +08:00
|
|
|
const protocBin = resolve(
|
|
|
|
protocDir,
|
|
|
|
`bin/${isLinux ? 'linux-x86_64' : 'win64'}`
|
|
|
|
);
|
|
|
|
const prepareCmds = [];
|
|
|
|
const setPathCmd = isLinux
|
|
|
|
? ['export', `PATH=${protocBin}:${protocDir}:"$PATH"`].join(' ')
|
|
|
|
: ['set', `PATH=${protocBin};${protocDir};%PATH%`].join(' ');
|
|
|
|
const protocVersionCmd = ['protoc', '--version'].join(' ');
|
|
|
|
prepareCmds.push(setPathCmd);
|
|
|
|
prepareCmds.push(protocVersionCmd);
|
|
|
|
|
|
|
|
readdirSync(protoDir, {
|
|
|
|
withFileTypes: true,
|
|
|
|
}).forEach((f) => {
|
|
|
|
recursiveGenerate(f, [], prepareCmds);
|
|
|
|
});
|
|
|
|
|
2023-07-17 16:13:45 +08:00
|
|
|
// console.log(prepareCmds);
|
2023-05-30 14:31:27 +08:00
|
|
|
|
|
|
|
exec(
|
|
|
|
prepareCmds.join(' && '),
|
|
|
|
{
|
|
|
|
maxBuffer: 1024 * 2000,
|
|
|
|
},
|
|
|
|
(err, stdout, stderr) => {
|
|
|
|
if (err) {
|
|
|
|
console.error(err);
|
|
|
|
throw err;
|
|
|
|
} else if (stderr.length > 0) {
|
|
|
|
console.error(stderr.toString());
|
|
|
|
throw new Error(stderr.toString());
|
|
|
|
} else {
|
|
|
|
console.log(stdout);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
);
|
|
|
|
}
|
|
|
|
|
|
|
|
// 执行
|
|
|
|
main();
|