import dayjs from 'dayjs' import { exec } from 'child_process' import { readFileSync, writeFileSync } from 'fs' const versionFile = './dist/versionInfo.json' main() /** * 写入json文件 * @param {*} version * @param {*} fileDirName */ function writeJson(version, fileDirName) { try { writeFileSync(fileDirName, JSON.stringify(version, null, 2), { flag: 'w+', encoding: 'utf-8' }) console.log(`-> 写入 ${fileDirName} 成功`) } catch (err) { console.error(`-> 写入 ${fileDirName} 失败: `) console.error(err) throw err } } /** * 获取最新的版本号 * @returns */ function getLatestVersion() { return new Promise((resolve, reject) => { return exec('git describe --abbrev=0 --tags', (err, version) => { if (err) { reject() // console.error('获取版本号失败:', err) console.error('获取版本号失败') } else { console.log('最新版本号:', version) exec('git rev-parse HEAD', (err, hash) => { if (err) { reject() // console.error('获取版本号失败:', err) console.error('获取版本号失败') } else { console.log('最新HASH:', hash) resolve({ version: version.trim(), hash: hash.trim() }) } }) } }) }) } // 主函数 function main() { getLatestVersion().then(({ version, hash }) => { const content = readFileSync(versionFile, 'utf-8') const packageInfo = JSON.parse(content) packageInfo.version = version packageInfo.hash = hash packageInfo.updateTime = dayjs().format('YYYY-MM-DD HH:mm:ss') writeJson(packageInfo, versionFile) }) }