git

package
v1.1.0 Latest Latest
Warning

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

Go to latest
Published: Nov 5, 2026 License: MIT Imports: 18 Imported by: 0

Documentation

Overview

Package git contains subprocess boundaries, independent of command flags.

Index

Constants

This section is empty.

Variables

View Source
var ErrAmbiguousRemote = errors.New("ambiguous repository: select --remote or --repo")

ErrAmbiguousRemote reports that repository discovery cannot choose between several remotes.

View Source
var ErrNotOnBranch = errors.New("not on a branch")

ErrNotOnBranch reports a detached HEAD or a directory outside a checkout.

Functions

func CredentialArguments

func CredentialArguments(instance, executable, user, configDir string) ([]string, error)

CredentialArguments scopes a helper to one Git operation instead of changing Git configuration. The empty helper resets other helpers for this instance.

func CredentialHelper

func CredentialHelper(instance, executable, user, configDir string) (string, error)

CredentialHelper builds a shell command for Git's helper protocol. Git itself supplies the final get/store/erase argument. No credential enters this command.

func CurrentBranch

func CurrentBranch(ctx context.Context, runner Runner, dir string) (string, error)

CurrentBranch names the checked-out branch, failing with ErrNotOnBranch when HEAD is detached or dir is not a checkout. It reads the full ref because --short answers heads/NAME for a branch that shares its name with a tag.

func CurrentUpstreamRemote

func CurrentUpstreamRemote(ctx context.Context, runner Runner, dir string) (branch, remote string)

CurrentUpstreamRemote names the checked-out branch and the remote it tracks; each is "" when HEAD is detached or the branch tracks no remote.

func DiscoverRemote

func DiscoverRemote(ctx context.Context, runner Runner, dir, preferred string, repository func(remote string) string) (string, error)

DiscoverRemote names the remote used for repository discovery: preferred when it exists, then the base remote pr checkout recorded for the current branch, the current branch's upstream remote unless it is a pulls/<owner>/<repo> head remote or origin beside an upstream remote (a fork clone), then upstream, origin, or the only remote. When repository is not nil, it names the repository of a remote gt can act on, or returns "" for one on another forge. Those steps then skip such remotes, and the other remotes decide when they name exactly one repository; with none of them usable the choice is the name-based one.

func FindCleanBranch

func FindCleanBranch(ctx context.Context, runner Runner, opts FindCleanBranchOptions) (localBranch, remote string, err error)

FindCleanBranch locates one local branch for PR cleanup without mutating Git state.

func HelperScope

func HelperScope(ctx context.Context, runner Runner, dir, instance string) string

HelperScope returns where Git is configured to ask gt for credentials of instance: "local" for the repository in dir, "global", or "" when it is not.

func PushAgitPR

func PushAgitPR(ctx context.Context, runner Runner, opts AgitOptions) error

PushAgitPR pushes head to refs/for/<base>/<topic> with optional title/description options.

func RecordBackportPull added in v1.0.0

func RecordBackportPull(ctx context.Context, runner Runner, dir, branch string, number int64) error

RecordBackportPull records the pull request a backport branch opened, so that pr commands on the branch select it, and forgets the backport state.

func RecordBaseRemote

func RecordBaseRemote(ctx context.Context, runner Runner, dir, branch, remote string) error

RecordBaseRemote records remote as the remote of the base repository of branch, which repository discovery prefers to the remote the branch tracks, such as a fork.

func RecordPull

func RecordPull(ctx context.Context, runner Runner, dir, branch string, number int64, baseRemote string) error

RecordPull records in the configuration of branch the pull request it belongs to and the remote of that pull request's base repository, which pr commands read to find the pull request of the branch and pr clean to find the branch of the pull request.

func RejectCredentials

func RejectCredentials(ctx context.Context, runner Runner, dir, instance, user, token string) error

RejectCredentials asks Git's credential helpers to erase the copies of token they stored for user on instance, such as one that a keychain kept after a push. Helpers keep entries with another password, such as the user's own. Runners that cannot send input reject nothing.

func RenameBaseRemote added in v1.0.0

func RenameBaseRemote(ctx context.Context, runner Runner, dir, from, to string) error

RenameBaseRemote records to as the base remote of every branch that recorded from, after git remote rename, which updates only Git's own keys.

func SSHArguments

func SSHArguments(key string, agent bool) ([]string, error)

SSHArguments selects a private key for one Git operation. Agent selection retains the user's SSH configuration, as does an account without a key.

func SetupCredentials

func SetupCredentials(ctx context.Context, runner Runner, options CredentialSetup) error

SetupCredentials installs a helper scoped to the instance. Unless KeepHelpers is set, an empty helper first resets other helpers for the instance, so they neither answer for gt nor store its token.

func SetupTLS

func SetupTLS(ctx context.Context, runner Runner, dir string, local bool, instance, certFile, keyFile string, insecure bool) error

SetupTLS writes the settings of TLSArguments to the global Git configuration, or with local to the configuration of the repository in dir, so that plain git fetch and push reach the instance.

func TLSArguments

func TLSArguments(instance, certFile, keyFile string, insecure bool) ([]string, error)

TLSArguments make one Git operation present the instance's TLS client certificate, with its key in keyFile or else in certFile, and skip certificate verification when insecure, as gt's API requests do. They apply only to the instance's URLs.

func UnsetInsecureTLS

func UnsetInsecureTLS(ctx context.Context, runner Runner, dir string, local bool, instance string) error

UnsetInsecureTLS removes the sslVerify=false that SetupTLS wrote for the instance, once the instance verifies certificates again. A setting with another value is kept.

func UnsetTLSCertificate added in v1.0.0

func UnsetTLSCertificate(ctx context.Context, runner Runner, dir string, local bool, instance string) error

UnsetTLSCertificate removes the sslCert and sslKey that SetupTLS wrote for the instance, once it has no client certificate. SetupTLS records what it wrote in gt.<instance>.sslCert and sslKey, so a setting it did not write, or that was changed since, is kept. So are the unrecorded settings of gt 0.2.0: by the time the client certificate is gone its path is too, so they cannot be told from settings written by hand.

func UpstreamRemote

func UpstreamRemote(ctx context.Context, runner Runner, dir, branch string) string

UpstreamRemote names the remote branch tracks, or "" when it tracks none or a local branch. Unlike splitting @{upstream}, it keeps remote names with slashes, such as the pulls/<owner>/<repo> remotes pr checkout adds.

Types

type AgitOptions

type AgitOptions struct {
	Directory, Remote, Head, Base, Topic, Title, Body string
	CredentialArgs                                    []string
	Prompt                                            bool
}

AgitOptions creates a pull request through Gitea's AGit push convention.

type BackportConflict added in v1.0.0

type BackportConflict struct {
	Target, Branch string
	Files          []string
	Kept           bool
}

BackportConflict reports a cherry-pick that stopped at conflicts. Kept tells whether the cherry-pick is still in progress on the backport branch or was undone.

func (*BackportConflict) Error added in v1.0.0

func (e *BackportConflict) Error() string

type BackportOptions added in v1.0.0

type BackportOptions struct {
	// CredentialArgs contains per-operation Git configuration for the fetches only.
	CredentialArgs []string
	Directory      string
	Remote         string
	Prompt         bool
	Number         int64
	// Base is the branch the pull request was merged into, MergeCommit the commit the merge left
	// there and MergeBase the commit of Base the pull request started from.
	Base, MergeCommit, MergeBase string
	Target, Branch               string
	// Keep leaves a conflicting cherry-pick in progress to resolve instead of undoing the backport.
	Keep bool
	// Hold, when set, returns a runner for one cherry-pick that holds back Git's diagnostics and a
	// function that shows them, so that only those of a cherry-pick left to the user are shown.
	Hold func() (Runner, func())
}

BackportOptions selects a merged pull request, the branch to backport it to and the new local branch that receives the cherry-picks.

type BackportResult added in v1.0.0

type BackportResult struct {
	Target  string   `json:"target"`
	Branch  string   `json:"branch"`
	Picked  []string `json:"picked"`
	Commits []string `json:"commits"`
	Number  int64    `json:"-"`
}

BackportResult describes a backport branch: the commits picked from the base branch and the commits they became on the backport branch.

func Backport added in v1.0.0

func Backport(ctx context.Context, runner Runner, opts BackportOptions) (BackportResult, error)

Backport cherry-picks the commits a merged pull request left on its base branch onto a new branch started from the remote's target branch, with -x, and switches back to the branch it ran on. A merge commit contributes the commits it merged; a commit without merge parents contributes itself and, when it ends a run of commits by the pull request's authors at their author dates, that run, which is how a rebase or fast-forward merge lands; any other single commit is a squash. On a conflict it undoes everything unless Keep is set.

func ContinueBackport added in v1.0.0

func ContinueBackport(ctx context.Context, runner Runner, dir string) (BackportResult, error)

ContinueBackport finishes the backport whose conflicts were resolved on the checked-out branch: it refuses while the cherry-pick is still in progress and switches back to the branch the backport started from.

type BackportSkipped added in v1.0.0

type BackportSkipped struct{ Err error }

BackportSkipped reports a target that cannot take the backport, such as one that already has it; the clone is left as it was, so that other targets can still be tried.

func (*BackportSkipped) Error added in v1.0.0

func (e *BackportSkipped) Error() string

func (*BackportSkipped) Unwrap added in v1.0.0

func (e *BackportSkipped) Unwrap() error

type BranchConfig

type BranchConfig struct {
	// Name is the local branch.
	Name string
	// Remote and Merge are the remote and branch the branch tracks, Merge without refs/heads/;
	// both are empty for a branch that tracks nothing or another local branch.
	Remote, Merge string
	// PullNumber and BaseRemote are what pr checkout recorded: the pull request the branch was
	// checked out from and the remote of that pull request's base repository.
	PullNumber int64
	BaseRemote string
}

BranchConfig is the configuration of a local branch that locates its pull request.

func CurrentBranchConfig

func CurrentBranchConfig(ctx context.Context, runner Runner, dir string) (BranchConfig, error)

CurrentBranchConfig reads the configuration of the checked-out branch, failing with ErrNotOnBranch when HEAD is detached or dir is not a checkout.

func ReadBranchConfig

func ReadBranchConfig(ctx context.Context, runner Runner, dir, name string) BranchConfig

ReadBranchConfig reads branch.<name>.remote, .merge and the keys pr checkout records. Missing or malformed keys stay empty.

type CheckoutOptions

type CheckoutOptions struct {
	// CredentialArgs contains per-operation Git configuration for the fetch only.
	CredentialArgs []string
	Directory      string
	Remote         string
	Number         int64
	Branch         string
	Detached       bool
	Update         bool
	Prompt         bool
	ExpectedCommit string
	// HeadRemote and HeadBranch select fork tracking when the head branch still exists.
	// When HeadBranch is empty, checkout fetches the retained pull ref from Remote.
	HeadRemote string
	HeadBranch string
}

CheckoutOptions identifies the base remote and how to check out the PR commit.

type CheckoutResult

type CheckoutResult struct {
	Detached bool   `json:"detached"`
	Branch   string `json:"branch"`
	Commit   string `json:"commit"`
	Remote   string `json:"remote,omitempty"`
	Tracking string `json:"tracking,omitempty"`
	// Unpushed counts the commits an existing branch has on top of the PR head, which it keeps.
	Unpushed int `json:"-"`
}

CheckoutResult describes the selected branch or detached PR commit.

func CheckoutPull

func CheckoutPull(ctx context.Context, runner Runner, options CheckoutOptions) (CheckoutResult, error)

CheckoutPull fetches a PR head and checks out its commit. When HeadRemote and HeadBranch are set, it fetches that head branch and configures tracking. Otherwise it fetches Gitea's retained pull ref from the base remote.

type CleanOptions

type CleanOptions struct {
	Directory, DefaultBranch, LocalBranch, Remote, RemoteBranch, RemoteSHA string
	CredentialArgs                                                         []string
	Prompt, DeleteRemote                                                   bool
}

CleanOptions identifies a closed PR's local branch and optional remote head. RemoteSHA, when set, is the commit the remote head must still be at to be deleted.

type CleanResult

type CleanResult struct {
	LocalBranch      string `json:"local_branch"`
	Remote           string `json:"remote,omitempty"`
	RemoteBranch     string `json:"remote_branch,omitempty"`
	DefaultBranch    string `json:"default_branch"`
	RemoteDeleted    bool   `json:"remote_deleted"`
	RemoteSkipped    bool   `json:"remote_skipped"`
	RemoteSkipReason string `json:"remote_skip_reason,omitempty"`
	// RemovedRemote is the Git remote that pr checkout added for the branch, removed with it.
	RemovedRemote string `json:"removed_remote,omitempty"`
}

CleanResult reports which branches were removed.

func CleanPull

func CleanPull(ctx context.Context, runner Runner, opts CleanOptions) (CleanResult, error)

CleanPull deletes the selected local branch and optionally its remote head.

type CleanSelectionError added in v1.0.0

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

CleanSelectionError reports that no single local branch of the pull request could be selected.

func (*CleanSelectionError) Error added in v1.0.0

func (e *CleanSelectionError) Error() string

type CommandError

type CommandError struct{ ExitCode int }

CommandError carries Git's exit status without including command arguments or output.

func (*CommandError) Error

func (*CommandError) Error() string

type CredentialSetup

type CredentialSetup struct {
	Directory, Instance, Executable, User, ConfigDirectory string
	Local                                                  bool
	// KeepHelpers adds gt's helper after other helpers instead of resetting them for the instance,
	// replacing only a helper gt installed before.
	KeepHelpers bool
}

CredentialSetup specifies an explicit persistent helper installation.

type FindCleanBranchOptions

type FindCleanBranchOptions struct {
	Directory, HeadSHA, HeadBranch  string
	DefaultBranch                   string
	PreferredNames, MatchingRemotes []string
	IgnoreSHA                       bool
	// PullNumber is the pull request being cleaned; a branch that pr checkout recorded for it
	// wins over branches that merely share the head branch's name.
	PullNumber int64
}

FindCleanBranchOptions searches for a local branch belonging to a closed PR.

type InputRunner

type InputRunner interface {
	Input(ctx context.Context, dir, input string, args ...string) (string, error)
}

InputRunner runs Git with text on its standard input.

type LocalBranch added in v1.0.0

type LocalBranch struct {
	BranchConfig
	Commit  string
	Current bool
	// Committed and UpstreamCommitted are the committer dates of the branch's tip and of the
	// remote-tracking branch it tracks, which is zero when there is none.
	Committed, UpstreamCommitted time.Time
}

LocalBranch is a local branch with the configuration that locates its pull request.

func LocalBranches added in v1.0.0

func LocalBranches(ctx context.Context, runner Runner, dir string) ([]LocalBranch, error)

LocalBranches lists the local branches of the clone in dir by name, in four git calls.

type Runner

type Runner interface {
	Output(context.Context, string, bool, ...string) (string, error)
}

Runner abstracts context-aware Git subprocess execution.

type SyncOptions

type SyncOptions struct {
	Directory, Remote, Branch string
	CredentialArgs            []string
	Prompt                    bool
}

SyncOptions selects the local branch to fast-forward and the remote whose branch of the same name it follows.

type SyncResult

type SyncResult struct {
	Branch   string `json:"branch"`
	Commit   string `json:"commit"`
	Previous string `json:"previous"`
	Remote   string `json:"remote"`
}

SyncResult reports a synced branch. Previous is the branch's commit before the sync, empty when the sync created the branch; it equals Commit when there was nothing to sync. For a sync on the server, Remote names the repository the branch was synced from.

func SyncBranch

func SyncBranch(ctx context.Context, runner Runner, opts SyncOptions) (SyncResult, error)

SyncBranch fast-forwards the local branch to the remote's branch of the same name, creating it when it is missing, and never changes which branch is checked out. The checked-out branch merges with --ff-only and needs a clean working tree; another branch moves with update-ref, which fails if the branch changed meanwhile. A branch that already contains the remote history is kept. A branch checked out in another linked worktree, or being rebased in any worktree, is refused, since moving it would leave that worktree's files behind its HEAD or break the rebase.

type System

type System struct {
	// Env overrides the subprocess environment when supplied.
	Env    []string
	In     io.Reader
	ErrOut io.Writer
}

System executes installed Git with explicit stream and prompting policy.

func (System) Input

func (s System) Input(ctx context.Context, dir, input string, args ...string) (string, error)

Input runs Git like Output with input on its standard input, without terminal prompts.

func (System) Output

func (s System) Output(ctx context.Context, dir string, prompt bool, args ...string) (string, error)

Output runs Git, suppressing credential prompts when interaction is disabled.

Directories

Path Synopsis
Package gittest shields tests that run Git from the developer's Git configuration.
Package gittest shields tests that run Git from the developer's Git configuration.

Jump to

Keyboard shortcuts

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