Files
echo/scripts/sync-version.cjs

53 lines
1.5 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/* 同步前端 package.json 的版本号到 Android 工程versionCode / versionName */
const fs = require('fs')
const path = require('path')
const rootDir = path.resolve(__dirname, '..')
const pkgPath = path.join(rootDir, 'package.json')
const androidGradlePath = path.join(rootDir, 'android', 'app', 'build.gradle')
const readJson = (file) => {
const raw = fs.readFileSync(file, 'utf8')
return JSON.parse(raw)
}
const calcVersionCode = (version) => {
const [major = 0, minor = 0, patch = 0] = String(version)
.split('.')
.map((n) => Number.parseInt(n, 10) || 0)
// 简单规则MMmmpp → 1.2.3 => 10203足够覆盖 099 范围
return major * 10000 + minor * 100 + patch
}
const syncAndroidGradle = (version) => {
if (!fs.existsSync(androidGradlePath)) {
console.warn('[version-sync] 未找到 android/app/build.gradle跳过 Android 同步')
return
}
const versionCode = calcVersionCode(version)
let content = fs.readFileSync(androidGradlePath, 'utf8')
content = content.replace(/versionCode\s+\d+/, `versionCode ${versionCode}`)
content = content.replace(/versionName\s+"[^"]+"/, `versionName "${version}"`)
fs.writeFileSync(androidGradlePath, content)
console.log(
`[version-sync] Android 已同步versionName=${version}, versionCode=${versionCode}`,
)
}
const main = () => {
const pkg = readJson(pkgPath)
const version = pkg.version
if (!version) {
throw new Error('package.json 中缺少 version 字段')
}
syncAndroidGradle(version)
}
main()