/** * 将proto文件编译到 src/proto/ */ const { readdirSync } = require('fs'); const { resolve } = require('path'); const os = require('os'); const { exec } = require('child_process'); const messageDir = resolve(__dirname, '../rts-sim-testing-message'); const protoDir = resolve(messageDir, 'protos'); const destDir = resolve(__dirname, '../src/protos'); /** * 递归处理所有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() { const protocDir = resolve(messageDir, 'protoc-23.1'); 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); }); // console.log(prepareCmds); 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();