Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
S

simple-git

> 开发工具
Open source

Simple and fast git helper functions.

190 stars0 likes0 views
WebsiteGitHub

About

Simple and fast git helper functions.

@napi-rs/simple-git

Repository

Usage

…

API

…

Disposal

dispose() — and its alias free() — eagerly releases the native git2 handle without waiting for garbage collection; both are idempotent. After disposal every throwing method throws "Repository has been disposed" (the Option-returning lookups return null instead), and every handle derived from the repo (Remote, Tree, Commit, Reference, RevWalk, …) throws the same error on use — whether it is the receiver or passed as an argument to another method (machine-enforced, not merely documented). Disposal does NOT cancel already-scheduled *Async operations: they reopen the repo on their own worker thread and run to completion. To cancel a pending async op, pass an AbortSignal to the *Async method rather than relying on dispose().

Reference

Usage

typescript
import { Repository } from '@napi-rs/simple-git'

const repo = new Repository('/path/to/repo') // Open an existed repo

const headReference = repo.head()

headReference.shorthand() // 'main'
headReference.name() // 'refs/heads/main'
headReference.target() // 7a1256e2f847f395219980bc06c6dadf0148f18d

API

typescript
/** An enumeration of all possible kinds of references. */
export const enum ReferenceType {
  /** A reference which points at an object id. */
  Direct = 0,
  /** A reference which points at another reference. */
  Symbolic = 1,
  Unknown = 2
}
export class Reference {
  /**
   * Ensure the reference name is well-formed.
   *
   * Validation is performed as if [`ReferenceFormat::ALLOW_ONELEVEL`]
   * was given to [`Reference.normalize_name`]. No normalization is
   * performed, however.
   *
   * ```ts
   * import { Reference } from '@napi-rs/simple-git'
   *
   * console.assert(Reference.isValidName("HEAD"));
   * console.assert(Reference.isValidName("refs/heads/main"));
   *
   * // But:
   * console.assert(!Reference.isValidName("main"));
   * console.assert(!Reference.isValidName("refs/heads/*"));
   * console.assert(!Reference.isValidName("foo//bar"));
   * 

…


## Error handling

Every error thrown by this library — from a synchronous method or from a rejected
`*Async` promise — is a standard `Error` carrying a `code` string property drawn
from a fixed union of tokens. The tokens are exported as the **`GitErrorCode`**
const enum, and any caught value can be narrowed to a coded error with the
**`isGitError(e)`** type guard:

```ts
import { isGitError, GitErrorCode } from '@napi-rs/simple-git'

try {
  // …some git operation…
} catch (e) {
  if (isGitError(e) && e.code === GitErrorCode.NotFound) {
    // handle the missing object/reference/config entry
  }
}

isGitError(e) returns true only when e is a genuine Error object whose code is a real member of the GitErrorCode enum; it narrows e to Error & { code: GitErrorCode } in TypeScript. The Error check is the native Node-API napi_is_error test (not a JS-level instanceof), so it recognizes cross-realm and subclassed errors while rejecting look-alike proxies and plain objects. Membership is validated against the enum (the single source of truth), so a non-git Error that merely exposes some other string .code (e.g. Node's ENOENT) returns false. The guard is total — it never throws for any input, even a hostile value with a throwing proxy trap or Symbol.hasInstance, or an Error whose code is a throwing getter (all return false) — so it is always safe to call inside a catch.

The 29 members of GitErrorCode are the 28 libgit2 error classes plus one napi-level token:

Token Meaning
GenericError Unclassified catch-all. Any unmapped or future libgit2 code collapses here — treat it as "something went wrong" rather than a specific class.
NotFound A requested object/reference/config entry does not exist.
Exists The object already exists and cannot be overwritten.
Ambiguous A short OID or name matched more than one object.
BufSize An output buffer was too small.
User A user-supplied callback returned an error.
BareRepo The operation is not allowed on a bare repository.
UnbornBranch HEAD points at a branch with no commits yet.
Unmerged The index contains unmerged entries.
NotFastForward A reference update was rejected because it was not fast-forward.
InvalidSpec A refspec/name is not well-formed.
Conflict A checkout/merge conflict prevents the operation.
Locked The resource is locked by another operation.
Modified The reference/object was modified concurrently.
Auth Authentication failed.
Certificate The server TLS certificate was rejected.
Applied The patch/commit was already applied.
Peel An object could not be peeled to the requested type.
Eof Unexpected end of file/stream.
Invalid An invalid operation or input for the current state.
Uncommitted Uncommitted changes prevent the operation.
Directory The operation is not valid on a directory.
MergeConflict A merge produced conflicts.
HashsumMismatch A hash verification failed.
IndexDirty The index has unsaved changes.
ApplyFail A patch failed to apply.
Owner The repository is owned by an unexpected user.
Timeout The operation timed out.
InvalidArg napi-level argument validation / API misuse (e.g. an option object reused across two *Async calls, or RemoteCallbacks passed to fetchAsync/pushAsync). Not a libgit2 class.

Synchronous methods and *Async promise rejections expose the same GitErrorCode token set, so you can branch on it either way:

typescript
import { isGitError, GitErrorCode } from '@napi-rs/simple-git'

// Synchronous
try {
  repo.findRemote('does-not-exist')
} catch (e) {
  if (isGitError(e) && e.code === GitErrorCode.NotFound) {
    // handle the missing remote
  }
}

// Asynchronous
await repo.getFileLatestModifiedDateAsync('build.rs').catch((e) => {
  if (isGitError(e) && e.code === GitErrorCode.GenericError) {
    // unclassified failure
  }
})

Cancellation is different. *Async methods that accept an AbortSignal reject an aborted call with napi's own AbortError, whose .code === "Cancelled". That is napi's runtime cancellation code — it is not a GitErrorCode member (it comes from napi, not the git layer), because cancellation bypasses the task's own reject hook. Because "Cancelled" is not a GitErrorCode member, isGitError returns false for it. Detect an aborted call separately — via the AbortSignal's aborted/abort event or by checking e.code === "Cancelled" — rather than through isGitError.

Performance

Compared with the exec function, which gets the file's latest modified date by spawning a child process. Getting the latest modified date from the file 1000 times:

Child process took 1.9s
@napi-rs/simple-git took 65ms

Issues· 0 open

View all issuesOpen on GitHub

No open issues yet, or sync has not completed.

> Tags

Rustlibgit2libgit2-librarynapinapi-rs

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 18, 2026
Category开发工具
PricingOpen source

> Related tools

V
VS Code
流行的开源代码编辑器
G
Git
分布式版本控制系统
V
Vite
下一代前端构建工具