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 nullconst manifest = await readFileAtRevision('/srv/app', 'HEAD', 'package.json', { maxBytes: 65_536 }); // null without the fileconst 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 repositoryconst 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 worktreeconst defaultBranch = await readRemoteDefaultBranch('/srv/app'); // 'main', or null when unknownconst 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:
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.
Generated from TSDoc
API reference
Every export of [email protected], 39 in all, with its signature, its errors, and an example.
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.
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.
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.
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.
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.
Reads a hosted repository's owner and name from its remote URL, such as the jesusgraterol and jg-packages of [email protected]: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.
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.
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.
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.
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.
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).
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.
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.
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.
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.
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.
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.
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.
the directory git runs in, such as the repository's working tree
timeoutSecondsproperty
number
the seconds the command may run before it's stopped. Defaults to 30
maxOutputBytesproperty
number
the bytes stdout and stderr may hold together. Defaults to 1 MiB
inputproperty
string | Uint8Array
the data written to git's stdin
signalproperty
AbortSignal
stops the command when it aborts
isolateConfigproperty
boolean
whether Git ignores the system config and the user's global config. Defaults to false
useCredentialHelpersproperty
boolean
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
envproperty
NodeJS.ProcessEnv
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
encodingproperty
TEncoding
whether stdout and stderr are decoded as UTF-8 or returned as bytes. Defaults to 'utf-8'
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.