const { exec } = require('child_process') const fs = require('fs') const getGitBranch = () => { return new Promise((resolve, reject) => { exec( 'git symbolic-ref --quiet --short HEAD || git describe --all --exact-match HEAD', (error, stdout, stderr) => { if (error) { reject(error) } else { const branch = stdout.trim() resolve(branch) } } ) }) } const extractVersion = (branch) => { let numberBranch = branch if (numberBranch.indexOf('/')) { numberBranch = numberBranch.split('/')[1] } if (numberBranch.indexOf('_')) { numberBranch = numberBranch.split('_')[0] } const versionRegex = /(v.*?)$/ const matches = numberBranch.match(versionRegex) return matches ? matches[0] : '' } const updateEnvFile = (branch) => { try { const envFilePath = '.env.production' const existingContent = fs.readFileSync(envFilePath, 'utf8') const updatedBranch = extractVersion(branch) const updatedContent = existingContent.replace( /(VITE_APP_GIT_BRANCH=).*/, `$1'${updatedBranch}'` ) fs.writeFileSync(envFilePath, updatedContent) console.log( 'Git 分支信息已更新到 .env.production 文件', branch, updatedBranch ) } catch (error) { console.error('更新 .env.production 文件失败:', error) } } getGitBranch() .then((branch) => { updateEnvFile(branch) }) .catch((error) => { console.error('获取 Git 分支失败:', error) })