/** * params * input: node version newVersion * output:process.argv == ['','','to'] */ const path = require('path'); const fs = require('fs'); console.log(process.argv) const argv = process.argv // 获取命令行参数中的新版本号,并过滤v字头 let newVersion = '' if(argv[2].includes('v')){ newVersion = process.argv[2].replace(/^v/, '') }else if(argv[2].includes('V')){ newVersion = argv[2].replace(/^V/, '') }else{ newVersion = argv[2] } if (!newVersion) { console.log('请传入新版本号,版本号遵循semver规范 .eg: 1.0.0, 1.0.1, 1.1.0'); process.exit(1); } // 获取当前命令行上下文路径 const currentDirectory = process.cwd(); // 获取 package.json 文件中的版本号 const packageJsonPath = path.join(currentDirectory, 'package.json'); const packageJsonContent = fs.readFileSync(packageJsonPath, 'utf8'); const packageJson = JSON.parse(packageJsonContent); const currentVersion = packageJson.version; packageJson.version = newVersion; //获取.beagle.yml及其版本号,并进行替换 const filePath = path.join(__dirname, '.beagle.yml'); fs.readFile(filePath, 'utf8', function (err, data) { if (err) { return console.log(err); } let from = 'v'+currentVersion; let to = '' if(argv[2].includes('v')){ to = argv[2] }else if(argv[2].includes('V')){ to = argv[2].replace(/^V/, 'v') }else{ to = 'v'+argv[2] } let re = new RegExp(from,"g"); let result = data.replace(re, to); //有大版本号的输入则替换大版本号 let fromArr = from.split('.') let toArr = to.split('.') //前2个相等则是小版本迭代 if(fromArr[0]==toArr[0]&&fromArr[1]==toArr[1]){ }else{ let shortFrom = ":"+fromArr[0]+'.'+fromArr[1]; let shortTo = ":"+toArr[0]+'.'+toArr[1]; let reShort = new RegExp(shortFrom,"g"); result = result.replace(reShort, shortTo); } //更新yml文件中的版本号 fs.writeFile(filePath, result, 'utf8', function (err) { if (err) return console.log(err); }); // 更新 package.json 文件中的版本号 fs.writeFileSync(packageJsonPath, JSON.stringify(packageJson, null, 2)); console.log(`版本号已从 ${currentVersion} 更新为 ${newVersion}`); });