zerogit

package
v0.12.0 Latest Latest
Warning

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

Go to latest
Published: Nov 3, 2026 License: MIT Imports: 14 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Index

Constants

View Source
const ChangeContractVersion = "zero.changes.report.v1"
View Source
const RuntimeGo = "go"

Variables

View Source
var ErrCompareAndSwapConflict = errors.New("compare-and-swap conflict")

ErrCompareAndSwapConflict reports that a ref changed since the expected tip was captured, so the compare-and-swap form of update-ref refused to move it. Callers distinguish this from an ordinary update-ref failure because it means someone else advanced the ref concurrently rather than that the write itself is broken, and destroying work to "recover" from it would be wrong.

Functions

func BuildBranchName

func BuildBranchName(gitUser, slug string) string

BuildBranchName composes a "<user>/<slug>" branch name from a git identity and a short feature slug (the convention used across Gitlawb tooling). Empty or unsafe inputs fall back to "user" and "changes" respectively so the result is always a valid, non-empty branch name.

func CommitsAhead

func CommitsAhead(ctx context.Context, cwd, remote, branch string, runGit Runner) (int, error)

CommitsAhead reports how many commits HEAD is ahead of the remote-tracking ref <remote>/<branch> or the advertised branch on a direct remote. Auto-branching runs this before creating and pushing a feature branch off the default branch: a clean, up-to-date default branch has nothing to publish, so the caller can refuse rather than push an empty comparison. It returns an error when the count cannot be determined (for example the remote-tracking ref was never fetched); callers treat that as a hard failure rather than guessing that there is something to publish.

func CurrentBranch

func CurrentBranch(ctx context.Context, cwd string, runGit Runner) string

CurrentBranch returns the short name of the currently checked-out branch, or "" when HEAD is detached / unresolvable. Callers that need the branch's configured upstream (for example the --yes unborn-remote preflight) use this instead of IsDefaultBranch so a remote-HEAD lookup failure does not block remote resolution.

func CurrentBranchTip

func CurrentBranchTip(ctx context.Context, cwd string, runGit Runner) string

CurrentBranchTip returns the SHA of the currently checked-out commit (HEAD^{commit}), or "" when HEAD is detached or unresolvable. ensureFeatureBranch uses this as the compare-and-swap old value when it restores the original default branch after creating a feature branch, so a concurrent advance of the default ref is refused instead of rewound.

func CurrentGitUser

func CurrentGitUser(ctx context.Context, cwd string, runGit Runner) string

CurrentGitUser resolves an identity to prefix generated branch names with: git config user.name, falling back to the OS account username, falling back to the literal "user" so BuildBranchName always gets a non-empty input.

func DeleteBranch

func DeleteBranch(ctx context.Context, cwd, fallbackBranch, branchToDelete string, runGit Runner) error

DeleteBranch switches to fallbackBranch and deletes branchToDelete.

func GenerateMessage

func GenerateMessage(summary ChangeSummary) string

func HeadCommitSubject

func HeadCommitSubject(ctx context.Context, cwd string, runGit Runner) string

HeadCommitSubject returns the subject line of the HEAD commit, or "" when it cannot be resolved (empty repository, not a git directory). Callers use it to name the branch for a push that follows a commit, where the working tree is already clean and a diff-based name would be empty.

func IsDefaultBranch

func IsDefaultBranch(ctx context.Context, options DefaultBranchOptions) (bool, string, string, error)

IsDefaultBranch reports whether options.Branch (or, if empty, the current branch) is the repository's default/protected branch, using the same check Push already applies before refusing to push straight to it. It returns the resolved branch name and remote alongside the bool so callers that left them empty don't need a second lookup: the remote is resolved exactly the way Push resolves it (explicit option, then the branch's configured upstream, then "origin"), so a caller can thread the same remote through a later Push instead of letting a freshly created branch with no tracking configuration silently fall back to "origin".

func IsNamedRemote

func IsNamedRemote(ctx context.Context, cwd, remote string, runGit Runner) bool

IsNamedRemote reports whether remote is shaped like a remote NAME (such as "origin", "upstream", or "team/upstream") rather than a direct URL (https://..., git@...) or a file path (/path/to/repo, C:\path\to\repo). It does not consult git config, so a name that is not configured (a typo) still reports true; the subsequent git command surfaces that failure. ctx, cwd, and runGit are accepted for signature stability with the other remote helpers and are unused.

func IsUnbornRemote

func IsUnbornRemote(ctx context.Context, cwd, remote string, runGit Runner) (bool, error)

IsUnbornRemote reports whether remote is a freshly created repository with no refs at all (no branches, no HEAD). ensureFeatureBranch consults this when CommitsAhead fails to determine why: a genuinely empty remote has no <remote>/<branch> tracking ref for CommitsAhead to diff against, and that is proof there is nothing published yet, not an unknown state to fail closed on. An error here (unreachable remote, timeout) leaves the state unconfirmed, so callers must treat that the same as a non-empty remote.

func RefreshTrackingRef

func RefreshTrackingRef(ctx context.Context, cwd, remote, branch string, runGit Runner) error

RefreshTrackingRef updates the local remote-tracking ref for <remote>/<branch> from the remote's current advertised tip. ensureFeatureBranch calls this before CommitsAhead: IsDefaultBranch already contacted the remote for its symref check, but a merely-cached origin/main (last written at clone or a previous fetch) can sit behind the remote's live tip, making a local-only rev-list comparison report nothing to publish when the remote has actually advanced. When remote is a raw URL or path, no remote-tracking ref is maintained and this call is a no-op.

func RemoteHasBranch

func RemoteHasBranch(ctx context.Context, cwd, remote, branch string, runGit Runner) (bool, error)

RemoteHasBranch reports whether remote already has refs/heads/<branch>. ensureFeatureBranch uses this on every non-default-branch push (not just when local upstream config is missing or wrong): a prior push may have published the branch even when push -u failed to write .git/config, and the nonexistence lease must not be reasserted against a ref that already exists on the remote.

This is existence-only, not tip equality. ensureFeatureBranch already covers the concurrent-creator race this could be mistaken for protecting: when the branch exists, it drops to a plain push and relies on Git's own fast-forward check as the safety net (see TestRunChangesPushDropsLeaseWhenBranchExistsOnRemote), so a survivor of a branch-name race with unrelated history is rejected there, not here. A tip-equality check here instead breaks the ordinary case: after publishing once, a second local commit makes HEAD outrun the remote tip, so this would report false, Push would reassert the empty-value force-with-lease=<branch>: (branch must not exist), and Git would reject the plain follow-up push with a stale-info error against a ref that plainly exists.

func ResetBranchRef

func ResetBranchRef(ctx context.Context, cwd, branch, newTip string, runGit Runner, expectedOld ...string) error

ResetBranchRef points the local branch ref at newTip without checking the branch out. ensureFeatureBranch uses this after creating a feature branch that owns the publishable commits: the normal flow commits on the default branch first, then creates user/slug at the same HEAD, and without this restore the local default keeps those commits and diverges from the remote after a squash-merge. newTip is typically the remote-tracking ref (origin/main) that CommitsAhead already used. Refuses to move the currently checked-out branch so callers must have already switched to the feature branch.

func ResolveRemoteBranchTip

func ResolveRemoteBranchTip(ctx context.Context, cwd, remote, branch string, runGit Runner) (string, error)

ResolveRemoteBranchTip returns the commit SHA that branch points to on remote. ensureFeatureBranch uses this as the restore target after auto-branching, and that target must never be a bare local branch name: resolving "main" yields the very commit the just-created feature branch owns, which makes the restore a silent no-op and leaves the publishable commits on the default branch. For a named remote the SHA comes from the local remote-tracking ref (which RefreshTrackingRef has just updated); for a direct URL or path it is resolved from the remote's advertised heads. It fails closed when no such commit exists rather than letting the caller substitute a local branch name.

func SlugifyBranchComponent

func SlugifyBranchComponent(s string) string

SlugifyBranchComponent lowercases s and collapses any run of non alphanumeric characters into a single hyphen, trimming leading/trailing hyphens and capping length so the result is a safe, short branch-name component.

func UpstreamRef

func UpstreamRef(ctx context.Context, cwd, branch string, runGit Runner) string

UpstreamRef returns the full upstream reference name for branch (e.g. "origin/feature-1" or "upstream/main"), or the empty string if no upstream or the ref cannot be resolved. Callers that need to know whether Zero's own `push -u` published exactly <remote>/<branch> compare this string rather than reading branch.<name>.remote alone: with branch.autoSetupMerge=inherit, `git checkout -b` copies remote=origin and merge=refs/heads/main from the source branch before any push, so a remote config field is not publication state.

func UpstreamRemote

func UpstreamRemote(ctx context.Context, cwd, branch string, runGit Runner) string

UpstreamRemote returns the configured upstream remote name for branch (e.g. "origin"), or "" if no upstream is configured. This alone is not proof of publication: branch.autoSetupMerge=inherit copies branch.<name>.remote from the source branch before any push. Prefer UpstreamRef when checking that <remote>/<branch> was actually published.

func UpstreamRemoteAndMergeBranch

func UpstreamRemoteAndMergeBranch(ctx context.Context, cwd, branch string, runGit Runner) (remote string, mergeBranch string)

UpstreamRemoteAndMergeBranch returns the configured upstream remote and merge branch for branch from git config branch.<name>.remote and branch.<name>.merge.

func ValidateMessage

func ValidateMessage(message string) error

Types

type BranchOptions

type BranchOptions struct {
	Cwd    string
	Name   string // full branch name, e.g. "alice/fix-typo"
	DryRun bool
	RunGit Runner
	// Remote, when non-empty, is the remote the new branch will be pushed
	// to; its branch names are treated as taken when resolving collisions,
	// so a remote-only stale branch (e.g. an old merged PR) is never
	// fast-forwarded with unrelated new work.
	Remote string
}

BranchOptions configures creating and checking out a new local branch.

type BranchResult

type BranchResult struct {
	Branch string `json:"branch"`
}

BranchResult reports the branch that was (or, in dry-run, would be) created.

func CreateBranch

func CreateBranch(ctx context.Context, options BranchOptions) (BranchResult, error)

CreateBranch checks out a new local branch named options.Name off the current HEAD. DryRun returns the requested trimmed name without collision resolution or repository mutation; a real run may append a numeric suffix when the name is already taken locally or on the remote.

type ChangeSnapshot

type ChangeSnapshot struct {
	Contract  string       `json:"contract"`
	Runtime   string       `json:"runtime"`
	Root      string       `json:"root"`
	Branch    string       `json:"branch,omitempty"`
	Base      string       `json:"base,omitempty"`
	Commit    string       `json:"commit,omitempty"`
	Clean     bool         `json:"clean"`
	Files     []FileChange `json:"files"`
	DiffStat  string       `json:"diffStat,omitempty"`
	Diff      string       `json:"diff,omitempty"`
	Truncated bool         `json:"truncated,omitempty"`
	Events    []Event      `json:"events"`
}

func SnapshotFromSummary

func SnapshotFromSummary(summary ChangeSummary) ChangeSnapshot

type ChangeSummary

type ChangeSummary struct {
	Root      string       `json:"root"`
	Branch    string       `json:"branch,omitempty"`
	Base      string       `json:"base,omitempty"`
	Commit    string       `json:"commit,omitempty"`
	Clean     bool         `json:"clean"`
	Files     []FileChange `json:"files"`
	DiffStat  string       `json:"diffStat,omitempty"`
	Diff      string       `json:"diff,omitempty"`
	Truncated bool         `json:"truncated,omitempty"`
}

func Inspect

func Inspect(ctx context.Context, options InspectOptions) (ChangeSummary, error)

type CommandResult

type CommandResult struct {
	Stdout   string
	Stderr   string
	ExitCode int
}

type CommitOptions

type CommitOptions struct {
	Cwd          string
	Message      string
	DryRun       bool
	MaxDiffBytes int
	RunGit       Runner
	RunGitEnv    EnvRunner
}

type CommitResult

type CommitResult struct {
	Root       string        `json:"root"`
	Message    string        `json:"message"`
	DryRun     bool          `json:"dryRun"`
	Committed  bool          `json:"committed"`
	CommitHash string        `json:"commitHash,omitempty"`
	Before     ChangeSummary `json:"before"`
}

func Commit

func Commit(ctx context.Context, options CommitOptions) (CommitResult, error)

type DefaultBranchOptions

type DefaultBranchOptions struct {
	Cwd    string
	Remote string
	Branch string // empty resolves the current branch
	RunGit Runner
}

DefaultBranchOptions resolves whether a branch is the repository's default/protected branch.

type DiffStat

type DiffStat struct {
	FilesChanged int
	Insertions   int
	Deletions    int
}

DiffStat is the parsed summary line of a `git diff --stat` invocation. The summary line ("N files changed, A insertions(+), B deletions(-)") carries no secret-bearing tokens, so it is safe to parse from an already-redacted stat.

func ParseDiffStat

func ParseDiffStat(stat string) DiffStat

ParseDiffStat extracts file/insertion/deletion counts from the trailing summary line of a `git diff --stat` output, e.g. "3 files changed, 12 insertions(+), 4 deletions(-)". Missing insertion or deletion clauses default to zero, and any malformed input yields a zero-value DiffStat without panicking.

func (DiffStat) NetLOC

func (stat DiffStat) NetLOC() int

NetLOC reports insertions minus deletions. The value may be zero or negative when a change removes at least as many lines as it adds.

type EnvRunner

type EnvRunner func(context.Context, string, []string, ...string) (CommandResult, error)

type Event

type Event struct {
	Type      EventType `json:"type"`
	Runtime   string    `json:"runtime,omitempty"`
	Contract  string    `json:"contract,omitempty"`
	Root      string    `json:"root,omitempty"`
	Branch    string    `json:"branch,omitempty"`
	Commit    string    `json:"commit,omitempty"`
	Clean     bool      `json:"clean,omitempty"`
	FileCount int       `json:"fileCount,omitempty"`
	Path      string    `json:"path,omitempty"`
	Status    string    `json:"status,omitempty"`
	Staged    bool      `json:"staged,omitempty"`
	Unstaged  bool      `json:"unstaged,omitempty"`
	Untracked bool      `json:"untracked,omitempty"`
}

func EventsFromSummary

func EventsFromSummary(summary ChangeSummary) []Event

type EventType

type EventType string
const (
	EventChangeSummary EventType = "change_summary"
	EventFileChange    EventType = "file_change"
)

type FileChange

type FileChange struct {
	Path      string `json:"path"`
	Status    string `json:"status"`
	Staged    bool   `json:"staged,omitempty"`
	Unstaged  bool   `json:"unstaged,omitempty"`
	Untracked bool   `json:"untracked,omitempty"`
}

type InspectOptions

type InspectOptions struct {
	Cwd          string
	BaseRef      string
	MaxDiffBytes int
	RunGit       Runner
	RunGitEnv    EnvRunner
}

type PROptions

type PROptions struct {
	Cwd   string
	Fill  bool
	Draft bool
	Title string
	Body  string
	RunGH Runner
}

type PRResult

type PRResult struct {
	Output string `json:"output"`
}

func CreatePR

func CreatePR(ctx context.Context, options PROptions) (PRResult, error)

type PushOptions

type PushOptions struct {
	Cwd    string
	Remote string
	Branch string
	Force  bool
	DryRun bool
	// RequireNewRemoteBranch guards this push with a zero-value
	// --force-with-lease, so it is rejected instead of fast-forwarding if
	// Branch already exists on Remote. CreateBranch's collision probe reads
	// the remote's branches before this push runs, leaving a window in which
	// a concurrent creator can publish the same generated name; this closes
	// it at the one point that actually talks to the remote atomically.
	RequireNewRemoteBranch bool
	AllowPushDefaultBranch bool
	RunGit                 Runner
	RunGitEnv              EnvRunner
}

type PushResult

type PushResult struct {
	Remote string `json:"remote"`
	Branch string `json:"branch"`
	Output string `json:"output"`
}

func Push

func Push(ctx context.Context, options PushOptions) (PushResult, error)

type Runner

type Runner func(context.Context, string, ...string) (CommandResult, error)

Jump to

Keyboard shortcuts

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