• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

steveukx/git-js: A light weight interface for running git commands in any node.j ...

原作者: [db:作者] 来自: 网络 收藏 邀请

开源软件名称:

steveukx/git-js

开源软件地址:

https://github.com/steveukx/git-js

开源编程语言:

TypeScript 94.2%

开源软件介绍:

Simple Git

NPM version

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

Version 3 - Out Now

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).

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 {default: 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,
};

// 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

  • 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.

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.

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
.diff(options, handlerFn) get the diff of the current repo compared to the last commit with a set of options supplied as a string
.diff(handlerFn) get the diff for all file in the current repo compared to the last commit
.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
.diffSummary(options, handlerFn) includes options in the call to diff --stat options and returns a DiffSummary
.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
.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
.stash([options, ][ handlerFn]) 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, ][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.
.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.
.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

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) - uses the checks out the supplied options object/array to check out.

  • .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 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 - when supplied along with options.to sets the range of commits to log
    • 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 - when supplied along with options.from sets the range of commits to log

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).

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

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).


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap