git

package
v18.6.0-rc43 Latest Latest
Warning

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

Go to latest
Published: Nov 19, 2025 License: MIT Imports: 20 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// InternalReferenceTypeHidden indicates that a reference should never be advertised or
	// writeable.
	InternalReferenceTypeHidden = InternalReferenceType(iota + 1)
	// InternalReferenceTypeReadonly indicates that a reference should be advertised, but not
	// writeable.
	InternalReferenceTypeReadonly
)
View Source
const DefaultBranch = "main"

DefaultBranch is the default reference written to HEAD when a repository is created

View Source
const DefaultRef = ReferenceName("refs/heads/" + DefaultBranch)

DefaultRef is the reference that GitLab will use if HEAD of the bare repository is not found, or other edge cases to detect the default branch.

View Source
const LegacyDefaultRef = ReferenceName("refs/heads/master")

LegacyDefaultRef is the reference that used to be the default HEAD of the bare repository. If the default reference is not found, Gitaly will still test the legacy default.

View Source
const MirrorRefSpec = "+refs/*:refs/*"

MirrorRefSpec is the refspec used when --mirror is specified on git clone.

View Source
const ObjectPoolRefNamespace = "refs/remotes/origin"

ObjectPoolRefNamespace is the namespace used for the references of the primary pool member part of an object pool.

View Source
const PackFileRegexCore = `(.*/pack-)([0-9a-f]{40}|[0-9a-f]{64})`

PackFileRegexCore is the regex that matches the common parts of pack and idx filenames.

View Source
const (
	// Rfc2822DateFormat is the date format that Git typically uses for dates.
	Rfc2822DateFormat = "Mon Jan 02 2006 15:04:05 -0700"
)
View Source
const ZeroChecksum = "0000000000000000000000000000000000000000"

ZeroChecksum is the hex representation of a checksum with no references added.

Variables

View Source
var (
	// ObjectHashSHA1 is the implementation of an object ID via SHA1.
	ObjectHashSHA1 = ObjectHash{
		Hash:         sha1.New,
		EmptyTreeOID: ObjectID("4b825dc642cb6eb9a060e54bf8d69288fbee4904"),
		ZeroOID:      ObjectID("0000000000000000000000000000000000000000"),
		Format:       "sha1",
		ProtoFormat:  gitalypb.ObjectFormat_OBJECT_FORMAT_SHA1,
	}

	// ObjectHashSHA256 is the implementation of an object ID via SHA256.
	ObjectHashSHA256 = ObjectHash{
		Hash:         sha256.New,
		EmptyTreeOID: ObjectID("6ef19b41225c5369f1c104d45d8d85efa9b057b53b14b4b9b939dd74decc5321"),
		ZeroOID:      ObjectID("0000000000000000000000000000000000000000000000000000000000000000"),
		Format:       "sha256",
		ProtoFormat:  gitalypb.ObjectFormat_OBJECT_FORMAT_SHA256,
	}
)
View Source
var (
	// ReferenceBackendReftables denotes the new binary format based
	// reftable backend.
	// See https://www.git-scm.com/docs/reftable for more details.
	ReferenceBackendReftables = ReferenceBackend{
		Name: "reftable",
		// contains filtered or unexported fields
	}

	// ReferenceBackendFiles denotes the traditional filesystem based
	// reference backend.
	ReferenceBackendFiles = ReferenceBackend{
		Name: "files",
		// contains filtered or unexported fields
	}
)
View Source
var (
	// ErrReferenceNotFound represents an error when a reference was not
	// found.
	ErrReferenceNotFound = errors.New("reference not found")
	// ErrReferenceAmbiguous represents an error when a reference couldn't
	// unambiguously be resolved.
	ErrReferenceAmbiguous = errors.New("reference is ambiguous")

	// ErrAlreadyExists represents an error when the resource is already exists.
	ErrAlreadyExists = errors.New("already exists")
	// ErrNotFound represents an error when the resource can't be found.
	ErrNotFound = errors.New("not found")
)
View Source
var InternalRefPrefixes = map[string]InternalReferenceType{

	"refs/environments/": InternalReferenceTypeReadonly,

	"refs/keep-around/": InternalReferenceTypeHidden,

	"refs/merge-requests/": InternalReferenceTypeReadonly,

	"refs/pipelines/": InternalReferenceTypeReadonly,

	"refs/remotes/": InternalReferenceTypeHidden,

	"refs/tmp/": InternalReferenceTypeHidden,
}

InternalRefPrefixes is an array of all reference prefixes which are used internally by GitLab. These need special treatment in some cases, e.g. to restrict writing to them.

Functions

func AlternateObjectDirectories

func AlternateObjectDirectories(ctx context.Context, logger log.Logger, storageRoot, repoPath string) ([]string, error)

AlternateObjectDirectories reads the alternates file of the repository and returns absolute paths to its alternate object directories, if any. The returned directories are verified to exist and that they are within the storage root. The alternate directories are returned recursively, not only the immediate alternates.

func DetectSignatureType

func DetectSignatureType(line string) gitalypb.SignatureType

DetectSignatureType detects the signature type of a git commit signature

func FormatSignatureTime

func FormatSignatureTime(t time.Time) string

FormatSignatureTime formats a time such that it can be embedded into a tag or commit object directly.

This function should not be used in all other contexts. Refer to `FormatTime()` for the reasoning.

func FormatTime

func FormatTime(t time.Time) string

FormatTime formats the given time such that it can be used by Git.

The formatted string uses RFC2822, which is typically used in the context of emails to format dates and which is well understood by Git in many contexts. This is _not_ usable though when you want to write a signature date directly into a Git object. In all other contexts, e.g. when passing a date via `GIT_COMMITTER_DATE`, it is preferable to use this format as it is unambiguous to Git. Unix timestamps are only recognized once they have at least 8 digits, which would thus rule all commit dates before 1970-04-26 17:46:40 +0000 UTC. While this is only ~4 months that we'd be missing since the birth of Unix timestamps, especially the zero date is likely going to come up frequently.

If you need to format a time to be used in signatures directly, e.g. because it is passed to git-hash-object(1), you can use `FormatSignatureTime()` instead.

func IsLFSPointer

func IsLFSPointer(b []byte) (bool, []byte, int64)

IsLFSPointer checks to see if a blob is an LFS pointer. TODO: this is incomplete as it does not recognize pre-release version of LFS blobs with the "https://hawser.github.com/spec/v1" version. For compatibility with the Ruby RPC, we leave this as-is for now though.

func ListPackfiles

func ListPackfiles(objDir string) ([]string, error)

ListPackfiles returns the packfiles in objDir.

func NewTreeEntry

func NewTreeEntry(commitOid, rootPath string, filename, oidBytes, modeBytes []byte) (*gitalypb.TreeEntry, error)

NewTreeEntry is a helper to construct a gitalypb.TreeEntry from the provided parameters.

func ObjectDirectories

func ObjectDirectories(ctx context.Context, logger log.Logger, storageRoot, repoPath string) ([]string, error)

ObjectDirectories looks for Git object directories, including alternates specified in objects/info/alternates.

CAVEAT Git supports quoted strings in here, but we do not. We should never need those on a Gitaly server.

func ParseDateSeconds

func ParseDateSeconds(seconds string) int64

ParseDateSeconds turns a seconds field in a Git commit into a unix timestamp

func ValidateReference

func ValidateReference(name string) error

ValidateReference checks whether a reference looks valid. It aims to be a faithful implementation of Git's own `check_or_sanitize_refname()` function and all divergent behaviour is considered to be a bug. Please also refer to https://git-scm.com/docs/git-check-ref-format#_description for further information on the actual rules.

func ValidateRevision

func ValidateRevision(revision []byte, opts ...ValidateRevisionOption) error

ValidateRevision checks if a revision looks valid. The default behaviour can be changed by passing ValidateRevisionOptions.

Types

type Checksum

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

Checksum is a hash representation of all references in a repository. Checksum must not be copied after first use.

func (*Checksum) Add

func (c *Checksum) Add(ref Reference)

Add adds a reference to the checksum.

func (*Checksum) AddBytes

func (c *Checksum) AddBytes(line []byte)

AddBytes adds a reference to the checksum that is a line in the output format of `git-show-ref`.

func (*Checksum) Bytes

func (c *Checksum) Bytes() []byte

Bytes returns the checksum as a slice of bytes.

func (*Checksum) IsZero

func (c *Checksum) IsZero() bool

IsZero returns true when no references have been added to the checksum.

func (*Checksum) String

func (c *Checksum) String() string

String returns the checksum as a hex encoded string.

type InternalReferenceType

type InternalReferenceType int

InternalReferenceType is the type of an internal reference.

type InvalidObjectIDCharError

type InvalidObjectIDCharError struct {
	OID     string
	BadChar rune
}

InvalidObjectIDCharError is returned when an object ID's string representation contains an invalid hexadecimal digit.

func (InvalidObjectIDCharError) Error

func (e InvalidObjectIDCharError) Error() string

type InvalidObjectIDLengthError

type InvalidObjectIDLengthError struct {
	OID           string
	CorrectLength int
	Length        int
}

InvalidObjectIDLengthError is returned when an object ID's string representation is not the required length.

func (InvalidObjectIDLengthError) Error

type Object

type Object interface {
	// ObjectInfo provides information about the object.
	ObjectInfo
	// Reader reads object data.
	io.Reader
	// WriterTo writes object data into a reader.
	io.WriterTo
}

Object is an interface encapsulating an object with contents.

type ObjectHash

type ObjectHash struct {
	// Hash is the hashing function used to hash objects.
	Hash func() hash.Hash
	// EmptyTreeOID is the object ID of the tree object that has no directory entries.
	EmptyTreeOID ObjectID
	// ZeroOID is the special value that Git uses to signal a ref or object does not exist
	ZeroOID ObjectID
	// Format is the name of the object hash.
	Format string
	// ProtoFormat is the Protobuf representation of the object format.
	ProtoFormat gitalypb.ObjectFormat
}

ObjectHash is a hash-function specific implementation of an object ID.

func ObjectHashByFormat

func ObjectHashByFormat(format string) (ObjectHash, error)

ObjectHashByFormat looks up the ObjectHash by its format name.

func ObjectHashByProto

func ObjectHashByProto(format gitalypb.ObjectFormat) (ObjectHash, error)

ObjectHashByProto looks up the ObjectHash by its Protobuf representation `gitalypb.ObjectFormat`. Returns an error in case the object format is not known.

func (ObjectHash) EncodedLen

func (h ObjectHash) EncodedLen() int

EncodedLen returns the length of the hex-encoded string of a full object ID.

func (ObjectHash) FromHex

func (h ObjectHash) FromHex(hex string) (ObjectID, error)

FromHex constructs a new ObjectID from the given hex representation of the object ID. Returns ErrInvalidObjectID if the given object ID is not valid.

func (ObjectHash) HashData

func (h ObjectHash) HashData(bytes []byte) ObjectID

HashData hashes the given bytes to an object ID.

func (ObjectHash) IsZeroOID

func (h ObjectHash) IsZeroOID(oid ObjectID) bool

IsZeroOID checks whether the given object ID is the all-zeroes object ID for the given hash.

func (ObjectHash) ValidateHex

func (h ObjectHash) ValidateHex(hex string) error

ValidateHex checks if `hex` is a syntactically correct object ID for the given hash. Abbreviated object IDs are not deemed to be valid. Returns an `ErrInvalidObjectID` if the `hex` is not valid.

type ObjectID

type ObjectID string

ObjectID represents an object ID.

func (ObjectID) Bytes

func (oid ObjectID) Bytes() ([]byte, error)

Bytes returns the byte representation of the ObjectID.

func (ObjectID) Revision

func (oid ObjectID) Revision() Revision

Revision returns a revision of the ObjectID. This directly returns the hex representation as every object ID is a valid revision.

func (ObjectID) String

func (oid ObjectID) String() string

String returns the hex representation of the ObjectID.

type ObjectInfo

type ObjectInfo interface {
	ObjectID() ObjectID
	ObjectType() string
	ObjectSize() int64
}

ObjectInfo is an interface encapsulating information about objects.

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
	// IsSymbolic tells whether the reference is direct or symbolic
	IsSymbolic bool
}

Reference represents a Git reference.

func NewReference

func NewReference(name ReferenceName, target ObjectID) Reference

NewReference creates a direct reference to an object.

func NewSymbolicReference

func NewSymbolicReference(name ReferenceName, target ReferenceName) Reference

NewSymbolicReference creates a symbolic reference to another reference.

type ReferenceBackend

type ReferenceBackend struct {

	// Name is the name of the reference backend.
	Name string
	// contains filtered or unexported fields
}

ReferenceBackend is the specific backend implementation of references.

func ReferenceBackendByName

func ReferenceBackendByName(name string) (ReferenceBackend, error)

ReferenceBackendByName maps the output of `rev-parse --show-ref-format` to Gitaly's internal reference backend types.

type ReferenceName

type ReferenceName string

ReferenceName represents the name of a git reference, e.g. "refs/heads/master". It does not support extended revision notation like a Revision does and must always contain a fully qualified reference.

func NewReferenceNameFromBranchName

func NewReferenceNameFromBranchName(branch string) ReferenceName

NewReferenceNameFromBranchName returns a new ReferenceName from a given branch name. Note that branch is treated as an unqualified branch name. This function will thus always prepend "refs/heads/".

func (ReferenceName) Branch

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

func (r ReferenceName) Revision() Revision

Revision converts the ReferenceName to a Revision. This is safe to do as a reference is always also a revision.

func (ReferenceName) String

func (r ReferenceName) String() string

String returns the string representation of the ReferenceName.

type ReferenceUpdate

type ReferenceUpdate struct {
	// OldOID is the old OID the reference is expected to point to prior to updating it.
	// If the reference does not point to the old value, the reference verification fails.
	OldOID ObjectID
	// NewOID is the new desired OID to point the reference to.
	NewOID ObjectID
	// OldTarget is the expected target for a symbolic reference.
	OldTarget ReferenceName
	// NewTarget stores the desired target for a symbolic reference.
	NewTarget ReferenceName
}

ReferenceUpdate describes the state of a reference's old and new tip in an update.

func (*ReferenceUpdate) IsRegularUpdate

func (r *ReferenceUpdate) IsRegularUpdate() bool

IsRegularUpdate is used to check if the update is a regular reference update, which updates a ref from an old OID to a new OID.

This excludes symrefs and regular <> symref conversions.

type ReferenceUpdates

type ReferenceUpdates map[ReferenceName]ReferenceUpdate

ReferenceUpdates contains references to update. Reference name is used as the key and the value is the expected old tip and the desired new tip.

type RequestWithUserAndTimestamp

type RequestWithUserAndTimestamp interface {
	GetUser() *gitalypb.User
	GetTimestamp() *timestamppb.Timestamp
}

RequestWithUserAndTimestamp represents a collection of requests that contains information used to generate a signature for user.

type Revision

type Revision string

Revision represents anything that resolves to either a commit, multiple commits or to an object different than a commit. This could be e.g. "master", "master^{commit}", an object hash or similar. See gitrevisions(1) for supported syntax.

func (Revision) String

func (r Revision) String() string

String returns the string representation of the Revision.

type Signature

type Signature struct {
	// Name of the author or the committer.
	Name string
	// Email of the author or the committer.
	Email string
	// When is the time of the commit.
	When time.Time
}

Signature represents a commits signature.

func NewSignature

func NewSignature(name, email string, when time.Time) Signature

NewSignature creates a new sanitized signature.

func SignatureFromRequest

func SignatureFromRequest(req RequestWithUserAndTimestamp) (Signature, error)

SignatureFromRequest generates and returns a signature from the request, respecting the timezone information of the user.

type ValidateRevisionOption

type ValidateRevisionOption func(cfg *validateRevisionConfig)

ValidateRevisionOption is an option that can be passed to ValidateRevision.

func AllowEmptyRevision

func AllowEmptyRevision() ValidateRevisionOption

AllowEmptyRevision changes ValidateRevision to not return an error in case the specified revision is empty.

func AllowPathScopedRevision

func AllowPathScopedRevision() ValidateRevisionOption

AllowPathScopedRevision changes ValidateRevision to allow path-scoped revisions like `HEAD:README.md`. Note that path-scoped revisions may contain any character except for NUL bytes. Most importantly, a path-scoped revision may contain newlines.

func AllowPseudoRevision

func AllowPseudoRevision() ValidateRevisionOption

AllowPseudoRevision changes ValidateRevision to allow pseudo-revisions understood by git-rev-list(1). This includes options like `--all`, `--not`, `--branches` or `--glob`.

type Version

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

Version represents the version of git itself.

func NewRCVersion

func NewRCVersion(major, minor, patch, gl uint32) Version

NewRCVersion constructs a new Git RC version from the given components.

func NewVersion

func NewVersion(major, minor, patch, gl uint32) Version

NewVersion constructs a new Git version from the given components.

func ParseVersion

func ParseVersion(versionStr string) (Version, error)

ParseVersion parses a git version string.

func ParseVersionOutput

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

func (Version) Equal

func (v Version) Equal(other Version) bool

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

func (Version) GreaterOrEqual

func (v Version) GreaterOrEqual(other Version) bool

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

func (Version) IsCatfileObjectTypeFilterSupported

func (v Version) IsCatfileObjectTypeFilterSupported() bool

IsCatfileObjectTypeFilterSupported checks whether the current Git version supports the `git cat-file --filter=` option.

func (Version) LessThan

func (v Version) LessThan(other Version) bool

LessThan determines whether the version is older than another version.

func (Version) String

func (v Version) String() string

String returns the string representation of the version.

func (Version) UsesBatchedUpdates

func (v Version) UsesBatchedUpdates(ctx context.Context) bool

UsesBatchedUpdates checks whether the current Git version uses batched updates in 'git-fetch(1)' and 'git-receive-pack(1)'.

Directories

Path Synopsis
Package pktline implements utility functions for working with the Git pkt-line format.
Package pktline implements utility functions for working with the Git pkt-line format.

Jump to

Keyboard shortcuts

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