# 获取当前分支名
git rev-parse --abbrev-ref HEAD
git branch --show-current
# 获取当前hash
git rev-parse HEAD
git rev-parse --short HEAD # 短的上面的代码是通过git命令获取的分支信息,怎么可以在项目代码里面获取分支信息呢?请看下文👇
execa具备如下特点:
npm install execa -S(async () => {
const {stdout} = await execa('echo', ['unicorns']);
console.log(stdout);
//=> 'unicorns'
})();
// stdout 表示执行命令的输出结果
/*{
command: 'echo unicorns',
escapedCommand: 'echo unicorns',
exitCode: 0,
stdout: '"unicorns"',
stderr: '',
all: undefined,
failed: false,
timedOut: false,
isCanceled: false,
killed: false
}*/execa还可以执行脚本命令,并输出结果,下面看一下如何在代码里面获取当前操作的分支👇
function getGitBranch() {
const res = execa.commandSync('git rev-parse --abbrev-ref HEAD');
return res.stdout;
}
const curbranch = getGitBranch()
console.log('curbranch==', curbranch); // master
// 以下是res输出
curbranch== master
{
command: 'git rev-parse --abbrev-ref HEAD',
escapedCommand: 'git rev-parse --abbrev-ref HEAD',
exitCode: 0,
stdout: 'master', # 命令执行结果输出
stderr: '',
failed: false,
timedOut: false,
isCanceled: false,
killed: false
}下面说一下脚本获取方式
我在掘金 git编写脚本 组合 commit-msg 一文中使用脚本获取分支信息,感兴趣可以看一下。
.git/HEAD 文件中的内容HEAD指向最新放入仓库的版本
ref: refs/heads/dev_0922#!/bin/bash
# 获取当前分支
line=$(head -n +1 .git/HEAD)
branch=${line##*/}
echo $branch # dev_0922