A highly extensible git implementation in pure Go.
go-git aims to reach the completeness of libgit2 or jgit, nowadays covers the majority of the plumbing read operations and some of the main write operations, but lacks the main porcelain operations such as merges.
It is highly extensible, we have been following the open/close principle in its design to facilitate extensions, mainly focusing the efforts on the persistence of the objects.
GitDirName this is a special folder where all the git stuff is.
View Sourcevar ( 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") ErrRemoteRefNotFound = errors.New("couldn't find remote ref") )View Source
var ( ErrBranchExists = errors.New("branch already exists") ErrBranchNotFound = errors.New("branch not found") ErrTagExists = errors.New("tag already exists") ErrTagNotFound = errors.New("tag not found") ErrFetching = 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") 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") ErrTargetDirNotEmpty = errors.New("destination path already exists and is not empty") )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") ErrSparseResetDirectoryNotFound = errors.New("sparse-reset directory not found on commit") )View Source
var ( ErrDestinationExists = errors.New("destination exists") ErrGlobNoMatches = errors.New("glob pattern did not match any files") ErrUnsupportedStatusStrategy = errors.New("unsupported status strategy") )View Source
var ErrHashOrReference = errors.New("ambiguous options, only one of CommitHash or ReferenceName can be passed")
This section is empty.
AddOptions describes how an `add` operation should be performed
Validate validates the fields and sets the default values.
BlameResult represents the result of a Blame operation.
Blame returns a BlameResult with the information about the last author of each line from file `path` at commit `c`.
String prints the results of a Blame using git-blame's style.
CheckoutOptions describes how a checkout operation should be performed.
Validate validates the fields and sets the default values.
type CleanOptions struct { Dir bool }
CleanOptions describes how a clean should be performed.
CloneOptions describes how a clone should be performed.
Validate validates the fields and sets the default values.
CommitOptions describes how a commit operation should be performed.
Validate validates the fields and sets the default values.
CreateTagOptions describes how a tag object should be created.
Validate validates the fields and sets the default values.
FetchOptions describes how a fetch should be performed
Validate validates the fields and sets the default values.
FileStatus contains the status of a file in the worktree
ForceWithLease sets fields on the lease If neither RefName nor Hash are set, ForceWithLease protects all refs in the refspec by ensuring the ref of the remote in the local repsitory matches the one in the ref advertisement.
GrepOptions describes how a grep should be performed.
Validate validates the fields and sets the default values.
TODO: deprecate in favor of Validate(r *Repository) in v6.
GrepResult is structure of a grep result.
type InitOption func(*initOptions)
WithDefaultBranch sets the default branch for the new repo (e.g. "refs/heads/master").
WithObjectFormat sets the repository's object format.
func WithWorkTree(worktree billy.Filesystem) InitOption
WithWorkTree sets the worktree filesystem for the repo. If not used, or a `nil` is passed as argument, will result in a bare repository.
Line values represent the contents and author of a line in BlamedResult values.
ListOptions describes how a remote list should be performed.
LogOptions describes how a log action should be performed.
const ( LogOrderDefault LogOrder = iota LogOrderDFS LogOrderDFSPost LogOrderBSF LogOrderCommitterTime LogOrderDFSPostFirstParent )
MergeOptions describes how a merge should be performed.
MergeStrategy represents the different types of merge strategies.
type PlainOpenOptions struct { DetectDotGit bool EnableDotGitCommonDir bool }
PlainOpenOptions describes how opening a plain repository should be performed.
Validate validates the fields and sets the default values.
PullOptions describes how a pull should be performed.
Validate validates the fields and sets the default values.
PushOptions describes how a push should be performed.
Validate validates the fields and sets the default values.
Remote represents a connection to a remote repository.
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.
Config returns the RemoteConfig object used to instantiate this Remote.
Fetch fetches references along with the objects necessary to complete their histories.
Returns nil if the operation is successful, NoErrAlreadyUpToDate if there are no changes to be fetched, or an error.
FetchContext fetches references along with the objects necessary to complete their histories.
Returns nil if the operation is successful, NoErrAlreadyUpToDate if there are no changes to be fetched, or an error.
The provided Context must be non-nil. If the context expires before the operation is complete, an error is returned. The context only affects the transport operations.
List the references on the remote repository. The provided Context must be non-nil. If the context expires before the operation is complete, an error is returned. The context only affects to the transport operations.
Push performs a push to the remote. Returns NoErrAlreadyUpToDate if the remote was already up-to-date.
PushContext performs a push to the remote. Returns NoErrAlreadyUpToDate if the remote was already up-to-date.
The provided Context must be non-nil. If the context expires before the operation is complete, an error is returned. The context only affects the transport operations.
type RepackConfig struct { UseRefDeltas bool OnlyDeletePacksOlderThan time.Time }
Repository represents a git repository
Clone a repository into the given Storer and worktree Filesystem with the given options, if worktree is nil a bare repository is created. If the given storer is not empty ErrTargetDirNotEmpty is returned.
// Filesystem abstraction based on memory fs := memfs.New() // Git objects storer based on memory storer := 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 repository changelog, err := fs.Open("CHANGELOG") if err != nil { log.Fatal(err) } io.Copy(os.Stdout, changelog)
Output: Initial changelog
CloneContext a repository into the given Storer and worktree Filesystem with the given options, if worktree is nil a bare repository is created. If the given storer is not empty ErrTargetDirNotEmpty is returned.
The provided Context must be non-nil. If the context expires before the operation is complete, an error is returned. The context only affects the transport operations.
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. If the given storer is not empty ErrTargetDirNotEmpty is returned
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 the repository is a normal one (not bare) and worktree is nil the err ErrWorktreeNotProvided is returned
PlainClone a repository into the path with the given options, isBare defines if the new repository will be bare or normal. If the path is not empty ErrTargetDirNotEmpty is returned.
// Tempdir to clone the repository dir, 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, &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 repository changelog, err := os.Open(filepath.Join(dir, "CHANGELOG")) if err != nil { log.Fatal(err) } io.Copy(os.Stdout, changelog)
Output: Initial changelog
// Tempdir to clone the repository dir, 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, &git.CloneOptions{ URL: "https://github.com/git-fixtures/basic.git", Auth: &http.BasicAuth{ Username: "abc123", // anything except an empty string Password: "github_access_token", }, }) if err != nil { log.Fatal(err) }
// Tempdir to clone the repository dir, 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, &git.CloneOptions{ URL: "https://github.com/git-fixtures/basic.git", Auth: &http.BasicAuth{ Username: "username", Password: "password", }, }) if err != nil { log.Fatal(err) }
PlainCloneContext a repository into the path with the given options, isBare defines if the new repository will be bare or normal. If the path is not empty ErrTargetDirNotEmpty is returned.
The provided Context must be non-nil. If the context expires before the operation is complete, an error is returned. The context only affects the transport operations.
PlainInit create an empty git repository at the given path. isBare defines if the repository will have worktree (non-bare) or not (bare), if the path is not empty ErrTargetDirNotEmpty is returned.
PlainOpen opens a git repository from the given path. It detects if the repository is bare or a normal one. If the path doesn't contain a valid repository ErrRepositoryNotExists is returned
PlainOpenWithOptions opens a git repository from the given path with specific options. See PlainOpen for more info.
BlobObject returns a Blob with the given hash. If not found plumbing.ErrObjectNotFound is returned.
BlobObjects returns an unsorted BlobIter with all the blobs in the repository.
Branch return a Branch if exists
Branches returns all the References that are Branches.
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
CommitObject return a Commit with the given hash. If not found plumbing.ErrObjectNotFound is returned.
CommitObjects returns an unsorted CommitIter with all the commits in the repository.
Config return the repository config. In a filesystem backed repository this means read the `.git/config`.
ConfigScoped returns the repository config, merged with requested scope and lower. For example if, config.GlobalScope is given the local and global config are returned merged in one config value.
CreateBranch creates a new Branch
CreateRemote creates a new remote
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)
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'.
CreateTag creates a tag. If opts is included, the tag is an annotated tag, otherwise a lightweight tag is created.
DeleteBranch delete a Branch from the repository and delete the config
DeleteObject deletes an object from a repository. The type conveniently matches PruneHandler.
DeleteRemote delete a remote from the repository and delete the config
DeleteTag deletes a tag from the repository.
Fetch fetches references along with the objects necessary to complete their histories, from the remote named as FetchOptions.RemoteName.
Returns nil if the operation is successful, NoErrAlreadyUpToDate if there are no changes to be fetched, or an error.
FetchContext fetches references along with the objects necessary to complete their histories, from the remote named as FetchOptions.RemoteName.
Returns nil if the operation is successful, NoErrAlreadyUpToDate if there are no changes to be fetched, or an error.
The provided Context must be non-nil. If the context expires before the operation is complete, an error is returned. The context only affects the transport operations.
Grep performs grep on a repository.
Head returns the reference where HEAD is pointing to.
Log returns the commit history from the given LogOptions.
Merge merges the reference branch into the current branch.
If the merge is not possible (or supported) returns an error without changing the HEAD for the current branch. Possible errors include:
Object returns an Object with the given hash. If not found plumbing.ErrObjectNotFound is returned.
Objects returns an unsorted ObjectIter with all the objects in the repository.
Push performs a push to the remote. Returns NoErrAlreadyUpToDate if the remote was already up-to-date, from the remote named as FetchOptions.RemoteName.
PushContext performs a push to the remote. Returns NoErrAlreadyUpToDate if the remote was already up-to-date, from the remote named as FetchOptions.RemoteName.
The provided Context must be non-nil. If the context expires before the operation is complete, an error is returned. The context only affects the transport operations.
Reference returns the reference for a given reference name. If resolved is true, any symbolic reference will be resolved.
References returns an unsorted ReferenceIter for all references.
r, _ := git.Clone(memory.NewStorage(), nil, &git.CloneOptions{ URL: "https://github.com/git-fixtures/basic.git", }) // simulating a git show-ref refs, _ := 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
Remote return a remote if exists
Remotes returns a list with all the remotes
ResolveRevision resolves revision to corresponding hash. It will always resolve 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)
SetConfig marshall and writes the repository config. In a filesystem backed repository this means write the `.git/config`. This function should be called with the result of `Repository.Config` and never with the output of `Repository.ConfigScoped`.
Tag returns a tag from the repository.
If you want to check to see if the tag is an annotated tag, you can call TagObject 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 present case plumbing.ErrObjectNotFound: // Not a tag object default: // Some other error }
TagObject returns a Tag with the given hash. If not found plumbing.ErrObjectNotFound is returned. This method only returns annotated Tags, no lightweight Tags.
TagObjects returns a unsorted TagIter that can step through all of the annotated tags in the repository.
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 call TagObject 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 }
TreeObject return a Tree with the given hash. If not found plumbing.ErrObjectNotFound is returned
TreeObjects returns an unsorted TreeIter with all the trees in the repository
Worktree returns a worktree based on the given fs, if nil the default worktree will be used.
ResetMode defines the mode of a reset operation.
const ( MixedReset ResetMode = iota HardReset MergeReset SoftReset )
ResetOptions describes how a reset operation should be performed.
Validate validates the fields and sets the default values.
type RestoreOptions struct { Staged bool Worktree bool Files []string }
RestoreOptions describes how a restore should be performed.
Validate validates the fields and sets the default values.
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. See https://git-scm.com/docs/gitformat-signature for more information.
package main import ( "encoding/base64" "fmt" "io" "time" "github.com/go-git/go-billy/v6/memfs" "github.com/go-git/go-git/v6/plumbing/object" "github.com/go-git/go-git/v6/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(), WithWorkTree(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
Status represents the current status of a Worktree. The key of the map is the path of the file.
File returns the FileStatus for a given path, if the FileStatus doesn't exists a new FileStatus is added to the map using the path as key.
IsClean returns true if all the files are in Unmodified status.
IsUntracked checks if file for given path is 'Untracked'
StatusCode status code of a file in the Worktree
StatusOptions defines the options for Worktree.StatusWithOptions().
StatusStrategy defines the different types of strategies when processing the worktree status.
type Submodule struct { }
Submodule a submodule allows you to keep another Git repository in a subdirectory of your repository.
Config returns the submodule config
Init initialize the submodule reading the recorded Entry in the index for the given submodule
Repository returns the Repository represented by this submodule
Status returns the status of the submodule.
Update the registered submodule to match what the superproject expects, the submodule should be initialized first calling the Init method or setting in the options SubmoduleUpdateOptions.Init equals true
UpdateContext the registered submodule to match what the superproject expects, the submodule should be initialized first calling the Init method or setting in the options SubmoduleUpdateOptions.Init equals true.
The provided Context must be non-nil. If the context expires before the operation is complete, an error is returned. The context only affects the transport operations.
type SubmoduleRecursivity uint
SubmoduleRecursivity defines how depth will affect any submodule recursive operation.
SubmoduleStatus contains the status for a submodule in the worktree
IsClean is the HEAD of the submodule is equals to the expected commit
String is equivalent to `git submodule status <submodule>`
This will print the SHA-1 of the currently checked out commit for a submodule, along with the submodule path and the output of git describe fo the SHA-1. Each SHA-1 will be prefixed with - if the submodule is not initialized, + if the currently checked out submodule commit does not match the SHA-1 found in the index of the containing repository.
SubmoduleUpdateOptions describes how a submodule update should be performed.
Submodules list of several submodules from the same repository.
Init initializes the submodules in this list.
Status returns the status of the submodules.
Update updates all the submodules in this list.
UpdateContext updates all the submodules in this list.
The provided Context must be non-nil. If the context expires before the operation is complete, an error is returned. The context only affects the transport operations.
SubmodulesStatus contains the status for all submodiles in the worktree
String is equivalent to `git submodule status`
type Worktree struct { Filesystem billy.Filesystem Excludes []gitignore.Pattern }
Worktree represents a git worktree.
Add adds the file contents of a file in the worktree to the index. if the file is already staged in the index no error is returned. If a file deleted from the Workspace is given, the file is removed from the index. If a directory given, adds the files and all his sub-directories recursively in the worktree to the index. If any of the files is already staged in the index no error is returned. When path is a file, the blob.Hash is returned.
AddGlob adds all paths, matching pattern, to the index. If pattern matches a directory path, all directory contents are added to the index recursively. No error is returned if all matching paths are already staged in index.
AddWithOptions file contents to the index, updates the index using the current content found in the working tree, to prepare the content staged for the next commit.
It typically adds the current content of existing paths as a whole, but with some options it can also be used to add content with only part of the changes made to the working tree files applied, or remove paths that do not exist in the working tree anymore.
Checkout switch branches or restore working tree files.
Clean the worktree by removing untracked files. An empty dir could be removed - this is what `git clean -f -d .` does.
Commit stores the current contents of the index in a new commit along with a log message from the user describing the changes.
Grep performs grep on a worktree.
Move moves or rename a file in the worktree and the index, directories are not supported.
Pull incorporates changes from a remote repository into the current branch. Returns nil if the operation is successful, NoErrAlreadyUpToDate if there are no changes to be fetched, or an error.
Pull only supports merges where the can be resolved as a fast-forward.
PullContext incorporates changes from a remote repository into the current branch. Returns nil if the operation is successful, NoErrAlreadyUpToDate if there 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 the operation is complete, an error is returned. The context only affects the transport operations.
Remove removes files from the working tree and from the index.
RemoveGlob removes all paths, matching pattern, from the index. If pattern matches a directory path, all directory contents are removed from the index recursively.
Reset the worktree to a specified state.
Restore restores specified files in the working tree or stage with contents from a 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, will result in ErrRestoreWorktreeOnlyNotSupported because restoring the working tree while leaving the stage untouched is not currently supported.
Restore with no files specified will return ErrNoRestorePaths.
Status returns the working tree status.
StatusWithOptions returns the working tree status.
Submodule returns the submodule with the given name
Submodules returns all the available submodules
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4