获取Node中最新的git提交的散列

我想在NodeJS的当前分支上得到最近提交的id / hash。

在NodeJS中,我想获得最近的id / hash,就git和提交而言。

除了Paulpro答案你可以使用exec

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

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

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

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

使用nodegit ,将path_to_repo定义为一个string,其中包含要获取commit的shao的path。 如果您想使用您的进程正在运行的目录,则用process.cwd()replacepath_to_repo

 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 } ); 

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

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

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

如果你总是在特定的分支上,你可以阅读.git/refs/heads/<branch_name>来轻松获得提交哈希。

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