const fs = require('fs'); const path = require('path'); function first2UpperCase(str) { return str.toLowerCase().replace(/( |^)[a-z]/g, L => L.toUpperCase()); } function scanAndCreate(structure, workerName, root) { Object.keys(structure) .forEach(name => { if (typeof structure[name] === 'object') { fs.mkdirSync(path.resolve(root, name)); scanAndCreate(structure[name], workerName, path.resolve(root, `./${name}`)); } else if (structure[name] === '') { fs.appendFileSync(path.resolve(root, name), ''); } else if (typeof structure[name] === 'string') { let content = fs.readFileSync(structure[name]).toString(); content = content .replace(/\${WorkerName}/g, first2UpperCase(workerName)) .replace(/\${workerName}/g, workerName); fs.appendFileSync(path.resolve(root, name), content); } }); } module.exports = { exec: async args => { if (!args.init) { throw new Error(`Command init not found in args`); } if (!args.name) { throw new Error('Command --name=... not found in args'); } const name = args.name; const structure = { [`${name}_worker`]: { 'main_thread': { action: { 'action.worker_ability_test.ts': path.resolve(__dirname, './template/main_thread/action/action.worker_ability_test.t'), }, [`${name}_main_thread.ts`]: path.resolve(__dirname, './template/main_thread/main_thread.t'), }, utils: { 'action_type.ts': path.resolve(__dirname, './template/utils/action_type.t'), 'payload_type.ts': path.resolve(__dirname, './template/utils/payload_type.t'), }, 'worker_thread': { action: { 'action.worker_ability_test.ts': path.resolve(__dirname, './template/worker_thread/action/action.worker_ability_test.t'), }, [`${name}_worker_thread.ts`]: path.resolve(__dirname, './template/worker_thread/worker_thread.t'), }, [`${name}_main_thread.helper.ts`]: path.resolve(__dirname, './template/main_thread.helper.t'), }, }; scanAndCreate(structure, name, args.where ? path.resolve(args.where) : process.cwd()); }, }; // 结构 // -xxx_worker // -|--main_thread // -|--|--action // -|--|--xxx_main_thread.ts // -|--utils // -|--|--action_type.ts // -|--worker_thread // -|--|--action // -|--|--worker_main_thread.ts