Uncle Gus
Uncle Gus

Reputation: 61

How to execute git commands from node using standard terminal commands

I am trying to merge branches into a main branch programmatically, using a node script. The first thing I tried was from Execute a command line binary with Node.js, which worked fine for executing terminal commands. But I encountered difficulties with changing the working directory. I wanted to change the working directory to the git repository, then run git commands from there. Executing cd ~/repo or cd /home/me/repo did not change the working directory at all and I could not find any way to change it other than using cd.

I then tried executing the git commands from the script's directory but pointed at my repo. I tried git --git-dir and git --work-tree but neither of those commands worked. The error was the same: fatal: Not a git repository (or any of the parent directories): .git I'm guessing this is because the directory where the script is running from is not a git repo.

So, I either want to send git commands to a directory other than the one I am running the script from, or I want a way to change the script's working directory. Preferably the latter. My full code and output is below:

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

Output:

> [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

Upvotes: 2

Views: 4822

Answers (2)

Uncle Gus
Uncle Gus

Reputation: 61

I got around this problem by using ShellJS. ShellJS has a method .cd() which changes the directory and seems to stick.

Upvotes: 1

VonC
VonC

Reputation: 1329082

Try instead with:

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

That will execute the git command in the context of your git repo /path/to/git/repo

Upvotes: 1

Related Questions