Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

获取当前 git 分支 #11

Open
maomao1996 opened this issue Aug 4, 2020 · 0 comments
Open

获取当前 git 分支 #11

maomao1996 opened this issue Aug 4, 2020 · 0 comments

Comments

@maomao1996
Copy link
Owner

maomao1996 commented Aug 4, 2020

获取当前 git 分支

命令

git 2.22 版本之后

git branch --show-current

git 2.22 版本之前

# 使用 rev-parse
git rev-parse --abbrev-ref HEAD

# 使用 symbolic-ref
git symbolic-ref --short -q HEAD

如果当前处于一个提交(commit)而不是分支上时会有以下区别

  • 使用 rev-parse 子命令时会返回 HEAD
  • 使用 symbolic-ref 子命令时会返回错误(空字符串)

symbolic-ref 和 rev-parse 的区别

node 中使用

execa

const execa = require('execa')
const branchName = execa.commandSync('git rev-parse --abbrev-ref HEAD').stdout

shelljs

const shell = require('shelljs')
const branchName = shell
  .exec('git rev-parse --abbrev-ref HEAD', { silent: true })
  .stdout.trim()

child_process

const child_process = require('child_process')
const branchName = child_process
  .execSync('git rev-parse --abbrev-ref HEAD', {
    encoding: 'utf8'
  })
  .trim()

用途

可以根据分支名在 webpack 编译时做处理(如: 线上环境打包只允许在 master 分支)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant