@hyperfrontend/versioning/git

git/

Git operations for versioning workflows with secure command execution.

Overview

This module provides a complete interface for git operations needed in versioning workflows: querying commit history, managing tags, staging files, and inspecting repository status. All command arguments are validated character-by-character to prevent command injection attacks.

Usage Examples

Using GitClient (Recommended)

import { createGitClient } from '@hyperfrontend/versioning'

const git = createGitClient({ cwd: '/path/to/repo' })

// Get recent commits
const commits = git.getCommitLog({ maxCount: 10 })

// Get commits since last release
const newCommits = git.getCommitsSince('v1.0.0')

// Get files changed between refs
const changedFiles = git.getChangedFilesBetween('origin/main', 'HEAD')
const changesWithStatus = git.getChangedFilesBetweenWithStatus('v1.0.0', 'v2.0.0')

// Get commit with file details
const commitWithFiles = git.getCommitWithFiles('abc1234')
if (commitWithFiles) {
  for (const file of commitWithFiles.files) {
    console.log(`${file.status}: ${file.path}`)
  }
}

// Check repository state
if (git.isClean()) {
  // Create a tag
  git.createTag('v1.1.0', { message: 'Release v1.1.0' })
}

// Check for in-progress operations before committing
const state = git.getOperationState()
if (state.inProgress) {
  console.warn(`Cannot proceed: git ${state.reason} in progress`)
}

Standalone Operations

import {
  getCommitsBetween,
  getTags,
  getLatestTag,
  commit,
  stage,
  getChangedFilesBetween,
  getChangedFilesBetweenWithStatus,
  getCommitWithFiles,
} from '@hyperfrontend/versioning'

// Get commits between tags
const commits = getCommitsBetween('v1.0.0', 'v2.0.0')
console.log(`${commits.length} commits between releases`)

// Get files changed since main
const changedFiles = getChangedFilesBetween('origin/main', 'HEAD')
console.log(`${changedFiles.length} files changed`)

// Get files with status information
const changes = getChangedFilesBetweenWithStatus('v1.0.0', 'v2.0.0')
const added = changes.filter((c) => c.status === 'added')
const deleted = changes.filter((c) => c.status === 'deleted')
console.log(`${added.length} added, ${deleted.length} deleted`)

// Get commit with file details for changelog attribution
const commitWithFiles = getCommitWithFiles('abc1234')
if (commitWithFiles) {
  console.log(`${commitWithFiles.subject} touched ${commitWithFiles.files.length} files`)
}

// Find latest version tag
const latest = getLatestTag({ pattern: '@scope/pkg@' })
console.log(`Latest: ${latest?.name}`)

// Stage and commit
stage(['package.json', 'CHANGELOG.md'])
commit('chore: release v1.1.0')

Working with Tags

import { extractVersionFromTag, extractPackageFromTag, buildTagName, getTagsForPackage } from '@hyperfrontend/versioning'

// Parse tag names
extractVersionFromTag('v1.2.3') // '1.2.3'
extractVersionFromTag('@scope/pkg@1.0.0') // '1.0.0'

extractPackageFromTag('@scope/pkg@1.0.0') // '@scope/pkg'
extractPackageFromTag('utils@1.2.3') // 'utils'

// Build tag names
buildTagName('@scope/pkg', '2.0.0') // '@scope/pkg@2.0.0'
buildTagName('lib', '1.0.0', '${package}-v${version}') // 'lib-v1.0.0'

// Get all tags for a package
const tags = getTagsForPackage('@hyperfrontend/versioning')

Working with Commits

import { createGitCommit, isMergeCommit, extractType, extractScope } from '@hyperfrontend/versioning'

// Parse conventional commits
const subject = 'feat(lib-versioning): add git operations'
extractType(subject) // 'feat'
extractScope(subject) // 'lib-versioning'

// Check commit characteristics
if (isMergeCommit(commit)) {
  console.log('Skipping merge commit')
}

Security

All user input undergoes character-by-character validation before being used in shell commands:

  • No regex: Eliminates ReDoS vulnerabilities
  • Allowlist validation: Only permitted characters pass through
  • Length limits: Prevents memory exhaustion attacks
  • No shell interpolation: Arguments are validated, not escaped-and-quoted

Allowed Characters by Function

FunctionAllowed Characters
escapeGitRefa-z A-Z 0-9 / - _ . @ ~ ^ { }
escapeGitPatha-z A-Z 0-9 / - _ . (space)
escapeFilePatha-z A-Z 0-9 / - _ . (space)
escapeAuthora-z A-Z 0-9 - _ . @ < > (space)
escapeGitTagPatterna-z A-Z 0-9 / - _ . @ *

Maximum Input Lengths

Input TypeMax Length
Git reference256
File path4096
Author string512
Commit message10000
Tag pattern256

See Also

API Reference§

ƒ Functions

§function

amendCommitNoEdit(options: Omit<CreateCommitOptions, "amend" | "noEdit">): GitCommit

Amends the last commit without changing the message. Useful for adding staged changes to the previous commit.
Parameters
NameTypeDescription
§options
Omit<CreateCommitOptions, "amend" | "noEdit">Configuration for the commit operation(default: {})
Returns
GitCommit
GitCommit object representing the amended commit
Example
Add staged changes to last commit without changing message
stage(['extra-file.ts'])
amendCommitNoEdit() // adds staged files to last commit
§function

commitReachableFromHead(hash: string, options: Pick<GitLogOptions, "cwd" | "timeout">): boolean

Checks if a commit is reachable from HEAD (i.e., is an ancestor of HEAD).
A commit may exist in the repository but be orphaned (not in current branch history). This function verifies that the commit is actually in the history of the current HEAD.
Common use cases:
  • Verify an external commit reference before using it for range queries
  • Detect if history was rewritten (rebase/force push) after a reference was recorded
Parameters
NameTypeDescription
§hash
stringCommit hash to check
§options
Pick<GitLogOptions, "cwd" | "timeout">Additional options(default: {})
Returns
boolean
True if the commit is an ancestor of HEAD
Example
Check if commit is reachable from HEAD
if (commitReachableFromHead(baseCommit)) {
  // Safe to use for commit range queries
  const commits = getCommitsSince(baseCommit)
} else {
  // Commit not in current history, need fallback strategy
}
§function

discardAllChanges(options: GitCommitOptions): boolean

Discards all uncommitted changes and unstages all files.
Combines discardChanges() + unstage(['.']) for complete working tree reset.
Warning: Destructive operation: discarded changes cannot be recovered.
Parameters
NameTypeDescription
§options
GitCommitOptionsConfiguration for the operation(default: {})
Returns
boolean
True if both operations succeeded
Example

Reset working directory to match HEAD

// Reset working directory to match HEAD
if (discardAllChanges()) {
  console.log('Working tree reset to HEAD')
}
§function

discardChanges(options: DiscardChangesOptions): boolean

Discards uncommitted changes to tracked files.
Uses git checkout -- <files> to restore files from HEAD. Returns true if successful, false otherwise (silent failure pattern).
Warning: Destructive operation: discarded changes cannot be recovered.
Parameters
NameTypeDescription
§options
DiscardChangesOptionsConfiguration including optional file list(default: {})
Returns
boolean
True if discard succeeded
Examples
Discard changes in tracked files
// Discard all changes
discardChanges()

// Discard specific files
discardChanges({ files: ['package.json', 'CHANGELOG.md'] })
Typical rollback pattern
// Typical rollback pattern
if (hasUnstagedChanges()) {
  discardChanges()
}
if (hasStagedChanges()) {
  unstage(['.'])
}
§function

getShortHash(hash: string): string

Gets a short hash (7 characters) from a full commit hash.
Parameters
NameTypeDescription
§hash
stringFull commit hash
Returns
string
Short hash (7 characters)
Example

Get short hash from full commit hash

getShortHash('abc123def456789') // => 'abc123d'
§function

amendCommit(message: string, options: Omit<CreateCommitOptions, "amend">): GitCommit

Amends the last commit with new message.
Parameters
NameTypeDescription
§message
stringThe new commit message to use
§options
Omit<CreateCommitOptions, "amend">Configuration for the commit operation(default: {})
Returns
GitCommit
GitCommit object representing the amended commit
Example
Amend the last commit with a new message
const commit = amendCommit('feat: improved feature')
§function

buildRefName(type: GitRefType, name: string, remote?: string): string

Builds a full reference name from type and name.
Parameters
NameTypeDescription
§type
GitRefTypeReference type
§name
stringReference name
§remote?
stringRemote name (for remote type)
Returns
string
Full reference name
Example
Build full reference names from type and name
buildRefName('branch', 'main') // 'refs/heads/main'
buildRefName('tag', 'v1.0.0') // 'refs/tags/v1.0.0'
buildRefName('remote', 'main', 'origin') // 'refs/remotes/origin/main'
§function

buildTagName(packageName: string, version: string, format: string): string

Builds a tag name from package name and version.
Parameters
NameTypeDescription
§packageName
stringPackage name (e.g., '@scope/package' or 'package')
§version
stringVersion string (e.g., '1.2.3')
§format
stringTag format template, uses ${package} and ${version} placeholders(default: '${package}@${version}')
Returns
string
Formatted tag name
Example
Build tag names with different formats
buildTagName('@scope/pkg', '1.2.3') // '@scope/pkg@1.2.3'
buildTagName('utils', '1.0.0', 'v${version}') // 'v1.0.0'
buildTagName('pkg', '2.0.0', '${package}-v${version}') // 'pkg-v2.0.0'
§function

commit(message: string, options: CreateCommitOptions): GitCommit

Creates a new commit.
Parameters
NameTypeDescription
§message
stringCommit message (subject line)
§options
CreateCommitOptionsCreate options(default: {})
Returns
GitCommit
Created GitCommit
Example
Create a new commit
const commit = createCommit('feat: add new feature')
const commit = createCommit('fix: resolve bug', { body: 'Detailed description' })
§function

commitExists(hash: string, options: Pick<GitLogOptions, "cwd" | "timeout">): boolean

Checks if a commit exists in the repository.
Parameters
NameTypeDescription
§hash
stringCommit hash to check
§options
Pick<GitLogOptions, "cwd" | "timeout">Additional options(default: {})
Returns
boolean
True if commit exists
Example

Check if a commit exists in the repository

if (commitExists('abc123def')) {
  console.log('Commit found in repository')
}
§function

compareRefsByName(a: GitRef, b: GitRef): number

Compares two references by name (alphabetically).
Parameters
NameTypeDescription
GitRefFirst reference
GitRefSecond reference
Returns
number
Comparison result (-1, 0, or 1)
Example

Sort references alphabetically by name

const refs = [refB, refA, refC]
refs.sort(compareRefsByName) // => [refA, refB, refC]
§function

compareTagsByVersion(a: GitTag, b: GitTag): number

Compares two tags by version (newest first). Useful for sorting tags.
Parameters
NameTypeDescription
GitTagFirst tag
GitTagSecond tag
Returns
number
Comparison result (-1, 0, or 1)
Example

Sort tags by version (newest first)

const tags = [tagV1, tagV2, tagV3]
tags.sort(compareTagsByVersion) // => [tagV3, tagV2, tagV1]
§function

createAnnotatedTag(options: CreateAnnotatedTagOptions): GitTag

Creates an annotated git tag.
Parameters
NameTypeDescription
§options
CreateAnnotatedTagOptionsTag creation options
Returns
GitTag
A new GitTag object
Example
Create an annotated git tag with metadata
const tag = createAnnotatedTag({
  name: 'v1.0.0',
  commitHash: 'abc123...',
  message: 'Release v1.0.0',
  taggerName: 'John Doe',
  taggerEmail: 'john@example.com',
  tagDate: '2026-03-12T10:00:00Z',
})
§function

createEmptyCommit(message: string, options: Omit<CreateCommitOptions, "allowEmpty">): GitCommit

Creates an empty commit (useful for CI triggers).
Parameters
NameTypeDescription
§message
stringText for the empty commit
§options
Omit<CreateCommitOptions, "allowEmpty">Configuration for the commit operation(default: {})
Returns
GitCommit
GitCommit object representing the new empty commit
Example
Create an empty commit for CI triggers
const commit = createEmptyCommit('chore: trigger CI')
§function

createGitClient(config: GitClientConfig): GitClient

Creates a git client for a specific working directory.
Parameters
NameTypeDescription
§config
GitClientConfigClient configuration(default: {})
Returns
GitClient
GitClient instance
Example
Create a git client for a repository
const git = createGitClient({ cwd: '/path/to/repo' })
const status = git.getStatus()
const commits = git.getCommitsSince('v1.0.0')
§function

createGitCommitModel(options: CreateGitCommitOptions): GitCommit

Creates a git commit model.
Parameters
NameTypeDescription
§options
CreateGitCommitOptionsCommit creation options
Returns
GitCommit
A new GitCommit object
Example
Create a git commit model
const commit = createGitCommit({
  hash: 'abc123...',
  authorName: 'John Doe',
  authorEmail: 'john@example.com',
  authorDate: '2026-03-12T10:00:00Z',
  subject: 'feat: add new feature',
})
§function

createGitRef(options: CreateGitRefOptions): GitRef

Creates a git reference from full name. Parses the reference type from the full name.
Parameters
NameTypeDescription
§options
CreateGitRefOptionsReference creation options
Returns
GitRef
A new GitRef object
Example
Create a git reference from full name
const ref = createGitRef({
  fullName: 'refs/heads/main',
  commitHash: 'abc123...',
})
§function

createLightweightTag(options: CreateLightweightTagOptions): GitTag

Creates a lightweight git tag.
Parameters
NameTypeDescription
§options
CreateLightweightTagOptionsTag creation options
Returns
GitTag
A new GitTag object
Example
Create a lightweight git tag
const tag = createLightweightTag({
  name: 'v1.0.0',
  commitHash: 'abc123...',
})
§function

createTag(name: string, options: CreateTagOptions): GitTag

Creates a new tag.
Parameters
NameTypeDescription
§name
stringThe name for the new tag
§options
CreateTagOptionsConfiguration including optional message for annotated tags(default: {})
Returns
GitTag
Created GitTag
Example
Create lightweight and annotated tags
// Create lightweight tag
const tag = createTag('v1.0.0')

// Create annotated tag
const tag = createTag('v1.0.0', { message: 'Release v1.0.0' })
§function

deleteTag(name: string, options: GitTagOptions): boolean

Deletes a tag.
Parameters
NameTypeDescription
§name
stringThe tag name to delete
§options
GitTagOptionsConfiguration for the tag operation(default: {})
Returns
boolean
True if deleted
Example
Delete a tag by name
const deleted = deleteTag('v1.0.0')
§function

escapeAuthor(author: string): string

Escapes an author string for safe use in git commands. Format: "Name <email>"
Parameters
NameTypeDescription
§author
stringAuthor to escape
Returns
string
Safe author string
Example

Escape an author string for git commit

const safeAuthor = escapeAuthor('John Doe <john@example.com>')
// => 'John Doe <john@example.com>'
§function

escapeFilePath(path: string): string

Escapes a file path for safe use in git commands.
Parameters
NameTypeDescription
§path
stringPath to escape
Returns
string
Safe path string
Example

Escape a file path for git commands

const safePath = escapeFilePath('src/utils/helper.ts')
// => 'src/utils/helper.ts'
escapeFilePath('file$name.ts') // throws - '$' is invalid
§function

escapeGitArg(arg: string): string

Escapes a general git argument for safe use in shell commands.
Parameters
NameTypeDescription
§arg
stringArgument to escape
Returns
string
Safe argument string
Example

Escape a git argument for shell commands

escapeGitArg('John Doe <john@example.com>') // => 'John Doe <john@example.com>'
§function

escapeGitMessage(message: string): string

Escapes a message for safe use in git commands.
Parameters
NameTypeDescription
§message
stringMessage to escape
Returns
string
Safe message string
Example

Escape a git commit message

const safeMessage = escapeGitMessage('Release v1.0.0 "stable"')
// => 'Release v1.0.0 \"stable\"'
§function

escapeGitPath(path: string): string

Escapes a file path for safe use in git commands.
Parameters
NameTypeDescription
§path
stringPath to escape
Returns
string
Safe path string
Example

Escape a file path for git commands

escapeGitPath('src/utils/helper.ts') // => 'src/utils/helper.ts'
escapeGitPath('path with spaces/file.ts') // => 'path with spaces/file.ts'
§function

escapeGitRef(ref: string): string

Escapes a git reference for safe use in shell commands.
Parameters
NameTypeDescription
§ref
stringReference to escape
Returns
string
Safe reference string
Example

Escape a git reference for shell commands

escapeGitRef('refs/heads/main') // => 'refs/heads/main'
escapeGitRef('feature/test') // => 'feature/test'
escapeGitRef('ref$invalid') // throws - '$' is invalid
§function

escapeGitTagPattern(pattern: string): string

Escapes a tag pattern for safe use in git commands.
Parameters
NameTypeDescription
§pattern
stringPattern to escape
Returns
string
Safe pattern string
Example

Escape a tag pattern for git commands

const safePattern = escapeGitTagPattern('@scope/package@')
// => '@scope/package@'
escapeGitTagPattern('v1.0.*') // throws - '*' is invalid
§function

extractPackageFromTag(tagName: string): string

Extracts package name from tag name. Handles formats like: @scope/package@1.2.3, package@1.2.3, package-v1.2.3 Uses character-by-character parsing (no regex).
Parameters
NameTypeDescription
§tagName
stringTag name to parse
Returns
string
The extracted package name or undefined if not found
Example
Extract package name from tag
extractPackageFromTag('@scope/pkg@1.2.3') // '@scope/pkg'
extractPackageFromTag('lib-utils@1.2.3') // 'lib-utils'
extractPackageFromTag('v1.2.3') // undefined
§function

extractScope(subject: string): string

Extracts the scope from a commit subject if it follows conventional commit format. Uses character-by-character parsing (no regex).
Parameters
NameTypeDescription
§subject
stringCommit subject line
Returns
string
Scope string or undefined if no scope found
Example
Extract scope from conventional commit
extractScope('feat(lib-versioning): add git support') // 'lib-versioning'
extractScope('fix: resolve issue') // undefined
§function

extractType(subject: string): string

Extracts the type from a commit subject if it follows conventional commit format. Uses character-by-character parsing (no regex).
Parameters
NameTypeDescription
§subject
stringCommit subject line
Returns
string
Type string or undefined if no valid type found
Example
Extract type from conventional commit
extractType('feat(lib-versioning): add git support') // 'feat'
extractType('fix: resolve issue') // 'fix'
extractType('random message') // undefined
§function

extractVersionFromTag(tagName: string): string

Extracts version from tag name. Handles common formats: v1.2.3, @scope/package@1.2.3, package@1.2.3 Uses character-by-character parsing (no regex).
Parameters
NameTypeDescription
§tagName
stringTag name to parse
Returns
string
The extracted version string or undefined if no version found
Example
Extract version from various tag formats
extractVersionFromTag('v1.2.3') // '1.2.3'
extractVersionFromTag('@scope/pkg@1.2.3') // '1.2.3'
extractVersionFromTag('release-1.2.3') // '1.2.3'
§function

filterRefsByRemote(refs: unknown, remote: string): unknown

Filters references by remote.
Parameters
NameTypeDescription
§refs
unknownReferences to filter
§remote
stringRemote name to filter by
Returns
unknown
Filtered references
Example

Filter references by remote

const originRefs = filterRefsByRemote(remoteRefs, 'origin')
const upstreamRefs = filterRefsByRemote(remoteRefs, 'upstream')
§function

filterRefsByType(refs: unknown, type: GitRefType): unknown

Filters references by type.
Parameters
NameTypeDescription
§refs
unknownReferences to filter
§type
GitRefTypeType to filter by
Returns
unknown
Filtered references
Example

Filter references by type

const branches = filterRefsByType(allRefs, 'branch')
const tags = filterRefsByType(allRefs, 'tag')
§function

getAheadCount(options: GitStatusOptions): number

Gets the number of commits ahead of upstream.
Parameters
NameTypeDescription
§options
GitStatusOptionsStatus options(default: {})
Returns
number
Number of commits ahead
Example

Get commits ahead of upstream

const ahead = getAheadCount()
console.log(`${ahead} commits to push`)
§function

getBehindCount(options: GitStatusOptions): number

Gets the number of commits behind upstream.
Parameters
NameTypeDescription
§options
GitStatusOptionsStatus options(default: {})
Returns
number
Number of commits behind
Example

Get commits behind upstream

const behind = getBehindCount()
console.log(`${behind} commits to pull`)
§function

getChangedFilesBetween(base: string, head: string, options: DiffOptions): unknown

Gets files changed between two git refs.
Uses git diff --name-only base...head which computes the merge-base internally, giving files changed in head since diverging from base.
Parameters
NameTypeDescription
§base
stringBase reference (e.g., 'origin/main', 'v1.0.0')
§head
stringHead reference (defaults to 'HEAD')(default: 'HEAD')
§options
DiffOptionsAdditional options(default: {})
Returns
unknown
Deduplicated list of changed file paths (relative to repo root)
Example
Get changed files between refs
// Files changed since diverging from main
const files = getChangedFilesBetween('origin/main')

// Files changed between two tags
const files = getChangedFilesBetween('v1.0.0', 'v2.0.0')
§function

getChangedFilesBetweenWithStatus(base: string, head: string, options: DiffOptions): unknown

Gets files changed between two refs with status information.
Parameters
NameTypeDescription
§base
stringBase reference
§head
stringHead reference (defaults to 'HEAD')(default: 'HEAD')
§options
DiffOptionsAdditional options(default: {})
Returns
unknown
Array of file changes with status
Example
Get file changes with status information
const changes = getChangedFilesBetweenWithStatus('v1.0.0', 'v2.0.0')
const added = changes.filter(c => c.status === 'added')
§function

getCommit(hash: string, options: Pick<GitLogOptions, "cwd" | "timeout">): GitCommit

Gets a single commit by its hash.
Parameters
NameTypeDescription
§hash
stringCommit hash (full or short)
§options
Pick<GitLogOptions, "cwd" | "timeout">Additional options(default: {})
Returns
GitCommit
GitCommit or null if not found
Example
Get a single commit by hash
const commit = getCommit('abc1234')
§function

getCommitLog(options: GitLogOptions): unknown

Gets the commit log from a git repository.
Parameters
NameTypeDescription
§options
GitLogOptionsConfiguration for retrieving the commit log(default: {})
Returns
unknown
Array of GitCommit objects
Example
Get commit log with options
const commits = getCommitLog({ maxCount: 10 })
const recentChanges = getCommitLog({ from: 'v1.0.0', to: 'HEAD' })
§function

getCommitsBetween(from: string, to: string, options: Omit<GitLogOptions, "from" | "to">): unknown

Gets commits between two references.
Parameters
NameTypeDescription
§from
stringStarting reference (exclusive)
§to
stringEnding reference (inclusive, default: HEAD)(default: 'HEAD')
§options
Omit<GitLogOptions, "from" | "to">Additional options(default: {})
Returns
unknown
Array of GitCommit objects
Example
Get commits between two references
const commits = getCommitsBetween('v1.0.0', 'v1.1.0')
§function

getCommitsSince(since: string, options: Omit<GitLogOptions, "from">): unknown

Gets commits since a specific tag or reference.
Parameters
NameTypeDescription
§since
stringReference to start from (exclusive)
§options
Omit<GitLogOptions, "from">Additional options(default: {})
Returns
unknown
Array of GitCommit objects
Example
Get commits since a tag
const commits = getCommitsSince('v1.0.0')
§function

getCommitWithFiles(hash: string, options: DiffOptions): GitCommitWithFiles

Gets a commit with its changed files.
Uses git diff-tree to retrieve file changes for a single commit. More efficient than fetching files for all commits when only specific commits need file attribution.
Parameters
NameTypeDescription
§hash
stringCommit hash (full or abbreviated)
§options
DiffOptionsAdditional options(default: {})
Returns
GitCommitWithFiles
Commit with files, or null if not found
Example
Get commit with its changed files
const commit = getCommitWithFiles('abc123')
if (commit) {
  console.log(`${commit.subject} touched ${commit.files.length} files`)
}
§function

getCurrentBranch(options: GitCommitOptions): string

Gets the current branch name.
Parameters
NameTypeDescription
§options
GitCommitOptionsConfiguration for the operation(default: {})
Returns
string
Branch name or null if detached
Example
Get the current branch name
const branch = getCurrentBranch()
§function

getHead(options: GitCommitOptions): string

Gets the current HEAD commit hash.
Parameters
NameTypeDescription
§options
GitCommitOptionsGit operation configuration(default: {})
Returns
string
HEAD commit hash or null
Example
Get the current HEAD commit
const head = getHead()
§function

getHeadHash(options: GitStatusOptions): string

Gets the current commit hash (HEAD).
Parameters
NameTypeDescription
§options
GitStatusOptionsStatus options(default: {})
Returns
string
Commit hash or null
Example

Get the current HEAD commit hash

const hash = getHeadHash()
// => 'abc123def456789012345678901234567890abcd'
§function

getHeadShortHash(options: GitStatusOptions): string

Gets the short current commit hash.
Parameters
NameTypeDescription
§options
GitStatusOptionsStatus options(default: {})
Returns
string
Short hash or null
Example

Get the short HEAD commit hash

const shortHash = getHeadShortHash()
// => 'abc123d'
§function

getLatestTag(options: ListTagsOptions): GitTag

Gets the latest tag (by creation date).
Parameters
NameTypeDescription
§options
ListTagsOptionsTag options with optional pattern(default: {})
Returns
GitTag
Latest GitTag or null
Example
Get the latest tag by creation date
const latest = getLatestTag()
const latestVersion = getLatestTag({ pattern: 'v' })
§function

getModifiedFiles(options: GitStatusOptions): unknown

Gets list of modified file paths (unstaged).
Parameters
NameTypeDescription
§options
GitStatusOptionsStatus options(default: {})
Returns
unknown
Array of modified file paths
Example

Get list of modified files

const modified = getModifiedFiles()
// => ['src/utils.ts', 'README.md']
§function

getOperationState(options: GitCommitOptions): GitOperationState

Detects if git is mid-operation (rebase, merge, patch apply).
Uses filesystem checks on .git/ state files rather than git commands. This is more reliable because file existence checks are atomic OS syscalls that work even when the git index is corrupted or git commands would hang.
Handles worktrees, submodules, and $GIT_DIR overrides via git rev-parse --git-dir.
Parameters
NameTypeDescription
§options
GitCommitOptionsConfiguration for the state check(default: {})
Returns
GitOperationState
Operation state with reason if in progress
Example
Detect if git is mid-operation
const state = getOperationState()
if (state.inProgress) {
  console.warn(`Cannot proceed: git ${state.reason} in progress`)
}
§function

getRemote(ref: GitRef): string

Gets the tracking remote for a reference.
Parameters
NameTypeDescription
§ref
GitRefReference to check
Returns
string
Remote name or undefined
Example

Get the remote for a reference

getRemote({ type: 'remote', name: 'main', remote: 'origin' }) // => 'origin'
getRemote({ type: 'branch', name: 'main' }) // => undefined
§function

getRepositoryRoot(options: GitStatusOptions): string

Gets the repository root directory.
Parameters
NameTypeDescription
§options
GitStatusOptionsStatus options(default: {})
Returns
string
Root directory path or null
Example
Get the repository root directory
const root = getRepositoryRoot()
§function

getStagedFiles(options: GitStatusOptions): unknown

Gets list of staged file paths.
Parameters
NameTypeDescription
§options
GitStatusOptionsStatus options(default: {})
Returns
unknown
Array of staged file paths
Example

Get list of staged files

const staged = getStagedFiles()
// => ['src/index.ts', 'package.json']
§function

getStatus(options: GitStatusOptions): RepositoryStatus

Gets the full repository status.
Parameters
NameTypeDescription
§options
GitStatusOptionsConfiguration for the status query(default: {})
Returns
RepositoryStatus
Comprehensive repository status information
Example
Get the full repository status
const status = getStatus()
if (!status.clean) {
  console.log('Working tree has changes')
}
§function

getTag(name: string, options: GitTagOptions): GitTag

Gets detailed information about a specific tag.
Parameters
NameTypeDescription
§name
stringThe tag name to look up
§options
GitTagOptionsConfiguration for the tag operation(default: {})
Returns
GitTag
GitTag or null if not found
Example
Get detailed information about a specific tag
const tag = getTag('v1.0.0')
§function

getTags(options: ListTagsOptions): unknown

Gets all tags from the repository.
Parameters
NameTypeDescription
§options
ListTagsOptionsTag listing options(default: {})
Returns
unknown
Array of GitTag objects
Example
Get all tags from the repository
const tags = getTags()
const versionTags = getTags({ pattern: 'v' })
§function

getTagsForPackage(packageName: string, options: ListTagsOptions): unknown

Gets tags that match a package name.
Parameters
NameTypeDescription
§packageName
stringPackage name to match
§options
ListTagsOptionsTag options(default: {})
Returns
unknown
Array of matching tags
Example
Get tags matching a package name
const tags = getTagsForPackage('@scope/pkg')
§function

getUntrackedFiles(options: GitStatusOptions): unknown

Gets list of untracked file paths.
Parameters
NameTypeDescription
§options
GitStatusOptionsStatus options(default: {})
Returns
unknown
Array of untracked file paths
Example

Get list of untracked files

const untracked = getUntrackedFiles()
// => ['new-file.ts', 'temp.log']
§function

hasConflicts(options: GitStatusOptions): boolean

Checks if there are merge conflicts.
Parameters
NameTypeDescription
§options
GitStatusOptionsStatus options(default: {})
Returns
boolean
True if there are conflicts
Example

Check for merge conflicts

if (hasConflicts()) {
  console.log('Resolve merge conflicts before continuing')
}
§function

hasStagedChanges(options: GitCommitOptions): boolean

Checks if there are staged changes.
Parameters
NameTypeDescription
§options
GitCommitOptionsConfiguration for the operation(default: {})
Returns
boolean
True if there are staged changes ready to commit
Example
Check for staged changes before committing
if (hasStagedChanges()) { createCommit('...') }
§function

hasUnstagedChanges(options: GitCommitOptions): boolean

Checks if there are unstaged changes (working tree dirty).
Parameters
NameTypeDescription
§options
GitCommitOptionsConfiguration for the operation(default: {})
Returns
boolean
True if there are unstaged changes in the working tree
Example
Check for unstaged changes before staging
if (hasUnstagedChanges()) { stage(['.']) }
§function

hasUntrackedFiles(options: GitCommitOptions): boolean

Checks if there are untracked files.
Parameters
NameTypeDescription
§options
GitCommitOptionsConfiguration for the operation(default: {})
Returns
boolean
True if there are untracked files in the working directory
Example

Check for untracked files

if (hasUntrackedFiles()) {
  console.log('New files detected that are not tracked by git')
}
§function

isAnnotatedTag(tag: GitTag): boolean

Checks if a tag is annotated.
Parameters
NameTypeDescription
§tag
GitTagTag to check
Returns
boolean
True if tag is annotated
Example

Check if a tag is annotated

const tag = createAnnotatedTag({ name: 'v1.0.0', commitHash: 'abc123', message: 'Release' })
isAnnotatedTag(tag) // => true
§function

isBranchRef(ref: GitRef): boolean

Checks if a reference is a branch.
Parameters
NameTypeDescription
§ref
GitRefReference to check
Returns
boolean
True if reference is a branch
Example

Check if reference is a branch

isBranchRef({ type: 'branch', name: 'main' }) // => true
§function

isClean(options: GitStatusOptions): boolean

Checks if the working tree is clean (no changes).
Parameters
NameTypeDescription
§options
GitStatusOptionsConfiguration for the status check(default: {})
Returns
boolean
True if working tree is clean with no uncommitted changes
Example
Check if working tree is clean
if (!isClean()) {
  throw new Error('Working tree has changes')
}
§function

isGitRepository(options: GitStatusOptions): boolean

Checks if the directory is a git repository.
Parameters
NameTypeDescription
§options
GitStatusOptionsStatus options(default: {})
Returns
boolean
True if in a git repository
Example
Check if directory is a git repository
if (!isGitRepository()) {
  throw new Error('Not a git repository')
}
§function

isHeadRef(ref: GitRef): boolean

Checks if a reference points to the current HEAD.
Parameters
NameTypeDescription
§ref
GitRefReference to check
Returns
boolean
True if reference is HEAD
Example

Check if reference points to HEAD

isHeadRef({ type: 'head', name: 'HEAD' }) // => true
isHeadRef({ type: 'branch', name: 'main', isHead: true }) // => true
§function

isLightweightTag(tag: GitTag): boolean

Checks if a tag is lightweight.
Parameters
NameTypeDescription
§tag
GitTagTag to check
Returns
boolean
True if tag is lightweight
Example

Check if a tag is lightweight

const tag = createLightweightTag({ name: 'v1.0.0', commitHash: 'abc123' })
isLightweightTag(tag) // => true
§function

isMergeCommit(commit: GitCommit): boolean

Checks if a commit is a merge commit (has multiple parents).
Parameters
NameTypeDescription
§commit
GitCommitCommit to check
Returns
boolean
True if commit has more than one parent
Example

Check if commit is a merge commit

if (isMergeCommit(commit)) {
  console.log('Commit has parents:', commit.parents)
}
§function

isOperationInProgress(options: GitCommitOptions): boolean

Checks if git is in the middle of an incomplete operation.
Convenience wrapper around getOperationState() for simple checks. Use getOperationState() directly when you need to know which operation is in progress.
Parameters
NameTypeDescription
§options
GitCommitOptionsConfiguration for the state check(default: {})
Returns
boolean
True if rebase, merge, or other operation is incomplete
Example
Check for incomplete operations
if (isOperationInProgress()) {
  throw new Error('Complete or abort the current git operation first')
}
§function

isRemoteRef(ref: GitRef): boolean

Checks if a reference is a remote tracking branch.
Parameters
NameTypeDescription
§ref
GitRefReference to check
Returns
boolean
True if reference is a remote
Example

Check if reference is a remote tracking branch

isRemoteRef({ type: 'remote', name: 'main', remote: 'origin' }) // => true
§function

isRootCommit(commit: GitCommit): boolean

Checks if a commit is a root commit (has no parents).
Parameters
NameTypeDescription
§commit
GitCommitCommit to check
Returns
boolean
True if commit has no parents
Example

Check if commit is the initial commit

if (isRootCommit(commit)) {
  console.log('This is the initial commit')
}
§function

isSameCommit(a: GitCommit, b: GitCommit): boolean

Checks if two commits are the same based on their hash.
Parameters
NameTypeDescription
GitCommitFirst commit
GitCommitSecond commit
Returns
boolean
True if commits have the same hash
Example

Compare two commits by hash

isSameCommit(commitA, commitB) // => true if commitA.hash === commitB.hash
§function

isTagRef(ref: GitRef): boolean

Checks if a reference is a tag.
Parameters
NameTypeDescription
§ref
GitRefReference to check
Returns
boolean
True if reference is a tag
Example

Check if reference is a tag

isTagRef({ type: 'tag', name: 'v1.0.0' }) // => true
§function

needsPull(options: GitStatusOptions): boolean

Checks if the repository needs to be pulled.
Parameters
NameTypeDescription
§options
GitStatusOptionsStatus options(default: {})
Returns
boolean
True if there are commits to pull
Example

Check if repository needs to be pulled

if (needsPull()) {
  console.log('Remote commits need to be pulled')
}
§function

needsPush(options: GitStatusOptions): boolean

Checks if the repository needs to be pushed.
Parameters
NameTypeDescription
§options
GitStatusOptionsStatus options(default: {})
Returns
boolean
True if there are unpushed commits
Example

Check if repository needs to be pushed

if (needsPush()) {
  console.log('Local commits need to be pushed')
}
§function

pushTag(name: string, remote: string, options: GitTagOptions): boolean

Pushes a tag to a remote.
Parameters
NameTypeDescription
§name
stringThe tag to push to the remote
§remote
stringRemote name (defaults to 'origin')(default: 'origin')
§options
GitTagOptionsConfiguration for the tag operation(default: {})
Returns
boolean
True if pushed successfully
Example
Push a tag to remote
pushTag('v1.0.0')
pushTag('v1.0.0', 'upstream')
§function

stage(files: unknown, options: StageOptions): boolean

Stages files for commit.
Parameters
NameTypeDescription
§files
unknownArray of file paths relative to working directory
§options
StageOptionsConfiguration for the staging operation(default: {})
Returns
boolean
True if staging succeeded
Example
Stage files for commit
stage(['package.json', 'CHANGELOG.md'])
stage(['.'], { all: true })
§function

stageAll(options: GitCommitOptions): boolean

Stages all changes (tracked and untracked).
Parameters
NameTypeDescription
§options
GitCommitOptionsConfiguration for the staging operation(default: {})
Returns
boolean
True if all changes were successfully added to the index
Example
Stage all tracked and untracked changes
stageAll() // stages all tracked and untracked changes
§function

tagExists(name: string, options: GitTagOptions): boolean

Checks if a tag exists.
Parameters
NameTypeDescription
§name
stringThe tag name to verify
§options
GitTagOptionsConfiguration for the tag operation(default: {})
Returns
boolean
True if tag exists
Example
Check if a tag exists
if (tagExists('v1.0.0')) { ... }
§function

unstage(files: unknown, options: GitCommitOptions): boolean

Unstages files.
Parameters
NameTypeDescription
§files
unknownArray of file paths to remove from staging area
§options
GitCommitOptionsConfiguration for the unstage operation(default: {})
Returns
boolean
True if unstaging succeeded
Example
Unstage files from the index
unstage(['package.json'])

◈ Interfaces

§interface

DiscardChangesOptions

Options for discarding changes.
Properties
§readonly cwd?:stringWorking directory (defaults to cwd)
§readonly files?:unknownFiles or directories to discard. If empty/undefined, discards ALL changes. Paths are relative to the working directory.
§readonly timeout?:numberTimeout in milliseconds
§interface

CreateAnnotatedTagOptions

Options for creating an annotated tag.
Properties
§readonly commitHash:stringTarget commit hash
§readonly message:stringTag message
§readonly name:stringTag name
§readonly tagDate:stringTag date (ISO 8601 format)
§readonly taggerEmail:stringTagger email
§readonly taggerName:stringTagger name
§interface

CreateCommitOptions

Options for creating a commit.
Properties
§readonly allowEmpty?:booleanAllow empty commit (no changes)
§readonly amend?:booleanAmend the last commit
§readonly author?:stringAuthor (format: "Name <email>")
§readonly body?:stringCommit message body (separate from subject)
§readonly cwd?:stringWorking directory (defaults to cwd)
§readonly files?:unknownSpecific files to commit (instead of all staged)
§readonly noEdit?:booleanKeep the existing commit message when amending (requires amend: true)
§readonly noVerify?:booleanDon't run pre-commit hooks
§readonly sign?:booleanSign the commit with GPG
§readonly timeout?:numberTimeout in milliseconds
§interface

CreateGitCommitOptions

Options for creating a git commit model.
Properties
§readonly authorDate:stringAuthor date (ISO 8601 format)
§readonly authorEmail:stringCommit author email
§readonly authorName:stringCommit author name
§readonly body?:stringFull commit body (defaults to empty string)
§readonly commitDate?:stringCommit date (defaults to author date)
§readonly committerEmail?:stringCommitter email (defaults to author)
§readonly committerName?:stringCommitter name (defaults to author)
§readonly hash:stringFull commit hash
§readonly parents?:unknownParent commit hashes (defaults to empty array)
§readonly refs?:unknownAssociated refs (defaults to empty array)
§readonly subject:stringCommit subject (first line of message)
§interface

CreateGitRefOptions

Options for creating a git reference.
Properties
§readonly commitHash:stringTarget commit hash
§readonly fullName:stringFull reference name
§readonly isHead?:booleanWhether this is the current HEAD
§interface

CreateLightweightTagOptions

Options for creating a lightweight tag.
Properties
§readonly commitHash:stringTarget commit hash
§readonly name:stringTag name
§interface

CreateTagOptions

Options for creating a tag.
Properties
§readonly cwd?:stringWorking directory (defaults to cwd)
§readonly force?:booleanForce overwrite if tag exists
§readonly message?:stringTag message (creates annotated tag if provided)
§readonly target?:stringTarget commit (defaults to HEAD)
§readonly timeout?:numberTimeout in milliseconds
§interface

DiffOptions

Options for diff-based queries.
Properties
§readonly cwd?:stringWorking directory (defaults to cwd)
§readonly timeout?:numberTimeout in milliseconds
§interface

FileChange

A file changed in a commit or between refs.
Properties
§readonly oldPath?:stringOriginal path for renames/copies
§readonly path:stringFile path relative to repository root
§readonly status:FileChangeStatusType of change
§interface

FileStatusEntry

Detailed file status.
Properties
§readonly indexStatus:FileStatusIndex (staging area) status
§readonly origPath?:stringOriginal path for renamed/copied files
§readonly path:stringFile path
§readonly workTreeStatus:FileStatusWorking tree status
§interface

GitClient

Git client interface.
Provides a unified interface for all git operations within a specific working directory.
Properties
§readonly cwd:stringWorking directory
§readonly timeout:numberDefault timeout
§interface

GitClientConfig

Git client configuration.
Properties
§readonly cwd?:stringWorking directory
§readonly throwOnError?:booleanWhether to throw on errors
§readonly timeout?:numberDefault timeout in milliseconds
§interface

GitCommit

A git commit with its metadata.
Properties
§readonly authorDate:stringAuthor date (ISO 8601 format)
§readonly authorEmail:stringCommit author email
§readonly authorName:stringCommit author name
§readonly body:stringFull commit body (excludes subject)
§readonly commitDate:stringCommit date (ISO 8601 format)
§readonly committerEmail:stringCommitter email
§readonly committerName:stringCommitter name
§readonly hash:stringFull commit hash (40 characters)
§readonly message:stringFull commit message (subject + body)
§readonly parents:unknownParent commit hashes
§readonly refs:unknownAssociated refs (branches, tags, etc.)
§readonly shortHash:stringAbbreviated commit hash (typically 7 characters)
§readonly subject:stringCommit subject (first line of message)
§interface

GitCommitOptions

Options for commit operations.
Properties
§readonly cwd?:stringWorking directory (defaults to cwd)
§readonly timeout?:numberTimeout in milliseconds
§interface

GitCommitWithFiles

A git commit with file change information.
Properties
§readonly authorDate:stringAuthor date (ISO 8601 format)
§readonly authorEmail:stringCommit author email
§readonly authorName:stringCommit author name
§readonly body:stringFull commit body (excludes subject)
§readonly commitDate:stringCommit date (ISO 8601 format)
§readonly committerEmail:stringCommitter email
§readonly committerName:stringCommitter name
§readonly files:unknownFiles changed in this commit
§readonly hash:stringFull commit hash (40 characters)
§readonly message:stringFull commit message (subject + body)
§readonly parents:unknownParent commit hashes
§readonly refs:unknownAssociated refs (branches, tags, etc.)
§readonly shortHash:stringAbbreviated commit hash (typically 7 characters)
§readonly subject:stringCommit subject (first line of message)
§interface

GitLogOptions

Options for git log operations.
Properties
§readonly author?:stringAuthor to filter by
§readonly cwd?:stringWorking directory (defaults to cwd)
§readonly from?:stringStarting commit reference (inclusive)
§readonly includeMerges?:booleanInclude merge commits
§readonly maxCount?:numberMaximum number of commits to retrieve. Zero retrieves every matching commit.
§readonly path?:stringFile path to filter commits by
§readonly timeout?:numberTimeout in milliseconds
§readonly to?:stringEnding commit reference (exclusive)
§interface

GitOperationState

Result of checking git's operation state.
Properties
§readonly details:GitOperationStateDetailsDetailed state for each check performed. Useful for diagnostics or when multiple states could theoretically overlap.
§readonly inProgress:booleanTrue if git is mid-operation (rebase, merge, etc.)
§readonly reason:GitOperationStateReasonWhich operation is in progress, if any. Returns the first detected state (exit-early pattern).
§interface

GitRef

A git reference.
Properties
§readonly commitHash:stringTarget commit hash
§readonly fullName:stringFull reference name (e.g., refs/heads/main)
§readonly isHead?:booleanWhether this is the current HEAD
§readonly name:stringShort reference name (e.g., main)
§readonly remote?:stringRemote name for remote refs
§readonly type:GitRefTypeReference type
§interface

GitStatusOptions

Options for status operations.
Properties
§readonly cwd?:stringWorking directory (defaults to cwd)
§readonly timeout?:numberTimeout in milliseconds
§interface

GitTag

A git tag with its metadata.
Properties
§readonly commitHash:stringTarget commit hash
§readonly message?:stringTag message (for annotated tags)
§readonly name:stringTag name
§readonly tagDate?:stringTag date (ISO 8601 format, for annotated tags)
§readonly taggerEmail?:stringTagger email (for annotated tags)
§readonly taggerName?:stringTagger name (for annotated tags)
§readonly type:GitTagTypeTag type
§interface

GitTagOptions

Options for tag operations.
Properties
§readonly cwd?:stringWorking directory (defaults to cwd)
§readonly timeout?:numberTimeout in milliseconds
§interface

ListTagsOptions

Options for listing tags.
Properties
§readonly cwd?:stringWorking directory (defaults to cwd)
§readonly maxCount?:numberMaximum number of tags to return
§readonly pattern?:stringPattern to filter tags by (prefix match)
§readonly sortByVersion?:booleanSort by version (descending)
§readonly timeout?:numberTimeout in milliseconds
§interface

RepositoryStatus

Repository status summary.
Properties
§readonly ahead:numberCommits ahead of upstream
§readonly behind:numberCommits behind upstream
§readonly branch:stringCurrent branch name
§readonly clean:booleanWhether working tree is clean
§readonly detached:booleanWhether HEAD is detached
§readonly hasConflicts:booleanWhether there are merge conflicts
§readonly modified:unknownModified files (unstaged)
§readonly staged:unknownStaged files
§readonly untracked:unknownUntracked files
§readonly upstream?:stringUpstream branch (if tracking)
§interface

StageOptions

Options for staging files.
Properties
§readonly all?:booleanStage all changes (including untracked)
§readonly cwd?:stringWorking directory (defaults to cwd)
§readonly force?:booleanForce add (ignore gitignore)
§readonly timeout?:numberTimeout in milliseconds
§readonly update?:booleanUpdate tracked files only

◆ Types

§type

FileChangeStatus

File change status codes matching git conventions.
type FileChangeStatus = "added" | "modified" | "deleted" | "renamed" | "copied"
§type

FileStatus

File status in a git repository.
type FileStatus = "modified" | "added" | "deleted" | "renamed" | "copied" | "untracked" | "ignored" | "unmerged"
§type

GitOperationStateOptions

Options for operation state check.
type GitOperationStateOptions = GitCommitOptions
§type

GitOperationStateReason

Reasons why git may be in an unstable operation state.
These correspond to state files that git creates during multi-step operations:
  • 'rebase-interactive': .git/rebase-merge exists (interactive rebase paused)
  • 'rebase-apply': .git/rebase-apply exists (mailbox-based rebase or git am)
  • 'merge-in-progress': .git/MERGE_HEAD exists (merge awaiting conflict resolution)
type GitOperationStateReason = "rebase-interactive" | "rebase-apply" | "merge-in-progress"
§type

GitRefType

Type of git reference.
type GitRefType = "branch" | "tag" | "remote" | "head" | "stash"
§type

GitTagType

Represents either a lightweight or annotated git tag.
type GitTagType = "lightweight" | "annotated"

● Variables

§type

DEFAULT_COMMIT_OPTIONS

Default commit options.
§type

DEFAULT_DIFF_OPTIONS

Default diff options.
§type

DEFAULT_GIT_CLIENT_CONFIG

Default git client configuration.
§type

DEFAULT_LOG_OPTIONS

Default log options.
§type

DEFAULT_OPERATION_STATE_OPTIONS

Default options for operation state checks.
§type

DEFAULT_STATUS_OPTIONS

Default status options.
§type

DEFAULT_TAG_OPTIONS

Default tag options.