git

package
v0.14.0 Latest Latest
Warning

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

Go to latest
Published: Nov 29, 2024 License: Apache-2.0 Imports: 22 Imported by: 0

Documentation

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 (
	RefsPrefix   = "refs/"
	BranchPrefix = "refs/heads/"
	TagPrefix    = "refs/tags/"
)
View Source
const (
	// GitTimeLayout is the (default) time layout used by git.
	GitTimeLayout = "Mon Jan _2 15:04:05 2006 -0700"
)
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 (
	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 (
	Version = sync.OnceValues(gitVersionDetect)
)

Functions

func BranchRev

func BranchRev(r string) string

func ConformingEmptyBlob

func ConformingEmptyBlob(hexOID string) string

func ConformingEmptyTree

func ConformingEmptyTree(hexOID string) string

func ConformingHashZero

func ConformingHashZero(hexOID string) string

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

func IsErrAlreadyLocked(err error) bool

func IsErrBadReferenceName

func IsErrBadReferenceName(err error) bool

func IsErrNotExist

func IsErrNotExist(err error) bool

IsErrNotExist if some error is ErrNotExist

func IsErrUnexpectedType

func IsErrUnexpectedType(err error) bool

func IsGitVersionAtLeast

func IsGitVersionAtLeast(ver string) 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 IsVersionAtLeast

func IsVersionAtLeast(actualVersion, desiredVersion string) bool

IsVersionAtLeast compares 2 version strings (ok to be prefixed with 'git version', ignores)

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, hashAlgo HashAlgo) 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 ReferenceBranchName

func ReferenceBranchName(b string) string

func ReferenceTagName

func ReferenceTagName(tag string) string

func ReferenceTarget

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

func ReferenceUpdate

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

func RepoIsBare

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

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 RevParseHashALG

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

func RevParseRepoPath

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

RevParseRepoPath parse repo dir

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
	// Tree is the hash of the root tree of the commit.
	Tree string
	// Parents are the hashes of the parent commits of the commit.
	Parents []string
	// Author is the original author of the commit.
	Author Signature
	// Committer is the one performing the commit, might be different from
	// Author.
	Committer Signature
	// ExtraHeaders stores headers not listed above, for instance
	// "encoding", "gpgsig", or "mergetag" (among others).
	ExtraHeaders []*ExtraHeader
	// Message is the commit message, contains arbitrary text.
	Message string
}

func (*Commit) Decode

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

func (*Commit) ExtractCommitGPGSignature

func (c *Commit) ExtractCommitGPGSignature() *CommitGPGSignature

func (*Commit) Signature

func (c *Commit) Signature() string

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

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

ResolveCommit resolve peeled commit

func (*Decoder) Tree

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

type ErrAlreadyLocked

type ErrAlreadyLocked struct {
	Ref string
}

func (*ErrAlreadyLocked) Error

func (e *ErrAlreadyLocked) Error() string

type ErrBadReferenceName

type ErrBadReferenceName struct {
	Name string
}

func (ErrBadReferenceName) Error

func (err ErrBadReferenceName) 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 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
	// 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
}

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 HashAlgo

type HashAlgo int

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

const (
	HashAlgoUNKNOWN HashAlgo = iota // UNKNOWN
	HashAlgoSHA1                    // SHA1
	HashAlgoSHA256                  // SHA256
)

func HashAlgoAlwaysOK

func HashAlgoAlwaysOK(repoPath string) HashAlgo

func HashAlgoFast

func HashAlgoFast(repoPath string) (HashAlgo, error)

func HashAlgoFromHexSize

func HashAlgoFromHexSize(hlen int) HashAlgo

func HashAlgoFromName

func HashAlgoFromName(algo string) HashAlgo

func HashAlgoFromRawSize

func HashAlgoFromRawSize(rlen int) HashAlgo

func (HashAlgo) EmptyBlobID

func (h HashAlgo) EmptyBlobID() string

func (HashAlgo) EmptyTreeID

func (h HashAlgo) EmptyTreeID() string

func (HashAlgo) Hasher

func (h HashAlgo) Hasher() hash.Hash

func (HashAlgo) HexSize

func (h HashAlgo) HexSize() int

HexSize: hex size

func (HashAlgo) RawSize

func (h HashAlgo) RawSize() int

RawSize: raw length

func (HashAlgo) String

func (h HashAlgo) String() string

func (HashAlgo) ZeroOID

func (h HashAlgo) 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 HashAlgo) (*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 Reference

type Reference struct {
	// Name is the full reference name of the reference.
	Name string
	// Hash is the Hash of the referred-to object.
	Hash string
	// ObjectType is the type of the object referenced.
	ObjectType ObjectType
	// ShortName is the short reference name of the reference
	ShortName string
}

func FindTagReference

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

func ParseReferenceLine

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

func ParseReferences

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

type ReferenceEx

type ReferenceEx struct {
	// Name is the full reference name of the reference.
	Name string
	// Hash is the Hash of the referred-to object.
	Hash string
	// ObjectType is the type of the object referenced.
	ObjectType ObjectType
	// ShortName is the short reference name of the reference
	ShortName string
	// ShortName is the short reference name of the reference
	Commit *Commit
}

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 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
	// Name of the tag.
	Name string
	// Object is the hash of the target object.
	Object string
	// Type is the object type of the target.
	Type string
	// Tagger is the one who created the tag.
	Tagger Signature
	// Message is an arbitrary text message.
	Message string
}

func (*Tag) Decode

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

func (*Tag) Extract

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

func (*Tag) ExtractCommitGPGSignature

func (t *Tag) ExtractCommitGPGSignature() *CommitGPGSignature

func (*Tag) StrictMessage

func (t *Tag) StrictMessage() string

type Tree

type Tree struct {
	// Hash of the tree object.
	Hash string
	// Entries is the list of entries held by this tree.
	Entries []*TreeEntry
}

Tree encapsulates a Git tree object.

func (*Tree) Decode

func (t *Tree) Decode(hash string, from io.Reader) (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.

type TreeEntry

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

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

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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