History

Update Git documentation (2.30.0)

Simon Legner committed 5 years ago

Commit 3600a9f1 parent 8f17cfa41 files · +4398 −1Browse files

Showing the changes to node_modules/simple-git/readme.md (1 of 41 files). Show all

Unified · Split

node_modules/simple-git/readme.md+380−0
@@ -0,0 +1,380 @@
1# Simple Git
2[![NPM version](https://img.shields.io/npm/v/simple-git.svg)](https://www.npmjs.com/package/simple-git) [![Build Status](https://travis-ci.org/steveukx/git-js.svg?branch=master)](https://travis-ci.org/steveukx/git-js)
3
4A light weight interface for running git commands in any [node.js](https://nodejs.org) application.
5
6# Installation
7
8Easiest through [npm](https://npmjs.org): `npm install simple-git`
9
10# Dependencies
11
12Requires [git](https://git-scm.com/downloads) to be installed and that it can be called using the command `git`.
13
14# Usage
15
16Include into your app using:
17
18```js
19const simpleGit = require('simple-git')(workingDirPath);
20```
21
22> where the `workingDirPath` is optional, defaulting to the current directory.
23
24Use `simpleGit` by chaining any of its functions together. Each function accepts an optional final argument which will
25be called when that step has been completed. When it is called it has two arguments - firstly an error object (or null
26when no error occurred) and secondly the data generated by that call.
27
28| API | What it does |
29|-----|--------------|
30| `.add([fileA, ...], handlerFn)` | adds one or more files to be under source control |
31| `.addAnnotatedTag(tagName, tagMessage, handlerFn)` | adds an annotated tag to the head of the current branch |
32| `.addConfig(key, value[, handlerFn])` | add a local configuration property |
33| `.addRemote(name, repo, handlerFn)` | adds a new named remote to be tracked as `name` at the path `repo` |
34| `.addTag(name, handlerFn)` | adds a lightweight tag to the head of the current branch |
35| `.branch([options, ][handlerFn])` | gets a list of all branches, calls `handlerFn` with two arguments, an error object and [BranchSummary](src/responses/BranchSummary.js) instance. When supplied, the options can be either an array of arguments supported by the [branch](https://git-scm.com/docs/git-branch) command or a standard [options](#how-to-specify-options) object. |
36| `.branchLocal([handlerFn])` | gets a list of local branches, calls `handlerFn` with two arguments, an error object and [BranchSummary](src/responses/BranchSummary.js) instance |
37| `.catFile(options[, handlerFn])` | generate `cat-file` detail, `options` should be an array of strings as supported arguments to the [cat-file](https://git-scm.com/docs/git-cat-file) command |
38| `.checkIgnore([filepath, ...], handlerFn)` | checks if filepath excluded by .gitignore rules |
39| `.checkIsRepo(handlerFn)` | Determines whether the current working directory is part of a git repository, the handler will be called with standard error object and a boolean response. |
40| `.checkout(checkoutWhat, handlerFn)` | checks out the supplied tag, revision or branch. `checkoutWhat` can be one or more strings to be used as parameters appended to the `git checkout` command. |
41| `.checkoutBranch(branchName, startPoint, handlerFn)` | checks out a new branch from the supplied start point |
42| `.checkoutLatestTag(handlerFn)` | convenience method to pull then checkout the latest tag |
43| `.checkoutLocalBranch(branchName, handlerFn)` | checks out a new local branch |
44| `.clean(mode [, options [, handlerFn]])` | clean the working tree. Mode should be "n" - dry run or "f" - force |
45| `.clearQueue()` | immediately clears the queue of pending tasks (note: any command currently in progress will still call its completion callback) |
46| `.clone(repoPath, [localPath, [options]], [handlerFn])` | clone a remote repo at `repoPath` to a local directory at `localPath` (can be omitted to use the default of a directory with the same name as the repo name) with an optional array of additional arguments to include between `git clone` and the trailing `repo local` arguments |
47| `.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) |
48| `.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 |
49| `.customBinary(gitPath)` | sets the command to use to reference git, allows for using a git binary not available on the path environment variable |
50| `.cwd(workingDirectory)` | Sets the current working directory for all commands after this step in the chain |
51| `.deleteLocalBranch(branchName, handlerFn)` | deletes a local branch |
52| `.diff(options, handlerFn)` | get the diff of the current repo compared to the last commit with a set of options supplied as a string |
53| `.diff(handlerFn)` | get the diff for all file in the current repo compared to the last commit |
54| `.diffSummary(handlerFn)` | gets a summary of the diff for files in the repo, uses the `git diff --stat` format to calculate changes. Handler is called with a nullable error object and an instance of the [DiffSummary](src/responses/DiffSummary.js) |
55| `.diffSummary(options, handlerFn)` | includes options in the call to `diff --stat options` and returns a [DiffSummary](src/responses/DiffSummary.js) |
56| `.env(name, value)` | Set environment variables to be passed to the spawned child processes, [see usage in detail below](#environment-variables). |
57| `.exec(handlerFn)` | calls a simple function in the current step |
58| `.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](#how-to-specify-options) either an array of string commands as supported by the [git fetch](https://git-scm.com/docs/git-fetch). On success, the returned data will be an instance of the [FetchSummary](src/responses/FetchSummary.js) |
59| `.fetch(remote, branch, handlerFn)` | update the local working copy database with changes from a remote repo |
60| `.fetch(handlerFn)` | update the local working copy database with changes from the default remote repo and branch |
61| `.getRemotes([verbose], handlerFn)` | gets a list of the named remotes, when the verbose option is supplied as true, includes the URLs and purpose of each ref |
62| `.init(bare, handlerFn)` | initialize a repository, optional `bare` parameter makes intialized repository bare |
63| `.listRemote([args], handlerFn)` | 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 `args` array of strings eg: `git.listRemote(['--heads', '--tags'], console.log.bind(console))` |
64| `.log([options], handlerFn)` | list commits between `options.from` and `options.to` tags or branch (if not specified will show all history). Additionally you can provide `options.file`, which is the path to a file in your repository. Then only this file will be considered. `options.symmetric` allows you to specify whether you want to use [symmetric revision range](https://git-scm.com/docs/gitrevisions#_dotted_range_notations) (To be compatible, by default, its value is true). For any other set of options, supply `options` as an array of strings to be appended to the `git log` command. To use a custom splitter in the log format, set `options.splitter` to be the string the log should be split on. Set `options.multiLine` to true to include a multi-line body in the output format. Options can also be supplied as a standard [options](#how-to-specify-options) object for adding custom properties supported by the [git log](https://git-scm.com/docs/git-log) command. |
65| `.mergeFromTo(from, to, [[options,] handlerFn])` | merge from one branch to another, when supplied the options should be an array of additional parameters to pass into the [git merge](https://git-scm.com/docs/git-merge) command |
66| `.merge(options, handlerFn)` | runs a merge, `options` can be either an array of arguments supported by the [git merge](https://git-scm.com/docs/git-merge) command or an [options](#how-to-specify-options) object. Conflicts during the merge result in an error response, the response type whether it was an error or success will be a [MergeSummary](src/responses/MergeSummary.js) instance. When successful, the MergeSummary has all detail from a the [PullSummary](src/responses/PullSummary.js) |
67| `.mirror(repoPath, localPath, handlerFn])` | clone and mirror the repo to local |
68| `.mv(from, to, handlerFn])` | rename or move a single file at `from` to `to`. On success the `handlerFn` will be called with a [MoveSummary](src/responses/MoveSummary.js) |
69| `.mv(from, to, handlerFn])` | move all files in the `from` array to the `to` directory. On success the `handlerFn` will be called with a [MoveSummary](src/responses/MoveSummary.js) |
70| `.outputHandler(handlerFn)` | attaches a handler that will be called with the name of the command being run and the `stdout` and `stderr` [readable streams](https://nodejs.org/api/stream.html#stream_class_stream_readable) created by the [child process](https://nodejs.org/api/child_process.html#child_process_class_childprocess) running that command |
71| `.pull(handlerFn)` | Pulls all updates from the default tracked repo |
72| `.pull(remote, branch, handlerFn)` | pull all updates from the specified remote branch (eg 'origin'/'master') |
73| `.pull(remote, branch, options, handlerFn)` | Pulls from named remote with any necessary options |
74| `.push(remote, branch[, options] handlerFn)` | pushes to a named remote/branch, supports additional [options](#how-to-specify-options) from the [git push](https://git-scm.com/docs/git-push) command. |
75| `.pushTags(remote, handlerFn)` | pushes tags to a named remote |
76| `.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 commmand will be treated as an error, otherwise treated as a success. |
77| `.rebase([options,] handlerFn)` | Rebases the repo, `options` should be supplied as an array of string parameters supported by the [git rebase](https://git-scm.com/docs/git-rebase) command, or an object of options (see details below for option formats). |
78| `.removeRemote(name, handlerFn)` | removes the named remote |
79| `.reset([resetMode,] handlerFn)` | resets the repository, the optional first argument can either be an array of options supported by the `git reset` command or one of the string constants `mixed`, `hard`, or `soft`, if omitted the reset will be a soft reset to head, handlerFn: (err) |
80| `.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](#how-to-specify-options) argument contain any options accepted by [git-revert](https://git-scm.com/docs/git-revert). |
81| `.revparse([options], handlerFn)` | wraps git rev-parse. Primarily used to convert friendly commit references (ie branch names) to SHA1 hashes. Options should be an array of string options compatible with the [git rev-parse](https://git-scm.com/docs/git-rev-parse) |
82| `.rm([fileA, ...], handlerFn)` | removes any number of files from source control |
83| `.rmKeepLocal([fileA, ...], handlerFn)` | removes files from source control but leaves them on disk |
84| `.silent(isSilent)` | sets whether the console should be used for logging errors (defaults to `true` when the `NODE_ENV` contains the string `prod`) |
85| `.stash([options, ][ handlerFn])` | Stash the working directory, optional first argument can be an array of string arguments or [options](#how-to-specify-options) object to pass to the [git stash](https://git-scm.com/docs/git-stash) command. |
86| `.stashList([options, ][handlerFn])` | Retrieves the stash list, optional first argument can be an object specifying `options.splitter` to override the default value of `;;;;`, alternatively options can be a set of arguments as supported by the `git stash list` command. |
87| `.subModule(args [, handlerFn])` | Run a `git submodule` command with on or more arguments passed in as an `args` array |
88| `.submoduleAdd(repo, path[, handlerFn])` | adds a new sub module |
89| `.submoduleInit([args, ][handlerFn])` | inits sub modules, args should be an array of string arguments to pass to the `git submodule init` command |
90| `.submoduleUpdate([args, ][handlerFn])` | updates sub modules, args should be an array of string arguments to pass to the `git submodule update` command |
91| `.tag(args[], handlerFn)` | Runs any supported [git tag](https://git-scm.com/docs/git-tag) commands with arguments passed as an array of strings . |
92| `.tags([options, ] handlerFn)` | list all tags, use the optional [options](#how-to-specify-options) object to set any options allows by the [git tag](https://git-scm.com/docs/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. |
93| `.show([options], handlerFn)` | Show various types of objects, for example the file content at a certain commit. `options` is the single value string or array of string commands you want to run |
94| `.status(handlerFn)` | gets the status of the current repo |
95
96# How to Specify Options
97
98For `.pull` or `.commit` options are included as an object, the keys of which will all be merged as trailing
99arguments in the command string. When the value of the property in the options object is a `string`, that name value
100pair will be included in the command string as `name=value`. For example:
101
102```js
103// results in 'git pull origin master --no-rebase'
104git().pull('origin', 'master', {'--no-rebase': null})
105
106// results in 'git pull origin master --rebase=true'
107git().pull('origin', 'master', {'--rebase': 'true'})
108```
109
110# Release History
111
112Bumped to a new major revision in the 1.x branch, now uses `ChildProcess.spawn` in place of `ChildProcess.exec` to
113add escaping to the arguments passed to each of the tasks.
114
115# Deprecated APIs
116
117Use of these APIs is deprecated and should be avoided as support for them will be removed in future release:
118
119`.then(func)` In versions 1.72 and below, it was possible to add a regular function call to the queue of tasks to be
120 run. As this name clashes with the use of Promises, in version 1.73.0 it is renamed to `.exec(fn)` and a warning will
121 be logged to `stdout` if `.then` is used. From version 2.0 the library will support promises without the need to wrap
122 or use the alternative require `require('simple-git/promise')`.
123
124`.log([from, to], handlerFn)` list commits between `from` and `to` tags or branch, switch to supplying the revisions
125as an options object instead.
126
127# Complex Requests
128
129When no suitable wrapper exists in the interface for creating a request, it is possible to run a command directly
130using `git.raw([...], handler)`. The array of commands are passed directly to the `git` binary:
131
132```js
133const git = require('simple-git');
134const path = '/path/to/repo';
135
136git(path).raw(
137[
138 'config',
139 '--global',
140 'advice.pushNonFastForward',
141 'false'
142], (err, result) => {
143
144 // err is null unless this command failed
145 // result is the raw output of this command
146
147});
148```
149
150# Authentication
151
152The easiest way to supply a username / password to the remote host is to include it in the URL, for example:
153
154```js
155const USER = 'something';
156const PASS = 'somewhere';
157const REPO = 'github.com/username/private-repo';
158
159const git = require('simple-git/promise');
160const remote = `https://${USER}:${PASS}@${REPO}`;
161
162git().silent(true)
163 .clone(remote)
164 .then(() => console.log('finished'))
165 .catch((err) => console.error('failed: ', err));
166
167```
168
169Be sure to enable silent mode to prevent fatal errors from being logged to stdout.
170
171# Environment Variables
172
173Pass one or more environment variables to the child processes spawned by `simple-git` with the `.env` method which
174supports passing either an object of name=value pairs or setting a single variable at a time:
175
176```js
177const GIT_SSH_COMMAND = "ssh -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no";
178
179const git = require('simple-git');
180
181git()
182 .env('GIT_SSH_COMMAND', GIT_SSH_COMMAND)
183 .status((err, status) => { /* */ })
184
185
186const gitP = require('simple-git/promise');
187
188gitP().env({ ...process.env, GIT_SSH_COMMAND })
189 .status()
190 .then(status => { })
191 .catch(err => {});
192
193```
194
195Note - when passing environment variables into the child process, these will replace the standard `process.env`
196variables, the example above creates a new object based on `process.env` but with the `GIT_SSH_COMMAND` property
197added.
198
199# TypeScript
200
201To import with TypeScript:
202
203```typescript
204import gitP, { SimpleGit, StatusResult } from 'simple-git/promise';
205
206const git: SimpleGit = gitP();
207const status: StatusResult = await git.status();
208```
209
210# Promise and async compatible
211
212To work with promises (either directly or as part of async/await), load the promise wrappers library:
213
214```js
215const simpleGit = require('simple-git/promise');
216const git = simpleGit();
217
218const status = await git.status();
219```
220
221Exceptions (generally recognised by the git process exiting with a non-zero status, or in some cases
222like `merge` the git process exits with a successful zero code but there are conflicts in the merge)
223should be handled by catching:
224
225```js
226try {
227 const mergeSummary = await git.merge();
228 console.log(`Merged ${ mergeSummary.merges.length } files`);
229}
230catch (err) {
231 // err.message - the string summary of the error
232 // err.stack - some stack trace detail
233 // err.git - where a parser was able to run, this is the parsed content
234
235 console.error(`Merge resulted in ${ err.git.conflicts.length } conflicts`);
236}
237```
238
239# Response Object Revisions
240
241| Class | Version | Change |
242| ListLogLine | v1.110.0 | The default format expression used in `.log` splits ref data out of the `message` into a property of its own: `{ message: 'Some commit message (some-branch-name)' }` becomes `{ message: 'Some commit message', refs: 'some-branch-name' }` |
243| ListLogLine | v1.110.0 | The commit body content is now included in the default format expression and can be used to identify the content of merge conflicts eg: `{ body: '# Conflicts:\n# some-file.txt' }` |
244
245# Troubleshooting
246
247### Every command returns ENOENT error message
248
249There are a few potential reasons:
250
251- `git` isn't available as a binary for the user running the main `node` process, custom paths to the binary can be used
252 with the `.customBinary(...)` api option.
253- the working directory passed in to the main `simple-git` function isn't accessible, check it is read/write accessible
254 by the user running the `node` process.
255
256### Log response properties are out of order
257
258The properties of `git.log` are fetched using a `;` as a delimiter. If your commit messages use the `;` character,
259supply a custom `splitter` in the options, for example: `git.log({ splitter: '|||' })`
260
261# Examples
262
263### async await with simple-git/promise:
264
265```js
266async function status (workingDir) {
267 const git = require('simple-git/promise');
268
269 let statusSummary = null;
270 try {
271 statusSummary = await git(workingDir).status();
272 }
273 catch (e) {
274 // handle the error
275 }
276
277 return statusSummary;
278}
279
280// using the async function
281status(__dirname + '/some-repo').then(status => console.log(status));
282```
283
284### Initialise a git repo if necessary
285```js
286const gitP = require('simple-git/promise');
287const git = gitP(__dirname);
288
289git.checkIsRepo()
290 .then(isRepo => !isRepo && initialiseRepo(git))
291 .then(() => git.fetch());
292
293function initialiseRepo (git) {
294 return git.init()
295 .then(() => git.addRemote('origin', 'https://some.git.repo'))
296}
297```
298
299### Update repo and get a list of tags
300```js
301require('simple-git')(__dirname + '/some-repo')
302 .pull()
303 .tags((err, tags) => console.log("Latest available tag: %s", tags.latest));
304
305// update repo and when there are changes, restart the app
306require('simple-git')()
307 .pull((err, update) => {
308 if(update && update.summary.changes) {
309 require('child_process').exec('npm restart');
310 }
311 });
312```
313
314### Starting a new repo
315```js
316require('simple-git')()
317 .init()
318 .add('./*')
319 .commit("first commit!")
320 .addRemote('origin', 'https://github.com/user/repo.git')
321 .push('origin', 'master');
322```
323
324### push with `-u`
325```js
326require('simple-git')()
327 .add('./*')
328 .commit("first commit!")
329 .addRemote('origin', 'some-repo-url')
330 .push(['-u', 'origin', 'master'], () => console.log('done'));
331```
332
333### Piping to the console for long running tasks
334```js
335require('simple-git')()
336 .outputHandler((command, stdout, stderr) => {
337 stdout.pipe(process.stdout);
338 stderr.pipe(process.stderr);
339 })
340 .checkout('https://github.com/user/repo.git');
341```
342
343### Update repo and print messages when there are changes, restart the app
344```js
345require('simple-git')()
346 .exec(() => console.log('Starting pull...'))
347 .pull((err, update) => {
348 if(update && update.summary.changes) {
349 require('child_process').exec('npm restart');
350 }
351 })
352 .exec(() => console.log('pull done.'));
353```
354
355### Get a full commits list, and then only between 0.11.0 and 0.12.0 tags
356```js
357require('simple-git')()
358 .log((err, log) => console.log(log))
359 .log('0.11.0', '0.12.0', (err, log) => console.log(log));
360```
361
362### Set the local configuration for author, then author for an individual commit
363```js
364require('simple-git')()
365 .addConfig('user.name', 'Some One')
366 .addConfig('user.email', 'some@one.com')
367 .commit('committed as "Some One"', 'file-one')
368 .commit('committed as "Another Person"', 'file-two', { '--author': '"Another Person <another@person.com>"' });
369```
370
371### Get remote repositories
372```js
373require('simple-git')()
374 .listRemote(['--get-url'], (err, data) => {
375 if (!err) {
376 console.log('Remote url for repository at ' + __dirname + ':');
377 console.log(data);
378 }
379 });
380```