2017-10-17 143 views
1

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

我接下来尝试从脚本目录执行git命令,但指向我的回购。我试过git --git-dirgit --work-tree,但这些命令都没有奏效。错误是一样的:fatal: Not a git repository (or any of the parent directories): .git我猜这是因为脚本运行的目录不是一个git仓库。

所以我要么发送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); 
      }) 
     } 
    } 
})(); 

输出:

> [email protected] start /home/me/CI 
> babel-node index.js --presets es2015,stage-2 

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

试试'git --git-dir =/home/me/repo/.git --work-tree =/home/me/repo merge foo'。不要使用'〜'来替换路径中的'/ home/me'。 – ElpieKay

+0

为什么你要这样做,而不是使用npm git包作为子进程?使用它时容易一百万倍... https://www.npmjs.com/package/nodegit – dvsoukup

回答

0

尝试,而不是用:

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

这会在你的混帐回购协议的上下文中执行git的命令/path/to/git/repo

+0

谢谢,我会试试看。我确实已经为这种情况找到了解决方案,但可能需要简化它才能使用您的建议。 –

0

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