All files index.ts

89.04% Statements 65/73
33.33% Branches 1/3
33.33% Functions 1/3
89.04% Lines 65/73

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 741x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x                 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x  
/*
 * @Date: 2023-05-29 19:26:33
 * @LastEditTime: 2023-06-01 20:06:43
 * @FilePath: /version-mark/lib/index.ts
 * @Description: 优先级 环境变量 > git > 文件 > 空
 * https://segmentfault.com/a/1190000042276279
 * https://juejin.cn/post/7181741108697759805#heading-9
 * https://juejin.cn/post/7037386586899611684#heading-14
 */
import { execSync } from 'child_process'
import { readFileSync } from 'fs'
import config from './config'
 
// 从环境变量获取
function getBranchFromEnv() {
  // gitlab 环境变量
  return process.env.CI_COMMIT_BRANCH
}
function getShaFromEnv() {
  // gitlab 环境变量
  return process.env.CI_COMMIT_SHORT_SHA
}
function getTimeFromEnv() {
  // gitlab 环境变量
  return process.env.CI_COMMIT_TIMESTAMP
}
 
let branchName = 'default'
let commitHash = 'default'
let commitDate = 'default'
let buildDate = 'default'
 
try {
  // 分支名
  branchName = (getBranchFromEnv() || execSync('git rev-parse --abbrev-ref HEAD')).toString().trim()
 
  // 最后一次提交版本
  commitHash = (getShaFromEnv() || execSync('git rev-parse HEAD')).toString().trim().slice(0, 8)
 
  // 最后一次提交时间
  commitDate = new Date(
    (getTimeFromEnv() || execSync('git show -s --format=%cd')).toString()
  ).toLocaleString('chinese', {
    hour12: false
  })
 
  // 打包时间
  buildDate = new Date().toLocaleString('chinese', { hour12: false })
} catch (e) {
  // git 获取失败 尝试文件中读取
  let fileData = null
 
  // 从文件读取
  try {
    fileData = readFileSync(config.filePath).toString().split('\n')
    branchName = fileData[0]
    commitHash = fileData[1]
    commitDate = fileData[2]
    buildDate = fileData[3]
  } catch (e) {}
}
 
const buildInfo = `分支:[${branchName}];提交Hash:[${commitHash}];提交日期:[${commitDate}];打包日期:[${buildDate}];`
 
export { branchName, commitHash, commitDate, buildDate, buildInfo }
 
export default {
  branchName,
  commitHash,
  commitDate,
  buildDate,
  buildInfo
}