git

package
v0.19.0 Latest Latest
Warning

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

Go to latest
Published: Sep 5, 2025 License: Apache-2.0 Imports: 24 Imported by: 0

Documentation

Overview

Copyright (c) 2016-present GitLab Inc. SPDX-License-Identifier: MIT

Index

Constants

View Source
const (
	GIT_HASH_UNKNOWN      = 0
	GIT_HASH_SHA1         = 1
	GIT_HASH_SHA256       = 2
	GIT_SHA1_RAWSZ        = 20
	GIT_SHA1_HEXSZ        = GIT_SHA1_RAWSZ * 2
	GIT_SHA256_RAWSZ      = 32
	GIT_SHA256_HEXSZ      = GIT_SHA256_RAWSZ * 2
	GIT_MAX_RAWSZ         = GIT_SHA256_RAWSZ
	GIT_MAX_HEXSZ         = GIT_SHA256_HEXSZ
	GIT_SHA1_ZERO_HEX     = "0000000000000000000000000000000000000000"
	GIT_SHA256_ZERO_HEX   = "0000000000000000000000000000000000000000000000000000000000000000"
	GIT_SHA1_EMPTY_TREE   = "4b825dc642cb6eb9a060e54bf8d69288fbee4904"
	GIT_SHA1_EMPTY_BLOB   = "e69de29bb2d1d6434b8b29ae775ad8c2e48c5391"
	GIT_SHA256_EMPTY_TREE = "6ef19b41225c5369f1c104d45d8d85efa9b057b53b14b4b9b939dd74decc5321"
	GIT_SHA256_EMPTY_BLOB = "473a0f4c3be8a93681a267e3b1e9a7dcda1185436fe141f7749120a303721813"
	GIT_SHA1_NAME         = "sha1"
	GIT_SHA256_NAME       = "sha256"
	HashKey               = "hash-algo"
	ReferenceNameDefault  = "refs/heads/master"
)
View Source
const (
	// GitTimeLayout is the (default) time layout used by git.
	GitTimeLayout = "Mon Jan _2 15:04:05 2006 -0700"
)
View Source
const (
	RefRevParseRulesCount = 6
)
View Source
const (
	ReferenceLineFormat = "%(refname)%00%(refname:short)%00%(objectname)%00%(objecttype)"
)
View Source
const (
	Sundries = "sundries"
)

Variables

View Source
var (
	ErrObjectNotFound = errors.New("object not found")
	// ErrInvalidType is returned when an invalid object type is provided.
	ErrInvalidType = errors.New("invalid object type")
)
View Source
var (
	ErrDifferentHash     = errors.New("attempt to reinitialize repository with different hash")
	ErrInvalidBranchName = errors.New("invalid initial branch name")
)
View Source
var (
	ErrBlankRevision = errors.New("empty revision")
	ErrBadRevision   = errors.New("revision can't start with '-'")
)
View Source
var BranchFormatFields = []string{
	"%(refname)", "%(refname:short)",
	"%(objectname)", "%(tree)", "%(contents:subject)",
	"%(authorname)", "%(authoremail)", "%(authordate:iso-strict)",
	"%(committername)", "%(committeremail)", "%(committerdate:iso-strict)",
}
View Source
var (
	ErrNoBranches = NewBranchNotFound("HEAD")
)
View Source
var (
	ErrReferenceNotFound = errors.New("reference not found")
)
View Source
var FallbackTimeValue = time.Unix(1<<63-62135596801, 999999999)

FallbackTimeValue is the value returned by `SafeTimeParse` in case it encounters a parse error. It's the maximum time value possible in golang. See https://gitlab.com/gitlab-org/gitaly/issues/556#note_40289573

View Source
var RefRevParseRules = []string{
	"%s",
	"refs/%s",
	"refs/tags/%s",
	"refs/heads/%s",
	"refs/remotes/%s",
	"refs/remotes/%s/HEAD",
}

RefRevParseRules are a set of rules to parse references into short names. These are the same rules as used by git in shorten_unambiguous_ref. See: https://github.com/git/git/blob/9857273be005833c71e2d16ba48e193113e12276/refs.c#L610

View Source
var (
	VersionDetect = sync.OnceValues(gitVersionDetect)
)

Functions

func ConformingEmptyBlob

func ConformingEmptyBlob(hexOID string) string

func ConformingEmptyTree

func ConformingEmptyTree(hexOID string) string

func ConformingHashZero

func ConformingHashZero(hexOID string) string

func DefaultBranchName added in v0.19.0

func DefaultBranchName(ctx context.Context, repoPath string) (string, error)

func ErrorIsNotFound

func ErrorIsNotFound(message string) bool

func FindScpLikeComponents

func FindScpLikeComponents(url string) (user, host, port, path string)

FindScpLikeComponents returns the user, host, port and path of the given SCP-like URL.

func HasSpecificReference added in v0.19.0

func HasSpecificReference(ctx context.Context, repoPath string, referencePrefix string) (bool, error)

func Hash

func Hash(ctx context.Context, repoPath string) (string, error)

Hash: Calculate the hash of the repository at the specified path

func HashFromEnv

func HashFromEnv(ctx context.Context, environ []string, repoPath string) (string, error)

HashFromEnv: Calculate the hash of the repository at the specified path and environment block

func IsBareRepository added in v0.19.0

func IsBareRepository(ctx context.Context, repoPath string) bool

func IsErrAlreadyLocked

func IsErrAlreadyLocked(err error) bool

func IsErrMalformedMode added in v0.19.0

func IsErrMalformedMode(err error) bool

func IsErrNotExist

func IsErrNotExist(err error) bool

IsErrNotExist if some error is ErrNotExist

func IsErrReferenceBadName added in v0.19.0

func IsErrReferenceBadName(err error) bool

func IsErrUnexpectedType

func IsErrUnexpectedType(err error) bool

func IsGitVersionAtLeast

func IsGitVersionAtLeast(other Version) bool

IsVersionAtLeast returns whether the git version is the one specified or higher argument is plain version string separated by '.' e.g. "2.3.1" but can omit minor/patch

func IsHashZero

func IsHashZero(hexOID string) bool

func IsLocalEndpoint

func IsLocalEndpoint(url string) bool

IsLocalEndpoint returns true if the given URL string specifies a local file endpoint. For example, on a Linux machine, `/home/user/src/go-git` would match as a local endpoint, but `https://github.com/src-d/go-git` would not.

func IsValidateSHA256 added in v0.19.0

func IsValidateSHA256(hs string) bool

func JoinBranchPrefix added in v0.19.0

func JoinBranchPrefix(b string) string

func JoinBranchRev added in v0.19.0

func JoinBranchRev(r string) string

func JoinTagPrefix added in v0.19.0

func JoinTagPrefix(tag string) string

func MatchesScheme

func MatchesScheme(url string) bool

MatchesScheme returns true if the given string matches a URL-like format scheme.

func MatchesScpLike

func MatchesScpLike(url string) bool

MatchesScpLike returns true if the given string matches an SCP-like format scheme.

func NewBranchNotFound

func NewBranchNotFound(branch string) error

func NewObjectNotFound

func NewObjectNotFound(oid string) error

func NewReader

func NewReader(ctx context.Context, opt *command.RunOpts, arg ...string) (io.ReadCloser, error)

NewReaderFromOptions new git command as a reader

func NewRepo

func NewRepo(ctx context.Context, repoPath, branch string, bare bool, shaFormat HashFormat) error

func NewRevisionNotFound

func NewRevisionNotFound(branch string) error

func NewSundriesDir

func NewSundriesDir(repoPath string, pattern string) (string, error)

func NewTagNotFound

func NewTagNotFound(branch string) error

func PareTimeFallback

func PareTimeFallback(s string) time.Time

PareTimeFallback parses a git date string with the RFC3339 format. If the date is invalid (possibly because the date is larger than golang's largest value) it returns the maximum date possible.

func ParseReference

func ParseReference(ctx context.Context, repoPath string, symref string) (string, string, error)

ParseReference parse symref return hash and refname

func ReferenceTarget

func ReferenceTarget(ctx context.Context, repoPath, reference string) (string, error)

func RevDivergingCount added in v0.19.0

func RevDivergingCount(ctx context.Context, repoPath string, from, to string) (int, int, error)

func RevParseCurrent

func RevParseCurrent(ctx context.Context, environ []string, repoPath string) (string, error)

RevParseCurrent: resolve the reference pointed to by HEAD

not git repo:

fatal: not a git repository (or any of the parent directories): .git

empty repo:

fatal: ambiguous argument 'HEAD': unknown revision or path not in the working tree. Use '--' to separate paths from revisions, like this: 'git <command> [<revision>...] -- [<file>...]'

ref not exists: HEAD

refs/heads/master

func RevParseCurrentEx

func RevParseCurrentEx(ctx context.Context, environ []string, repoPath string) (string, string, error)

RevParseCurrentEx parse HEAD return hash and refname

git rev-parse HEAD --symbolic-full-name HEAD

result:

85e15f6f6272033eb83e5a56f650a7a5f9c84cf6
refs/heads/master

func RevParseHEAD

func RevParseHEAD(ctx context.Context, environ []string, repoPath string) (string, error)

RevParseHEAD: resolve the reference pointed to by HEAD

not git repo: fatal: not a git repository (or any parent directory): .git

empty repo: HEAD fatal: 有歧义的参数 'HEAD':未知的版本或路径不存在于工作区中。 使用 '--' 来分隔版本和路径,例如: 'git <命令> [<版本>...] -- [<文件>...]'

ref not exists: HEAD

ref exists: refs/heads/master

func RevParseHashFormat added in v0.19.0

func RevParseHashFormat(ctx context.Context, repoPath string) (string, error)

func RevParseRepoPath

func RevParseRepoPath(ctx context.Context, p string) string

RevParseRepoPath parse repo dir

func RevParseWorktree added in v0.19.0

func RevParseWorktree(ctx context.Context, p string) (string, error)

--show-toplevel

func RevUniqueList added in v0.19.0

func RevUniqueList(ctx context.Context, repoPath string, ours, theirs string) ([]string, error)
func SymReferenceLink(ctx context.Context, repoPath string, refname string) error

SymReferenceLink: Update default branch or current branch

func UpdateRef added in v0.19.0

func UpdateRef(ctx context.Context, repoPath string, reference string, oldRev, newRev string, forceUpdate bool) error

fatal: update_ref failed for ref 'refs/heads/release/1.0.0_20250728': 'refs/heads/release' exists; cannot create 'refs/heads/release/1.0.0_20250728

func ValidateBranchName

func ValidateBranchName(branch []byte) bool

ValidateBranchName: creating branches starting with - is not supported

func ValidateBytesRevision

func ValidateBytesRevision(revision []byte) error

ValidateBytesRevision checks if a revision looks valid

func ValidateHex

func ValidateHex(hs string) error

func ValidateHexLax

func ValidateHexLax(hs string) bool

func ValidateNumber

func ValidateNumber(s string) bool

func ValidateReferenceName

func ValidateReferenceName(refname []byte) bool

* Try to read one refname component from the front of refname. * Return the length of the component found, or -1 if the component is * not legal. It is legal if it is something reasonable to have under * ".git/refs/"; We do not like it if: * * - it begins with ".", or * - it has double dots "..", or * - it has ASCII control characters, or * - it has ":", "?", "[", "\", "^", "~", SP, or TAB anywhere, or * - it has "*" anywhere unless REFNAME_REFSPEC_PATTERN is set, or * - it ends with a "/", or * - it ends with ".lock", or * - it contains a "@{" portion * * When sanitized is not NULL, instead of rejecting the input refname * as an error, try to come up with a usable replacement for the input * refname in it.

func ValidateRevision

func ValidateRevision(revision string) error

ValidateBytesRevision checks if a revision looks valid

func ValidateTagName

func ValidateTagName(tag []byte) bool

ValidateTagName: creating tags starting with - is not supported

Types

type Commit

type Commit struct {
	// Hash of the commit object.
	Hash string `json:"hash"`
	// Tree is the hash of the root tree of the commit.
	Tree string `json:"tree"`
	// Parents are the hashes of the parent commits of the commit.
	Parents []string `json:"parents"`
	// Author is the original author of the commit.
	Author Signature `json:"author"`
	// Committer is the one performing the commit, might be different from
	// Author.
	Committer Signature `json:"committer"`
	// ExtraHeaders stores headers not listed above, for instance
	// "encoding", "gpgsig", or "mergetag" (among others).
	ExtraHeaders []*ExtraHeader `json:"extra_header,omitempty"`
	// Message is the commit message, contains arbitrary text.
	Message string `json:"message"`
	// contains filtered or unexported fields
}

func ParseRev added in v0.19.0

func ParseRev(ctx context.Context, repoPath string, revision string) (*Commit, error)

func (*Commit) Decode

func (c *Commit) Decode(hash string, reader io.Reader, size int64) error

func (*Commit) ExtractCommitGPGSignature

func (c *Commit) ExtractCommitGPGSignature() *CommitGPGSignature

func (*Commit) Pretty added in v0.19.0

func (c *Commit) Pretty(w io.Writer) (err error)

func (*Commit) Signature

func (c *Commit) Signature() string

func (*Commit) Size added in v0.19.0

func (c *Commit) Size() int64

func (*Commit) Subject

func (c *Commit) Subject() string

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 Decoder

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

func NewDecoder

func NewDecoder(ctx context.Context, repoPath string) (*Decoder, error)

func (*Decoder) Blob

func (d *Decoder) Blob(objectKey string) (*Object, error)

func (*Decoder) BlobEntry

func (d *Decoder) BlobEntry(revision string, path string) (*Object, error)

func (*Decoder) Close

func (d *Decoder) Close() error

func (*Decoder) Commit

func (d *Decoder) Commit(objectKey string) (*Commit, error)

func (*Decoder) ExhaustiveMeta

func (d *Decoder) ExhaustiveMeta(location string) (*Metadata, error)

func (*Decoder) ExhaustiveObjectReader

func (d *Decoder) ExhaustiveObjectReader(location string) (*Object, error)

ExhaustiveObjectReader: Exhaustive read object

Can two branches 'a' and 'a/b' exist at the same time in git? Normally, this is impossible, but when we manually edit packed-refs, we can create 'a' and 'a/b' at the same time, because packed-refs has no file system restrictions, of course this will Annoys git, so it's not recommended, in the 'Exhaustive*' functions, we don't care about this unusual case.

func (*Decoder) Meta

func (d *Decoder) Meta(objectKey string) (*Metadata, error)

func (*Decoder) Object

func (d *Decoder) Object(objectKey string) (any, error)

func (*Decoder) ObjectReader

func (d *Decoder) ObjectReader(objectKey string) (*Object, error)

func (*Decoder) ParseRev added in v0.19.0

func (d *Decoder) ParseRev(objectKey string) (*Commit, error)

ParseRev resolve peeled commit

func (*Decoder) ReadEntry

func (d *Decoder) ReadEntry(revision string, path string) (*Object, error)

func (*Decoder) ReadOverflow

func (d *Decoder) ReadOverflow(objectKey string, limit int64) (b []byte, err error)

func (*Decoder) Tree

func (d *Decoder) Tree(objectKey string) (*Tree, error)

type ErrAlreadyLocked

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

func (*ErrAlreadyLocked) Error

func (e *ErrAlreadyLocked) Error() string

type ErrMalformedMode added in v0.19.0

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

func (*ErrMalformedMode) Error added in v0.19.0

func (e *ErrMalformedMode) Error() string

type ErrNotExist

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

ErrNotExist commit not exist error

func (*ErrNotExist) Error

func (err *ErrNotExist) Error() string

type ErrReferenceBadName added in v0.19.0

type ErrReferenceBadName struct {
	Name string
}

func (ErrReferenceBadName) Error added in v0.19.0

func (err ErrReferenceBadName) Error() string

type ErrUnexpectedType

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

func (*ErrUnexpectedType) Error

func (e *ErrUnexpectedType) Error() string

type ExtraHeader

type ExtraHeader struct {
	// K is the header key, or the first run of bytes up until a ' ' (\x20)
	// character.
	K string `json:"k"`
	// V is the header value, or the remaining run of bytes in the line,
	// stripping off the above "K" field as a prefix.
	V string `json:"v"`
}

ExtraHeader encapsulates a key-value pairing of header key to header value. It is stored as a struct{string, string} in memory as opposed to a map[string]string to maintain ordering in a byte-for-byte encode/decode round trip.

type FileMode added in v0.19.0

type FileMode uint32

A FileMode represents the kind of tree entries used by git. It resembles regular file systems modes, although FileModes are considerably simpler (there are not so many), and there are some, like Submodule that has no file system equivalent.

const (
	// Empty is used as the FileMode of tree elements when comparing
	// trees in the following situations:
	//
	// - the mode of tree elements before their creation.  - the mode of
	// tree elements after their deletion.  - the mode of unmerged
	// elements when checking the index.
	//
	// Empty has no file system equivalent.  As Empty is the zero value
	// of FileMode, it is also returned by New and
	// NewFromOsNewFromOSFileMode along with an error, when they fail.
	Empty FileMode = 0
	// Dir represent a Directory.
	Dir FileMode = 0040000
	// Regular represent non-executable files.  Please note this is not
	// the same as golang regular files, which include executable files.
	Regular FileMode = 0100644
	// Deprecated represent non-executable files with the group writable
	// bit set.  This mode was supported by the first versions of git,
	// but it has been deprecated nowadays.  This library uses them
	// internally, so you can read old packfiles, but will treat them as
	// Regulars when interfacing with the outside world.  This is the
	// standard git behavior.
	Deprecated FileMode = 0100664
	// Executable represents executable files.
	Executable FileMode = 0100755
	// Symlink represents symbolic links to files.
	Symlink FileMode = 0120000
	// Submodule represents git submodules.  This mode has no file system
	// equivalent.
	Submodule FileMode = 0160000
	// Fragmentation of large files
	Fragments FileMode = 0400000
)

func New added in v0.19.0

func New(s string) (FileMode, error)

New takes the octal string representation of a FileMode and returns the FileMode and a nil error. If the string can not be parsed to a 32 bit unsigned octal number, it returns Empty and the parsing error.

Example: "40000" means Dir, "100644" means Regular.

Please note this function does not check if the returned FileMode is valid in git or if it is malformed. For instance, "1" will return the malformed FileMode(1) and a nil error.

func NewFromOS added in v0.19.0

func NewFromOS(m os.FileMode) (FileMode, error)

NewFromOS returns the FileMode used by git to represent the provided file system modes and a nil error on success. If the file system mode cannot be mapped to any valid git mode (as with sockets or named pipes), it will return Empty and an error.

Note that some git modes cannot be generated from os.FileModes, like Deprecated and Submodule; while Empty will be returned, along with an error, only when the method fails.

func (FileMode) Bytes added in v0.19.0

func (m FileMode) Bytes() []byte

Bytes return a slice of 4 bytes with the mode in little endian encoding.

func (FileMode) IsFile added in v0.19.0

func (m FileMode) IsFile() bool

IsFile returns if the FileMode represents that of a file, this is, Regular, Deprecated, Executable or Link.

func (FileMode) IsFragments added in v0.19.0

func (m FileMode) IsFragments() bool

func (FileMode) IsMalformed added in v0.19.0

func (m FileMode) IsMalformed() bool

IsMalformed returns if the FileMode should not appear in a git packfile, this is: Empty and any other mode not mentioned as a constant in this package.

func (FileMode) IsRegular added in v0.19.0

func (m FileMode) IsRegular() bool

IsRegular returns if the FileMode represents that of a regular file, this is, either Regular or Deprecated. Please note that Executable are not regular even though in the UNIX tradition, they usually are: See the IsFile method.

func (FileMode) MarshalJSON added in v0.19.0

func (m FileMode) MarshalJSON() ([]byte, error)

func (FileMode) Origin added in v0.19.0

func (m FileMode) Origin() FileMode

func (FileMode) String added in v0.19.0

func (m FileMode) String() string

String returns the FileMode as a string in the standard git format, this is, an octal number padded with ceros to 7 digits. Malformed modes are printed in that same format, for easier debugging.

Example: Regular is "0100644", Empty is "0000000".

func (FileMode) ToOSFileMode added in v0.19.0

func (m FileMode) ToOSFileMode() (os.FileMode, error)

ToOSFileMode returns the os.FileMode to be used when creating file system elements with the given git mode and a nil error on success.

When the provided mode cannot be mapped to a valid file system mode (e.g. Submodule) it returns os.FileMode(0) and an error.

The returned file mode does not take into account the umask.

func (*FileMode) UnmarshalJSON added in v0.19.0

func (m *FileMode) UnmarshalJSON(b []byte) error

func (FileMode) Unmask added in v0.19.0

func (m FileMode) Unmask() FileMode

type HashFormat added in v0.19.0

type HashFormat int

HashFormat: https://git-scm.com/docs/hash-function-transition/

const (
	HashUNKNOWN HashFormat = iota // UNKNOWN
	HashSHA1                      // SHA1
	HashSHA256                    // SHA256
)

func ExtensionsFormat added in v0.19.0

func ExtensionsFormat(repoPath string) (HashFormat, string)

ExtensionsFormat: return objectFormat, refFormat

func HashFormatFromBinarySize added in v0.19.0

func HashFormatFromBinarySize(bsize int) HashFormat

func HashFormatFromName added in v0.19.0

func HashFormatFromName(algo string) HashFormat

func HashFormatFromSize added in v0.19.0

func HashFormatFromSize(size int) HashFormat

func HashFormatOK added in v0.19.0

func HashFormatOK(repoPath string) HashFormat

func HashFormatResult added in v0.19.0

func HashFormatResult(repoPath string) (HashFormat, error)

func (HashFormat) EmptyBlobID added in v0.19.0

func (h HashFormat) EmptyBlobID() string

func (HashFormat) EmptyTreeID added in v0.19.0

func (h HashFormat) EmptyTreeID() string

func (HashFormat) Hasher added in v0.19.0

func (h HashFormat) Hasher() hash.Hash

func (HashFormat) HexSize added in v0.19.0

func (h HashFormat) HexSize() int

HexSize: hex size

func (HashFormat) RawSize added in v0.19.0

func (h HashFormat) RawSize() int

RawSize: raw length

func (HashFormat) String added in v0.19.0

func (h HashFormat) String() string

func (HashFormat) ZeroOID added in v0.19.0

func (h HashFormat) ZeroOID() string

type HashResult

type HashResult struct {
	HEAD       string
	Hash       string
	References int
}

func HashEx

func HashEx(ctx context.Context, repoPath string) (*HashResult, error)

HashEx: Calculates the hash of the repository at the specified path and returns HEAD, the number of references

type Metadata

type Metadata struct {
	// Hash of the object.
	Hash string
	// Size is the total uncompressed size of the blob's contents.
	Size int64
	// Type of the object
	Type ObjectType
}

object metadata

type ODB

type ODB struct {
	*gitobj.Database
	// contains filtered or unexported fields
}

func NewODB

func NewODB(repoPath string, hashAlgo HashFormat) (*ODB, error)

NewODB open repo default odb

func (*ODB) Close

func (o *ODB) Close() error

type Object

type Object struct {
	// Hash of the object.
	Hash string
	// Size is the total uncompressed size of the blob's contents.
	Size int64
	// Type of the object
	Type ObjectType
	// contains filtered or unexported fields
}

func (*Object) Discard

func (o *Object) Discard()

func (*Object) Read

func (o *Object) Read(p []byte) (int, error)

func (*Object) WriteTo

func (o *Object) WriteTo(w io.Writer) (int64, error)

WriteTo implements the io.WriterTo interface. It defers the write to the embedded object reader via `io.Copy()`, which in turn will use `WriteTo()` or `ReadFrom()` in case these interfaces are implemented by the respective reader or writer.

type ObjectType

type ObjectType int8

ObjectType internal object type Integer values from 0 to 7 map to those exposed by git. AnyObject is used to represent any from 0 to 7.

const (
	InvalidObject ObjectType = 0
	CommitObject  ObjectType = 1
	TreeObject    ObjectType = 2
	BlobObject    ObjectType = 3
	TagObject     ObjectType = 4
	// 5 reserved for future expansion
	OFSDeltaObject ObjectType = 6
	REFDeltaObject ObjectType = 7

	AnyObject ObjectType = -127
)

func ParseObjectType

func ParseObjectType(value string) (typ ObjectType, err error)

ParseObjectType parses a string representation of ObjectType. It returns an error on parse failure.

func (ObjectType) Bytes

func (t ObjectType) Bytes() []byte

func (ObjectType) IsDelta

func (t ObjectType) IsDelta() bool

IsDelta returns true for any ObjectTyoe that represents a delta (i.e. REFDeltaObject or OFSDeltaObject).

func (ObjectType) String

func (t ObjectType) String() string

func (ObjectType) Valid

func (t ObjectType) Valid() bool

Valid returns true if t is a valid ObjectType.

type Order

type Order int
const (
	OrderNone Order = iota
	OrderNewest
	OrderOldest
)

type Printer added in v0.19.0

type Printer interface {
	Pretty(io.Writer) error
}

type RefUpdater added in v0.19.0

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

func NewRefUpdater added in v0.19.0

func NewRefUpdater(ctx context.Context, repoPath string, environ []string, noDeref bool) (*RefUpdater, error)

func (*RefUpdater) Close added in v0.19.0

func (u *RefUpdater) Close() error

Close closes the updater and aborts a possible open transaction. No changes will be written to disk, all lockfiles will be cleaned up and the process will exit.

func (*RefUpdater) Commit added in v0.19.0

func (u *RefUpdater) Commit() error

Commit applies the commands specified in other calls to the Updater. Commit finishes the reference transaction and another one must be started before further changes can be staged.

func (*RefUpdater) Create added in v0.19.0

func (u *RefUpdater) Create(reference ReferenceName, oid string) error

Create commands the reference to be created with the given object ID. The ref must not exist.

A reference transaction must be started before calling Create.

func (*RefUpdater) Delete added in v0.19.0

func (u *RefUpdater) Delete(reference ReferenceName) error

Delete commands the reference to be removed from the repository. This command will ignore any old state of the reference and just force-remove it.

A reference transaction must be started before calling Delete.

func (*RefUpdater) Prepare added in v0.19.0

func (u *RefUpdater) Prepare() error

Prepare prepares the reference transaction by locking all references and determining their current values. The updates are not yet committed and will be rolled back in case there is no call to `Commit()`. This call is optional.

func (*RefUpdater) Start added in v0.19.0

func (u *RefUpdater) Start() error

Start begins a new reference transaction. The reference changes are not performed until Commit is explicitly called.

func (*RefUpdater) Update added in v0.19.0

func (u *RefUpdater) Update(reference ReferenceName, newRev, oldRev string) error

Update commands the reference to be updated to point at the object ID specified in newOID. If newOID is the zero OID, then the branch will be deleted. If oldOID is a non-empty string, then the reference will only be updated if its current value matches the old value. If the old value is the zero OID, then the branch must not exist.

A reference transaction must be started before calling Update.

func (*RefUpdater) UpdateSymbolicReference added in v0.19.0

func (u *RefUpdater) UpdateSymbolicReference(reference, newTarget ReferenceName) error

UpdateSymbolicReference is used to do a symbolic reference update. We can potentially provide the oldTarget or the oldOID.

type Reference

type Reference struct {
	// Name is the name of the reference
	Name ReferenceName
	// Target is the target of the reference. For direct references it
	// contains the object ID, for symbolic references it contains the
	// target branch name.
	Target string
	// ObjectType is the type of the object referenced.
	ObjectType ObjectType
	// ShortName: ONLY git parsed (else maybe empty)
	ShortName string
	// IsSymbolic tells whether the reference is direct or symbolic
	IsSymbolic bool
}

Reference represents a Git reference.

func FindBranch added in v0.19.0

func FindBranch(ctx context.Context, repoPath string, name string) (*Reference, error)

func FindTag added in v0.19.0

func FindTag(ctx context.Context, repoPath string, name string) (*Reference, error)

func NewReference added in v0.19.0

func NewReference(name ReferenceName, target string) Reference

NewReference creates a direct reference to an object.

func NewSymbolicReference added in v0.19.0

func NewSymbolicReference(name ReferenceName, target ReferenceName) Reference

NewSymbolicReference creates a symbolic reference to another reference.

func ParseOneReference added in v0.19.0

func ParseOneReference(referenceLine string) (*Reference, error)

func ParseReferences

func ParseReferences(ctx context.Context, repoPath string, order Order) ([]*Reference, error)

type ReferenceEx

type ReferenceEx struct {
	Name       ReferenceName // name
	ShortName  string        // short name
	Target     string        // target commit,tag or symbolic
	IsSymbolic bool          // is symbolic
	Commit     *Commit       // commit
}

func ParseBranchLineEx added in v0.19.0

func ParseBranchLineEx(referenceLine string) (*ReferenceEx, error)

type ReferenceName added in v0.19.0

type ReferenceName string

ReferenceName reference name's

const (
	HEAD   ReferenceName = "HEAD"
	Master ReferenceName = "refs/heads/master"
)

func NewBranchReferenceName added in v0.19.0

func NewBranchReferenceName(name string) ReferenceName

NewBranchReferenceName returns a reference name describing a branch based on his short name.

func NewNoteReferenceName added in v0.19.0

func NewNoteReferenceName(name string) ReferenceName

NewNoteReferenceName returns a reference name describing a note based on his short name.

func NewRemoteHEADReferenceName added in v0.19.0

func NewRemoteHEADReferenceName(remote string) ReferenceName

NewRemoteHEADReferenceName returns a reference name describing a the HEAD branch of a remote.

func NewRemoteReferenceName added in v0.19.0

func NewRemoteReferenceName(remote, name string) ReferenceName

NewRemoteReferenceName returns a reference name describing a remote branch based on his short name and the remote name.

func NewTagReferenceName added in v0.19.0

func NewTagReferenceName(name string) ReferenceName

NewTagReferenceName returns a reference name describing a tag based on short his name.

func (ReferenceName) Branch added in v0.19.0

func (r ReferenceName) Branch() (string, bool)

Branch returns `true` and the branch name if the reference is a branch. E.g. if ReferenceName is "refs/heads/master", it will return "master". If it is not a branch, `false` is returned.

func (ReferenceName) BranchName added in v0.19.0

func (r ReferenceName) BranchName() string

func (ReferenceName) IsBranch added in v0.19.0

func (r ReferenceName) IsBranch() bool

IsBranch check if a reference is a branch

func (ReferenceName) IsNote added in v0.19.0

func (r ReferenceName) IsNote() bool

IsNote check if a reference is a note

func (ReferenceName) IsRemote added in v0.19.0

func (r ReferenceName) IsRemote() bool

IsRemote check if a reference is a remote

func (ReferenceName) IsTag added in v0.19.0

func (r ReferenceName) IsTag() bool

IsTag check if a reference is a tag

func (ReferenceName) Short added in v0.19.0

func (r ReferenceName) Short() string

Short returns the short name of a ReferenceName

un strict, does not check whether the name is ambiguous

func (ReferenceName) String added in v0.19.0

func (r ReferenceName) String() string

func (ReferenceName) TagName added in v0.19.0

func (r ReferenceName) TagName() string

type ReferenceType added in v0.19.0

type ReferenceType int8

ReferenceType reference type's

const (
	InvalidReference  ReferenceType = 0
	HashReference     ReferenceType = 1
	SymbolicReference ReferenceType = 2
)

func (ReferenceType) String added in v0.19.0

func (r ReferenceType) String() string

type Signature

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

Signature represents the Author or Committer information.

func SignatureFromLine

func SignatureFromLine(line string) *Signature

func (*Signature) Decode

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

Decode decodes a byte array representing a signature to signature

func (*Signature) Encode

func (s *Signature) Encode(w io.Writer) error

func (*Signature) String

func (s *Signature) String() string

String implements the fmt.Stringer interface and formats a Signature as expected in the Git commit internal object format. For instance:

Taylor Blau <ttaylorr@github.com> 1494258422 -0600

type Tag

type Tag struct {
	// Hash of the tag.
	Hash string `json:"hash"`
	// Name of the tag.
	Name string `json:"name"`
	// Object is the hash of the target object.
	Object string `json:"object"`
	// Type is the object type of the target.
	Type string `json:"type"`
	// Tagger is the one who created the tag.
	Tagger Signature `json:"tagger"`
	// Content is an arbitrary text message.
	Content string `json:"content"`
	// contains filtered or unexported fields
}

func (*Tag) Decode

func (t *Tag) Decode(hash string, reader io.Reader, size int64) error

func (*Tag) Extract

func (t *Tag) Extract() (message string, signature string)

func (*Tag) ExtractCommitGPGSignature

func (t *Tag) ExtractCommitGPGSignature() *CommitGPGSignature

func (*Tag) Message

func (t *Tag) Message() string

func (*Tag) Pretty added in v0.19.0

func (t *Tag) Pretty(w io.Writer) error

func (*Tag) Size added in v0.19.0

func (t *Tag) Size() int64

type Tree

type Tree struct {
	// Hash of the tree object.
	Hash string `json:"hash"`
	// Entries is the list of entries held by this tree.
	Entries []*TreeEntry `json:"entries"`
	// contains filtered or unexported fields
}

Tree encapsulates a Git tree object.

func (*Tree) Decode

func (t *Tree) Decode(hash string, from io.Reader, size int64) (n int, err error)

Decode implements Object.Decode and decodes the uncompressed tree being read. It returns the number of uncompressed bytes being consumed off of the stream, which should be strictly equal to the size given.

If any error was encountered along the way, that will be returned, along with the number of bytes read up to that point.

func (*Tree) Pretty added in v0.19.0

func (t *Tree) Pretty(w io.Writer) error

Pretty tree

func (*Tree) Size added in v0.19.0

func (t *Tree) Size() int64

type TreeEntry

type TreeEntry struct {
	// Name is the entry name relative to the tree in which this entry is
	// contained.
	Name string `json:"name"`
	// Hash is the object ID (Hex) for this tree entry.
	Hash string `json:"hash"`
	// Filemode is the filemode of this tree entry on disk.
	Filemode FileMode `json:"mode"`
}

TreeEntry encapsulates information about a single tree entry in a tree listing.

func (e *TreeEntry) IsLink() bool

IsLink returns true if the given TreeEntry is a blob which represents a symbolic link (i.e., with a filemode of 0120000.

func (*TreeEntry) Type

func (e *TreeEntry) Type() string

Type is the type of entry (either blob: BlobObjectType, or a sub-tree: TreeObjectType).

type Version

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

func NewVersion added in v0.19.0

func NewVersion(major, minor, patch uint32) Version

NewVersion constructs a new Git version from the given components.

func ParseVersion added in v0.19.0

func ParseVersion(versionStr string) (Version, error)

ParseVersion parses a git version string.

func ParseVersionOutput added in v0.19.0

func ParseVersionOutput(versionOutput []byte) (Version, error)

ParseVersionOutput parses output returned by git-version(1). It is expected to be in the format "git version 2.39.1".

func (Version) Equal added in v0.19.0

func (v Version) Equal(other Version) bool

Equal determines whether the version is the same as another version.

func (Version) GreaterOrEqual added in v0.19.0

func (v Version) GreaterOrEqual(other Version) bool

GreaterOrEqual determines whether the version is newer than or equal to another version.

func (Version) LessThan added in v0.19.0

func (v Version) LessThan(other Version) bool

LessThan determines whether the version is older than another version.

func (Version) String added in v0.19.0

func (v Version) String() string

String returns the string representation of the version.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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