获取Node中最近的git提交的哈希值

[英]Get hash of most recent git commit in Node


I'd like to get the id/hash of the most recent commit on the current branch in NodeJS.

我想在NodeJS中获取当前分支上最近提交的id / hash。

In NodeJS, I'd like to get the most recent id/hash, with respect to git and commits thereof.

在NodeJS中,我想获得最新的id / hash,关于git和commits。

5 个解决方案

#1


20  

In addition to Paulpro answer you can use exec.

除了Paulpro的答案,你可以使用exec。

require('child_process').exec('git rev-parse HEAD', function(err, stdout) {
    console.log('Last commit hash on this branch is:', stdout);
});

#2


57  

Short solution, no external module needed (synchronous alternative to Edin's answer):

简短的解决方案,无需外部模块(同步替代Edin的答案):

revision = require('child_process')
  .execSync('git rev-parse HEAD')
  .toString().trim()

and if you want to manually specify the root directory of the git project, use the second argument of execSync to pass the cwd option, like execSync('git rev-parse HEAD', {cwd: __dirname})

如果你想手动指定git项目的根目录,使用execSync的第二个参数传递cwd选项,如execSync('git rev-parse HEAD',{cwd:__dirname})

#3


9  

Using nodegit, with path_to_repo defined as a string containing the path to the repo you want to get the commit sha for. If you want to use the directory your process is running from, then replace path_to_repo with process.cwd():

使用nodegit,将path_to_repo定义为包含要获取提交sha的repo路径的字符串。如果要使用运行该进程的目录,请将path_to_repo替换为process.cwd():

var Git = require( 'nodegit' );

Git.Repository.open( path_to_repo ).then( function( repository ) {
  return repository.getHeadCommit( );
} ).then( function ( commit ) {
  return commit.sha();
} ).then( function ( hash ) {
  // use `hash` here
} );

#4


0  

You can also use git-fs (it's name on npm is git-fs, on Github it's node-git.)

你也可以使用git-fs(它在npm上的名字是git-fs,在Github上它是node-git。)

Git('path/to/repo')
Git.getHead((err, sha) => {
    console.log('The hash is: ' + sha)
})

The same module can read directories and files from the repo.

同一模块可以从repo读取目录和文件。

#5


0  

If you are always on specific branch, you can read .git/refs/heads/<branch_name> to easily get commit hash.

如果您始终在特定分支上,则可以阅读.git / refs / heads / 以轻松获取提交哈希。

const fs = require('fs');
const util = require('util');

util.promisify(fs.readFile)('.git/refs/heads/master').then((hash) => {
    console.log(hash.toString().trim());
});

注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2015/12/29/95a6b3492ca9a657854374cb5c5eea79.html



 
粤ICP备14056181号  © 2014-2020 ITdaan.com