Documentation
¶
Overview ¶
Package gitsafe centralizes safety-critical git primitives shared across commands that move HEAD or rewrite refs (undo, wipe, timemachine).
At present this package only hosts the backup ref naming helper (SHARED-07). See docs/roadmap-v2.md for the full set of planned extractions.
Index ¶
- Constants
- Variables
- func BackupRefName(kind, branch string, when time.Time) string
- func PruneKindBackups(ctx context.Context, runner git.Runner, kind, branch string, ...) int
- func ResolveRef(ctx context.Context, r git.Runner, ref string) (string, error)
- func SanitizeBranchSegment(branch string) string
- type BackupRef
- type BranchFFResult
- type FFOutcome
- type Option
- type Report
- type RestoreError
- type RestoreOption
- type Restorer
- type Result
- type Stage
- type Strategy
- type Target
Constants ¶
const ( KeyConfirm = 'y' KeyHardReset = 'R' KeyPreview = 'r' KeyAbort = 'n' KeyAbortAlias = 'N' )
Keypress identifiers consumed by DecideStrategy. These mirror the keys the `gk timemachine` / `gk undo` confirmation modal binds: `y` commits the default safe strategy, `R` requests hard reset, `r` asks for a preview only, `n`/`Esc` aborts.
Variables ¶
var ErrAbort = errors.New("aborted")
ErrAbort is returned when the user explicitly declines (`n` / `Esc`). Callers treat this as a non-error early exit.
var ErrPreview = errors.New("preview requested; restore not executed")
ErrPreview is returned when the user requests a preview (`r`) without committing to the restore. Callers display the dry-run plan and re-prompt.
var ErrRequiresForceDiscard = errors.New("hard reset on dirty tree without autostash; pass --force-discard to proceed")
ErrRequiresForceDiscard is returned by DecideStrategy when the user presses `R` on a dirty tree with autostash disabled. Hard reset in that state would silently destroy uncommitted work, so the caller must either (a) enable autostash, (b) route through `--force-discard`, or (c) clean the tree.
Functions ¶
func BackupRefName ¶
BackupRefName returns the canonical backup ref path used by every gk command that creates a recovery anchor before moving HEAD:
refs/gk/<kind>-backup/<safeBranch>/<unix>
kind is a short identifier for the originating command ("undo", "wipe", "timemachine"). An empty branch (detached HEAD) is rendered as "detached" and any "/" characters in the branch name are rewritten to "-" so the segment is a single path component.
The output format is part of gk's recovery UX — `gk undo` and `gk wipe` print this path to stdout and users copy-paste it into `git reset --hard <ref>` to recover. Do not change the format without updating the recovery docs in internal/cli/undo.go and wipe.go.
func PruneKindBackups ¶
func PruneKindBackups(ctx context.Context, runner git.Runner, kind, branch string, maxAge time.Duration, keepRecent int) int
PruneKindBackups bounds the refs/gk/<kind>-backup/<branch>/<unix> family for callers outside BranchFF — notably aicommit's EnsureBackupRef, which writes a refs/gk/ai-commit-backup/* ref on every `gk commit` and otherwise has nothing to prune it (git.PruneBackups scans only refs/gk/backup/*, and BranchFF's prune runs only for its own integration kinds). Same conservative policy: keep the keepRecent newest, delete the rest older than maxAge. Best-effort; returns the number deleted.
func ResolveRef ¶
ResolveRef resolves a ref name to its full commit SHA via `git rev-parse --verify <ref>^{commit}`. Exported because multiple gk commands need this helper (gk undo --to, gk timemachine restore, gk precheck).
func SanitizeBranchSegment ¶
SanitizeBranchSegment converts a branch name into a safe single-component path segment for use inside a ref name. Detached HEAD (empty string) maps to "detached"; any "/" is replaced with "-".
Types ¶
type BackupRef ¶
type BackupRef struct {
Ref string // full ref path, e.g. refs/gk/undo-backup/main/1700000000
Kind string // "undo" | "wipe" | "timemachine" | "forget" | "ai-commit"
Branch string // branch segment as stored (NOT de-sanitized); empty when "detached"
When time.Time // parsed from the unix segment; zero when unparseable
SHA string // commit the ref points at
}
BackupRef describes a single gk-managed backup ref as returned by ListBackups. The fields are parsed from the ref path (refs/gk/<kind>-backup/<branch>/<unix>) and the pointed-at commit SHA.
func ListBackups ¶
ListBackups scans refs/gk/*-backup/ and returns every backup ref known to this repo, newest first. Empty output is not an error — fresh repos simply have no backups yet.
The ref format `refs/gk/<kind>-backup/<branch>/<unix>` is produced by BackupRefName; this function inverts that format. Paths that do not match are skipped silently (defensive — users can create their own refs under refs/gk/ without breaking the lister).
type BranchFFResult ¶
type BranchFFResult struct {
Branch string
OldSHA string
NewSHA string
Outcome FFOutcome
Reason string // human-facing detail for FFBlocked / FFError
BackupRef string // set only when Outcome == FFOk
}
BranchFFResult is the full outcome of a BranchFF call. It is always returned populated (OldSHA/NewSHA included even on a blocked/error path) so callers can log the attempted move.
func BranchFF ¶
func BranchFF(ctx context.Context, runner git.Runner, now func() time.Time, kind, branch, newSHA string) (BranchFFResult, error)
BranchFF fast-forwards refs/heads/<branch> to newSHA — safely and recoverably. It is the single ref-advance primitive shared by the wrap-up verbs (ship's base fast-forward, land --to, promote, pull --with-base), replacing the ad-hoc `git branch -f` / bare `update-ref` calls that each implemented only part of the contract.
Steps (ordering is the safety invariant — do NOT reorder):
- classify — resolve the branch's current tip (oldSHA) and compare to newSHA: equal → FFUpToDate; oldSHA is an ancestor of newSHA → proceed; otherwise → FFBlocked (not fast-forwardable).
- guard — refuse (FFBlocked) when the branch is checked out in any worktree. `git branch -f` refuses this for free; a bare `update-ref` would silently desync that worktree's index, so the guard is restored here explicitly.
- backup — write refs/gk/<kind>-backup/<branch>/<unix> at oldSHA BEFORE the move, so the previous tip is always recoverable via gk timemachine / git reset.
- move — `update-ref <ref> newSHA oldSHA`, a compare-and-swap that fails loudly if a concurrent process moved the ref (no silent overwrite, unlike `git branch -f`). On failure the backup ref is rolled back.
It never moves a ref that is not a strict fast-forward, so no commit can be orphaned. The returned error is non-nil only for FFError; FFOk / FFUpToDate / FFBlocked all return a nil error — blocked is a result, not a failure.
kind labels the backup ref ("ship", "land", "pull"). now supplies the backup timestamp; nil defaults to time.Now.
type FFOutcome ¶
type FFOutcome int
FFOutcome classifies the result of a BranchFF call. Callers map it to their own reporting (e.g. the agent envelope's ok/blocked state) — gitsafe stays ignorant of that layer, returning only this domain classification.
const ( // FFOk: the branch ref was fast-forwarded to newSHA via a compare-and-swap // update-ref, and a backup ref was written first. Result.BackupRef is set. FFOk FFOutcome = iota // FFUpToDate: the branch already pointed at newSHA. Nothing moved and no // backup was written. FFUpToDate // FFBlocked: the move was refused as a precondition, not an error — newSHA // is not a descendant of the branch tip (diverged or ahead), or the branch // is checked out in a worktree. Result.Reason explains which. FFBlocked // FFError: an unexpected git failure occurred; the returned error is non-nil. FFError )
type Option ¶
type Option func(*checkOpts)
Option customizes Check's behavior.
func WithWorkDir ¶
WithWorkDir pins the working directory used for filesystem-based git-state detection. Required for tests that use a FakeRunner, and any caller whose runner is not an *git.ExecRunner. Without this option, Check uses the process cwd — which is almost always wrong for callers that construct a runner with an explicit Dir.
type Report ¶
Report captures the result of a Preflight check. Callers typically branch on report.OK() or report.Err() — the latter produces the canonical error with a hint string that matches gk's existing UX.
Callers that intentionally proceed on a dirty tree (e.g. `gk wipe`) should call report.AllowDirty().Err() to suppress the dirty-tree signal while still rejecting an in-progress rebase/merge/cherry-pick.
func Check ¶
Check runs the standard gk preflight: gitstate in-progress detection plus dirty-tree detection. Returns a Report the caller can interpret. Any underlying failure (filesystem error reading .git state, or git-status failure) is returned as the second value.
func (Report) AllowDirty ¶
AllowDirty returns a copy of the report with the dirty-tree signal cleared. Used by destructive commands (`gk wipe`) that intentionally discard local changes: the in-progress guard still fires, but dirty tree is tolerated.
type RestoreError ¶
RestoreError wraps the underlying git failure with the Stage at which it occurred plus a Recovery hint the caller can print. Returned from Restore whenever any step fails — callers use errors.As(err, &gitsafe.RestoreError{}) to inspect.
func (*RestoreError) Error ¶
func (e *RestoreError) Error() string
func (*RestoreError) Unwrap ¶
func (e *RestoreError) Unwrap() error
type RestoreOption ¶
type RestoreOption func(*restoreOpts)
RestoreOption customizes Restore's behavior.
func WithAutostash ¶
func WithAutostash(enabled bool) RestoreOption
WithAutostash controls whether Restore stashes dirty working tree changes before the reset and pops the stash afterwards. Only meaningful when the tree is dirty; Restore does not force a dirty check before invoking this (callers are expected to have run gitsafe.Check).
When enabled, the ordering contract becomes:
- snapshot HEAD
- write backup ref
- stash push --include-untracked
- git reset --<mode> target
- stash pop
If step 3 fails, the backup ref is rolled back (update-ref -d) and Restore returns with Stage == StageAutostash — the user's worktree is untouched.
If step 5 (pop) fails (typically a conflict), Result.AutostashRef is set so the caller can instruct the user to resolve manually via `git stash pop`.
type Restorer ¶
type Restorer struct {
// contains filtered or unexported fields
}
Restorer performs the atomic "backup ref + reset" dance shared by every HEAD-moving gk command. Callers construct one via NewRestorer and call Restore once per operation.
func NewRestorer ¶
NewRestorer returns a Restorer for the given command kind. kind is embedded in the backup ref path (`refs/gk/<kind>-backup/...`); callers must pass a stable identifier.
func (*Restorer) Backup ¶
Backup creates a backup ref at the current HEAD and returns its full path. The ref path follows the BackupRefName format; callers typically surface this path in stdout so users know how to recover via `git reset --hard`.
func (*Restorer) Restore ¶
func (r *Restorer) Restore(ctx context.Context, branch string, target Target, strategy Strategy, opts ...RestoreOption) (Result, error)
Restore moves HEAD to the Target using the given Strategy.
Contract (ordering invariant — do NOT reorder):
- snapshot — ResolveRef("HEAD") → Result.From
- backup — update-ref <backupRef> HEAD (must precede any HEAD motion)
- autostash — stash push -u (only if WithAutostash(true) passed)
- reset — git reset --<mode> target.SHA
- pop — stash pop (only if step 3 ran)
- verify — ResolveRef("HEAD") confirms the move (warning-only on failure)
Failure handling:
- step 1/2 fail → RestoreError with Stage=snapshot/backup; nothing mutated
- step 3 fails → update-ref -d rolls back step 2; tree untouched
- step 4 fails → backup ref intact; Recovery hint = `git reset --hard <backupRef>`
- step 5 fails → result.AutostashRef set; Restore returns *with* the result (not an error) because HEAD motion succeeded; caller prints a warning
- step 6 fails → warning only; the operation is considered successful
The branch argument is used only for the backup ref name; pass an empty string for detached HEAD (SanitizeBranchSegment translates that to "detached").
type Result ¶
type Result struct {
BackupRef string
From string
To string
Strategy Strategy
// AutostashRef is set (and non-empty) only when an autostash was pushed
// but the subsequent `stash pop` step could not re-apply cleanly (e.g.
// conflict). Callers should surface it so the user can finish manually
// via `git stash pop <ref>`. Empty when no stash was pushed or pop
// succeeded.
AutostashRef string
}
Result is returned by a successful Restore. Callers format the output themselves — the struct keeps gitsafe independent of cobra/stdout conventions.
type Stage ¶
type Stage string
Stage identifies which step of Restore produced a failure. Callers branch on Stage to decide how aggressively to surface the error; for example, a "reset" failure leaves the backup ref intact and the user can recover, but a "snapshot" failure means nothing happened at all.
type Strategy ¶
type Strategy int
Strategy selects the git reset mode used during Restore.
The names mirror `git reset --<mode>` exactly. TM-14's decision table chooses the appropriate Strategy based on (dirty, autostash, key); callers that bypass the modal supply one directly.
const ( // StrategyMixed maps to `git reset --mixed` — HEAD moves, index is // updated to match, working tree is preserved. This is `gk undo`'s // default: non-destructive on the worktree. StrategyMixed Strategy = iota // StrategyHard maps to `git reset --hard` — HEAD moves, index and // working tree are both rewritten. Destructive to uncommitted changes. // Used by `gk wipe` and `gk timemachine restore --mode hard`. StrategyHard // StrategySoft maps to `git reset --soft` — only HEAD moves, staged // changes remain staged. Used by `gk undo --soft` to uncommit: HEAD // rewinds while the index and working tree stay untouched. StrategySoft // StrategyKeep maps to `git reset --keep` — HEAD moves if the working // tree can be kept in sync; refuses otherwise. TM-14 picks this when // the tree is dirty and autostash is off. StrategyKeep )
func DecideStrategy ¶
DecideStrategy maps (dirty, autostash, keypress) to the appropriate Strategy per the TM-14 hard-reset decision table (SYN_v2.1):
| dirty | autostash | key | → Strategy | |-------|-----------|----------|--------------------| | false | — | y | Mixed | | false | — | R | Hard | | true | true | y | Hard (+ autostash) | | true | false | y | Keep | | true | false | R | ErrRequiresForceDiscard | | any | — | r | ErrPreview | | any | — | n/Esc | ErrAbort |
When err != nil, the returned Strategy has no meaning and should be ignored. The caller decides whether to re-prompt (on ErrPreview) or exit (on ErrAbort / ErrRequiresForceDiscard).
Callers with autostash always enabled (TM-18 WithAutostash) should pass autostash=true so the decision table picks Hard-with-autostash instead of Keep on dirty+`y`.