Get Branch Name & Commit ID without Git

Git

可以使用 Git 命令行工具获取到当前使用的分支名称,最新的 Git Commit ID 等信息。然而,在不借助 Git 命令的情况下,依然可以通过 .git 文件,找到这些信息。

在 .git 文件夹中,HEAD 文件记录了当前分支的指向。文件内容 refs 后面跟着的就是分支名。这个分支名亦是一个路径,在 .git 目录下使用这个相对路径可以得到当前分支指向的头部 Commit ID。

举个例子:

发现 ./.git/HEAD 中的内容是:ref: refs/heads/master,通过查看 ./.git/refs/heads/master 文件中的内容,就可以知道当前的头部 Commit ID。同样,去除 refs/heads 之后,就可以得到当前的分支名称,即 master

对应的 Node.js 代码如下:

const git = path.resolve(process.cwd(), '.git');
const head = path.resolve(git, 'HEAD');
const ref = fs.readFileSync(head, 'utf8').trim().substr('ref: '.length);
const commit = fs.readFileSync(path.resolve(git, ref), 'utf8').trim();
const branch = ref.substr('refs/heads/'.length);

console.log(branch, commit);