steveukx / git-js

A light weight interface for running git commands in any node.js application.
MIT License
3.43k stars 313 forks source link

Simple Git

NPM version

A lightweight interface for running git commands in any node.js application.

Installation

Use your favourite package manager:

System Dependencies

Requires git to be installed and that it can be called using the command git.

Usage

Include into your JavaScript app using common js:

// require the library, main export is a function
const simpleGit = require('simple-git');
simpleGit().clean(simpleGit.CleanOptions.FORCE);

// or use named properties
const { simpleGit, CleanOptions } = require('simple-git');
simpleGit().clean(CleanOptions.FORCE);

Include into your JavaScript app as an ES Module:

import { simpleGit, CleanOptions } from 'simple-git';

simpleGit().clean(CleanOptions.FORCE);

Include in a TypeScript app using the bundled type definitions:

import { simpleGit, SimpleGit, CleanOptions } from 'simple-git';

const git: SimpleGit = simpleGit().clean(CleanOptions.FORCE);

Configuration

Configure each simple-git instance with a properties object passed to the main simpleGit function:

import { simpleGit, SimpleGit, SimpleGitOptions } from 'simple-git';

const options: Partial<SimpleGitOptions> = {
   baseDir: process.cwd(),
   binary: 'git',
   maxConcurrentProcesses: 6,
   trimmed: false,
};

// when setting all options in a single object
const git: SimpleGit = simpleGit(options);

// or split out the baseDir, supported for backward compatibility
const git: SimpleGit = simpleGit('/some/path', { binary: 'git' });

The first argument can be either a string (representing the working directory for git commands to run in), SimpleGitOptions object or undefined, the second parameter is an optional SimpleGitOptions object.

All configuration properties are optional, the default values are shown in the example above.

Per-command Configuration

To prefix the commands run by simple-git with custom configuration not saved in the git config (ie: using the -c command) supply a config option to the instance builder:

// configure the instance with a custom configuration property
const git: SimpleGit = simpleGit('/some/path', { config: ['http.proxy=someproxy'] });

// any command executed will be prefixed with this config
// runs: git -c http.proxy=someproxy pull
await git.pull();

Configuring Plugins

Using Task Promises

Each task in the API returns the simpleGit instance for chaining together multiple tasks, and each step in the chain is also a Promise that can be await ed in an async function or returned in a Promise chain.

const git = simpleGit();

// chain together tasks to await final result
await git.init().addRemote('origin', '...remote.git');

// or await each step individually
await git.init();
await git.addRemote('origin', '...remote.git');

Catching errors in async code

To catch errors in async code, either wrap the whole chain in a try/catch:

const git = simpleGit();
try {
   await git.init();
   await git.addRemote(name, repoUrl);
} catch (e) {
   /* handle all errors here */
}

or catch individual steps to permit the main chain to carry on executing rather than jumping to the final catch on the first error:

const git = simpleGit();
try {
   await git.init().catch(ignoreError);
   await git.addRemote(name, repoUrl);
} catch (e) {
   /* handle all errors here */
}

function ignoreError() {}

Using Task Callbacks

In addition to returning a promise, each method can also be called with a trailing callback argument to handle the result of the task.

const git = simpleGit();
git.init(onInit).addRemote('origin', 'git@github.com:steveukx/git-js.git', onRemoteAdd);

function onInit(err, initResult) {}
function onRemoteAdd(err, addRemoteResult) {}

If any of the steps in the chain result in an error, all pending steps will be cancelled, see the parallel tasks section for more information on how to run tasks in parallel rather than in series .

Task Responses

Whether using a trailing callback or a Promise, tasks either return the raw string or Buffer response from the git binary, or where possible a parsed interpretation of the response.

For type details of the response for each of the tasks, please see the TypeScript definitions.

Upgrading from Version 2

From v3 of simple-git you can now import as an ES module, Common JS module or as TypeScript with bundled type definitions. Upgrading from v2 will be seamless for any application not relying on APIs that were marked as deprecated in v2 (deprecation notices were logged to stdout as console.warn in v2).

API

API What it does
.add([fileA, ...], handlerFn) adds one or more files to be under source control
.addAnnotatedTag(tagName, tagMessage, handlerFn) adds an annotated tag to the head of the current branch
.addTag(name, handlerFn) adds a lightweight tag to the head of the current branch
.catFile(options, [handlerFn]) generate cat-file detail, options should be an array of strings as supported arguments to the cat-file command
.checkIgnore([filepath, ...], handlerFn) checks if filepath excluded by .gitignore rules
.clearQueue() immediately clears the queue of pending tasks (note: any command currently in progress will still call its completion callback)
.commit(message, handlerFn) commits changes in the current working directory with the supplied message where the message can be either a single string or array of strings to be passed as separate arguments (the git command line interface converts these to be separated by double line breaks)
.commit(message, [fileA, ...], options, handlerFn) commits changes on the named files with the supplied message, when supplied, the optional options object can contain any other parameters to pass to the commit command, setting the value of the property to be a string will add name=value to the command string, setting any other type of value will result in just the key from the object being passed (ie: just name), an example of setting the author is below
.customBinary(gitPath) sets the command to use to reference git, allows for using a git binary not available on the path environment variable docs
.env(name, value) Set environment variables to be passed to the spawned child processes, see usage in detail below.
.exec(handlerFn) calls a simple function in the current step
.fetch([options, ] handlerFn) update the local working copy database with changes from the default remote repo and branch, when supplied the options argument can be a standard options object either an array of string commands as supported by the git fetch.
.fetch(remote, branch, handlerFn) update the local working copy database with changes from a remote repo
.fetch(handlerFn) update the local working copy database with changes from the default remote repo and branch
.outputHandler(handlerFn) attaches a handler that will be called with the name of the command being run and the stdout and stderr readable streams created by the child process running that command, see examples
.raw(args, [handlerFn]) Execute any arbitrary array of commands supported by the underlying git binary. When the git process returns a non-zero signal on exit and it printed something to stderr, the command will be treated as an error, otherwise treated as a success.
.rebase([options,] handlerFn) Rebases the repo, options should be supplied as an array of string parameters supported by the git rebase command, or an object of options (see details below for option formats).
.revert(commit , [options , [handlerFn]]) reverts one or more commits in the working copy. The commit can be any regular commit-ish value (hash, name or offset such as HEAD~2) or a range of commits (eg: master~5..master~2). When supplied the options argument contain any options accepted by git-revert.
.rm([fileA, ...], handlerFn) removes any number of files from source control
.rmKeepLocal([fileA, ...], handlerFn) removes files from source control but leaves them on disk
.tag(args[], handlerFn) Runs any supported git tag commands with arguments passed as an array of strings .
.tags([options, ] handlerFn) list all tags, use the optional options object to set any options allows by the git tag command. Tags will be sorted by semantic version number by default, for git versions 2.7 and above, use the --sort option to set a custom sort.

git apply

git branch

git clean

git checkout

git clone

git config

git count-objects

git diff

git grep examples

git hash-object

git init

git log

git merge

git mv

git pull

git push

git remote

git reset

git rev-parse / repo properties

git show

git status

git submodule

git stash

git version examples

changing the working directory examples

How to Specify Options

Where the task accepts custom options (eg: pull or commit), these can be supplied as an object, the keys of which will all be merged as trailing arguments in the command string, or as a simple array of strings.

Options as an Object

When the value of the property in the options object is a string, that name value pair will be included in the command string as name=value. For example:

// results in 'git pull origin master --no-rebase'
git.pull('origin', 'master', { '--no-rebase': null });

// results in 'git pull origin master --rebase=true'
git.pull('origin', 'master', { '--rebase': 'true' });

Options as an Array

Options can also be supplied as an array of strings to be merged into the task's commands in the same way as when an object is used:

// results in 'git pull origin master --no-rebase'
git.pull('origin', 'master', ['--no-rebase']);

Release History

Major release 3.x changes the packaging of the library, making it consumable as a CommonJS module, ES module as well as with TypeScript (see usage above). The library is now published as a single file, so please ensure your application hasn't been making use of non-documented APIs by importing from a sub-directory path.

See also:

Concurrent / Parallel Requests

When the methods of simple-git are chained together, they create an execution chain that will run in series, useful for when the tasks themselves are order-dependent, eg:

simpleGit().init().addRemote('origin', 'https://some-repo.git').fetch();

Each task requires that the one before it has been run successfully before it is called, any errors in a step of the chain should prevent later steps from being attempted.

When the methods of simple-git are called on the root instance (ie: git = simpleGit()) rather than chained off another task, it starts a new chain and will not be affected failures in tasks already being run. Useful for when the tasks are independent of each other, eg:

const git = simpleGit();
const results = await Promise.all([
   git.raw('rev-parse', '--show-cdup').catch(swallow),
   git.raw('rev-parse', '--show-prefix').catch(swallow),
]);
function swallow(err) {
   return null;
}

Each simple-git instance limits the number of spawned child processes that can be run simultaneously and manages the queue of pending tasks for you. Configure this value by passing an options object to the simpleGit function, eg:

const git = simpleGit({ maxConcurrentProcesses: 10 });

Treating tasks called on the root instance as the start of separate chains is a change to the behaviour of simple-git and was added in version 2.11.0.

Complex Requests

When no suitable wrapper exists in the interface for creating a request, run the command directly using git.raw([...], handler). The array of commands are passed directly to the git binary:

const path = '/path/to/repo';
const commands = ['config', '--global', 'advice.pushNonFastForward', 'false'];

// using an array of commands and node-style callback
simpleGit(path).raw(commands, (err, result) => {
   // err is null unless this command failed
   // result is the raw output of this command
});

// using a var-args of strings and awaiting rather than using the callback
const result = await simpleGit(path).raw(...commands);

// automatically trim trailing white-space in responses
const result = await simpleGit(path, { trimmed: true }).raw(...commands);

Authentication

The easiest way to supply a username / password to the remote host is to include it in the URL, for example:

const USER = 'something';
const PASS = 'somewhere';
const REPO = 'github.com/username/private-repo';

const remote = `https://${USER}:${PASS}@${REPO}`;

simpleGit()
   .clone(remote)
   .then(() => console.log('finished'))
   .catch((err) => console.error('failed: ', err));

Be sure to not enable debug logging when using this mechanism for authentication to ensure passwords aren't logged to stdout.

Environment Variables

Pass one or more environment variables to the child processes spawned by simple-git with the .env method which supports passing either an object of name=value pairs or setting a single variable at a time:

const GIT_SSH_COMMAND = 'ssh -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no';

simpleGit()
   .env('GIT_SSH_COMMAND', GIT_SSH_COMMAND)
   .status((err, status) => {
      /*  */
   });

simpleGit()
   .env({ ...process.env, GIT_SSH_COMMAND })
   .status()
   .then((status) => {})
   .catch((err) => {});

Note - when passing environment variables into the child process, these will replace the standard process.env variables, the example above creates a new object based on process.env but with the GIT_SSH_COMMAND property added.

Exception Handling

When the git process exits with a non-zero status (or in some cases like merge the git process exits with a successful zero code but there are conflicts in the merge) the task will reject with a GitError when there is no available parser to handle the error or a GitResponseError for when there is.

See the err property of the callback:

git.merge((err, mergeSummary) => {
   if (err.git) {
      mergeSummary = err.git; // the failed mergeSummary
   }
});

Catch errors with try/catch in async code:

try {
   const mergeSummary = await git.merge();
   console.log(`Merged ${mergeSummary.merges.length} files`);
} catch (err) {
   // err.message - the string summary of the error
   // err.stack - some stack trace detail
   // err.git - where a parser was able to run, this is the parsed content

   console.error(`Merge resulted in ${err.git.conflicts.length} conflicts`);
}

Catch errors with a .catch on the promise:

const mergeSummary = await git.merge().catch((err) => {
   if (err.git) {
      return err.git;
   } // the unsuccessful mergeSummary
   throw err; // some other error, so throw
});

if (mergeSummary.failed) {
   console.error(`Merge resulted in ${mergeSummary.conflicts.length} conflicts`);
}

With typed errors available in TypeScript

import { simpleGit, MergeSummary, GitResponseError } from 'simple-git';
try {
   const mergeSummary = await simpleGit().merge();
   console.log(`Merged ${mergeSummary.merges.length} files`);
} catch (err) {
   // err.message - the string summary of the error
   // err.stack - some stack trace detail
   // err.git - where a parser was able to run, this is the parsed content
   const mergeSummary: MergeSummary = (err as GitResponseError<MergeSummary>).git;
   const conflicts = mergeSummary?.conflicts || [];

   console.error(`Merge resulted in ${conflicts.length} conflicts`);
}

Troubleshooting / FAQ

Enable logging

See the debug logging guide for logging examples and how to make use of the debug library's programmatic interface in your application.

Enable Verbose Logging

See the debug logging guide for the full list of verbose logging options to use with the debug library.

Every command returns ENOENT error message

There are a few potential reasons:

Log format fails

The properties of git log are fetched using the --pretty=format argument which supports different tokens depending on the version of git - for example the %D token used to show the refs was added in git 2.2.3, for any version before that please ensure you are supplying your own format object with properties supported by the version of git you are using.

For more details of the supported tokens, please see the official git log documentation

Log response properties are out of order

The properties of git.log are fetched using the character sequence ò as a delimiter. If your commit messages use this sequence, supply a custom splitter in the options, for example: git.log({ splitter: '💻' })

Pull / Diff / Merge summary responses don't recognise any files

In some cases git will show progress messages or additional detail on error states in the output for stdErr that will help debug your issue, these messages are also included in the verbose log.

Legacy Node Versions

From v3.x, simple-git will drop support for node.js version 10 or below, to use in a lower version of node will result in errors such as:

To resolve these issues, either upgrade to a newer version of node.js or ensure you are using the necessary polyfills from core-js - see Legacy Node Versions.

Examples

using a pathspec to limit the scope of the task

If the simple-git API doesn't explicitly limit the scope of the task being run (ie: git.add() requires the files to be added, but git.status() will run against the entire repo), add a pathspec to the command using trailing options:

import { simpleGit, pathspec } from "simple-git";

const git = simpleGit();
const wholeRepoStatus = await git.status();
const subDirStatusUsingOptArray = await git.status([pathspec('sub-dir')]);
const subDirStatusUsingOptObject = await git.status({ 'sub-dir': pathspec('sub-dir') });

async await

async function status(workingDir) {
   let statusSummary = null;
   try {
      statusSummary = await simpleGit(workingDir).status();
   } catch (e) {
      // handle the error
   }

   return statusSummary;
}

// using the async function
status(__dirname + '/some-repo').then((status) => console.log(status));

Initialise a git repo if necessary

const git = simpleGit(__dirname);

git.checkIsRepo()
   .then((isRepo) => !isRepo && initialiseRepo(git))
   .then(() => git.fetch());

function initialiseRepo(git) {
   return git.init().then(() => git.addRemote('origin', 'https://some.git.repo'));
}

Update repo and get a list of tags

simpleGit(__dirname + '/some-repo')
   .pull()
   .tags((err, tags) => console.log('Latest available tag: %s', tags.latest));

// update repo and when there are changes, restart the app
simpleGit().pull((err, update) => {
   if (update && update.summary.changes) {
      require('child_process').exec('npm restart');
   }
});

Starting a new repo

simpleGit()
   .init()
   .add('./*')
   .commit('first commit!')
   .addRemote('origin', 'https://github.com/user/repo.git')
   .push('origin', 'master');

push with -u

simpleGit()
   .add('./*')
   .commit('first commit!')
   .addRemote('origin', 'some-repo-url')
   .push(['-u', 'origin', 'master'], () => console.log('done'));

Piping to the console for long-running tasks

See progress events for more details on logging progress updates.

const git = simpleGit({
   progress({ method, stage, progress }) {
      console.log(`git.${method} ${stage} stage ${progress}% complete`);
   },
});
git.checkout('https://github.com/user/repo.git');

Update repo and print messages when there are changes, restart the app

// when using a chain
simpleGit()
   .exec(() => console.log('Starting pull...'))
   .pull((err, update) => {
      if (update && update.summary.changes) {
         require('child_process').exec('npm restart');
      }
   })
   .exec(() => console.log('pull done.'));

// when using async and optional chaining
const git = simpleGit();
console.log('Starting pull...');
if ((await git.pull())?.summary.changes) {
   require('child_process').exec('npm restart');
}
console.log('pull done.');

Get a full commits list, and then only between 0.11.0 and 0.12.0 tags

console.log(await simpleGit().log());
console.log(await simpleGit().log('0.11.0', '0.12.0'));

Set the local configuration for author, then author for an individual commit

simpleGit()
   .addConfig('user.name', 'Some One')
   .addConfig('user.email', 'some@one.com')
   .commit('committed as "Some One"', 'file-one')
   .commit('committed as "Another Person"', 'file-two', {
      '--author': '"Another Person <another@person.com>"',
   });

Get remote repositories

simpleGit().listRemote(['--get-url'], (err, data) => {
   if (!err) {
      console.log('Remote url for repository at ' + __dirname + ':');
      console.log(data);
   }
});