Code Monkey home page Code Monkey logo

git-js's Introduction

Simple Git

NPM version

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

Installation

Use your favourite package manager:

  • npm: npm install simple-git
  • yarn: yarn add simple-git

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

  • AbortController Terminate pending and future tasks in a simple-git instance (requires node >= 16).

  • Custom Binary Customise the git binary simple-git uses when spawning git child processes.

  • Completion Detection Customise how simple-git detects the end of a git process.

  • Error Detection Customise the detection of errors from the underlying git process.

  • Progress Events Receive progress events as git works through long-running processes.

  • Spawned Process Ownership Configure the system uid / gid to use for spawned git processes.

  • Timeout Automatically kill the wrapped git process after a rolling timeout.

  • Unsafe Selectively opt out of simple-git safety precautions - for advanced users and use cases.

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', '[email protected]: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

  • .applyPatch(patch, [options]) applies a single string patch (as generated by git diff), optionally configured with the supplied options to set any arguments supported by the apply command. Returns the unmodified string response from stdout of the git binary.
  • .applyPatch(patches, [options]) applies an array of string patches (as generated by git diff), optionally configured with the supplied options to set any arguments supported by the apply command. Returns the unmodified string response from stdout of the git binary.

git branch

  • .branch([options]) uses the supplied options to run any arguments supported by the branch command. Either returns a BranchSummaryResult instance when listing branches, or a BranchSingleDeleteResult type object when the options included -d, -D or --delete which cause it to delete a named branch rather than list existing branches.
  • .branchLocal() gets a list of local branches as a BranchSummaryResult instance
  • .deleteLocalBranch(branchName) deletes a local branch - treats a failed attempt as an error
  • .deleteLocalBranch(branchName, forceDelete) deletes a local branch, optionally explicitly setting forceDelete to true - treats a failed attempt as an error
  • .deleteLocalBranches(branchNames) deletes multiple local branches
  • .deleteLocalBranches(branchNames, forceDelete) deletes multiple local branches, optionally explicitly setting forceDelete to true

git clean

  • .clean(mode) clean the working tree. Mode should be "n" - dry run or "f" - force
  • .clean(cleanSwitches [,options]) set cleanSwitches to a string containing any number of the supported single character options, optionally with a standard options object

git checkout

  • .checkout(checkoutWhat , [options]) - checks out the supplied tag, revision or branch when supplied as a string, additional arguments supported by git checkout can be supplied as an options object/array.

  • .checkout(options) - check out a tag or revision using the supplied options

  • .checkoutBranch(branchName, startPoint) - checks out a new branch from the supplied start point.

  • .checkoutLocalBranch(branchName) - checks out a new local branch

git clone

  • .clone(repoPath, [localPath, [options]]) clone a remote repo at repoPath to a local directory at localPath, optionally with a standard options object of additional arguments to include between git clone and the trailing repo local arguments

  • .clone(repoPath, [options]) clone a remote repo at repoPath to a directory in the current working directory with the same name as the repo

  • mirror(repoPath, [localPath, [options]]) behaves the same as the .clone interface with the --mirror flag enabled.

git config

  • .addConfig(key, value, append = false, scope = 'local') add a local configuration property, when append is set to true the configuration setting is appended to rather than overwritten in the local config. Use the scope argument to pick where to save the new configuration setting (use the exported GitConfigScope enum, or equivalent string values - worktree | local | global | system).

  • .getConfig(key) get the value(s) for a named key as a ConfigGetResult

  • .getConfig(key, scope) get the value(s) for a named key as a ConfigGetResult but limit the scope of the properties searched to a single specified scope (use the exported GitConfigScope enum, or equivalent string values - worktree | local | global | system)

  • .listConfig() reads the current configuration and returns a ConfigListSummary

  • .listConfig(scope: GitConfigScope) as with listConfig but returns only those items in a specified scope (note that configuration values are overlaid on top of each other to build the config git will actually use - to resolve the configuration you are using use (await listConfig()).all without the scope argument)

git count-objects

git diff

  • .diff([ options ]) get the diff of the current repo compared to the last commit, optionally including any number of other arguments supported by git diff supplied as an options object/array. Returns the raw diff output as a string.

  • .diffSummary([ options ]) creates a DiffResult to summarise the diff for files in the repo. Uses the --stat format by default which can be overridden by passing in any of the log format commands (eg: --numstat or --name-stat) as part of the optional options object/array.

git grep examples

  • .grep(searchTerm) searches for a single search term across all files in the working tree, optionally passing a standard options object of additional arguments
  • .grep(grepQueryBuilder(...)) use the grepQueryBuilder to create a complex query to search for, optionally passing a standard options object of additional arguments

git hash-object

  • .hashObject(filePath, write = false) computes the object ID value for the contents of the named file (which can be outside of the work tree), optionally writing the resulting value to the object database.

git init

  • .init(bare , [options]) initialize a repository using the boolean bare parameter to intialise a bare repository. Any number of other arguments supported by git init can be supplied as an options object/array.

  • .init([options]) initialize a repository using any arguments supported by git init supplied as an options object/array.

git log

  • .log([options]) list commits between options.from and options.to tags or branch (if not specified will show all history). Use the options object to set any options supported by the git log command or any of the following:

    • options.file - the path to a file in your repository to only consider this path.
    • options.format - custom log format object, keys are the property names used on the returned object, values are the format string from pretty formats
    • options.from - sets the oldest commit in the range to return, use along with options.to to set a bounded range
    • options.mailMap - defaults to true, enables the use of mail map in returned values for email and name from the default format
    • options.maxCount - equivalent to setting the --max-count option
    • options.multiLine - enables multiline body values in the default format (disabled by default)
    • options.splitter - the character sequence to use as a delimiter between fields in the log, should be a value that doesn't appear in any log message (defaults to ò)
    • options.strictDate - switches the authored date value from an ISO 8601-like format to be strict ISO 8601 format
    • options.symmetric - defaults to true, enables symmetric revision range rather than a two-dot range
    • options.to - sets the newset commit in the range to return, use along with options.from to set a bounded range

    When only one of options.from and options.to is supplied, the default value of the omitted option is equivalent to HEAD. For any other commit, explicitly supply both from and to commits (for example use await git.firstCommit() as the default value of from to log since the first commit of the repo).

git merge

  • .merge(options) runs a merge using any configuration options supported by git merge. Conflicts during the merge result in an error response, the response is an instance of MergeSummary whether it was an error or success. When successful, the MergeSummary has all detail from a the PullSummary along with summary detail for the merge. When the merge failed, the MergeSummary contains summary detail for why the merge failed and which files prevented the merge.

  • .mergeFromTo(remote, branch , [options]) - merge from the specified branch into the currently checked out branch, similar to .merge but with the remote and branch supplied as strings separately to any additional options.

git mv

  • .mv(from, to) rename or move a single file at from to to

  • .mv(from, to) move all files in the from array to the to directory

git pull

  • .pull([options]) pulls all updates from the default tracked remote, any arguments supported by git pull can be supplied as an options object/array.

  • .pull(remote, branch, [options]) pulls all updates from the specified remote branch (eg 'origin'/'master') along with any custom options object/array

git push

  • .push([options]) pushes to a named remote/branch using any supported options from the git push command. Note that simple-git enforces the use of --verbose --porcelain options in order to parse the response. You don't need to supply these options.

  • .push(remote, branch, [options]) pushes to a named remote/branch, supports additional options from the git push command.

  • .pushTags(remote, [options]) pushes local tags to a named remote (equivalent to using .push([remote, '--tags']))

git remote

  • .addRemote(name, repo, [options]) adds a new named remote to be tracked as name at the path repo, optionally with any supported options for the git add call.
  • .getRemotes([verbose]) gets a list of the named remotes, supply the optional verbose option as true to include the URLs and purpose of each ref
  • .listRemote([options]) lists remote repositories - there are so many optional arguments in the underlying git ls-remote call, just supply any you want to use as the optional options eg: git.listRemote(['--heads', '--tags'], console.log)
  • .remote([options]) runs a git remote command with any number of options
  • .removeRemote(name) removes the named remote

git reset

  • .reset(resetMode, [resetOptions]) resets the repository, sets the reset mode to one of the supported types (use a constant from the exported ResetMode enum, or a string equivalent: mixed, soft, hard, merge, keep). Any number of other arguments supported by git reset can be supplied as an options object/array.

  • .reset(resetOptions) resets the repository with the supplied options

  • .reset() resets the repository in soft mode.

git rev-parse / repo properties

  • .revparse([options]) sends the supplied options to git rev-parse and returns the string response from git.

  • .checkIsRepo() gets whether the current working directory is a descendent of a git repository.

  • .checkIsRepo('bare') gets whether the current working directory is within a bare git repo (see either git clone --bare or git init --bare).

  • .checkIsRepo('root') gets whether the current working directory is the root directory for a repo (sub-directories will return false).

  • .firstCommit() gets the commit hash of the first commit made to the current repo.

git show

  • .show(options) show various types of objects for example the file content at a certain commit. options is the single value string or any options supported by the git show command.
  • .showBuffer(options) same as the .show API, but returns the Buffer content directly to allow for showing binary file content.

git status

  • .status([options]) gets the status of the current repo, resulting in a StatusResult. Additional arguments supported by git status can be supplied as an options object/array.

git submodule

  • .subModule(options) Run a git submodule command with on or more arguments passed in as an options array or object
  • .submoduleAdd(repo, path) Adds a new sub module
  • .submoduleInit([options] Initialises sub modules, the optional options argument can be used to pass extra options to the git submodule init command.
  • .submoduleUpdate(subModuleName, [options]) Updates sub modules, can be called with a sub module name and options, just the options or with no arguments

git stash

  • .stash([ options ]) Stash the working directory, optional first argument can be an array of string arguments or options object to pass to the git stash command.

  • .stashList([ options ]) Retrieves the stash list, optional first argument can be an object in the same format as used in git log.

git version examples

  • .version() retrieve the major, minor and patch for the currently installed git. Use the .installed property of the result to determine whether git is accessible on the path.

changing the working directory examples

  • .cwd(workingDirectory) Sets the working directory for all future commands - note, this will change the working for the root instance, any chain created from the root will also be changed.
  • .cwd({ path, root = false }) Sets the working directory for all future commands either in the current chain of commands (where root is omitted or set to false) or in the main instance (where root is true).

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:

  • git isn't available as a binary for the user running the main node process, custom paths to the binary can be used with the .customBinary(...) API option.

  • the working directory passed in to the main simple-git function isn't accessible, check it is read/write accessible by the user running the node process. This library uses @kwsites/file-exists to validate the working directory exists, to output its logs add @kwsites/file-exists to your DEBUG environment variable. eg:

    DEBUG=@kwsites/file-exists,simple-git node ./your-app.js

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

  • Enable verbose logs with the environment variable DEBUG=simple-git:task:*,simple-git:output:*
  • Check the output (for example: simple-git:output:diff:1 [stdOut] 1 file changed, 1 insertion(+))
  • Check the stdOut output is the same as you would expect to see when running the command directly in terminal
  • Check the language used in the response is english locale

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:

  • Object.fromEntries is not a function
  • Object.entries is not a function
  • message.flatMap is not a function

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', '[email protected]')
   .commit('committed as "Some One"', 'file-one')
   .commit('committed as "Another Person"', 'file-two', {
      '--author': '"Another Person <[email protected]>"',
   });

Get remote repositories

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

git-js's People

Contributors

berzeg avatar bumpmann avatar cflynn07 avatar danmpalmer avatar darky avatar denghongcai avatar dependabot[bot] avatar esherouse3 avatar gerdon262-domare avatar github-actions[bot] avatar globegitter avatar guobacai avatar harisbeha avatar honkinggoose avatar hugoruscitti avatar karfau avatar maxhallinan avatar mblaszczyk-atlassian avatar modelbitjason avatar mroswald avatar nromito avatar palashkulsh avatar rhalff avatar shepherdsam avatar snyk-bot avatar stephenlacy avatar stephenlautier avatar stevenorell avatar steveukx avatar vitya1 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

git-js's Issues

Verbose output

Adding an option (or defaulting) to verbose output would be amazing. When cloning large repo's, the script appears to hang.

EG, when cloning, would be amazing to see the native Git output while the clone was in progress.

I'm not a Node expert, though, so let me know if that's an easy change for me to make myself on my machine.

using simple-git before running 'git config'

After rebuilding my webserver, I accidentally did not run git config --global user.email "[email protected]" or git config --global user.name "Your Name". This oversight seemed to cause git.commit() to 'hang'. Here is the general idea:

git('/path/to/repo')
  .add('./*')
  .commit('commit message', function(e, data) {
    console.log(e); //null
    console.log(data); //false
  })
  .revparse(['HEAD'], function(e, data) {
    //not reached
  });

Inside the commit() callback, e is set to null and data is set to false. Additionally, the revparse() callback is not executed.

Is this the intended/expected behavior? If you use git commit from the command line before running either of the config steps, you will see a message that looks something like this:

19:00:28: *** Please tell me who you are.

Run

  git config --global user.email "[email protected]"
  git config --global user.name "Your Name"

Do you think this message should be interpreted as an error? In any case, should git.commit() and related methods provide some sort of indication that the global git config has not been set?

Just thought I'd get your opinion on this before I looked at how to do it.

then() causes TypeError in node v0.10.29 and later

When you use a then() block, you'll get this error with node 0.10.29 and later:

TypeError: Incorrect value of args option
    at Object.exports.spawn (child_process.js:725:11)
    at Git._schedule (/home/airspring/scratch/node_modules/simple-git/src/git.js:651:40)
    at process._tickCallback (node.js:442:13)

Platform: OSX
simple-git: 1.3.0

It works in:

0.10.26
0.10.27
0.10.28

It fails in:

0.10.29
0.10.30
0.10.31
0.10.33
0.10.38

I also tested on Linux, and it failed there too with node 0.10.26.
I did not not test node 0.12.x

I'm suspicious of my report since it means this problem has been undetected since node 0.10.29 was released about a year ago: http://blog.nodejs.org/2014/06/16/node-v0-10-29-stable/ But it's easy to reproduce:

if (process.argv.length < 3) {
    console.log('need a path to a git repo');
    process.exit(-1);
}

var path_to_repo = process.argv[2];
console.log('running git status for ' + path_to_repo);

require('simple-git')(path_to_repo)
     .status(function(err, status) {
     })
     .then(function() {
        console.log('status done.');
     });

Expected behavior: 'status done' prints out without any errors
Actual behavior: message is not printed. The error noted above is seen.

merge command

Thank you for the easy to use library.

I may have missed it, but the current API doesn't seem to support git merge, so to merge branches I am doing this:

simpleGit._run(['merge', 'master', 'branch1'], function(err, data) { ... });

Support for merge would be greatly appreciated.

Results of git-pull are unreliable

I've gotten summary strings with changes: 100644 (obviously the mode, not the change), file listings with ... in them, and missing additions/deletions.

Due to how Git formats the output of pull (even with -v), it might be worthwhile to manually abridge the results of git diff <before-pull>...HEAD instead of trying to parse the output of pull.

simpleGit.pull doesn't detect changes if all changes are deletions

When using git-js to do a pull, it fails to detect if there were changes that were only deletions. If there were no insertions, the "update" parameter returns a response saying that nothing has changed, when in fact I did delete a single line:

{"files":[],"insertions":{},"deletions":{},"summary":{"changes":0,"insertions":0,"deletions":0}}

It appears this is due to this line in git.js: _parsePull:

    var fileUpdateRegex = /^\s*(.+)\s\|\s(\d+)\s([\+]+)/;

The line to capture looks like this:

     src/TestComponent/TestComponent.scss | 1 -

The regular expression will capture if a minus sign is added:

      var fileUpdateRegex = /^\s*(.+)\s\|\s(\d+)\s([\+\-]+)/;

Here is how we are using git-js and then check the results:

 simpleGit.pull('origin', 'staging', function doPull(err, update) {
    try {
      console.log(JSON.stringify(update));
      if (update
        && (Object.keys(update.insertions).length > 0
          || Object.keys(update.deletions).length > 0)) {
      ...

Typo in Fetch

If i try to use the fetch() method I get this error:

C:\Users\dlowerre\full_throttle\node_modules\simple-git\src\git.js:171
then && then(err, !err && this._parsePush(data));
^
TypeError: Object # has no method '_parsePush'

There is indeed no function '_parsePush' defined for the Git object. Perhaps this should be a call to _parsePull?

It turns out I needed to do a 'pull' instead of a 'fetch' so I am not stuck on this problem, but I thought I would let you know about it.

Push allows -u flag

Would it be possible to add an option, allowing us to set the -u flag of the push command? I do

  var Git = require('simple-git')(localPath);
  Git.init()
        .add('./*')
        .commit("first commit!")
        .addRemote('origin', 'some-repo-url')
        .push('origin', 'master')
        .then(fn);

and then i get the old and famous

 There is no tracking information for the current branch.
 Please specify which branch you want to merge with.
 See git-pull(1) for details

    git pull <remote> <branch>

 If you wish to set tracking information for this branch you can do so with:

   git branch --set-upstream-to=origin/<branch> master

Maybe there is another way of doing that and is currently available?

Regards, Dani

log gives quoted output

    gitRepo
        .log(function(err, log) {
            console.log(log);
        });

Gives me hashes with prepended ' and author_email's with appended '. And also the stdoutput is quoted with '

Support git log --merges

Hi Guys,

This is a nice lib, thanks for your work. I ran in to an issue whereby I wanted to look at just merge changes between branches.

I'm going to push a PR for this shortly (it's really simple) - would love some feedback.

Steps to test:

In your config object, set the following:

config.merges: true,
config.branch: qa

Can I provide a user and password ?

Hi,
I am looking for a project like yours.
I would like to clone and pull a private git repository.
Can I provide a user/password with your api ?

repo.rm([array], cb...) cannot handle multiple files

Tested on git version 2.7.4 and 1.8.3.1
Simple-git version 1.38.0

var repo = require('simple-git')('.');
repo.status(function(err, data) {
  // data.deleted is [ 'asdf', 'qwer' ]
});

repo.rm(['asdf', 'qwer'], function(err) {
  // err is: fatal: pathspec 'asdf,qwer' did not match any files
});

Documentation too vague?

I've been picking through the code, to be sure the functions do what I expect them to do, and surprisingly I'm finding that the descriptions are somewhat misleading, particularly when they involve a number of parameters (mergeFromTo, pull, etc), as the git commands being used use the parameters in a different way to what's described in the documentation.

For example, mergeFromTo seems to indicate that it merges from into to (or vice versa?), but the git documentation indicates that it merges both into the current branch. Additionally, pull indicates that it pulls a remote branch, which I'd assumed would pull the remote branch to the tracking branch, but actually, if you're not on the tracking branch, pull acts like a merge. It wouldn't surprise me if someone used this expecting some background checking out or something to merge the two specified branches.

At the very least, it might be worth linking to the relevant git docs for each function for transparency regarding both the function parameters and any option flags.

Document init command

Whilst this command is featured in one of the examples it is not given as a command in the list of possible commands

Authentication

Is it possible to pass in authorization (such as a GitHub token) on methods such as .clone() for private repos, instead of my current method of adding a username and password in to the remote?

Expand implemented commands

Hey @steveukx, looks like a good package here. I have a project that uses a much more janky implementation. I would like to switch over to this package, but I need a few more features. If it is good with you, I will fork and upstream the features.

The commands I need are:

  • git init
  • git submodule [add, init, update]
  • git ls-remote --tags

Do you have contributor guidelines? Does this all sound good?

Diff with another branch

Hi, I'm trying to get a diff from another branch and I'm not sure if this is the correct way:

simpleGit.diff(['HEAD remotes/origin/branch_name --name-only'], function (err, diff)...

This is the error I get:

fatal: ambiguous argument 'HEAD remotes/origin/bugfixing_v1 --name-only': unknown revision or path not in the working tree.
Use '--' to separate paths from revisions, like this:
'git [...] -- [...]'

Works fine when running from the command line.
Is it the right way to do it or maybe a bug?

Thank you.

Checkout local branch

Is there a way I can checkout a local branch? I just want to run git checkout -b develop but it looks like I can't use checkout() or checkoutBranch(). Am I missing something or is this a feature that does not exist?

Would that be something you could possibly add?

Thanks!

Missing chain in getRemotes

/node_modules/simple-git/src/git.js:483
         next(err, !err && function () {
         ^
TypeError: next is not a function

Trying to execute simpleGit.getRemotes(true).then();

Error when nothing to commit

"TypeError: Cannot read property '1' of null"
This error appear when I try to commit but there is nothing to commit

Pushing to remote

git push not currently supported, pushing to default and to named remote and branch should both be possible.

Add custom git log separator

Thank you for this easy to use library! A colleague of mine have been writing commits that included semicolons (;). Now I try to make some statistics from git log, and it fails to parse it correctly. Looking at the code, I found that for log, you use

var command = ["log", "--pretty=format:'%H;%ai;%s%d;%aN;%ae'"];

To overcome the mentioned issue, I replaced semicolons to triple-semicolons and all worked well again. (Also needed to replace in this function: Git.prototype._parseListLog.)

Perhaps you could make it more reliable by selecting a more rare character, or adding an optional parameter for the separator. I would loved to see these changes and further use your great library!

Empty tags in tag list

Using 1.37 on OS X with git 2.8.4 and node 4.4.4.

My repository looks like this:

$ git tag -l
2016_06_08_NEW
2016_06_08_NEW2
2016_06_08_NEW23

repo.tags() results in

[
    "2016_06_08_NEW",
    "2016_06_08_NEW2",
    "2016_06_08_NEW23",
    ""
]

So an array of 3 tags and an additional empty tag.
I fixed it for now by adding
.filter(function(item){return item !== "";})
Any idea if this a bug in my repo, in my code or in git-js? If anyone can reproduce it, I'd be happy to do a PR.
I assume it's because git adds a final \n to wrap the last line and .split("\n") returns the empty line, too.

reset with commitId

can you Give the interface reset a commit id parameter it like: git reset commitId

Git checkout hash

I'm trying to checkout a hash tag referencing a commit. Is this functionality included?

Neither of the following APIs seem to work with hash values.

repo.checkout(hash, function(error, data) { ... });

repo.checkoutLocal(hash, function(error, data) { ... });

How to handle credentials?

Is there any way to have different credentials? can you set what credentials to use for a git call? For example, repository 1 uses my personal credentials while repository 2 uses my work credentials. Is this possible?

Managing remotes

None of the git remote methods are supported - requires support for git remote add and git remote remove

add force flag to checkout

The title says it all :).
I need to force a checkout and dont see a way to do this until now.

Would it be possible to add a force flag (or a forceCheckout-method) to do that?

code execution vulnerability

This module should not be used with any user input as it is very easy to inject code:

~/src/git-js(master ✗) node -e "require('./src/git.js')('.').add('\";echo HELLO WORLD > foo\"')"
~/src/git-js(master ✗) cat foo 
HELLO WORLD
~/src/git-js(master ✗) 

Request: Add option for silent errors

Great module, we're using it with great success.

I'd like to request a small feature addition - the ability to silence the error output to console. We're using this in an environment where we're curating our console output very carefully to deliver a clean experience for our build tools. We're already catching the errors that are thrown should there be an error in the git child process, so we don't need the extraneous console output.

This line here is the culprit: https://github.com/steveukx/git-js/blob/master/src/git.js#L627

Cheers

Branch command does not work with detached current branch

After checking out a branch which is detached, git branch command reports something akin to the following:

* (detached from First-tag) 573b9ed for todd
  develop                   1f5dd41 [behind 5] FirstNewFile.txt edited online with Bitbucket
  feature/My-new-feature    1f5dd41 FirstNewFile.txt edited online with Bitbucket
  master                    1be9589 add to master

Note the format of the first line. This causes a problem in regular expression in branchSummary.js:

BranchSummary.parse = function (commit) {
   var branchSummary = new BranchSummary();

   commit.split('\n')
      .forEach(function (line) {
            var branch = /^(\*?\s+)(\S+)\s+([a-z0-9]+)\s(.*)$/.exec(line);
         if (branch) {
            branchSummary.push(
               branch[1].charAt(0) === '*',
               branch[2],
               branch[3],
               branch[4]
            );
         }
      });

   return branchSummary;
};

My local fix looks like this:

BranchSummary.parse = function (commit) {
   var branchSummary = new BranchSummary();

   commit.split('\n')
      .forEach(function (line) {
         if (line.charAt(2) === '(') var branch = /^(\*?\s+)\(([^)]+)\)\s+([a-z0-9]+)\s(.*)$/.exec(line)
            else var branch = /^(\*?\s+)(\S+)\s+([a-z0-9]+)\s(.*)$/.exec(line);
         if (branch) {
            branchSummary.push(
               branch[1].charAt(0) === '*',
               branch[2],
               branch[3],
               branch[4]
            );
         }
      });

   return branchSummary;
};

There may be better other ways to deal with this but hopefully this helps.
Todd

Change working directory

Is there any possible way, outside of require to change between multiple working directories?

I am working in a project that could have multiple git repositories and I need to switch between these folders and branch/commit/push each of them on specific route calls.

Support for Promises?

Given that there is a .then method, it seems to imply that a Promise is returned, but that's not actually the case. So if you want a Promise, you have to crudely wrap it:

let promise = new Promise(resolve => {
  simpleGit(dir)
    .add('./*')
    .commit('New')
    .push('origin', 'master')
    .then(resolve);
});

So could support be added for Promises? One big benefit is that consumers could then use .catch for errors.

Error: spawn git ENOENT

When I create a bare repository prompted the following errors:
Error: spawn git ENOENT
     at exports._errnoException (util.js: 860: 11)
     at Process.ChildProcess._handle.onexit (internal / child_process.js: 178: 32)
     at onErrorNT (internal / child_process.js: 344: 16)
     at doNTCallback2 (node.js: 450: 9)
     at process._tickCallback (node.js: 364: 17)
     at Function.Module.runMain (module.js: 459: 11)
     at startup (node.js: 136: 18)
     at node.js: 972: 3

code:

var simpleGit = require('simple-git');

var bareDir = 'test.git';

simpleGit(bareDir).init(true, function() {
console.log("init bare done");
});

Make startPoint optinal for checkoutBranch

Hi thanks for working on this library.

What do you guys think about making startPoint optional so that I can do:

  simpleGit(root).checkoutBranch('my_new_branch')

that results in:

git checkout -b my_new_branch

If you guys agree with this change I can send a PR.

submodule init

I'm not sure if I just completely missed something but I can't find a implementation of submodule init

simple-git in windows machine

I'm trying to use npm simple-git in windows machine. But when I run it with node.js it shows me the following error message.

events.js:85
throw er; // Unhandled 'error' event
^
Error: spawn git ENOENT

Node version: v0.12.2
npm version: 2.7.4

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.