获取Node中最近一次git提交的哈希值 您所在的位置:网站首页 nodegit 获取Node中最近一次git提交的哈希值

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

2023-04-19 06:23| 来源: 网络整理| 查看: 265

百度翻译此文   有道翻译此文 问题描述

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 commits thereof.

推荐答案

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().trim(); if (rev.indexOf(':') === -1) { return rev; } else { return fs.readFileSync('.git/' + rev.substring(5)).toString().trim(); } 其他推荐答案

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

其他推荐答案

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


【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有