gitutil

package
v2.1.9 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 17, 2026 License: Apache-2.0 Imports: 12 Imported by: 0

Documentation

Index

Constants

View Source
const (
	ReviewStateApproved         = "APPROVED"
	ReviewStateChangesRequested = "CHANGES_REQUESTED"
	ReviewStateCommented        = "COMMENTED"
)
View Source
const DefaultMinChecks = 1
View Source
const GhDelim = "|stackeddiff-delim|"

Variables

This section is empty.

Functions

func ApplyDiffFromRef added in v2.1.4

func ApplyDiffFromRef(fromRef string, toRef string)

ApplyDiffFromRef diffs fromRef..toRef, applies the result to the working tree, and stages all changes.

func CheckLocalBranches added in v2.1.4

func CheckLocalBranches(gitDir string, branchNames []string) []string

CheckLocalBranches returns the subset of branchNames that exist as local branches.

func CherryPick added in v2.1.9

func CherryPick(options util.ExecuteOptions, gitDir string, commits ...string) (string, error)

CherryPick cherry-picks all commits with --ff and skips any that are empty (i.e., commits that are already on main and would result in no changes). Uses [cherryPickWithRetry] to recover from index.lock contention.

func CherryPickOrDie added in v2.1.9

func CherryPickOrDie(options util.ExecuteOptions, gitDir string, commits ...string)

CherryPick cherry-picks all commits with --ff and skips any that are empty (i.e., commits that are already on main and would result in no changes). Uses [cherryPickWithRetry] to recover from index.lock contention.

func GetAllApprovingUsers

func GetAllApprovingUsers(branchName string) []string

Returns users that have already approved the latest commit. This uses the "reviews" field filtered by commit OID, unlike GetPullRequestStatus which uses "latestReviews" (the latest review per user, regardless of commit).

Example output of gh pr view:

$ gh pr view mybranch --json "reviews"

{
  "reviews": [
    {
      "id": "PRR_kwDODeVIac6f37Qq",
      "author": {
        "login": "mybestie"
      },
      "authorAssociation": "MEMBER",
      "body": "",
      "submittedAt": "2025-03-13T14:47:31Z",
      "includesCreatedEdit": false,
      "reactionGroups": [],
      "state": "COMMENTED",
      "commit": {
        "oid": "af01bdf8eb5649956096a608717f7de5eeb97e45"
      }
    },
    {
      "id": "PRR_kwDODeVIac6f5jeG",
      "author": {
        "login": "myfave"
      },
      "authorAssociation": "MEMBER",
      "body": "",
      "submittedAt": "2025-03-13T16:32:44Z",
      "includesCreatedEdit": false,
      "reactionGroups": [],
      "state": "APPROVED",
      "commit": {
        "oid": "af01bdf8eb5649956096a608717f7de5eeb97e45"
      }
    }
  ]
}

func GetBranchLatestCommit

func GetBranchLatestCommit(branchName string) string

Returns full commit hash of branch with name of branchName, or "" if no such branch.

func GetEmailLocalPart added in v2.1.4

func GetEmailLocalPart() string

GetEmailLocalPart returns the local-part (before the @) of the git user.email config value.

func GetLocalHasBranchOrDie

func GetLocalHasBranchOrDie(branchName string) bool

func GetLocalMainBranchOrDie

func GetLocalMainBranchOrDie() string

Returns name of the local main branch, or panics if it cannot be determined. The result is cached after the first call.

func GetLoggedInUsername

func GetLoggedInUsername() string

func GetMainBranchForHelp

func GetMainBranchForHelp() string

Returns name of main branch, or "main" if cannot be determined. For use by CLI help.

func GetMainWorktreePath

func GetMainWorktreePath() string

Returns the path of the main worktree. Panics if it cannot be determined.

func GetMergeBaseWithOriginMain added in v2.1.4

func GetMergeBaseWithOriginMain(branchName string) string

GetMergeBaseWithOriginMain returns the merge-base (divergence point) between branchName and origin/main.

func GetRemoteMainBranchOrDie

func GetRemoteMainBranchOrDie() string

Returns name of the remote main branch, or panics if it cannot be determined. Handles initial repository setup (setting origin/HEAD) if needed. The result is cached after the first call.

func GetRepoHostname

func GetRepoHostname() string

func GetRepoNameWithOwner

func GetRepoNameWithOwner() string

Returns "repository-owner/repository-name" for the origin remote. Uses the origin URL explicitly so that forks resolve to the fork itself, not the parent repository.

func GhRepoArgs added in v2.1.4

func GhRepoArgs() []string

GhRepoArgs returns "--repo", "owner/repo" for use with gh pr subcommands when in a fork, or an empty slice when not in a fork.

func GitPush added in v2.1.5

func GitPush(options util.ExecuteOptions, args ...string) (string, error)

GitPush runs "git push" with the given args. If the push fails because of missing LFS objects (error contains "git lfs push --all"), it pushes LFS objects first and retries the push.

func GitPushOrDie added in v2.1.5

func GitPushOrDie(options util.ExecuteOptions, args ...string) string

GitPushOrDie is like GitPush but panics on failure.

func GitSwitch

func GitSwitch(branchName string)

func IsAncestor added in v2.1.9

func IsAncestor(ancestor string, descendant string) bool

IsAncestor reports whether ancestor is reachable from descendant through parent relationships (git merge-base --is-ancestor exits 0 when true, 1 when false).

func IsSecondaryWorktree

func IsSecondaryWorktree() bool

Returns true if running in a secondary worktree (not the main worktree).

func PopStash

func PopStash(popStash bool)

func PrependGitDir

func PrependGitDir(dir string, args ...string) []string

PrependGitDir prepends "-C", dir to args if dir is non-empty. This causes git to run as if invoked from that directory.

func RebaseAndSkipAllEmpty

func RebaseAndSkipAllEmpty(options util.ExecuteOptions, otherRebaseArgs ...string) (string, error)

func RebaseAndSkipAllEmptyOrDie

func RebaseAndSkipAllEmptyOrDie(options util.ExecuteOptions, otherRebaseArgs ...string) string

func RemoteHasBranch

func RemoteHasBranch(branchName string) bool

Returns whether branchName is on remote.

func RequireMainBranch

func RequireMainBranch()

func ResetCacheForTesting

func ResetCacheForTesting()

ResetCacheForTesting clears all cached values. For use in tests only.

func Stash

func Stash(forName string) bool

func WithStashAndRollback

func WithStashAndRollback(stashName string, fn func(rollbackManager *GitRollbackManager))

WithStashAndRollback wraps the common pattern of stashing, saving rollback state, executing a function, and restoring on error. The callback receives the rollback manager so it can call SaveState() or CreatedBranch() as needed.

Types

type GitRollbackManager

type GitRollbackManager struct {
	// contains filtered or unexported fields
}

func (*GitRollbackManager) Clear

func (rollbackManager *GitRollbackManager) Clear()

func (*GitRollbackManager) CreatedBranch

func (rollbackManager *GitRollbackManager) CreatedBranch(branchName string)

func (*GitRollbackManager) Restore

func (rollbackManager *GitRollbackManager) Restore(err any)

func (*GitRollbackManager) SaveState

func (rollbackManager *GitRollbackManager) SaveState()

func (*GitRollbackManager) SkipRestore

func (rollbackManager *GitRollbackManager) SkipRestore()

type LatestReview

type LatestReview struct {
	Login        string
	State        string
	BodyLength   int
	CommentCount int
	// OnLatestCommit is true when the review was submitted against the PR's
	// latest commit. Comments left on older commits are considered stale.
	OnLatestCommit bool
}

func (LatestReview) HasComments

func (r LatestReview) HasComments() bool

HasComments reports whether the review has meaningful comments on the latest commit. Comments left on older commits are ignored so that stale feedback does not keep surfacing after the PR has been updated.

type PrInfo

type PrInfo struct {
	Number string
	Title  string
	State  string
	Body   string
}

PrInfo holds information about a pull request

func GetMergedPR

func GetMergedPR(branchName string) *PrInfo

GetMergedPR checks if a branch has a merged pull request. Returns the PR information if found, nil otherwise.

func GetUnmergedPR

func GetUnmergedPR(branchName string) *PrInfo

GetUnmergedPR checks if a branch has an open (unmerged) pull request. Returns the PR information if found, nil otherwise.

type PullRequestChecksStatus

type PullRequestChecksStatus struct {
	Pending   int
	Failing   int
	Passing   int
	MinChecks int
}

func (PullRequestChecksStatus) IsFailing

func (s PullRequestChecksStatus) IsFailing() bool

func (PullRequestChecksStatus) IsSuccess

func (s PullRequestChecksStatus) IsSuccess() bool

func (PullRequestChecksStatus) PercentageComplete

func (s PullRequestChecksStatus) PercentageComplete() float32

func (PullRequestChecksStatus) Total

func (s PullRequestChecksStatus) Total() int

type PullRequestState

type PullRequestState int
const (
	PullRequestStateClosed PullRequestState = iota
	PullRequestStateOpen
	PullRequestStateMerged
)

type PullRequestStatus

type PullRequestStatus struct {
	Checks         PullRequestChecksStatus
	State          PullRequestState
	TotalReviewers int
	LatestReviews  []LatestReview
	CanMerge       bool
	IsDraft        bool
	IsInMergeQueue bool
}

func GetPullRequestStatus

func GetPullRequestStatus(branchName string, minChecks int) PullRequestStatus

GetPullRequestStatus fetches PR status via a single gh api graphql call using a jq query that produces CSV lines. Example output:

rateLimit,1,4999,5000,2025-01-01T00:00:00Z
headCommit,af01bdf8eb5649956096a608717f7de5eeb97e45
check,COMPLETED,SUCCESS,
check,,,SUCCESS
state,OPEN
reviewRequestCount,3
latestReview,someuser,APPROVED,4,0,af01bdf8eb5649956096a608717f7de5eeb97e45
latestReview,otheruser,CHANGES_REQUESTED,0,2,0000000000000000000000000000000000000000
mergeStateStatus,CLEAN
isDraft,false
autoMerge,false

type WorktreeInfo

type WorktreeInfo struct {
	Path           string
	BranchOrCommit string
}

WorktreeInfo holds the path and branch name (or commit hash for detached HEAD) of a git worktree.

func GetSecondaryWorktrees

func GetSecondaryWorktrees() []WorktreeInfo

GetSecondaryWorktrees returns all secondary worktrees (excludes the main worktree).

func GetWorktrees

func GetWorktrees() []WorktreeInfo

GetWorktrees returns all worktrees. The first entry (index 0) is always the main worktree. Panics if git worktree list fails. For worktrees on a detached HEAD, BranchOrCommit is set to the commit hash.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL