@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

Function Allowed Characters
escapeGitRef a-z A-Z 0-9 / - _ . @ ~ ^ { }
escapeGitPath a-z A-Z 0-9 / - _ . (space)
escapeFilePath a-z A-Z 0-9 / - _ . (space)
escapeAuthor a-z A-Z 0-9 - _ . @ < > (space)
escapeGitTagPattern a-z A-Z 0-9 / - _ . @ *

Maximum Input Lengths

Input Type Max Length
Git reference 256
File path 4096
Author string 512
Commit message 10000
Tag pattern 256

See Also

  • workspace/ — Uses git for version coordination
  • flow/ — Orchestrates git commit/tag operations
  • commits/ — Parses conventional commit messages
  • Main README — Package overview and quick start
  • ARCHITECTURE.md — Design principles and data flow

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
string
Commit 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
GitCommitOptions
Configuration 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
DiscardChangesOptions
Configuration 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
string
Full 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
string
The 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
GitRefType
Reference type
§name
string
Reference name
§remote?
string
Remote 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
string
Package name (e.g., '@scope/package' or 'package')
§version
string
Version string (e.g., '1.2.3')
§format
string
Tag 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
string
Commit message (subject line)
§options
CreateCommitOptions
Create 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
string
Commit 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
GitRef
First reference
GitRef
Second 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
GitTag
First tag
GitTag
Second 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
CreateAnnotatedTagOptions
Tag 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
string
Text 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
GitClientConfig
Client 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
CreateGitCommitOptions
Commit 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
CreateGitRefOptions
Reference 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
CreateLightweightTagOptions
Tag 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
string
The name for the new tag
§options
CreateTagOptions
Configuration 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
string
The tag name to delete
§options
GitTagOptions
Configuration 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
string
Author 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
string
Path 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
string
Argument 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
string
Message 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
string
Path 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
string
Reference 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
string
Pattern 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
string
Tag 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
string
Commit 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
string
Commit 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
string
Tag 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
unknown
References to filter
§remote
string
Remote 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
unknown
References to filter
§type
GitRefType
Type 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
GitStatusOptions
Status 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
GitStatusOptions
Status 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
string
Base reference (e.g., 'origin/main', 'v1.0.0')
§head
string
Head reference (defaults to 'HEAD')
(default: 'HEAD')
§options
DiffOptions
Additional 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
string
Base reference
§head
string
Head reference (defaults to 'HEAD')
(default: 'HEAD')
§options
DiffOptions
Additional 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
string
Commit 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
GitLogOptions
Configuration 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
string
Starting reference (exclusive)
§to
string
Ending 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
string
Reference 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
string
Commit hash (full or abbreviated)
§options
DiffOptions
Additional 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
GitCommitOptions
Configuration 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
GitCommitOptions
Git 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
GitStatusOptions
Status 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
GitStatusOptions
Status 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
ListTagsOptions
Tag 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
GitStatusOptions
Status 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
GitCommitOptions
Configuration 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
GitRef
Reference 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
GitStatusOptions
Status 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
GitStatusOptions
Status 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
GitStatusOptions
Configuration 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
string
The tag name to look up
§options
GitTagOptions
Configuration 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
ListTagsOptions
Tag 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
string
Package name to match
§options
ListTagsOptions
Tag 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
GitStatusOptions
Status 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
GitStatusOptions
Status 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
GitCommitOptions
Configuration 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
GitCommitOptions
Configuration 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
GitCommitOptions
Configuration 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
GitTag
Tag 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
GitRef
Reference 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
GitStatusOptions
Configuration 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
GitStatusOptions
Status 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
GitRef
Reference 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
GitTag
Tag 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
GitCommit
Commit 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
GitCommitOptions
Configuration 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
GitRef
Reference 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
GitCommit
Commit 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
GitCommit
First commit
GitCommit
Second 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
GitRef
Reference 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
GitStatusOptions
Status 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
GitStatusOptions
Status 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
string
The tag to push to the remote
§remote
string
Remote name (defaults to 'origin')
(default: 'origin')
§options
GitTagOptions
Configuration 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
unknown
Array of file paths relative to working directory
§options
StageOptions
Configuration 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
GitCommitOptions
Configuration 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
string
The tag name to verify
§options
GitTagOptions
Configuration 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
unknown
Array of file paths to remove from staging area
§options
GitCommitOptions
Configuration 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?:string
Working directory (defaults to cwd)
§readonly files?:unknown
Files or directories to discard. If empty/undefined, discards ALL changes. Paths are relative to the working directory.
§readonly timeout?:number
Timeout in milliseconds
§interface

CreateAnnotatedTagOptions

Options for creating an annotated tag.

Properties

§readonly commitHash:string
Target commit hash
§readonly message:string
Tag message
§readonly name:string
Tag name
§readonly tagDate:string
Tag date (ISO 8601 format)
§readonly taggerEmail:string
Tagger email
§readonly taggerName:string
Tagger name
§interface

CreateCommitOptions

Options for creating a commit.

Properties

§readonly allowEmpty?:boolean
Allow empty commit (no changes)
§readonly amend?:boolean
Amend the last commit
§readonly author?:string
Author (format: "Name <email>")
§readonly body?:string
Commit message body (separate from subject)
§readonly cwd?:string
Working directory (defaults to cwd)
§readonly files?:unknown
Specific files to commit (instead of all staged)
§readonly noEdit?:boolean
Keep the existing commit message when amending (requires amend: true)
§readonly noVerify?:boolean
Don't run pre-commit hooks
§readonly sign?:boolean
Sign the commit with GPG
§readonly timeout?:number
Timeout in milliseconds
§interface

CreateGitCommitOptions

Options for creating a git commit model.

Properties

§readonly authorDate:string
Author date (ISO 8601 format)
§readonly authorEmail:string
Commit author email
§readonly authorName:string
Commit author name
§readonly body?:string
Full commit body (defaults to empty string)
§readonly commitDate?:string
Commit date (defaults to author date)
§readonly committerEmail?:string
Committer email (defaults to author)
§readonly committerName?:string
Committer name (defaults to author)
§readonly hash:string
Full commit hash
§readonly parents?:unknown
Parent commit hashes (defaults to empty array)
§readonly refs?:unknown
Associated refs (defaults to empty array)
§readonly subject:string
Commit subject (first line of message)
§interface

CreateGitRefOptions

Options for creating a git reference.

Properties

§readonly commitHash:string
Target commit hash
§readonly fullName:string
Full reference name
§readonly isHead?:boolean
Whether this is the current HEAD
§interface

CreateLightweightTagOptions

Options for creating a lightweight tag.

Properties

§readonly commitHash:string
Target commit hash
§readonly name:string
Tag name
§interface

CreateTagOptions

Options for creating a tag.

Properties

§readonly cwd?:string
Working directory (defaults to cwd)
§readonly force?:boolean
Force overwrite if tag exists
§readonly message?:string
Tag message (creates annotated tag if provided)
§readonly target?:string
Target commit (defaults to HEAD)
§readonly timeout?:number
Timeout in milliseconds
§interface

DiffOptions

Options for diff-based queries.

Properties

§readonly cwd?:string
Working directory (defaults to cwd)
§readonly timeout?:number
Timeout in milliseconds
§interface

FileChange

A file changed in a commit or between refs.

Properties

§readonly oldPath?:string
Original path for renames/copies
§readonly path:string
File path relative to repository root
§readonly status:FileChangeStatus
Type of change
§interface

FileStatusEntry

Detailed file status.

Properties

§readonly indexStatus:FileStatus
Index (staging area) status
§readonly origPath?:string
Original path for renamed/copied files
§readonly path:string
File path
§readonly workTreeStatus:FileStatus
Working tree status
§interface

GitClient

Git client interface.
Provides a unified interface for all git operations within a specific working directory.

Properties

§readonly cwd:string
Working directory
§readonly timeout:number
Default timeout
§interface

GitClientConfig

Git client configuration.

Properties

§readonly cwd?:string
Working directory
§readonly throwOnError?:boolean
Whether to throw on errors
§readonly timeout?:number
Default timeout in milliseconds
§interface

GitCommit

A git commit with its metadata.

Properties

§readonly authorDate:string
Author date (ISO 8601 format)
§readonly authorEmail:string
Commit author email
§readonly authorName:string
Commit author name
§readonly body:string
Full commit body (excludes subject)
§readonly commitDate:string
Commit date (ISO 8601 format)
§readonly committerEmail:string
Committer email
§readonly committerName:string
Committer name
§readonly hash:string
Full commit hash (40 characters)
§readonly message:string
Full commit message (subject + body)
§readonly parents:unknown
Parent commit hashes
§readonly refs:unknown
Associated refs (branches, tags, etc.)
§readonly shortHash:string
Abbreviated commit hash (typically 7 characters)
§readonly subject:string
Commit subject (first line of message)
§interface

GitCommitOptions

Options for commit operations.

Properties

§readonly cwd?:string
Working directory (defaults to cwd)
§readonly timeout?:number
Timeout in milliseconds
§interface

GitCommitWithFiles

A git commit with file change information.

Properties

§readonly authorDate:string
Author date (ISO 8601 format)
§readonly authorEmail:string
Commit author email
§readonly authorName:string
Commit author name
§readonly body:string
Full commit body (excludes subject)
§readonly commitDate:string
Commit date (ISO 8601 format)
§readonly committerEmail:string
Committer email
§readonly committerName:string
Committer name
§readonly files:unknown
Files changed in this commit
§readonly hash:string
Full commit hash (40 characters)
§readonly message:string
Full commit message (subject + body)
§readonly parents:unknown
Parent commit hashes
§readonly refs:unknown
Associated refs (branches, tags, etc.)
§readonly shortHash:string
Abbreviated commit hash (typically 7 characters)
§readonly subject:string
Commit subject (first line of message)
§interface

GitLogOptions

Options for git log operations.

Properties

§readonly author?:string
Author to filter by
§readonly cwd?:string
Working directory (defaults to cwd)
§readonly from?:string
Starting commit reference (inclusive)
§readonly includeMerges?:boolean
Include merge commits
§readonly maxCount?:number
Maximum number of commits to retrieve
§readonly path?:string
File path to filter commits by
§readonly timeout?:number
Timeout in milliseconds
§readonly to?:string
Ending commit reference (exclusive)
§interface

GitOperationState

Result of checking git's operation state.

Properties

§readonly details:GitOperationStateDetails
Detailed state for each check performed. Useful for diagnostics or when multiple states could theoretically overlap.
§readonly inProgress:boolean
True if git is mid-operation (rebase, merge, etc.)
§readonly reason:GitOperationStateReason
Which operation is in progress, if any. Returns the first detected state (exit-early pattern).
§interface

GitRef

A git reference.

Properties

§readonly commitHash:string
Target commit hash
§readonly fullName:string
Full reference name (e.g., refs/heads/main)
§readonly isHead?:boolean
Whether this is the current HEAD
§readonly name:string
Short reference name (e.g., main)
§readonly remote?:string
Remote name for remote refs
§readonly type:GitRefType
Reference type
§interface

GitStatusOptions

Options for status operations.

Properties

§readonly cwd?:string
Working directory (defaults to cwd)
§readonly timeout?:number
Timeout in milliseconds
§interface

GitTag

A git tag with its metadata.

Properties

§readonly commitHash:string
Target commit hash
§readonly message?:string
Tag message (for annotated tags)
§readonly name:string
Tag name
§readonly tagDate?:string
Tag date (ISO 8601 format, for annotated tags)
§readonly taggerEmail?:string
Tagger email (for annotated tags)
§readonly taggerName?:string
Tagger name (for annotated tags)
§readonly type:GitTagType
Tag type
§interface

GitTagOptions

Options for tag operations.

Properties

§readonly cwd?:string
Working directory (defaults to cwd)
§readonly timeout?:number
Timeout in milliseconds
§interface

ListTagsOptions

Options for listing tags.

Properties

§readonly cwd?:string
Working directory (defaults to cwd)
§readonly maxCount?:number
Maximum number of tags to return
§readonly pattern?:string
Pattern to filter tags by (prefix match)
§readonly sortByVersion?:boolean
Sort by version (descending)
§readonly timeout?:number
Timeout in milliseconds
§interface

RepositoryStatus

Repository status summary.

Properties

§readonly ahead:number
Commits ahead of upstream
§readonly behind:number
Commits behind upstream
§readonly branch:string
Current branch name
§readonly clean:boolean
Whether working tree is clean
§readonly detached:boolean
Whether HEAD is detached
§readonly hasConflicts:boolean
Whether there are merge conflicts
§readonly modified:unknown
Modified files (unstaged)
§readonly staged:unknown
Staged files
§readonly untracked:unknown
Untracked files
§readonly upstream?:string
Upstream branch (if tracking)
§interface

StageOptions

Options for staging files.

Properties

§readonly all?:boolean
Stage all changes (including untracked)
§readonly cwd?:string
Working directory (defaults to cwd)
§readonly force?:boolean
Force add (ignore gitignore)
§readonly timeout?:number
Timeout in milliseconds
§readonly update?:boolean
Update 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.