updateGitInfo.js 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. const { exec } = require('child_process')
  2. const fs = require('fs')
  3. const getGitBranch = () => {
  4. return new Promise((resolve, reject) => {
  5. exec(
  6. 'git symbolic-ref --quiet --short HEAD || git describe --all --exact-match HEAD',
  7. (error, stdout, stderr) => {
  8. if (error) {
  9. reject(error)
  10. } else {
  11. const branch = stdout.trim()
  12. resolve(branch)
  13. }
  14. }
  15. )
  16. })
  17. }
  18. const extractVersion = (branch) => {
  19. const versionRegex = /(v.*?)$/
  20. const matches = branch.match(versionRegex)
  21. return matches ? matches[0] : ''
  22. }
  23. const updateEnvFile = (branch) => {
  24. try {
  25. const envFilePath = '.env.production'
  26. const existingContent = fs.readFileSync(envFilePath, 'utf8')
  27. const updatedBranch = extractVersion(branch)
  28. const updatedContent = existingContent.replace(
  29. /(VITE_APP_GIT_BRANCH=).*/,
  30. `$1'${updatedBranch}'`
  31. )
  32. fs.writeFileSync(envFilePath, updatedContent)
  33. console.log(
  34. 'Git 分支信息已更新到 .env.production 文件',
  35. branch,
  36. updatedBranch
  37. )
  38. } catch (error) {
  39. console.error('更新 .env.production 文件失败:', error)
  40. }
  41. }
  42. getGitBranch()
  43. .then((branch) => {
  44. updateEnvFile(branch)
  45. })
  46. .catch((error) => {
  47. console.error('获取 Git 分支失败:', error)
  48. })