github.com/jfrog/frogbot@v1.1.1-0.20231221090046-821a26f50338/action/node_modules/simple-git/readme.md (about) 1 # Simple Git 2 3 [](https://www.npmjs.com/package/simple-git) 4 5 A lightweight interface for running `git` commands in any [node.js](https://nodejs.org) application. 6 7 # Version 3 - Out Now 8 9 From v3 of `simple-git` you can now import as an ES module, Common JS module or as TypeScript with bundled type 10 definitions. Upgrading from v2 will be seamless for any application not relying on APIs that were marked as deprecated 11 in v2 (deprecation notices were logged to `stdout` as `console.warn` in v2). 12 13 # Installation 14 15 Use your favourite package manager: 16 17 - [npm](https://npmjs.org): `npm install simple-git` 18 - [yarn](https://yarnpkg.com/): `yarn add simple-git` 19 20 # System Dependencies 21 22 Requires [git](https://git-scm.com/downloads) to be installed and that it can be called using the command `git`. 23 24 # Usage 25 26 Include into your JavaScript app using common js: 27 28 ```javascript 29 // require the library, main export is a function 30 const simpleGit = require('simple-git'); 31 simpleGit().clean(simpleGit.CleanOptions.FORCE); 32 33 // or use named properties 34 const { simpleGit, CleanOptions } = require('simple-git'); 35 simpleGit().clean(CleanOptions.FORCE); 36 ``` 37 38 Include into your JavaScript app as an ES Module: 39 40 ```javascript 41 import { simpleGit, CleanOptions } from 'simple-git'; 42 43 simpleGit().clean(CleanOptions.FORCE); 44 ``` 45 46 Include in a TypeScript app using the bundled type definitions: 47 48 ```typescript 49 import { simpleGit, SimpleGit, CleanOptions } from 'simple-git'; 50 51 const git: SimpleGit = simpleGit().clean(CleanOptions.FORCE); 52 ``` 53 54 ## Configuration 55 56 Configure each `simple-git` instance with a properties object passed to the main `simpleGit` function: 57 58 ```typescript 59 import { simpleGit, SimpleGit, SimpleGitOptions } from 'simple-git'; 60 61 const options: Partial<SimpleGitOptions> = { 62 baseDir: process.cwd(), 63 binary: 'git', 64 maxConcurrentProcesses: 6, 65 trimmed: false, 66 }; 67 68 // when setting all options in a single object 69 const git: SimpleGit = simpleGit(options); 70 71 // or split out the baseDir, supported for backward compatibility 72 const git: SimpleGit = simpleGit('/some/path', { binary: 'git' }); 73 ``` 74 75 The first argument can be either a string (representing the working directory for `git` commands to run in), 76 `SimpleGitOptions` object or `undefined`, the second parameter is an optional `SimpleGitOptions` object. 77 78 All configuration properties are optional, the default values are shown in the example above. 79 80 ## Per-command Configuration 81 82 To prefix the commands run by `simple-git` with custom configuration not saved in the git config (ie: using the 83 `-c` command) supply a `config` option to the instance builder: 84 85 ```typescript 86 // configure the instance with a custom configuration property 87 const git: SimpleGit = simpleGit('/some/path', { config: ['http.proxy=someproxy'] }); 88 89 // any command executed will be prefixed with this config 90 // runs: git -c http.proxy=someproxy pull 91 await git.pull(); 92 ``` 93 94 ## Configuring Plugins 95 96 - [AbortController](https://github.com/steveukx/git-js/blob/main/docs/PLUGIN-ABORT-CONTROLLER.md) 97 Terminate pending and future tasks in a `simple-git` instance (requires node >= 16). 98 99 - [Completion Detection](https://github.com/steveukx/git-js/blob/main/docs/PLUGIN-COMPLETION-DETECTION.md) 100 Customise how `simple-git` detects the end of a `git` process. 101 102 - [Error Detection](https://github.com/steveukx/git-js/blob/main/docs/PLUGIN-ERRORS.md) 103 Customise the detection of errors from the underlying `git` process. 104 105 - [Progress Events](https://github.com/steveukx/git-js/blob/main/docs/PLUGIN-PROGRESS-EVENTS.md) 106 Receive progress events as `git` works through long-running processes. 107 108 - [Spawned Process Ownership](https://github.com/steveukx/git-js/blob/main/docs/PLUGIN-SPAWN-OPTIONS.md) 109 Configure the system `uid` / `gid` to use for spawned `git` processes. 110 111 - [Timeout](https://github.com/steveukx/git-js/blob/main/docs/PLUGIN-TIMEOUT.md) 112 Automatically kill the wrapped `git` process after a rolling timeout. 113 114 - [Unsafe](https://github.com/steveukx/git-js/blob/main/docs/PLUGIN-UNSAFE-ACTIONS.md) 115 Selectively opt out of `simple-git` safety precautions - for advanced users and use cases. 116 117 ## Using Task Promises 118 119 Each task in the API returns the `simpleGit` instance for chaining together multiple tasks, and each 120 step in the chain is also a `Promise` that can be `await` ed in an `async` function or returned in a 121 `Promise` chain. 122 123 ```javascript 124 const git = simpleGit(); 125 126 // chain together tasks to await final result 127 await git.init().addRemote('origin', '...remote.git'); 128 129 // or await each step individually 130 await git.init(); 131 await git.addRemote('origin', '...remote.git'); 132 ``` 133 134 ### Catching errors in async code 135 136 To catch errors in async code, either wrap the whole chain in a try/catch: 137 138 ```javascript 139 const git = simpleGit(); 140 try { 141 await git.init(); 142 await git.addRemote(name, repoUrl); 143 } catch (e) { 144 /* handle all errors here */ 145 } 146 ``` 147 148 or catch individual steps to permit the main chain to carry on executing rather than 149 jumping to the final `catch` on the first error: 150 151 ```javascript 152 const git = simpleGit(); 153 try { 154 await git.init().catch(ignoreError); 155 await git.addRemote(name, repoUrl); 156 } catch (e) { 157 /* handle all errors here */ 158 } 159 160 function ignoreError() {} 161 ``` 162 163 ## Using Task Callbacks 164 165 In addition to returning a promise, each method can also be called with a trailing callback argument 166 to handle the result of the task. 167 168 ```javascript 169 const git = simpleGit(); 170 git.init(onInit).addRemote('origin', 'git@github.com:steveukx/git-js.git', onRemoteAdd); 171 172 function onInit(err, initResult) {} 173 function onRemoteAdd(err, addRemoteResult) {} 174 ``` 175 176 If any of the steps in the chain result in an error, all pending steps will be cancelled, see the 177 [parallel tasks](<(#concurrent--parallel-requests)>) section for more information on how to run tasks in parallel rather than in series . 178 179 ## Task Responses 180 181 Whether using a trailing callback or a Promise, tasks either return the raw `string` or `Buffer` response from the 182 `git` binary, or where possible a parsed interpretation of the response. 183 184 For type details of the response for each of the tasks, please see the [TypeScript definitions](https://github.com/steveukx/git-js/blob/main/simple-git/typings/simple-git.d.ts). 185 186 # API 187 188 | API | What it does | 189 | ---------------------------------------------------- |------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| 190 | `.add([fileA, ...], handlerFn)` | adds one or more files to be under source control | 191 | `.addAnnotatedTag(tagName, tagMessage, handlerFn)` | adds an annotated tag to the head of the current branch | 192 | `.addTag(name, handlerFn)` | adds a lightweight tag to the head of the current branch | 193 | `.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 | 194 | `.checkIgnore([filepath, ...], handlerFn)` | checks if filepath excluded by .gitignore rules | 195 | `.clearQueue()` | immediately clears the queue of pending tasks (note: any command currently in progress will still call its completion callback) | 196 | `.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) | 197 | `.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 | 198 | `.customBinary(gitPath)` | sets the command to use to reference git, allows for using a git binary not available on the path environment variable | 199 | `.env(name, value)` | Set environment variables to be passed to the spawned child processes, [see usage in detail below](#environment-variables). | 200 | `.exec(handlerFn)` | calls a simple function in the current step | 201 | `.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). | 202 | `.fetch(remote, branch, handlerFn)` | update the local working copy database with changes from a remote repo | 203 | `.fetch(handlerFn)` | update the local working copy database with changes from the default remote repo and branch | 204 | `.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, see [examples](https://github.com/steveukx/git-js/blob/main/examples/git-output-handler.md) | 205 | `.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. | 206 | `.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). | 207 | `.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). | 208 | `.rm([fileA, ...], handlerFn)` | removes any number of files from source control | 209 | `.rmKeepLocal([fileA, ...], handlerFn)` | removes files from source control but leaves them on disk | 210 | `.tag(args[], handlerFn)` | Runs any supported [git tag](https://git-scm.com/docs/git-tag) commands with arguments passed as an array of strings . | 211 | `.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. | 212 213 ## git apply 214 215 - `.applyPatch(patch, [options])` applies a single string patch (as generated by `git diff`), optionally configured with the supplied [options](#how-to-specify-options) to set any arguments supported by the [apply](https://git-scm.com/docs/git-apply) command. Returns the unmodified string response from `stdout` of the `git` binary. 216 - `.applyPatch(patches, [options])` applies an array of string patches (as generated by `git diff`), optionally configured with the supplied [options](#how-to-specify-options) to set any arguments supported by the [apply](https://git-scm.com/docs/git-apply) command. Returns the unmodified string response from `stdout` of the `git` binary. 217 218 ## git branch 219 220 - `.branch([options])` uses the supplied [options](#how-to-specify-options) to run any arguments supported by the [branch](https://git-scm.com/docs/git-branch) command. Either returns a [BranchSummaryResult](https://github.com/steveukx/git-js/blob/main/simple-git/src/lib/responses/BranchSummary.ts) instance when listing branches, or a [BranchSingleDeleteResult](https://github.com/steveukx/git-js/blob/main/simple-git/typings/response.d.ts) type object when the options included `-d`, `-D` or `--delete` which cause it to delete a named branch rather than list existing branches. 221 - `.branchLocal()` gets a list of local branches as a [BranchSummaryResult](https://github.com/steveukx/git-js/blob/main/simple-git/src/lib/responses/BranchSummary.ts) instance 222 - `.deleteLocalBranch(branchName)` deletes a local branch - treats a failed attempt as an error 223 - `.deleteLocalBranch(branchName, forceDelete)` deletes a local branch, optionally explicitly setting forceDelete to true - treats a failed attempt as an error 224 - `.deleteLocalBranches(branchNames)` deletes multiple local branches 225 - `.deleteLocalBranches(branchNames, forceDelete)` deletes multiple local branches, optionally explicitly setting forceDelete to true 226 227 ## git clean 228 229 - `.clean(mode)` clean the working tree. Mode should be "n" - dry run or "f" - force 230 - `.clean(cleanSwitches [,options])` set `cleanSwitches` to a string containing any number of the supported single character options, optionally with a standard [options](#how-to-specify-options) object 231 232 ## git checkout 233 234 - `.checkout(checkoutWhat , [options])` - checks out the supplied tag, revision or branch when supplied as a string, 235 additional arguments supported by [git checkout](https://git-scm.com/docs/git-checkout) can be supplied as an 236 [options](#how-to-specify-options) object/array. 237 238 - `.checkout(options)` - check out a tag or revision using the supplied [options](#how-to-specify-options) 239 240 - `.checkoutBranch(branchName, startPoint)` - checks out a new branch from the supplied start point. 241 242 - `.checkoutLocalBranch(branchName)` - checks out a new local branch 243 244 ## git clone 245 246 - `.clone(repoPath, [localPath, [options]])` clone a remote repo at `repoPath` to a local directory at `localPath`, optionally with a standard [options](#how-to-specify-options) object of additional arguments to include between `git clone` and the trailing `repo local` arguments 247 - `.clone(repoPath, [options])` clone a remote repo at `repoPath` to a directory in the current working directory with the same name as the repo 248 249 - `mirror(repoPath, [localPath, [options]])` behaves the same as the `.clone` interface with the [`--mirror` flag](https://git-scm.com/docs/git-clone#Documentation/git-clone.txt---mirror) enabled. 250 251 ## git config 252 253 - `.addConfig(key, value, append = false, scope = 'local')` add a local configuration property, when `append` is set to 254 `true` the configuration setting is appended to rather than overwritten in the local config. Use the `scope` argument 255 to pick where to save the new configuration setting (use the exported `GitConfigScope` enum, or equivalent string 256 values - `worktree | local | global | system`). 257 - `.getConfig(key)` get the value(s) for a named key as a [ConfigGetResult](https://github.com/steveukx/git-js/blob/main/simple-git/typings/response.d.ts) 258 - `.getConfig(key, scope)` get the value(s) for a named key as a [ConfigGetResult](https://github.com/steveukx/git-js/blob/main/simple-git/typings/response.d.ts) but limit the 259 scope of the properties searched to a single specified scope (use the exported `GitConfigScope` enum, or equivalent 260 string values - `worktree | local | global | system`) 261 262 - `.listConfig()` reads the current configuration and returns a [ConfigListSummary](https://github.com/steveukx/git-js/blob/main/simple-git/src/lib/responses/ConfigList.ts) 263 - `.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) 264 265 ## git diff 266 267 - `.diff([ options ])` get the diff of the current repo compared to the last commit, optionally including 268 any number of other arguments supported by [git diff](https://git-scm.com/docs/git-diff) supplied as an 269 [options](#how-to-specify-options) object/array. Returns the raw `diff` output as a string. 270 271 - `.diffSummary([ options ])` creates a [DiffResult](https://github.com/steveukx/git-js/blob/main/simple-git/src/lib/responses/DiffSummary.ts) 272 to summarise the diff for files in the repo. Uses the `--stat` format by default which can be overridden 273 by passing in any of the log format commands (eg: `--numstat` or `--name-stat`) as part of the optional 274 [options](#how-to-specify-options) object/array. 275 276 ## git grep [examples](https://github.com/steveukx/git-js/blob/main/examples/git-grep.md) 277 278 - `.grep(searchTerm)` searches for a single search term across all files in the working tree, optionally passing a standard [options](#how-to-specify-options) object of additional arguments 279 - `.grep(grepQueryBuilder(...))` use the `grepQueryBuilder` to create a complex query to search for, optionally passing a standard [options](#how-to-specify-options) object of additional arguments 280 281 ## git hash-object 282 283 - `.hashObject(filePath, write = false)` computes the object ID value for the contents of the named file (which can be 284 outside of the work tree), optionally writing the resulting value to the object database. 285 286 ## git init 287 288 - `.init(bare , [options])` initialize a repository using the boolean `bare` parameter to intialise a bare repository. 289 Any number of other arguments supported by [git init](https://git-scm.com/docs/git-init) can be supplied as an 290 [options](#how-to-specify-options) object/array. 291 292 - `.init([options])` initialize a repository using any arguments supported by 293 [git init](https://git-scm.com/docs/git-init) supplied as an [options](#how-to-specify-options) object/array. 294 295 ## git log 296 297 - `.log([options])` list commits between `options.from` and `options.to` tags or branch (if not specified will 298 show all history). Use the `options` object to set any [options](#how-to-specify-options) supported by the 299 [git log](https://git-scm.com/docs/git-log) command or any of the following: 300 301 - `options.file` - the path to a file in your repository to only consider this path. 302 - `options.format` - custom log format object, keys are the property names used on the returned object, values are the format string from [pretty formats](https://git-scm.com/docs/pretty-formats#Documentation/pretty-formats.txt) 303 - `options.from` - sets the oldest commit in the range to return, use along with `options.to` to set a bounded range 304 - `options.mailMap` - defaults to true, enables the use of [mail map](https://git-scm.com/docs/gitmailmap) in returned values for email and name from the default format 305 - `options.maxCount` - equivalent to setting the `--max-count` option 306 - `options.multiLine` - enables multiline body values in the default format (disabled by default) 307 - `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 `ò`) 308 - `options.strictDate` - switches the authored date value from an ISO 8601-like format to be strict ISO 8601 format 309 - `options.symmetric` - defaults to true, enables [symmetric revision range](https://git-scm.com/docs/gitrevisions#_dotted_range_notations) rather than a two-dot range 310 - `options.to` - sets the newset commit in the range to return, use along with `options.from` to set a bounded range 311 312 ## git merge 313 314 - `.merge(options)` runs a merge using any configuration [options](#how-to-specify-options) supported 315 by [git merge](https://git-scm.com/docs/git-merge). 316 Conflicts during the merge result in an error response, the response is an instance of 317 [MergeSummary](https://github.com/steveukx/git-js/blob/main/simple-git/src/lib/responses/MergeSummary.ts) whether it was an error or success. 318 When successful, the MergeSummary has all detail from a the [PullSummary](https://github.com/steveukx/git-js/blob/main/simple-git/src/lib/responses/PullSummary.ts) 319 along with summary detail for the merge. 320 When the merge failed, the MergeSummary contains summary detail for why the merge failed and which files 321 prevented the merge. 322 323 - `.mergeFromTo(remote, branch , [options])` - merge from the specified branch into the currently checked out branch, 324 similar to `.merge` but with the `remote` and `branch` supplied as strings separately to any additional 325 [options](#how-to-specify-options). 326 327 ## git mv 328 329 - `.mv(from, to)` rename or move a single file at `from` to `to` 330 331 - `.mv(from, to)` move all files in the `from` array to the `to` directory 332 333 ## git pull 334 335 - `.pull([options])` pulls all updates from the default tracked remote, any arguments supported by 336 [git pull](https://git-scm.com/docs/git-pull) can be supplied as an [options](#how-to-specify-options) object/array. 337 338 - `.pull(remote, branch, [options])` pulls all updates from the specified remote branch (eg 'origin'/'master') along 339 with any custom [options](#how-to-specify-options) object/array 340 341 ## git push 342 343 - `.push([options])` pushes to a named remote/branch using any supported [options](#how-to-specify-options) 344 from the [git push](https://git-scm.com/docs/git-push) command. Note that `simple-git` enforces the use of 345 `--verbose --porcelain` options in order to parse the response. You don't need to supply these options. 346 347 - `.push(remote, branch, [options])` pushes to a named remote/branch, supports additional 348 [options](#how-to-specify-options) from the [git push](https://git-scm.com/docs/git-push) command. 349 350 - `.pushTags(remote, [options])` pushes local tags to a named remote (equivalent to using `.push([remote, '--tags'])`) 351 352 ## git remote 353 354 - `.addRemote(name, repo, [options])` adds a new named remote to be tracked as `name` at the path `repo`, optionally with any supported [options](#how-to-specify-options) for the [git add](https://git-scm.com/docs/git-remote#Documentation/git-remote.txt-emaddem) call. 355 - `.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 356 - `.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](#how-to-specify-options) eg: `git.listRemote(['--heads', '--tags'], console.log)` 357 - `.remote([options])` runs a `git remote` command with any number of [options](#how-to-specify-options) 358 - `.removeRemote(name)` removes the named remote 359 360 ## git reset 361 362 - `.reset(resetMode, [resetOptions])` resets the repository, sets the reset mode to one of the supported types (use a constant from 363 the exported `ResetMode` enum, or a string equivalent: `mixed`, `soft`, `hard`, `merge`, `keep`). Any number of other arguments 364 supported by [git reset](https://git-scm.com/docs/git-reset) can be supplied as an [options](#how-to-specify-options) object/array. 365 366 - `.reset(resetOptions)` resets the repository with the supplied [options](#how-to-specify-options) 367 368 - `.reset()` resets the repository in `soft` mode. 369 370 ## git rev-parse / repo properties 371 372 - `.revparse([options])` sends the supplied [options](#how-to-specify-options) to [git rev-parse](https://git-scm.com/docs/git-rev-parse) and returns the string response from `git`. 373 374 - `.checkIsRepo()` gets whether the current working directory is a descendent of a git repository. 375 - `.checkIsRepo('bare')` gets whether the current working directory is within a bare git repo (see either [git clone --bare](https://git-scm.com/docs/git-clone#Documentation/git-clone.txt---bare) or [git init --bare](https://git-scm.com/docs/git-init#Documentation/git-init.txt---bare)). 376 - `.checkIsRepo('root')` gets whether the current working directory is the root directory for a repo (sub-directories will return false). 377 378 ## git show 379 380 - `.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](#how-to-specify-options) supported by the [git show](https://git-scm.com/docs/git-show) command. 381 - `.showBuffer(options)` same as the `.show` api, but returns the Buffer content directly to allow for showing binary file content. 382 383 ## git status 384 385 - `.status([options])` gets the status of the current repo, resulting in a [StatusResult](https://github.com/steveukx/git-js/blob/main/simple-git/typings/response.d.ts). Additional arguments 386 supported by [git status](https://git-scm.com/docs/git-status) can be supplied as an [options](#how-to-specify-options) object/array. 387 388 ## git submodule 389 390 - `.subModule(options)` Run a `git submodule` command with on or more arguments passed in as an [options](#how-to-specify-options) array or object 391 - `.submoduleAdd(repo, path)` Adds a new sub module 392 - `.submoduleInit([options]` Initialises sub modules, the optional [options](#how-to-specify-options) argument can be used to pass extra options to the `git submodule init` command. 393 - `.submoduleUpdate(subModuleName, [options])` Updates sub modules, can be called with a sub module name and [options](#how-to-specify-options), just the options or with no arguments 394 395 ## git stash 396 397 - `.stash([ options ])` 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. 398 399 - `.stashList([ options ])` Retrieves the stash list, optional first argument can be an object in the same format as used in [git log](#git-log). 400 401 ## git version [examples](https://github.com/steveukx/git-js/blob/main/examples/git-version.md) 402 403 - `.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. 404 405 ## changing the working directory [examples](https://github.com/steveukx/git-js/blob/main/examples/git-change-working-directory.md) 406 407 - `.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. 408 - `.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`). 409 410 ## How to Specify Options 411 412 Where the task accepts custom options (eg: `pull` or `commit`), these can be supplied as an object, the keys of which 413 will all be merged as trailing arguments in the command string, or as a simple array of strings. 414 415 ### Options as an Object 416 417 When the value of the property in the options object is a `string`, that name value 418 pair will be included in the command string as `name=value`. For example: 419 420 ```javascript 421 // results in 'git pull origin master --no-rebase' 422 git.pull('origin', 'master', { '--no-rebase': null }); 423 424 // results in 'git pull origin master --rebase=true' 425 git.pull('origin', 'master', { '--rebase': 'true' }); 426 ``` 427 428 ### Options as an Array 429 430 Options can also be supplied as an array of strings to be merged into the task's commands 431 in the same way as when an object is used: 432 433 ```javascript 434 // results in 'git pull origin master --no-rebase' 435 git.pull('origin', 'master', ['--no-rebase']); 436 ``` 437 438 # Release History 439 440 Major release 3.x changes the packaging of the library, making it consumable as a CommonJS module, ES module as well as 441 with TypeScript (see [usage](#usage) above). The library is now published as a single file, so please ensure your 442 application hasn't been making use of non-documented APIs by importing from a sub-directory path. 443 444 See also: 445 446 - [release notes v3](https://github.com/steveukx/git-js/blob/main/simple-git/CHANGELOG.md) 447 - [release notes v2](https://github.com/steveukx/git-js/blob/main/docs/RELEASE-NOTES-V2.md) 448 449 # Concurrent / Parallel Requests 450 451 When the methods of `simple-git` are chained together, they create an execution chain that will run in series, useful 452 for when the tasks themselves are order-dependent, eg: 453 454 ```typescript 455 simpleGit().init().addRemote('origin', 'https://some-repo.git').fetch(); 456 ``` 457 458 Each task requires that the one before it has been run successfully before it is called, any errors in a 459 step of the chain should prevent later steps from being attempted. 460 461 When the methods of `simple-git` are called on the root instance (ie: `git = simpleGit()`) rather than chained 462 off another task, it starts a new chain and will not be affected failures in tasks already being run. Useful 463 for when the tasks are independent of each other, eg: 464 465 ```typescript 466 const git = simpleGit(); 467 const results = await Promise.all([ 468 git.raw('rev-parse', '--show-cdup').catch(swallow), 469 git.raw('rev-parse', '--show-prefix').catch(swallow), 470 ]); 471 function swallow(err) { 472 return null; 473 } 474 ``` 475 476 Each `simple-git` instance limits the number of spawned child processes that can be run simultaneously and 477 manages the queue of pending tasks for you. Configure this value by passing an options object to the 478 `simpleGit` function, eg: 479 480 ```typescript 481 const git = simpleGit({ maxConcurrentProcesses: 10 }); 482 ``` 483 484 Treating tasks called on the root instance as the start of separate chains is a change to the behaviour of 485 `simple-git` and was added in version `2.11.0`. 486 487 # Complex Requests 488 489 When no suitable wrapper exists in the interface for creating a request, run the command directly 490 using `git.raw([...], handler)`. The array of commands are passed directly to the `git` binary: 491 492 ```javascript 493 const path = '/path/to/repo'; 494 const commands = ['config', '--global', 'advice.pushNonFastForward', 'false']; 495 496 // using an array of commands and node-style callback 497 simpleGit(path).raw(commands, (err, result) => { 498 // err is null unless this command failed 499 // result is the raw output of this command 500 }); 501 502 // using a var-args of strings and awaiting rather than using the callback 503 const result = await simpleGit(path).raw(...commands); 504 505 // automatically trim trailing white-space in responses 506 const result = await simpleGit(path, { trimmed: true }).raw(...commands); 507 ``` 508 509 # Authentication 510 511 The easiest way to supply a username / password to the remote host is to include it in the URL, for example: 512 513 ```javascript 514 const USER = 'something'; 515 const PASS = 'somewhere'; 516 const REPO = 'github.com/username/private-repo'; 517 518 const remote = `https://${USER}:${PASS}@${REPO}`; 519 520 simpleGit() 521 .clone(remote) 522 .then(() => console.log('finished')) 523 .catch((err) => console.error('failed: ', err)); 524 ``` 525 526 Be sure to not enable debug logging when using this mechanism for authentication 527 to ensure passwords aren't logged to stdout. 528 529 # Environment Variables 530 531 Pass one or more environment variables to the child processes spawned by `simple-git` with the `.env` method which 532 supports passing either an object of name=value pairs or setting a single variable at a time: 533 534 ```javascript 535 const GIT_SSH_COMMAND = 'ssh -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no'; 536 537 simpleGit() 538 .env('GIT_SSH_COMMAND', GIT_SSH_COMMAND) 539 .status((err, status) => { 540 /* */ 541 }); 542 543 simpleGit() 544 .env({ ...process.env, GIT_SSH_COMMAND }) 545 .status() 546 .then((status) => {}) 547 .catch((err) => {}); 548 ``` 549 550 Note - when passing environment variables into the child process, these will replace the standard `process.env` 551 variables, the example above creates a new object based on `process.env` but with the `GIT_SSH_COMMAND` property added. 552 553 # Exception Handling 554 555 When the `git` process exits with a non-zero status (or in some cases like `merge` the git process exits with a 556 successful zero code but there are conflicts in the merge) the task will reject with a `GitError` when there is no 557 available parser to handle the error or a 558 `GitResponseError` for when there is. 559 560 See the `err` property of the callback: 561 562 ```javascript 563 git.merge((err, mergeSummary) => { 564 if (err.git) { 565 mergeSummary = err.git; // the failed mergeSummary 566 } 567 }); 568 ``` 569 570 Catch errors with try/catch in async code: 571 572 ```javascript 573 try { 574 const mergeSummary = await git.merge(); 575 console.log(`Merged ${mergeSummary.merges.length} files`); 576 } catch (err) { 577 // err.message - the string summary of the error 578 // err.stack - some stack trace detail 579 // err.git - where a parser was able to run, this is the parsed content 580 581 console.error(`Merge resulted in ${err.git.conflicts.length} conflicts`); 582 } 583 ``` 584 585 Catch errors with a `.catch` on the promise: 586 587 ```javascript 588 const mergeSummary = await git.merge().catch((err) => { 589 if (err.git) { 590 return err.git; 591 } // the unsuccessful mergeSummary 592 throw err; // some other error, so throw 593 }); 594 595 if (mergeSummary.failed) { 596 console.error(`Merge resulted in ${mergeSummary.conflicts.length} conflicts`); 597 } 598 ``` 599 600 With typed errors available in TypeScript 601 602 ```typescript 603 import { simpleGit, MergeSummary, GitResponseError } from 'simple-git'; 604 try { 605 const mergeSummary = await simpleGit().merge(); 606 console.log(`Merged ${mergeSummary.merges.length} files`); 607 } catch (err) { 608 // err.message - the string summary of the error 609 // err.stack - some stack trace detail 610 // err.git - where a parser was able to run, this is the parsed content 611 const mergeSummary: MergeSummary = (err as GitResponseError<MergeSummary>).git; 612 const conflicts = mergeSummary?.conflicts || []; 613 614 console.error(`Merge resulted in ${conflicts.length} conflicts`); 615 } 616 ``` 617 618 # Troubleshooting / FAQ 619 620 ### Enable logging 621 622 See the [debug logging guide](https://github.com/steveukx/git-js/blob/main/docs/DEBUG-LOGGING-GUIDE.md) for logging examples and how to 623 make use of the [debug](https://www.npmjs.com/package/debug) library's programmatic interface 624 in your application. 625 626 ### Enable Verbose Logging 627 628 See the [debug logging guide](https://github.com/steveukx/git-js/blob/main/docs/DEBUG-LOGGING-GUIDE.md#verbose-logging-options) for 629 the full list of verbose logging options to use with the 630 [debug](https://www.npmjs.com/package/debug) library. 631 632 ### Every command returns ENOENT error message 633 634 There are a few potential reasons: 635 636 - `git` isn't available as a binary for the user running the main `node` process, custom paths to the binary can be used 637 with the `.customBinary(...)` api option. 638 639 - the working directory passed in to the main `simple-git` function isn't accessible, check it is read/write accessible 640 by the user running the `node` process. This library uses 641 [@kwsites/file-exists](https://www.npmjs.com/package/@kwsites/file-exists) to validate the working directory exists, 642 to output its logs add `@kwsites/file-exists` to your `DEBUG` environment variable. eg: 643 644 `DEBUG=@kwsites/file-exists,simple-git node ./your-app.js` 645 646 ### Log format fails 647 648 The properties of `git log` are fetched using the `--pretty=format` argument which supports different tokens depending 649 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 650 before that please ensure you are supplying your own format object with properties supported by the version of git you 651 are using. 652 653 For more details of the supported tokens, please see the 654 [official `git log` documentation](https://git-scm.com/docs/git-log#_pretty_formats) 655 656 ### Log response properties are out of order 657 658 The properties of `git.log` are fetched using the character sequence `ò` as a delimiter. If your commit messages 659 use this sequence, supply a custom `splitter` in the options, for example: `git.log({ splitter: '💻' })` 660 661 ### Pull / Diff / Merge summary responses don't recognise any files 662 663 - Enable verbose logs with the environment variable `DEBUG=simple-git:task:*,simple-git:output:*` 664 - Check the output (for example: `simple-git:output:diff:1 [stdOut] 1 file changed, 1 insertion(+)`) 665 - Check the `stdOut` output is the same as you would expect to see when running the command directly in terminal 666 - Check the language used in the response is english locale 667 668 In some cases `git` will show progress messages or additional detail on error states in the output for 669 `stdErr` that will help debug your issue, these messages are also included in the verbose log. 670 671 ### Legacy Node Versions 672 673 From `v3.x`, `simple-git` will drop support for `node.js` version 10 or below, to use in a lower version of node will 674 result in errors such as: 675 676 - `Object.fromEntries is not a function` 677 - `Object.entries is not a function` 678 - `message.flatMap is not a function` 679 680 To resolve these issues, either upgrade to a newer version of node.js or ensure you are using the necessary polyfills 681 from `core-js` - see [Legacy Node Versions](https://github.com/steveukx/git-js/blob/main/docs/LEGACY_NODE_VERSIONS.md). 682 683 # Examples 684 685 ### using a pathspec to limit the scope of the task 686 687 If the `simple-git` api doesn't explicitly limit the scope of the task being run (ie: `git.add()` requires the files to 688 be added, but `git.status()` will run against the entire repo), add a `pathspec` to the command using trailing options: 689 690 ```typescript 691 import { simpleGit, pathspec } from "simple-git"; 692 693 const git = simpleGit(); 694 const wholeRepoStatus = await git.status(); 695 const subDirStatusUsingOptArray = await git.status([pathspec('sub-dir')]); 696 const subDirStatusUsingOptObject = await git.status({ 'sub-dir': pathspec('sub-dir') }); 697 ``` 698 699 ### async await 700 701 ```javascript 702 async function status(workingDir) { 703 let statusSummary = null; 704 try { 705 statusSummary = await simpleGit(workingDir).status(); 706 } catch (e) { 707 // handle the error 708 } 709 710 return statusSummary; 711 } 712 713 // using the async function 714 status(__dirname + '/some-repo').then((status) => console.log(status)); 715 ``` 716 717 ### Initialise a git repo if necessary 718 719 ```javascript 720 const git = simpleGit(__dirname); 721 722 git.checkIsRepo() 723 .then((isRepo) => !isRepo && initialiseRepo(git)) 724 .then(() => git.fetch()); 725 726 function initialiseRepo(git) { 727 return git.init().then(() => git.addRemote('origin', 'https://some.git.repo')); 728 } 729 ``` 730 731 ### Update repo and get a list of tags 732 733 ```javascript 734 simpleGit(__dirname + '/some-repo') 735 .pull() 736 .tags((err, tags) => console.log('Latest available tag: %s', tags.latest)); 737 738 // update repo and when there are changes, restart the app 739 simpleGit().pull((err, update) => { 740 if (update && update.summary.changes) { 741 require('child_process').exec('npm restart'); 742 } 743 }); 744 ``` 745 746 ### Starting a new repo 747 748 ```javascript 749 simpleGit() 750 .init() 751 .add('./*') 752 .commit('first commit!') 753 .addRemote('origin', 'https://github.com/user/repo.git') 754 .push('origin', 'master'); 755 ``` 756 757 ### push with `-u` 758 759 ```javascript 760 simpleGit() 761 .add('./*') 762 .commit('first commit!') 763 .addRemote('origin', 'some-repo-url') 764 .push(['-u', 'origin', 'master'], () => console.log('done')); 765 ``` 766 767 ### Piping to the console for long-running tasks 768 769 See [progress events](https://github.com/steveukx/git-js/blob/main/docs/PLUGIN-PROGRESS-EVENTS.md) for more details on 770 logging progress updates. 771 772 ```javascript 773 const git = simpleGit({ 774 progress({ method, stage, progress }) { 775 console.log(`git.${method} ${stage} stage ${progress}% complete`); 776 }, 777 }); 778 git.checkout('https://github.com/user/repo.git'); 779 ``` 780 781 ### Update repo and print messages when there are changes, restart the app 782 783 ```javascript 784 // when using a chain 785 simpleGit() 786 .exec(() => console.log('Starting pull...')) 787 .pull((err, update) => { 788 if (update && update.summary.changes) { 789 require('child_process').exec('npm restart'); 790 } 791 }) 792 .exec(() => console.log('pull done.')); 793 794 // when using async and optional chaining 795 const git = simpleGit(); 796 console.log('Starting pull...'); 797 if ((await git.pull())?.summary.changes) { 798 require('child_process').exec('npm restart'); 799 } 800 console.log('pull done.'); 801 ``` 802 803 ### Get a full commits list, and then only between 0.11.0 and 0.12.0 tags 804 805 ```javascript 806 console.log(await simpleGit().log()); 807 console.log(await simpleGit().log('0.11.0', '0.12.0')); 808 ``` 809 810 ### Set the local configuration for author, then author for an individual commit 811 812 ```javascript 813 simpleGit() 814 .addConfig('user.name', 'Some One') 815 .addConfig('user.email', 'some@one.com') 816 .commit('committed as "Some One"', 'file-one') 817 .commit('committed as "Another Person"', 'file-two', { 818 '--author': '"Another Person <another@person.com>"', 819 }); 820 ``` 821 822 ### Get remote repositories 823 824 ```javascript 825 simpleGit().listRemote(['--get-url'], (err, data) => { 826 if (!err) { 827 console.log('Remote url for repository at ' + __dirname + ':'); 828 console.log(data); 829 } 830 }); 831 ```