How to execute git commands from node using standard terminal commands - node.js

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

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

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

Related

How can I run curl and prompt for a password when running from npm?

I'm working on a Node.js file to automatically create a new Github repo.
When I run curl -u 'BretCameron' https://api.github.com/user/repos -d '{"name":"test_repo"}' in the terminal, it asks me for my GitHub password and then creates the new repo.
But I can't get this to work in Node, even though the git commands in my sample code are working fine:
const { exec, execSync } = require('child_process');
function run(func) {
console.log(execSync(func).toString())
}
run('touch README.md');
run('git init');
run('git add README.md');
run('git commit -m "First commit"');
exec(`curl -u 'BretCameron' https://api.github.com/user/repos -d '{"name":"test_repo"}'`));
I have tried with the exec and execSync functions from the child_process module, as well as putting it into my helper function run. Can anyone offer some advice?

git pull not executing through a webhook in bash script

I have a node server running on ec2 in ubuntu which should update when I push into master as I have created a hook for that in Gitab integrations.
I saw the hook working through the logs and executing every command expect simple git pull.
I have checked many similar questions which have suggestions like appending env -i to reset the GIT_DIR so that the command can execute but no luck so far.
I tried executing different commands like git status and they are executing through the hook in bash script normally.
Here is my script which is in my home folder along with the repository:
#!bin/bash
cd toTheFolder
git pull
here is the end-point which executes the script
childProcess.exec(
"bash temp.sh",
{ cwd: "/home/ubuntu/repoFolder" },
function(err, stdout, stderr) {
console.log(stdout, stderr);
if (err) {
return res.status(500).send(err);
}
res.status(200).send("OK");
}
);
The error it returns is {"killed":false,"code":1,"signal":null,"cmd":"bash temp.sh"}
Any thoughts on why simple git pull is not working would be a huge help.
-Thanks
EDIT: here is the output of stdout
git#gitlab.com: Permission denied (publickey).
fatal: Could not read from remote repository.
Please make sure you have the correct access rights
and the repository exists.
Use the following command
git pull https://username:password#mygithost.com/my/repository
Remember to replace the [username:password] with your git credentials, [mygithost.com] with your git host ( gitlab, ..etc), [my/repository] with your repository url
It would not work for github anyway cause they removed the username/password authentication support.
For github please check your ssh connection between your server and github.

Node.js Child Processes failing GitHub ssh authentication

Goal
Hello, I am creating a Node.js application to update my code when a push is made automatically.
Problem
Everything works in it, except, the actual git pull. The repo is private and needs to use ssh, however when I use the same command in terminal it works. I have keychaining on so it doesn't ask for my passphrase. Any ideas and how to fix this?
Relevant code
const exec = require("child_process").exec;
exec('cd ' + repo + ' && git pull origin deployment', (egitpull,stdoutgitpull,stderrgitpull)=>{
if(egitpull) return console.error(`git pull exec error:${egitpull}`)
console.log(`git pull stdout: ${stdoutgitpull}`);
console.log(`git pull stderr: ${stderrgitpull}`);
Command run:
cd /mp/ && git pull origin deployment
Out of child process vrs. in child process
Edit:
Removing the passphrase from the key entirely does seem to solve the issue, but I would much prefer having it in there for security reasons.
If you are using an ssh-agent for your ssh keys, try forwarding the SSH_AUTH_SOCK and SSH_AGENT_PID env variables to the child process, like this:
exec('cd ' + repo + ' && git pull origin deployment',
{
env: {
SSH_AUTH_SOCK: process.env.SSH_AUTH_SOCK,
SSH_AGENT_PID: process.env.SSH_AGENT_PID
}
},
(egitpull,stdoutgitpull,stderrgitpull) => {
// ...
});

“bash read command” in nodejs

I wanna write a git hook scripts with nodejs which I'm good at. In bash files, I can get params like this:
#!/bin/bash
read local_ref local_sha remote_ref remote_sha
Is there any same command in nodejs?
#!/usr/bin/env node
"bash read function in nodejs"
here are some module which help u to write command
node-cmd
Simple commandline/terminal interface to allow you to run cli or bash style commands as if you were in the terminal.
shelljs
ShellJS is a portable (Windows/Linux/OS X) implementation of Unix shell commands on top of the Node.js API. You can use it to eliminate your shell script's dependency on Unix while still keeping its familiar and powerful commands. You can also install it globally so you can run it from outside Node projects - say goodbye to those gnarly Bash scripts!
https://www.npmjs.com/package/node-cmd
https://www.npmjs.com/package/shelljs
have a look at this code may help u
var cmd=require('node-cmd');
cmd.get(
git clone https://github.com/RIAEvangelist/node-cmd.git
cd node-cmd
ls
,
function(data){
console.log('the node-cmd cloned dir contains these files :\n\n',data)
}
);
have look on this module
// starting a new repo
require('simple-git')()
.init()
.add('./*')
.commit("first commit!")
.addRemote('origin', 'https://github.com/user/repo.git')
.push('origin', 'master');
// push with -u
require('simple-git')()
.add('./*')
.commit("first commit!")
.addRemote('origin', 'some-repo-url')
.push(['-u', 'origin', 'master'], function () {
// done.
});
https://www.npmjs.com/package/simple-git

Running a command using puppet only if it has not been executed earlier

Suppose I want to make sure that my VM has devstack on it.
exec{ "openstack":
command => "git clone https://git.openstack.org/openstack-dev/devstack",
}
This is the puppet code I write for it and it works fine for the first time. Now I want to put a check. I want to clone the repository only if it has not been done already. How to do that
You say
exec { 'openstack':
command => 'git clone https://git.openstack.org/openstack-dev/devstack',
creates => '/path/to/somewhere/devstack',
cwd => '/path/to/somewhere',
path => '/usr/bin',
}
Now if the directory /path/to/somewhere/devstack exists the clone command won't run.
exec { "openstack":
command => 'git clone https://git.openstack.org/openstack-dev/devstack /path/to/devstack",
unless => 'test -d /path/to/devstack'
}
its a really hacky way to handle this. you should look into the vcsrepo puppet module https://github.com/puppetlabs/puppetlabs-vcsrepo

Resources