使用 node.js 获取当前的 git 分支

use*_*917 6 git node.js

如何在没有外部库的情况下使用 node.js 获取当前的 git 分支?我需要能够获取当前分支名称以在我的节点文件中执行另一个功能。

更新部分工作代码

我可以用这个获取分支名称,但如果stdout匹配给定的字符串,似乎无法注销消息。

const { exec } = require('child_process');
exec('git rev-parse --abbrev-ref HEAD', (err, stdout, stderr) => {
    if (stdout === 'name-of-branch') {
        console.log(this is the correct branch);
    }
});
Run Code Online (Sandbox Code Playgroud)

Aay*_*all 10

请试试这个作品

const { exec } = require('child_process');
exec('git rev-parse --abbrev-ref HEAD', (err, stdout, stderr) => {
    if (err) {
        // handle your error
    }

    if (typeof stdout === 'string' && (stdout.trim() === 'master')) {
      console.log(`The branch is master`);
      // Call your function here conditionally as per branch
    }
});
Run Code Online (Sandbox Code Playgroud)

接收输出为

$: node test.js 
The branch is master
Run Code Online (Sandbox Code Playgroud)


Jak*_* S. 8

这应该这样做:

const { exec } = require('child_process');
exec('git branch --show-current', (err, stdout, stderr) => {
    if (err) {
        // handle your error
    }
});
Run Code Online (Sandbox Code Playgroud)

stdout变量将包含您的分支名称。你需要安装 git 才能工作。


jas*_*ner 5

只需将@Aayush Mall的答案添加为 ES6 模块,这样您就可以在项目中的任何位置获取当前分支并按照您喜欢的方式使用。

import { exec } from 'child_process';

const getBranch = () => new Promise((resolve, reject) => {
    return exec('git rev-parse --abbrev-ref HEAD', (err, stdout, stderr) => {
        if (err)
            reject(`getBranch Error: ${err}`);
        else if (typeof stdout === 'string')
            resolve(stdout.trim());
    });
});

export { getBranch }


// --- --- Another File / Module --- ---

import { getBranch } from './moduleLocation.mjs'

const someAsyncFunction = async () => {
  console.log(await getBranch()); 
}

someAsyncFunction();
Run Code Online (Sandbox Code Playgroud)