gitops

package
v0.9.0 Latest Latest
Warning

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

Go to latest
Published: Sep 8, 2026 License: MIT Imports: 9 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AddRemote

func AddRemote(dir, name, url string) error

AddRemote adds a named remote pointing at url.

func CherryPick

func CherryPick(dir, rev string) error

CherryPick applies the changes from a single commit onto the current branch, creating a new commit. Can conflict (uses the same conflict machinery as merge/rebase); resolve then CherryPickContinue, or CherryPickAbort.

func CherryPickAbort

func CherryPickAbort(dir string) error

CherryPickAbort cancels an in-progress cherry-pick and restores the pre-cherry-pick state.

func CherryPickContinue

func CherryPickContinue(dir string) error

CherryPickContinue resumes an in-progress cherry-pick after conflicts are resolved and staged.

func Clone

func Clone(url, dest string) (string, error)

Clone clones url into dest. dest is the target directory for the working copy (e.g. C:\repos\gitmate). If dest is empty, git derives it from the URL's repo name, placed under the current directory. Returns the absolute path of the resulting repo directory.

Unlike other operations, clone runs OUTSIDE any existing repo — git is invoked in dest's parent directory (created if needed) so the clone lands correctly.

func CommitMerge

func CommitMerge(dir string) (string, error)

CommitMerge finishes an in-progress merge by committing with git's prepared MERGE_MSG (no editor). Use after all conflicts are resolved + staged. Returns the new commit's short hash.

func ConflictedFiles

func ConflictedFiles(dir string) ([]string, error)

ConflictedFiles returns paths currently in a conflicted (unmerged) state.

func CreateCommit

func CreateCommit(dir, message string) (string, error)

CreateCommit creates a commit with the given message and returns the new short hash.

func CreateTag

func CreateTag(dir, name, message string) error

CreateTag makes a tag at HEAD. If message is non-empty it's an annotated tag (-a -m); otherwise a lightweight tag. Fails if the tag already exists.

func CurrentBranch

func CurrentBranch(dir string) (string, error)

CurrentBranch returns the checked-out branch name.

func DeleteBranch

func DeleteBranch(dir, name string, force bool) error

DeleteBranch deletes a branch. With force=false it uses safe delete (-d), which refuses to delete a branch holding commits not merged elsewhere. With force=true it uses -D, deleting regardless (may orphan commits). Git refuses to delete the currently checked-out branch either way.

func DeleteRemoteTag

func DeleteRemoteTag(dir, name string) error

DeleteRemoteTag deletes a tag from origin (git push origin --delete <tag>). Local deletion is separate (DeleteTag) — this only removes it from the remote.

func DeleteTag

func DeleteTag(dir, name string) error

DeleteTag removes a local tag.

func Discard

func Discard(dir string, paths ...string) error

Discard throws away working-tree changes to tracked paths, restoring them to their staged/HEAD state. This is DESTRUCTIVE — uncommitted edits are lost and cannot be recovered. It does not touch untracked files (git restore ignores them); callers should guard against passing untracked paths.

func Fetch

func Fetch(dir, remote string) error

Fetch downloads objects and refs from a remote without merging. Empty remote defaults to "origin". Updates remote-tracking branches (so ahead/behind reflect the remote) but does not touch the working tree.

func FetchTags

func FetchTags(dir string) error

FetchTags syncs tags from origin, pruning local tags that were deleted on the remote (so ListTags reflects the remote after e.g. a browser-side deletion).

func GetRemoteURL

func GetRemoteURL(dir, name string) (string, error)

GetRemoteURL returns the URL of the named remote (e.g. "origin").

func HeadSHA

func HeadSHA(dir string) (string, error)

HeadSHA returns the full commit SHA that HEAD currently points at. Used to capture a restore point before a history-moving operation (merge/rebase/reset).

func IsRepo added in v0.7.0

func IsRepo(dir string) bool

IsRepo reports whether dir is inside a git working tree. Used to gate all git and GitHub operations so the app doesn't fire (and cascade-fail) when launched in a non-repository folder.

func LastCommitSubject

func LastCommitSubject(dir, branch string) (string, error)

LastCommitSubject returns the subject line of the most recent commit on the given branch (or HEAD if branch is empty). Used to default a PR title.

func MarkResolved

func MarkResolved(dir, path string) error

MarkResolved stages a (hand-edited) conflicted file, marking it resolved.

func MaybeRunRebaseEditor

func MaybeRunRebaseEditor(args []string) (handled bool, exitCode int)

MaybeRunRebaseEditor checks os.Args for the hidden rebase-editor subcommands and, if present, performs the edit and returns true (the caller should then exit). Both the CLI and GUI mains call this at the very top of main() so that when git invokes "<self> __rebase-seq-editor <prepared> <gitTodo>" the process does the copy and exits — no external script, identical on every OS.

Returns (handled, exitCode). When handled is true, main must exit with exitCode. When false, main proceeds normally.

func Merge

func Merge(dir, branch string) error

Merge merges the named branch into the current branch. On conflicts git exits non-zero and leaves conflict markers; that error is returned to surface.

func MergeAbort

func MergeAbort(dir string) error

MergeAbort aborts an in-progress merge, restoring the pre-merge state.

func MergeInProgress

func MergeInProgress(dir string) bool

MergeInProgress reports whether a merge is underway (MERGE_HEAD exists).

func Pull

func Pull(dir string, rebase bool) error

Pull integrates remote changes into the current branch. rebase=true replays local commits on top of upstream (linear); otherwise merges. Either mode can conflict — returned as an error for the caller to surface.

func Push

func Push(dir, remote, branch string, setUpstream bool) error

Push pushes a branch to a remote. setUpstream adds -u to link the local branch to remote/<branch> (needed the first time a branch is pushed).

func PushTag

func PushTag(dir, name string) error

PushTag pushes a single tag to origin. This is what triggers a tag-based release workflow — tags do NOT travel with a normal `git push`.

func ReadPRTemplate

func ReadPRTemplate(dir string) string

ReadPRTemplate returns the repo's PR template contents, or "" if none.

func Rebase

func Rebase(dir, base string) error

Rebase replays the current branch's commits on top of base. Like merge it can conflict — but per replayed commit, so it may stop repeatedly. On conflict git exits non-zero; resolve then RebaseContinue, or RebaseAbort to bail.

func RebaseAbort

func RebaseAbort(dir string) error

RebaseAbort aborts an in-progress rebase, restoring the pre-rebase state.

func RebaseContinue

func RebaseContinue(dir string) error

RebaseContinue resumes a rebase after conflicts are resolved and staged.

func RebaseInProgress

func RebaseInProgress(dir string) bool

RebaseInProgress reports whether a rebase is underway (the rebase-merge or rebase-apply state dir exists under .git).

func RemoveRemote

func RemoveRemote(dir, name string) error

RemoveRemote deletes a remote reference (does not touch commits).

func RenameBranch

func RenameBranch(dir, oldName, newName string) error

RenameBranch renames a branch (git branch -m). Renaming the current branch is allowed.

func RenameRemote

func RenameRemote(dir, oldName, newName string) error

RenameRemote renames a remote (and its remote-tracking refs).

func RepoRoot

func RepoRoot(dir string) string

RepoRoot resolves dir to the top level of its git working tree (via rev-parse --show-toplevel). Returns the input unchanged if resolution fails (e.g. not a repo yet). The GUI uses this to pin repoDir to the repo ROOT, so path-relative git commands don't resolve against a subdirectory like gui/.

func Reset

func Reset(dir, rev string, mode ResetMode) error

Reset moves HEAD to rev using the given mode.

func ResolveOurs

func ResolveOurs(dir, path string) error

ResolveOurs resolves a file by taking our side entirely (git checkout --ours).

func ResolveTheirs

func ResolveTheirs(dir, path string) error

ResolveTheirs resolves a file by taking their side entirely (git checkout --theirs).

func Revert

func Revert(dir, rev string) error

Revert creates a NEW commit that undoes the changes of a previous commit — the safe, history-preserving undo (unlike Reset, which rewrites history). Can conflict; resolve then RevertContinue, or RevertAbort.

func RevertAbort

func RevertAbort(dir string) error

RevertAbort cancels an in-progress revert and restores the pre-revert state.

func RevertContinue

func RevertContinue(dir string) error

RevertContinue resumes an in-progress revert after conflicts are resolved and staged.

func RunInteractiveRebase

func RunInteractiveRebase(dir, base string, steps []RebaseStep) error

RunInteractiveRebase performs an interactive rebase onto base, applying the given plan (reorder/drop/squash/fixup/reword) by driving git non-interactively via the injectable sequence/message editors.

func SequencerInProgress

func SequencerInProgress(dir string) (cherryPick bool, revert bool)

SequencerInProgress reports whether a cherry-pick or revert is mid-operation (paused on a conflict). Both use git's "sequencer" state.

func SmartDeleteTag

func SmartDeleteTag(dir, name string) (string, error)

SmartDeleteTag deletes a tag wherever it exists: local, remote, or both. It checks presence first so it never errors trying to delete a side that isn't there. Returns a short description of what was removed.

func Stage

func Stage(dir string, paths ...string) error

Stage runs `git add`. With no paths, stages everything (new, modified, deleted).

func StageHunk

func StageHunk(dir, path string, h Hunk) error

StageHunk stages a single hunk of a file by building a patch for just that hunk and applying it to the index (git apply --cached). This is how you stage part of a file's changes without staging the whole file.

func StashApply

func StashApply(dir, ref string) error

StashApply applies a stash WITHOUT removing it from the stash list (unlike StashPop, which applies and drops). Empty ref applies the most recent.

func StashDrop

func StashDrop(dir, ref string) error

StashDrop discards a stash entry without applying it. An empty ref drops the most recent. Destructive — the stashed changes are lost.

func StashPop

func StashPop(dir, ref string) error

StashPop applies the stash at the given ref and removes it from the stash list. An empty ref pops the most recent (stash@{0}).

func StashSave

func StashSave(dir, message string, includeUntracked bool) error

StashSave stashes tracked working-tree and index changes. If message is non-empty it's used as the stash description. includeUntracked also stashes untracked files (git stash push -u). Returns nil even if there was nothing to stash — callers can re-check status.

func Switch

func Switch(dir, branch string) error

Switch changes the checked-out branch. Git refuses if uncommitted changes would be overwritten; that refusal is returned as an error for the caller to surface (commit, discard, or — once available — stash first).

func SwitchNew

func SwitchNew(dir, branch string) error

SwitchNew creates a new branch from the current HEAD and switches to it (git switch -c). Fails if the branch already exists.

func UndoTo

func UndoTo(dir, sha string) error

UndoTo hard-resets HEAD back to a previously captured SHA — the mechanism behind "undo last operation". The pre-undo state remains recoverable via the reflog, so an undo is itself reversible.

func Unstage

func Unstage(dir string, paths ...string) error

Unstage removes paths from the index (staged -> unstaged), leaving the working tree untouched. With no paths, unstages everything.

func UnstageHunk

func UnstageHunk(dir, path string, h Hunk) error

UnstageHunk removes a single staged hunk from the index by applying its patch in reverse against the index (git apply --cached --reverse).

Types

type BlameLine

type BlameLine struct {
	Line    int    // 1-based line number in the current file
	Short   string // short commit hash
	Author  string // author name
	Content string // the line's text
}

BlameLine is one line of a file with the commit that last touched it.

func Blame

func Blame(dir, path string) ([]BlameLine, error)

Blame returns per-line authorship for a file using `git blame --porcelain`, which emits stable, machine-readable records (one header block per line group plus a tab-prefixed content line).

type Branch

type Branch struct {
	Name        string
	IsCurrent   bool
	IsLocal     bool   // has a local refs/heads/ ref
	IsRemote    bool   // exists on a remote (refs/remotes/)
	Remote      string // remote name for remote-only branches (e.g. "origin")
	Upstream    string
	Ahead       int
	Behind      int
	LastHash    string
	LastSubject string
	LastWhen    time.Time
}

Branch is one parsed local branch.

func GetBranches

func GetBranches(dir string) ([]Branch, error)

GetBranches lists local branches sorted by most-recent commit first.

type Commit

type Commit struct {
	Hash    string
	Short   string
	Author  string
	Email   string
	When    time.Time
	Subject string
}

Commit is one parsed log entry.

func GetLog

func GetLog(dir string, limit int) ([]Commit, error)

GetLog runs git log with a fixed format and parses up to `limit` commits. GetLog logs the current branch (HEAD).

func GetLogRef

func GetLogRef(dir, ref string, limit int) ([]Commit, error)

GetLogRef logs a specific ref (branch, tag, commit-ish). Empty ref = HEAD.

type CommitDetail

type CommitDetail struct {
	Hash    string
	Short   string
	Author  string
	Email   string
	Date    string
	Subject string
	Body    string
	Files   []FileDiff
}

CommitDetail is a single commit's metadata plus its file diffs.

func Show

func Show(dir, rev string) (*CommitDetail, error)

Show returns metadata and the diff for a single revision, using `git show` (which handles the root commit — no parent — correctly).

type ConflictFile

type ConflictFile struct {
	Path  string
	Hunks []ConflictHunk
	Raw   string
}

ConflictFile is a conflicted file's regions plus the raw marked-up content.

func ReadConflict

func ReadConflict(dir, path string) (*ConflictFile, error)

ReadConflict returns the conflict for a file, reading the authoritative "ours" (index stage 2) and "theirs" (stage 3) blobs via git — reliable regardless of marker formatting or the process working directory.

type ConflictHunk

type ConflictHunk struct {
	Ours   []string // stage 2 — current branch (HEAD)
	Theirs []string // stage 3 — the merged-in branch
}

ConflictHunk is one conflict region: the "ours" and "theirs" content.

type DiffOptions

type DiffOptions struct {
	Staged bool
	Rev    string
	Path   string
}

DiffOptions selects what to diff.

type FileChange

type FileChange struct {
	Staged   string // human-readable index (staged) state
	Unstaged string // human-readable working-tree state
	Path     string
	OrigPath string // set for renames/copies
}

FileChange is one entry from git status.

type FileDiff

type FileDiff struct {
	OldPath string
	NewPath string
	Binary  bool
	Hunks   []Hunk
}

FileDiff is the diff for a single file.

func Diff

func Diff(dir string, opts DiffOptions) ([]FileDiff, error)

Diff returns structured diffs for the given options.

func ParseUnifiedDiff

func ParseUnifiedDiff(out string) []FileDiff

ParseUnifiedDiff turns `git diff` output into []FileDiff.

type Hunk

type Hunk struct {
	Header string
	Lines  []Line
}

Hunk is one @@ ... @@ block.

type Line

type Line struct {
	Kind    LineKind
	Content string
	OldNum  int
	NewNum  int
}

Line is one line within a hunk.

type LineKind

type LineKind string

LineKind classifies a diff line.

const (
	LineContext LineKind = "context"
	LineAdd     LineKind = "add"
	LineRemove  LineKind = "remove"
)

Diff line kinds.

type RebaseAction

type RebaseAction string

RebaseAction is what to do with a commit in an interactive rebase.

const (
	RebasePick   RebaseAction = "pick"
	RebaseReword RebaseAction = "reword"
	RebaseSquash RebaseAction = "squash"
	RebaseFixup  RebaseAction = "fixup"
	RebaseDrop   RebaseAction = "drop"
)

Interactive-rebase actions.

type RebaseStep

type RebaseStep struct {
	SHA     string       // full or short commit SHA
	Subject string       // commit subject (for display)
	Action  RebaseAction // pick/reword/squash/fixup/drop
	Message string       // replacement/combined message for reword & squash; empty otherwise
}

RebaseStep is one line of the interactive-rebase plan: a commit + the action to take, plus (for reword/squash) an optional replacement message.

func InteractiveRebaseTodo

func InteractiveRebaseTodo(dir, base string) ([]RebaseStep, error)

InteractiveRebaseTodo returns the commits from base..HEAD (oldest first, the order a rebase todo uses) as a default plan of "pick" steps, ready to be reordered/edited by the caller.

type ReflogEntry

type ReflogEntry struct {
	Short    string // abbreviated commit hash HEAD pointed at
	Selector string // e.g. "HEAD@{0}"
	Action   string // commit, reset, checkout, merge, rebase, pull, ...
	Message  string // the rest of the description
}

ReflogEntry is one line of `git reflog` — where HEAD moved and why.

func Reflog

func Reflog(dir string, limit int) ([]ReflogEntry, error)

Reflog returns HEAD's reflog, newest first, up to limit entries (0 = all). This is the "undo safety net" — every position HEAD has held, so a bad reset or rebase can be traced back and recovered.

type Remote

type Remote struct {
	Name string
	URL  string
}

Remote is a named remote and its fetch URL.

func ListRemotes

func ListRemotes(dir string) ([]Remote, error)

ListRemotes returns the configured remotes with their fetch URLs.

type ResetMode

type ResetMode string

ResetMode is soft (move HEAD, keep index + working tree), mixed (move HEAD + reset index, keep working tree — the default), or hard (move HEAD + reset index + working tree, DISCARDING uncommitted changes and orphaning commits after the target — recoverable via reflog until it expires).

const (
	ResetSoft  ResetMode = "soft"
	ResetMixed ResetMode = "mixed"
	ResetHard  ResetMode = "hard"
)

Reset modes for Reset (soft keeps changes staged; mixed unstages; hard discards).

type Stash

type Stash struct {
	Ref     string // e.g. "stash@{0}"
	Index   int    // 0-based position
	Branch  string // branch the stash was made on (best-effort parse)
	Message string // the stash description
}

Stash is one entry from `git stash list`.

func StashList

func StashList(dir string) ([]Stash, error)

StashList returns the stash entries, newest first (stash@{0} is newest).

type Status

type Status struct {
	Branch    string
	Upstream  string
	Ahead     int
	Behind    int
	Detached  bool
	Changes   []FileChange
	Untracked []string
}

Status is the parsed result of `git status --porcelain=v2 --branch`.

func GetStatus

func GetStatus(dir string) (*Status, error)

GetStatus runs status --porcelain=v2 --branch and parses the output.

type Tag

type Tag struct {
	Name    string
	Subject string // annotation message or the tagged commit's subject (local only)
	Local   bool   // exists in the local repo
	Remote  bool   // exists on origin
}

Tag is one entry from the tag list, with where it exists.

func ListTags

func ListTags(dir string) ([]Tag, error)

ListTags returns tags, newest first (by creation), with a one-line subject.

func (Tag) Location

func (t Tag) Location() string

Location returns a human label: "local only", "remote only", or "both".

Jump to

Keyboard shortcuts

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