updateGitInfo.js 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  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. let numberBranch = branch
  20. if (numberBranch.indexOf('/')) {
  21. numberBranch = numberBranch.split('/')[1]
  22. }
  23. if (numberBranch.indexOf('_')) {
  24. numberBranch = numberBranch.split('_')[0]
  25. }
  26. const versionRegex = /(v.*?)$/
  27. const matches = numberBranch.match(versionRegex)
  28. return matches ? matches[0] : ''
  29. }
  30. const updateEnvFile = (branch) => {
  31. try {
  32. const envFilePath = '.env.production'
  33. const existingContent = fs.readFileSync(envFilePath, 'utf8')
  34. const updatedBranch = extractVersion(branch)
  35. const updatedContent = existingContent.replace(
  36. /(VITE_APP_GIT_BRANCH=).*/,
  37. `$1'${updatedBranch}'`
  38. )
  39. fs.writeFileSync(envFilePath, updatedContent)
  40. console.log(
  41. 'Git 分支信息已更新到 .env.production 文件',
  42. branch,
  43. updatedBranch
  44. )
  45. } catch (error) {
  46. console.error('更新 .env.production 文件失败:', error)
  47. }
  48. }
  49. getGitBranch()
  50. .then((branch) => {
  51. updateEnvFile(branch)
  52. })
  53. .catch((error) => {
  54. console.error('获取 Git 分支失败:', error)
  55. })