go-git.v4: gopkg.in/src-d/go-git.v4 Index | Examples | Files | Directories

package git

import "gopkg.in/src-d/go-git.v4"

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.

Index

Examples

Package Files

blame.go common.go doc.go object_walker.go options.go prune.go references.go remote.go repository.go status.go submodule.go worktree.go worktree_commit.go worktree_linux.go worktree_status.go

Constants

const GitDirName = ".git"

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

Variables

var (
    ErrBranchHashExclusive  = errors.New("Branch and Hash are mutually exclusive")
    ErrCreateRequiresBranch = errors.New("Branch is mandatory when Create is used")
)
var (
    ErrMissingName    = errors.New("name field is required")
    ErrMissingTagger  = errors.New("tagger field is required")
    ErrMissingMessage = errors.New("message field is required")
)
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")
)
var (
    // ErrBranchExists an error stating the specified branch already exists
    ErrBranchExists = errors.New("branch already exists")
    // ErrBranchNotFound an error stating the specified branch does not exist
    ErrBranchNotFound = errors.New("branch not found")
    // ErrTagExists an error stating the specified tag already exists
    ErrTagExists = errors.New("tag already exists")
    // ErrTagNotFound an error stating the specified tag does not exist
    ErrTagNotFound = errors.New("tag not found")

    ErrInvalidReference          = errors.New("invalid reference, should be a tag or a branch")
    ErrRepositoryNotExists       = errors.New("repository does not exist")
    ErrRepositoryAlreadyExists   = errors.New("repository already exists")
    ErrRemoteNotFound            = errors.New("remote not found")
    ErrRemoteExists              = errors.New("remote already exists")
    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")
)
var (
    ErrSubmoduleAlreadyInitialized = errors.New("submodule already initialized")
    ErrSubmoduleNotInitialized     = errors.New("submodule not initialized")
)
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")
)
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")
)
var (
    ErrHashOrReference = errors.New("ambiguous options, only one of CommitHash or ReferenceName can be passed")
)
var ErrLooseObjectsNotSupported = errors.New("Loose objects not supported")
var (
    ErrMissingAuthor = errors.New("author field is required")
)
var (
    ErrMissingURL = errors.New("URL field is required")
)

type BlameResult Uses

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

BlameResult represents the result of a Blame operation.

func Blame Uses

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

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

type CheckoutOptions Uses

type CheckoutOptions struct {
    // Hash is the hash of the commit to be checked out. If used, HEAD will be
    // in detached mode. If Create is not used, Branch and Hash are mutually
    // exclusive.
    Hash plumbing.Hash
    // Branch to be checked out, if Branch and Hash are empty is set to `master`.
    Branch plumbing.ReferenceName
    // Create a new branch named Branch and start it at Hash.
    Create bool
    // 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 changes
    Force bool
}

CheckoutOptions describes how a checkout 31operation should be performed.

func (*CheckoutOptions) Validate Uses

func (o *CheckoutOptions) Validate() error

Validate validates the fields and sets the default values.

type CleanOptions Uses

type CleanOptions struct {
    Dir bool
}

CleanOptions describes how a clean should be performed.

type CloneOptions Uses

type CloneOptions struct {
    // The (possibly remote) repository URL to clone from.
    URL string
    // Auth credentials, if required, to use with the remote repository.
    Auth transport.AuthMethod
    // Name of the remote to be added, by default `origin`.
    RemoteName string
    // Remote branch to clone.
    ReferenceName plumbing.ReferenceName
    // Fetch only ReferenceName if true.
    SingleBranch bool
    // No checkout of HEAD after clone if true.
    NoCheckout bool
    // Limit fetching to the specified number of commits.
    Depth int
    // 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.
    RecurseSubmodules SubmoduleRescursivity
    // 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.
    Progress sideband.Progress
    // Tags describe how the tags will be fetched from the remote repository,
    // by default is AllTags.
    Tags TagMode
}

CloneOptions describes how a clone should be performed.

func (*CloneOptions) Validate Uses

func (o *CloneOptions) Validate() error

Validate validates the fields and sets the default values.

type CommitOptions Uses

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.
    All bool
    // Author is the author's signature of the commit.
    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
}

CommitOptions describes how a commit operation should be performed.

func (*CommitOptions) Validate Uses

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

Validate validates the fields and sets the default values.

type CreateTagOptions Uses

type CreateTagOptions struct {
    // Tagger defines the signature of the tag creator.
    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.
    Message string
    // 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 Uses

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

Validate validates the fields and sets the default values.

type FetchOptions Uses

type FetchOptions struct {
    // Name of the remote to fetch from. Defaults to origin.
    RemoteName string
    RefSpecs   []config.RefSpec
    // Depth limit fetching to the specified number of commits from the tip of
    // each remote branch history.
    Depth int
    // Auth credentials, if required, to use with the remote repository.
    Auth transport.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.
    Progress sideband.Progress
    // Tags describe how the tags will be fetched from the remote repository,
    // by default is TagFollowing.
    Tags TagMode
    // Force allows the fetch to update a local branch even when the remote
    // branch does not descend from it.
    Force bool
}

FetchOptions describes how a fetch should be performed

func (*FetchOptions) Validate Uses

func (o *FetchOptions) Validate() error

Validate validates the fields and sets the default values.

type FileStatus Uses

type FileStatus struct {
    // Staging is the status of a file in the staging area
    Staging StatusCode
    // Worktree is the status of a file in the worktree
    Worktree StatusCode
    // Extra contains extra information, such as the previous name in a rename
    Extra string
}

FileStatus contains the status of a file in the worktree

type GrepOptions Uses

type GrepOptions struct {
    // Patterns are compiled Regexp objects to be matched.
    Patterns []*regexp.Regexp
    // InvertMatch selects non-matching lines.
    InvertMatch bool
    // CommitHash is the hash of the commit from which worktree should be derived.
    CommitHash plumbing.Hash
    // ReferenceName is the branch or tag name from which worktree should be derived.
    ReferenceName plumbing.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 Uses

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

Validate validates the fields and sets the default values.

type GrepResult Uses

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

GrepResult is structure of a grep result.

func (GrepResult) String Uses

func (gr GrepResult) String() string

type Line Uses

type Line struct {
    // Author is the email address of the last author that modified the line.
    Author string
    // Text is the original text of the line.
    Text string
    // Date is when the original text of the line was introduced
    Date time.Time
    // Hash is the commit hash that introduced the original line
    Hash plumbing.Hash
}

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

type ListOptions Uses

type ListOptions struct {
    // Auth credentials, if required, to use with the remote repository.
    Auth transport.AuthMethod
}

ListOptions describes how a remote list should be performed.

type LogOptions Uses

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.
    From plumbing.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 search
    Order LogOrder

    // Show only those commits in which the specified file was inserted/updated.
    // It is equivalent to running `git log -- <file-name>`.
    FileName *string
}

LogOptions describes how a log action should be performed.

type LogOrder Uses

type LogOrder int8
const (
    LogOrderDefault LogOrder = iota
    LogOrderDFS
    LogOrderDFSPost
    LogOrderBSF
    LogOrderCommitterTime
)

type PlainOpenOptions Uses

type PlainOpenOptions struct {
    // DetectDotGit defines whether parent directories should be
    // walked until a .git directory or file is found.
    DetectDotGit bool
}

PlainOpenOptions describes how opening a plain repository should be performed.

func (*PlainOpenOptions) Validate Uses

func (o *PlainOpenOptions) Validate() error

Validate validates the fields and sets the default values.

type PruneHandler Uses

type PruneHandler func(unreferencedObjectHash plumbing.Hash) error

type PruneOptions Uses

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

type PullOptions Uses

type PullOptions struct {
    // Name of the remote to be pulled. If empty, uses the default.
    RemoteName string
    // Remote branch to clone. If empty, uses HEAD.
    ReferenceName plumbing.ReferenceName
    // Fetch only ReferenceName if true.
    SingleBranch bool
    // Limit fetching to the specified number of commits.
    Depth int
    // Auth credentials, if required, to use with the remote repository.
    Auth transport.AuthMethod
    // RecurseSubmodules controls if new commits of all populated submodules
    // should be fetched too.
    RecurseSubmodules SubmoduleRescursivity
    // 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.
    Progress sideband.Progress
    // Force allows the pull to update a local branch even when the remote
    // branch does not descend from it.
    Force bool
}

PullOptions describes how a pull should be performed.

func (*PullOptions) Validate Uses

func (o *PullOptions) Validate() error

Validate validates the fields and sets the default values.

type PushOptions Uses

type PushOptions struct {
    // RemoteName is the name of the remote to be pushed to.
    RemoteName string
    // RefSpecs specify what destination ref to update with what source
    // object. 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.
    Auth transport.AuthMethod
    // Progress is where the human readable information sent by the server is
    // stored, if nil nothing is stored.
    Progress sideband.Progress
}

PushOptions describes how a push should be performed.

func (*PushOptions) Validate Uses

func (o *PushOptions) Validate() error

Validate validates the fields and sets the default values.

type Remote Uses

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

Remote represents a connection to a remote repository.

func (*Remote) Config Uses

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

Config returns the RemoteConfig object used to instantiate this Remote.

func (*Remote) Fetch Uses

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

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.

func (*Remote) FetchContext Uses

func (r *Remote) FetchContext(ctx context.Context, o *FetchOptions) 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 to the transport operations.

func (*Remote) List Uses

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

List the references on the remote repository.

func (*Remote) Push Uses

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

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

func (*Remote) PushContext Uses

func (r *Remote) PushContext(ctx context.Context, o *PushOptions) (err error)

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 to the transport operations.

func (*Remote) String Uses

func (r *Remote) String() string

type RepackConfig Uses

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

type Repository Uses

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

Repository represents a git repository

func Clone Uses

func Clone(s storage.Storer, worktree billy.Filesystem, o *CloneOptions) (*Repository, error)

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 ErrRepositoryAlreadyExists 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 to the transport operations.

Code:

// 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 storer 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

func CloneContext Uses

func CloneContext(
    ctx context.Context, s storage.Storer, worktree billy.Filesystem, o *CloneOptions,
) (*Repository, error)

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 ErrRepositoryAlreadyExists 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 to the transport operations.

func Init Uses

func Init(s storage.Storer, worktree billy.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. If the given storer is not empty ErrRepositoryAlreadyExists is returned

func Open Uses

func Open(s storage.Storer, worktree billy.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 the repository is a normal one (not bare) and worktree is nil the err ErrWorktreeNotProvided is returned

func PlainClone Uses

func PlainClone(path string, isBare bool, o *CloneOptions) (*Repository, error)

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 ErrRepositoryAlreadyExists is returned.

TODO(mcuadros): move isBare to CloneOptions in v5

Code:

// Tempdir to clone the repository
dir, err := ioutil.TempDir("", "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 repository
changelog, err := os.Open(filepath.Join(dir, "CHANGELOG"))
if err != nil {
    log.Fatal(err)
}

io.Copy(os.Stdout, changelog)

Output:

Initial changelog

Code:

// Tempdir to clone the repository
dir, err := ioutil.TempDir("", "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 string
        Password: "github_access_token",
    },
})

if err != nil {
    log.Fatal(err)
}

Code:

// Tempdir to clone the repository
dir, err := ioutil.TempDir("", "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)
}

func PlainCloneContext Uses

func PlainCloneContext(ctx context.Context, path string, isBare bool, o *CloneOptions) (*Repository, error)

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 ErrRepositoryAlreadyExists 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 to the transport operations.

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

func PlainInit Uses

func PlainInit(path string, isBare bool) (*Repository, error)

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 ErrRepositoryAlreadyExists is returned.

func PlainOpen Uses

func PlainOpen(path string) (*Repository, error)

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

func PlainOpenWithOptions Uses

func PlainOpenWithOptions(path string, o *PlainOpenOptions) (*Repository, error)

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

func (*Repository) BlobObject Uses

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

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

func (*Repository) BlobObjects Uses

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

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

func (*Repository) Branch Uses

func (r *Repository) Branch(name string) (*config.Branch, error)

Branch return a Branch if exists

func (*Repository) Branches Uses

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

Branches returns all the References that are Branches.

func (*Repository) CommitObject Uses

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

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

func (*Repository) CommitObjects Uses

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

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

func (*Repository) Config Uses

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

Config return the repository config

func (*Repository) CreateBranch Uses

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

CreateBranch creates a new Branch

func (*Repository) CreateRemote Uses

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

CreateRemote creates a new remote

Code:

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) CreateTag Uses

func (r *Repository) CreateTag(name string, hash plumbing.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 Uses

func (r *Repository) DeleteBranch(name string) error

DeleteBranch delete a Branch from the repository and delete the config

func (*Repository) DeleteObject Uses

func (r *Repository) DeleteObject(hash plumbing.Hash) error

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

func (*Repository) DeleteRemote Uses

func (r *Repository) DeleteRemote(name string) error

DeleteRemote delete a remote from the repository and delete the config

func (*Repository) DeleteTag Uses

func (r *Repository) DeleteTag(name string) error

DeleteTag deletes a tag from the repository.

func (*Repository) Fetch Uses

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

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.

func (*Repository) FetchContext Uses

func (r *Repository) FetchContext(ctx context.Context, o *FetchOptions) 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 to the transport operations.

func (*Repository) Head Uses

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

Head returns the reference where HEAD is pointing to.

func (*Repository) Log Uses

func (r *Repository) Log(o *LogOptions) (object.CommitIter, error)

Log returns the commit history from the given LogOptions.

func (*Repository) Notes Uses

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 Uses

func (r *Repository) Object(t plumbing.ObjectType, h plumbing.Hash) (object.Object, error)

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

func (*Repository) Objects Uses

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

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

func (*Repository) Prune Uses

func (r *Repository) Prune(opt PruneOptions) error

func (*Repository) Push Uses

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

Push performs a push to the remote. Returns NoErrAlreadyUpToDate if the remote was already up-to-date, from the remote named as FetchOptions.RemoteName.

func (*Repository) PushContext Uses

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

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 to the transport operations.

func (*Repository) Reference Uses

func (r *Repository) Reference(name plumbing.ReferenceName, resolved bool) (
    *plumbing.Reference, error)

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

func (*Repository) References Uses

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

References returns an unsorted ReferenceIter for all references.

Code:

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

func (*Repository) Remote Uses

func (r *Repository) Remote(name string) (*Remote, error)

Remote return a remote if exists

func (*Repository) Remotes Uses

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

Remotes returns a list with all the remotes

func (*Repository) RepackObjects Uses

func (r *Repository) RepackObjects(cfg *RepackConfig) (err error)

func (*Repository) ResolveRevision Uses

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

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})

func (*Repository) Tag Uses

func (r *Repository) Tag(name string) (*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 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
}

func (*Repository) TagObject Uses

func (r *Repository) TagObject(h plumbing.Hash) (*object.Tag, 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.

func (*Repository) TagObjects Uses

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

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

func (*Repository) Tags Uses

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

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
}

func (*Repository) TreeObject Uses

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

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

func (*Repository) TreeObjects Uses

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

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

func (*Repository) Worktree Uses

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

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

type ResetMode Uses

type ResetMode int8

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.
    MixedReset ResetMode = 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
)

type ResetOptions Uses

type ResetOptions struct {
    // Commit, if commit is pressent set the current branch head (HEAD) to it.
    Commit plumbing.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.
    Mode ResetMode
}

ResetOptions describes how a reset operation should be performed.

func (*ResetOptions) Validate Uses

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

Validate validates the fields and sets the default values.

type Status Uses

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 Uses

func (s Status) File(path string) *FileStatus

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.

func (Status) IsClean Uses

func (s Status) IsClean() bool

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

func (Status) IsUntracked Uses

func (s Status) IsUntracked(path string) bool

IsUntracked checks if file for given path is 'Untracked'

func (Status) String Uses

func (s Status) String() string

type StatusCode Uses

type StatusCode byte

StatusCode status code of a file in the Worktree

const (
    Unmodified         StatusCode = ' '
    Untracked          StatusCode = '?'
    Modified           StatusCode = 'M'
    Added              StatusCode = 'A'
    Deleted            StatusCode = 'D'
    Renamed            StatusCode = 'R'
    Copied             StatusCode = 'C'
    UpdatedButUnmerged StatusCode = 'U'
)

type Submodule Uses

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

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

func (*Submodule) Config Uses

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

Config returns the submodule config

func (*Submodule) Init Uses

func (s *Submodule) Init() error

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

func (*Submodule) Repository Uses

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

Repository returns the Repository represented by this submodule

func (*Submodule) Status Uses

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

Status returns the status of the submodule.

func (*Submodule) Update Uses

func (s *Submodule) Update(o *SubmoduleUpdateOptions) error

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

func (*Submodule) UpdateContext Uses

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

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 to the transport operations.

type SubmoduleRescursivity Uses

type SubmoduleRescursivity uint

SubmoduleRescursivity defines how depth will affect any submodule recursive operation.

const (
    // DefaultRemoteName name of the default Remote, just like git command.
    DefaultRemoteName = "origin"

    // NoRecurseSubmodules disables the recursion for a submodule operation.
    NoRecurseSubmodules SubmoduleRescursivity = 0
    // DefaultSubmoduleRecursionDepth allow recursion in a submodule operation.
    DefaultSubmoduleRecursionDepth SubmoduleRescursivity = 10
)

type SubmoduleStatus Uses

type SubmoduleStatus struct {
    Path     string
    Current  plumbing.Hash
    Expected plumbing.Hash
    Branch   plumbing.ReferenceName
}

SubmoduleStatus contains the status for a submodule in the worktree

func (*SubmoduleStatus) IsClean Uses

func (s *SubmoduleStatus) IsClean() bool

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

func (*SubmoduleStatus) String Uses

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 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.

type SubmoduleUpdateOptions Uses

type SubmoduleUpdateOptions struct {
    // Init, if true initializes the submodules recorded in the index.
    Init bool
    // NoFetch tell to the update command to not fetch new objects from the
    // remote site.
    NoFetch bool
    // 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.
    RecurseSubmodules SubmoduleRescursivity
    // Auth credentials, if required, to use with the remote repository.
    Auth transport.AuthMethod
}

SubmoduleUpdateOptions describes how a submodule update should be performed.

type Submodules Uses

type Submodules []*Submodule

Submodules list of several submodules from the same repository.

func (Submodules) Init Uses

func (s Submodules) Init() error

Init initializes the submodules in this list.

func (Submodules) Status Uses

func (s Submodules) Status() (SubmodulesStatus, error)

Status returns the status of the submodules.

func (Submodules) Update Uses

func (s Submodules) Update(o *SubmoduleUpdateOptions) error

Update updates all the submodules in this list.

func (Submodules) UpdateContext Uses

func (s Submodules) UpdateContext(ctx context.Context, o *SubmoduleUpdateOptions) error

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 to the transport operations.

type SubmodulesStatus Uses

type SubmodulesStatus []*SubmoduleStatus

SubmodulesStatus contains the status for all submodiles in the worktree

func (SubmodulesStatus) String Uses

func (s SubmodulesStatus) String() string

String is equivalent to `git submodule status`

type TagMode Uses

type TagMode int
const (
    InvalidTagMode TagMode = 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 all
    NoTags
)

type Worktree Uses

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

Worktree represents a git worktree.

func (*Worktree) Add Uses

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

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.

func (*Worktree) AddGlob Uses

func (w *Worktree) AddGlob(pattern string) error

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.

func (*Worktree) Checkout Uses

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

Checkout switch branches or restore working tree files.

func (*Worktree) Clean Uses

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 Uses

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

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

func (*Worktree) Grep Uses

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

Grep performs grep on a worktree.

func (*Worktree) Move Uses

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

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

func (*Worktree) Pull Uses

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 are no changes to be fetched, or an error.

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

func (*Worktree) PullContext Uses

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

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 to the transport operations.

func (*Worktree) Remove Uses

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

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

func (*Worktree) RemoveGlob Uses

func (w *Worktree) RemoveGlob(pattern string) error

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

func (*Worktree) Reset Uses

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

Reset the worktree to a specified state.

func (*Worktree) Status Uses

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

Status returns the working tree status.

func (*Worktree) Submodule Uses

func (w *Worktree) Submodule(name string) (*Submodule, error)

Submodule returns the submodule with the given name

func (*Worktree) Submodules Uses

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

Submodules returns all the available submodules

Directories

PathSynopsis
cli/go-git
configPackage config contains the abstraction of multiple config files
internal/revisionPackage revision extracts git revision from string More informations about revision : https://www.kernel.org/pub/software/scm/git/docs/gitrevisions.html
plumbingpackage plumbing implement the core interfaces and structs used by go-git
plumbing/cache
plumbing/filemode
plumbing/format/configPackage config implements encoding and decoding of git config files.
plumbing/format/diff
plumbing/format/gitignorePackage 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.
plumbing/format/idxfilePackage idxfile implements encoding and decoding of packfile idx files.
plumbing/format/indexPackage index implements encoding and decoding of index format files.
plumbing/format/objfilePackage objfile implements encoding and decoding of object files.
plumbing/format/packfilePackage packfile implements encoding and decoding of packfile format.
plumbing/format/pktlinePackage pktline implements reading payloads form pkt-lines and encoding pkt-lines from payloads.
plumbing/objectPackage object contains implementations of all Git objects and utility functions to work with them.
plumbing/protocol/packp
plumbing/protocol/packp/capabilityPackage capability defines the server and client capabilities.
plumbing/protocol/packp/sidebandPackage sideband implements a sideband mutiplex/demultiplexer
plumbing/revlistPackage revlist provides support to access the ancestors of commits, in a similar way as the git-rev-list command.
plumbing/storerPackage storer defines the interfaces to store objects, references, etc.
plumbing/transportPackage transport includes the implementation for different transport protocols.
plumbing/transport/clientPackage client contains helper function to deal with the different client protocols.
plumbing/transport/filePackage file implements the file transport protocol.
plumbing/transport/gitPackage git implements the git transport protocol.
plumbing/transport/httpPackage http implements the HTTP transport protocol.
plumbing/transport/internal/commonPackage common implements the git pack protocol with a pluggable transport.
plumbing/transport/serverPackage server implements the git server protocol.
plumbing/transport/sshPackage ssh implements the SSH transport protocol.
plumbing/transport/testPackage test implements common test suite for different transport implementations.
storage
storage/filesystemPackage filesystem is a storage backend base on filesystems
storage/filesystem/dotgithttps://github.com/git/git/blob/master/Documentation/gitrepository-layout.txt
storage/memoryPackage memory is a storage backend base on memory
storage/test
utils/binaryPackage binary implements sintax-sugar functions on top of the standard library binary package
utils/diffPackage diff implements line oriented diffs, similar to the ancient Unix diff command.
utils/ioutilPackage ioutil implements some I/O utility functions.
utils/merkletriePackage merkletrie provides support for n-ary trees that are at the same time Merkle trees and Radix trees (tries).
utils/merkletrie/filesystem
utils/merkletrie/index
utils/merkletrie/internal/frame
utils/merkletrie/internal/fsnoderPackage fsnoder allows to create merkletrie noders that resemble file systems, from human readable string descriptions.
utils/merkletrie/noderPackage noder provide an interface for defining nodes in a merkletrie, their hashes and their paths (a noders and its ancestors).

Package git imports 46 packages (graph) and is imported by 224 packages. Updated 2018-11-27. Refresh now. Tools for package owners.