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
| #!/usr/bin/env node
const { program } = require('commander'); const chalk = require('chalk'); const inquirer = require('inquirer'); const fs = require('fs-extra'); const path = require('path'); const ora = require('ora'); const { execSync } = require('child_process');
program .name('devtool') .description('开发者实用工具箱') .version('1.0.0');
program .command('create <project-name>') .description('创建新项目') .option('-t, --template <template>', '项目模板', 'express') .action(async (projectName, options) => { const spinner = ora('创建项目中...').start();
try { const projectPath = path.resolve(process.cwd(), projectName);
if (fs.existsSync(projectPath)) { spinner.fail(chalk.red(`目录 ${projectName} 已存在`)); return; }
fs.mkdirsSync(projectPath);
const template = options.template;
if (template === 'express') { createExpressProject(projectPath, projectName); } else if (template === 'cli') { createCliProject(projectPath, projectName); } else if (template === 'api') { createApiProject(projectPath, projectName); }
spinner.succeed(chalk.green(`项目 ${projectName} 创建成功!`));
console.log(`\n${chalk.blue('下一步:')}`); console.log(` cd ${projectName}`); console.log(` npm install`); console.log(` npm run dev\n`);
} catch (error) { spinner.fail(chalk.red(`创建失败: ${error.message}`)); } });
program .command('batch') .description('文件批量处理工具') .option('-p, --path <path>', '目标目录', '.') .option('-e, --ext <ext>', '文件扩展名', '.md') .option('-r, --replace <old> <new>', '替换文本') .action(async (options) => { const spinner = ora('扫描文件中...').start();
try { const targetDir = path.resolve(options.path); const ext = options.ext;
if (!fs.existsSync(targetDir)) { spinner.fail(chalk.red(`目录 ${targetDir} 不存在`)); return; }
const files = findFiles(targetDir, ext); spinner.succeed(chalk.green(`找到 ${files.length} 个 ${ext} 文件`));
if (options.replace) { const [oldStr, newStr] = options.replace; let count = 0;
files.forEach(file => { let content = fs.readFileSync(file, 'utf-8'); if (content.includes(oldStr)) { content = content.replace(new RegExp(oldStr, 'g'), newStr); fs.writeFileSync(file, content, 'utf-8'); count++; console.log(` ${chalk.green('✓')} ${path.relative(targetDir, file)}`); } });
console.log(`\n${chalk.blue(`替换完成:共修改 ${count} 个文件`)}`); } else { console.log(`\n${chalk.blue('文件列表:')}`); files.forEach(file => { console.log(` ${chalk.green('●')} ${path.relative(targetDir, file)}`); }); } } catch (error) { spinner.fail(chalk.red(`处理失败: ${error.message}`)); } });
program .command('gitflow') .description('Git 工作流快捷命令') .option('-m, --message <message>', '提交信息') .option('-p, --push', '是否推送') .action(async (options) => { try { if (!fs.existsSync('.git')) { console.log(chalk.red('当前目录不是 Git 仓库')); return; }
const { action } = await inquirer.prompt([ { type: 'list', name: 'action', message: '选择操作:', choices: [ { name: '📦 提交所有更改', value: 'commit' }, { name: '🔀 切换分支', value: 'branch' }, { name: '📋 查看状态', value: 'status' }, { name: '🧹 清理分支', value: 'clean' } ] } ]);
switch (action) { case 'commit': const commitMsg = options.message || 'update'; execSync('git add -A', { stdio: 'inherit' }); execSync(`git commit -m "${commitMsg}"`, { stdio: 'inherit' }); if (options.push) { execSync('git push', { stdio: 'inherit' }); } console.log(chalk.green('✓ 提交成功')); break;
case 'branch': const { branchAction } = await inquirer.prompt([ { type: 'list', name: 'branchAction', message: '选择分支操作:', choices: ['查看分支', '创建分支', '切换分支'] } ]);
if (branchAction === '查看分支') { execSync('git branch', { stdio: 'inherit' }); } else if (branchAction === '创建分支') { const { branchName } = await inquirer.prompt([ { type: 'input', name: 'branchName', message: '分支名称:' } ]); execSync(`git checkout -b ${branchName}`, { stdio: 'inherit' }); } else { const { branchName } = await inquirer.prompt([ { type: 'input', name: 'branchName', message: '分支名称:' } ]); execSync(`git checkout ${branchName}`, { stdio: 'inherit' }); } break;
case 'status': execSync('git status', { stdio: 'inherit' }); break;
case 'clean': execSync('git branch --merged', { stdio: 'inherit' }); break; } } catch (error) { console.log(chalk.red(`操作失败: ${error.message}`)); } });
program .command('info') .description('显示系统信息') .action(() => { console.log(`\n${chalk.blue('系统信息:')}`); console.log(` Node.js: ${chalk.green(process.version)}`); console.log(` Platform: ${chalk.green(process.platform)}`); console.log(` Arch: ${chalk.green(process.arch)}`); console.log(` CPU Cores: ${chalk.green(require('os').cpus().length)}`); console.log(` Memory: ${chalk.green(`${(require('os').totalmem() / 1024 / 1024 / 1024).toFixed(1)} GB`)}`); console.log(` Free Memory: ${chalk.green(`${(require('os').freemem() / 1024 / 1024 / 1024).toFixed(1)} GB`)}`); console.log(` Home Dir: ${chalk.green(require('os').homedir())}`); console.log(` Hostname: ${chalk.green(require('os').hostname())}`); console.log(''); });
function findFiles(dir, ext, fileList = []) { const files = fs.readdirSync(dir); files.forEach(file => { const filePath = path.join(dir, file); if (fs.statSync(filePath).isDirectory()) { findFiles(filePath, ext, fileList); } else if (file.endsWith(ext)) { fileList.push(filePath); } }); return fileList; }
function createExpressProject(projectPath, projectName) { fs.writeJSONSync(path.join(projectPath, 'package.json'), { name: projectName, version: '1.0.0', description: '', main: 'src/app.js', scripts: { start: 'node src/app.js', dev: 'nodemon src/app.js' }, dependencies: { express: '^4.18.2', cors: '^2.8.5', dotenv: '^16.3.1' }, devDependencies: { nodemon: '^3.0.2' } }, { spaces: 2 });
fs.mkdirsSync(path.join(projectPath, 'src/routes')); fs.mkdirsSync(path.join(projectPath, 'src/middleware'));
fs.writeFileSync(path.join(projectPath, 'src/app.js'), `const express = require('express'); const cors = require('cors'); require('dotenv').config();
const app = express(); const PORT = process.env.PORT || 3000;
app.use(cors()); app.use(express.json());
// 路由 app.use('/api', require('./routes/index'));
app.listen(PORT, () => { console.log(\`Server running on port \${PORT}\`); }); `);
fs.writeFileSync(path.join(projectPath, 'src/routes/index.js'), `const express = require('express'); const router = express.Router();
router.get('/health', (req, res) => { res.json({ status: 'ok' }); });
module.exports = router; `);
fs.writeFileSync(path.join(projectPath, '.env'), 'PORT=3000\n');
fs.writeFileSync(path.join(projectPath, '.gitignore'), 'node_modules/\n.env\n'); }
function createCliProject(projectPath, projectName) { fs.writeJSONSync(path.join(projectPath, 'package.json'), { name: projectName, version: '1.0.0', bin: { [projectName]: 'bin/index.js' }, dependencies: { commander: '^11.1.0', chalk: '^4.1.2' } }, { spaces: 2 });
fs.mkdirsSync(path.join(projectPath, 'bin'));
fs.writeFileSync(path.join(projectPath, 'bin/index.js'), `#!/usr/bin/env node const { program } = require('commander'); const chalk = require('chalk');
program .name('${projectName}') .version('1.0.0') .description('CLI tool');
program .command('hello <name>') .action((name) => { console.log(chalk.green(\`Hello, \${name}!\`)); });
program.parse(); `); }
function createApiProject(projectPath, projectName) { fs.writeJSONSync(path.join(projectPath, 'package.json'), { name: projectName, version: '1.0.0', main: 'src/app.js', scripts: { start: 'node src/app.js', dev: 'nodemon src/app.js' }, dependencies: { express: '^4.18.2', mongoose: '^7.6.3', bcryptjs: '^2.4.3', jsonwebtoken: '^9.0.2', cors: '^2.8.5', dotenv: '^16.3.1' } }, { spaces: 2 });
fs.mkdirsSync(path.join(projectPath, 'src/{models,routes,middleware,controllers}')); }
program.parse();
|