Movatterモバイル変換


[0]ホーム

URL:


git

packagemodule
v5.16.4Latest Latest
Warning

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

Go to latest
Published: Nov 23, 2025 License:Apache-2.0Imports:57Imported by:4,756

Details

Repository

github.com/go-git/go-git

Links

README

go-git logoGoDocBuild StatusGo Report Card

go-git is a highly extensible git implementation library written inpure Go.

It can be used to manipulate git repositories at low level(plumbing) or high level(porcelain), through an idiomatic Go API. It also supports several types of storage, such as in-memory filesystems, or custom implementations, thanks to theStorer interface.

It's being actively developed since 2015 and is being used extensively byKeybase,Gitea orPulumi, and by many other libraries and tools.

Project Status

After the legal issues with thesrc-d organization, the lack of update for four months and the requirement to make a hard fork, the project isnow back to normality.

The project is currently actively maintained by individual contributors, including several of the original authors, but also backed by a new company,gitsight, wherego-git is a critical component used at scale.

Comparison with git

go-git aims to be fully compatible withgit, all theporcelain operations are implemented to work exactly asgit does.

git is a humongous project with years of development by thousands of contributors, making it challenging forgo-git to implement all the features. You can find a comparison ofgo-git vsgit in thecompatibility documentation.

Installation

The recommended way to installgo-git is:

import "github.com/go-git/go-git/v5" // with go modules enabled (GO111MODULE=on or outside GOPATH)import "github.com/go-git/go-git" // with go modules disabled

Examples

Please note that theCheckIfError andInfo functions used in the examples are from theexamples package just to be used in the examples.

Basic example

A basic example that mimics the standardgit clone command

// Clone the given repository to the given directoryInfo("git clone https://github.com/go-git/go-git")_, err := git.PlainClone("/tmp/foo", false, &git.CloneOptions{    URL:      "https://github.com/go-git/go-git",    Progress: os.Stdout,})CheckIfError(err)

Outputs:

Counting objects: 4924, done.Compressing objects: 100% (1333/1333), done.Total 4924 (delta 530), reused 6 (delta 6), pack-reused 3533

In-memory example

Cloning a repository into memory and printing the history of HEAD, just likegit log does

// Clones the given repository in memory, creating the remote, the local// branches and fetching the objects, exactly as:Info("git clone https://github.com/go-git/go-billy")r, err := git.Clone(memory.NewStorage(), nil, &git.CloneOptions{    URL: "https://github.com/go-git/go-billy",})CheckIfError(err)// Gets the HEAD history from HEAD, just like this command:Info("git log")// ... retrieves the branch pointed by HEADref, err := r.Head()CheckIfError(err)// ... retrieves the commit historycIter, err := r.Log(&git.LogOptions{From: ref.Hash()})CheckIfError(err)// ... just iterates over the commits, printing iterr = cIter.ForEach(func(c *object.Commit) error {fmt.Println(c)return nil})CheckIfError(err)

Outputs:

commit ded8054fd0c3994453e9c8aacaf48d118d42991eAuthor: Santiago M. Mola <santi@mola.io>Date:   Sat Nov 12 21:18:41 2016 +0100    index: ReadFrom/WriteTo returns IndexReadError/IndexWriteError. (#9)commit df707095626f384ce2dc1a83b30f9a21d69b9dfcAuthor: Santiago M. Mola <santi@mola.io>Date:   Fri Nov 11 13:23:22 2016 +0100    readwriter: fix bug when writing index. (#10)    When using ReadWriter on an existing siva file, absolute offset for    index entries was not being calculated correctly....

You can find thisexample and many others in theexamples folder.

Contribute

Contributions are more than welcome, if you are interested please take a look toourContributing Guidelines.

License

Apache License Version 2.0, seeLICENSE

Documentation

Overview

A highly extensible git implementation in pure Go.

go-git aims to reach the completeness of libgit2 or jgit, nowadays covers themajority of the plumbing read operations and some of the main writeoperations, but lacks the main porcelain operations such as merges.

It is highly extensible, we have been following the open/close principle inits design to facilitate extensions, mainly focusing the efforts on thepersistence of the objects.

Index

Examples

Constants

View Source
const GitDirName = ".git"

GitDirName this is a special folder where all the git stuff is.

Variables

View Source
var (ErrBranchHashExclusive  =errors.New("Branch and Hash are mutually exclusive")ErrCreateRequiresBranch =errors.New("Branch is mandatory when Create is used"))
View Source
var (ErrMissingName    =errors.New("name field is required")ErrMissingTagger  =errors.New("tagger field is required")ErrMissingMessage =errors.New("message field is required"))
View Source
var (NoErrAlreadyUpToDate     =errors.New("already up-to-date")ErrDeleteRefNotSupported =errors.New("server does not support delete-refs")ErrForceNeeded           =errors.New("some refs were not updated")ErrExactSHA1NotSupported =errors.New("server does not support exact SHA1 refspec")ErrEmptyUrls             =errors.New("URLs cannot be empty"))
View Source
var (// ErrBranchExists an error stating the specified branch already existsErrBranchExists =errors.New("branch already exists")// ErrBranchNotFound an error stating the specified branch does not existErrBranchNotFound =errors.New("branch not found")// ErrTagExists an error stating the specified tag already existsErrTagExists =errors.New("tag already exists")// ErrTagNotFound an error stating the specified tag does not existErrTagNotFound =errors.New("tag not found")// ErrFetching is returned when the packfile could not be downloadedErrFetching =errors.New("unable to fetch packfile")ErrInvalidReference            =errors.New("invalid reference, should be a tag or a branch")ErrRepositoryNotExists         =errors.New("repository does not exist")ErrRepositoryIncomplete        =errors.New("repository's commondir path does not exist")ErrRepositoryAlreadyExists     =errors.New("repository already exists")ErrRemoteNotFound              =errors.New("remote not found")ErrRemoteExists                =errors.New("remote already exists")ErrAnonymousRemoteName         =errors.New("anonymous remote name must be 'anonymous'")ErrWorktreeNotProvided         =errors.New("worktree should be provided")ErrIsBareRepository            =errors.New("worktree not available in a bare repository")ErrUnableToResolveCommit       =errors.New("unable to resolve commit")ErrPackedObjectsNotSupported   =errors.New("packed objects not supported")ErrSHA256NotSupported          =errors.New("go-git was not compiled with SHA256 support")ErrAlternatePathNotSupported   =errors.New("alternate path must use the file scheme")ErrUnsupportedMergeStrategy    =errors.New("unsupported merge strategy")ErrFastForwardMergeNotPossible =errors.New("not possible to fast-forward merge changes"))
View Source
var (ErrSubmoduleAlreadyInitialized =errors.New("submodule already initialized")ErrSubmoduleNotInitialized     =errors.New("submodule not initialized"))
View Source
var (ErrWorktreeNotClean                =errors.New("worktree is not clean")ErrSubmoduleNotFound               =errors.New("submodule not found")ErrUnstagedChanges                 =errors.New("worktree contains unstaged changes")ErrGitModulesSymlink               =errors.New(gitmodulesFile + " is a symlink")ErrNonFastForwardUpdate            =errors.New("non-fast-forward update")ErrRestoreWorktreeOnlyNotSupported =errors.New("worktree only is not supported"))
View Source
var (// ErrDestinationExists in an Move operation means that the target exists on// the worktree.ErrDestinationExists =errors.New("destination exists")// ErrGlobNoMatches in an AddGlob if the glob pattern does not match any// files in the worktree.ErrGlobNoMatches =errors.New("glob pattern did not match any files")// ErrUnsupportedStatusStrategy occurs when an invalid StatusStrategy is used// when processing the Worktree status.ErrUnsupportedStatusStrategy =errors.New("unsupported status strategy"))
View Source
var (// ErrEmptyCommit occurs when a commit is attempted using a clean// working tree, with no changes to be committed.ErrEmptyCommit =errors.New("cannot create empty commit: clean working tree"))
View Source
var (ErrHashOrReference =errors.New("ambiguous options, only one of CommitHash or ReferenceName can be passed"))
View Source
var ErrLooseObjectsNotSupported =errors.New("loose objects not supported")
View Source
var (ErrMissingAuthor =errors.New("author field is required"))
View Source
var (ErrMissingURL =errors.New("URL field is required"))
View Source
var (ErrNoRestorePaths =errors.New("you must specify path(s) to restore"))

Functions

This section is empty.

Types

typeAddOptionsadded inv5.2.0

type AddOptions struct {// All equivalent to `git add -A`, update the index not only where the// working tree has a file matching `Path` but also where the index already// has an entry. This adds, modifies, and removes index entries to match the// working tree.  If no `Path` nor `Glob` is given when `All` option is// used, all files in the entire working tree are updated.Allbool// Path is the exact filepath to the file or directory to be added.Pathstring// Glob adds all paths, matching pattern, to the index. If pattern matches a// directory path, all directory contents are added to the index recursively.Globstring// SkipStatus adds the path with no status check. This option is relevant only// when the `Path` option is specified and does not apply when the `All` option is used.// Notice that when passing an ignored path it will be added anyway.// When true it can speed up adding files to the worktree in very large repositories.SkipStatusbool}

AddOptions describes how an `add` operation should be performed

func (*AddOptions)Validateadded inv5.2.0

func (o *AddOptions) Validate(r *Repository)error

Validate validates the fields and sets the default values.

typeBlameResult

type BlameResult struct {// Path is the path of the File that we're blaming.Pathstring// Rev (Revision) is the hash of the specified Commit used to generate this result.Revplumbing.Hash// Lines contains every line with its authorship.Lines []*Line}

BlameResult represents the result of a Blame operation.

funcBlame

func Blame(c *object.Commit, pathstring) (*BlameResult,error)

Blame returns a BlameResult with the information about the last author ofeach line from file `path` at commit `c`.

func (BlameResult)Stringadded inv5.8.0

func (bBlameResult) String()string

String prints the results of a Blame using git-blame's style.

typeCheckoutOptions

type CheckoutOptions struct {// Hash is the hash of a commit or tag to be checked out. If used, HEAD// will be in detached mode. If Create is not used, Branch and Hash are// mutually exclusive.Hashplumbing.Hash// Branch to be checked out, if Branch and Hash are empty is set to `master`.Branchplumbing.ReferenceName// Create a new branch named Branch and start it at Hash.Createbool// Force, if true when switching branches, proceed even if the index or the// working tree differs from HEAD. This is used to throw away local changesForcebool// Keep, if true when switching branches, local changes (the index or the// working tree changes) will be kept so that they can be committed to the// target branch. Force and Keep are mutually exclusive, should not be both// set to true.Keepbool// SparseCheckoutDirectoriesSparseCheckoutDirectories []string}

CheckoutOptions describes how a checkout operation should be performed.

func (*CheckoutOptions)Validate

func (o *CheckoutOptions) Validate()error

Validate validates the fields and sets the default values.

typeCleanOptions

type CleanOptions struct {Dirbool}

CleanOptions describes how a clean should be performed.

typeCloneOptions

type CloneOptions struct {// The (possibly remote) repository URL to clone from.URLstring// Auth credentials, if required, to use with the remote repository.Authtransport.AuthMethod// Name of the remote to be added, by default `origin`.RemoteNamestring// Remote branch to clone.ReferenceNameplumbing.ReferenceName// Fetch only ReferenceName if true.SingleBranchbool// Mirror clones the repository as a mirror.//// Compared to a bare clone, mirror not only maps local branches of the// source to local branches of the target, it maps all refs (including// remote-tracking branches, notes etc.) and sets up a refspec configuration// such that all these refs are overwritten by a git remote update in the// target repository.Mirrorbool// No checkout of HEAD after clone if true.NoCheckoutbool// Limit fetching to the specified number of commits.Depthint// RecurseSubmodules after the clone is created, initialize all submodules// within, using their default settings. This option is ignored if the// cloned repository does not have a worktree.RecurseSubmodulesSubmoduleRescursivity// ShallowSubmodules limit cloning submodules to the 1 level of depth.// It matches the git command --shallow-submodules.ShallowSubmodulesbool// Progress is where the human readable information sent by the server is// stored, if nil nothing is stored and the capability (if supported)// no-progress, is sent to the server to avoid send this information.Progresssideband.Progress// Tags describe how the tags will be fetched from the remote repository,// by default is AllTags.TagsTagMode// InsecureSkipTLS skips SSL verification if protocol is HTTPS.InsecureSkipTLSbool// ClientCert is the client certificate to use for mutual TLS authentication// over the HTTPS protocol.ClientCert []byte// ClientKey is the client key to use for mutual TLS authentication over// the HTTPS protocol.ClientKey []byte// CABundle specifies an additional CA bundle to use together with the// system cert pool.CABundle []byte// ProxyOptions provides info required for connecting to a proxy.ProxyOptionstransport.ProxyOptions// When the repository to clone is on the local machine, instead of// using hard links, automatically setup .git/objects/info/alternates// to share the objects with the source repository.// The resulting repository starts out without any object of its own.// NOTE: this is a possibly dangerous operation; do not use it unless// you understand what it does.//// [Reference]:https://git-scm.com/docs/git-clone#Documentation/git-clone.txt---sharedSharedbool}

CloneOptions describes how a clone should be performed.

func (*CloneOptions)Validate

func (o *CloneOptions) Validate()error

Validate validates the fields and sets the default values.

typeCommitOptions

type CommitOptions struct {// All automatically stage files that have been modified and deleted, but// new files you have not told Git about are not affected.Allbool// AllowEmptyCommits enable empty commits to be created. An empty commit// is when no changes to the tree were made, but a new commit message is// provided. The default behavior is false, which results in ErrEmptyCommit.AllowEmptyCommitsbool// Author is the author's signature of the commit. If Author is empty the// Name and Email is read from the config, and time.Now it's used as When.Author *object.Signature// Committer is the committer's signature of the commit. If Committer is// nil the Author signature is used.Committer *object.Signature// Parents are the parents commits for the new commit, by default when// len(Parents) is zero, the hash of HEAD reference is used.Parents []plumbing.Hash// SignKey denotes a key to sign the commit with. A nil value here means the// commit will not be signed. The private key must be present and already// decrypted.SignKey *openpgp.Entity// Signer denotes a cryptographic signer to sign the commit with.// A nil value here means the commit will not be signed.// Takes precedence over SignKey.SignerSigner// Amend will create a new commit object and replace the commit that HEAD currently// points to. Cannot be used with All nor Parents.Amendbool}

CommitOptions describes how a commit operation should be performed.

func (*CommitOptions)Validate

func (o *CommitOptions) Validate(r *Repository)error

Validate validates the fields and sets the default values.

typeCreateTagOptions

type CreateTagOptions struct {// Tagger defines the signature of the tag creator. If Tagger is empty the// Name and Email is read from the config, and time.Now it's used as When.Tagger *object.Signature// Message defines the annotation of the tag. It is canonicalized during// validation into the format expected by git - no leading whitespace and// ending in a newline.Messagestring// SignKey denotes a key to sign the tag with. A nil value here means the tag// will not be signed. The private key must be present and already decrypted.SignKey *openpgp.Entity}

CreateTagOptions describes how a tag object should be created.

func (*CreateTagOptions)Validate

func (o *CreateTagOptions) Validate(r *Repository, hashplumbing.Hash)error

Validate validates the fields and sets the default values.

typeFetchOptions

type FetchOptions struct {// Name of the remote to fetch from. Defaults to origin.RemoteNamestring// RemoteURL overrides the remote repo address with a custom URLRemoteURLstringRefSpecs  []config.RefSpec// Depth limit fetching to the specified number of commits from the tip of// each remote branch history.Depthint// Auth credentials, if required, to use with the remote repository.Authtransport.AuthMethod// Progress is where the human readable information sent by the server is// stored, if nil nothing is stored and the capability (if supported)// no-progress, is sent to the server to avoid send this information.Progresssideband.Progress// Tags describe how the tags will be fetched from the remote repository,// by default is TagFollowing.TagsTagMode// Force allows the fetch to update a local branch even when the remote// branch does not descend from it.Forcebool// InsecureSkipTLS skips SSL verification if protocol is HTTPS.InsecureSkipTLSbool// ClientCert is the client certificate to use for mutual TLS authentication// over the HTTPS protocol.ClientCert []byte// ClientKey is the client key to use for mutual TLS authentication over// the HTTPS protocol.ClientKey []byte// CABundle specifies an additional CA bundle to use together with the// system cert pool.CABundle []byte// ProxyOptions provides info required for connecting to a proxy.ProxyOptionstransport.ProxyOptions// Prune specify that local refs that match given RefSpecs and that do// not exist remotely will be removed.Prunebool}

FetchOptions describes how a fetch should be performed

func (*FetchOptions)Validate

func (o *FetchOptions) Validate()error

Validate validates the fields and sets the default values.

typeFileStatus

type FileStatus struct {// Staging is the status of a file in the staging areaStagingStatusCode// Worktree is the status of a file in the worktreeWorktreeStatusCode// Extra contains extra information, such as the previous name in a renameExtrastring}

FileStatus contains the status of a file in the worktree

typeForceWithLeaseadded inv5.5.0

type ForceWithLease struct {// RefName, when set will protect the ref by ensuring it matches the// hash in the ref advertisement.RefNameplumbing.ReferenceName// Hash is the expected object id of RefName. The push will be rejected unless this// matches the corresponding object id of RefName in the refs advertisement.Hashplumbing.Hash}

ForceWithLease sets fields on the leaseIf neither RefName nor Hash are set, ForceWithLease protectsall refs in the refspec by ensuring the ref of the remote in the local repsitorymatches the one in the ref advertisement.

typeGrepOptions

type GrepOptions struct {// Patterns are compiled Regexp objects to be matched.Patterns []*regexp.Regexp// InvertMatch selects non-matching lines.InvertMatchbool// CommitHash is the hash of the commit from which worktree should be derived.CommitHashplumbing.Hash// ReferenceName is the branch or tag name from which worktree should be derived.ReferenceNameplumbing.ReferenceName// PathSpecs are compiled Regexp objects of pathspec to use in the matching.PathSpecs []*regexp.Regexp}

GrepOptions describes how a grep should be performed.

func (*GrepOptions)Validate

func (o *GrepOptions) Validate(w *Worktree)error

Validate validates the fields and sets the default values.

TODO: deprecate in favor of Validate(r *Repository) in v6.

typeGrepResult

type GrepResult struct {// FileName is the name of file which contains match.FileNamestring// LineNumber is the line number of a file at which a match was found.LineNumberint// Content is the content of the file at the matching line.Contentstring// TreeName is the name of the tree (reference name/commit hash) at// which the match was performed.TreeNamestring}

GrepResult is structure of a grep result.

func (GrepResult)String

func (grGrepResult) String()string

typeInitOptionsadded inv5.7.0

type InitOptions struct {// The default branch (e.g. "refs/heads/master")DefaultBranchplumbing.ReferenceName}

typeLine

type Line struct {// Author is the email address of the last author that modified the line.Authorstring// AuthorName is the name of the last author that modified the line.AuthorNamestring// Text is the original text of the line.Textstring// Date is when the original text of the line was introducedDatetime.Time// Hash is the commit hash that introduced the original lineHashplumbing.Hash}

Line values represent the contents and author of a line in BlamedResult values.

typeListOptions

type ListOptions struct {// Auth credentials, if required, to use with the remote repository.Authtransport.AuthMethod// InsecureSkipTLS skips SSL verification if protocol is HTTPS.InsecureSkipTLSbool// ClientCert is the client certificate to use for mutual TLS authentication// over the HTTPS protocol.ClientCert []byte// ClientKey is the client key to use for mutual TLS authentication over// the HTTPS protocol.ClientKey []byte// CABundle specifies an additional CA bundle to use together with the// system cert pool.CABundle []byte// PeelingOption defines how peeled objects are handled during a// remote list.PeelingOptionPeelingOption// ProxyOptions provides info required for connecting to a proxy.ProxyOptionstransport.ProxyOptions// Timeout specifies the timeout in seconds for list operationsTimeoutint}

ListOptions describes how a remote list should be performed.

typeLogOptions

type LogOptions struct {// When the From option is set the log will only contain commits// reachable from it. If this option is not set, HEAD will be used as// the default From.Fromplumbing.Hash// The default traversal algorithm is Depth-first search// set Order=LogOrderCommitterTime for ordering by committer time (more compatible with `git log`)// set Order=LogOrderBSF for Breadth-first searchOrderLogOrder// Show only those commits in which the specified file was inserted/updated.// It is equivalent to running `git log -- <file-name>`.// this field is kept for compatibility, it can be replaced with PathFilterFileName *string// Filter commits based on the path of files that are updated// takes file path as argument and should return true if the file is desired// It can be used to implement `git log -- <path>`// either <path> is a file path, or directory path, or a regexp of file/directory pathPathFilter func(string)bool// Pretend as if all the refs in refs/, along with HEAD, are listed on the command line as <commit>.// It is equivalent to running `git log --all`.// If set on true, the From option will be ignored.Allbool// Show commits more recent than a specific date.// It is equivalent to running `git log --since <date>` or `git log --after <date>`.Since *time.Time// Show commits older than a specific date.// It is equivalent to running `git log --until <date>` or `git log --before <date>`.Until *time.Time}

LogOptions describes how a log action should be performed.

typeLogOrder

type LogOrderint8
const (LogOrderDefaultLogOrder =iotaLogOrderDFSLogOrderDFSPostLogOrderBSFLogOrderCommitterTime)

typeMergeOptionsadded inv5.12.0

type MergeOptions struct {// Strategy defines the merge strategy to be used.StrategyMergeStrategy}

MergeOptions describes how a merge should be performed.

typeMergeStrategyadded inv5.12.0

type MergeStrategyint8

MergeStrategy represents the different types of merge strategies.

const (// FastForwardMerge represents a Git merge strategy where the current// branch can be simply updated to point to the HEAD of the branch being// merged. This is only possible if the history of the branch being merged// is a linear descendant of the current branch, with no conflicting commits.//// This is the default option.FastForwardMergeMergeStrategy =iota)

typeNoMatchingRefSpecErroradded inv5.2.0

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

func (NoMatchingRefSpecError)Erroradded inv5.2.0

func (NoMatchingRefSpecError)Isadded inv5.2.0

typePeelingOptionadded inv5.7.0

type PeelingOptionuint8

PeelingOption represents the different ways to handle peeled references.

Peeled references represent the underlying object of an annotated(or signed) tag. Refer to upstream documentation for more info:https://github.com/git/git/blob/master/Documentation/technical/reftable.txt

const (// IgnorePeeled ignores all peeled reference names. This is the default behavior.IgnorePeeledPeelingOption = 0// OnlyPeeled returns only peeled reference names.OnlyPeeledPeelingOption = 1// AppendPeeled appends peeled reference names to the reference list.AppendPeeledPeelingOption = 2)

typePlainInitOptionsadded inv5.7.0

type PlainInitOptions struct {InitOptions// Determines if the repository will have a worktree (non-bare) or not (bare).BareboolObjectFormatformatcfg.ObjectFormat}

func (*PlainInitOptions)Validateadded inv5.7.0

func (o *PlainInitOptions) Validate()error

Validate validates the fields and sets the default values.

typePlainOpenOptions

type PlainOpenOptions struct {// DetectDotGit defines whether parent directories should be// walked until a .git directory or file is found.DetectDotGitbool// Enable .git/commondir support (seehttps://git-scm.com/docs/gitrepository-layout#Documentation/gitrepository-layout.txt).// NOTE: This option will only work with the filesystem storage.EnableDotGitCommonDirbool}

PlainOpenOptions describes how opening a plain repository should beperformed.

func (*PlainOpenOptions)Validate

func (o *PlainOpenOptions) Validate()error

Validate validates the fields and sets the default values.

typePruneHandler

type PruneHandler func(unreferencedObjectHashplumbing.Hash)error

typePruneOptions

type PruneOptions struct {// OnlyObjectsOlderThan if set to non-zero value// selects only objects older than the time provided.OnlyObjectsOlderThantime.Time// Handler is called on matching objectsHandlerPruneHandler}

typePullOptions

type PullOptions struct {// Name of the remote to be pulled. If empty, uses the default.RemoteNamestring// RemoteURL overrides the remote repo address with a custom URLRemoteURLstring// Remote branch to clone. If empty, uses HEAD.ReferenceNameplumbing.ReferenceName// Fetch only ReferenceName if true.SingleBranchbool// Limit fetching to the specified number of commits.Depthint// Auth credentials, if required, to use with the remote repository.Authtransport.AuthMethod// RecurseSubmodules controls if new commits of all populated submodules// should be fetched too.RecurseSubmodulesSubmoduleRescursivity// Progress is where the human readable information sent by the server is// stored, if nil nothing is stored and the capability (if supported)// no-progress, is sent to the server to avoid send this information.Progresssideband.Progress// Force allows the pull to update a local branch even when the remote// branch does not descend from it.Forcebool// InsecureSkipTLS skips SSL verification if protocol is HTTPS.InsecureSkipTLSbool// ClientCert is the client certificate to use for mutual TLS authentication// over the HTTPS protocol.ClientCert []byte// ClientKey is the client key to use for mutual TLS authentication over// the HTTPS protocol.ClientKey []byte// CABundle specifies an additional CA bundle to use together with the// system cert pool.CABundle []byte// ProxyOptions provides info required for connecting to a proxy.ProxyOptionstransport.ProxyOptions}

PullOptions describes how a pull should be performed.

func (*PullOptions)Validate

func (o *PullOptions) Validate()error

Validate validates the fields and sets the default values.

typePushOptions

type PushOptions struct {// RemoteName is the name of the remote to be pushed to.RemoteNamestring// RemoteURL overrides the remote repo address with a custom URLRemoteURLstring// RefSpecs specify what destination ref to update with what source object.//// The format of a <refspec> parameter is an optional plus +, followed by//  the source object <src>, followed by a colon :, followed by the destination ref <dst>.// The <src> is often the name of the branch you would want to push, but it can be a SHA-1.// The <dst> tells which ref on the remote side is updated with this push.//// A refspec with empty src can be used to delete a reference.RefSpecs []config.RefSpec// Auth credentials, if required, to use with the remote repository.Authtransport.AuthMethod// Progress is where the human readable information sent by the server is// stored, if nil nothing is stored.Progresssideband.Progress// Prune specify that remote refs that match given RefSpecs and that do// not exist locally will be removed.Prunebool// Force allows the push to update a remote branch even when the local// branch does not descend from it.Forcebool// InsecureSkipTLS skips SSL verification if protocol is HTTPS.InsecureSkipTLSbool// ClientCert is the client certificate to use for mutual TLS authentication// over the HTTPS protocol.ClientCert []byte// ClientKey is the client key to use for mutual TLS authentication over// the HTTPS protocol.ClientKey []byte// CABundle specifies an additional CA bundle to use together with the// system cert pool.CABundle []byte// RequireRemoteRefs only allows a remote ref to be updated if its current// value is the one specified here.RequireRemoteRefs []config.RefSpec// FollowTags will send any annotated tags with a commit target reachable from// the refs already being pushedFollowTagsbool// ForceWithLease allows a force push as long as the remote ref adheres to a "lease"ForceWithLease *ForceWithLease// PushOptions sets options to be transferred to the server during push.Options map[string]string// Atomic sets option to be an atomic pushAtomicbool// ProxyOptions provides info required for connecting to a proxy.ProxyOptionstransport.ProxyOptions}

PushOptions describes how a push should be performed.

func (*PushOptions)Validate

func (o *PushOptions) Validate()error

Validate validates the fields and sets the default values.

typeRemote

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

Remote represents a connection to a remote repository.

funcNewRemote

func NewRemote(sstorage.Storer, c *config.RemoteConfig) *Remote

NewRemote creates a new Remote.The intended purpose is to use the Remote for tasks such as listing remote references (like using git ls-remote).Otherwise Remotes should be created via the use of a Repository.

func (*Remote)Config

func (r *Remote) Config() *config.RemoteConfig

Config returns the RemoteConfig object used to instantiate this Remote.

func (*Remote)Fetch

func (r *Remote) Fetch(o *FetchOptions)error

Fetch fetches references along with the objects necessary to complete theirhistories.

Returns nil if the operation is successful, NoErrAlreadyUpToDate if there areno changes to be fetched, or an error.

func (*Remote)FetchContext

func (r *Remote) FetchContext(ctxcontext.Context, o *FetchOptions)error

FetchContext fetches references along with the objects necessary to completetheir histories.

Returns nil if the operation is successful, NoErrAlreadyUpToDate if there areno changes to be fetched, or an error.

The provided Context must be non-nil. If the context expires before theoperation is complete, an error is returned. The context only affects thetransport operations.

func (*Remote)List

func (r *Remote) List(o *ListOptions) (rfs []*plumbing.Reference, errerror)

func (*Remote)ListContextadded inv5.4.0

func (r *Remote) ListContext(ctxcontext.Context, o *ListOptions) (rfs []*plumbing.Reference, errerror)

List the references on the remote repository.The provided Context must be non-nil. If the context expires before theoperation is complete, an error is returned. The context only affects to thetransport operations.

func (*Remote)Push

func (r *Remote) Push(o *PushOptions)error

Push performs a push to the remote. Returns NoErrAlreadyUpToDate if theremote was already up-to-date.

func (*Remote)PushContext

func (r *Remote) PushContext(ctxcontext.Context, o *PushOptions) (errerror)

PushContext performs a push to the remote. Returns NoErrAlreadyUpToDate ifthe remote was already up-to-date.

The provided Context must be non-nil. If the context expires before theoperation is complete, an error is returned. The context only affects thetransport operations.

func (*Remote)String

func (r *Remote) String()string

typeRepackConfig

type RepackConfig struct {// UseRefDeltas configures whether packfile encoder will use reference deltas.// By default OFSDeltaObject is used.UseRefDeltasbool// OnlyDeletePacksOlderThan if set to non-zero value// selects only objects older than the time provided.OnlyDeletePacksOlderThantime.Time}

typeRepository

type Repository struct {Storerstorage.Storer// contains filtered or unexported fields}

Repository represents a git repository

funcClone

Clone a repository into the given Storer and worktree Filesystem with thegiven options, if worktree is nil a bare repository is created. If the givenstorer is not empty ErrRepositoryAlreadyExists is returned.

Example
// Filesystem abstraction based on memoryfs := memfs.New()// Git objects storer based on memorystorer := memory.NewStorage()// Clones the repository into the worktree (fs) and stores all the .git// content into the storer_, err := git.Clone(storer, fs, &git.CloneOptions{URL: "https://github.com/git-fixtures/basic.git",})if err != nil {log.Fatal(err)}// Prints the content of the CHANGELOG file from the cloned repositorychangelog, err := fs.Open("CHANGELOG")if err != nil {log.Fatal(err)}io.Copy(os.Stdout, changelog)
Output:Initial changelog

funcCloneContext

func CloneContext(ctxcontext.Context, sstorage.Storer, worktreebilly.Filesystem, o *CloneOptions,) (*Repository,error)

CloneContext a repository into the given Storer and worktree Filesystem withthe given options, if worktree is nil a bare repository is created. If thegiven storer is not empty ErrRepositoryAlreadyExists is returned.

The provided Context must be non-nil. If the context expires before theoperation is complete, an error is returned. The context only affects thetransport operations.

funcInit

func Init(sstorage.Storer, worktreebilly.Filesystem) (*Repository,error)

Init creates an empty git repository, based on the given Storer and worktree.The worktree Filesystem is optional, if nil a bare repository is created. Ifthe given storer is not empty ErrRepositoryAlreadyExists is returned

funcInitWithOptionsadded inv5.7.0

func InitWithOptions(sstorage.Storer, worktreebilly.Filesystem, optionsInitOptions) (*Repository,error)

funcOpen

func Open(sstorage.Storer, worktreebilly.Filesystem) (*Repository,error)

Open opens a git repository using the given Storer and worktree filesystem,if the given storer is complete empty ErrRepositoryNotExists is returned.The worktree can be nil when the repository being opened is bare, if therepository is a normal one (not bare) and worktree is nil the errErrWorktreeNotProvided is returned

funcPlainClone

func PlainClone(pathstring, isBarebool, o *CloneOptions) (*Repository,error)

PlainClone a repository into the path with the given options, isBare definesif the new repository will be bare or normal. If the path is not emptyErrRepositoryAlreadyExists is returned.

TODO(mcuadros): move isBare to CloneOptions in v5

Example
// Tempdir to clone the repositorydir, err := os.MkdirTemp("", "clone-example")if err != nil {log.Fatal(err)}defer os.RemoveAll(dir) // clean up// Clones the repository into the given dir, just as a normal git clone does_, err = git.PlainClone(dir, false, &git.CloneOptions{URL: "https://github.com/git-fixtures/basic.git",})if err != nil {log.Fatal(err)}// Prints the content of the CHANGELOG file from the cloned repositorychangelog, err := os.Open(filepath.Join(dir, "CHANGELOG"))if err != nil {log.Fatal(err)}io.Copy(os.Stdout, changelog)
Output:Initial changelog
Example (AccessToken)
// Tempdir to clone the repositorydir, err := os.MkdirTemp("", "clone-example")if err != nil {log.Fatal(err)}defer os.RemoveAll(dir) // clean up// Clones the repository into the given dir, just as a normal git clone does_, err = git.PlainClone(dir, false, &git.CloneOptions{URL: "https://github.com/git-fixtures/basic.git",Auth: &http.BasicAuth{Username: "abc123", // anything except an empty stringPassword: "github_access_token",},})if err != nil {log.Fatal(err)}
Example (UsernamePassword)
// Tempdir to clone the repositorydir, err := os.MkdirTemp("", "clone-example")if err != nil {log.Fatal(err)}defer os.RemoveAll(dir) // clean up// Clones the repository into the given dir, just as a normal git clone does_, err = git.PlainClone(dir, false, &git.CloneOptions{URL: "https://github.com/git-fixtures/basic.git",Auth: &http.BasicAuth{Username: "username",Password: "password",},})if err != nil {log.Fatal(err)}

funcPlainCloneContext

func PlainCloneContext(ctxcontext.Context, pathstring, isBarebool, o *CloneOptions) (*Repository,error)

PlainCloneContext a repository into the path with the given options, isBaredefines if the new repository will be bare or normal. If the path is not emptyErrRepositoryAlreadyExists is returned.

The provided Context must be non-nil. If the context expires before theoperation is complete, an error is returned. The context only affects thetransport operations.

TODO(mcuadros): move isBare to CloneOptions in v5TODO(smola): refuse upfront to clone on a non-empty directory in v5, see #1027

funcPlainInit

func PlainInit(pathstring, isBarebool) (*Repository,error)

PlainInit create an empty git repository at the given path. isBare definesif the repository will have worktree (non-bare) or not (bare), if the pathis not empty ErrRepositoryAlreadyExists is returned.

funcPlainInitWithOptionsadded inv5.7.0

func PlainInitWithOptions(pathstring, opts *PlainInitOptions) (*Repository,error)

funcPlainOpen

func PlainOpen(pathstring) (*Repository,error)

PlainOpen opens a git repository from the given path. It detects if therepository is bare or a normal one. If the path doesn't contain a validrepository ErrRepositoryNotExists is returned

funcPlainOpenWithOptions

func PlainOpenWithOptions(pathstring, o *PlainOpenOptions) (*Repository,error)

PlainOpenWithOptions opens a git repository from the given path with specificoptions. See PlainOpen for more info.

func (*Repository)BlobObject

func (r *Repository) BlobObject(hplumbing.Hash) (*object.Blob,error)

BlobObject returns a Blob with the given hash. If not foundplumbing.ErrObjectNotFound is returned.

func (*Repository)BlobObjects

func (r *Repository) BlobObjects() (*object.BlobIter,error)

BlobObjects returns an unsorted BlobIter with all the blobs in the repository.

func (*Repository)Branch

func (r *Repository) Branch(namestring) (*config.Branch,error)

Branch return a Branch if exists

func (*Repository)Branches

func (r *Repository) Branches() (storer.ReferenceIter,error)

Branches returns all the References that are Branches.

Example
r, _ := git.Clone(memory.NewStorage(), nil, &git.CloneOptions{URL: "https://github.com/git-fixtures/basic.git",})branches, _ := r.Branches()branches.ForEach(func(branch *plumbing.Reference) error {fmt.Println(branch.Hash().String(), branch.Name())return nil})// Example Output:// 6ecf0ef2c2dffb796033e5a02219af86ec6584e5 refs/heads/master

func (*Repository)CommitObject

func (r *Repository) CommitObject(hplumbing.Hash) (*object.Commit,error)

CommitObject return a Commit with the given hash. If not foundplumbing.ErrObjectNotFound is returned.

func (*Repository)CommitObjects

func (r *Repository) CommitObjects() (object.CommitIter,error)

CommitObjects returns an unsorted CommitIter with all the commits in the repository.

func (*Repository)Config

func (r *Repository) Config() (*config.Config,error)

Config return the repository config. In a filesystem backed repository thismeans read the `.git/config`.

func (*Repository)ConfigScopedadded inv5.1.0

func (r *Repository) ConfigScoped(scopeconfig.Scope) (*config.Config,error)

ConfigScoped returns the repository config, merged with requested scope andlower. For example if, config.GlobalScope is given the local and global configare returned merged in one config value.

func (*Repository)CreateBranch

func (r *Repository) CreateBranch(c *config.Branch)error

CreateBranch creates a new Branch

func (*Repository)CreateRemote

func (r *Repository) CreateRemote(c *config.RemoteConfig) (*Remote,error)

CreateRemote creates a new remote

Example
r, _ := git.Init(memory.NewStorage(), nil)// Add a new remote, with the default fetch refspec_, err := r.CreateRemote(&config.RemoteConfig{Name: "example",URLs: []string{"https://github.com/git-fixtures/basic.git"},})if err != nil {log.Fatal(err)}list, err := r.Remotes()if err != nil {log.Fatal(err)}for _, r := range list {fmt.Println(r)}// Example Output:// example https://github.com/git-fixtures/basic.git (fetch)// example https://github.com/git-fixtures/basic.git (push)

func (*Repository)CreateRemoteAnonymous

func (r *Repository) CreateRemoteAnonymous(c *config.RemoteConfig) (*Remote,error)

CreateRemoteAnonymous creates a new anonymous remote. c.Name must be "anonymous".It's used like 'git fetch git@github.com:src-d/go-git.git master:master'.

func (*Repository)CreateTag

func (r *Repository) CreateTag(namestring, hashplumbing.Hash, opts *CreateTagOptions) (*plumbing.Reference,error)

CreateTag creates a tag. If opts is included, the tag is an annotated tag,otherwise a lightweight tag is created.

func (*Repository)DeleteBranch

func (r *Repository) DeleteBranch(namestring)error

DeleteBranch delete a Branch from the repository and delete the config

func (*Repository)DeleteObject

func (r *Repository) DeleteObject(hashplumbing.Hash)error

DeleteObject deletes an object from a repository.The type conveniently matches PruneHandler.

func (*Repository)DeleteRemote

func (r *Repository) DeleteRemote(namestring)error

DeleteRemote delete a remote from the repository and delete the config

func (*Repository)DeleteTag

func (r *Repository) DeleteTag(namestring)error

DeleteTag deletes a tag from the repository.

func (*Repository)Fetch

func (r *Repository) Fetch(o *FetchOptions)error

Fetch fetches references along with the objects necessary to completetheir histories, from the remote named as FetchOptions.RemoteName.

Returns nil if the operation is successful, NoErrAlreadyUpToDate if there areno changes to be fetched, or an error.

func (*Repository)FetchContext

func (r *Repository) FetchContext(ctxcontext.Context, o *FetchOptions)error

FetchContext fetches references along with the objects necessary to completetheir histories, from the remote named as FetchOptions.RemoteName.

Returns nil if the operation is successful, NoErrAlreadyUpToDate if there areno changes to be fetched, or an error.

The provided Context must be non-nil. If the context expires before theoperation is complete, an error is returned. The context only affects thetransport operations.

func (*Repository)Grepadded inv5.7.0

func (r *Repository) Grep(opts *GrepOptions) ([]GrepResult,error)

Grep performs grep on a repository.

func (*Repository)Head

func (r *Repository) Head() (*plumbing.Reference,error)

Head returns the reference where HEAD is pointing to.

func (*Repository)Log

Log returns the commit history from the given LogOptions.

func (*Repository)Mergeadded inv5.12.0

Merge merges the reference branch into the current branch.

If the merge is not possible (or supported) returns an error without changingthe HEAD for the current branch. Possible errors include:

  • The merge strategy is not supported.
  • The specific strategy cannot be used (e.g. using FastForwardMerge when one is not possible).

func (*Repository)Notes

func (r *Repository) Notes() (storer.ReferenceIter,error)

Notes returns all the References that are notes. For more information:https://git-scm.com/docs/git-notes

func (*Repository)Object

Object returns an Object with the given hash. If not foundplumbing.ErrObjectNotFound is returned.

func (*Repository)Objects

func (r *Repository) Objects() (*object.ObjectIter,error)

Objects returns an unsorted ObjectIter with all the objects in the repository.

func (*Repository)Prune

func (r *Repository) Prune(optPruneOptions)error

func (*Repository)Push

func (r *Repository) Push(o *PushOptions)error

Push performs a push to the remote. Returns NoErrAlreadyUpToDate ifthe remote was already up-to-date, from the remote named asFetchOptions.RemoteName.

func (*Repository)PushContext

func (r *Repository) PushContext(ctxcontext.Context, o *PushOptions)error

PushContext performs a push to the remote. Returns NoErrAlreadyUpToDate ifthe remote was already up-to-date, from the remote named asFetchOptions.RemoteName.

The provided Context must be non-nil. If the context expires before theoperation is complete, an error is returned. The context only affects thetransport operations.

func (*Repository)Reference

func (r *Repository) Reference(nameplumbing.ReferenceName, resolvedbool) (*plumbing.Reference,error)

Reference returns the reference for a given reference name. If resolved istrue, any symbolic reference will be resolved.

func (*Repository)References

func (r *Repository) References() (storer.ReferenceIter,error)

References returns an unsorted ReferenceIter for all references.

Example
r, _ := git.Clone(memory.NewStorage(), nil, &git.CloneOptions{URL: "https://github.com/git-fixtures/basic.git",})// simulating a git show-refrefs, _ := r.References()refs.ForEach(func(ref *plumbing.Reference) error {if ref.Type() == plumbing.HashReference {fmt.Println(ref)}return nil})// Example Output:// 6ecf0ef2c2dffb796033e5a02219af86ec6584e5 refs/remotes/origin/master// e8d3ffab552895c19b9fcf7aa264d277cde33881 refs/remotes/origin/branch// 6ecf0ef2c2dffb796033e5a02219af86ec6584e5 refs/heads/master

func (*Repository)Remote

func (r *Repository) Remote(namestring) (*Remote,error)

Remote return a remote if exists

func (*Repository)Remotes

func (r *Repository) Remotes() ([]*Remote,error)

Remotes returns a list with all the remotes

func (*Repository)RepackObjects

func (r *Repository) RepackObjects(cfg *RepackConfig) (errerror)

func (*Repository)ResolveRevision

func (r *Repository) ResolveRevision(inplumbing.Revision) (*plumbing.Hash,error)

ResolveRevision resolves revision to corresponding hash. It will alwaysresolve to a commit hash, not a tree or annotated tag.

Implemented resolvers : HEAD, branch, tag, heads/branch, refs/heads/branch,refs/tags/tag, refs/remotes/origin/branch, refs/remotes/origin/HEAD, tilde and caret (HEAD~1, master~^, tag~2, ref/heads/master~1, ...), selection by text (HEAD^{/fix nasty bug}), hash (prefix and full)

func (*Repository)SetConfigadded inv5.1.0

func (r *Repository) SetConfig(cfg *config.Config)error

SetConfig marshall and writes the repository config. In a filesystem backedrepository this means write the `.git/config`. This function should be calledwith the result of `Repository.Config` and never with the output of`Repository.ConfigScoped`.

func (*Repository)Tag

func (r *Repository) Tag(namestring) (*plumbing.Reference,error)

Tag returns a tag from the repository.

If you want to check to see if the tag is an annotated tag, you can callTagObject on the hash of the reference in ForEach:

ref, err := r.Tag("v0.1.0")if err != nil {  // Handle error}obj, err := r.TagObject(ref.Hash())switch err {case nil:  // Tag object presentcase plumbing.ErrObjectNotFound:  // Not a tag objectdefault:  // Some other error}

func (*Repository)TagObject

func (r *Repository) TagObject(hplumbing.Hash) (*object.Tag,error)

TagObject returns a Tag with the given hash. If not foundplumbing.ErrObjectNotFound is returned. This method only returnsannotated Tags, no lightweight Tags.

func (*Repository)TagObjects

func (r *Repository) TagObjects() (*object.TagIter,error)

TagObjects returns a unsorted TagIter that can step through all of the annotatedtags in the repository.

func (*Repository)Tags

Tags returns all the tag References in a repository.

If you want to check to see if the tag is an annotated tag, you can callTagObject on the hash Reference passed in through ForEach:

iter, err := r.Tags()if err != nil {  // Handle error}if err := iter.ForEach(func (ref *plumbing.Reference) error {  obj, err := r.TagObject(ref.Hash())  switch err {  case nil:    // Tag object present  case plumbing.ErrObjectNotFound:    // Not a tag object  default:    // Some other error    return err  }}); err != nil {  // Handle outer iterator error}

func (*Repository)TreeObject

func (r *Repository) TreeObject(hplumbing.Hash) (*object.Tree,error)

TreeObject return a Tree with the given hash. If not foundplumbing.ErrObjectNotFound is returned

func (*Repository)TreeObjects

func (r *Repository) TreeObjects() (*object.TreeIter,error)

TreeObjects returns an unsorted TreeIter with all the trees in the repository

func (*Repository)Worktree

func (r *Repository) Worktree() (*Worktree,error)

Worktree returns a worktree based on the given fs, if nil the defaultworktree will be used.

typeResetMode

type ResetModeint8

ResetMode defines the mode of a reset operation.

const (// MixedReset resets the index but not the working tree (i.e., the changed// files are preserved but not marked for commit) and reports what has not// been updated. This is the default action.MixedResetResetMode =iota// HardReset resets the index and working tree. Any changes to tracked files// in the working tree are discarded.HardReset// MergeReset resets the index and updates the files in the working tree// that are different between Commit and HEAD, but keeps those which are// different between the index and working tree (i.e. which have changes// which have not been added).//// If a file that is different between Commit and the index has unstaged// changes, reset is aborted.MergeReset// SoftReset does not touch the index file or the working tree at all (but// resets the head to <commit>, just like all modes do). This leaves all// your changed files "Changes to be committed", as git status would put it.SoftReset)

typeResetOptions

type ResetOptions struct {// Commit, if commit is present set the current branch head (HEAD) to it.Commitplumbing.Hash// Mode, form resets the current branch head to Commit and possibly updates// the index (resetting it to the tree of Commit) and the working tree// depending on Mode. If empty MixedReset is used.ModeResetMode// Files, if not empty will constrain the reseting the index to only files// specified in this list.Files []string}

ResetOptions describes how a reset operation should be performed.

func (*ResetOptions)Validate

func (o *ResetOptions) Validate(r *Repository)error

Validate validates the fields and sets the default values.

typeRestoreOptionsadded inv5.13.0

type RestoreOptions struct {// Marks to restore the content in the indexStagedbool// Marks to restore the content of the working treeWorktreebool// List of file paths that will be restoredFiles []string}

RestoreOptions describes how a restore should be performed.

func (*RestoreOptions)Validateadded inv5.13.0

func (o *RestoreOptions) Validate()error

Validate validates the fields and sets the default values.

typeSigneradded inv5.12.0

type Signer interface {Sign(messageio.Reader) ([]byte,error)}

Signer is an interface for signing git objects.message is a reader containing the encoded object to be signed.Implementors should return the encoded signature and an error if any.Seehttps://git-scm.com/docs/gitformat-signature for more information.

Example
package mainimport ("encoding/base64""fmt""io""time""github.com/go-git/go-billy/v5/memfs""github.com/go-git/go-git/v5/plumbing/object""github.com/go-git/go-git/v5/storage/memory")type b64signer struct{}// This is not secure, and is only used as an example for testing purposes.// Please don't do this.func (b64signer) Sign(message io.Reader) ([]byte, error) {b, err := io.ReadAll(message)if err != nil {return nil, err}out := make([]byte, base64.StdEncoding.EncodedLen(len(b)))base64.StdEncoding.Encode(out, b)return out, nil}func main() {repo, err := Init(memory.NewStorage(), memfs.New())if err != nil {panic(err)}w, err := repo.Worktree()if err != nil {panic(err)}commit, err := w.Commit("example commit", &CommitOptions{Author: &object.Signature{Name:  "John Doe",Email: "john@example.com",When:  time.UnixMicro(1234567890).UTC(),},Signer:            b64signer{},AllowEmptyCommits: true,})if err != nil {panic(err)}obj, err := repo.CommitObject(commit)if err != nil {panic(err)}fmt.Println(obj.PGPSignature)}
Output:dHJlZSA0YjgyNWRjNjQyY2I2ZWI5YTA2MGU1NGJmOGQ2OTI4OGZiZWU0OTA0CmF1dGhvciBKb2huIERvZSA8am9obkBleGFtcGxlLmNvbT4gMTIzNCArMDAwMApjb21taXR0ZXIgSm9obiBEb2UgPGpvaG5AZXhhbXBsZS5jb20+IDEyMzQgKzAwMDAKCmV4YW1wbGUgY29tbWl0

typeStatus

type Status map[string]*FileStatus

Status represents the current status of a Worktree.The key of the map is the path of the file.

func (Status)File

func (sStatus) File(pathstring) *FileStatus

File returns the FileStatus for a given path, if the FileStatus doesn'texists a new FileStatus is added to the map using the path as key.

func (Status)IsClean

func (sStatus) IsClean()bool

IsClean returns true if all the files are in Unmodified status.

func (Status)IsUntracked

func (sStatus) IsUntracked(pathstring)bool

IsUntracked checks if file for given path is 'Untracked'

func (Status)String

func (sStatus) String()string

typeStatusCode

type StatusCodebyte

StatusCode status code of a file in the Worktree

const (UnmodifiedStatusCode = ' 'UntrackedStatusCode = '?'ModifiedStatusCode = 'M'AddedStatusCode = 'A'DeletedStatusCode = 'D'RenamedStatusCode = 'R'CopiedStatusCode = 'C'UpdatedButUnmergedStatusCode = 'U')

typeStatusOptionsadded inv5.13.0

type StatusOptions struct {StrategyStatusStrategy}

StatusOptions defines the options for Worktree.StatusWithOptions().

typeStatusStrategyadded inv5.13.0

type StatusStrategyint

StatusStrategy defines the different types of strategies when processingthe worktree status.

const (// Empty starts its status map from empty. Missing entries for a given// path means that the file is untracked. This causes a known issue (#119)// whereby unmodified files can be incorrectly reported as untracked.//// This can be used when returning the changed state within a modified Worktree.// For example, to check whether the current worktree is clean.EmptyStatusStrategy = 0// Preload goes through all existing nodes from the index and add them to the// status map as unmodified. This is currently the most reliable strategy// although it comes at a performance cost in large repositories.//// This method is recommended when fetching the status of unmodified files.// For example, to confirm the status of a specific file that is either// untracked or unmodified.PreloadStatusStrategy = 1)

typeSubmodule

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

Submodule a submodule allows you to keep another Git repository in asubdirectory of your repository.

func (*Submodule)Config

func (s *Submodule) Config() *config.Submodule

Config returns the submodule config

func (*Submodule)Init

func (s *Submodule) Init()error

Init initialize the submodule reading the recorded Entry in the index forthe given submodule

func (*Submodule)Repository

func (s *Submodule) Repository() (*Repository,error)

Repository returns the Repository represented by this submodule

func (*Submodule)Status

func (s *Submodule) Status() (*SubmoduleStatus,error)

Status returns the status of the submodule.

func (*Submodule)Update

Update the registered submodule to match what the superproject expects, thesubmodule should be initialized first calling the Init method or setting inthe options SubmoduleUpdateOptions.Init equals true

func (*Submodule)UpdateContext

func (s *Submodule) UpdateContext(ctxcontext.Context, o *SubmoduleUpdateOptions)error

UpdateContext the registered submodule to match what the superprojectexpects, the submodule should be initialized first calling the Init method orsetting in the options SubmoduleUpdateOptions.Init equals true.

The provided Context must be non-nil. If the context expires before theoperation is complete, an error is returned. The context only affects thetransport operations.

typeSubmoduleRescursivity

type SubmoduleRescursivityuint

SubmoduleRescursivity defines how depth will affect any submodule recursiveoperation.

const (// DefaultRemoteName name of the default Remote, just like git command.DefaultRemoteName = "origin"// NoRecurseSubmodules disables the recursion for a submodule operation.NoRecurseSubmodulesSubmoduleRescursivity = 0// DefaultSubmoduleRecursionDepth allow recursion in a submodule operation.DefaultSubmoduleRecursionDepthSubmoduleRescursivity = 10)

typeSubmoduleStatus

type SubmoduleStatus struct {PathstringCurrentplumbing.HashExpectedplumbing.HashBranchplumbing.ReferenceName}

SubmoduleStatus contains the status for a submodule in the worktree

func (*SubmoduleStatus)IsClean

func (s *SubmoduleStatus) IsClean()bool

IsClean is the HEAD of the submodule is equals to the expected commit

func (*SubmoduleStatus)String

func (s *SubmoduleStatus) String()string

String is equivalent to `git submodule status <submodule>`

This will print the SHA-1 of the currently checked out commit for asubmodule, along with the submodule path and the output of git describe fothe SHA-1. Each SHA-1 will be prefixed with - if the submodule is notinitialized, + if the currently checked out submodule commit does not matchthe SHA-1 found in the index of the containing repository.

typeSubmoduleUpdateOptions

type SubmoduleUpdateOptions struct {// Init, if true initializes the submodules recorded in the index.Initbool// NoFetch tell to the update command to not fetch new objects from the// remote site.NoFetchbool// RecurseSubmodules the update is performed not only in the submodules of// the current repository but also in any nested submodules inside those// submodules (and so on). Until the SubmoduleRescursivity is reached.RecurseSubmodulesSubmoduleRescursivity// Auth credentials, if required, to use with the remote repository.Authtransport.AuthMethod// Depth limit fetching to the specified number of commits from the tip of// each remote branch history.Depthint}

SubmoduleUpdateOptions describes how a submodule update should be performed.

typeSubmodules

type Submodules []*Submodule

Submodules list of several submodules from the same repository.

func (Submodules)Init

func (sSubmodules) Init()error

Init initializes the submodules in this list.

func (Submodules)Status

func (sSubmodules) Status() (SubmodulesStatus,error)

Status returns the status of the submodules.

func (Submodules)Update

Update updates all the submodules in this list.

func (Submodules)UpdateContext

UpdateContext updates all the submodules in this list.

The provided Context must be non-nil. If the context expires before theoperation is complete, an error is returned. The context only affects thetransport operations.

typeSubmodulesStatus

type SubmodulesStatus []*SubmoduleStatus

SubmodulesStatus contains the status for all submodiles in the worktree

func (SubmodulesStatus)String

func (sSubmodulesStatus) String()string

String is equivalent to `git submodule status`

typeTagMode

type TagModeint
const (InvalidTagModeTagMode =iota// TagFollowing any tag that points into the histories being fetched is also// fetched. TagFollowing requires a server with `include-tag` capability// in order to fetch the annotated tags objects.TagFollowing// AllTags fetch all tags from the remote (i.e., fetch remote tags// refs/tags/* into local tags with the same name)AllTags// NoTags fetch no tags from the remote at allNoTags)

typeWorktree

type Worktree struct {// Filesystem underlying filesystem.Filesystembilly.Filesystem// External excludes not found in the repository .gitignoreExcludes []gitignore.Pattern// contains filtered or unexported fields}

Worktree represents a git worktree.

func (*Worktree)Add

func (w *Worktree) Add(pathstring) (plumbing.Hash,error)

Add adds the file contents of a file in the worktree to the index. if thefile is already staged in the index no error is returned. If a file deletedfrom the Workspace is given, the file is removed from the index. If adirectory given, adds the files and all his sub-directories recursively inthe worktree to the index. If any of the files is already staged in the indexno error is returned. When path is a file, the blob.Hash is returned.

func (*Worktree)AddGlob

func (w *Worktree) AddGlob(patternstring)error

AddGlob adds all paths, matching pattern, to the index. If pattern matches adirectory path, all directory contents are added to the index recursively. Noerror is returned if all matching paths are already staged in index.

func (*Worktree)AddWithOptionsadded inv5.2.0

func (w *Worktree) AddWithOptions(opts *AddOptions)error

AddWithOptions file contents to the index, updates the index using thecurrent content found in the working tree, to prepare the content staged forthe next commit.

It typically adds the current content of existing paths as a whole, but withsome options it can also be used to add content with only part of the changesmade to the working tree files applied, or remove paths that do not exist inthe working tree anymore.

func (*Worktree)Checkout

func (w *Worktree) Checkout(opts *CheckoutOptions)error

Checkout switch branches or restore working tree files.

func (*Worktree)Clean

func (w *Worktree) Clean(opts *CleanOptions)error

Clean the worktree by removing untracked files.An empty dir could be removed - this is what `git clean -f -d .` does.

func (*Worktree)Commit

func (w *Worktree) Commit(msgstring, opts *CommitOptions) (plumbing.Hash,error)

Commit stores the current contents of the index in a new commit along witha log message from the user describing the changes.

func (*Worktree)Grep

func (w *Worktree) Grep(opts *GrepOptions) ([]GrepResult,error)

Grep performs grep on a worktree.

func (*Worktree)Move

func (w *Worktree) Move(from, tostring) (plumbing.Hash,error)

Move moves or rename a file in the worktree and the index, directories arenot supported.

func (*Worktree)Pull

func (w *Worktree) Pull(o *PullOptions)error

Pull incorporates changes from a remote repository into the current branch.Returns nil if the operation is successful, NoErrAlreadyUpToDate if there areno changes to be fetched, or an error.

Pull only supports merges where the can be resolved as a fast-forward.

func (*Worktree)PullContext

func (w *Worktree) PullContext(ctxcontext.Context, o *PullOptions)error

PullContext incorporates changes from a remote repository into the currentbranch. Returns nil if the operation is successful, NoErrAlreadyUpToDate ifthere are no changes to be fetched, or an error.

Pull only supports merges where the can be resolved as a fast-forward.

The provided Context must be non-nil. If the context expires before theoperation is complete, an error is returned. The context only affects thetransport operations.

func (*Worktree)Remove

func (w *Worktree) Remove(pathstring) (plumbing.Hash,error)

Remove removes files from the working tree and from the index.

func (*Worktree)RemoveGlob

func (w *Worktree) RemoveGlob(patternstring)error

RemoveGlob removes all paths, matching pattern, from the index. If patternmatches a directory path, all directory contents are removed from the indexrecursively.

func (*Worktree)Reset

func (w *Worktree) Reset(opts *ResetOptions)error

Reset the worktree to a specified state.

func (*Worktree)ResetSparselyadded inv5.5.0

func (w *Worktree) ResetSparsely(opts *ResetOptions, dirs []string)error

func (*Worktree)Restoreadded inv5.13.0

func (w *Worktree) Restore(o *RestoreOptions)error

Restore restores specified files in the working tree or stage with contents froma restore source. If a path is tracked but does not exist in the restore,source, it will be removed to match the source.

If Staged and Worktree are true, then the restore source will be the index.If only Staged is true, then the restore source will be HEAD.If only Worktree is true or neither Staged nor Worktree are true, willresult in ErrRestoreWorktreeOnlyNotSupported because restoring the workingtree while leaving the stage untouched is not currently supported.

Restore with no files specified will return ErrNoRestorePaths.

func (*Worktree)Status

func (w *Worktree) Status() (Status,error)

Status returns the working tree status.

func (*Worktree)StatusWithOptionsadded inv5.13.0

func (w *Worktree) StatusWithOptions(oStatusOptions) (Status,error)

StatusWithOptions returns the working tree status.

func (*Worktree)Submodule

func (w *Worktree) Submodule(namestring) (*Submodule,error)

Submodule returns the submodule with the given name

func (*Worktree)Submodules

func (w *Worktree) Submodules() (Submodules,error)

Submodules returns all the available submodules

Source Files

View all Source files

Directories

PathSynopsis
blamecommand
branchcommand
checkoutcommand
clonecommand
commitcommand
contextcommand
logcommand
lscommand
ls-remotecommand
merge_basecommand
opencommand
progresscommand
pullcommand
pushcommand
remotescommand
restorecommand
revisioncommand
sha256command
showcasecommand
submodulecommand
tagcommand
Package config contains the abstraction of multiple config files
Package config contains the abstraction of multiple config files
internal
revision
Package revision extracts git revision from string More information about revision : https://www.kernel.org/pub/software/scm/git/docs/gitrevisions.html
Package revision extracts git revision from string More information about revision : https://www.kernel.org/pub/software/scm/git/docs/gitrevisions.html
package plumbing implement the core interfaces and structs used by go-git
package plumbing implement the core interfaces and structs used by go-git
format/commitgraph
Package commitgraph implements encoding and decoding of commit-graph files.
Package commitgraph implements encoding and decoding of commit-graph files.
format/commitgraph/v2
Package v2 implements encoding and decoding of commit-graph files.
Package v2 implements encoding and decoding of commit-graph files.
format/config
Package config implements encoding and decoding of git config files.
Package config implements encoding and decoding of git config files.
format/gitignore
Package gitignore implements matching file system paths to gitignore patterns that can be automatically read from a git repository tree in the order of definition priorities.
Package gitignore implements matching file system paths to gitignore patterns that can be automatically read from a git repository tree in the order of definition priorities.
format/idxfile
Package idxfile implements encoding and decoding of packfile idx files.
Package idxfile implements encoding and decoding of packfile idx files.
format/index
Package index implements encoding and decoding of index format files.
Package index implements encoding and decoding of index format files.
format/objfile
Package objfile implements encoding and decoding of object files.
Package objfile implements encoding and decoding of object files.
format/packfile
Package packfile implements encoding and decoding of packfile format.
Package packfile implements encoding and decoding of packfile format.
format/pktline
Package pktline implements reading payloads form pkt-lines and encoding pkt-lines from payloads.
Package pktline implements reading payloads form pkt-lines and encoding pkt-lines from payloads.
hash
package hash provides a way for managing the underlying hash implementations used across go-git.
package hash provides a way for managing the underlying hash implementations used across go-git.
object
Package object contains implementations of all Git objects and utility functions to work with them.
Package object contains implementations of all Git objects and utility functions to work with them.
object/commitgraph
Package commitgraph provides an interface for efficient traversal over Git commit graph either through the regular object storage, or optionally with the index stored in commit-graph file (Git 2.18+).
Package commitgraph provides an interface for efficient traversal over Git commit graph either through the regular object storage, or optionally with the index stored in commit-graph file (Git 2.18+).
protocol/packp/capability
Package capability defines the server and client capabilities.
Package capability defines the server and client capabilities.
protocol/packp/sideband
Package sideband implements a sideband mutiplex/demultiplexer
Package sideband implements a sideband mutiplex/demultiplexer
revlist
Package revlist provides support to access the ancestors of commits, in a similar way as the git-rev-list command.
Package revlist provides support to access the ancestors of commits, in a similar way as the git-rev-list command.
storer
Package storer defines the interfaces to store objects, references, etc.
Package storer defines the interfaces to store objects, references, etc.
transport
Package transport includes the implementation for different transport protocols.
Package transport includes the implementation for different transport protocols.
transport/client
Package client contains helper function to deal with the different client protocols.
Package client contains helper function to deal with the different client protocols.
transport/file
Package file implements the file transport protocol.
Package file implements the file transport protocol.
transport/git
Package git implements the git transport protocol.
Package git implements the git transport protocol.
transport/http
Package http implements the HTTP transport protocol.
Package http implements the HTTP transport protocol.
transport/internal/common
Package common implements the git pack protocol with a pluggable transport.
Package common implements the git pack protocol with a pluggable transport.
transport/server
Package server implements the git server protocol.
Package server implements the git server protocol.
transport/ssh
Package ssh implements the SSH transport protocol.
Package ssh implements the SSH transport protocol.
transport/test
Package test implements common test suite for different transport implementations.
Package test implements common test suite for different transport implementations.
filesystem
Package filesystem is a storage backend base on filesystems
Package filesystem is a storage backend base on filesystems
filesystem/dotgit
https://github.com/git/git/blob/master/Documentation/gitrepository-layout.txt
https://github.com/git/git/blob/master/Documentation/gitrepository-layout.txt
memory
Package memory is a storage backend base on memory
Package memory is a storage backend base on memory
transactional
Package transactional is a transactional implementation of git.Storer, it demux the write and read operation of two separate storers, allowing to merge content calling Storage.Commit.
Package transactional is a transactional implementation of git.Storer, it demux the write and read operation of two separate storers, allowing to merge content calling Storage.Commit.
utils
binary
Package binary implements syntax-sugar functions on top of the standard library binary package
Package binary implements syntax-sugar functions on top of the standard library binary package
diff
Package diff implements line oriented diffs, similar to the ancient Unix diff command.
Package diff implements line oriented diffs, similar to the ancient Unix diff command.
ioutil
Package ioutil implements some I/O utility functions.
Package ioutil implements some I/O utility functions.
merkletrie
Package merkletrie provides support for n-ary trees that are at the same time Merkle trees and Radix trees (tries).
Package merkletrie provides support for n-ary trees that are at the same time Merkle trees and Radix trees (tries).
merkletrie/internal/fsnoder
Package fsnoder allows to create merkletrie noders that resemble file systems, from human readable string descriptions.
Package fsnoder allows to create merkletrie noders that resemble file systems, from human readable string descriptions.
merkletrie/noder
Package noder provide an interface for defining nodes in a merkletrie, their hashes and their paths (a noders and its ancestors).
Package noder provide an interface for defining nodes in a merkletrie, their hashes and their paths (a noders and its ancestors).

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f orF : Jump to
y orY : Canonical URL
go.dev uses cookies from Google to deliver and enhance the quality of its services and to analyze traffic.Learn more.

[8]ページ先頭

©2009-2025 Movatter.jp