简单快速的 git 帮助函数。
@napi-rs/simple-gitRepository……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().
Referenceimport { 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/** 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:
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.
*Asyncmethods that accept anAbortSignalreject an aborted call with napi's ownAbortError, whose.code === "Cancelled". That is napi's runtime cancellation code — it is not aGitErrorCodemember (it comes from napi, not the git layer), because cancellation bypasses the task's own reject hook. Because"Cancelled"is not aGitErrorCodemember,isGitErrorreturnsfalsefor it. Detect an aborted call separately — via theAbortSignal'saborted/abortevent or by checkinge.code === "Cancelled"— rather than throughisGitError.
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,或尚未同步最近议题。