Get hash of most recent git commit in Node

后端 未结 7 1739
礼貌的吻别
礼貌的吻别 2020-12-24 01:57

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

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

相关标签:
7条回答
  • 2020-12-24 02:08

    Here's a version I worked up that uses fs.promises and async/await.

    import {default as fsWithCallbacks} from 'fs';
    const fs = fsWithCallbacks.promises;
    
    const getGitId = async () => {
      const gitId = await fs.readFile('.git/HEAD', 'utf8');
      if (gitId.indexOf(':') === -1) {
        return gitId;
      }
      const refPath = '.git/' + gitId.substring(5).trim();
      return await fs.readFile(refPath, 'utf8');
    };
    
    const gitId = await getGitId();
    
    0 讨论(0)
  • 2020-12-24 02:14

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

    Optionally, you can use execSync() to avoid the callback.

    Solution #2 (no git required):

    • 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();
    }
    
    0 讨论(0)
  • 2020-12-24 02:17

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

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

    0 讨论(0)
  • 2020-12-24 02:17

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

    const fs = require('fs');
    const util = require('util');
    
    util.promisify(fs.readFile)('.git/refs/heads/master').then((hash) => {
        console.log(hash.toString().trim());
    });
    
    0 讨论(0)
  • 2020-12-24 02:21

    You can also use git-fs (it's name on npm is git-fs, on Github it's 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.

    0 讨论(0)
  • 2020-12-24 02:25

    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():

    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
    } );
    
    0 讨论(0)
提交回复
热议问题