Documentation
¶
Overview ¶
Package git provides access to the Git CLI with a Git library-like interface.
All shell-to-Git interactions should be done through this package.
Index ¶
- Variables
- func Init(ctx context.Context, dir string, opts InitOptions) (*Repository, *Worktree, error)
- type BlobInfo
- type BranchDeleteOptions
- type CheckoutFilesRequest
- type CloneOptions
- type CommitDetail
- type CommitMessage
- type CommitObject
- type CommitRange
- type CommitRequest
- type CommitTreeRequest
- type Config
- type ConfigEntry
- type ConfigKey
- type ConfigOptions
- type ConflictStage
- type CreateBranchRequest
- type FetchOptions
- type FileStatus
- type FileStatusCode
- type Hash
- type InitOptions
- type ListFilesOptions
- type ListRemoteRefsOptions
- type ListTreeOptions
- type LocalBranch
- type LocalBranchesOptions
- type MergeTreeConflictDetails
- type MergeTreeConflictError
- type MergeTreeConflictFile
- type MergeTreeRequest
- type Mode
- type OpenOptions
- type PullOptions
- type PushOptions
- type RebaseBackend
- type RebaseContinueOptions
- type RebaseInterruptError
- type RebaseInterruptKind
- type RebaseRequest
- type RebaseState
- type Refspec
- type RemoteRef
- type RenameBranchRequest
- type Repository
- func (r *Repository) BranchExists(ctx context.Context, branch string) bool
- func (r *Repository) BranchUpstream(ctx context.Context, branch string) (string, error)
- func (r *Repository) CommitAheadBehind(ctx context.Context, upstream, head string) (ahead, behind int, err error)
- func (r *Repository) CommitMessageRange(ctx context.Context, start, stop string) ([]CommitMessage, error)
- func (r *Repository) CommitSubject(ctx context.Context, commitish string) (string, error)
- func (r *Repository) CommitTree(ctx context.Context, req CommitTreeRequest) (Hash, error)
- func (r *Repository) CountCommits(ctx context.Context, commits CommitRange) (int, error)
- func (r *Repository) CreateBranch(ctx context.Context, req CreateBranchRequest) error
- func (r *Repository) DeleteBranch(ctx context.Context, branch string, opts BranchDeleteOptions) error
- func (r *Repository) DiffTree(ctx context.Context, treeish1, treeish2 string) iter.Seq2[FileStatus, error]
- func (r *Repository) Fetch(ctx context.Context, opts FetchOptions) error
- func (r *Repository) ForkPoint(ctx context.Context, a, b string) (Hash, error)
- func (r *Repository) HashAt(ctx context.Context, treeish, path string) (Hash, error)
- func (r *Repository) IsAncestor(ctx context.Context, a, b Hash) bool
- func (r *Repository) ListCommits(ctx context.Context, commits CommitRange) iter.Seq2[Hash, error]
- func (r *Repository) ListCommitsDetails(ctx context.Context, commits CommitRange) iter.Seq2[CommitDetail, error]
- func (r *Repository) ListRemoteRefs(ctx context.Context, remote string, opts *ListRemoteRefsOptions) iter.Seq2[RemoteRef, error]
- func (r *Repository) ListRemotes(ctx context.Context) ([]string, error)
- func (r *Repository) ListTree(ctx context.Context, tree Hash, opts ListTreeOptions) iter.Seq2[TreeEntry, error]
- func (r *Repository) LocalBranches(ctx context.Context, opts *LocalBranchesOptions) iter.Seq2[LocalBranch, error]
- func (r *Repository) MakeTree(ctx context.Context, ents iter.Seq2[TreeEntry, error]) (_ Hash, numEnts int, err error)
- func (r *Repository) MergeBase(ctx context.Context, a, b string) (Hash, error)
- func (r *Repository) MergeTree(ctx context.Context, req MergeTreeRequest) (_ Hash, retErr error)
- func (r *Repository) OpenWorktree(ctx context.Context, dir string) (*Worktree, error)
- func (r *Repository) PeelToCommit(ctx context.Context, ref string) (Hash, error)
- func (r *Repository) PeelToTree(ctx context.Context, ref string) (Hash, error)
- func (r *Repository) ReadCommit(ctx context.Context, commitish string) (*CommitObject, error)
- func (r *Repository) ReadObject(ctx context.Context, typ Type, hash Hash, dst io.Writer) error
- func (r *Repository) RemoteDefaultBranch(ctx context.Context, remote string) (string, error)
- func (r *Repository) RemoteFetchRefspecs(ctx context.Context, remote string) ([]Refspec, error)
- func (r *Repository) RemoteURL(ctx context.Context, remote string) (string, error)
- func (r *Repository) RenameBranch(ctx context.Context, req RenameBranchRequest) error
- func (r *Repository) SetBranchUpstream(ctx context.Context, branch, upstream string) error
- func (r *Repository) SetRef(ctx context.Context, req SetRefRequest) error
- func (r *Repository) UpdateTree(ctx context.Context, req UpdateTreeRequest) (_ Hash, err error)
- func (r *Repository) Var(ctx context.Context, name string) (string, error)
- func (r *Repository) WithLogger(log *silog.Logger) *Repository
- func (r *Repository) Worktrees(ctx context.Context) iter.Seq2[*WorktreeListItem, error]
- func (r *Repository) WriteObject(ctx context.Context, typ Type, src io.Reader) (Hash, error)
- type ResetMode
- type ResetOptions
- type SetRefRequest
- type Signature
- type TreeEntry
- type Type
- type UpdateTreeRequest
- type Worktree
- func (w *Worktree) CheckoutBranch(ctx context.Context, branch string) error
- func (w *Worktree) CheckoutFiles(ctx context.Context, req *CheckoutFilesRequest) error
- func (w *Worktree) Commit(ctx context.Context, req CommitRequest) error
- func (w *Worktree) CurrentBranch(ctx context.Context) (string, error)
- func (w *Worktree) DetachHead(ctx context.Context, commitish string) error
- func (w *Worktree) DiffIndex(ctx context.Context, treeish string) ([]FileStatus, error)
- func (w *Worktree) DiffWork(ctx context.Context) iter.Seq2[FileStatus, error]
- func (w *Worktree) Head(ctx context.Context) (Hash, error)
- func (w *Worktree) ListFilesPaths(ctx context.Context, opts *ListFilesOptions) iter.Seq2[string, error]
- func (w *Worktree) ListUntrackedFiles(ctx context.Context) iter.Seq2[string, error]
- func (w *Worktree) PeelToCommit(ctx context.Context, ref string) (Hash, error)
- func (w *Worktree) Pull(ctx context.Context, opts PullOptions) error
- func (w *Worktree) Push(ctx context.Context, opts PushOptions) error
- func (w *Worktree) Rebase(ctx context.Context, req RebaseRequest) (err error)
- func (w *Worktree) RebaseAbort(ctx context.Context) error
- func (w *Worktree) RebaseContinue(ctx context.Context, opts *RebaseContinueOptions) error
- func (w *Worktree) RebaseState(context.Context) (*RebaseState, error)
- func (w *Worktree) Repository() *Repository
- func (w *Worktree) Reset(ctx context.Context, commit string, opts ResetOptions) error
- func (w *Worktree) RootDir() string
- func (w *Worktree) StashApply(ctx context.Context, stash string) error
- func (w *Worktree) StashCreate(ctx context.Context, message string) (Hash, error)
- func (w *Worktree) StashStore(ctx context.Context, stashHash Hash, message string) error
- func (w *Worktree) WriteIndexTree(ctx context.Context) (Hash, error)
- type WorktreeListItem
Constants ¶
This section is empty.
Variables ¶
var ErrDetachedHead = errors.New("in detached HEAD state")
ErrDetachedHead indicates that the repository is unexpectedly in detached HEAD state.
var ErrNoChanges = errors.New("no changes to stash")
ErrNoChanges is returned when there are no changes to stash.
var ErrNoRebase = errors.New("no rebase in progress")
ErrNoRebase indicates that a rebase is not in progress.
var ErrNotExist = errors.New("does not exist")
ErrNotExist is returned when a Git object does not exist.
Functions ¶
func Init ¶
func Init(ctx context.Context, dir string, opts InitOptions) (*Repository, *Worktree, error)
Init initializes a new Git repository at the given directory.
Types ¶
type BlobInfo ¶
type BlobInfo struct {
// Mode is the file mode of the blob.
//
// Defaults to [RegularMode] if unset.
Mode Mode
// Hash is the hash of the blob.
Hash Hash
// Path is the path to the blob relative to the tree root.
// If it contains slashes, intermediate directories will be created.
Path string
}
BlobInfo is a single blob in a tree.
type BranchDeleteOptions ¶
type BranchDeleteOptions struct {
// Force specifies that a branch should be deleted
// even if it has unmerged changes.
Force bool
// Remote indicates that the branch being deleted
// is a remote tracking branch.
Remote bool
}
BranchDeleteOptions specifies options for deleting a branch.
type CheckoutFilesRequest ¶ added in v0.18.0
type CheckoutFilesRequest struct {
// Pathspecs are the paths, or path patterns, to checkout.
Pathspecs []string // required
// TreeIsh is the tree-ish to checkout files from.
// If empty, files will be checked out from the index.
TreeIsh string
// Overlay, when true, does not remove files that exist in the index
// but not in the tree-ish being checked out.
// When false (default), such files are removed.
Overlay bool
}
CheckoutFilesRequest specifies the parameters for checking out files.
type CloneOptions ¶ added in v0.8.0
type CloneOptions struct {
// Log specifies the logger to use for messages.
Log *silog.Logger
// contains filtered or unexported fields
}
CloneOptions configures the behavior of Clone.
type CommitDetail ¶
type CommitDetail struct {
// Hash is the full hash of the commit.
Hash Hash
// ShortHash is the short (usually 7-character) hash of the commit.
ShortHash Hash
// Subject is the first line of the commit message.
Subject string
// AuthorDate is the time the commit was authored.
AuthorDate time.Time
}
CommitDetail contains information about a commit.
func (*CommitDetail) String ¶
func (cd *CommitDetail) String() string
type CommitMessage ¶
type CommitMessage struct {
// Subject for the commit.
// Contains no leading or trailing whitespace.
Subject string
// Body of the commit.
// Contains no leading or trailing whitespace.
Body string
}
CommitMessage is the subject and body of a commit.
func (CommitMessage) String ¶
func (m CommitMessage) String() string
type CommitObject ¶ added in v0.18.0
type CommitObject struct {
Hash Hash
Tree Hash
Parents []Hash
Author Signature
Committer Signature
Subject string
Body string
}
CommitObject is a Git commit object.
func (*CommitObject) Message ¶ added in v0.18.0
func (c *CommitObject) Message() string
Message returns the full commit message, which is the subject followed by two newlines and the body (if any).
type CommitRange ¶
type CommitRange []string
CommitRange builds up arguments for a ListCommits command.
func CommitRangeFrom ¶
func CommitRangeFrom(from Hash) CommitRange
CommitRangeFrom builds a commit range that reports the given commit and all its parents until the root commit.
func (CommitRange) ExcludeFrom ¶
func (r CommitRange) ExcludeFrom(hash Hash) CommitRange
ExcludeFrom indicates that the listing should exclude commits reachable from the given hash.
func (CommitRange) FirstParent ¶
func (r CommitRange) FirstParent() CommitRange
FirstParent indicates that only the first parent of each commit should be listed if it is a merge commit.
func (CommitRange) Limit ¶
func (r CommitRange) Limit(n int) CommitRange
Limit sets the maximum number of commits to list.
func (CommitRange) Reverse ¶
func (r CommitRange) Reverse() CommitRange
Reverse indicates that the commits should be listed in reverse order.
type CommitRequest ¶
type CommitRequest struct {
// Message is the commit message.
//
// If this and ReuseMessag are empty,
// $EDITOR is opened to edit the message.
Message string
// ReuseMessage uses the commit message from the given commitish
// as the commit message.
ReuseMessage string
// Template is the commit message template.
//
// If Message is empty, this fills the initial commit message
// when the user is editing the commit message.
//
// Note that if the user does not edit the message,
// the commit will be aborted.
// Therefore, do not use this as a default message.
Template string
// All stages all changes before committing.
All bool
// Amend amends the last commit.
Amend bool
// NoEdit skips editing the commit message.
NoEdit bool
// AllowEmpty allows a commit with no changes.
AllowEmpty bool
// Create a new commit which "fixes up" the commit at the given commitish.
Fixup string
// NoVerify allows a commit with pre-commit and commit-msg hooks bypassed.
NoVerify bool
// Signoff adds a Signed-off-by trailer to the commit message.
Signoff bool
// If set, the Author and/or Committer signatures are used for the commit.
Author, Committer *Signature
}
CommitRequest is a request to commit changes. It relies on the 'git commit' command.
type CommitTreeRequest ¶
type CommitTreeRequest struct {
// Hash is the hash of a tree object
// representing the state of the repository
// at the time of the commit.
Tree Hash // required
// Message is the commit message.
Message string // required
// Parents are the hashes of the parent commits.
// This will usually have one element.
// It may have more than one element for a merge commit,
// and no elements for the initial commit.
Parents []Hash
// Author and Committer sign the commit.
//
// The current user is used for anything that is nil.
// The current user may not be available in all contexts.
Author, Committer *Signature
// GPGSign indicates whether to GPG sign the commit.
GPGSign bool
}
CommitTreeRequest is a request to create a new commit.
type Config ¶ added in v0.4.0
type Config struct {
// contains filtered or unexported fields
}
Config provides access to Git configuration in the current context.
func NewConfig ¶ added in v0.4.0
func NewConfig(opts ConfigOptions) *Config
NewConfig builds a new Config object for accessing Git configuration.
func (*Config) ListRegexp ¶ added in v0.4.0
func (cfg *Config) ListRegexp(ctx context.Context, patterns ...string) iter.Seq2[ConfigEntry, error]
ListRegexp lists all configuration entries that match the given patterns. If no patterns are provided, it lists all entries.
type ConfigEntry ¶ added in v0.4.0
ConfigEntry is a single key-value pair in Git configuration.
type ConfigKey ¶ added in v0.4.0
type ConfigKey string
ConfigKey is divided into three parts:
section.subsection.name
subsection may be absent, or may be comprised of multiple parts. section and name are case-insensitive. subsection is case-sensitive.
func (ConfigKey) Canonical ¶ added in v0.4.0
Canonical returns a canonicalized form of the key. As the section and name are case-insensitive, they are lowercased, and the subsection is left as-is.
func (ConfigKey) Section ¶ added in v0.4.0
Section returns the section name for the key, or the key itself if it doesn't have a section.
func (ConfigKey) Split ¶ added in v0.4.0
Split splits the key into its three parts: section, subsection, and name.
func (ConfigKey) Subsection ¶ added in v0.4.0
Subsection returns the subsection name for the key, or an empty string if it doesn't have a subsection.
type ConfigOptions ¶ added in v0.4.0
type ConfigOptions struct {
// Dir specifies the directory to run Git commands in.
// Defaults to the current working directory if empty.
Dir string
// Env specifies additional environment variables
// to set when running Git commands.
Env []string
// Log used for logging messages to the user.
// If nil, no messages are logged.
Log *silog.Logger
// contains filtered or unexported fields
}
ConfigOptions configures the behavior of a Config.
type ConflictStage ¶ added in v0.18.0
type ConflictStage int
ConflictStage represents the stage of a file in a merge conflict.
const ( // ConflictStageOk is a non-conflicted file. ConflictStageOk ConflictStage = 0 // ConflictStageBase is the common ancestor version of the file. ConflictStageBase ConflictStage = 1 // ConflictStageOurs is the version of the file from the current branch. ConflictStageOurs ConflictStage = 2 // ConflictStageTheirs is the version of the file from the branch being merged in. ConflictStageTheirs ConflictStage = 3 )
func (ConflictStage) String ¶ added in v0.18.0
func (s ConflictStage) String() string
type CreateBranchRequest ¶
type CreateBranchRequest struct {
// Name of the branch.
Name string
// Head is the commitish to start the branch from.
// Defaults to the current HEAD.
Head string
// Force specifies that the branch should be created
// at the given Head even if a branch with the same name
// already exists.
Force bool
}
CreateBranchRequest specifies the parameters for creating a new branch.
type FetchOptions ¶
type FetchOptions struct {
// Remote is the remote to fetch from.
//
// If empty, the default remote for the current branch is used.
// If the current branch does not have a remote configured,
// the operation fails.
Remote string
// Refspecs are the refspecs to fetch.
// If non-empty, the Remote must be specified as well.
Refspecs []Refspec
}
FetchOptions specifies parameters for the Fetch method.
type FileStatus ¶
type FileStatus struct {
// Status of the file.
Status string
// Path to the file relative to the tree root.
Path string
}
FileStatus is a single file in a diff.
type FileStatusCode ¶
type FileStatusCode string
FileStatusCode specifies the status of a file in a diff.
const ( FileUnchanged FileStatusCode = "" FileAdded FileStatusCode = "A" FileCopied FileStatusCode = "C" FileDeleted FileStatusCode = "D" FileModified FileStatusCode = "M" FileRenamed FileStatusCode = "R" FileTypeChanged FileStatusCode = "T" FileUnmerged FileStatusCode = "U" )
List of file status codes from https://git-scm.com/docs/git-diff-index#Documentation/git-diff-index.txt---diff-filterACDMRTUXB82308203.
type Hash ¶
type Hash string
Hash is a 40-character Git object ID.
const ZeroHash Hash = "0000000000000000000000000000000000000000"
ZeroHash is the hash of an empty Git object. It is used to represent the absence of a hash.
type InitOptions ¶
type InitOptions struct {
// Log specifies the logger to use for messages.
Log *silog.Logger
// Branch is the name of the initial branch to create.
// Defaults to "main".
Branch string
// contains filtered or unexported fields
}
InitOptions configures the behavior of Init.
type ListFilesOptions ¶ added in v0.15.0
type ListFilesOptions struct {
// Unmerged states unmerged files should be shown in the output.
Unmerged bool
}
ListFilesOptions shows information about files in the worktree or the index.
type ListRemoteRefsOptions ¶ added in v0.8.0
type ListRemoteRefsOptions struct {
// Heads filters the references to only those under refs/heads.
Heads bool
// Patterns specifies additional filters on the reference names.
Patterns []string
}
ListRemoteRefsOptions control the behavior of ListRemoteRefs.
type ListTreeOptions ¶
type ListTreeOptions struct {
// Recurse specifies whether subtrees should be expanded.
Recurse bool
}
ListTreeOptions specifies options for the ListTree operation.
type LocalBranch ¶
type LocalBranch struct {
// Name is the name of the branch.
Name string
// Hash is the commit hash that the branch
// currently points to.
Hash Hash
// Worktree is the path at which this branch is checked out, if any.
Worktree string
}
LocalBranch represents a local branch in a repository.
type LocalBranchesOptions ¶ added in v0.11.0
type LocalBranchesOptions struct {
// Sort specifies an optional value for git branch --sort.
Sort string
// Patterns is a list of patterns to filter branches.
// If specified, only branches matching at least one of the patterns
// will be returned.
//
// Patterns may be:
//
// - literal branch names, e.g. "main", will be matched exactly
// - branch prefixes ending in '/', e.g. "feature/",
// will match branches that start with "feature/"
// - glob patterns, e.g. 'foo*',
// will return branches that match the glob pattern
// in the same '/'-section.
Patterns []string
}
LocalBranchesOptions specifies options for listing local branches.
type MergeTreeConflictDetails ¶ added in v0.18.0
type MergeTreeConflictDetails struct {
// Paths is a list of files affected by this message/kind of conflict.
Paths []string
// Type is the type of conflict.
// This is a stable string like
// "CONFLICT (rename/delete)", "CONFLICT (binary)", etc.
// This may be consumed programmatically.
Type string
// Message is a detailed user-readable message explaining the conflict.
// This string is not stable and may change between Git versions.
Message string
}
MergeTreeConflictDetails represents an informational message about a conflict.
type MergeTreeConflictError ¶ added in v0.18.0
type MergeTreeConflictError struct {
// Files is the list of files that are in conflict.
//
// There may be multiple entries for the same file
// representing different stages of the conflict.
Files []MergeTreeConflictFile
// Details is a list of detailed messages about the conflicts,
// as well as conflicts that were resolved automatically
// (e.g. "Auto-merging <file>").
//
// Do not assume len(Details) == len(Files).
// Do not assume len(Details) > 0 means there are blocking conflicts.
Details []MergeTreeConflictDetails
}
MergeTreeConflictError is returned from the MergeTree operation when a conflict is encountered.
func (*MergeTreeConflictError) Error ¶ added in v0.18.0
func (e *MergeTreeConflictError) Error() string
type MergeTreeConflictFile ¶ added in v0.18.0
type MergeTreeConflictFile struct {
// Mode is the file mode of the conflicted file.
// This identifies directories, symlinks, etc.
Mode Mode
// Object is the hash of the object in the tree.
Object Hash
// Stage is the stage of the file in the conflict.
// This includes whether this is the base, ours, or theirs version.
Stage ConflictStage
// Path is the path of the conflicted file.
Path string
}
MergeTreeConflictFile represents a file that is in conflict.
type MergeTreeRequest ¶ added in v0.18.0
type MergeTreeRequest struct {
// Branch1 is the first branch or commit to merge.
//
// This must be a commit-ish value if MergeBase is not provided.
// Otherwise, it can be any tree-ish value.
Branch1 string // required
// Branch2 is the second branch or commit to merge.
//
// This must be a commit-ish value if MergeBase is not provided.
// Otherwise, it can be any tree-ish value.
Branch2 string // required
// MergeBase optionally specifies an explicit merge base for the merge.
// If provided, Branch1 and Branch2 can be any tree-ish values.
// The difference between this and Branch1 will be applied to Branch2.
//
// Use of this parameter requires Git 2.45 or later.
MergeBase string
// contains filtered or unexported fields
}
MergeTreeRequest specifies the parameters for a merge-tree operation.
type Mode ¶
type Mode int
Mode is the octal file mode of a Git tree entry.
List of modes that git-spice cares about. Git recognizes a few more, but we don't use them.
type OpenOptions ¶
type OpenOptions struct {
// Log specifies the logger to use for messages.
Log *silog.Logger
// contains filtered or unexported fields
}
OpenOptions configures the behavior of Open.
type PullOptions ¶
PullOptions specifies options for the Pull operation.
type PushOptions ¶
type PushOptions struct {
// Remote is the remote to push to.
//
// If empty, the default remote for the current branch is used.
// If the current branch does not have a remote configured,
// the operation fails.
Remote string
// Force indicates that a push should overwrite the ref.
Force bool
// ForceWithLease indicates that a push should overwrite a ref
// even if the new value is not a descendant of the current value
// provided that our knowledge of the current value is up-to-date.
ForceWithLease string
// Refspec is the refspec to push.
// If empty, the current branch is pushed to the remote.
Refspec Refspec
// NoVerify indicates that pre-push hooks should be bypassed.
NoVerify bool
}
PushOptions specifies options for the Push operation.
type RebaseBackend ¶
type RebaseBackend int
RebaseBackend specifies the kind of rebase backend in use.
See https://git-scm.com/docs/git-rebase#_behavioral_differences for details.
const ( // RebaseBackendMerge refers to the "merge" backend. // It is the default backend used by Git, // and handles more corner cases better. RebaseBackendMerge RebaseBackend = iota // RebaseBackendApply refers to the "apply" backend. // It is rarely used and may be phased out in the future // if the merge backend gains all of its features. // It is enabled with the --apply flag. RebaseBackendApply )
func (RebaseBackend) String ¶
func (b RebaseBackend) String() string
type RebaseContinueOptions ¶ added in v0.15.0
type RebaseContinueOptions struct {
// Editor specifies the editor to use for interactive rebases.
// If empty, the default editor will be used.
Editor string
}
RebaseContinueOptions holds options for the rebase operation.
type RebaseInterruptError ¶
type RebaseInterruptError struct {
Kind RebaseInterruptKind
State *RebaseState // always non-nil
// Err is non-nil only if the rebase operation failed
// due to a conflict.
Err error
}
RebaseInterruptError indicates that a rebasing operation was interrupted. It includes the kind of interruption and the current rebase state.
func (*RebaseInterruptError) Error ¶
func (e *RebaseInterruptError) Error() string
func (*RebaseInterruptError) Unwrap ¶
func (e *RebaseInterruptError) Unwrap() error
type RebaseInterruptKind ¶
type RebaseInterruptKind int
RebaseInterruptKind specifies the kind of rebase interruption.
const ( // RebaseInterruptConflict indicates that a rebase operation // was interrupted due to a conflict. RebaseInterruptConflict RebaseInterruptKind = iota // RebaseInterruptDeliberate indicates that a rebase operation // was interrupted deliberately by the user. // This is usually done to edit the rebase instructions. RebaseInterruptDeliberate )
type RebaseRequest ¶
type RebaseRequest struct {
// Branch is the branch to rebase.
Branch string
// Upstream is the upstream commitish
// from which the current branch started.
//
// Commits between Upstream and Branch will be rebased.
Upstream string
// Onto is the new base commit to rebase onto.
// If unspecified, defaults to Upstream.
Onto string
// Autostash is true if the rebase should automatically stash
// dirty changes before starting the rebase operation,
// and re-apply them after the rebase is complete.
Autostash bool
// Quiet reduces the output of the rebase operation.
Quiet bool
// Interactive is true if the rebase should present the user
// with a list of rebase instructions to edit
// before starting the rebase operation.
Interactive bool
}
RebaseRequest is a request to rebase a branch.
type RebaseState ¶
type RebaseState struct {
// Branch is the branch being rebased.
Branch string
// Backend specifies which merge backend is being used.
// Merge is the default.
// Apply is rarely used and may be phased out in the future.
Backend RebaseBackend
}
RebaseState holds information about the current state of a rebase operation.
type Refspec ¶
type Refspec string
Refspec specifies which refs to fetch/submit for fetch/push operations. See git-fetch(1) and git-push(1) for more information.
func (Refspec) Matches ¶ added in v0.21.0
Matches checks if a branch name matches a fetch refspec pattern.
The refspec should be in the format used by git fetch, e.g.:
- "refs/heads/foo/*" (pattern)
- "+refs/heads/foo/*:refs/remotes/origin/foo/*" (full refspec with destination)
- "refs/heads/master" (exact match)
For fetch refspecs with a destination (containing ':'), only the source side (left of ':') is used for matching.
This implements the same algorithm as Git: https://github.com/git/git/blob/f0ef5b6d9bcc258e4cbef93839d1b7465d5212b9/refspec.c#L298-L333
type RemoteRef ¶ added in v0.8.0
type RemoteRef struct {
// Name is the full name of the reference.
// For example "refs/heads/main".
Name string
// Hash is the Git object hash that the reference points to.
Hash Hash
}
RemoteRef is a reference in a remote Git repository.
type RenameBranchRequest ¶
type RenameBranchRequest struct {
// OldName is the current name of the branch.
OldName string
// NewName is the new name for the branch.
NewName string
}
RenameBranchRequest specifies the parameters for renaming a branch.
type Repository ¶
type Repository struct {
// contains filtered or unexported fields
}
Repository is a handle to a Git repository. It provides read-write access to the repository's contents.
func Open ¶
func Open(ctx context.Context, dir string, opts OpenOptions) (*Repository, error)
Open opens the repository at the given directory. If dir is empty, the current working directory is used.
func (*Repository) BranchExists ¶
func (r *Repository) BranchExists(ctx context.Context, branch string) bool
BranchExists reports whether a branch with the given name exists.
func (*Repository) BranchUpstream ¶
BranchUpstream reports the upstream branch of a local branch. Returns ErrNotExist if the branch has no upstream configured.
func (*Repository) CommitAheadBehind ¶ added in v0.13.0
func (r *Repository) CommitAheadBehind(ctx context.Context, upstream, head string) (ahead, behind int, err error)
CommitAheadBehind reports how many commits head is of upstream. That is, for upstream...head, it returns the number of commits in head that are not in upstream, and the number of commits in upstream that are not in head.
func (*Repository) CommitMessageRange ¶
func (r *Repository) CommitMessageRange(ctx context.Context, start, stop string) ([]CommitMessage, error)
CommitMessageRange returns the commit messages in the range (start, ^stop). That is, all commits reachable from start but not from stop.
func (*Repository) CommitSubject ¶
CommitSubject returns the subject of a commit.
func (*Repository) CommitTree ¶
func (r *Repository) CommitTree(ctx context.Context, req CommitTreeRequest) (Hash, error)
CommitTree creates a new commit with a given tree hash as the state of the repository.
It returns the hash of the new commit.
func (*Repository) CountCommits ¶
func (r *Repository) CountCommits(ctx context.Context, commits CommitRange) (int, error)
CountCommits reports the number of commits matched by the given range.
func (*Repository) CreateBranch ¶
func (r *Repository) CreateBranch(ctx context.Context, req CreateBranchRequest) error
CreateBranch creates a new branch in the repository. This operation fails if a branch with the same name already exists.
func (*Repository) DeleteBranch ¶
func (r *Repository) DeleteBranch( ctx context.Context, branch string, opts BranchDeleteOptions, ) error
DeleteBranch deletes a branch from the repository. It returns an error if the branch does not exist, or if it has unmerged changes and the Force option is not set.
func (*Repository) DiffTree ¶ added in v0.19.0
func (r *Repository) DiffTree(ctx context.Context, treeish1, treeish2 string) iter.Seq2[FileStatus, error]
DiffTree compares two trees and returns an iterator over files that are different. The treeish1 and treeish2 arguments can be any valid tree-ish references.
func (*Repository) Fetch ¶
func (r *Repository) Fetch(ctx context.Context, opts FetchOptions) error
Fetch fetches objects and refs from a remote repository.
func (*Repository) ForkPoint ¶
ForkPoint reports the point at which b diverged from a. See man git-merge-base for more information.
func (*Repository) HashAt ¶
HashAt reports the hash of the object at the provided path in the given treeish.
func (*Repository) IsAncestor ¶
func (r *Repository) IsAncestor(ctx context.Context, a, b Hash) bool
IsAncestor reports whether a is an ancestor of b.
func (*Repository) ListCommits ¶
func (r *Repository) ListCommits(ctx context.Context, commits CommitRange) iter.Seq2[Hash, error]
ListCommits returns a list of commits matched by the given range.
func (*Repository) ListCommitsDetails ¶
func (r *Repository) ListCommitsDetails(ctx context.Context, commits CommitRange) iter.Seq2[CommitDetail, error]
ListCommitsDetails returns details about commits matched by the given range.
func (*Repository) ListRemoteRefs ¶ added in v0.8.0
func (r *Repository) ListRemoteRefs( ctx context.Context, remote string, opts *ListRemoteRefsOptions, ) iter.Seq2[RemoteRef, error]
ListRemoteRefs lists references in a remote Git repository that match the given options.
func (*Repository) ListRemotes ¶
func (r *Repository) ListRemotes(ctx context.Context) ([]string, error)
ListRemotes returns a list of remotes for the repository.
func (*Repository) ListTree ¶
func (r *Repository) ListTree( ctx context.Context, tree Hash, opts ListTreeOptions, ) iter.Seq2[TreeEntry, error]
ListTree lists the entries in the given tree.
By default, the returned entries will only include the immediate children of the tree. Subdirectories will be listed as tree objects, and have to be expanded manually.
If opts.Recurse is true, this operation will expand all subtrees. The returned entries will only include blobs, and their path will be the full path relative to the root of the tree.
func (*Repository) LocalBranches ¶
func (r *Repository) LocalBranches(ctx context.Context, opts *LocalBranchesOptions) iter.Seq2[LocalBranch, error]
LocalBranches returns an iterator over local branches in the repository.
func (*Repository) MakeTree ¶
func (r *Repository) MakeTree(ctx context.Context, ents iter.Seq2[TreeEntry, error]) (_ Hash, numEnts int, err error)
MakeTree creates a new Git tree from the given entries.
The tree will contain *only* the given entries and nothing else. Entries must not contain slashes in their names; this operation does not create subtrees.
Returns the hash of the new tree and the number of entries written.
func (*Repository) MergeTree ¶ added in v0.18.0
func (r *Repository) MergeTree(ctx context.Context, req MergeTreeRequest) (_ Hash, retErr error)
MergeTree performs a merge without touching the index or working tree, returning the hash of the resulting tree.
For conflicts, this method returns a MergeTreeConflictError that reports information about the conflicting files. If the conflicts were resolved automatically (e.g. "Auto-merging <file>"), and there are no other blocking conflicts, this will NOT return an error.
func (*Repository) OpenWorktree ¶ added in v0.15.0
OpenWorktree opens a worktree of this repository at the given directory.
func (*Repository) PeelToCommit ¶
PeelToCommit reports the commit hash of the provided commit-ish. It returns ErrNotExist if the object does not exist.
func (*Repository) PeelToTree ¶
PeelToTree reports the tree object at the provided tree-ish. It returns ErrNotExist if the object does not exist.
func (*Repository) ReadCommit ¶ added in v0.18.0
func (r *Repository) ReadCommit(ctx context.Context, commitish string) (*CommitObject, error)
ReadCommit reads a commit object by a commit-ish string, which may be a full or partial commit hash,
func (*Repository) ReadObject ¶
ReadObject reads the object with the given hash from the repository into the given writer.
This is not useful for tree objects. Use ListTree instead.
func (*Repository) RemoteDefaultBranch ¶
RemoteDefaultBranch reports the default branch of a remote. The remote must be known to the repository.
func (*Repository) RemoteFetchRefspecs ¶ added in v0.21.0
RemoteFetchRefspecs returns the fetch refspecs for a remote. That is, the refspecs used when fetching from the remote. Example:
+refs/heads/*:refs/remotes/origin/*
func (*Repository) RenameBranch ¶
func (r *Repository) RenameBranch(ctx context.Context, req RenameBranchRequest) error
RenameBranch renames a branch in the repository.
func (*Repository) SetBranchUpstream ¶
func (r *Repository) SetBranchUpstream( ctx context.Context, branch, upstream string, ) error
SetBranchUpstream sets the upstream ref for a local branch. The upstream must be in the form "remote/branch".
If upstream is empty, the upstream is unset.
func (*Repository) SetRef ¶
func (r *Repository) SetRef(ctx context.Context, req SetRefRequest) error
SetRef changes the value of a ref to a new hash.
It optionally allows verifying the current value of the ref before updating it.
func (*Repository) UpdateTree ¶
func (r *Repository) UpdateTree(ctx context.Context, req UpdateTreeRequest) (_ Hash, err error)
UpdateTree updates an existing Git tree with differential changes to blobs and returns the hash of the new tree.
func (*Repository) WithLogger ¶ added in v0.14.0
func (r *Repository) WithLogger(log *silog.Logger) *Repository
WithLogger returns a copy of the repository that will use the given logger.
func (*Repository) Worktrees ¶ added in v0.16.0
func (r *Repository) Worktrees(ctx context.Context) iter.Seq2[*WorktreeListItem, error]
Worktrees returns a list of worktrees associated with the repository.
func (*Repository) WriteObject ¶
WriteObject writes an object of the given type to the repository, and returns the hash of the written object.
type ResetMode ¶
type ResetMode int
ResetMode specifies the reset mode used in the form:
git reset --<mode> <commit>
The default mode is ResetMixed.
const ( // ResetModeUnset is the default reset mode. ResetModeUnset ResetMode = iota // ResetMixed resets the index to the specified commit // but leaves the working tree unchanged. ResetMixed // ResetHard resets the index and working tree to the specified commit. ResetHard // ResetSoft resets HEAD to the specified commit, // leaving the index and working tree unchanged. ResetSoft )
type ResetOptions ¶
type ResetOptions struct {
Quiet bool
Mode ResetMode
// Patch lets the user choose which hunks to stage.
// Mode must be ResetModeUnset.
Patch bool
// Update the index entries for the specified paths only.
// Leave the working tree and the current branch unchanged.
// Mode must be ResetModeUnset.
Paths []string
}
ResetOptions configures the behavior of Reset.
type SetRefRequest ¶
type SetRefRequest struct {
// Ref is the name of the ref to set.
// If the ref is a branch or tag, it should be fully qualified
// (e.g., "refs/heads/main" or "refs/tags/v1.0").
Ref string // required
// Hash is the hash to set the ref to.
Hash Hash // required
// OldHash, if set, specifies the current value of the ref.
// The ref will only be updated if it currently points to OldHash.
// Set this to ZeroHash to ensure that a ref being created
// does not already exist.
OldHash Hash
// Reason, if set, is a human-readable reason for the ref update.
Reason string
}
SetRefRequest is a request to set a ref to a new hash.
type Signature ¶
type Signature struct {
// Name of the signer.
Name string
// Email of the signer.
Email string
// Time at which the signature was made.
// If this is zero, the current time is used.
Time time.Time
}
Signature holds authorship information for a commit.
type TreeEntry ¶
type TreeEntry struct {
// Mode is the file mode of the entry.
//
// For regular files, this is RegularMode.
// For directories, this is DirMode.
Mode Mode
// Type is the type of the entry.
//
// This is either BlobType or TreeType.
Type Type
// Hash is the hash of the entry.
Hash Hash
// Name is the name of the entry.
Name string
}
TreeEntry is a single entry in a Git tree.
type UpdateTreeRequest ¶
type UpdateTreeRequest struct {
// Tree is the starting tree hash.
//
// This may be empty or [ZeroHash] to start with an empty tree.
Tree Hash
// Writes is a sequence of blobs to write to the tree.
Writes []BlobInfo
// Deletes is a set of paths to delete from the tree.
Deletes []string
}
UpdateTreeRequest is a request to update an existing Git tree.
Unlike MakeTree, it's able to operate on paths with slashes.
type Worktree ¶ added in v0.15.0
type Worktree struct {
// contains filtered or unexported fields
}
Worktree is a checkout of a Git repository at a specific path. Operations that require a working tree (e.g. branch checkout, rebase, etc.) are only available on the worktree.
func Clone ¶ added in v0.8.0
Clone clones a Git repository from the given URL to the given directory.
func InitWorktree ¶ added in v0.15.0
InitWorktree initializes a new Git repository at the given directory. If dir is empty, the current working directory is used.
func OpenWorktree ¶ added in v0.15.0
OpenWorktree opens a worktree of this repository at the given directory, automatically detecting the repository's root directory.
func (*Worktree) CheckoutBranch ¶ added in v0.18.0
CheckoutBranch switches to the specified branch. If the branch does not exist, it returns an error.
func (*Worktree) CheckoutFiles ¶ added in v0.18.0
func (w *Worktree) CheckoutFiles(ctx context.Context, req *CheckoutFilesRequest) error
CheckoutFiles checks out files from the specified tree-ish to the working directory. This wraps 'git checkout [<tree-ish>] -- [<pathspec>...]'.
func (*Worktree) Commit ¶ added in v0.15.0
func (w *Worktree) Commit(ctx context.Context, req CommitRequest) error
Commit runs the 'git commit' command, allowing the user to commit changes.
func (*Worktree) CurrentBranch ¶ added in v0.15.0
CurrentBranch reports the current branch name. It returns ErrDetachedHead if the repository is in detached HEAD state.
func (*Worktree) DetachHead ¶ added in v0.15.0
DetachHead detaches the HEAD from the current branch and points it to the specified commitish (if provided). Otherwise, it stays at the current commit.
func (*Worktree) DiffIndex ¶ added in v0.15.0
DiffIndex compares the index with the given tree and returns the list of files that are different. The treeish argument can be any valid tree-ish reference.
func (*Worktree) DiffWork ¶ added in v0.19.0
DiffWork compares the working tree with the index and returns an iterator over files that are different.
func (*Worktree) ListFilesPaths ¶ added in v0.15.0
func (w *Worktree) ListFilesPaths(ctx context.Context, opts *ListFilesOptions) iter.Seq2[string, error]
ListFilesPaths lists files in the worktree or the index using the given options to filter.
func (*Worktree) ListUntrackedFiles ¶ added in v0.19.0
ListUntrackedFiles lists untracked files in the worktree.
func (*Worktree) PeelToCommit ¶ added in v0.15.0
PeelToCommit reports the commit hash of the provided commit-ish in the context of the worktree (e.g. HEAD refers to the worktree's HEAD). It returns ErrNotExist if the object does not exist.
func (*Worktree) Pull ¶ added in v0.15.0
func (w *Worktree) Pull(ctx context.Context, opts PullOptions) error
Pull fetches objects and refs from a remote repository and merges them into the current branch.
func (*Worktree) Push ¶ added in v0.15.2
func (w *Worktree) Push(ctx context.Context, opts PushOptions) error
Push pushes objects and refs to a remote repository.
func (*Worktree) Rebase ¶ added in v0.15.0
func (w *Worktree) Rebase(ctx context.Context, req RebaseRequest) (err error)
Rebase runs a git rebase operation with the specified parameters. It returns RebaseInterruptError for known rebase interruptions,
func (*Worktree) RebaseAbort ¶ added in v0.15.0
RebaseAbort aborts an ongoing rebase operation.
func (*Worktree) RebaseContinue ¶ added in v0.15.0
func (w *Worktree) RebaseContinue(ctx context.Context, opts *RebaseContinueOptions) error
RebaseContinue continues an ongoing rebase operation.
func (*Worktree) RebaseState ¶ added in v0.15.0
func (w *Worktree) RebaseState(context.Context) (*RebaseState, error)
RebaseState loads information about an ongoing rebase, or ErrNoRebase if no rebase is in progress.
func (*Worktree) Repository ¶ added in v0.15.0
func (w *Worktree) Repository() *Repository
Repository returns the Git repository that this worktree belongs to.
func (*Worktree) Reset ¶ added in v0.15.0
Reset resets the index and optionally the working tree to the specified commit.
func (*Worktree) RootDir ¶ added in v0.16.0
RootDir returns the absolute path to the root directory of the worktree.
func (*Worktree) StashApply ¶ added in v0.18.0
StashApply applies a stash to the working directory. If stash is not supplied, the most recent stash is applied. Unlike 'stash pop', this accepts a hash string to identify the stash.
func (*Worktree) StashCreate ¶ added in v0.18.0
StashCreate creates a stash entry and returns its object name. It does not store the stash in the stash reflog. Returns ErrNoChanges if there are no changes to stash.
func (*Worktree) StashStore ¶ added in v0.18.0
StashStore stores a stash created by StashCreate in the stash reflog.
type WorktreeListItem ¶ added in v0.16.0
type WorktreeListItem struct {
// Path is the path to the worktree.
// Use this with Repository.OpenWorktree.
Path string
// Bare reports that the worktree is a bare repository.
Bare bool
// Detached reports that the worktree is in a detached HEAD state.
Detached bool
// LockedReason reports why the worktree is locked, if it is.
// It is empty if the worktree is not locked.
LockedReason string
// Branch is the name of the branch checked out in this worktree.
// If empty, the worktree may not have a branch checked out.
Branch string
// Head is the hash of the HEAD commit in this worktree.
Head Hash
}
WorktreeListItem represents a worktree associated with a repository.