Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use node.js to determine if in git directory

I am trying to determine if my node process is running in a git directory. The following works, but is still outputting a fatal error in the console.

function testForGit() {
    try {
        var test = execSync('git rev-parse --is-inside-work-tree', {encoding: 'utf8'});
    } catch (e) {
    }
    return !!test;
}

console.log(testForGit());

When in a directory under the control of git, I get true as the result. But when outside of a directory under the control of git, I get:

fatal: Not a git repository (or any of the parent directories): .git
false

My question(s):

Is there a way to suppress the error being logged? Or is there a better way to determine if I am in a directory under git control?

Essentially, I am trying to do the bash equivalent of

if git rev-parse --git-dir > /dev/null 2>&1; then
    ... do something
fi
like image 496
KevBot Avatar asked May 12 '16 22:05

KevBot


1 Answers

If you use docker and don't want to install git as a system-level dependency when build image for your application. Maybe because we want to build the image faster and keep the image size as small as possible.

The way @janos provides will not work.

Another way is to check is there a .git directory or not in root path of your project. But it depends on your requirements. For my case, it's enough.

exports.isGitSync = function isGitSync (dir) {
  return fs.existsSync(path.join(dir, '.git'))
}
like image 72
slideshowp2 Avatar answered Oct 11 '22 11:10

slideshowp2