/* auto-generated by NAPI-RS */ /* eslint-disable */ /** * Which binding artifact the generated loader actually loaded: `'native'` for * a native addon, otherwise the `platformArchABI` of the WASI flavor. Every * flavor napi-rs can build is listed, because `NAPI_RS_NATIVE_LIBRARY_PATH` * can point the loader at a WASI artifact this package does not build itself. */ export declare const __napiBindingTarget: 'native' | 'wasm32-wasi' | 'wasm32-wasip1' declare global { interface IteratorObject extends globalThis.Iterator { [globalThis.Symbol.iterator](): globalThis.IteratorObject } } export declare class Blob { /** Get the id (SHA1) of a repository blob */ id(): string /** Determine if the blob content is most certainly binary or not. */ isBinary(): boolean /** Get the content of this blob. */ content(): Buffer /** Get the size in bytes of the contents of this blob. */ size(): number } /** * A git branch. * * A branch is a thin wrapper around an underlying reference; the full * reference name is available via `reference_name`. */ export declare class Branch { /** * Return the name of the given local or remote branch. * * Returns `None` if the name is not valid utf-8. */ name(): string | null /** Determine if the current local branch is pointed at by HEAD. */ isHead(): boolean /** * Get the full name of the reference backing this branch * (e.g. `refs/heads/main`). * * Returns `None` if the reference name is not valid utf-8. */ referenceName(): string | null /** Delete an existing branch reference. */ delete(): void /** * Return the reference supporting the remote tracking branch, given a local * branch reference. * * Returns `None` when the branch has no configured upstream. */ upstream(): Branch | null /** * Return the reference backing this branch as a live `Reference`. * * Branches are direct references, so the resolved direct reference is * returned (e.g. `refs/heads/main`). */ get(): Reference } export declare class Commit { /** Get the id (SHA1) of a repository object */ id(): string /** * Get the id of the tree pointed to by this commit. * * No attempts are made to fetch an object from the ODB. */ treeId(): string /** Get the tree pointed to by this commit. */ tree(): Tree /** * Get the full message of a commit. * * The returned message will be slightly prettified by removing any * potential leading newlines. * * `None` will be returned if the message is not valid utf-8 */ message(): string | null /** * Get the full message of a commit as a byte slice. * * The returned message will be slightly prettified by removing any * potential leading newlines. */ messageBytes(): Buffer /** * Get the encoding for the message of a commit, as a string representing a * standard encoding name. * * `None` will be returned if the encoding is not known */ messageEncoding(): string | null /** * Get the full raw message of a commit. * * `None` will be returned if the message is not valid utf-8 */ messageRaw(): string | null /** Get the full raw message of a commit. */ messageRawBytes(): Buffer /** * Get the full raw text of the commit header. * * `None` will be returned if the message is not valid utf-8 */ rawHeader(): string | null /** Get an arbitrary header field. */ headerFieldBytes(field: string): Buffer /** Get the full raw text of the commit header. */ rawHeaderBytes(): Buffer /** * Get the short "summary" of the git commit message. * * The returned message is the summary of the commit, comprising the first * paragraph of the message with whitespace trimmed and squashed. * * `None` may be returned if an error occurs or if the summary is not valid * utf-8. */ summary(): string | null /** * Get the short "summary" of the git commit message. * * The returned message is the summary of the commit, comprising the first * paragraph of the message with whitespace trimmed and squashed. * * `None` may be returned if an error occurs */ summaryBytes(): Buffer | null /** * Get the long "body" of the git commit message. * * The returned message is the body of the commit, comprising everything * but the first paragraph of the message. Leading and trailing whitespaces * are trimmed. * * `None` may be returned if an error occurs or if the summary is not valid * utf-8. */ body(): string | null /** * Get the long "body" of the git commit message. * * The returned message is the body of the commit, comprising everything * but the first paragraph of the message. Leading and trailing whitespaces * are trimmed. * * `None` may be returned if an error occurs. */ bodyBytes(): Buffer | null /** * Get the commit time (i.e. committer time) of a commit. * * Returns the committer time as a UTC `Date`; the committer's timezone * offset is not preserved (the value is normalized to UTC). */ time(): Date /** Get the author of this commit. */ author(): Signature /** Get the committer of this commit. */ committer(): Signature /** * Amend this existing commit with all non-`None` values * * This creates a new commit that is exactly the same as the old commit, * except that any non-`None` values will be updated. The new commit has * the same parents as the old commit. * * For information about `update_ref`, see [`Repository::commit`]. * * [`Repository::commit`]: struct.Repository.html#method.commit */ amend(updateRef?: string | undefined | null, author?: Signature | undefined | null, committer?: Signature | undefined | null, messageEncoding?: string | undefined | null, message?: string | undefined | null, tree?: Tree | undefined | null): string /** * Get the number of parents of this commit. * * Use the `parents` iterator to return an iterator over all parents. */ parentCount(): number /** * Get the specified parent of the commit. * * Use the `parents` iterator to return an iterator over all parents. */ parent(i: number): Commit /** * Get the specified parent id of the commit. * * This is different from `parent`, which will attempt to load the * parent commit from the ODB. * * Use the `parent_ids` iterator to return an iterator over all parents. */ parentId(i: number): string /** Casts this Commit to be usable as an `Object` */ asObject(): GitObject } /** * A git configuration store. * * Obtain one with `Repository.config()` (a prioritized view of system, global * and repository config) or `Config.openDefault()` (system/global/XDG only). */ export declare class Config { /** * Open the global, XDG and system configuration files into a single * prioritized config object that can be used when accessing default config * data outside a repository. */ static openDefault(): Config /** * Get the value of a string config variable as an owned string. * * All config files are searched in order of their level (highest priority * first) and the first occurrence is returned. Errors if the value is not * valid utf-8 or the key is missing. */ getString(name: string): string /** Get the value of a boolean config variable. */ getBoolean(name: string): boolean /** * Get the value of an integer config variable, as a JS `number`. * * Reads the value as a 64-bit integer. Errors with `InvalidArg` when it lies * outside the JS safe-integer range (±(2^53 − 1)), where a `number` would lose * precision — use `getBigInt` for those. */ getNumber(name: string): number /** * Get the value of an i64 config variable, as a JS `bigint`. * * Returns a `bigint` rather than a `number` so values beyond * `Number.MAX_SAFE_INTEGER` (2^53 - 1) survive without truncation. */ getBigInt(name: string): bigint /** * Set the value of a string config variable in the config file with the * highest level (usually the local one). */ setString(name: string, value: string): void /** * Set the value of a boolean config variable in the config file with the * highest level (usually the local one). */ setBoolean(name: string, value: boolean): void /** * Set the value of an integer config variable in the config file with the * highest level (usually the local one). Takes a JS `number`. * * Errors with `InvalidArg` when `value` is not an integer or lies outside the * JS safe-integer range (±(2^53 − 1)) — use `setBigInt` for larger magnitudes * rather than silently truncating. */ setNumber(name: string, value: number): void /** * Set the value of an i64 config variable in the config file with the * highest level (usually the local one). Takes a JS `bigint`. * * Errors with `InvalidArg` if the `bigint` does not fit losslessly in an * i64 rather than silently truncating it. */ setBigInt(name: string, value: bigint): void /** * Delete a config variable from the config file with the highest level * (usually the local one). */ removeEntry(name: string): void /** * Create a read-only point-in-time snapshot of this configuration. * * A snapshot gives a consistent view for looking up complex values. Note * that `get_*` on a live (non-snapshot) config re-reads the underlying * files on each call. */ snapshot(): Config /** * List configuration entries, optionally filtered by a glob pattern. * * Each borrowed entry is eagerly materialized into an owned `ConfigEntry`. * Entries whose name or value is not valid utf-8 are skipped. */ entries(glob?: string | undefined | null): Array } export declare class Cred { /** * Create a "default" credential usable for Negotiate mechanisms like NTLM * or Kerberos authentication. */ constructor() /** * Create a new ssh key credential object used for querying an ssh-agent. * * The username specified is the username to authenticate. */ static sshKeyFromAgent(username: string): Cred /** Create a new passphrase-protected ssh key credential object. */ static sshKey(username: string, publickey: string | undefined | null, privatekey: string, passphrase?: string | undefined | null): Cred /** Create a new ssh key credential object reading the keys from memory. */ static sshKeyFromMemory(username: string, publickey: string | undefined | null, privatekey: string, passphrase?: string | undefined | null): Cred /** Create a new plain-text username and password credential object. */ static userpassPlaintext(username: string, password: string): Cred /** * Create a credential to specify a username. * * This is used with ssh authentication to query for the username if none is * specified in the URL. */ static username(username: string): Cred /** Check whether a credential object contains username information. */ hasUsername(): boolean /** * Return the type of credentials that this object represents. * * The value is the raw `CredentialType` bitset (an OR-able `number`); test * individual bits with `credTypeContains` and the `CredentialType` constants. */ credType(): number } /** * An iterator over the diffs in a delta * * This type extends JavaScript's `Iterator`, and so has the iterator helper * methods. It may extend the upcoming TypeScript `Iterator` class in the future. * * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Iterator#iterator_helper_methods * @see https://www.typescriptlang.org/docs/handbook/release-notes/typescript-5-6.html#iterator-helper-methods */ export declare class Deltas { [globalThis.Symbol.iterator](): this next(...[value]: [] | [void]): globalThis.IteratorResult return(...[value]: [] | [void]): globalThis.IteratorResult throw(exception?: unknown): globalThis.IteratorResult } export interface Deltas extends globalThis.Omit, 'next' | 'return' | 'throw'> {} export declare class Diff { /** * Merge one diff into another. * * This merges items from the "from" list into the "self" list. The * resulting diff will have all items that appear in either list. * If an item appears in both lists, then it will be "merged" to appear * as if the old version was from the "onto" list and the new version * is from the "from" list (with the exception that if the item has a * pending DELETE in the middle, then it will show as deleted). */ merge(diff: Diff): void /** Returns an iterator over the deltas in this diff. */ deltas(): Deltas /** Check if deltas are sorted case sensitively or insensitively. */ isSortedIcase(): boolean /** * Render the diff as unified-diff bytes (the `git diff` patch format). * * `git_diff_line::content` does not include the origin sigil, so for * context/add/delete lines the `+`/`-`/space sigil is emitted before the * content bytes, matching libgit2's `diff_print.c`. * * Returned as raw bytes rather than a string so non-UTF-8 file content is * preserved exactly. */ toPatch(): Buffer } export declare class DiffDelta { /** * Returns the flags on the delta. * * The value is the raw `git2::DiffFlags` bitset (an OR-able `number`); test * individual bits with `diffFlagsContains` and the `DiffFlags` constants. */ flags(): number /** Returns the number of files in this delta. */ numFiles(): number /** Returns the status of this entry */ status(): Delta /** * Return the file which represents the "from" side of the diff. * * What side this means depends on the function that was used to generate * the diff and will be documented on the function itself. */ oldFile(): DiffFile /** * Return the file which represents the "to" side of the diff. * * What side this means depends on the function that was used to generate * the diff and will be documented on the function itself. */ newFile(): DiffFile } export declare class DiffFile { /** * Returns the Oid of this item. * * If this entry represents an absent side of a diff (e.g. the `old_file` * of a `Added` delta), then the oid returned will be zeroes. */ id(): string /** * Returns the path of the entry relative to the working directory of the * repository, as a lossily-decoded (UTF-8) string. * * Returns `null` when the path is absent or not representable. */ path(): string | null /** Returns the size of this entry, in bytes */ size(): number /** Returns `true` if file(s) are treated as binary data. */ isBinary(): boolean /** Returns `true` if file(s) are treated as text data. */ isNotBinary(): boolean /** Returns `true` if `id` value is known correct. */ isValidId(): boolean /** Returns `true` if file exists at this side of the delta. */ exists(): boolean /** Returns file mode. */ mode(): FileMode } /** * @remarks Single-use: consumed by the first `fetch()` or `fetchAsync()` call. * Reusing the same instance throws (`InvalidArg`, "FetchOptions can only be used * once") — synchronously at the call site even for `fetchAsync` (it does NOT * reject the returned Promise). Construct a fresh instance per call. */ export declare class FetchOptions { constructor() /** Set the callbacks to use for the fetch operation. */ remoteCallback(callback: RemoteCallbacks): this /** Set the proxy options to use for the fetch operation. */ proxyOptions(options: ProxyOptions): this /** Set whether to perform a prune after the fetch. */ prune(prune: FetchPrune): this /** * Set whether to write the results to FETCH_HEAD. * * Defaults to `true`. */ updateFetchhead(update: boolean): this /** * Set fetch depth, a value less or equal to 0 is interpreted as pull * everything (effectively the same as not declaring a limit depth). */ depth(depth: number): this /** * Set how to behave regarding tags on the remote, such as auto-downloading * tags for objects we're downloading or downloading all of them. * * The default is to auto-follow tags. */ downloadTags(opt: AutotagOption): this /** * Set remote redirection settings; whether redirects to another host are * permitted. * * By default, git will follow a redirect on the initial request * (`/info/refs`), but not subsequent requests. */ followRedirects(opt: RemoteRedirect): this /** * Set extra headers for this fetch operation. * * Throws if any header contains an interior NUL byte. */ customHeaders(headers: Array): this } export declare class GitObject { /** Get the id (SHA1) of a repository object */ id(): string /** Get the type of the object. */ kind(): ObjectType | null /** * Recursively peel an object until an object of the specified type is met. * * If you pass `Any` as the target type, then the object will be * peeled until the type changes (e.g. a tag will be chased until the * referenced object is no longer a tag). */ peel(kind: ObjectType): GitObject /** Recursively peel an object until a blob is found */ peelToBlob(): Blob } /** * A git index (the staging area). * * Obtain one with `Repository.index()`. Mutating methods change the in-memory * index only; call `write()` to persist it to disk, or `writeTree()` to write * its current state to the object database as a tree (whose OID can then be * used to create a commit). */ export declare class Index { /** * Add or update an index entry from a file on disk. * * The `path` is relative to the repository's working directory and must be * readable. This forces the file to be added to the index even if it is * ignored. */ addPath(path: string): void /** * Add or update index entries matching files in the working directory. * * `pathspecs` defaults to `["*"]` (everything) when omitted. Ignored files * are skipped unless `force` is `true`, which maps to * `IndexAddOption::FORCE`. */ addAll(pathspecs?: Array | undefined | null, force?: boolean | undefined | null): void /** * Update all index entries to match the working directory. * * Existing entries are refreshed and entries whose file no longer exists are * removed. `pathspecs` defaults to `["*"]` when omitted. This will fail on a * bare index. */ updateAll(pathspecs?: Array | undefined | null): void /** Remove an index entry corresponding to a file on disk. */ removePath(path: string): void /** Get the count of entries currently in the index. */ size(): number /** Write the in-memory index back to disk using an atomic file lock. */ write(): void /** * Write the index as a tree to the object database and return its OID. * * The index must be associated with an existing repository and must not * contain any conflicted entries. The returned OID can be used to create a * commit. */ writeTree(): string } export declare class ProxyOptions { constructor() /** * Try to auto-detect the proxy from the git configuration. * * Note that this will override `url` specified before. */ auto(): this /** * Specify the exact URL of the proxy to use. * * Note that this will override `auto` specified before. */ url(url: string): this } /** * @remarks Single-use: consumed by the first `push()` or `pushAsync()` call. * Reusing the same instance throws (`InvalidArg`, "PushOptions can only be used * once") — synchronously at the call site even for `pushAsync` (it does NOT * reject the returned Promise). Construct a fresh instance per call. */ export declare class PushOptions { constructor() /** Set the callbacks to use for the push operation. */ remoteCallback(callback: RemoteCallbacks): this /** Set the proxy options to use for the push operation. */ proxyOptions(options: ProxyOptions): this /** * If the transport being used to push to the remote requires the creation * of a pack file, this controls the number of worker threads used by the * packbuilder when creating that pack file to be sent to the remote. * * If set to 0 the packbuilder will auto-detect the number of threads to * create, and the default value is 1. */ packbuilderParallelism(parallel: number): this /** * Set remote redirection settings; whether redirects to another host are * permitted. * * By default, git will follow a redirect on the initial request * (`/info/refs`), but not subsequent requests. */ followRedirects(opt: RemoteRedirect): this /** * Set extra headers for this push operation. * * Throws if any header contains an interior NUL byte. */ customHeaders(headers: Array): this /** * Set "push options" to deliver to the remote. * * Throws if any push option contains an interior NUL byte. */ remotePushOptions(options: Array): this } export declare 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")); * ``` */ static isValidName(name: string): boolean /** Check if a reference is a local branch. */ isBranch(): boolean /** Check if a reference is a note. */ isNote(): boolean /** Check if a reference is a remote tracking branch */ isRemote(): boolean /** Check if a reference is a tag */ isTag(): boolean kind(): ReferenceType /** * Get the full name of a reference. * * Returns `None` if the name is not valid utf-8. */ name(): string | null /** * Get the full shorthand of a reference. * * This will transform the reference name into a name "human-readable" * version. If no shortname is appropriate, it will return the full name. * * Returns `None` if the shorthand is not valid utf-8. */ shorthand(): string | null /** * Get the OID pointed to by a direct reference. * * Only available if the reference is direct (i.e. an object id reference, * not a symbolic one). */ target(): string | null /** * Return the peeled OID target of this reference. * * This peeled OID only applies to direct references that point to a hard * Tag object: it is the result of peeling such Tag. */ targetPeel(): string | null /** * Peel a reference to a tree * * This method recursively peels the reference until it reaches * a tree. */ peelToTree(): Tree /** * Get full name to the reference pointed to by a symbolic reference. * * May return `None` if the reference is either not symbolic or not a * valid utf-8 string. */ symbolicTarget(): string | null /** * Resolve a symbolic reference to a direct reference. * * This method iteratively peels a symbolic reference until it resolves to * a direct reference to an OID. * * If a direct reference is passed as an argument, a copy of that * reference is returned. */ resolve(): Reference /** * Rename an existing reference. * * This method works for both direct and symbolic references. * * If the force flag is not enabled, and there's already a reference with * the given name, the renaming will fail. */ rename(newName: string, force: boolean, msg: string): Reference } export declare class Remote { /** Ensure the remote name is well-formed. */ static isValidName(name: string): boolean /** * Get the remote's name. * * Returns `None` if this remote has not yet been named or if the name is * not valid utf-8 */ name(): string | null /** * Get the remote's url. * * Returns `None` if the url is not valid utf-8 */ url(): string | null /** * Get the remote's pushurl. * * Returns `None` if the pushurl is not valid utf-8 */ pushUrl(): string | null /** * Get the remote's default branch. * * The remote (or more exactly its transport) must have connected to the * remote repository. This default branch is available as soon as the * connection to the remote is initiated and it remains available after * disconnecting. */ defaultBranch(): string /** Open a connection to a remote. */ connect(dir: Direction): void /** Check whether the remote is connected */ connected(): boolean /** Disconnect from the remote */ disconnect(): void /** * Cancel the operation * * At certain points in its operation, the network code checks whether the * operation has been cancelled and if so stops the operation. */ stop(): void /** * Download new data and update tips * * Convenience function to connect to a remote, download the data, * disconnect and update the remote-tracking branches. */ fetch(refspecs: Array, fetchOptions?: FetchOptions | undefined | null): void /** * Perform a push. * * If `refspecs` is empty the configured push refspecs are used. Delete a * remote ref by pushing `":refs/heads/branch"`. To detect per-ref server * rejections, set a `pushUpdateReference` callback on the `RemoteCallbacks`. */ push(refspecs: Array, pushOptions?: PushOptions | undefined | null): void /** * Asynchronous variant of `fetch`, performed off the main thread. * * `fetchOptions` may carry data-only settings (depth, prune, proxy url, * headers, ...). It must NOT carry `RemoteCallbacks`: those hold JS-backed * callbacks bound to the main JS thread and cannot be invoked safely from a * worker thread. If callbacks are required, use the synchronous `fetch`. * * Resolves the remote by name against the repository's CURRENT on-disk * configuration at the moment this async operation actually runs, not * against a snapshot of the `Remote` object's state when it was loaded. * If `remoteSetUrl`/`remoteAddFetch`/`remoteDelete` mutate this remote's * config after it was loaded but before this call completes, the * mutation IS observed here — unlike the synchronous `fetch()`, which * operates on the already-loaded snapshot and is documented as * unaffected by later config changes. Use the synchronous `fetch()` * when strict snapshot isolation from concurrent config changes matters. * * Safety: do not use the same `Remote` from the main thread while this async * operation is pending; the underlying git2 handle is not `Sync`. * * Synchronous pre-throw: although the declared return is `Promise`, * argument/state validation runs synchronously on the calling thread and * THROWS synchronously (the CALL throws — it does NOT return a rejected * Promise) when `fetchOptions` has already been consumed by a prior async * call or carries `RemoteCallbacks`. Wrap the CALL itself * (`try { await remote.fetchAsync(...) }`), not just the awaited Promise. */ fetchAsync(refspecs: Array, fetchOptions?: FetchOptions | undefined | null, signal?: AbortSignal | undefined | null): Promise /** * Asynchronous variant of `push`, performed off the main thread. * * `pushOptions` may carry data-only settings (packbuilder parallelism, * proxy url, headers, ...). It must NOT carry `RemoteCallbacks`: those hold * JS-backed callbacks bound to the main JS thread and cannot be invoked * safely from a worker thread. If callbacks (e.g. `pushUpdateReference`) are * required, use the synchronous `push`. * * Resolves against a URL/refspec snapshot captured from this loaded * `Remote` at call time (using the configured `pushurl` when set, else * `url`), rather than re-resolving the remote by name against live * on-disk config the way `fetchAsync` does. This asymmetry with * `fetchAsync` is intentional and is not merely a config-drift * optimization: libgit2's local transport ignores a configured `pushurl` * for the actual push — it re-derives the destination directly from the * remote's fetch `url` (see `transports/local.c`'s `local_push()`, * `push->remote->url`), even though `pushurl` is correctly used during * the connection handshake (`remote.c`'s `git_remote__urlfordirection`). * Re-resolving by name here, like `fetchAsync` does, would silently push * to the wrong destination for any local/file-path remote with a * configured `pushurl`. Capturing the effective push URL up front and * handing it to an anonymous remote sidesteps the bug, because that * remote's SOLE url is already the pushurl-resolved value. Trade-off: a * later `remoteSetUrl`/`remoteSetPushUrl`/`remoteAddPush` on the same name * after this `Remote` was loaded is NOT observed by an already-scheduled * `pushAsync`, matching the synchronous `push()` contract ("no loaded * remote instances will be affected"). Also note: pushurl + refspecs are * the config properties this snapshot captures, not the complete set that * can diverge between named and anonymous remote resolution — libgit2's * HTTP proxy auto-detection also consults `remote..proxy`, so * `pushAsync(...)` combined with `PushOptions.proxyOptions(new * ProxyOptions().auto())` will not pick up that per-remote proxy config * the way the synchronous, named-remote `push()` does. This is a known, * accepted gap (see the `remote_url` field doc on `RemotePushTask`), not * chased further here. * * Safety: do not use the same `Remote` from the main thread while this async * operation is pending; the underlying git2 handle is not `Sync`. * * Synchronous pre-throw: although the declared return is `Promise`, * argument/state validation runs synchronously on the calling thread and * THROWS synchronously (the CALL throws — it does NOT return a rejected * Promise) when `pushOptions` has already been consumed by a prior async * call or carries `RemoteCallbacks`, or when this remote's push URL is * unreadable/absent or its configured push refspecs cannot be read. Wrap the * CALL itself (`try { await remote.pushAsync(...) }`), not just the awaited * Promise. */ pushAsync(refspecs: Array, pushOptions?: PushOptions | undefined | null, signal?: AbortSignal | undefined | null): Promise /** * Update the tips to the new state * * `update_flags` is a raw bitset of `RemoteUpdateFlags` OR-ed together * (e.g. `RemoteUpdateFlags.UpdateFetchHead`). Unknown bits are ignored. */ updateTips(updateFlags: number, downloadTags: AutotagOption, callbacks?: RemoteCallbacks | undefined | null, msg?: string | undefined | null): void } /** * @remarks Single-use: attaching this to a `FetchOptions`/`PushOptions` via * `remoteCallback()` consumes it; a second attach throws (`InvalidArg`, * "RemoteCallbacks can only be used once"). Construct a fresh instance per * attach. (`updateTips` does NOT consume it and may reuse the same instance.) */ export declare class RemoteCallbacks { constructor() /** * The callback through which to fetch credentials if required. * * # Example * * Prepare a callback to authenticate using the `$HOME/.ssh/id_rsa` SSH key, and * extracting the username from the URL (i.e. git@github.com:rust-lang/git2-rs.git): * * ```js * import { join } from 'node:path' * import { homedir } from 'node:os' * * import { Cred, FetchOptions, RemoteCallbacks, RepoBuilder, credTypeContains } from '@napi-rs/simple-git' * * const builder = new RepoBuilder() * * const remoteCallbacks = new RemoteCallbacks() * .credentials((cred) => { * return Cred.sshKey(cred.username, null, join(homedir(), '.ssh', 'id_rsa'), null) * }) * * const fetchOptions = new FetchOptions().depth(0).remoteCallback(remoteCallbacks) * * const repo = builder.branch('master') * .fetchOptions(fetchOptions) * .clone("git@github.com:rust-lang/git2-rs.git", "git2-rs") * ``` */ credentials(callback: (arg: CredInfo) => Cred): this /** The callback through which progress is monitored. */ transferProgress(callback: (arg: Progress) => void): this /** * The callback through which progress of push transfer is monitored. * * The callback receives a single `PushTransferProgress` object describing how * many objects have been processed and how many bytes have been sent. */ pushTransferProgress(callback: (arg: PushTransferProgress) => void): this /** * Set a callback to get invoked for each updated reference on a push. * * The callback is invoked once per reference with a single * `PushUpdateReference` object. `status` is `null` when the reference was * updated successfully; otherwise it is the server's rejection reason. */ pushUpdateReference(callback: (arg: PushUpdateReference) => void): this } export declare class RepoBuilder { constructor() /** * Indicate whether the repository will be cloned as a bare repository or * not. */ bare(bare: boolean): this /** * Specify the name of the branch to check out after the clone. * * If not specified, the remote's default branch will be used. */ branch(branch: string): this /** * Configures options for bypassing the git-aware transport on clone. * * Bypassing it means that instead of a fetch libgit2 will copy the object * database directory instead of figuring out what it needs, which is * faster. If possible, it will hardlink the files to save space. */ cloneLocal(cloneLocal: CloneLocal): this /** * Options which control the fetch, including callbacks. * * The callbacks are used for reporting fetch progress, and for acquiring * credentials in the event they are needed. */ fetchOptions(fetchOptions: FetchOptions): this clone(url: string, path: string): Repository } export declare class Repository { /** * Eagerly release the underlying git2 repository handle * (`git_repository_free`), closing any open packfile file descriptors and * memory-mapped indexes without waiting for JavaScript garbage collection. * * This is idempotent: calling it more than once (or calling `free()` * afterwards) is a no-op. * * After disposal, every throwing method throws * `"Repository has been disposed"`; the `Option`-returning methods * (`workdir()`, `namespace()`, `findRemote()`, `findTree()`, * `findCommit()`, `findTag()`, `findTagByPrefix()`) return `null` instead. * Any handle previously derived from * this repository — `Remote`, `Reference`, `Tree`, `TreeEntry`, `Commit`, * `Tag`, `Branch`, `GitObject`, `Diff`, `RevWalk` and their descendants — * throws the same `"Repository has been disposed"` error on use, whether it * is the receiver or an argument passed to another method. This is * machine-enforced (mirroring better-sqlite3's `db.close()`), not merely a * documented contract. * * Disposal does NOT cancel `*Async` operations already in flight: a worker * scheduled before `dispose()` reopens the repository from its path on its * own thread and runs to completion (its promise still resolves and refs or * objects may change on disk), because it never touches this freed handle. * New `*Async` calls made after disposal throw synchronously. To cancel a * pending async operation, pass an `AbortSignal` to the `*Async` method * rather than relying on `dispose()`. * * `Symbol.dispose` cannot be generated by napi, so `using` support is * opt-in via a single line at startup: * * ```js * Repository.prototype[Symbol.dispose] ??= Repository.prototype.dispose * ``` */ dispose(): void /** * Alias for `dispose()`. Eagerly releases the underlying git2 repository * handle; idempotent. See `dispose()` for the full disposal contract. */ free(): void static init(p: string): Repository /** * Find and open an existing repository, with additional options. * * `flags` is a raw bitset of `RepositoryOpenFlags` OR-ed together (e.g. * `RepositoryOpenFlags.NoSearch | RepositoryOpenFlags.CrossFS`). Unknown * bits are ignored. * * - `RepositoryOpenFlags.NoSearch`: only open the repository at `path`; do * not walk upward through parent directories searching for one. * - `RepositoryOpenFlags.CrossFS`: when searching upward, allow crossing * filesystem boundaries. * - `RepositoryOpenFlags.Bare`: force opening as a bare repository (ignore * any working directory) and defer loading its config. * - `RepositoryOpenFlags.NoDotGit`: don't try appending `/.git` to `path`. * - `RepositoryOpenFlags.FromEnv`: resolve the repository from the same * environment variables git honors (ignores the other flags and * `ceilingDirs`). * * Note: a `FromEnv` handle re-consults the environment when an `*Async` * method reopens it on a worker thread. The git directory, working * directory, and namespace are re-pinned to this handle's resolved * values, but environment-derived index/object inputs (notably * `GIT_INDEX_FILE`, `GIT_OBJECT_DIRECTORY`, and * `GIT_ALTERNATE_OBJECT_DIRECTORIES`) are re-read from the *current* * process environment at reopen time. Mutating those variables between a * synchronous call and a later `*Async` call on the same handle can make * the two observe different index/object state. For stable results, do * not change those variables mid-flight, or open without `FromEnv`. * * `ceilingDirs` is a list of absolute paths at which the upward search stops * (ignored when `RepositoryOpenFlags.FromEnv` is set). */ static openExt(path: string, flags: number, ceilingDirs: Array): Repository /** * Attempt to open an already-existing repository at or above `path` * * This starts at `path` and looks up the filesystem hierarchy * until it finds a repository. */ static discover(path: string): Repository /** * Creates a new `--bare` repository in the specified folder. * * The folder must exist prior to invoking this function. */ static initBare(path: string): Repository /** * Clone a remote repository. * * See the `RepoBuilder` struct for more information. This function will * delegate to a fresh `RepoBuilder` */ static clone(url: string, path: string): Repository /** * Asynchronous variant of `clone`, performed off the main thread. * * The network/clone work runs on a worker thread and the resulting * `Repository` is constructed on the main thread once the clone completes. * * Safety: the resulting `Repository` only exists once the promise resolves; the * underlying git2 handle is not `Sync`, so use it only from the main thread. */ static cloneAsync(url: string, path: string, signal?: AbortSignal | undefined | null): Promise /** * Clone a remote repository, initialize and update its submodules * recursively. * * This is similar to `git clone --recursive`. */ static cloneRecurse(url: string, path: string): Repository /** * Attempt to open an already-existing repository at `path`. * * The path can point to either a normal or bare repository. */ constructor(gitDir: string) /** Retrieve and resolve the reference pointed at by HEAD. */ head(): Reference /** * Get the configuration file for this repository. * * If a configuration file has not been set, the default config set for the * repository will be returned, including global and system configurations. */ config(): Config /** * Create a new action signature with default user and now timestamp. * * This looks up the `user.name` and `user.email` from the configuration and * uses the current time as the timestamp. It returns an error if either the * `user.name` or `user.email` are not set. */ signature(): Signature /** Tests whether this repository is a shallow clone. */ isShallow(): boolean /** Tests whether this repository is empty. */ isEmpty(): boolean /** Tests whether this repository is a worktree. */ isWorktree(): boolean /** * Returns the path to the `.git` folder for normal repositories or the * repository itself for bare repositories. */ path(): string /** Returns the current state of this repository */ state(): RepositoryState /** * Get the path of the working directory for this repository. * * If this repository is bare, then `None` is returned. */ workdir(): string | null /** * Set the path to the working directory for this repository. * * If `update_link` is true, create/update the gitlink file in the workdir * and set config "core.worktree" (if workdir is not the parent of the .git * directory). */ setWorkdir(path: string, updateGitlink: boolean): void /** * Get the currently active namespace for this repository. * * If there is no namespace, or the namespace is not a valid utf8 string, * `None` is returned. */ namespace(): string | null /** Set the active namespace for this repository. */ setNamespace(namespace: string): void /** Remove the active namespace for this repository. */ removeNamespace(): void /** * Retrieves the Git merge message (the contents of `.git/MERGE_MSG`). * Remember to remove the message when finished. */ mergeMessage(): string /** Remove the Git merge message (`.git/MERGE_MSG`). */ removeMergeMessage(): void /** List all remotes for a given repository */ remotes(): Array /** Get the information for a particular remote */ findRemote(name: string): Remote | null /** * Add a remote with the default fetch refspec to the repository's * configuration. */ remote(name: string, url: string): Remote /** * Add a remote with the provided fetch refspec to the repository's * configuration. */ remoteWithFetch(name: string, url: string, refspec: string): Remote /** * Create an anonymous remote * * Create a remote with the given URL and refspec in memory. You can use * this when you have a URL instead of a remote's name. Note that anonymous * remotes cannot be converted to persisted remotes. */ remoteAnonymous(url: string): Remote /** * Give a remote a new name * * All remote-tracking branches and configuration settings for the remote * are updated. * * A temporary in-memory remote cannot be given a name with this method. * * No loaded instances of the remote with the old name will change their * name or their list of refspecs. * * The returned array of strings is a list of the non-default refspecs * which cannot be renamed and are returned for further processing by the * caller. */ remoteRename(name: string, newName: string): Array /** * Delete an existing persisted remote. * * All remote-tracking branches and configuration settings for the remote * will be removed. */ remoteDelete(name: string): this /** * Add a fetch refspec to the remote's configuration * * Add the given refspec to the fetch list in the configuration for the * named remote, without loading it. No loaded remote instances will be * affected. */ remoteAddFetch(name: string, refspec: string): this /** * Add a push refspec to the remote's configuration. * * Add the given refspec to the push list in the configuration. No * loaded remote instances will be affected. */ remoteAddPush(name: string, refspec: string): this /** * Set the URL of a remote in the repository's configuration. * * Updates the configured fetch URL for the named remote. No loaded * remote instances will be affected. */ remoteSetUrl(name: string, url: string): this /** * Set the remote's URL for pushing in the configuration. * * Remote objects already in memory will not be affected. This assumes * the common case of a single-url remote and will otherwise return an * error. * * `None` indicates that it should be cleared. */ remoteSetPushUrl(name: string, url?: string | undefined | null): this /** Lookup a reference to one of the objects in a repository. */ findTree(oid: string): Tree | null findCommit(oid: string): Commit | null /** * List the branches in the repository. * * Pass `filter` to restrict the listing to local or remote branches; omit it * to list both. Branches whose names are not valid utf-8 are skipped (they * cannot be re-resolved by name). */ branches(filter?: BranchType | undefined | null): Array /** * Lookup a branch by its name in a repository. * * Returns `null` when no branch with that name and type exists. */ findBranch(name: string, branchType: BranchType): Branch | null /** * Create a new branch pointing at a target commit. * * A new direct reference will be created pointing to this target commit. If * `force` is true and a branch already exists with the given name, it will * be replaced. */ branch(branchName: string, target: Commit, force: boolean): Branch /** * Check out the tree pointed to by `treeish` (a commit, tag or tree object), * updating the working directory to match. * * This does NOT update HEAD; pair it with `set_head` to switch branches. * The checkout is **safe** by default — pass `options.force = true` to * overwrite local modifications. */ checkoutTree(treeish: GitObject, options?: CheckoutOptions | undefined | null): void /** * Update files in the index and the working tree to match the content of * the tree pointed at by HEAD. * * The checkout is **safe** by default — pass `options.force = true` to * overwrite local modifications. */ checkoutHead(options?: CheckoutOptions | undefined | null): void /** * Update files in the working tree to match the content of the repository's * index. * * The checkout is **safe** by default — pass `options.force = true` to * overwrite local modifications. */ checkoutIndex(options?: CheckoutOptions | undefined | null): void /** * Make HEAD point to the reference named `refname`. * * If `refname` names an existing branch, HEAD becomes a symbolic reference * to that branch; otherwise it points to a not-yet-existing branch. This * does not touch the working directory — checkout separately. */ setHead(refname: string): void /** * Make HEAD point directly at the commit with the given OID, detaching it * from any branch. */ setHeadDetached(oid: string): void /** * Create a new direct reference named `name` pointing at the object `oid`. * * If `force` is true and a reference already exists with the given name, it * will be overwritten; otherwise the call fails. `log_message` is recorded * in the reflog. */ reference(name: string, oid: string, force: boolean, logMessage: string): Reference /** * Create a new symbolic reference named `name` pointing at the reference * named `target` (e.g. `refs/heads/main`). * * If `force` is true and a reference already exists with the given name, it * will be overwritten; otherwise the call fails. `log_message` is recorded * in the reflog. */ referenceSymbolic(name: string, target: string, force: boolean, logMessage: string): Reference /** * Create a new tag in the repository from an object * * A new reference will also be created pointing to this tag object. If * `force` is true and a reference already exists with the given name, * it'll be replaced. * * The message will not be cleaned up. * * The tag name will be checked for validity. You must avoid the characters * '~', '^', ':', ' \ ', '?', '[', and '*', and the sequences ".." and " @ * {" which have special meaning to revparse. */ tag(name: string, target: GitObject, tagger: Signature, message: string, force: boolean): string /** * Create a new tag in the repository from an object without creating a reference. * * The message will not be cleaned up. * * The tag name will be checked for validity. You must avoid the characters * '~', '^', ':', ' \ ', '?', '[', and '*', and the sequences ".." and " @ * {" which have special meaning to revparse. */ tagAnnotation(name: string, target: GitObject, tagger: Signature, message: string): string /** * Create a new lightweight tag pointing at a target object * * A new direct reference will be created pointing to this target object. * If force is true and a reference already exists with the given name, * it'll be replaced. */ tagLightweight(name: string, target: GitObject, force: boolean): string /** * Lookup a tag object from the repository. * * Returns `null` when no tag object with that OID exists. */ findTag(oid: string): Tag | null /** * Lookup a tag object by prefix hash from the repository. * * Returns `null` when no tag object matches the prefix. */ findTagByPrefix(prefixHash: string): Tag | null /** * Delete an existing tag reference. * * The tag name will be checked for validity, see `tag` for some rules * about valid names. */ tagDelete(name: string): void /** * Get a list with all the tags in the repository. * * An optional fnmatch pattern can also be specified. */ tagNames(pattern?: string | undefined | null): Array /** * iterate over all tags calling `cb` on each. * * The callback receives a single `TagForeachItem` object carrying the tag's * OID (`id`, a 40-char hex string) and its raw reference name (`nameBytes`, * a `Buffer`). Return `true` to continue iteration, `false` to stop. */ tagForeach(cb: (arg: TagForeachItem) => boolean): void /** * Create a diff between a tree and the working directory. * * The tree you provide will be used for the "old_file" side of the delta, * and the working directory will be used for the "new_file" side. * * This is not the same as `git diff ` or `git diff-index * `. Those commands use information from the index, whereas this * function strictly returns the differences between the tree and the files * in the working directory, regardless of the state of the index. Use * `tree_to_workdir_with_index` to emulate those commands. * * To see difference between this and `tree_to_workdir_with_index`, * consider the example of a staged file deletion where the file has then * been put back into the working dir and further modified. The * tree-to-workdir diff for that file is 'modified', but `git diff` would * show status 'deleted' since there is a staged delete. * * If `None` is passed for `tree`, then an empty tree is used. */ diffTreeToWorkdir(oldTree?: Tree | undefined | null, options?: DiffOptions | undefined | null): Diff /** * Create a diff between a tree and the working directory using index data * to account for staged deletes, tracked files, etc. * * This emulates `git diff ` by diffing the tree to the index and * the index to the working directory and blending the results into a * single diff that includes staged deleted, etc. */ diffTreeToWorkdirWithIndex(oldTree?: Tree | undefined | null, options?: DiffOptions | undefined | null): Diff /** * Create a diff between two trees inside this repository. * * The `old_tree` will be used for the "old_file" side of the delta and the * `new_tree` will be used for the "new_file" side. If `None` is passed for * either tree, an empty tree is used for that side. * * Combined with `treebuilder()` + `blob()`, two arbitrary strings can be * diffed without a workdir (like `git diff --no-index`): write each string * to a blob, put each blob in a single-entry tree via `TreeBuilder`, and * diff the two trees. */ diffTreeToTree(oldTree?: Tree | undefined | null, newTree?: Tree | undefined | null, options?: DiffOptions | undefined | null): Diff /** * Create a `TreeBuilder` to construct an in-memory tree. * * The builder edits a single level of a tree (each `insert` filename is one * path component). Pass `source` to start from a copy of an existing tree's * entries, or omit it to start empty. `write()` materializes the builder's * entries into a real tree object in this repository's object database. */ treebuilder(source?: Tree | undefined | null): TreeBuilder /** * Create new commit in the repository * * If the `update_ref` is not `None`, name of the reference that will be * updated to point to this commit. If the reference is not direct, it will * be resolved to a direct reference. Use "HEAD" to update the HEAD of the * current branch and make it point to this commit. If the reference * doesn't exist yet, it will be created. If it does exist, the first * parent must be the tip of this branch. * * `parents` is an optional list of parent commit OID hex strings. When it * is `None` or empty a parent-less root commit is created; otherwise each * OID is resolved to a commit and used as a parent (the first parent must * be the current tip of `update_ref`). */ commit(updateRef: string | undefined | null, author: Signature, committer: Signature, message: string, tree: Tree, parents?: Array | undefined | null): string /** * Asynchronous variant of `commit`, performed off the main thread. * * Resolves with the new commit's OID hex string. Arguments mirror `commit`: * the `author`/`committer` signatures are copied and the `tree` is captured * by OID, so the work can be moved to a worker thread safely. * * Safety: do not use the same `Repository` from the main thread while this * async operation is pending; the underlying git2 handle is not `Sync`. */ commitAsync(updateRef: string | undefined | null, author: Signature, committer: Signature, message: string, tree: Tree, parents?: Array | undefined | null, signal?: AbortSignal | undefined | null): Promise /** * Get the index (staging area) file for this repository. * * If a custom index has not been set, the default index for the repository * will be returned (the one at `.git/index`). */ index(): Index /** * Write an in-memory buffer to the object database as a blob and return its * OID hex string. */ blob(data: Uint8Array): string /** * Read a file from the filesystem and write its content to the object * database as a blob, returning its OID hex string. */ blobPath(path: string): string /** * Look up a blob in the repository's object database by its OID hex * string. Throws if the OID is malformed or no such blob exists. */ findBlob(oid: string): Blob /** Create a revwalk that can be used to traverse the commit graph. */ revWalk(): RevWalk /** * Last-modified commit time of `filepath` in **milliseconds since the Unix * epoch**. Throws when the merge-skipping walk finds no commit that modified * the path (never added, or touched only by merges). For a `null`-on-missing * `Date`, use `getFileLastModifiedDate`. * * This keeps the raw merge-skipping walk and does NOT apply the merge-only * fallback of `getFileLatestModified`: a file present only via merge commits * (an "evil merge") is treated as untouched and THROWS here, even though * `getFileLatestModified` returns a record for it. */ getFileLatestModifiedDate(filepath: string): number /** * Asynchronous variant of `getFileLatestModifiedDate`, computed off the main * thread. Rejects when the merge-skipping walk finds no commit that modified * `filepath` (never added, or touched only by merges). */ getFileLatestModifiedDateAsync(filepath: string, signal?: AbortSignal | undefined | null): Promise /** * Last-modified commit time of `filepath` as a `Date`, or `null` when the * merge-skipping walk finds no commit that modified it (never added, or * touched only by merges; never throws for the missing case). Equals * `FileModification.committerTime` from `getFileLatestModified` EXCEPT for a * file present only via merges: this method keeps the raw merge-skipping walk * and returns `null`, whereas `getFileLatestModified` falls back to the LATEST * merge that changed the file. Only real errors throw (unborn/empty HEAD, corrupt * object, out-of-range timestamp). For milliseconds-since-epoch, use * `getFileLatestModifiedDate`. */ getFileLastModifiedDate(filepath: string): Date | null /** * Asynchronous variant of `getFileLastModifiedDate`, computed off the main * thread. Resolves to `null` when the merge-skipping walk finds no commit that * modified `filepath` (never added, or touched only by merges). */ getFileLastModifiedDateAsync(filepath: string, signal?: AbortSignal | undefined | null): Promise /** * Last commit that modified `filepath` (author/committer identity, summary, * OID), or `null` when no non-merge commit ever recorded a change to the path * AND it is not present at HEAD -- i.e. a path never added, OR one that only * merge commits ever touched and that is absent at HEAD (e.g. deleted by a * merge; see the merge-only note below). A path present (a blob) at HEAD * always resolves. * * Walks history from HEAD newest-first (`Sort::TIME | Sort::TOPOLOGICAL`), * diffing each non-merge commit against its parent under a libgit2 pathspec * (so `filepath` may be a directory or glob that matches a file); merge * commits are skipped when finding the last modification. `committerTime` * equals `getFileLastModifiedDate` EXCEPT for the merge-only fallback below, * where THIS record resolves but the standalone date methods keep the raw * merge-skipping walk (`getFileLastModifiedDate` returns `null`, * `getFileLatestModifiedDate` throws). Only real errors throw (unborn/empty * HEAD, corrupt object, out-of-range timestamp). * * A path present at HEAD that ONLY merge commits ever touched (introduced or * last changed by an "evil merge", so the merge-skipping walk above finds * nothing) FALLS BACK to a record whose flat fields are the LATEST merge that * genuinely changed the path, while `created` is the OLDEST (creating) merge * -- so `commitId === created.commitId` ONLY when a single merge both added * and last-changed the file; a file added by one evil merge and later changed * by another has `commitId` = the later merge and `created.commitId` = the * earlier one. This fallback fires ONLY for a path still PRESENT (a blob) at * HEAD; `null` is returned for a path ABSENT at HEAD -- never added, OR * deleted (even by a merge). * * The result also carries `created`: the commit that FIRST added the file, * from a SEPARATE oldest-first ancestry walk resolving the EXACT * repo-root-relative path (merge commits are included in this walk, a * delete-then-re-add returns the ORIGINAL add, and there is NO * rename-follow). `created` is a FILE's creation: it is left undefined when * `filepath` is a glob, or when the path is a DIRECTORY (a tree entry) or a * submodule (a gitlink) AT HEAD -- even if a FILE of that name existed earlier * in history -- while the flat fields may still resolve via pathspec. A path * that is a file at HEAD, AND a file deleted by an ordinary (non-merge) commit * (absent at HEAD but still yielding a record, present earlier in history), * both still report their ORIGINAL creation commit. */ getFileLatestModified(filepath: string): FileModification | null /** * Asynchronous variant of `getFileLatestModified`, computed off the main * thread. Resolves to `null` under the same condition as the sync method (no * non-merge modification AND absent at HEAD). */ getFileLatestModifiedAsync(filepath: string, signal?: AbortSignal | undefined | null): Promise /** * Resolve the last commit that modified each of `filepaths` in a single * history walk (early-exits once every path is resolved). * * Unlike the single-file methods, each input is matched by EXACT * repo-root-relative path string, NOT libgit2 pathspec/glob semantics (there * is no glob expansion). A directory (tree) or submodule (gitlink) path is * not a file, and if such a path nonetheless resolves to a present record its * `created` is `undefined` (see below). Every input path is present as a key * in the result; a path maps to `null` under the same condition as * `getFileLatestModified` -- no non-merge commit ever recorded a change to it * AND it is absent at HEAD (never added, OR only merge commits touched it and * it is absent at HEAD, e.g. deleted by a merge; see below). Merge commits are * skipped when finding the last modification; only real errors throw. * * A path present at HEAD that ONLY merge commits ever touched (an "evil * merge", which the merge-skipping walk above misses) FALLS BACK to a record * whose flat fields are the LATEST merge that genuinely changed the path, * while `created` is the OLDEST (creating) merge -- so `commitId === * created.commitId` ONLY when a single merge both added and last-changed the * file (a file added by one evil merge and later changed by another has * `commitId` = the later merge and `created.commitId` = the earlier one). * This fallback fires ONLY for a path still PRESENT (a blob) at HEAD; a key is * `null` for a path ABSENT at HEAD -- never added, OR deleted (even by a * merge). * * Each present record also carries `created`: the commit that FIRST added * that path, from a SEPARATE oldest-first ancestry walk over the same EXACT * path (merge commits are included in this walk, a delete-then-re-add returns * the ORIGINAL add, and there is NO rename-follow). A present record's * `created` is `undefined` when the exact path is a directory (tree) or * submodule (gitlink) at HEAD; a path deleted by an ordinary (non-merge) * commit (absent at HEAD but still yielding a record) still resolves its * original creation. */ getFilesLatestModified(filepaths: Array): Record /** * Asynchronous variant of `getFilesLatestModified`, computed off the main * thread. Every input path is a key; a path maps to `null` under the same * condition as the sync `getFilesLatestModified` (no non-merge modification * AND absent at HEAD). */ getFilesLatestModifiedAsync(filepaths: Array, signal?: AbortSignal | undefined | null): Promise> /** * List the working-tree and index status of files in the repository. * * Mirrors `git status`. By default untracked files are included and ignored * files are not; pass `options` to tune the scan. Each returned `FileStatus` * decodes the `git2::Status` flags into booleans plus the raw `bits`. */ statuses(options?: StatusOptions | undefined | null): Array /** * Get the status of a single file by its workdir-relative path. * * This is more efficient than scanning the whole tree when only one path is * of interest. Errors (e.g. an ambiguous path) surface as a napi error. */ statusFile(path: string): FileStatus /** Asynchronous variant of `statuses`, computed off the main thread. */ statusesAsync(options?: StatusOptions | undefined | null, signal?: AbortSignal | undefined | null): Promise> /** * Compute the blame for `path`: who last changed each line, as an ordered * list of hunks (contiguous runs of lines sharing one final commit). * * `path` is workdir-relative. Pass `options` to restrict the line/commit * range or enable copy tracking. Each `BlameHunk` is eagerly materialized * so it outlives the underlying libgit2 blame. */ blameFile(path: string, options?: BlameOptions | undefined | null): Array /** * Blame `path` and return only the hunk covering `line_no` (1-based), or * `null` when the line is out of range. */ blameLine(path: string, lineNo: number, options?: BlameOptions | undefined | null): BlameHunk | null /** Asynchronous variant of `blame_file`, computed off the main thread. */ blameFileAsync(path: string, options?: BlameOptions | undefined | null, signal?: AbortSignal | undefined | null): Promise> /** * Commit (committer) time in **milliseconds since the Unix epoch** of the * earliest commit whose tree contains `filepath`. Throws when no commit in * history contains the path. * * Walks all history from HEAD newest-first (`Sort::TIME | Sort::TOPOLOGICAL`) * and keeps the last-visited commit whose tree contains `filepath` (matched * by exact tree path, not pathspec) — i.e. the oldest containing commit; * merge commits are included in this walk. Rename detection is NOT performed * (no `git log --follow`), so history is not traced across renames. Also * throws on real errors (unborn/empty HEAD, corrupt object, out-of-range * timestamp). */ getFileCreatedDate(filepath: string): number /** * Asynchronous variant of `getFileCreatedDate`, computed off the main thread. * Rejects when no commit in history contains `filepath`. */ getFileCreatedDateAsync(filepath: string, signal?: AbortSignal | undefined | null): Promise } /** * This type extends JavaScript's `Iterator`, and so has the iterator helper * methods. It may extend the upcoming TypeScript `Iterator` class in the future. * * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Iterator#iterator_helper_methods * @see https://www.typescriptlang.org/docs/handbook/release-notes/typescript-5-6.html#iterator-helper-methods */ export declare class RevWalk { /** * Reset a revwalk to allow re-configuring it. * * The revwalk is automatically reset when iteration of its commits * completes. */ reset(): this /** * Set the sorting mode for a revwalk. * * `sorting` is a raw bitset of `Sort` flags OR-ed together (e.g. * `Sort.Time | Sort.Reverse`). Unknown bits are ignored. */ setSorting(sorting: number): this /** * Simplify the history by first-parent * * No parents other than the first for each commit will be enqueued. */ simplifyFirstParent(): this /** * Mark a commit to start traversal from. * * The given OID must belong to a commitish on the walked repository. * * The given commit will be used as one of the roots when starting the * revision walk. At least one commit must be pushed onto the walker before * a walk can be started. */ push(oid: string): this /** * Push the repository's HEAD * * For more information, see `push`. */ pushHead(): this /** * Push matching references * * The OIDs pointed to by the references that match the given glob pattern * will be pushed to the revision walker. * * A leading 'refs/' is implied if not present as well as a trailing `/ \ * *` if the glob lacks '?', ' \ *' or '['. * * Any references matching this glob which do not point to a commitish * will be ignored. */ pushGlob(glob: string): this /** * Push and hide the respective endpoints of the given range. * * The range should be of the form `..` where each * `` is in the form accepted by `revparse_single`. The left-hand * commit will be hidden and the right-hand commit pushed. */ pushRange(range: string): this /** * Push the OID pointed to by a reference * * The reference must point to a commitish. */ pushRef(reference: string): this /** Mark a commit as not of interest to this revwalk. */ hide(oid: string): this /** * Hide the repository's HEAD * * For more information, see `hide`. */ hideHead(): this /** * Hide matching references. * * The OIDs pointed to by the references that match the given glob pattern * and their ancestors will be hidden from the output on the revision walk. * * A leading 'refs/' is implied if not present as well as a trailing `/ \ * *` if the glob lacks '?', ' \ *' or '['. * * Any references matching this glob which do not point to a commitish * will be ignored. */ hideGlob(glob: string): this /** * Hide the OID pointed to by a reference. * * The reference must point to a commitish. */ hideRef(reference: string): this [globalThis.Symbol.iterator](): this next(...[value]: [] | [void]): globalThis.IteratorResult return(...[value]: [] | [void]): globalThis.IteratorResult throw(exception?: unknown): globalThis.IteratorResult } export interface RevWalk extends globalThis.Omit, 'next' | 'return' | 'throw'> {} /** * A Signature is used to indicate authorship of various actions throughout the * library. * * Signatures contain a name, email, and timestamp. All fields can be specified * with `new` while the `now` constructor omits the timestamp. The * [`Repository::signature`] method can be used to create a default signature * with name and email values read from the configuration. * * [`Repository::signature`]: struct.Repository.html#method.signature */ export declare class Signature { /** * Create a new action signature with a timestamp of 'now'. * * See `new` for more information */ static now(name: string, email: string): Signature /** * Create a new action signature. * * The `time` is a JS `Date`; it is recorded at whole-second resolution with a * zero time-zone offset (UTC). * * Returns error if either `name` or `email` contain angle brackets. */ constructor(name: string, email: string, time: Date) /** * Gets the name on the signature. * * Returns `None` if the name is not valid utf-8 */ name(): string | null /** * Gets the email on the signature. * * Returns `None` if the email is not valid utf-8 */ email(): string | null /** Return the time the signature was recorded, as a `Date`. */ when(): Date } export declare class Tag { /** * Determine whether a tag name is valid, meaning that (when prefixed with refs/tags/) that * it is a valid reference name, and that any additional tag name restrictions are imposed * (eg, it cannot start with a -). */ static isValidName(name: string): boolean /** Get the id (SHA1) of a repository object */ id(): string /** * Get the message of a tag * * Returns None if there is no message or if it is not valid utf8 */ message(): string | null /** * Get the message of a tag * * Returns None if there is no message */ messageBytes(): Buffer | null /** * Get the name of a tag * * Returns None if it is not valid utf8 */ name(): string | null /** Get the name of a tag */ nameBytes(): Buffer /** Recursively peel a tag until a non tag git_object is found */ peel(): GitObject } export declare class Tree { /** Get the id (SHA1) of a repository object */ id(): string /** Get the number of entries listed in a tree. */ size(): number /** Return `true` if there is not entry */ isEmpty(): boolean /** Returns an iterator over the entries in this tree. */ entries(): TreeIter /** Lookup a tree entry by SHA value */ getId(id: string): TreeEntry | null /** Lookup a tree entry by its position in the tree */ get(index: number): TreeEntry | null /** * Lookup a direct child entry of this tree by its name. * * `name` is a single path component (a filename), not a multi-component * path; this does not descend into subtrees. To follow a relative path * through nested subtrees, use `getPath`. */ getName(name: string): TreeEntry | null /** * Lookup a tree entry by a relative path, descending through subtrees. * * `name` is a path relative to this tree and may contain multiple * components (e.g. `src/lib.rs`); each component is resolved in turn, * walking into nested subtrees. To look up a direct child by its name, * use `getName`. */ getPath(name: string): TreeEntry | null } export declare class TreeBuilder { /** * Add or update an entry in the builder. * * `filename` must be a single path component (this is a single-level * builder, not a recursive path). `filemode` is a raw git file mode; * valid values are 0o040000 (16384, tree), 0o100644 (33188, blob), * 0o100755 (33261, executable blob), 0o120000 (40960, symlink) and * 0o160000 (57344, submodule commit). * * No attempt is made to ensure that the provided OID points to an object * of a reasonable type (or any object at all). */ insert(filename: string, oid: string, filemode: number): void /** Remove an entry from the builder by its filename. */ remove(filename: string): void /** * Get an entry from the builder from its filename. * * Returns `null` when no entry with that filename exists. */ get(filename: string): TreeBuilderEntry | null /** * Write the contents of the builder as a tree object into the * repository's object database and return its OID hex string. */ write(): string /** Clear all the entries in the builder. */ clear(): void /** Get the number of entries listed in the builder. */ len(): number /** Return `true` if there is no entry in the builder. */ isEmpty(): boolean } export declare class TreeEntry { /** Get the id of the object pointed by the entry */ id(): string /** Get the name of a tree entry */ name(): string /** Get the filename of a tree entry */ nameBytes(): Buffer /** Convert a tree entry to the object it points to. */ toObject(repo: Repository): GitObject } /** * This type extends JavaScript's `Iterator`, and so has the iterator helper * methods. It may extend the upcoming TypeScript `Iterator` class in the future. * * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Iterator#iterator_helper_methods * @see https://www.typescriptlang.org/docs/handbook/release-notes/typescript-5-6.html#iterator-helper-methods */ export declare class TreeIter { [globalThis.Symbol.iterator](): this next(...[value]: [] | [void]): globalThis.IteratorResult return(...[value]: [] | [void]): globalThis.IteratorResult throw(exception?: unknown): globalThis.IteratorResult } export interface TreeIter extends globalThis.Omit, 'next' | 'return' | 'throw'> {} /** Automatic tag following options. */ export declare const enum AutotagOption { /** Use the setting from the remote's configuration */ Unspecified = 0, /** Ask the server for tags pointing to objects we're already downloading */ Auto = 1, /** Don't ask for any tags beyond the refspecs */ None = 2, /** Ask for all the tags */ All = 3, } /** * A single blame hunk: a contiguous run of lines attributed to one commit. * * All identity fields are copied out of the borrowed `git2::BlameHunk` so the * value can safely outlive the underlying `git2::Blame`. */ export interface BlameHunk { /** Number of lines covered by this hunk. */ linesInHunk: number /** 40-char lowercase hex OID of the commit where these lines were last changed. */ finalCommitId: string /** Line number where this hunk begins in the final file (1-based). */ finalStartLine: number /** Author name of the final commit. Undefined if absent or not valid UTF-8. */ finalAuthorName?: string /** Author email of the final commit. Undefined if absent or not valid UTF-8. */ finalAuthorEmail?: string /** Author time of the final commit, as a `Date`. The Unix epoch if no signature. */ finalTime: Date /** 40-char lowercase hex OID of the commit where this hunk was found. */ origCommitId: string /** Line number where this hunk begins in the original file (1-based). */ origStartLine: number /** Path to the file where this hunk originated. Undefined if not valid UTF-8. */ origPath?: string /** Whether this hunk was tracked to a boundary commit (root or `oldest_commit`). */ isBoundary: boolean } /** * Options controlling how a blame is computed. * * Every field is optional; omitted fields fall back to libgit2's defaults * (no copy tracking, the whole file, starting from the current HEAD). */ export interface BlameOptions { /** * Track lines that have moved within a file. Defaults to `false`. * * Note: libgit2 1.9.4 does not implement blame copy/move tracking, so * setting this flag has no effect today (accepted for forward-compat; * effectively a no-op). */ trackCopiesSameFile?: boolean /** * Track lines that have moved across files in the same commit. Defaults to `false`. * * Note: libgit2 1.9.4 does not implement blame copy/move tracking, so * setting this flag has no effect today (accepted for forward-compat; * effectively a no-op). */ trackCopiesSameCommitMoves?: boolean /** 40-char hex OID of the newest commit to consider (the blame starts here). */ newestCommit?: string /** 40-char hex OID of the oldest commit to consider (a boundary). */ oldestCommit?: string /** Restrict the search to first-parent history only. Defaults to `false`. */ firstParent?: boolean /** Map names/emails through the repository's mailmap. Defaults to `false`. */ useMailmap?: boolean /** Ignore whitespace differences. Defaults to `false`. */ ignoreWhitespace?: boolean /** The first line in the file to blame (1-based). */ minLine?: number /** The last line in the file to blame (1-based). */ maxLine?: number } /** An enumeration for the possible types of branches. */ export declare const enum BranchType { /** A local branch not on a remote. */ Local = 0, /** A branch for a remote. */ Remote = 1, } /** * A single `@@`-delimited hunk of a buffer diff, with its header text and * eagerly materialized lines. */ export interface BufferDiffHunk { /** The hunk header text (e.g. `@@ -1,2 +1,3 @@`), as bytes decoded lossily. */ header: string oldStart: number oldLines: number newStart: number newLines: number lines: Array } /** * A single line inside a `BufferDiffHunk`. `oldLineno`/`newLineno` are `null` * when the line does not exist on that side (added lines have no `oldLineno`, * deleted lines have no `newLineno`). `content` is the raw line bytes * (including any trailing newline, but NOT the leading `+`/`-`/space sigil — * that sigil is `origin`). */ export interface BufferDiffLine { /** * One-character sigil classifying the line: `' '` context, `'+'` addition, * `'-'` deletion, `'='`/`'>'`/`'<'` end-of-file markers, `'F'` file header, * `'H'` hunk header, `'B'` binary marker. */ origin: string oldLineno: number | null newLineno: number | null content: Buffer } /** * The fully materialized result of `diffBuffers`. Everything is copied out * eagerly because `git2::Patch` borrows the input buffers and cannot escape. */ export interface BufferDiffResult { /** * The complete unified-diff bytes of the patch (empty buffer when the two * sides are identical). Returned as raw bytes rather than a string so * non-UTF-8 content is preserved exactly. */ patch: Buffer hunks: Array stats: BufferDiffStats } /** * Line counts for a buffer diff. `filesChanged` is `1` when the patch is * non-empty and `0` otherwise (`Patch` is a single-delta structure). */ export interface BufferDiffStats { additions: number deletions: number filesChanged: number } /** * Options controlling how a checkout writes files into the working directory. * * The default is a **safe** checkout (matching `git checkout`): files with * local modifications are left untouched. Set `force` to overwrite them, which * can discard uncommitted changes — use it deliberately. */ export interface CheckoutOptions { /** * Force the checkout, overwriting any local changes in the working tree. * Defaults to a safe checkout when omitted or `false`. */ force?: boolean /** * Recreate files that are missing from the working tree even in a safe * checkout. */ recreateMissing?: boolean /** Allow the checkout to write files that conflict with the working tree. */ allowConflicts?: boolean /** * Restrict the checkout to these pathspecs. When omitted, all paths are * checked out. */ paths?: Array /** * Write the checked-out files into this directory instead of the * repository's working directory. */ targetDir?: string } export declare const enum CloneLocal { /** * Auto-detect (default) * * Here libgit2 will bypass the git-aware transport for local paths, but * use a normal fetch for `file://` URLs. */ Auto = 0, /** Bypass the git-aware transport even for `file://` URLs. */ Local = 1, /** Never bypass the git-aware transport */ None = 2, /** Bypass the git-aware transport, but don't try to use hardlinks. */ NoLinks = 3, } /** * A single commit's identity/time metadata, reused for the commit that CREATED * a file (`FileModification::created`). Same 8 fields as `FileModification`'s * commit metadata. All times are `Date`s (UTC; timezone offset ignored). */ export interface CommitInfo { /** 40-char lowercase hex OID of the commit that first added the file. */ commitId: string /** Commit summary (first line). Undefined if absent or not valid UTF-8. */ summary?: string /** Author name. Undefined if not valid UTF-8. */ authorName?: string /** Author email. Undefined if not valid UTF-8. */ authorEmail?: string /** Author time, as a `Date`. */ authorTime: Date /** Committer name. Undefined if not valid UTF-8. */ committerName?: string /** Committer email. Undefined if not valid UTF-8. */ committerEmail?: string /** Committer time, as a `Date`. */ committerTime: Date } /** * A single configuration entry: its fully-qualified name, value, and the * level (file) it was read from. */ export interface ConfigEntry { name: string value: string level: ConfigLevel } /** * The priority level a configuration entry or file applies to. Higher levels * take precedence; `Local` (the repository's own `.git/config`) is where * `set_*`/`remove_entry` write by default. */ export declare const enum ConfigLevel { /** System-wide on Windows, for compatibility with portable git */ ProgramData = 0, /** System-wide configuration file, e.g. /etc/gitconfig */ System = 1, /** XDG-compatible configuration file, e.g. ~/.config/git/config */ Xdg = 2, /** User-specific configuration, e.g. ~/.gitconfig */ Global = 3, /** Repository specific config, e.g. $PWD/.git/config */ Local = 4, /** Worktree specific configuration file, e.g. $GIT_DIR/config.worktree */ Worktree = 5, /** Application specific configuration file */ App = 6, /** Highest level available */ Highest = 7, } /** Types of credentials that can be requested by a credential callback. */ export declare const enum CredentialType { /** 1 << 0 */ UserPassPlaintext = 1, /** 1 << 1 */ SshKey = 2, /** 1 << 6 */ SshMemory = 64, /** 1 << 2 */ SshCustom = 4, /** 1 << 3 */ Default = 8, /** 1 << 4 */ SshInteractive = 16, /** 1 << 5 */ Username = 32, } export interface CredInfo { /** * Raw `CredentialType` bitset of the credential types the server will * accept. OR-able; test bits with `credTypeContains`. */ credType: number url: string username: string } /** * Check whether a raw credential-type bitset contains a given `CredentialType` * bit. * * `cred_type` is the raw value (e.g. `CredInfo.credType` or `Cred.credType()`); * `flag` is one of the `CredentialType` constants. Returns * `(cred_type & flag) === flag`. */ export declare function credTypeContains(credType: number, flag: CredentialType): boolean export declare const enum Delta { /** No changes */ Unmodified = 0, /** Entry does not exist in old version */ Added = 1, /** Entry does not exist in new version */ Deleted = 2, /** Entry content changed between old and new */ Modified = 3, /** Entry was renamed between old and new */ Renamed = 4, /** Entry was copied from another old entry */ Copied = 5, /** Entry is ignored item in workdir */ Ignored = 6, /** Entry is untracked item in workdir */ Untracked = 7, /** Type of entry changed between old and new */ Typechange = 8, /** Entry is unreadable */ Unreadable = 9, /** Entry in the index is conflicted */ Conflicted = 10, } /** * Diff two raw in-memory buffers without a repository, like * `git diff --no-index`. * * Pass `null` for a buffer to treat that side as absent (the delta is then * reported as an added or deleted file with a `/dev/null` header); passing * `null` for both yields an empty patch with zero hunks. An absent side is * distinct from an empty buffer: `diffBuffers(null, p, Buffer.alloc(0), p)` * reports a file creation. `oldPath`/`newPath` only label the output headers. */ export declare function diffBuffers(oldBuffer: Uint8Array | null, oldPath: string | null, newBuffer: Uint8Array | null, newPath: string | null, options?: DiffOptions | null): BufferDiffResult export declare const enum DiffFlags { /** * File(s) treated as binary data. * 1 << 0 */ Binary = 1, /** * File(s) treated as text data. * 1 << 1 */ NotBinary = 2, /** * `id` value is known correct. * 1 << 2 */ ValidId = 4, /** * File exists at this side of the delta. * 1 << 3 */ Exists = 8, } /** * Check whether a raw diff-flags bitset contains a given `DiffFlags` bit. * * `flags` is the raw value returned by `DiffDelta.flags()`; `flag` is one of * the `DiffFlags` constants. Returns `(flags & flag) === flag`. */ export declare function diffFlagsContains(flags: number, flag: DiffFlags): boolean export interface DiffOptions { /** * Include unmodified files in the diff. Normally unmodified entries are * skipped entirely; when this is `true` they are pulled into the diff (so * they appear in `Diff.deltas()` with an `Unmodified` status) and are also * shown in the listing output formats (name-only, name-status, raw). They * are still never emitted in the patch format. */ showUnmodified?: boolean } /** An enumeration of the possible directions for a remote. */ export declare const enum Direction { /** Data will be fetched (read) from this remote. */ Fetch = 0, /** Data will be pushed (written) to this remote. */ Push = 1, } /** Configuration for how pruning is done on a fetch */ export declare const enum FetchPrune { /** Use the setting from the configuration */ Unspecified = 0, /** Force pruning on */ On = 1, /** Force pruning off */ Off = 2, } /** Valid modes for index and tree entries. */ export declare const enum FileMode { /** Unreadable */ Unreadable = 0, /** Tree */ Tree = 1, /** Blob */ Blob = 2, /** Group writable blob. Obsolete mode kept for compatibility reasons */ BlobGroupWritable = 3, /** Blob executable */ BlobExecutable = 4, /** Link */ Link = 5, /** Commit */ Commit = 6, } /** * Last commit that modified a file, with author/committer identity. * All times are `Date`s (UTC; timezone offset ignored). */ export interface FileModification { /** 40-char lowercase hex OID of the last commit that modified the file. */ commitId: string /** Commit summary (first line). Undefined if absent or not valid UTF-8. */ summary?: string /** Author name. Undefined if not valid UTF-8. */ authorName?: string /** Author email. Undefined if not valid UTF-8. */ authorEmail?: string /** Author time, as a `Date`. */ authorTime: Date /** Committer name. Undefined if not valid UTF-8. */ committerName?: string /** Committer email. Undefined if not valid UTF-8. */ committerEmail?: string /** * Committer time, as a `Date`. Equal to `getFileLastModifiedDate` EXCEPT for a * file present only via merge commits: this record falls back to the LATEST * merge that changed the file (see `created`), whereas the standalone * `getFileLastModifiedDate` keeps the raw merge-skipping walk and returns * `null` for it (and `getFileLatestModifiedDate` throws). */ committerTime: Date /** * The commit that FIRST added this file (its creation), resolved by an * oldest-first ancestry walk over the EXACT repo-root-relative path -- SEPARATE * from the newest-first modification walk above. `created` is a FILE's * creation, so whether it resolves is decided by the queried path's ENTRY KIND * AT HEAD: Undefined when a glob was passed, or when the path is a DIRECTORY (a * tree entry) or a submodule (a gitlink/Commit entry) AT HEAD -- even if a FILE * of that name existed earlier in history -- since no such entry is a file (the * flat fields may still resolve via pathspec in those cases). A path that is a * blob at HEAD, AND a file deleted by an ordinary (non-merge) commit (absent * at HEAD but still yielding a record, a blob earlier in history), BOTH still * report their ORIGINAL creation. (A path that no commit * in history ever added yields no record at all -- the whole `FileModification` * is `null`/absent -- not a present record with this field missing. A path * present at HEAD that ONLY merge commits ever touched, on the other hand, * yields a record whose flat fields are the LATEST merge that changed the path * while `created` is the OLDEST (creating) merge -- so `commit_id == * created.commit_id` only when a single merge both added and last-changed the * file; this merge-only fallback fires ONLY for a path still PRESENT at HEAD, * so a merge-only path ABSENT at HEAD -- e.g. deleted by a merge -- yields no * record at all.) A delete-then-re-add returns the ORIGINAL add; merge * commits are included; no rename-follow. */ created?: CommitInfo } /** * Status of a single file in the working tree and/or index. * * The boolean flags mirror the `git2::Status` bits; `bits` carries the raw * value as a forward-compatible escape hatch for flags not surfaced here. */ export interface FileStatus { /** Workdir-relative path. Undefined if the path is not valid UTF-8. */ path?: string /** Raw `git2::Status` bits — forward-compat escape hatch. */ bits: number /** Staged: a new file was added to the index. */ isIndexNew: boolean /** Staged: a tracked file was modified in the index. */ isIndexModified: boolean /** Staged: a tracked file was deleted from the index. */ isIndexDeleted: boolean /** Staged: a tracked file was renamed in the index. */ isIndexRenamed: boolean /** Staged: a tracked file changed type in the index. */ isIndexTypechange: boolean /** Unstaged: an untracked file (new in the working directory). */ isWtNew: boolean /** Unstaged: a tracked file was modified in the working directory. */ isWtModified: boolean /** Unstaged: a tracked file was deleted from the working directory. */ isWtDeleted: boolean /** Unstaged: a tracked file changed type in the working directory. */ isWtTypechange: boolean /** Unstaged: a tracked file was renamed in the working directory. */ isWtRenamed: boolean /** The file is ignored. */ isIgnored: boolean /** The file has merge conflicts. */ isConflicted: boolean } /** * Stable string tokens surfaced to JS as `error.code`. The first 28 variants * mirror `git2::ErrorCode` (verbatim names); `InvalidArg` is the napi-level * token. `GenericError` doubles as the catch-all. `GitErrorCode: Copy` ⇒ it is * `Send + Sync`, which is required so it can ride along as an async carrier * field on `napi::Error`. */ export declare const enum GitErrorCode { GenericError = 'GenericError', NotFound = 'NotFound', Exists = 'Exists', Ambiguous = 'Ambiguous', BufSize = 'BufSize', User = 'User', BareRepo = 'BareRepo', UnbornBranch = 'UnbornBranch', Unmerged = 'Unmerged', NotFastForward = 'NotFastForward', InvalidSpec = 'InvalidSpec', Conflict = 'Conflict', Locked = 'Locked', Modified = 'Modified', Auth = 'Auth', Certificate = 'Certificate', Applied = 'Applied', Peel = 'Peel', Eof = 'Eof', Invalid = 'Invalid', Uncommitted = 'Uncommitted', Directory = 'Directory', MergeConflict = 'MergeConflict', HashsumMismatch = 'HashsumMismatch', IndexDirty = 'IndexDirty', ApplyFail = 'ApplyFail', Owner = 'Owner', Timeout = 'Timeout', InvalidArg = 'InvalidArg', } /** * Runtime type guard for the coded errors this addon throws. * * Returns `true` iff `e` is a genuine `Error` object — tested with the * Node-API native-error check (`napi_is_error`, a pure V8 `IsNativeError` * test) — whose `code` is a real member of the `GitErrorCode` enum. The * native check recognizes cross-realm and subclassed errors while rejecting * look-alike proxies and plain objects. Membership is validated against that * generated enum (the single source of truth), so a non-git `Error` (e.g. * Node's `ENOENT`) or an `AbortSignal` cancellation (`code: 'Cancelled'`, * which is a napi-level token, NOT a `GitErrorCode`) returns `false`. * Non-errors, plain objects, `null`/`undefined`, and `Error`s without a * member `code` all return `false`. * * The guard is TOTAL: it never throws for any input. Because the `Error` * check is the native `napi_is_error` (which runs NO JS callbacks), a hostile * value cannot hijack it — a throwing `[[GetPrototypeOf]]`/proxy trap or a * throwing `Error[Symbol.hasInstance]` yields `false`, not a thrown error. An * `Error` whose `code` is a throwing getter likewise yields `false` (the * pending exception is cleared), so it is always safe to call inside a * `catch`. */ export declare function isGitError(e: unknown): e is Error & { code: GitErrorCode } export declare const enum ObjectType { /** Any kind of git object */ Any = 0, /** An object which corresponds to a git commit */ Commit = 1, /** An object which corresponds to a git tree */ Tree = 2, /** An object which corresponds to a git blob */ Blob = 3, /** An object which corresponds to a git tag */ Tag = 4, } export interface Progress { totalObjects: number indexedObjects: number receivedObjects: number localObjects: number totalDeltas: number indexedDeltas: number receivedBytes: number } export interface PushTransferProgress { current: number total: number bytes: number } /** A single reference update reported during a push. */ export interface PushUpdateReference { /** * The full name of the reference that was updated (e.g. * `refs/heads/main`). */ refname: string /** * `null` when the reference was updated successfully; otherwise the * server's rejection reason. */ status: string | null } /** An enumeration of all possible kinds of references. */ export declare const enum ReferenceType { /** A reference which points at an object id. */ Direct = 0, /** A reference which points at another reference. */ Symbolic = 1, Unknown = 2, } /** * Remote redirection settings; whether redirects to another host are * permitted. * * By default, git will follow a redirect on the initial request * (`/info/refs`), but not subsequent requests. */ export declare const enum RemoteRedirect { /** Do not follow any off-site redirects at any stage of the fetch or push. */ None = 0, /** * Allow off-site redirects only upon the initial request. This is the * default. */ Initial = 1, /** Allow redirects at any stage in the fetch or push. */ All = 2, } /** * OR-able flags for `Remote.updateTips`. Each discriminant is the real libgit2 * `GIT_REMOTE_UPDATE_*` bit, so they can be combined with `|`. */ export declare const enum RemoteUpdateFlags { UpdateFetchHead = 1, ReportUnchanged = 2, } /** * OR-able flags for `Repository.openExt`. Each discriminant is the real * libgit2 `GIT_REPOSITORY_OPEN_*` bit, so they can be combined with `|`. */ export declare const enum RepositoryOpenFlags { /** * Only open the specified path; don't walk upward searching. * 1 << 0 */ NoSearch = 1, /** * Search across filesystem boundaries. * 1 << 1 */ CrossFS = 2, /** * Force opening as bare repository, and defer loading its config. * 1 << 2 */ Bare = 4, /** * Don't try appending `/.git` to the specified repository path. * 1 << 3 */ NoDotGit = 8, /** * Respect environment variables like `$GIT_DIR`. * 1 << 4 */ FromEnv = 16, } export declare const enum RepositoryState { Clean = 0, Merge = 1, Revert = 2, RevertSequence = 3, CherryPick = 4, CherryPickSequence = 5, Bisect = 6, Rebase = 7, RebaseInteractive = 8, RebaseMerge = 9, ApplyMailbox = 10, ApplyMailboxOrRebase = 11, } /** Orderings that may be specified for Revwalk iteration. */ export declare const enum Sort { /** * Sort the repository contents in no particular ordering. * * This sorting is arbitrary, implementation-specific, and subject to * change at any time. This is the default sorting for new walkers. */ None = 0, /** * Sort the repository contents in topological order (children before * parents). * * This sorting mode can be combined with time sorting. * 1 << 0 */ Topological = 1, /** * Sort the repository contents by commit time. * * This sorting mode can be combined with topological sorting. * 1 << 1 */ Time = 2, /** * Iterate through the repository contents in reverse order. * * This sorting mode can be combined with any others. * 1 << 2 */ Reverse = 4, } /** * Options controlling how a working-tree status scan is performed. * * Every field is optional; omitted fields fall back to the git CLI defaults * (`include_untracked` is `true`, everything else `false`). */ export interface StatusOptions { /** Include untracked files in the status. Defaults to `true`. */ includeUntracked?: boolean /** Include ignored files in the status. Defaults to `false`. */ includeIgnored?: boolean /** Include unmodified files in the status. Defaults to `false`. */ includeUnmodified?: boolean /** Skip submodules. Defaults to `false`. */ excludeSubmodules?: boolean /** * Recurse into untracked directories instead of reporting the directory * itself. Defaults to `false`. */ recurseUntrackedDirs?: boolean /** Detect renames between the HEAD tree and the index. Defaults to `false`. */ renamesHeadToIndex?: boolean /** Detect renames between the index and the working directory. Defaults to `false`. */ renamesIndexToWorkdir?: boolean /** Restrict the scan to the given pathspecs. */ pathspec?: Array } /** A single tag visited during `Repository.tagForeach`. */ export interface TagForeachItem { /** The tag's OID as a 40-char hex string. */ id: string /** * The tag's raw reference name (e.g. `refs/tags/v1.0.0`) as bytes, since it * is not guaranteed to be valid UTF-8. */ nameBytes: Buffer } /** A single entry in a `TreeBuilder`, as returned by `TreeBuilder.get()`. */ export interface TreeBuilderEntry { /** The OID of the object the entry points to, as a 40-char hex string. */ oid: string /** * The raw git file mode of the entry (e.g. 0o100644 = 33188 for a normal * blob, 0o040000 = 16384 for a tree). */ filemode: number }