git

package
v1.15.7 Latest Latest
Warning

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

Go to latest
Published: Dec 2, 2021 License: MIT Imports: 37 Imported by: 67

README

Git Module

This module is merged from https://github.com/go-gitea/git which is a Go module to access Git through shell commands. Now it's a part of gitea's main repository for easier pull request.

Documentation

Index

Examples

Constants

View Source
const BranchPrefix = "refs/heads/"

BranchPrefix base dir of the branch information file store on git

View Source
const DefaultLocale = "C"

DefaultLocale is the default LC_ALL to run git commands in.

View Source
const EmptySHA = "0000000000000000000000000000000000000000"

EmptySHA defines empty git SHA

View Source
const EmptyTreeSHA = "4b825dc642cb6eb9a060e54bf8d69288fbee4904"

EmptyTreeSHA is the SHA of an empty tree

View Source
const (
	// GitTimeLayout is the (default) time layout used by git.
	GitTimeLayout = "Mon Jan _2 15:04:05 2006 -0700"
)
View Source
const (
	// HookPathUpdate hook update path
	HookPathUpdate = "hooks/update"
)
View Source
const NotesRef = "refs/notes/commits"

NotesRef is the git ref where Gitea will look for git-notes data. The value ("refs/notes/commits") is the default ref used by git-notes.

View Source
const TagPrefix = "refs/tags/"

TagPrefix tags prefix path on the repository

Variables

View Source
var (
	// Prefix the log prefix
	Prefix = "[git-module] "
	// GitVersionRequired is the minimum Git version required
	GitVersionRequired = "1.7.2"

	// GitExecutable is the command name of git
	// Could be updated to an absolute path while initialization
	GitExecutable = "git"

	// DefaultContext is the default context to run git commands in
	// will be overwritten by Init with HammerContext
	DefaultContext = context.Background()
)
View Source
var (
	// ErrNotValidHook error when a git hook is not valid
	ErrNotValidHook = errors.New("not a valid Git hook")
)
View Source
var (
	// GlobalCommandArgs global command args for external package setting
	GlobalCommandArgs []string
)
View Source
var SHAPattern = regexp.MustCompile(`^[0-9a-f]{4,40}$`)

SHAPattern can be used to determine if a string is an valid sha

Functions

func AddChanges

func AddChanges(repoPath string, all bool, files ...string) error

AddChanges marks local changes to be ready for commit.

func AddChangesWithArgs added in v1.11.0

func AddChangesWithArgs(repoPath string, gloablArgs []string, all bool, files ...string) error

AddChangesWithArgs marks local changes to be ready for commit.

func AllCommitsCount added in v1.11.0

func AllCommitsCount(repoPath string, hidePRRefs bool, files ...string) (int64, error)

AllCommitsCount returns count of all commits in repository

func CheckGitVersionAtLeast added in v1.14.0

func CheckGitVersionAtLeast(atLeast string) error

CheckGitVersionAtLeast check git version is at least the constraint version

func CheckLFSVersion added in v1.15.0

func CheckLFSVersion()

CheckLFSVersion will check lfs version, if not satisfied, then disable it.

func Checkout

func Checkout(repoPath string, opts CheckoutOptions) error

Checkout checkouts a branch

func Clone

func Clone(from, to string, opts CloneRepoOptions) (err error)

Clone clones original repository to target path.

func CloneWithArgs added in v1.11.0

func CloneWithArgs(ctx context.Context, from, to string, args []string, opts CloneRepoOptions) (err error)

CloneWithArgs original repository to target path.

func CloneWithContext added in v1.13.1

func CloneWithContext(ctx context.Context, from, to string, opts CloneRepoOptions) (err error)

CloneWithContext clones original repository to target path.

func CommitChanges

func CommitChanges(repoPath string, opts CommitChangesOptions) error

CommitChanges commits local changes with given committer, author and message. If author is nil, it will be the same as committer.

func CommitChangesWithArgs added in v1.11.0

func CommitChangesWithArgs(repoPath string, args []string, opts CommitChangesOptions) error

CommitChangesWithArgs commits local changes with given committer, author and message. If author is nil, it will be the same as committer.

func CommitsCount

func CommitsCount(repoPath string, revision ...string) (int64, error)

CommitsCount returns number of total commits of until given revision.

func CommitsCountFiles added in v1.14.0

func CommitsCountFiles(repoPath string, revision, relpath []string) (int64, error)

CommitsCountFiles returns number of total commits of until given revision.

func ConcatenateError added in v1.14.0

func ConcatenateError(err error, stderr string) error

ConcatenateError concatenats an error with stderr string

func CutDiffAroundLine added in v1.12.0

func CutDiffAroundLine(originalDiff io.Reader, line int64, old bool, numbersOfLine int) (string, error)

CutDiffAroundLine cuts a diff of a file in way that only the given line + numberOfLine above it will be shown it also recalculates hunks and adds the appropriate headers to the new diff. Warning: Only one-file diffs are allowed.

Example
const diff = `diff --git a/README.md b/README.md
--- a/README.md
+++ b/README.md
@@ -1,3 +1,6 @@
 # gitea-github-migrator
+
+ Build Status
- Latest Release
 Docker Pulls
+ cut off
+ cut off`
result, _ := CutDiffAroundLine(strings.NewReader(diff), 4, false, 3)
println(result)
Output:

func Fsck

func Fsck(ctx context.Context, repoPath string, timeout time.Duration, args ...string) error

Fsck verifies the connectivity and validity of the objects in the database

func GetDiffShortStat added in v1.13.0

func GetDiffShortStat(repoPath string, args ...string) (numFiles, totalAdditions, totalDeletions int, err error)

GetDiffShortStat counts number of changed files, number of additions and deletions

func GetFullCommitID

func GetFullCommitID(repoPath, shortID string) (string, error)

GetFullCommitID returns full length (40) of commit ID by given short SHA in a repository.

func GetLastCommitForPaths added in v1.13.0

func GetLastCommitForPaths(ctx context.Context, commit *Commit, treePath string, paths []string) (map[string]*Commit, error)

GetLastCommitForPaths returns last commit information

func GetLatestCommitTime

func GetLatestCommitTime(repoPath string) (time.Time, error)

GetLatestCommitTime returns time for latest commit in repository (across all branches)

func GetNote

func GetNote(ctx context.Context, repo *Repository, commitID string, note *Note) error

GetNote retrieves the git-notes data for a given commit.

func GetRawDiff added in v1.12.0

func GetRawDiff(repoPath, commitID string, diffType RawDiffType, writer io.Writer) error

GetRawDiff dumps diff results of repository in given commit ID to io.Writer.

func GetRawDiffForFile added in v1.12.0

func GetRawDiffForFile(repoPath, startCommit, endCommit string, diffType RawDiffType, file string, writer io.Writer) error

GetRawDiffForFile dumps diff results of file in given commit ID to io.Writer.

func GetRemoteAddress added in v1.15.0

func GetRemoteAddress(repoPath, remoteName string) (*url.URL, error)

GetRemoteAddress returns the url of a specific remote of the repository.

func GetRepoRawDiffForFile added in v1.12.0

func GetRepoRawDiffForFile(repo *Repository, startCommit, endCommit string, diffType RawDiffType, file string, writer io.Writer) error

GetRepoRawDiffForFile dumps diff results of file in given commit ID to io.Writer according given repository

func Init

func Init(ctx context.Context) error

Init initializes git module

func InitRepository

func InitRepository(repoPath string, bare bool) error

InitRepository initializes a new Git repository.

func IsBranchExist

func IsBranchExist(repoPath, name string) bool

IsBranchExist returns true if given branch exists in the repository.

func IsErrBadLink(err error) bool

IsErrBadLink if some error is ErrBadLink

func IsErrBranchNotExist

func IsErrBranchNotExist(err error) bool

IsErrBranchNotExist checks if an error is a ErrBranchNotExist.

func IsErrExecTimeout

func IsErrExecTimeout(err error) bool

IsErrExecTimeout if some error is ErrExecTimeout

func IsErrMoreThanOne added in v1.15.0

func IsErrMoreThanOne(err error) bool

IsErrMoreThanOne checks if an error is a ErrMoreThanOne

func IsErrNotExist

func IsErrNotExist(err error) bool

IsErrNotExist if some error is ErrNotExist

func IsErrPushOutOfDate added in v1.12.0

func IsErrPushOutOfDate(err error) bool

IsErrPushOutOfDate checks if an error is a ErrPushOutOfDate.

func IsErrPushRejected added in v1.12.0

func IsErrPushRejected(err error) bool

IsErrPushRejected checks if an error is a ErrPushRejected.

func IsErrUnsupportedVersion

func IsErrUnsupportedVersion(err error) bool

IsErrUnsupportedVersion if some error is ErrUnsupportedVersion

func IsReferenceExist

func IsReferenceExist(repoPath, name string) bool

IsReferenceExist returns true if given reference exists in the repository.

func IsRepoURLAccessible

func IsRepoURLAccessible(url string) bool

IsRepoURLAccessible checks if given repository URL is accessible.

func IsTagExist

func IsTagExist(repoPath, name string) bool

IsTagExist returns true if given tag exists in the repository.

func IsValidHookName

func IsValidHookName(name string) bool

IsValidHookName returns true if given name is a valid Git hook.

func LoadGitVersion added in v1.13.0

func LoadGitVersion() error

LoadGitVersion returns current Git version from shell.

func LocalVersion added in v1.13.0

func LocalVersion() (*version.Version, error)

LocalVersion returns current Git version from shell.

func LogNameStatusRepo added in v1.15.0

func LogNameStatusRepo(ctx context.Context, repository, head, treepath string, paths ...string) (*bufio.Reader, func())

LogNameStatusRepo opens git log --raw in the provided repo and returns a stdin pipe, a stdout reader and cancel function

func MoveFile

func MoveFile(repoPath, oldTreeName, newTreeName string) error

MoveFile moves a file to another file or directory.

func ParseBool added in v1.11.0

func ParseBool(value string) (result bool, valid bool)

ParseBool returns the boolean value represented by the string as per git's git_config_bool true will be returned for the result if the string is empty, but valid will be false. "true", "yes", "on" are all true, true "false", "no", "off" are all false, true 0 is false, true Any other integer is true, true Anything else will return false, false

func ParseDiffHunkString added in v1.12.0

func ParseDiffHunkString(diffhunk string) (leftLine, leftHunk, rightLine, righHunk int)

ParseDiffHunkString parse the diffhunk content and return

func ParseTreeLine added in v1.14.0

func ParseTreeLine(rd *bufio.Reader, modeBuf, fnameBuf, shaBuf []byte) (mode, fname, sha []byte, n int, err error)

ParseTreeLine reads an entry from a tree in a cat-file --batch stream This carefully avoids allocations - except where fnameBuf is too small. It is recommended therefore to pass in an fnameBuf large enough to avoid almost all allocations

Each line is composed of: <mode-in-ascii-dropping-initial-zeros> SP <fname> NUL <20-byte SHA>

We don't attempt to convert the 20-byte SHA to 40-byte SHA to save a lot of time

func Pull

func Pull(repoPath string, opts PullRemoteOptions) error

Pull pulls changes from remotes.

func Push

func Push(repoPath string, opts PushOptions) error

Push pushs local commits to given remote branch.

func ReadBatchLine added in v1.14.0

func ReadBatchLine(rd *bufio.Reader) (sha []byte, typ string, size int64, err error)

ReadBatchLine reads the header line from cat-file --batch We expect: <sha> SP <type> SP <size> LF sha is a 40byte not 20byte here

func ReadTagObjectID added in v1.14.0

func ReadTagObjectID(rd *bufio.Reader, size int64) (string, error)

ReadTagObjectID reads a tag object ID hash from a cat-file --batch stream, throwing away the rest of the stream.

func ReadTreeID added in v1.14.0

func ReadTreeID(rd *bufio.Reader, size int64) (string, error)

ReadTreeID reads a tree ID from a cat-file --batch stream, throwing away the rest of the stream.

func RefEndName

func RefEndName(refStr string) string

RefEndName return the end name of a ref name

func RefURL added in v1.12.0

func RefURL(repoURL, ref string) string

RefURL returns the absolute URL for a ref in a repository

func ResetHEAD

func ResetHEAD(repoPath string, hard bool, revision string) error

ResetHEAD resets HEAD to given revision or head of branch.

func SetExecutablePath added in v1.10.0

func SetExecutablePath(path string) error

SetExecutablePath changes the path of git executable and checks the file permission and version.

func SetUpdateHook

func SetUpdateHook(repoPath, content string) (err error)

SetUpdateHook writes given content to update hook of the repository.

func SplitRefName added in v1.11.0

func SplitRefName(refStr string) (string, string)

SplitRefName splits a full refname to reftype and simple refname

func To40ByteSHA added in v1.14.2

func To40ByteSHA(sha, out []byte) []byte

To40ByteSHA converts a 20-byte SHA into a 40-byte sha. Input and output can be the same 40 byte slice to support in place conversion without allocations. This is at least 100x quicker that hex.EncodeToString NB This requires that out is a 40-byte slice

func VersionInfo added in v1.15.0

func VersionInfo() string

VersionInfo returns git version information

func WalkGitLog added in v1.15.0

func WalkGitLog(ctx context.Context, repo *Repository, head *Commit, treepath string, paths ...string) (map[string]string, error)

WalkGitLog walks the git log --name-status for the head commit in the provided treepath and files

Types

type ArchiveType

type ArchiveType int

ArchiveType archive types

const (
	// ZIP zip archive type
	ZIP ArchiveType = iota + 1
	// TARGZ tar gz archive type
	TARGZ
)

func (ArchiveType) String added in v1.12.0

func (a ArchiveType) String() string

String converts an ArchiveType to string

type BlamePart

type BlamePart struct {
	Sha   string
	Lines []string
}

BlamePart represents block of blame - continuous lines with one sha

type BlameReader

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

BlameReader returns part of file blame one by one

func CreateBlameReader

func CreateBlameReader(ctx context.Context, repoPath, commitID, file string) (*BlameReader, error)

CreateBlameReader creates reader for given repository, commit and file

func (*BlameReader) Close

func (r *BlameReader) Close() error

Close BlameReader - don't run NextPart after invoking that

func (*BlameReader) NextPart

func (r *BlameReader) NextPart() (*BlamePart, error)

NextPart returns next part of blame (sequential code lines with the same commit)

type Blob

type Blob struct {
	ID SHA1
	// contains filtered or unexported fields
}

Blob represents a Git object.

func (*Blob) DataAsync

func (b *Blob) DataAsync() (io.ReadCloser, error)

DataAsync gets a ReadCloser for the contents of a blob without reading it all. Calling the Close function on the result will discard all unread output.

func (*Blob) GetBlobContent

func (b *Blob) GetBlobContent() (string, error)

GetBlobContent Gets the content of the blob as raw text

func (*Blob) GetBlobContentBase64

func (b *Blob) GetBlobContentBase64() (string, error)

GetBlobContentBase64 Reads the content of the blob with a base64 encode and returns the encoded string

func (*Blob) GetBlobLineCount added in v1.11.0

func (b *Blob) GetBlobLineCount() (int, error)

GetBlobLineCount gets line count of the blob

func (*Blob) GuessContentType added in v1.15.0

func (b *Blob) GuessContentType() (typesniffer.SniffedType, error)

GuessContentType guesses the content type of the blob.

func (*Blob) Name

func (b *Blob) Name() string

Name returns name of the tree entry this blob object was created from (or empty string)

func (*Blob) Size

func (b *Blob) Size() int64

Size returns the uncompressed size of the blob

type Branch

type Branch struct {
	Name string
	Path string
	// contains filtered or unexported fields
}

Branch represents a Git branch.

func GetBranchesByPath

func GetBranchesByPath(path string, skip, limit int) ([]*Branch, int, error)

GetBranchesByPath returns a branch by it's path if limit = 0 it will not limit

func (*Branch) GetCommit

func (branch *Branch) GetCommit() (*Commit, error)

GetCommit returns the head commit of a branch

type Cache added in v1.14.0

type Cache interface {
	// Put puts value into cache with key and expire time.
	Put(key string, val interface{}, timeout int64) error
	// Get gets cached value by given key.
	Get(key string) interface{}
}

Cache represents a caching interface

type CheckAttributeOpts added in v1.11.0

type CheckAttributeOpts struct {
	CachedOnly    bool
	AllAttributes bool
	Attributes    []string
	Filenames     []string
}

CheckAttributeOpts represents the possible options to CheckAttribute

type CheckoutOptions

type CheckoutOptions struct {
	Timeout   time.Duration
	Branch    string
	OldBranch string
}

CheckoutOptions options when heck out some branch

type CloneRepoOptions

type CloneRepoOptions struct {
	Timeout    time.Duration
	Mirror     bool
	Bare       bool
	Quiet      bool
	Branch     string
	Shared     bool
	NoCheckout bool
	Depth      int
}

CloneRepoOptions options when clone a repository

type CodeActivityAuthor added in v1.12.0

type CodeActivityAuthor struct {
	Name    string
	Email   string
	Commits int64
}

CodeActivityAuthor represents git statistics data for commit authors

type CodeActivityStats

type CodeActivityStats struct {
	AuthorCount              int64
	CommitCount              int64
	ChangedFiles             int64
	Additions                int64
	Deletions                int64
	CommitCountInAllBranches int64
	Authors                  []*CodeActivityAuthor
}

CodeActivityStats represents git statistics data

type Command

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

Command represents a command with its subcommands or arguments.

func NewCommand

func NewCommand(args ...string) *Command

NewCommand creates and returns a new Git Command based on given command and arguments.

func NewCommandContext added in v1.12.0

func NewCommandContext(ctx context.Context, args ...string) *Command

NewCommandContext creates and returns a new Git Command based on given command and arguments.

func NewCommandContextNoGlobals added in v1.12.0

func NewCommandContextNoGlobals(ctx context.Context, args ...string) *Command

NewCommandContextNoGlobals creates and returns a new Git Command based on given command and arguments only with the specify args and don't care global command args

func NewCommandNoGlobals added in v1.11.0

func NewCommandNoGlobals(args ...string) *Command

NewCommandNoGlobals creates and returns a new Git Command based on given command and arguments only with the specify args and don't care global command args

func (*Command) AddArguments

func (c *Command) AddArguments(args ...string) *Command

AddArguments adds new argument(s) to the command.

func (*Command) Run

func (c *Command) Run() (string, error)

Run executes the command in default working directory and returns stdout in string and error (combined with stderr).

func (*Command) RunInDir

func (c *Command) RunInDir(dir string) (string, error)

RunInDir executes the command in given directory and returns stdout in string and error (combined with stderr).

func (*Command) RunInDirBytes

func (c *Command) RunInDirBytes(dir string) ([]byte, error)

RunInDirBytes executes the command in given directory and returns stdout in []byte and error (combined with stderr).

func (*Command) RunInDirFullPipeline

func (c *Command) RunInDirFullPipeline(dir string, stdout, stderr io.Writer, stdin io.Reader) error

RunInDirFullPipeline executes the command in given directory, it pipes stdout and stderr to given io.Writer.

func (*Command) RunInDirPipeline

func (c *Command) RunInDirPipeline(dir string, stdout, stderr io.Writer) error

RunInDirPipeline executes the command in given directory, it pipes stdout and stderr to given io.Writer.

func (*Command) RunInDirTimeout

func (c *Command) RunInDirTimeout(timeout time.Duration, dir string) ([]byte, error)

RunInDirTimeout executes the command in given directory with given timeout, and returns stdout in []byte and error (combined with stderr).

func (*Command) RunInDirTimeoutEnv

func (c *Command) RunInDirTimeoutEnv(env []string, timeout time.Duration, dir string) ([]byte, error)

RunInDirTimeoutEnv executes the command in given directory with given timeout, and returns stdout in []byte and error (combined with stderr).

func (*Command) RunInDirTimeoutEnvFullPipeline

func (c *Command) RunInDirTimeoutEnvFullPipeline(env []string, timeout time.Duration, dir string, stdout, stderr io.Writer, stdin io.Reader) error

RunInDirTimeoutEnvFullPipeline executes the command in given directory with given timeout, it pipes stdout and stderr to given io.Writer and passes in an io.Reader as stdin.

func (*Command) RunInDirTimeoutEnvFullPipelineFunc added in v1.11.0

func (c *Command) RunInDirTimeoutEnvFullPipelineFunc(env []string, timeout time.Duration, dir string, stdout, stderr io.Writer, stdin io.Reader, fn func(context.Context, context.CancelFunc) error) error

RunInDirTimeoutEnvFullPipelineFunc executes the command in given directory with given timeout, it pipes stdout and stderr to given io.Writer and passes in an io.Reader as stdin. Between cmd.Start and cmd.Wait the passed in function is run.

func (*Command) RunInDirTimeoutEnvPipeline

func (c *Command) RunInDirTimeoutEnvPipeline(env []string, timeout time.Duration, dir string, stdout, stderr io.Writer) error

RunInDirTimeoutEnvPipeline executes the command in given directory with given timeout, it pipes stdout and stderr to given io.Writer.

func (*Command) RunInDirTimeoutFullPipeline

func (c *Command) RunInDirTimeoutFullPipeline(timeout time.Duration, dir string, stdout, stderr io.Writer, stdin io.Reader) error

RunInDirTimeoutFullPipeline executes the command in given directory with given timeout, it pipes stdout and stderr to given io.Writer, and stdin from the given io.Reader

func (*Command) RunInDirTimeoutPipeline

func (c *Command) RunInDirTimeoutPipeline(timeout time.Duration, dir string, stdout, stderr io.Writer) error

RunInDirTimeoutPipeline executes the command in given directory with given timeout, it pipes stdout and stderr to given io.Writer.

func (*Command) RunInDirWithEnv

func (c *Command) RunInDirWithEnv(dir string, env []string) (string, error)

RunInDirWithEnv executes the command in given directory and returns stdout in string and error (combined with stderr).

func (*Command) RunTimeout

func (c *Command) RunTimeout(timeout time.Duration) (string, error)

RunTimeout executes the command in default working directory with given timeout, and returns stdout in string and error (combined with stderr).

func (*Command) SetDescription added in v1.11.0

func (c *Command) SetDescription(desc string) *Command

SetDescription sets the description for this command which be returned on c.String()

func (*Command) SetParentContext added in v1.11.0

func (c *Command) SetParentContext(ctx context.Context) *Command

SetParentContext sets the parent context for this command

func (*Command) String

func (c *Command) String() string

type Commit

type Commit struct {
	Branch string // Branch this commit belongs to
	Tree
	ID            SHA1 // The ID of this commit object
	Author        *Signature
	Committer     *Signature
	CommitMessage string
	Signature     *CommitGPGSignature

	Parents []SHA1 // SHA1 strings
	// contains filtered or unexported fields
}

Commit represents a git commit.

func CommitFromReader added in v1.12.0

func CommitFromReader(gitRepo *Repository, sha SHA1, reader io.Reader) (*Commit, error)

CommitFromReader will generate a Commit from a provided reader We need this to interpret commits from cat-file or cat-file --batch

If used as part of a cat-file --batch stream you need to limit the reader to the correct size

func (*Commit) CommitsBefore

func (c *Commit) CommitsBefore() (*list.List, error)

CommitsBefore returns all the commits before current revision

func (*Commit) CommitsBeforeLimit

func (c *Commit) CommitsBeforeLimit(num int) (*list.List, error)

CommitsBeforeLimit returns num commits before current revision

func (*Commit) CommitsBeforeUntil

func (c *Commit) CommitsBeforeUntil(commitID string) (*list.List, error)

CommitsBeforeUntil returns the commits between commitID to current revision

func (*Commit) CommitsByRange

func (c *Commit) CommitsByRange(page, pageSize int) (*list.List, error)

CommitsByRange returns the specific page commits before current revision, every page's number default by CommitsRangeSize

func (*Commit) CommitsCount

func (c *Commit) CommitsCount() (int64, error)

CommitsCount returns number of total commits of until current revision.

func (*Commit) FileChangedSinceCommit

func (c *Commit) FileChangedSinceCommit(filename, pastCommit string) (bool, error)

FileChangedSinceCommit Returns true if the file given has changed since the the past commit YOU MUST ENSURE THAT pastCommit is a valid commit ID.

func (*Commit) GetBranchName

func (c *Commit) GetBranchName() (string, error)

GetBranchName gets the closest branch name (as returned by 'git name-rev --name-only')

func (*Commit) GetCommitByPath

func (c *Commit) GetCommitByPath(relpath string) (*Commit, error)

GetCommitByPath return the commit of relative path object.

func (*Commit) GetFilesChangedSinceCommit

func (c *Commit) GetFilesChangedSinceCommit(pastCommit string) ([]string, error)

GetFilesChangedSinceCommit get all changed file names between pastCommit to current revision

func (*Commit) GetRepositoryDefaultPublicGPGKey added in v1.11.0

func (c *Commit) GetRepositoryDefaultPublicGPGKey(forceUpdate bool) (*GPGSettings, error)

GetRepositoryDefaultPublicGPGKey returns the default public key for this commit

func (*Commit) GetSubModule

func (c *Commit) GetSubModule(entryname string) (*SubModule, error)

GetSubModule get the sub module according entryname

func (*Commit) GetSubModules

func (c *Commit) GetSubModules() (*ObjectCache, error)

GetSubModules get all the sub modules of current revision git tree

func (*Commit) GetTagName added in v1.13.0

func (c *Commit) GetTagName() (string, error)

GetTagName gets the current tag name for given commit

func (*Commit) HasFile added in v1.10.0

func (c *Commit) HasFile(filename string) (bool, error)

HasFile returns true if the file given exists on this commit This does only mean it's there - it does not mean the file was changed during the commit.

func (*Commit) HasPreviousCommit added in v1.11.0

func (c *Commit) HasPreviousCommit(commitHash SHA1) (bool, error)

HasPreviousCommit returns true if a given commitHash is contained in commit's parents

func (*Commit) LoadBranchName added in v1.13.0

func (c *Commit) LoadBranchName() (err error)

LoadBranchName load branch name for commit

func (*Commit) Message

func (c *Commit) Message() string

Message returns the commit message. Same as retrieving CommitMessage directly.

func (*Commit) Parent

func (c *Commit) Parent(n int) (*Commit, error)

Parent returns n-th parent (0-based index) of the commit.

func (*Commit) ParentCount

func (c *Commit) ParentCount() int

ParentCount returns number of parents of the commit. 0 if this is the root commit, otherwise 1,2, etc.

func (*Commit) ParentID

func (c *Commit) ParentID(n int) (SHA1, error)

ParentID returns oid of n-th parent (0-based index). It returns nil if no such parent exists.

func (*Commit) SearchCommits

func (c *Commit) SearchCommits(opts SearchCommitsOptions) (*list.List, error)

SearchCommits returns the commits match the keyword before current revision

func (*Commit) Summary

func (c *Commit) Summary() string

Summary returns first line of commit message.

type CommitChangesOptions

type CommitChangesOptions struct {
	Committer *Signature
	Author    *Signature
	Message   string
}

CommitChangesOptions the options when a commit created

type CommitFileStatus

type CommitFileStatus struct {
	Added    []string
	Removed  []string
	Modified []string
}

CommitFileStatus represents status of files in a commit.

func GetCommitFileStatus

func GetCommitFileStatus(repoPath, commitID string) (*CommitFileStatus, error)

GetCommitFileStatus returns file status of commit in given repository.

func NewCommitFileStatus

func NewCommitFileStatus() *CommitFileStatus

NewCommitFileStatus creates a CommitFileStatus

type CommitGPGSignature

type CommitGPGSignature struct {
	Signature string
	Payload   string //TODO check if can be reconstruct from the rest of commit information to not have duplicate data
}

CommitGPGSignature represents a git commit signature part.

type CommitInfo added in v1.14.0

type CommitInfo struct {
	Entry         *TreeEntry
	Commit        *Commit
	SubModuleFile *SubModuleFile
}

CommitInfo describes the first commit with the provided entry

type CommitTreeOpts

type CommitTreeOpts struct {
	Parents    []string
	Message    string
	KeyID      string
	NoGPGSign  bool
	AlwaysSign bool
}

CommitTreeOpts represents the possible options to CommitTree

type CompareInfo

type CompareInfo struct {
	MergeBase    string
	BaseCommitID string
	HeadCommitID string
	Commits      *list.List
	NumFiles     int
}

CompareInfo represents needed information for comparing references.

type CountObject

type CountObject struct {
	Count       int64
	Size        int64
	InPack      int64
	Packs       int64
	SizePack    int64
	PrunePack   int64
	Garbage     int64
	SizeGarbage int64
}

CountObject represents repository count objects report

func CountObjects added in v1.11.0

func CountObjects(repoPath string) (*CountObject, error)

CountObjects returns the results of git count-objects on the repoPath

type DeleteBranchOptions

type DeleteBranchOptions struct {
	Force bool
}

DeleteBranchOptions Option(s) for delete branch

type DivergeObject

type DivergeObject struct {
	Ahead  int
	Behind int
}

DivergeObject represents commit count diverging commits

func GetDivergingCommits

func GetDivergingCommits(repoPath string, baseBranch string, targetBranch string) (DivergeObject, error)

GetDivergingCommits returns the number of commits a targetBranch is ahead or behind a baseBranch

type Entries

type Entries []*TreeEntry

Entries a list of entry

func (Entries) CustomSort

func (tes Entries) CustomSort(cmp func(s1, s2 string) bool)

CustomSort customizable string comparing sort entry list

func (Entries) GetCommitsInfo

func (tes Entries) GetCommitsInfo(ctx context.Context, commit *Commit, treePath string, cache *LastCommitCache) ([]CommitInfo, *Commit, error)

GetCommitsInfo gets information of all commits that are corresponding to these entries

func (Entries) Sort

func (tes Entries) Sort()

Sort sort the list of entry

type EntryMode

type EntryMode int

EntryMode the type of the object in the git tree

const (
	// EntryModeBlob
	EntryModeBlob EntryMode = 0100644
	// EntryModeExec
	EntryModeExec EntryMode = 0100755
	// EntryModeSymlink
	EntryModeSymlink EntryMode = 0120000
	// EntryModeCommit
	EntryModeCommit EntryMode = 0160000
	// EntryModeTree
	EntryModeTree EntryMode = 0040000
)

There are only a few file modes in Git. They look like unix file modes, but they can only be one of these.

func ToEntryMode added in v1.14.0

func ToEntryMode(value string) EntryMode

ToEntryMode converts a string to an EntryMode

func (EntryMode) String added in v1.14.0

func (e EntryMode) String() string

String converts an EntryMode to a string

type ErrBadLink struct {
	Name    string
	Message string
}

ErrBadLink entry.FollowLink error

func (ErrBadLink) Error

func (err ErrBadLink) Error() string

type ErrBranchNotExist

type ErrBranchNotExist struct {
	Name string
}

ErrBranchNotExist represents a "BranchNotExist" kind of error.

func (ErrBranchNotExist) Error

func (err ErrBranchNotExist) Error() string

type ErrExecTimeout

type ErrExecTimeout struct {
	Duration time.Duration
}

ErrExecTimeout error when exec timed out

func (ErrExecTimeout) Error

func (err ErrExecTimeout) Error() string

type ErrMoreThanOne added in v1.15.0

type ErrMoreThanOne struct {
	StdOut string
	StdErr string
	Err    error
}

ErrMoreThanOne represents an error if pull request fails when there are more than one sources (branch, tag) with the same name

func (*ErrMoreThanOne) Error added in v1.15.0

func (err *ErrMoreThanOne) Error() string

type ErrNotExist

type ErrNotExist struct {
	ID      string
	RelPath string
}

ErrNotExist commit not exist error

func (ErrNotExist) Error

func (err ErrNotExist) Error() string

type ErrPushOutOfDate added in v1.12.0

type ErrPushOutOfDate struct {
	StdOut string
	StdErr string
	Err    error
}

ErrPushOutOfDate represents an error if merging fails due to unrelated histories

func (*ErrPushOutOfDate) Error added in v1.12.0

func (err *ErrPushOutOfDate) Error() string

func (*ErrPushOutOfDate) Unwrap added in v1.12.0

func (err *ErrPushOutOfDate) Unwrap() error

Unwrap unwraps the underlying error

type ErrPushRejected added in v1.12.0

type ErrPushRejected struct {
	Message string
	StdOut  string
	StdErr  string
	Err     error
}

ErrPushRejected represents an error if merging fails due to rejection from a hook

func (*ErrPushRejected) Error added in v1.12.0

func (err *ErrPushRejected) Error() string

func (*ErrPushRejected) GenerateMessage added in v1.12.0

func (err *ErrPushRejected) GenerateMessage()

GenerateMessage generates the remote message from the stderr

func (*ErrPushRejected) Unwrap added in v1.12.0

func (err *ErrPushRejected) Unwrap() error

Unwrap unwraps the underlying error

type ErrUnsupportedVersion

type ErrUnsupportedVersion struct {
	Required string
}

ErrUnsupportedVersion error when required git version not matched

func (ErrUnsupportedVersion) Error

func (err ErrUnsupportedVersion) Error() string

type GPGSettings added in v1.11.0

type GPGSettings struct {
	Sign             bool
	KeyID            string
	Email            string
	Name             string
	PublicKeyContent string
}

GPGSettings represents the default GPG settings for this repository

func (*GPGSettings) LoadPublicKeyContent added in v1.11.0

func (gpgSettings *GPGSettings) LoadPublicKeyContent() error

LoadPublicKeyContent will load the key from gpg

type Hasher added in v1.14.0

type Hasher struct {
	hash.Hash
}

Hasher is a struct that will generate a SHA1

func NewHasher added in v1.14.0

func NewHasher(t ObjectType, size int64) Hasher

NewHasher takes an object type and size and creates a hasher to generate a SHA

func (Hasher) Sum added in v1.14.0

func (h Hasher) Sum() (sha1 SHA1)

Sum generates a SHA1 for the provided hash

type Hook

type Hook struct {
	IsActive bool   // Indicates whether repository has this hook.
	Content  string // Content of hook if it's active.
	Sample   string // Sample content from Git.
	// contains filtered or unexported fields
}

Hook represents a Git hook.

func GetHook

func GetHook(repoPath, name string) (*Hook, error)

GetHook returns a Git hook by given name and repository.

func ListHooks

func ListHooks(repoPath string) (_ []*Hook, err error)

ListHooks returns a list of Git hooks of given repository.

func (*Hook) Name

func (h *Hook) Name() string

Name return the name of the hook

func (*Hook) Update

func (h *Hook) Update() error

Update updates hook settings.

type LastCommitCache

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

LastCommitCache represents a cache to store last commit

func NewLastCommitCache added in v1.14.0

func NewLastCommitCache(repoPath string, gitRepo *Repository, ttl func() int64, cache Cache) *LastCommitCache

NewLastCommitCache creates a new last commit cache for repo

func (*LastCommitCache) CacheCommit added in v1.14.0

func (c *LastCommitCache) CacheCommit(ctx context.Context, commit *Commit) error

CacheCommit will cache the commit from the gitRepository

func (*LastCommitCache) Get

func (c *LastCommitCache) Get(ref, entryPath string, wr WriteCloserError, rd *bufio.Reader) (interface{}, error)

Get get the last commit information by commit id and entry path

func (*LastCommitCache) Put

func (c *LastCommitCache) Put(ref, entryPath, commitID string) error

Put put the last commit id with commit and entry path

type LimitedReaderCloser added in v1.14.0

type LimitedReaderCloser struct {
	R io.Reader
	C io.Closer
	N int64
}

LimitedReaderCloser is a limited reader closer

func (*LimitedReaderCloser) Close added in v1.14.0

func (l *LimitedReaderCloser) Close() error

Close implements io.Closer

func (*LimitedReaderCloser) Read added in v1.14.0

func (l *LimitedReaderCloser) Read(p []byte) (n int, err error)

Read implements io.Reader

type LogNameStatusCommitData added in v1.15.0

type LogNameStatusCommitData struct {
	CommitID  string
	ParentIDs []string
	Paths     []bool
}

LogNameStatusCommitData represents a commit artefact from git log raw

type LogNameStatusRepoParser added in v1.15.0

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

LogNameStatusRepoParser parses a git log raw output from LogRawRepo

func NewLogNameStatusRepoParser added in v1.15.0

func NewLogNameStatusRepoParser(ctx context.Context, repository, head, treepath string, paths ...string) *LogNameStatusRepoParser

NewLogNameStatusRepoParser returns a new parser for a git log raw output

func (*LogNameStatusRepoParser) Close added in v1.15.0

func (g *LogNameStatusRepoParser) Close()

Close closes the parser

func (*LogNameStatusRepoParser) Next added in v1.15.0

func (g *LogNameStatusRepoParser) Next(treepath string, paths2ids map[string]int, changed []bool, maxpathlen int) (*LogNameStatusCommitData, error)

Next returns the next LogStatusCommitData

type Note

type Note struct {
	Message []byte
	Commit  *Commit
}

Note stores information about a note created using git-notes.

type ObjectCache

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

ObjectCache provides thread-safe cache operations.

func (*ObjectCache) Get

func (oc *ObjectCache) Get(id string) (interface{}, bool)

Get get cached obj by id

func (*ObjectCache) Set

func (oc *ObjectCache) Set(id string, obj interface{})

Set add obj to cache

type ObjectType

type ObjectType string

ObjectType git object type

const (
	// ObjectCommit commit object type
	ObjectCommit ObjectType = "commit"
	// ObjectTree tree object type
	ObjectTree ObjectType = "tree"
	// ObjectBlob blob object type
	ObjectBlob ObjectType = "blob"
	// ObjectTag tag object type
	ObjectTag ObjectType = "tag"
	// ObjectBranch branch object type
	ObjectBranch ObjectType = "branch"
)

func (ObjectType) Bytes added in v1.14.0

func (o ObjectType) Bytes() []byte

Bytes returns the byte array for the Object Type

type PullRemoteOptions

type PullRemoteOptions struct {
	Timeout time.Duration
	All     bool
	Rebase  bool
	Remote  string
	Branch  string
}

PullRemoteOptions options when pull from remote

type PushOptions

type PushOptions struct {
	Remote  string
	Branch  string
	Force   bool
	Mirror  bool
	Env     []string
	Timeout time.Duration
}

PushOptions options when push to remote

type RawDiffType added in v1.12.0

type RawDiffType string

RawDiffType type of a raw diff.

const (
	RawDiffNormal RawDiffType = "diff"
	RawDiffPatch  RawDiffType = "patch"
)

RawDiffType possible values.

type Reference

type Reference struct {
	Name string

	Object SHA1 // The id of this commit object
	Type   string
	// contains filtered or unexported fields
}

Reference represents a Git ref.

func (*Reference) Commit

func (ref *Reference) Commit() (*Commit, error)

Commit return the commit of the reference

func (*Reference) RefGroup added in v1.14.0

func (ref *Reference) RefGroup() string

RefGroup returns the group type of the reference

func (*Reference) ShortName added in v1.14.0

func (ref *Reference) ShortName() string

ShortName returns the short name of the reference

type Repository

type Repository struct {
	Path string
	// contains filtered or unexported fields
}

Repository represents a Git repository.

func OpenRepository

func OpenRepository(repoPath string) (*Repository, error)

OpenRepository opens the repository at the given path.

func (*Repository) AddObjectToIndex

func (repo *Repository) AddObjectToIndex(mode string, object SHA1, filename string) error

AddObjectToIndex adds the provided object hash to the index at the provided filename

func (*Repository) AddRemote

func (repo *Repository) AddRemote(name, url string, fetch bool) error

AddRemote adds a new remote to repository.

func (*Repository) CatFileBatch added in v1.15.0

func (repo *Repository) CatFileBatch() (WriteCloserError, *bufio.Reader, func())

CatFileBatch obtains a CatFileBatch for this repository

func (*Repository) CatFileBatchCheck added in v1.15.0

func (repo *Repository) CatFileBatchCheck() (WriteCloserError, *bufio.Reader, func())

CatFileBatchCheck obtains a CatFileBatchCheck for this repository

func (*Repository) CheckAttribute added in v1.11.0

func (repo *Repository) CheckAttribute(opts CheckAttributeOpts) (map[string]map[string]string, error)

CheckAttribute return the Blame object of file

func (*Repository) Close added in v1.9.6

func (repo *Repository) Close()

Close this repository, in particular close the underlying gogitStorage if this is not nil

func (*Repository) CommitTree

func (repo *Repository) CommitTree(author *Signature, committer *Signature, tree *Tree, opts CommitTreeOpts) (SHA1, error)

CommitTree creates a commit from a given tree id for the user with provided message

func (*Repository) CommitsBetween

func (repo *Repository) CommitsBetween(last *Commit, before *Commit) (*list.List, error)

CommitsBetween returns a list that contains commits between [before, last). If before is detached (removed by reset + push) it is not included.

func (*Repository) CommitsBetweenIDs

func (repo *Repository) CommitsBetweenIDs(last, before string) (*list.List, error)

CommitsBetweenIDs return commits between twoe commits

func (*Repository) CommitsBetweenLimit added in v1.11.0

func (repo *Repository) CommitsBetweenLimit(last *Commit, before *Commit, limit, skip int) (*list.List, error)

CommitsBetweenLimit returns a list that contains at most limit commits skipping the first skip commits between [before, last)

func (*Repository) CommitsByFileAndRange

func (repo *Repository) CommitsByFileAndRange(revision, file string, page int) (*list.List, error)

CommitsByFileAndRange return the commits according revision file and the page

func (*Repository) CommitsByFileAndRangeNoFollow added in v1.10.0

func (repo *Repository) CommitsByFileAndRangeNoFollow(revision, file string, page int) (*list.List, error)

CommitsByFileAndRangeNoFollow return the commits according revision file and the page

func (*Repository) CommitsCountBetween

func (repo *Repository) CommitsCountBetween(start, end string) (int64, error)

CommitsCountBetween return numbers of commits between two commits

func (*Repository) ConvertToSHA1 added in v1.9.1

func (repo *Repository) ConvertToSHA1(commitID string) (SHA1, error)

ConvertToSHA1 returns a Hash object from a potential ID string

func (*Repository) CreateAnnotatedTag

func (repo *Repository) CreateAnnotatedTag(name, message, revision string) error

CreateAnnotatedTag create one annotated tag in the repository

func (*Repository) CreateArchive added in v1.15.0

func (repo *Repository) CreateArchive(ctx context.Context, format ArchiveType, target io.Writer, usePrefix bool, commitID string) error

CreateArchive create archive content to the target path

func (*Repository) CreateBranch

func (repo *Repository) CreateBranch(branch, oldbranchOrCommit string) error

CreateBranch create a new branch

func (*Repository) CreateTag

func (repo *Repository) CreateTag(name, revision string) error

CreateTag create one tag in the repository

func (*Repository) DeleteBranch

func (repo *Repository) DeleteBranch(name string, opts DeleteBranchOptions) error

DeleteBranch delete a branch by name on repository.

func (*Repository) EmptyIndex

func (repo *Repository) EmptyIndex() error

EmptyIndex empties the index

func (*Repository) FileBlame

func (repo *Repository) FileBlame(revision, path, file string) ([]byte, error)

FileBlame return the Blame object of file

func (*Repository) FileChangedBetweenCommits

func (repo *Repository) FileChangedBetweenCommits(filename, id1, id2 string) (bool, error)

FileChangedBetweenCommits Returns true if the file changed between commit IDs id1 and id2 You must ensure that id1 and id2 are valid commit ids.

func (*Repository) FileCommitsCount

func (repo *Repository) FileCommitsCount(revision, file string) (int64, error)

FileCommitsCount return the number of files at a revision

func (*Repository) FilesCountBetween

func (repo *Repository) FilesCountBetween(startCommitID, endCommitID string) (int, error)

FilesCountBetween return the number of files changed between two commits

func (*Repository) GetAllCommitsCount added in v1.11.0

func (repo *Repository) GetAllCommitsCount() (int64, error)

GetAllCommitsCount returns count of all commits in repository

func (*Repository) GetAnnotatedTag

func (repo *Repository) GetAnnotatedTag(sha string) (*Tag, error)

GetAnnotatedTag returns a Git tag by its SHA, must be an annotated tag

func (*Repository) GetBlob

func (repo *Repository) GetBlob(idStr string) (*Blob, error)

GetBlob finds the blob object in the repository.

func (*Repository) GetBranch

func (repo *Repository) GetBranch(branch string) (*Branch, error)

GetBranch returns a branch by it's name

func (*Repository) GetBranchCommit

func (repo *Repository) GetBranchCommit(name string) (*Commit, error)

GetBranchCommit returns the last commit of given branch.

func (*Repository) GetBranchCommitID

func (repo *Repository) GetBranchCommitID(name string) (string, error)

GetBranchCommitID returns last commit ID string of given branch.

func (*Repository) GetBranches

func (repo *Repository) GetBranches(skip, limit int) ([]string, int, error)

GetBranches returns branches from the repository, skipping skip initial branches and returning at most limit branches, or all branches if limit is 0.

func (*Repository) GetCodeActivityStats

func (repo *Repository) GetCodeActivityStats(fromTime time.Time, branch string) (*CodeActivityStats, error)

GetCodeActivityStats returns code statistics for activity page

func (*Repository) GetCommit

func (repo *Repository) GetCommit(commitID string) (*Commit, error)

GetCommit returns commit object of by ID string.

func (*Repository) GetCommitByPath

func (repo *Repository) GetCommitByPath(relpath string) (*Commit, error)

GetCommitByPath returns the last commit of relative path.

func (*Repository) GetCommitsFromIDs added in v1.13.0

func (repo *Repository) GetCommitsFromIDs(commitIDs []string) (commits *list.List)

GetCommitsFromIDs get commits from commit IDs

func (*Repository) GetCompareInfo

func (repo *Repository) GetCompareInfo(basePath, baseBranch, headBranch string) (_ *CompareInfo, err error)

GetCompareInfo generates and returns compare information between base and head branches of repositories.

func (*Repository) GetDefaultBranch added in v1.13.0

func (repo *Repository) GetDefaultBranch() (string, error)

GetDefaultBranch gets default branch of repository.

func (*Repository) GetDefaultPublicGPGKey added in v1.11.0

func (repo *Repository) GetDefaultPublicGPGKey(forceUpdate bool) (*GPGSettings, error)

GetDefaultPublicGPGKey will return and cache the default public GPG settings for this repository

func (*Repository) GetDiff added in v1.11.0

func (repo *Repository) GetDiff(base, head string, w io.Writer) error

GetDiff generates and returns patch data between given revisions.

func (*Repository) GetDiffFromMergeBase added in v1.12.0

func (repo *Repository) GetDiffFromMergeBase(base, head string, w io.Writer) error

GetDiffFromMergeBase generates and return patch data from merge base to head

func (*Repository) GetDiffNumChangedFiles added in v1.13.0

func (repo *Repository) GetDiffNumChangedFiles(base, head string) (int, error)

GetDiffNumChangedFiles counts the number of changed files This is substantially quicker than shortstat but...

func (*Repository) GetDiffOrPatch added in v1.11.0

func (repo *Repository) GetDiffOrPatch(base, head string, w io.Writer, formatted bool) error

GetDiffOrPatch generates either diff or formatted patch data between given revisions

func (*Repository) GetDiffShortStat added in v1.13.0

func (repo *Repository) GetDiffShortStat(base, head string) (numFiles, totalAdditions, totalDeletions int, err error)

GetDiffShortStat counts number of changed files, number of additions and deletions

func (*Repository) GetHEADBranch

func (repo *Repository) GetHEADBranch() (*Branch, error)

GetHEADBranch returns corresponding branch of HEAD.

func (*Repository) GetHook

func (repo *Repository) GetHook(name string) (*Hook, error)

GetHook get one hook according the name on a repository

func (*Repository) GetLanguageStats added in v1.12.0

func (repo *Repository) GetLanguageStats(commitID string) (map[string]int64, error)

GetLanguageStats calculates language stats for git repository at specified commit

func (*Repository) GetMergeBase

func (repo *Repository) GetMergeBase(tmpRemote string, base, head string) (string, string, error)

GetMergeBase checks and returns merge base of two branches and the reference used as base.

func (*Repository) GetPatch

func (repo *Repository) GetPatch(base, head string, w io.Writer) error

GetPatch generates and returns format-patch data between given revisions.

func (*Repository) GetRefCommitID

func (repo *Repository) GetRefCommitID(name string) (string, error)

GetRefCommitID returns the last commit ID string of given reference (branch or tag).

func (*Repository) GetRefType

func (repo *Repository) GetRefType(ref string) ObjectType

GetRefType gets the type of the ref based on the string

func (*Repository) GetRefs

func (repo *Repository) GetRefs() ([]*Reference, error)

GetRefs returns all references of the repository.

func (*Repository) GetRefsFiltered

func (repo *Repository) GetRefsFiltered(pattern string) ([]*Reference, error)

GetRefsFiltered returns all references of the repository that matches patterm exactly or starting with.

func (*Repository) GetTag

func (repo *Repository) GetTag(name string) (*Tag, error)

GetTag returns a Git tag by given name.

func (*Repository) GetTagCommit

func (repo *Repository) GetTagCommit(name string) (*Commit, error)

GetTagCommit get the commit of the specific tag via name

func (*Repository) GetTagCommitID

func (repo *Repository) GetTagCommitID(name string) (string, error)

GetTagCommitID returns last commit ID string of given tag.

func (*Repository) GetTagID

func (repo *Repository) GetTagID(name string) (string, error)

GetTagID returns the object ID for a tag (annotated tags have both an object SHA AND a commit SHA)

func (*Repository) GetTagInfos

func (repo *Repository) GetTagInfos(page, pageSize int) ([]*Tag, error)

GetTagInfos returns all tag infos of the repository.

func (*Repository) GetTagNameBySHA

func (repo *Repository) GetTagNameBySHA(sha string) (string, error)

GetTagNameBySHA returns the name of a tag from its tag object SHA or commit SHA

func (*Repository) GetTagType

func (repo *Repository) GetTagType(id SHA1) (string, error)

GetTagType gets the type of the tag, either commit (simple) or tag (annotated)

func (*Repository) GetTags

func (repo *Repository) GetTags() (tags []string, err error)

GetTags returns all tags of the repository.

func (*Repository) GetTree

func (repo *Repository) GetTree(idStr string) (*Tree, error)

GetTree find the tree object in the repository.

func (*Repository) HashObject

func (repo *Repository) HashObject(reader io.Reader) (SHA1, error)

HashObject takes a reader and returns SHA1 hash for that reader

func (*Repository) Hooks

func (repo *Repository) Hooks() ([]*Hook, error)

Hooks get all the hooks on the repository

func (*Repository) IsBranchExist

func (repo *Repository) IsBranchExist(name string) bool

IsBranchExist returns true if given branch exists in current repository.

func (*Repository) IsCommitExist

func (repo *Repository) IsCommitExist(name string) bool

IsCommitExist returns true if given commit exists in current repository.

func (*Repository) IsCommitInBranch added in v1.14.0

func (repo *Repository) IsCommitInBranch(commitID, branch string) (r bool, err error)

IsCommitInBranch check if the commit is on the branch

func (*Repository) IsEmpty

func (repo *Repository) IsEmpty() (bool, error)

IsEmpty Check if repository is empty.

func (*Repository) IsObjectExist added in v1.15.0

func (repo *Repository) IsObjectExist(name string) bool

IsObjectExist returns true if given reference exists in the repository.

func (*Repository) IsReferenceExist added in v1.15.0

func (repo *Repository) IsReferenceExist(name string) bool

IsReferenceExist returns true if given reference exists in the repository.

func (*Repository) IsTagExist

func (repo *Repository) IsTagExist(name string) bool

IsTagExist returns true if given tag exists in the repository.

func (*Repository) LineBlame

func (repo *Repository) LineBlame(revision, path, file string, line uint) (*Commit, error)

LineBlame returns the latest commit at the given line

func (*Repository) LsFiles

func (repo *Repository) LsFiles(filenames ...string) ([]string, error)

LsFiles checks if the given filenames are in the index

func (*Repository) LsTree added in v1.15.0

func (repo *Repository) LsTree(ref string, filenames ...string) ([]string, error)

LsTree checks if the given filenames are in the tree

func (*Repository) ReadTreeToIndex

func (repo *Repository) ReadTreeToIndex(treeish string) error

ReadTreeToIndex reads a treeish to the index

func (*Repository) RemoveFilesFromIndex

func (repo *Repository) RemoveFilesFromIndex(filenames ...string) error

RemoveFilesFromIndex removes given filenames from the index - it does not check whether they are present.

func (*Repository) RemoveRemote

func (repo *Repository) RemoveRemote(name string) error

RemoveRemote removes a remote from repository.

func (*Repository) ResolveReference added in v1.14.0

func (repo *Repository) ResolveReference(name string) (string, error)

ResolveReference resolves a name to a reference

func (*Repository) SetDefaultBranch

func (repo *Repository) SetDefaultBranch(name string) error

SetDefaultBranch sets default branch of repository.

func (*Repository) WriteTree

func (repo *Repository) WriteTree() (*Tree, error)

WriteTree writes the current index as a tree to the object db and returns its hash

type SHA1

type SHA1 [20]byte

SHA1 a git commit name

func ComputeBlobHash added in v1.14.0

func ComputeBlobHash(content []byte) SHA1

ComputeBlobHash compute the hash for a given blob content

func ComputeHash added in v1.14.0

func ComputeHash(t ObjectType, content []byte) SHA1

ComputeHash compute the hash for a given ObjectType and content

func MustID

func MustID(b []byte) SHA1

MustID always creates a new SHA1 from a [20]byte array with no validation of input.

func MustIDFromString

func MustIDFromString(s string) SHA1

MustIDFromString always creates a new sha from a ID with no validation of input.

func NewID

func NewID(b []byte) (SHA1, error)

NewID creates a new SHA1 from a [20]byte array.

func NewIDFromString

func NewIDFromString(s string) (SHA1, error)

NewIDFromString creates a new SHA1 from a ID string of length 40.

func (SHA1) IsZero added in v1.14.0

func (s SHA1) IsZero() bool

IsZero returns whether this SHA1 is all zeroes

func (SHA1) String added in v1.14.0

func (s SHA1) String() string

String returns a string representation of the SHA

type SearchCommitsOptions

type SearchCommitsOptions struct {
	Keywords            []string
	Authors, Committers []string
	After, Before       string
	All                 bool
}

SearchCommitsOptions specify the parameters for SearchCommits

func NewSearchCommitsOptions

func NewSearchCommitsOptions(searchString string, forAllRefs bool) SearchCommitsOptions

NewSearchCommitsOptions construct a SearchCommitsOption from a space-delimited search string

type Signature

type Signature struct {
	// Name represents a person name. It is an arbitrary string.
	Name string
	// Email is an email, but it cannot be assumed to be well-formed.
	Email string
	// When is the timestamp of the signature.
	When time.Time
}

Signature represents the Author or Committer information.

func (*Signature) Decode added in v1.14.0

func (s *Signature) Decode(b []byte)

Decode decodes a byte array representing a signature to signature

func (*Signature) String added in v1.14.0

func (s *Signature) String() string

type SubModule

type SubModule struct {
	Name string
	URL  string
}

SubModule submodule is a reference on git repository

type SubModuleFile

type SubModuleFile struct {
	*Commit
	// contains filtered or unexported fields
}

SubModuleFile represents a file with submodule type.

func NewSubModuleFile

func NewSubModuleFile(c *Commit, refURL, refID string) *SubModuleFile

NewSubModuleFile create a new submodule file

func (*SubModuleFile) RefID

func (sf *SubModuleFile) RefID() string

RefID returns reference ID.

func (*SubModuleFile) RefURL

func (sf *SubModuleFile) RefURL(urlPrefix, repoFullName, sshDomain string) string

RefURL guesses and returns reference URL.

type Tag

type Tag struct {
	Name string
	ID   SHA1

	Object    SHA1 // The id of this commit object
	Type      string
	Tagger    *Signature
	Message   string
	Signature *CommitGPGSignature
	// contains filtered or unexported fields
}

Tag represents a Git tag.

func (*Tag) Commit

func (tag *Tag) Commit() (*Commit, error)

Commit return the commit of the tag reference

type Tree

type Tree struct {
	ID         SHA1
	ResolvedID SHA1
	// contains filtered or unexported fields
}

Tree represents a flat directory listing.

func NewTree

func NewTree(repo *Repository, id SHA1) *Tree

NewTree create a new tree according the repository and tree id

func (*Tree) GetBlobByPath

func (t *Tree) GetBlobByPath(relpath string) (*Blob, error)

GetBlobByPath get the blob object according the path

func (*Tree) GetTreeEntryByPath

func (t *Tree) GetTreeEntryByPath(relpath string) (*TreeEntry, error)

GetTreeEntryByPath get the tree entries according the sub dir

func (*Tree) ListEntries

func (t *Tree) ListEntries() (Entries, error)

ListEntries returns all entries of current tree.

func (*Tree) ListEntriesRecursive

func (t *Tree) ListEntriesRecursive() (Entries, error)

ListEntriesRecursive returns all entries of current tree recursively including all subtrees

func (*Tree) SubTree

func (t *Tree) SubTree(rpath string) (*Tree, error)

SubTree get a sub tree by the sub dir path

type TreeEntry

type TreeEntry struct {
	ID SHA1
	// contains filtered or unexported fields
}

TreeEntry the leaf in the git tree

func ParseTreeEntries

func ParseTreeEntries(data []byte) ([]*TreeEntry, error)

ParseTreeEntries parses the output of a `git ls-tree -l` command.

func (*TreeEntry) Blob

func (te *TreeEntry) Blob() *Blob

Blob returns the blob object the entry

func (te *TreeEntry) FollowLink() (*TreeEntry, error)

FollowLink returns the entry pointed to by a symlink

func (te *TreeEntry) FollowLinks() (*TreeEntry, error)

FollowLinks returns the entry ultimately pointed to by a symlink

func (*TreeEntry) GetSubJumpablePathName

func (te *TreeEntry) GetSubJumpablePathName() string

GetSubJumpablePathName return the full path of subdirectory jumpable ( contains only one directory )

func (*TreeEntry) IsDir

func (te *TreeEntry) IsDir() bool

IsDir if the entry is a sub dir

func (*TreeEntry) IsExecutable added in v1.9.1

func (te *TreeEntry) IsExecutable() bool

IsExecutable if the entry is an executable file (not necessarily binary)

func (te *TreeEntry) IsLink() bool

IsLink if the entry is a symlink

func (*TreeEntry) IsRegular

func (te *TreeEntry) IsRegular() bool

IsRegular if the entry is a regular file

func (*TreeEntry) IsSubModule

func (te *TreeEntry) IsSubModule() bool

IsSubModule if the entry is a sub module

func (*TreeEntry) Mode

func (te *TreeEntry) Mode() EntryMode

Mode returns the mode of the entry

func (*TreeEntry) Name

func (te *TreeEntry) Name() string

Name returns the name of the entry

func (*TreeEntry) Size

func (te *TreeEntry) Size() int64

Size returns the size of the entry

func (*TreeEntry) Type

func (te *TreeEntry) Type() string

Type returns the type of the entry (commit, tree, blob)

type WriteCloserError added in v1.15.0

type WriteCloserError interface {
	io.WriteCloser
	CloseWithError(err error) error
}

WriteCloserError wraps an io.WriteCloser with an additional CloseWithError function

func CatFileBatch added in v1.14.0

func CatFileBatch(repoPath string) (WriteCloserError, *bufio.Reader, func())

CatFileBatch opens git cat-file --batch in the provided repo and returns a stdin pipe, a stdout reader and cancel function

func CatFileBatchCheck added in v1.15.0

func CatFileBatchCheck(repoPath string) (WriteCloserError, *bufio.Reader, func())

CatFileBatchCheck opens git cat-file --batch-check in the provided repo and returns a stdin pipe, a stdout reader and cancel function

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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