获取Node中最新的git commit的哈希 [英] Get hash of most recent git commit in Node
本文介绍了获取Node中最新的git commit的哈希的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想获取NodeJS当前分支上最新提交的ID/哈希值.
I'd like to get the id/hash of the most recent commit on the current branch in NodeJS.
在NodeJS中,我想获取有关git及其提交的最新id/哈希值.
In NodeJS, I'd like to get the most recent id/hash, with respect to git and commits thereof.
推荐答案
解决方案1(需要git,带有回调):
Solution #1 (git required, with callback):
require('child_process').exec('git rev-parse HEAD', function(err, stdout) {
console.log('Last commit hash on this branch is:', stdout);
});
(可选)您可以使用execSync()
避免回调.
Optionally, you can use execSync()
to avoid the callback.
解决方案2(无需git):
Solution #2 (no git required):
- 获取文件
.git/HEAD
的内容
- 如果git repo处于分离头状态,则内容将为哈希值
- 如果git repo在某个分支上,则内容将类似于:"refs:refs/heads/current-branch-name"
- 获取
.git/refs/heads/current-branch-name
的内容
- 处理此过程中所有可能的错误
- 要直接从master分支获取最新的哈希,可以获取文件的内容:
.git/refs/heads/master
- get contents of the file
.git/HEAD
- if the git repo is in the detached head state, the content will be the hash
- if the git repo is on some branch, the content will be something like: "refs: refs/heads/current-branch-name"
- get contents of
.git/refs/heads/current-branch-name
- handle all possible errors in this process
- to get the latest hash from the master branch directly, you can get the contents of the file:
.git/refs/heads/master
可以使用以下代码进行编码:
This can be coded with something like:
const rev = fs.readFileSync('.git/HEAD').toString();
if (rev.indexOf(':') === -1) {
return rev;
} else {
return fs.readFileSync('.git/' + rev.substring(5)).toString();
}
这篇关于获取Node中最新的git commit的哈希的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文