|
| 1 | +#!/usr/bin/env node |
| 2 | +// 版本号同步工具 |
| 3 | +// 读取 package.json 中 version 的值,更新 sonar-project.properties 中的 sonar.projectVersion 的值 |
| 4 | +const fs = require('fs') |
| 5 | +const path = require('path') |
| 6 | +const chalk = require('chalk') |
| 7 | + |
| 8 | +const packagePath = path.resolve(process.cwd(), 'package.json') |
| 9 | +const sonarPath = path.resolve(process.cwd(), 'sonar-project.properties') |
| 10 | + |
| 11 | +if (!fs.existsSync(packagePath)) { |
| 12 | + console.error(chalk.red(`No package.json file found in' ${process.cwd()} is this a JavaScript repo?`)) |
| 13 | + process.exit(1) |
| 14 | +} |
| 15 | + |
| 16 | +const packageJson = require(packagePath) |
| 17 | + |
| 18 | +if (!packageJson.version) { |
| 19 | + console.error(chalk.red('package.json has no version field')) |
| 20 | +} |
| 21 | + |
| 22 | +if (!fs.existsSync(sonarPath)) { |
| 23 | + console.log(chalk.yellow('skipped: sonar-project.properties')) |
| 24 | + return |
| 25 | +} |
| 26 | +const sonarFile = fs.readFileSync(sonarPath, 'utf8') |
| 27 | + |
| 28 | +const sonarVersionRegex = /sonar\.projectVersion=(.*)/ |
| 29 | +const match = sonarFile.match(sonarVersionRegex) |
| 30 | +if (!match) { |
| 31 | + console.error(chalk.red('sonar-project.properties file doesn\'t have a version number. Fix this and run again.')) |
| 32 | + process.exit(1) |
| 33 | +} |
| 34 | + |
| 35 | +const oldSonarVersionString = match[0] |
| 36 | +const newSonarVersionString = `sonar.projectVersion=${packageJson.version}` |
| 37 | +if (oldSonarVersionString !== newSonarVersionString) { |
| 38 | + fs.writeFileSync(sonarPath, sonarFile.replace(oldSonarVersionString, newSonarVersionString), 'utf8') |
| 39 | + console.log(chalk.green(`replace '${oldSonarVersionString}' -> '${newSonarVersionString}'`)) |
| 40 | +} |
0 commit comments