# jg-git-commands

> Git commands for Node.js that never prompt or inherit Git environment variables, with time and output limits, typed reads, and remote URL parsing.

- **Version:** `0.5.0`
- **Runtimes:** Node.js
- **Install:** `npm install jg-git-commands`
- **On npm:** [jg-git-commands](https://www.npmjs.com/package/jg-git-commands)
- **Source:** [packages/jg-git-commands](https://github.com/jesusgraterol/jg-packages/tree/main/packages/jg-git-commands)
- **Recipes:** [jg-git-commands recipes](https://jg-packages.jesusgraterol.dev/packages/jg-git-commands/recipes/index.md)

## Usage

Read a repository with typed helpers. Each runs `git` without a shell and without prompting, puts `--end-of-options` before the values you pass, and throws a classified error when the command fails:

```ts
import {
  isWorkingTreeClean,
  readFileAtRevision,
  readRemoteRefs,
  resolveCommit,
} from 'jg-git-commands';

const head = await resolveCommit('/srv/app', 'HEAD'); // the commit's full object ID, or null
const manifest = await readFileAtRevision('/srv/app', 'HEAD', 'package.json', { maxBytes: 65_536 }); // null without the file
const isClean = await isWorkingTreeClean('/srv/app');
const remote = await readRemoteRefs('/srv/app', 'origin', ['refs/heads/main']); // Map { 'refs/heads/main' => '…' }
```

`readStatus` gives the commit HEAD points at, null before the first one, and each changed path with its two status letters and, for a rename or a copy, its original path, from `git status --porcelain=v2`. `getRemoteUrl` reads a remote's URL, and `fetchCommit` fetches one commit by its object ID, at depth 1 by default, without tags, hooks, or automatic maintenance.

Read paths, the index, and the config as typed values. The readers of paths run with `-z` and refuse a path that isn't valid UTF-8 with `GIT_OUTPUT_INVALID`, instead of returning a mangled one. `readIndexEntries` and `listUntrackedFiles` also refuse a listing Git warned about, such as one that left out a directory it couldn't open, instead of returning an incomplete list:

```ts
import {
  listUntrackedFiles,
  readChangedPaths,
  readConfigBoolean,
  readGitVersion,
  readIndexEntries,
  readTopLevel,
} from 'jg-git-commands';

const root = await readTopLevel('/srv/app/src'); // '/srv/app', null inside .git or a bare repository
const changed = await readChangedPaths('/srv/app', 'origin/main', { to: 'HEAD' }); // ['src/index.ts']
const entries = await readIndexEntries('/srv/app'); // [{ mode: '100644', stage: 0, path: 'README.md' }]
const untracked = await listUntrackedFiles('/srv/app', { paths: ['docs'] });
const hasSymlinks = await readConfigBoolean('/srv/app', 'core.symlinks', true);
const { major, minor } = await readGitVersion('/srv/app'); // also reads suffixes such as .windows.1
```

Run any other command with `runGit`, which resolves with the exit code, whatever it is, and the output, as bytes with `encoding: 'buffer'`. `assertGitSucceeded` throws the same classified errors as the typed helpers:

```ts
import { assertGitSucceeded, runGit } from 'jg-git-commands';

const result = await runGit(['log', '-1', '--format=%s'], { cwd: '/srv/app', timeoutSeconds: 10 });
assertGitSucceeded(result, 'log');
```

Tell how commits, worktrees and remotes relate, such as before a fast-forward, or to name a repository by its host's `owner/name`:

```ts
import {
  getRemoteUrl,
  isAncestor,
  parseRemoteRepository,
  readCommonDirectory,
  readRemoteDefaultBranch,
} from 'jg-git-commands';

const canFastForward = await isAncestor('/srv/app', 'origin/main', 'HEAD');
const gitDirectory = await readCommonDirectory('/srv/app-feature'); // '/srv/app/.git' from a worktree
const defaultBranch = await readRemoteDefaultBranch('/srv/app'); // 'main', or null when unknown
const repository = parseRemoteRepository(await getRemoteUrl('/srv/app')); // { owner, name }, or null
```

`calculateGitBlobObjectId(content, { algorithm })` gives the object ID `git hash-object` would, for SHA-1 or SHA-256 repositories, without running Git.

### What every command runs with

- `GIT_TERMINAL_PROMPT=0`, so it never waits at a terminal.
- An empty `GIT_ASKPASS` and `-c core.askPass=`, so no askpass program runs, whether `GIT_ASKPASS`, `core.askPass`, or `SSH_ASKPASS` names one.
- `-c credential.helper=`, unless `useCredentialHelpers` is set, which empties the helper list from every config, the repository's included.
- `GCM_INTERACTIVE=never`, so Git Credential Manager, a helper that opens its own sign-in window, fails instead of prompting when `useCredentialHelpers` lets it run. It overrides the `credential.interactive` config.
- `GIT_SSH_COMMAND=ssh -o BatchMode=yes -o ConnectTimeout=10`, which overrides `core.sshCommand`, so SSH never asks for a password or a passphrase either.
- None of the inherited `GIT_*` variables, such as `GIT_DIR`, `GIT_WORK_TREE`, or `GIT_CONFIG_PARAMETERS`, nor `SSH_ASKPASS`, in any case, since Windows reads `git_dir` as `GIT_DIR`. Pass the ones you need, such as `GIT_SSL_CAINFO`, in `env`, which ignores `GIT_ASKPASS`, `GIT_TERMINAL_PROMPT`, `GCM_INTERACTIVE`, and `SSH_ASKPASS`, in any case too, so nothing passed there turns a prompt back on.
- No file system monitor, no pager, no colors, and no recursing into submodules, whatever the config says, and `GIT_OPTIONAL_LOCKS=0`, `GIT_NO_REPLACE_OBJECTS=1`, `GIT_NO_LAZY_FETCH=1`, and `GIT_LITERAL_PATHSPECS=1`.
- The C locale, `LC_ALL=C`, `LANG=C`, and `LANGUAGE=C`, so Git writes its messages in English and a failure can be classified.
- No transport, with an empty `GIT_ALLOW_PROTOCOL`, so no command reaches another repository unless you allow it. `readRemoteRefs` and `fetchCommit` allow HTTPS and SSH by default; pass `GIT_ALLOW_PROTOCOL` in `env` for others, such as `file` for a local remote.
- A 30-second timeout and a 1 MiB output limit, which reject with jg-process's `PROCESS_TIMED_OUT` and `PROCESS_OUTPUT_TOO_LARGE`, after stopping the command and everything it started.

### Partial clones never fetch while reading

In a partial clone, Git fetches a missing object from the remote the moment a command reads it, which turns a read into a network request to whatever the repository's config names. `GIT_NO_LAZY_FETCH=1` stops that, but only Git 2.45 and later, and the 2.39.4 to 2.44.1 security releases, honor it. The empty `GIT_ALLOW_PROTOCOL` stops it on every version, even when the repository's own config sets `protocol.file.allow=always`, so a read of a missing object fails instead. Git 2.32 or later is required.

### Credentials

Without credential helpers, a remote that asks for credentials fails at once. Authenticate with SSH keys that need no passphrase prompt, such as a deploy key or an agent, or pass the credentials yourself. A token in the URL shows up in the process listing, which other users on the machine can read. A header passed as config in `env` doesn't:

```ts
import { readRemoteRefs } from 'jg-git-commands';

declare const token: string;

const refs = await readRemoteRefs(
  '/srv/app',
  'https://github.com/acme/app.git',
  ['refs/heads/main'],
  {
    env: {
      GIT_CONFIG_COUNT: '1',
      GIT_CONFIG_KEY_0: 'http.extraHeader',
      GIT_CONFIG_VALUE_0: `Authorization: Bearer ${token}`,
    },
  },
);
```

With `useCredentialHelpers: true`, the configured helpers answer, still without an askpass program or a terminal. Git Credential Manager still answers with the credentials it has stored, but it never opens a sign-in window: where it would need one, the command fails instead.

### Trust boundary

jg-git-commands stops prompts and ignores inherited Git environment variables. It doesn't make Git safe for repositories or URLs you don't trust on its own:

- **Global and system config** apply unless you pass `isolateConfig: true`. They can attach a stored header to every request (`http.extraHeader`), rewrite URLs (`url.<base>.insteadOf`), route requests through a proxy (`http.proxy`), include other files (`include.path`), and allow other transports (`protocol.<name>.allow`). Code that handles repositories or URLs it doesn't trust passes `isolateConfig: true`.
- **Repository config** can still run programs, so jg-git-commands isn't a sandbox for a repository whose config you don't trust:
  - `readStatus` and `isWorkingTreeClean`: `git status` runs the `filter.<driver>.clean` programs that `.gitattributes` and the config name.
  - `readRemoteRefs` with a remote's name: Git runs the `remote.<name>.uploadpack` command over the file transport.
  - A `git://` URL: Git runs `core.gitProxy`.
  - Only `readFileAtRevision` and `resolveCommit` read objects without running anything from the config.

### Errors

| Code                       | When                                                                                                                                                        |
| -------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `GIT_NOT_FOUND`            | `git` isn't on the `PATH`                                                                                                                                   |
| `GIT_REPOSITORY_NOT_FOUND` | A typed helper's command, or one `assertGitSucceeded` checks, failed because the directory isn't in a repository                                            |
| `GIT_ACCESS_DENIED`        | It failed because Git refused the repository, for its ownership, `safe.directory`, or a file's permissions                                                  |
| `GIT_COMMAND_FAILED`       | It failed otherwise                                                                                                                                         |
| `GIT_INVALID_ARGUMENT`     | An argument isn't valid, such as a working directory that doesn't exist, one past Windows's path limit, a path outside the repository, or a short object ID |
| `GIT_OUTPUT_INVALID`       | Git's output isn't in the expected format, such as a path that isn't valid UTF-8                                                                            |

The failures' data holds the subcommand and the exit code, never stderr, which can show a URL with credentials in it. jg-process's `PROCESS_START_FAILED`, `PROCESS_TIMED_OUT`, `PROCESS_OUTPUT_TOO_LARGE`, and `PROCESS_TREE_SURVIVED` pass through, and an aborted `signal` rejects with its reason.

## <a id="api-reference"></a>jg-git-commands API reference

Every export of `jg-git-commands@0.5.0`, 39 in all, with its signature, its errors, and an example. It's generated from the package's TSDoc.

- Functions: [`assertGitSucceeded`](#api-assertGitSucceeded), [`calculateGitBlobObjectId`](#api-calculateGitBlobObjectId), [`createGitEnvironment`](#api-createGitEnvironment), [`fetchCommit`](#api-fetchCommit), [`getRemoteUrl`](#api-getRemoteUrl), [`isAncestor`](#api-isAncestor), [`isWorkingTreeClean`](#api-isWorkingTreeClean), [`listUntrackedFiles`](#api-listUntrackedFiles), [`parseRemoteRepository`](#api-parseRemoteRepository), [`readChangedPaths`](#api-readChangedPaths), [`readCommonDirectory`](#api-readCommonDirectory), [`readConfigBoolean`](#api-readConfigBoolean), [`readFileAtRevision`](#api-readFileAtRevision), [`readGitVersion`](#api-readGitVersion), [`readIndexEntries`](#api-readIndexEntries), [`readRemoteDefaultBranch`](#api-readRemoteDefaultBranch), [`readRemoteRefs`](#api-readRemoteRefs), [`readStatus`](#api-readStatus), [`readTopLevel`](#api-readTopLevel), [`resolveCommit`](#api-resolveCommit), [`runGit`](#api-runGit)
- Constants: [`DEFAULT_GIT_MAX_OUTPUT_BYTES`](#api-DEFAULT_GIT_MAX_OUTPUT_BYTES), [`DEFAULT_GIT_SSH_COMMAND`](#api-DEFAULT_GIT_SSH_COMMAND), [`DEFAULT_GIT_TIMEOUT_SECONDS`](#api-DEFAULT_GIT_TIMEOUT_SECONDS), [`ERRORS`](#api-ERRORS)
- Types: [`ICalculateGitBlobObjectIdOptions`](#api-ICalculateGitBlobObjectIdOptions), [`IFetchCommitOptions`](#api-IFetchCommitOptions), [`IGitCommandOptions`](#api-IGitCommandOptions), [`IGitEnvironmentOptions`](#api-IGitEnvironmentOptions), [`IGitObjectFormat`](#api-IGitObjectFormat), [`IGitStatus`](#api-IGitStatus), [`IGitVersion`](#api-IGitVersion), [`IIndexEntry`](#api-IIndexEntry), [`IListPathsOptions`](#api-IListPathsOptions), [`IReadChangedPathsOptions`](#api-IReadChangedPathsOptions), [`IReadFileAtRevisionOptions`](#api-IReadFileAtRevisionOptions), [`IRemoteRepository`](#api-IRemoteRepository), [`IRunGitOptions`](#api-IRunGitOptions), [`IStatusEntry`](#api-IStatusEntry)

### <a id="api-functions"></a>Functions

#### <a id="api-assertGitSucceeded"></a>`assertGitSucceeded`

*Function*

Throws the error for a git command that exited with a code other than 0, classified from its stderr, which runGit has Git write in English: `GIT_REPOSITORY_NOT_FOUND` when the directory isn't in a repository, `GIT_ACCESS_DENIED` when Git refused the repository, for its ownership or a file's permissions, and `GIT_COMMAND_FAILED` otherwise. The error's data holds the subcommand and the exit code, never stderr, which can show a URL with credentials in it.

```ts
assertGitSucceeded(
  result: IProcessResult<string | Buffer<ArrayBufferLike>>,
  subcommand: string,
): void
```

**Parameters**

- `result` `IProcessResult<string | Buffer<ArrayBufferLike>>`: The command's result, from runGit.
- `subcommand` `string`: The git subcommand that ran, such as `rev-parse`.

**Throws**

- `GIT_REPOSITORY_NOT_FOUND`: The directory isn't in a Git repository.
- `GIT_ACCESS_DENIED`: Git can't access the repository.
- `GIT_COMMAND_FAILED`: The git command failed.

**Example**

```ts
import { assertGitSucceeded, runGit } from 'jg-git-commands';

const result = await runGit(['check-attr', '--stdin', '-z', 'text'], { cwd: '/srv/app', input: 'README.md\0' });
assertGitSucceeded(result, 'check-attr');
```

#### <a id="api-calculateGitBlobObjectId"></a>`calculateGitBlobObjectId`

*Function*

Calculates the object ID Git gives a file's content, as `git hash-object` does, without running Git: the hash of `blob <length>\0` followed by the bytes.

```ts
calculateGitBlobObjectId(
  content: string | Uint8Array<ArrayBufferLike>,
  options?: ICalculateGitBlobObjectIdOptions,
): string
```

**Parameters**

- `content` `string | Uint8Array<ArrayBufferLike>`: The file's bytes, or its text, encoded as UTF-8.
- `options?` `ICalculateGitBlobObjectIdOptions`: The repository's object format. Defaults to `{}`.

**Returns** `string`: The object ID, in lowercase hexadecimal.

**Throws**

- `GIT_INVALID_ARGUMENT`: An argument isn't valid.

**Example**

```ts
import { calculateGitBlobObjectId } from 'jg-git-commands';

calculateGitBlobObjectId('hello\n'); // 'ce013625030ba8dba906f756967f9e9ca394464a'
```

#### <a id="api-createGitEnvironment"></a>`createGitEnvironment`

*Function*

Builds the environment a git command runs in: the base environment without the variables that change what Git does, every `GIT_*` one, such as `GIT_DIR` or `GIT_CONFIG_PARAMETERS`, and `SSH_ASKPASS` with `SSH_ASKPASS_REQUIRE`, then the variables that keep it from prompting: `GIT_TERMINAL_PROMPT=0`, an empty `GIT_ASKPASS`, which ends Git's askpass lookup before `core.askPass` and `SSH_ASKPASS`, `GCM_INTERACTIVE=never`, so Git Credential Manager fails rather than open a sign-in window, and an SSH command in batch mode. It also allows no transport, with an empty `GIT_ALLOW_PROTOCOL`, so reading a partial clone never fetches a missing object, and sets the C locale, so Git's messages are in English. Names are compared without case, as Windows does, so a `git_dir` or `Lc_All` from the base environment can't stand in for the variables it removes or sets. With `isolateConfig`, Git also ignores the system config, the user's global config, and the system attributes file, which otherwise still apply.

```ts
createGitEnvironment(options?: IGitEnvironmentOptions): ProcessEnv
```

**Parameters**

- `options?` `IGitEnvironmentOptions`: Whether to isolate the config, the SSH command, and the base environment. Defaults to `{}`.

**Returns** `ProcessEnv`: The environment.

**Example**

```ts
import { createGitEnvironment } from 'jg-git-commands';

const env = createGitEnvironment({
  isolateConfig: true,
  baseEnv: { PATH: '/usr/bin', GIT_DIR: '/srv/other/.git' },
});
env['GIT_DIR']; // undefined
env['GIT_CONFIG_NOSYSTEM']; // '1'
env['GIT_ALLOW_PROTOCOL']; // ''
```

#### <a id="api-fetchCommit"></a>`fetchCommit`

*Function*

Fetches a commit by its object ID from a URL into a repository, with only the history `depth` asks for, and without tags, submodules, hooks, automatic maintenance, or writing `FETCH_HEAD`. Read it afterwards by its object ID, such as with readFileAtRevision. The remote must allow fetching a commit by its object ID, as GitHub does. It allows the HTTPS and SSH transports; set `GIT_ALLOW_PROTOCOL` in `env` for another.

```ts
fetchCommit(
  cwd: string,
  url: string,
  objectId: string,
  options?: IFetchCommitOptions,
): Promise<void>
```

**Parameters**

- `cwd` `string`: The repository's directory, such as a bare one made for the fetch.
- `url` `string`: The remote's URL.
- `objectId` `string`: The commit's full object ID.
- `options?` `IFetchCommitOptions`: The history's depth, and runGit's options. Defaults to `{}`.

**Returns** `Promise<void>`: A promise that resolves once the commit is fetched.

**Throws**

- `GIT_INVALID_ARGUMENT`: An argument isn't valid.
- `GIT_REPOSITORY_NOT_FOUND`: The directory isn't in a Git repository.
- `GIT_ACCESS_DENIED`: Git can't access the repository.
- `GIT_COMMAND_FAILED`: The git command failed.
- `GIT_NOT_FOUND`: Git isn't installed, or isn't on the PATH.
- `PROCESS_START_FAILED`: Unable to start the command
- `PROCESS_TIMED_OUT`: The process didn't finish within the timeout
- `PROCESS_OUTPUT_TOO_LARGE`: The process wrote more output than allowed
- `PROCESS_TREE_SURVIVED`: The process tree is still running after it was force-stopped
- The signal's reason when the signal aborts.

**Example**

```ts
import { fetchCommit } from 'jg-git-commands';

await fetchCommit('/srv/cache/app.git', 'https://github.com/jesusgraterol/jg-packages.git', 'a'.repeat(40));
```

#### <a id="api-getRemoteUrl"></a>`getRemoteUrl`

*Function*

Reads a remote's URL, with the config's `url.<base>.insteadOf` rewrites applied.

```ts
getRemoteUrl(
  cwd: string,
  name?: string,
  options?: IGitCommandOptions,
): Promise<string>
```

**Parameters**

- `cwd` `string`: The repository's directory.
- `name?` `string`: The remote's name. Defaults to `origin`. Defaults to `'origin'`.
- `options?` `IGitCommandOptions`: runGit's options, such as the timeout. Defaults to `{}`.

**Returns** `Promise<string>`: A promise that resolves to the URL.

**Throws**

- `GIT_INVALID_ARGUMENT`: An argument isn't valid.
- `GIT_REPOSITORY_NOT_FOUND`: The directory isn't in a Git repository.
- `GIT_ACCESS_DENIED`: Git can't access the repository.
- `GIT_COMMAND_FAILED`: The git command failed.
- `GIT_OUTPUT_INVALID`: Git's output isn't in the expected format.
- `GIT_NOT_FOUND`: Git isn't installed, or isn't on the PATH.
- `PROCESS_START_FAILED`: Unable to start the command
- `PROCESS_TIMED_OUT`: The process didn't finish within the timeout
- `PROCESS_OUTPUT_TOO_LARGE`: The process wrote more output than allowed
- `PROCESS_TREE_SURVIVED`: The process tree is still running after it was force-stopped
- The signal's reason when the signal aborts.

**Example**

```ts
import { getRemoteUrl } from 'jg-git-commands';

const url = await getRemoteUrl('/srv/app');
```

#### <a id="api-isAncestor"></a>`isAncestor`

*Function*

Tells whether one commit is an ancestor of another, or the same commit, with `git merge-base --is-ancestor`, such as whether a branch can fast-forward to a commit.

```ts
isAncestor(
  cwd: string,
  ancestor: string,
  descendant: string,
  options?: IGitCommandOptions,
): Promise<boolean>
```

**Parameters**

- `cwd` `string`: The repository's directory.
- `ancestor` `string`: The revision that may be the ancestor.
- `descendant` `string`: The revision that may descend from it.
- `options?` `IGitCommandOptions`: runGit's options, such as the timeout. Defaults to `{}`.

**Returns** `Promise<boolean>`: A promise that resolves to whether it is.

**Throws**

- `GIT_INVALID_ARGUMENT`: An argument isn't valid.
- `GIT_REPOSITORY_NOT_FOUND`: The directory isn't in a Git repository.
- `GIT_ACCESS_DENIED`: Git can't access the repository.
- `GIT_COMMAND_FAILED`: The git command failed.
- `GIT_OUTPUT_INVALID`: Git's output isn't in the expected format.
- `GIT_NOT_FOUND`: Git isn't installed, or isn't on the PATH.
- `PROCESS_START_FAILED`: Unable to start the command
- `PROCESS_TIMED_OUT`: The process didn't finish within the timeout
- `PROCESS_OUTPUT_TOO_LARGE`: The process wrote more output than allowed
- `PROCESS_TREE_SURVIVED`: The process tree is still running after it was force-stopped
- The signal's reason when the signal aborts.

**Example**

```ts
import { isAncestor } from 'jg-git-commands';

const canFastForward = await isAncestor('/srv/app', 'origin/main', 'HEAD');
```

#### <a id="api-isWorkingTreeClean"></a>`isWorkingTreeClean`

*Function*

Checks whether the working tree has no changes, staged or not, and no untracked files that aren't ignored.

```ts
isWorkingTreeClean(cwd: string, options?: IGitCommandOptions): Promise<boolean>
```

**Parameters**

- `cwd` `string`: The repository's directory.
- `options?` `IGitCommandOptions`: runGit's options, such as the output limit. Defaults to `{}`.

**Returns** `Promise<boolean>`: A promise that resolves to whether it's clean.

**Throws**

- `GIT_INVALID_ARGUMENT`: An argument isn't valid.
- `GIT_REPOSITORY_NOT_FOUND`: The directory isn't in a Git repository.
- `GIT_ACCESS_DENIED`: Git can't access the repository.
- `GIT_COMMAND_FAILED`: The git command failed.
- `GIT_OUTPUT_INVALID`: Git's output isn't in the expected format.
- `GIT_NOT_FOUND`: Git isn't installed, or isn't on the PATH.
- `PROCESS_START_FAILED`: Unable to start the command
- `PROCESS_TIMED_OUT`: The process didn't finish within the timeout
- `PROCESS_OUTPUT_TOO_LARGE`: The process wrote more output than allowed
- `PROCESS_TREE_SURVIVED`: The process tree is still running after it was force-stopped
- The signal's reason when the signal aborts.

**Example**

```ts
import { isWorkingTreeClean } from 'jg-git-commands';

if (!(await isWorkingTreeClean('/srv/app'))) {
  // commit or stash the changes first
}
```

#### <a id="api-listUntrackedFiles"></a>`listUntrackedFiles`

*Function*

Lists the untracked files that aren't ignored, with `git ls-files --others --exclude-standard -z`, each file in an untracked directory included. A path that isn't valid UTF-8 fails the read, and so does a warning from Git, such as for a directory it couldn't open, which it otherwise leaves out of the list while still succeeding.

```ts
listUntrackedFiles(cwd: string, options?: IListPathsOptions): Promise<string[]>
```

**Parameters**

- `cwd` `string`: The repository's directory.
- `options?` `IListPathsOptions`: The paths to limit the list to, read literally, and runGit's options. Defaults to `{}`.

**Returns** `Promise<string[]>`: A promise that resolves to the paths from the repository's root.

**Throws**

- `GIT_INVALID_ARGUMENT`: An argument isn't valid.
- `GIT_REPOSITORY_NOT_FOUND`: The directory isn't in a Git repository.
- `GIT_ACCESS_DENIED`: Git can't access the repository.
- `GIT_COMMAND_FAILED`: The git command failed.
- `GIT_OUTPUT_INVALID`: Git's output isn't in the expected format.
- `GIT_NOT_FOUND`: Git isn't installed, or isn't on the PATH.
- `PROCESS_START_FAILED`: Unable to start the command
- `PROCESS_TIMED_OUT`: The process didn't finish within the timeout
- `PROCESS_OUTPUT_TOO_LARGE`: The process wrote more output than allowed
- `PROCESS_TREE_SURVIVED`: The process tree is still running after it was force-stopped
- The signal's reason when the signal aborts.

**Example**

```ts
import { listUntrackedFiles } from 'jg-git-commands';

const untracked = await listUntrackedFiles('/srv/app', { paths: ['docs'] });
```

#### <a id="api-parseRemoteRepository"></a>`parseRemoteRepository`

*Function*

Reads a hosted repository's owner and name from its remote URL, such as the `jesusgraterol` and `jg-packages` of `git@github.com:jesusgraterol/jg-packages.git`, from the SCP-like SSH form, an `ssh://` URL or an HTTPS URL, with or without `.git`. It reaches no remote.

```ts
parseRemoteRepository(url: string): IRemoteRepository | null
```

**Parameters**

- `url` `string`: The remote's URL, such as `getRemoteUrl` reads.

**Returns** `IRemoteRepository | null`: The owner and name, or null for a URL of another form, such as a local path, a URL with nested groups, or one carrying credentials.

**Example**

```ts
import { parseRemoteRepository } from 'jg-git-commands';

parseRemoteRepository('git@github.com:jesusgraterol/jg-packages.git'); // { owner: 'jesusgraterol', name: 'jg-packages' }
parseRemoteRepository('https://github.com/jesusgraterol/jg-packages'); // { owner: 'jesusgraterol', name: 'jg-packages' }
parseRemoteRepository('../jg-packages'); // null
```

#### <a id="api-readChangedPaths"></a>`readChangedPaths`

*Function*

Lists the paths that changed between a revision and another, or the working tree, with `git diff --name-only -z`, without external diff programs, text conversion, rename detection, or submodules, so a rename lists both its paths. A path that isn't valid UTF-8 fails the read.

```ts
readChangedPaths(
  cwd: string,
  from: string,
  options?: IReadChangedPathsOptions,
): Promise<string[]>
```

**Parameters**

- `cwd` `string`: The repository's directory.
- `from` `string`: The revision the changes start at, such as a base commit.
- `options?` `IReadChangedPathsOptions`: The revision the changes end at, the working tree by default, and runGit's options. Defaults to `{}`.

**Returns** `Promise<string[]>`: A promise that resolves to the paths from the repository's root, in Git's order.

**Throws**

- `GIT_INVALID_ARGUMENT`: An argument isn't valid.
- `GIT_REPOSITORY_NOT_FOUND`: The directory isn't in a Git repository.
- `GIT_ACCESS_DENIED`: Git can't access the repository.
- `GIT_COMMAND_FAILED`: The git command failed.
- `GIT_OUTPUT_INVALID`: Git's output isn't in the expected format.
- `GIT_NOT_FOUND`: Git isn't installed, or isn't on the PATH.
- `PROCESS_START_FAILED`: Unable to start the command
- `PROCESS_TIMED_OUT`: The process didn't finish within the timeout
- `PROCESS_OUTPUT_TOO_LARGE`: The process wrote more output than allowed
- `PROCESS_TREE_SURVIVED`: The process tree is still running after it was force-stopped
- The signal's reason when the signal aborts.

**Example**

```ts
import { readChangedPaths } from 'jg-git-commands';

const changed = await readChangedPaths('/srv/app', 'origin/main', { to: 'HEAD' });
```

#### <a id="api-readCommonDirectory"></a>`readCommonDirectory`

*Function*

Reads the real path of the Git directory a repository shares with all its worktrees, the same from the main checkout and from any linked worktree, such as to tell whether two checkouts are one repository.

```ts
readCommonDirectory(cwd: string, options?: IGitCommandOptions): Promise<string>
```

**Parameters**

- `cwd` `string`: A checkout, one of its worktrees, or a directory inside one.
- `options?` `IGitCommandOptions`: runGit's options, such as the timeout. Defaults to `{}`.

**Returns** `Promise<string>`: A promise that resolves to the directory's real path.

**Throws**

- `GIT_INVALID_ARGUMENT`: An argument isn't valid.
- `GIT_REPOSITORY_NOT_FOUND`: The directory isn't in a Git repository.
- `GIT_ACCESS_DENIED`: Git can't access the repository.
- `GIT_COMMAND_FAILED`: The git command failed.
- `GIT_OUTPUT_INVALID`: Git's output isn't in the expected format.
- `GIT_NOT_FOUND`: Git isn't installed, or isn't on the PATH.
- `PROCESS_START_FAILED`: Unable to start the command
- `PROCESS_TIMED_OUT`: The process didn't finish within the timeout
- `PROCESS_OUTPUT_TOO_LARGE`: The process wrote more output than allowed
- `PROCESS_TREE_SURVIVED`: The process tree is still running after it was force-stopped
- The signal's reason when the signal aborts.

**Example**

```ts
import { readCommonDirectory } from 'jg-git-commands';

await readCommonDirectory('/srv/app-feature'); // '/srv/app/.git', for a worktree of /srv/app
```

#### <a id="api-readConfigBoolean"></a>`readConfigBoolean`

*Function*

Reads a boolean config value, such as `core.symlinks`, with `git config --type=bool`, so every form Git accepts, such as `yes` or `on`, reads as true. A key that isn't set reads as the default.

```ts
readConfigBoolean(
  cwd: string,
  key: string,
  defaultValue: boolean,
  options?: IGitCommandOptions,
): Promise<boolean>
```

**Parameters**

- `cwd` `string`: The repository's directory.
- `key` `string`: The key, such as `core.sparseCheckout`.
- `defaultValue` `boolean`: The value when the key isn't set.
- `options?` `IGitCommandOptions`: runGit's options, such as `isolateConfig`. Defaults to `{}`.

**Returns** `Promise<boolean>`: A promise that resolves to the value.

**Throws**

- `GIT_INVALID_ARGUMENT`: An argument isn't valid.
- `GIT_REPOSITORY_NOT_FOUND`: The directory isn't in a Git repository.
- `GIT_ACCESS_DENIED`: Git can't access the repository.
- `GIT_COMMAND_FAILED`: The git command failed, such as for a value that isn't a boolean.
- `GIT_OUTPUT_INVALID`: Git's output isn't in the expected format.
- `GIT_NOT_FOUND`: Git isn't installed, or isn't on the PATH.
- `PROCESS_START_FAILED`: Unable to start the command
- `PROCESS_TIMED_OUT`: The process didn't finish within the timeout
- `PROCESS_OUTPUT_TOO_LARGE`: The process wrote more output than allowed
- `PROCESS_TREE_SURVIVED`: The process tree is still running after it was force-stopped
- The signal's reason when the signal aborts.

**Example**

```ts
import { readConfigBoolean } from 'jg-git-commands';

const hasSymlinks = await readConfigBoolean('/srv/app', 'core.symlinks', true);
```

#### <a id="api-readFileAtRevision"></a>`readFileAtRevision`

*Function*

Reads a file as UTF-8 text at a revision, with `git cat-file blob <rev>:<path>`, without checking it out and without running anything from the repository's config.

```ts
readFileAtRevision(
  cwd: string,
  rev: string,
  path: string,
  options?: IReadFileAtRevisionOptions,
): Promise<string | null>
```

**Parameters**

- `cwd` `string`: The repository's directory.
- `rev` `string`: The revision, such as a commit's object ID.
- `path` `string`: The file's path from the repository's root, such as `package.json`.
- `options?` `IReadFileAtRevisionOptions`: The file's size limit, and runGit's options. Defaults to `{}`.

**Returns** `Promise<string | null>`: A promise that resolves to the file's text, or null when the revision has no file at the path.

**Throws**

- `GIT_INVALID_ARGUMENT`: An argument isn't valid.
- `GIT_REPOSITORY_NOT_FOUND`: The directory isn't in a Git repository.
- `GIT_ACCESS_DENIED`: Git can't access the repository.
- `GIT_COMMAND_FAILED`: The git command failed, such as for a revision that doesn't exist, or a path
- that names a directory.
- `GIT_NOT_FOUND`: Git isn't installed, or isn't on the PATH.
- `PROCESS_START_FAILED`: Unable to start the command
- `PROCESS_TIMED_OUT`: The process didn't finish within the timeout
- `PROCESS_OUTPUT_TOO_LARGE`: The process wrote more output than allowed
- `PROCESS_TREE_SURVIVED`: The process tree is still running after it was force-stopped
- The signal's reason when the signal aborts.

**Example**

```ts
import { readFileAtRevision } from 'jg-git-commands';

const manifest = await readFileAtRevision('/srv/app', 'HEAD', 'package.json', { maxBytes: 65_536 });
```

#### <a id="api-readGitVersion"></a>`readGitVersion`

*Function*

Reads the installed Git's version, with `git version`, whatever suffixes the build adds, such as Git for Windows' `2.45.1.windows.1`, Microsoft's `2.45.2.vfs.0.0`, a release candidate's `2.48.0.rc1`, or Apple's `2.39.5 (Apple Git-154)`.

```ts
readGitVersion(cwd: string, options?: IGitCommandOptions): Promise<IGitVersion>
```

**Parameters**

- `cwd` `string`: The directory git runs in.
- `options?` `IGitCommandOptions`: runGit's options, such as the timeout. Defaults to `{}`.

**Returns** `Promise<IGitVersion>`: A promise that resolves to the version.

**Throws**

- `GIT_INVALID_ARGUMENT`: An argument isn't valid.
- `GIT_REPOSITORY_NOT_FOUND`: The directory isn't in a Git repository.
- `GIT_ACCESS_DENIED`: Git can't access the repository.
- `GIT_COMMAND_FAILED`: The git command failed.
- `GIT_OUTPUT_INVALID`: Git's output isn't in the expected format.
- `GIT_NOT_FOUND`: Git isn't installed, or isn't on the PATH.
- `PROCESS_START_FAILED`: Unable to start the command
- `PROCESS_TIMED_OUT`: The process didn't finish within the timeout
- `PROCESS_OUTPUT_TOO_LARGE`: The process wrote more output than allowed
- `PROCESS_TREE_SURVIVED`: The process tree is still running after it was force-stopped
- The signal's reason when the signal aborts.

**Example**

```ts
import { readGitVersion } from 'jg-git-commands';

const { major, minor } = await readGitVersion('/srv/app');
if (major < 2 || (major === 2 && minor < 32)) {
  // ask for Git 2.32 or later
}
```

#### <a id="api-readIndexEntries"></a>`readIndexEntries`

*Function*

Lists the index's entries, with `git ls-files --cached --stage -z`: each tracked path's file mode and merge stage, 0 unless it's in a conflict, which lists a path once per stage. A path that isn't valid UTF-8, or a warning from Git, fails the read.

```ts
readIndexEntries(
  cwd: string,
  options?: IListPathsOptions,
): Promise<IIndexEntry[]>
```

**Parameters**

- `cwd` `string`: The repository's directory.
- `options?` `IListPathsOptions`: The paths to limit the list to, read literally, and runGit's options. Defaults to `{}`.

**Returns** `Promise<IIndexEntry[]>`: A promise that resolves to the entries, paths from the repository's root.

**Throws**

- `GIT_INVALID_ARGUMENT`: An argument isn't valid.
- `GIT_REPOSITORY_NOT_FOUND`: The directory isn't in a Git repository.
- `GIT_ACCESS_DENIED`: Git can't access the repository.
- `GIT_COMMAND_FAILED`: The git command failed.
- `GIT_OUTPUT_INVALID`: Git's output isn't in the expected format.
- `GIT_NOT_FOUND`: Git isn't installed, or isn't on the PATH.
- `PROCESS_START_FAILED`: Unable to start the command
- `PROCESS_TIMED_OUT`: The process didn't finish within the timeout
- `PROCESS_OUTPUT_TOO_LARGE`: The process wrote more output than allowed
- `PROCESS_TREE_SURVIVED`: The process tree is still running after it was force-stopped
- The signal's reason when the signal aborts.

**Example**

```ts
import { readIndexEntries } from 'jg-git-commands';

const links = (await readIndexEntries('/srv/app')).filter(({ mode }) => mode === '120000');
```

#### <a id="api-readRemoteDefaultBranch"></a>`readRemoteDefaultBranch`

*Function*

Reads the default branch a remote had when the repository was cloned, or when `git remote set-head` last set it, from the remote's HEAD ref, without reaching the remote.

```ts
readRemoteDefaultBranch(
  cwd: string,
  remote?: string,
  options?: IGitCommandOptions,
): Promise<string | null>
```

**Parameters**

- `cwd` `string`: The repository's directory.
- `remote?` `string`: The remote's name. Defaults to `origin`. Defaults to `'origin'`.
- `options?` `IGitCommandOptions`: runGit's options, such as the timeout. Defaults to `{}`.

**Returns** `Promise<string | null>`: A promise that resolves to the branch, such as `main`, or null when the repository doesn't know the remote's default branch.

**Throws**

- `GIT_INVALID_ARGUMENT`: An argument isn't valid.
- `GIT_REPOSITORY_NOT_FOUND`: The directory isn't in a Git repository.
- `GIT_ACCESS_DENIED`: Git can't access the repository.
- `GIT_COMMAND_FAILED`: The git command failed.
- `GIT_OUTPUT_INVALID`: Git's output isn't in the expected format.
- `GIT_NOT_FOUND`: Git isn't installed, or isn't on the PATH.
- `PROCESS_START_FAILED`: Unable to start the command
- `PROCESS_TIMED_OUT`: The process didn't finish within the timeout
- `PROCESS_OUTPUT_TOO_LARGE`: The process wrote more output than allowed
- `PROCESS_TREE_SURVIVED`: The process tree is still running after it was force-stopped
- The signal's reason when the signal aborts.

**Example**

```ts
import { readRemoteDefaultBranch } from 'jg-git-commands';

const branch = (await readRemoteDefaultBranch('/srv/app')) ?? 'main';
```

#### <a id="api-readRemoteRefs"></a>`readRemoteRefs`

*Function*

Reads the object ID of each ref asked for from a remote, a configured remote's name or a URL, with `git ls-remote --refs`. A ref the remote doesn't have is missing from the map. It allows the HTTPS and SSH transports; set `GIT_ALLOW_PROTOCOL` in `env` for another, such as `file`, over which Git runs the `remote.<name>.uploadpack` command a remote's config names.

```ts
readRemoteRefs(
  cwd: string,
  remote: string,
  refs: readonly string[],
  options?: IGitCommandOptions,
): Promise<Map<string, string>>
```

**Parameters**

- `cwd` `string`: The repository's directory.
- `remote` `string`: The remote's name, such as `origin`, or its URL.
- `refs` `readonly string[]`: The full ref names, such as `refs/heads/main`.
- `options?` `IGitCommandOptions`: runGit's options, such as `useCredentialHelpers` for an authenticated remote. Defaults to `{}`.

**Returns** `Promise<Map<string, string>>`: A promise that resolves to the object ID of each ref found.

**Throws**

- `GIT_INVALID_ARGUMENT`: An argument isn't valid.
- `GIT_REPOSITORY_NOT_FOUND`: The directory isn't in a Git repository.
- `GIT_ACCESS_DENIED`: Git can't access the repository.
- `GIT_COMMAND_FAILED`: The git command failed.
- `GIT_OUTPUT_INVALID`: Git's output isn't in the expected format.
- `GIT_NOT_FOUND`: Git isn't installed, or isn't on the PATH.
- `PROCESS_START_FAILED`: Unable to start the command
- `PROCESS_TIMED_OUT`: The process didn't finish within the timeout
- `PROCESS_OUTPUT_TOO_LARGE`: The process wrote more output than allowed
- `PROCESS_TREE_SURVIVED`: The process tree is still running after it was force-stopped
- The signal's reason when the signal aborts.

**Example**

```ts
import { readRemoteRefs } from 'jg-git-commands';

const refs = await readRemoteRefs('/srv/app', 'origin', ['refs/heads/main', 'refs/tags/v1.0.0']);
const main = refs.get('refs/heads/main'); // the commit's object ID, or undefined
```

#### <a id="api-readStatus"></a>`readStatus`

*Function*

Reads the working tree's status with `git status --porcelain=v2 -z --branch`: the commit HEAD points at, null before the first commit, and the changed paths, staged or not, renames and copies with their original paths, conflicts with their status letters, and every untracked file that isn't ignored. Submodules are left out. Git runs the clean filters that `.gitattributes` and the config name while it compares files. A path that isn't valid UTF-8 fails the read.

```ts
readStatus(cwd: string, options?: IGitCommandOptions): Promise<IGitStatus>
```

**Parameters**

- `cwd` `string`: The repository's directory.
- `options?` `IGitCommandOptions`: runGit's options, such as the output limit. Defaults to `{}`.

**Returns** `Promise<IGitStatus>`: A promise that resolves to the commit and the entries, none for a clean working tree.

**Throws**

- `GIT_INVALID_ARGUMENT`: An argument isn't valid.
- `GIT_REPOSITORY_NOT_FOUND`: The directory isn't in a Git repository.
- `GIT_ACCESS_DENIED`: Git can't access the repository.
- `GIT_COMMAND_FAILED`: The git command failed.
- `GIT_OUTPUT_INVALID`: Git's output isn't in the expected format.
- `GIT_NOT_FOUND`: Git isn't installed, or isn't on the PATH.
- `PROCESS_START_FAILED`: Unable to start the command
- `PROCESS_TIMED_OUT`: The process didn't finish within the timeout
- `PROCESS_OUTPUT_TOO_LARGE`: The process wrote more output than allowed
- `PROCESS_TREE_SURVIVED`: The process tree is still running after it was force-stopped
- The signal's reason when the signal aborts.

**Example**

```ts
import { readStatus } from 'jg-git-commands';

const { commit, entries } = await readStatus('/srv/app');
const renamed = entries.filter(({ index }) => index === 'R');
```

#### <a id="api-readTopLevel"></a>`readTopLevel`

*Function*

Reads the root of the working tree a directory is in, with `git rev-parse --show-toplevel`. It's null inside a `.git` directory or a bare repository, which have no working tree, and fails with GIT_REPOSITORY_NOT_FOUND outside any repository.

```ts
readTopLevel(cwd: string, options?: IGitCommandOptions): Promise<string | null>
```

**Parameters**

- `cwd` `string`: The directory.
- `options?` `IGitCommandOptions`: runGit's options, such as the timeout. Defaults to `{}`.

**Returns** `Promise<string | null>`: A promise that resolves to the working tree's root, or null.

**Throws**

- `GIT_INVALID_ARGUMENT`: An argument isn't valid.
- `GIT_REPOSITORY_NOT_FOUND`: The directory isn't in a Git repository.
- `GIT_ACCESS_DENIED`: Git can't access the repository.
- `GIT_COMMAND_FAILED`: The git command failed.
- `GIT_OUTPUT_INVALID`: Git's output isn't in the expected format.
- `GIT_NOT_FOUND`: Git isn't installed, or isn't on the PATH.
- `PROCESS_START_FAILED`: Unable to start the command
- `PROCESS_TIMED_OUT`: The process didn't finish within the timeout
- `PROCESS_OUTPUT_TOO_LARGE`: The process wrote more output than allowed
- `PROCESS_TREE_SURVIVED`: The process tree is still running after it was force-stopped
- The signal's reason when the signal aborts.

**Example**

```ts
import { readTopLevel } from 'jg-git-commands';

const root = await readTopLevel('/srv/app/src'); // '/srv/app'
```

#### <a id="api-resolveCommit"></a>`resolveCommit`

*Function*

Resolves a revision, such as a branch, a tag, or an abbreviated object ID, to the full object ID of the commit it names. It reads objects without running anything from the repository's config.

```ts
resolveCommit(
  cwd: string,
  rev: string,
  options?: IGitCommandOptions,
): Promise<string | null>
```

**Parameters**

- `cwd` `string`: The repository's directory.
- `rev` `string`: The revision.
- `options?` `IGitCommandOptions`: runGit's options, such as the timeout. Defaults to `{}`.

**Returns** `Promise<string | null>`: A promise that resolves to the commit's object ID, or null when the revision doesn't name a commit, such as a branch that doesn't exist.

**Throws**

- `GIT_INVALID_ARGUMENT`: An argument isn't valid.
- `GIT_REPOSITORY_NOT_FOUND`: The directory isn't in a Git repository.
- `GIT_ACCESS_DENIED`: Git can't access the repository.
- `GIT_COMMAND_FAILED`: The git command failed.
- `GIT_OUTPUT_INVALID`: Git's output isn't in the expected format.
- `GIT_NOT_FOUND`: Git isn't installed, or isn't on the PATH.
- `PROCESS_START_FAILED`: Unable to start the command
- `PROCESS_TIMED_OUT`: The process didn't finish within the timeout
- `PROCESS_OUTPUT_TOO_LARGE`: The process wrote more output than allowed
- `PROCESS_TREE_SURVIVED`: The process tree is still running after it was force-stopped
- The signal's reason when the signal aborts.

**Example**

```ts
import { resolveCommit } from 'jg-git-commands';

const commit = await resolveCommit('/srv/app', 'HEAD'); // null before the first commit
```

#### <a id="api-runGit"></a>`runGit`

*Function*

Runs a git command that never prompts: without a terminal prompt or an askpass program, in an environment without inherited Git variables, with an SSH command in batch mode, without a file system monitor or a pager, and, unless `useCredentialHelpers`, without credential helpers, the repository's included. A helper that does run can't prompt either: Git Credential Manager runs with `GCM_INTERACTIVE=never`, so it fails rather than open a sign-in window. Without credential helpers, authenticate with SSH keys or credentials you pass yourself, such as a header set as config in `env`. It also runs without colors or recursing into submodules, in the C locale, and allows no transport unless `env` sets `GIT_ALLOW_PROTOCOL`, so reading a partial clone never fetches. It resolves with the exit code, whatever it is, and the output, decoded as UTF-8 or as bytes with `encoding: 'buffer'`; a timeout or too much output rejects as jg-process's runProcess does. `assertGitSucceeded` throws the classified error for a failed command.

```ts
runGit<TEncoding extends IProcessOutputEncoding = "utf-8">(
  args: readonly string[],
  options: IRunGitOptions<TEncoding>,
): Promise<IProcessResult<IProcessOutput<TEncoding>>>
```

**Parameters**

- `args` `readonly string[]`: The command's arguments, such as `['status', '--porcelain=v1']`.
- `options` `IRunGitOptions<TEncoding>`: The working directory, the limits, and how much of the user's setup applies.

**Returns** `Promise<IProcessResult<IProcessOutput<TEncoding>>>`: A promise that resolves with the exit code and the output.

**Throws**

- `GIT_INVALID_ARGUMENT`: An argument isn't valid.
- `GIT_NOT_FOUND`: Git isn't installed, or isn't on the PATH.
- `PROCESS_START_FAILED`: Unable to start the command
- `PROCESS_TIMED_OUT`: The process didn't finish within the timeout
- `PROCESS_OUTPUT_TOO_LARGE`: The process wrote more output than allowed
- `PROCESS_TREE_SURVIVED`: The process tree is still running after it was force-stopped
- The signal's reason when the signal aborts.

**Example**

```ts
import { runGit } from 'jg-git-commands';

const { exitCode, stdout } = await runGit(['log', '-1', '--format=%H'], { cwd: '/srv/app' });
```

### <a id="api-constants"></a>Constants

#### <a id="api-DEFAULT_GIT_MAX_OUTPUT_BYTES"></a>`DEFAULT_GIT_MAX_OUTPUT_BYTES`

*Constant*

the bytes a git command's output may take when the options don't say (1 MiB)

```ts
const DEFAULT_GIT_MAX_OUTPUT_BYTES: 1048576
```

#### <a id="api-DEFAULT_GIT_SSH_COMMAND"></a>`DEFAULT_GIT_SSH_COMMAND`

*Constant*

the SSH command Git uses unless the options give another: no password or passphrase prompt, and a connection that gives up after 10 seconds

```ts
const DEFAULT_GIT_SSH_COMMAND: "ssh -o BatchMode=yes -o ConnectTimeout=10"
```

#### <a id="api-DEFAULT_GIT_TIMEOUT_SECONDS"></a>`DEFAULT_GIT_TIMEOUT_SECONDS`

*Constant*

the seconds a git command may run when the options don't say

```ts
const DEFAULT_GIT_TIMEOUT_SECONDS: 30
```

#### <a id="api-ERRORS"></a>`ERRORS`

*Constant*

the codes for every error thrown by the package

```ts
const ERRORS: { GIT_NOT_FOUND: "GIT_NOT_FOUND"; GIT_COMMAND_FAILED: "GIT_COMMAND_FAILED"; GIT_INVALID_ARGUMENT: "GIT_INVALID_ARGUMENT"; GIT_OUTPUT_INVALID: "GIT_OUTPUT_INVALID"; GIT_REPOSITORY_NOT_FOUND: "GIT_REPOSITORY_NOT_FOUND"; GIT_ACCESS_DENIED: "GIT_ACCESS_DENIED" }
```

### <a id="api-types"></a>Types

#### <a id="api-ICalculateGitBlobObjectIdOptions"></a>`ICalculateGitBlobObjectIdOptions`

*Type*

what calculateGitBlobObjectId takes

```ts
type ICalculateGitBlobObjectIdOptions = {
    algorithm?: IGitObjectFormat | undefined;
};
```

**Members**

- `algorithm: IGitObjectFormat` (property): the repository's object format. Defaults to 'sha1'

#### <a id="api-IFetchCommitOptions"></a>`IFetchCommitOptions`

*Type*

what fetchCommit takes

```ts
type IFetchCommitOptions = IGitCommandOptions & {
    depth?: number | undefined;
};
```

#### <a id="api-IGitCommandOptions"></a>`IGitCommandOptions`

*Type*

what every command helper takes besides its own arguments: runGit's options, but the working directory and stdin

```ts
type IGitCommandOptions = Omit<IRunGitOptions, 'cwd' | 'input'>;
```

#### <a id="api-IGitEnvironmentOptions"></a>`IGitEnvironmentOptions`

*Type*

what createGitEnvironment takes

```ts
type IGitEnvironmentOptions = {
    isolateConfig?: boolean | undefined;
    sshCommand?: string | undefined;
    baseEnv?: NodeJS.ProcessEnv | undefined;
};
```

**Members**

- `isolateConfig: boolean` (property): whether Git ignores the system config and the user's global config, such as for a repository or a URL the caller doesn't trust. Defaults to false
- `sshCommand: string` (property): the SSH command Git runs for ssh:// remotes. Defaults to DEFAULT_GIT_SSH_COMMAND
- `baseEnv: NodeJS.ProcessEnv` (property): the environment to start from, without its Git variables. Defaults to process.env

#### <a id="api-IGitObjectFormat"></a>`IGitObjectFormat`

*Type*

the hash algorithms Git names objects with

```ts
type IGitObjectFormat = 'sha1' | 'sha256';
```

#### <a id="api-IGitStatus"></a>`IGitStatus`

*Type*

the working tree's status: the commit HEAD points at, or null before the first commit, and the changed and untracked paths

```ts
type IGitStatus = {
    commit: string | null;
    entries: IStatusEntry[];
};
```

**Members**

- `commit: string | null` (property)
- `entries: IStatusEntry[]` (property)

#### <a id="api-IGitVersion"></a>`IGitVersion`

*Type*

a Git version, such as 2.45.1

```ts
type IGitVersion = {
    major: number;
    minor: number;
    patch: number;
};
```

**Members**

- `major: number` (property)
- `minor: number` (property)
- `patch: number` (property)

#### <a id="api-IIndexEntry"></a>`IIndexEntry`

*Type*

one entry of the index: its file mode, such as `100644`, its merge stage, 0 unless it's in a conflict, and its path from the repository's root

```ts
type IIndexEntry = {
    mode: string;
    stage: 0 | 1 | 2 | 3;
    path: string;
};
```

**Members**

- `mode: string` (property)
- `stage: 0 | 1 | 2 | 3` (property)
- `path: string` (property)

#### <a id="api-IListPathsOptions"></a>`IListPathsOptions`

*Type*

what readIndexEntries and listUntrackedFiles take

```ts
type IListPathsOptions = IGitCommandOptions & {
    paths?: readonly string[] | undefined;
};
```

#### <a id="api-IReadChangedPathsOptions"></a>`IReadChangedPathsOptions`

*Type*

what readChangedPaths takes

```ts
type IReadChangedPathsOptions = IGitCommandOptions & {
    to?: string | undefined;
};
```

#### <a id="api-IReadFileAtRevisionOptions"></a>`IReadFileAtRevisionOptions`

*Type*

what readFileAtRevision takes

```ts
type IReadFileAtRevisionOptions = Omit<IGitCommandOptions, 'maxOutputBytes'> & {
    maxBytes?: number | undefined;
};
```

#### <a id="api-IRemoteRepository"></a>`IRemoteRepository`

*Type*

a hosted repository's owner and name, as its remote URL names them

```ts
type IRemoteRepository = {
    owner: string;
    name: string;
};
```

**Members**

- `owner: string` (property)
- `name: string` (property)

#### <a id="api-IRunGitOptions"></a>`IRunGitOptions`

*Type*

what runGit takes

```ts
type IRunGitOptions<TEncoding extends IProcessOutputEncoding = 'utf-8'> = {
    cwd: string;
    timeoutSeconds?: number | undefined;
    maxOutputBytes?: number | undefined;
    input?: string | Uint8Array | undefined;
    signal?: AbortSignal | undefined;
    isolateConfig?: boolean | undefined;
    useCredentialHelpers?: boolean | undefined;
    env?: NodeJS.ProcessEnv | undefined;
    encoding?: TEncoding | undefined;
};
```

**Members**

- `cwd: string` (property): the directory git runs in, such as the repository's working tree
- `timeoutSeconds: number` (property): the seconds the command may run before it's stopped. Defaults to 30
- `maxOutputBytes: number` (property): the bytes stdout and stderr may hold together. Defaults to 1 MiB
- `input: string | Uint8Array` (property): the data written to git's stdin
- `signal: AbortSignal` (property): stops the command when it aborts
- `isolateConfig: boolean` (property): whether Git ignores the system config and the user's global config. Defaults to false
- `useCredentialHelpers: boolean` (property): whether the configured credential helpers run, such as for authenticated HTTPS; they still can't use an askpass program or the terminal, and Git Credential Manager can't open a sign-in window. Defaults to false, which empties their list
- `env: NodeJS.ProcessEnv` (property): more variables, such as GIT_SSL_CAINFO, set after the inherited Git variables are removed; an undefined value unsets one. GIT_ASKPASS, GIT_TERMINAL_PROMPT, GCM_INTERACTIVE, SSH_ASKPASS, and SSH_ASKPASS_REQUIRE are ignored, so nothing the caller passes lets a prompt through. Set GIT_ALLOW_PROTOCOL to allow a transport, such as `file` or `https`, which every command refuses by default
- `encoding: TEncoding` (property): whether stdout and stderr are decoded as UTF-8 or returned as bytes. Defaults to 'utf-8'

#### <a id="api-IStatusEntry"></a>`IStatusEntry`

*Type*

A path `git status` reports, with its two status letters: `M` modified, `T` type changed, `A` added, `D` deleted, `R` renamed, `C` copied, `U` unmerged, `?` untracked, and a space for unchanged. An unmerged path keeps the letters Git gives its conflict, such as `UU` or `AA`.

```ts
type IStatusEntry = {
    index: string;
    workingTree: string;
    path: string;
    originalPath: string | null;
};
```

**Members**

- `index: string` (property): the status in the index, against HEAD
- `workingTree: string` (property): the status in the working tree, against the index
- `path: string` (property): the path from the repository's root
- `originalPath: string | null` (property): the path before a rename or a copy, or null
