【问题标题】:How to execute git commands from node using standard terminal commands如何使用标准终端命令从节点执行 git 命令
【发布时间】:2018-03-28 15:36:39
【问题描述】:

我正在尝试使用节点脚本以编程方式将分支合并到主分支中。我尝试的第一件事是来自Execute a command line binary with Node.js,它可以很好地执行终端命令。但是我在更改工作目录时遇到了困难。我想将工作目录更改为 git 存储库,然后从那里运行 git 命令。执行cd ~/repocd /home/me/repo 根本没有改变工作目录,除了使用cd 之外我找不到任何方法来改变它。

然后我尝试从脚本目录执行 git 命令,但指向我的仓库。我尝试了git --git-dirgit --work-tree,但这些命令都不起作用。错误是一样的:fatal: Not a git repository (or any of the parent directories): .git 我猜这是因为运行脚本的目录不是 git repo。

所以,我要么想将 git 命令发送到我运行脚本的目录以外的目录,要么我想改变脚本的工作目录。最好是后者。我的完整代码和输出如下:

import JiraData from './jiradata';
const jiraData = new JiraData();
const { exec } = require('child_process');

(async function () {
    const cards = await jiraData.getCardsInTest();
    let commands = ['cd /home/me/repo', 'pwd'];
    let proceeding = true;
    // for (const card of cards) {
    //     commands.push(`git merge origin/${card} --commit --no-edit`);
    // }

    for (const command of commands) {
        if (proceeding) {
            console.log(`Executing command "${command}"`);
            exec(command, (err, stdout, stderr) => {
                if (err) {
                    proceeding = false;
                    console.log(stderr);
                    return;
                }
                console.log(stdout);
            })
        }
    }
})();

输出:

> ci@1.0.0 start /home/me/CI
> babel-node index.js --presets es2015,stage-2

Executing command "cd /home/me/repo"
Executing command "pwd"
/home/me/CI

【问题讨论】:

  • 试试git --git-dir=/home/me/repo/.git --work-tree=/home/me/repo merge foo。不要使用~ 替换路径中的/home/me
  • 您将其作为子进程而不是使用 npm git 包的任何特殊原因?使用它大约容易一百万倍......npmjs.com/package/nodegit

标签: node.js git bash


【解决方案1】:

尝试改为:

git -C /path/to/git/repo your_git_command

这将在你的 git repo /path/to/git/repo 上下文中执行 git 命令

【讨论】:

  • 谢谢,我会试试的。我确实已经为这种情况找到了解决方案,但可能值得简化它以使用您的建议。
【解决方案2】:

我通过使用 ShellJS 解决了这个问题。 ShellJS 有一个方法.cd(),它改变了目录并且似乎坚持了下来。

【讨论】:

    猜你喜欢
    • 2014-12-15
    • 1970-01-01
    • 1970-01-01
    • 2016-08-21
    • 2012-05-22
    • 1970-01-01
    • 1970-01-01
    • 2015-02-11
    • 2015-05-27
    相关资源
    最近更新 更多