gitutil

package
v0.0.0-...-f9e3ac8 Latest Latest
Warning

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

Go to latest
Published: Apr 30, 2026 License: MIT Imports: 10 Imported by: 0

Documentation

Overview

Package gitutil — branch checkout helpers.

Package gitutil — centralized date display formatting.

Package gitutil extracts Git metadata by running git commands.

Package gitutil — latest-branch core operations.

Package gitutil — latest-branch resolve operations.

Package gitutil — repoid.go derives a stable, transport-neutral identifier from a Git remote URL.

The identifier is the canonical "host/owner/repo" form, lowercased, with the .git suffix and trailing slashes stripped. Two URLs that point at the same repository over different transports (HTTPS vs SSH vs scp-style) collapse to the same string, which makes the value safe to use as a deterministic key for re-cloning, dedup, and cross-export joins.

Examples:

https://github.com/acme/widget.git    -> github.com/acme/widget
git@github.com:acme/widget.git        -> github.com/acme/widget
ssh://git@github.com/acme/widget      -> github.com/acme/widget

Unfamiliar URL shapes are returned lowercased + trimmed but otherwise untouched, so callers can still equality-compare without risking a silent false-match against a different repo.

Index

Constants

View Source
const (
	BranchSourceHEAD           = "HEAD"
	BranchSourceDetached       = "detached"
	BranchSourceRemoteTracking = "remote-tracking"
	BranchSourceDefault        = "default"
	BranchSourceUnknown        = "unknown"
)

Branch source labels describe how a repo's branch was determined.

Variables

This section is empty.

Functions

func CanonicalRepoID

func CanonicalRepoID(raw string) string

CanonicalRepoID collapses an https / ssh / scp-style git URL down to a "host/owner/repo" string suitable for equality comparison and stable cross-format identity. Empty input returns "".

func CheckOnline

func CheckOnline() error

CheckOnline verifies network connectivity by dialing a remote host.

func CheckoutBranch

func CheckoutBranch(repoPath, branch string) (string, error)

CheckoutBranch runs `git -C <repoPath> checkout <branch>` and returns the combined stdout+stderr so callers can surface the user-friendly "Switched to branch 'foo'" / "Already on 'foo'" lines git prints to stderr. We deliberately use CombinedOutput (not Output) because git's progress and status messages all go to stderr.

The branch name is taken verbatim — strip any "origin/" prefix at the caller (see cmd/latestbranchswitch.go) so this helper stays a thin pass-through with one job.

func CurrentBranch

func CurrentBranch(repoPath string) (string, error)

CurrentBranch returns the current branch name for a repo.

func DetectBranch

func DetectBranch(repoPath string) (branch, source string)

DetectBranch returns the branch name and a label describing how it was detected, using constants.DefaultBranch as the last-resort fallback. Equivalent to DetectBranchWithDefault(repoPath, constants.DefaultBranch). Kept as the legacy entry point so existing callers compile unchanged.

func DetectBranchWithDefault

func DetectBranchWithDefault(repoPath, fallback string) (branch, source string)

DetectBranchWithDefault is DetectBranch with a caller-supplied fallback branch name. Resolution order (each step falls through to the next on miss):

  1. HEAD via `git rev-parse --abbrev-ref HEAD` → "HEAD" when on a named branch. NOTE: a detached HEAD or empty result no longer terminates resolution — we fall through to the remote-default lookups so the returned name is always usable for `git clone -b` when possible.
  2. Local remote-tracking ref via `git symbolic-ref refs/remotes/origin/ HEAD` → "remote-tracking". Works when the repo was cloned with `--single-branch` skipped (the common case).
  3. Live remote query via `git ls-remote --symref origin HEAD` → "remote-tracking". Covers single-branch clones and shallow mirrors where step 2's local ref is absent.
  4. Caller-supplied `fallback` → "default". Last-resort guess so callers always have SOMETHING to attempt. When fallback is the empty string, this step is skipped — the function continues to the detached-HEAD / unknown sentinels below so callers that want to *see* "we have nothing" can pass "" instead of a placeholder.

Only when every step fails does the function return ("HEAD", "detached") for an actual detached HEAD or ("", "unknown") for a totally opaque repo — preserving the original sentinels for downstream consumers (cloner/strategy.go) that branch on BranchSource.

func FetchAll

func FetchAll(repoPath string)

FetchAll runs git fetch --all --prune for a repo (best effort).

func FetchAllPrune

func FetchAllPrune() error

FetchAllPrune runs git fetch --all --prune.

func FilterByPattern

func FilterByPattern(refs []string, pattern string) []string

FilterByPattern keeps only refs whose branch name matches the given glob or substring pattern.

func FilterByRemote

func FilterByRemote(refs []string, remote string) []string

FilterByRemote keeps only refs starting with "<remote>/".

func FormatDisplayDate

func FormatDisplayDate(t time.Time) string

FormatDisplayDate converts a time.Time to the local time zone and returns a human-friendly string: DD-Mon-YYYY hh:mm AM/PM.

func FormatDisplayDateUTC

func FormatDisplayDateUTC(t time.Time) string

FormatDisplayDateUTC converts a time.Time to UTC and returns a human-friendly string: DD-Mon-YYYY hh:mm AM/PM (UTC).

func IsInsideWorkTree

func IsInsideWorkTree() bool

IsInsideWorkTree checks if the current directory is inside a git repo.

func IsOnline

func IsOnline() bool

IsOnline returns true if network connectivity is available.

func ListRemoteBranches

func ListRemoteBranches() ([]string, error)

ListRemoteBranches returns trimmed remote-tracking branch names, excluding HEAD pointer lines.

func PrintOfflineWarning

func PrintOfflineWarning()

PrintOfflineWarning prints a user-friendly offline message.

func RemoteURL

func RemoteURL(repoPath string) (string, error)

RemoteURL returns the origin remote URL for a repo at the given path.

func ResolveContains

func ResolveContains(sha, remote string) []string

ResolveContains returns branch names whose history contains sha.

func ResolveDefaultBranchName

func ResolveDefaultBranchName(repoPath string) string

ResolveDefaultBranchName returns the repo's default branch name by asking `git symbolic-ref refs/remotes/origin/HEAD` first, then falling back to constants.DefaultBranch. The returned name is already stripped of the "origin/" prefix and ready for `git checkout`.

This is the engine behind `gitmap branch default` / `gitmap b def`. Kept separate from DetectBranch (which has different semantics — it returns the *current* branch with a "default" sentinel only as a last-resort fallback).

func ResolvePointsAt

func ResolvePointsAt(sha, remote string) []string

ResolvePointsAt returns branch names that point exactly at sha.

func SortByDateDesc

func SortByDateDesc(items []RemoteBranchInfo)

SortByDateDesc sorts items by CommitDate descending.

func SortByNameAsc

func SortByNameAsc(items []RemoteBranchInfo)

SortByNameAsc sorts items by branch name ascending.

func StripRemotePrefix

func StripRemotePrefix(ref string) string

StripRemotePrefix removes the "<remote>/" prefix from a ref.

func TruncSha

func TruncSha(sha string) string

TruncSha returns the first N characters of a SHA for display.

Types

type RemoteBranchInfo

type RemoteBranchInfo struct {
	RemoteRef  string
	CommitDate time.Time
	Sha        string
	Subject    string
}

RemoteBranchInfo holds commit metadata for a remote-tracking branch.

func ReadBranchTips

func ReadBranchTips(refs []string) ([]RemoteBranchInfo, error)

ReadBranchTips reads commit metadata for each remote ref.

type RepoStatus

type RepoStatus struct {
	Branch      string
	Dirty       bool
	Untracked   int
	Modified    int
	Staged      int
	Ahead       int
	Behind      int
	StashCount  int
	Unreachable bool
}

RepoStatus holds the live state of a Git repository.

func Status

func Status(repoPath string) RepoStatus

Status returns the full live status of a repository. If the path does not exist or is not a git repo, Unreachable is set.

Jump to

Keyboard shortcuts

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