如何使用标准的terminal命令从节点执行git命令
我正在尝试以编程方式使用节点脚本将分支合并到主分支。 我尝试的第一件事是从Node.js执行一个命令行二进制文件 ,这对于执行terminal命令来说工作得很好。 但是我遇到了改变工作目录的困难。 我想改变工作目录到git仓库,然后从那里运行git命令。 执行cd ~/repo
或cd /home/me/repo
根本不会改变工作目录,除了使用cd
之外,我找不到任何方法来改变它。
我接下来尝试从脚本的目录执行git命令,但指向我的回购。 我试过git --git-dir
和git --work-tree
但是这两个命令都没有工作。 错误是一样的: fatal: Not a git repository (or any of the parent directories): .git
我猜这是因为脚本运行的目录fatal: Not a git repository (or any of the parent directories): .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); }) } } })();
输出:
> 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 -C /path/to/git/repo your_git_command
这将在你的git repo /path/to/git/repo
的上下文中执行git命令
我通过使用ShellJS来解决这个问题。 ShellJS有一个方法.cd()
改变目录,似乎坚持。