updateGitInfo.js 1.2 KB

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