localrepo

package
v16.11.10 Latest Latest
Warning

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

Go to latest
Published: Sep 16, 2024 License: MIT Imports: 37 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// MergeStageAncestor denotes a conflicting file version from the common ancestor.
	MergeStageAncestor = MergeStage(1)
	// MergeStageOurs denotes a conflicting file version from our commit.
	MergeStageOurs = MergeStage(2)
	// MergeStageTheirs denotes a conflicting file version from their commit.
	MergeStageTheirs = MergeStage(3)
)

Variables

View Source
var (
	// ErrMissingTree indicates a missing tree when attempting to write a commit
	ErrMissingTree = errors.New("missing tree")
	// ErrMissingCommitterName indicates an attempt to write a commit without a
	// committer name
	ErrMissingCommitterName = errors.New("missing committer name")
	// ErrMissingAuthorName indicates an attempt to write a commit without a
	// committer name
	ErrMissingAuthorName = errors.New("missing author name")
	// ErrDisallowedCharacters indicates the name and/or email contains disallowed
	// characters
	ErrDisallowedCharacters = errors.New("disallowed characters")
	// ErrObjectNotFound is returned in case an object could not be found.
	ErrObjectNotFound = errors.New("object not found")
)
View Source
var (
	// FetchOptsTagsDefault enables importing of tags only on fetched branches.
	FetchOptsTagsDefault = FetchOptsTags("")
	// FetchOptsTagsAll enables importing of every tag from the remote repository.
	FetchOptsTagsAll = FetchOptsTags("--tags")
	// FetchOptsTagsNone disables importing of tags from the remote repository.
	FetchOptsTagsNone = FetchOptsTags("--no-tags")
)
View Source
var (
	// ErrTreeNotExist indicates that the requested tree does not exist, either because the revision
	// is invalid or because the path is not valid.
	ErrTreeNotExist = errors.New("invalid object name")
	// ErrNotTreeish indicates that the requested revision or path does not resolve to a tree
	// object.
	ErrNotTreeish = errors.New("not treeish")
	// ErrEntryNotFound indicates an entry could not be found.
	ErrEntryNotFound = errors.New("entry not found")
	// ErrEntryExists indicates an entry already exists.
	ErrEntryExists = errors.New("entry already exists")
	// ErrPathTraversal indicates a path contains a traversal.
	ErrPathTraversal = errors.New("path contains traversal")
	// ErrAbsolutePath indicates the path is an absolute path
	ErrAbsolutePath = errors.New("path is absolute")
	// ErrEmptyPath indicates the path is an absolute path
	ErrEmptyPath = errors.New("path is empty")
	// ErrDisallowedPath indicates the path is invalid
	ErrDisallowedPath = errors.New("disallowed path")
)
View Source
var ErrEmptyBundle = errors.New("refusing to create empty bundle")

ErrEmptyBundle is returned when the bundle to be created would have been empty.

View Source
var ErrMergeTreeUnrelatedHistory = errors.New("unrelated histories")

ErrMergeTreeUnrelatedHistory is used to denote the error when trying to merge two trees without unrelated history. This occurs when we don't use set the `allowUnrelatedHistories` option in the config.

View Source
var ErrParse = errors.New("failed to parse git ls-tree response")

ErrParse is returned when the parse of an entry was unsuccessful

Functions

func FormatTag

func FormatTag(
	objectID git.ObjectID,
	objectType string,
	tagName, tagBody []byte,
	tagger git.Signature,
) (string, error)

FormatTag is used by WriteTag (or for testing) to make the tag signature to feed to git-mktag, i.e. the plain-text mktag format. This does not create an object, just crafts input for "git mktag" to consume.

We are not being paranoid about exhaustive input validation here because we're just about to run git's own "fsck" check on this.

However, if someone injected parameters with extra newlines they could cause subsequent values to be ignored via a crafted message. This someone could also locally craft a tag locally and "git push" it. But allowing e.g. someone to provide their own timestamp here would at best be annoying, and at worst run up against some other assumption (e.g. that some hook check isn't as strict on locally generated data).

Types

type AddTreeEntryOption added in v16.1.0

type AddTreeEntryOption func(*addTreeEntryConfig)

AddTreeEntryOption is a function that sets options on the addTreeEntryConfig struct.

func WithOverwriteDirectory added in v16.1.0

func WithOverwriteDirectory() AddTreeEntryOption

WithOverwriteDirectory allows Add to overwrite a directory

func WithOverwriteFile added in v16.1.0

func WithOverwriteFile() AddTreeEntryOption

WithOverwriteFile allows Add to overwrite a file

type BadObjectError

type BadObjectError struct {
	// ObjectID is the object id of the object that was bad.
	ObjectID git.ObjectID
}

BadObjectError is returned when attempting to walk a bad object.

func (BadObjectError) Error

func (err BadObjectError) Error() string

Error returns the error message.

type ConflictInfoMessage

type ConflictInfoMessage struct {
	Paths   []string
	Type    string
	Message string
}

ConflictInfoMessage holds the information message output from git-merge-tree(1).

type ConflictingFileInfo

type ConflictingFileInfo struct {
	FileName string
	Mode     int32
	OID      git.ObjectID
	Stage    MergeStage
}

ConflictingFileInfo holds the conflicting file info output from git-merge-tree(1).

type CreateBundleOpts

type CreateBundleOpts struct {
	// Patterns contains all patterns which shall be bundled. Patterns should
	// be in the format accepted by git-rev-list(1) over stdin. Patterns which
	// don't match any reference will be silently ignored.
	Patterns io.Reader
}

CreateBundleOpts are optional configurations used when creating a bundle

type Entries

type Entries []TreeEntry

Entries holds every ls-tree Entry

func (Entries) Len

func (e Entries) Len() int

func (Entries) Less

func (e Entries) Less(i, j int) bool

Less sorts entries by type in the order [*tree *blobs *submodules]

func (Entries) Swap

func (e Entries) Swap(i, j int)

type Factory

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

Factory builds Repo instances.

func NewFactory

func NewFactory(logger log.Logger, locator storage.Locator, cmdFactory git.CommandFactory, catfileCache catfile.Cache) Factory

NewFactory returns a factory type that builds Repo instances. It helps avoid having to drill down Repo dependencies to all call sites that need to build a Repo.

func (Factory) Build

func (f Factory) Build(repo *gitalypb.Repository) *Repo

Build returns a Repo for the given repository.

func (Factory) ScopeByStorage

func (f Factory) ScopeByStorage(storage string) (StorageScopedFactory, error)

ScopeByStorage returns a StorageScopedFactory that builds Repo instances for a given storage from only a relative path. It checks the storage exists so the callers don't have to handle the error checking when building repositories.

type FetchBundleOpts added in v16.1.0

type FetchBundleOpts struct {
	// UpdateHead updates HEAD based on the HEAD object ID in the bundle file,
	// if available.
	UpdateHead bool
}

FetchBundleOpts are optional configurations used when fetching from a bundle.

type FetchFailedError

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

FetchFailedError indicates that the fetch has failed.

func (FetchFailedError) Error

func (e FetchFailedError) Error() string

Error returns the error message.

type FetchOpts

type FetchOpts struct {
	// Env is a list of env vars to pass to the cmd.
	Env []string
	// CommandOptions is a list of options to use with 'git' command.
	CommandOptions []git.CmdOpt
	// Prune if set fetch removes any remote-tracking references that no longer exist on the remote.
	// https://git-scm.com/docs/git-fetch#Documentation/git-fetch.txt---prune
	Prune bool
	// Force if set fetch overrides local references with values from remote that's
	// doesn't have the previous commit as an ancestor.
	// https://git-scm.com/docs/git-fetch#Documentation/git-fetch.txt---force
	Force bool
	// Verbose controls how much information is written to stderr. The list of
	// refs updated by the fetch will only be listed if verbose is true.
	// https://git-scm.com/docs/git-fetch#Documentation/git-fetch.txt---quiet
	// https://git-scm.com/docs/git-fetch#Documentation/git-fetch.txt---verbose
	Verbose bool
	// Tags controls whether tags will be fetched as part of the remote or not.
	// https://git-scm.com/docs/git-fetch#Documentation/git-fetch.txt---tags
	// https://git-scm.com/docs/git-fetch#Documentation/git-fetch.txt---no-tags
	Tags FetchOptsTags
	// DryRun, if enabled, performs the `git-fetch(1)` command without updating any references.
	DryRun bool
	// Porcelain controls `git-fetch(1)` command output and when enabled prints output in an
	// easy-to-parse format. By default, `git-fetch(1)` output is suppressed by the `--quiet` flag.
	// Therefore, the Verbose option must also be enabled to receive output.
	Porcelain bool
	// Stdout if set it would be used to redirect stdout stream into it.
	Stdout io.Writer
	// Stderr if set it would be used to redirect stderr stream into it.
	Stderr io.Writer
	// DisableTransactions will disable the reference-transaction hook and atomic transactions.
	DisableTransactions bool
}

FetchOpts is used to configure invocation of the 'FetchRemote' command.

type FetchOptsTags

type FetchOptsTags string

FetchOptsTags controls what tags needs to be imported on fetch.

func (FetchOptsTags) String

func (t FetchOptsTags) String() string

type FormatTagError

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

FormatTagError is used by FormatTag() below

func (FormatTagError) Error

func (e FormatTagError) Error() string

type GetRemoteReferencesOption

type GetRemoteReferencesOption func(*getRemoteReferenceConfig)

GetRemoteReferencesOption is an option which can be passed to GetRemoteReferences.

func WithConfig

func WithConfig(config ...git.ConfigPair) GetRemoteReferencesOption

WithConfig sets up Git configuration for the git-ls-remote(1) invocation. The config pairs are set up via `WithConfigEnv()` and are thus not exposed via the command line.

func WithPatterns

func WithPatterns(patterns ...string) GetRemoteReferencesOption

WithPatterns sets up a set of patterns which are then used to filter the list of returned references.

func WithSSHCommand

func WithSSHCommand(cmd string) GetRemoteReferencesOption

WithSSHCommand sets the SSH invocation to use when communicating with the remote.

type InvalidCommitError

type InvalidCommitError git.Revision

InvalidCommitError is returned when the revision does not point to a valid commit object.

func (InvalidCommitError) Error

func (err InvalidCommitError) Error() string

type InvalidObjectError

type InvalidObjectError string

InvalidObjectError is returned when trying to get an object id that is invalid or does not exist.

func (InvalidObjectError) Error

func (err InvalidObjectError) Error() string

type MergeStage

type MergeStage uint

MergeStage denotes the stage indicated by git-merge-tree(1) in the conflicting files information section. The man page for git-merge(1) holds more information regarding the values of the stages and what they indicate.

type MergeTreeConflictError

type MergeTreeConflictError struct {
	ConflictingFileInfo []ConflictingFileInfo
	ConflictInfoMessage []ConflictInfoMessage
}

MergeTreeConflictError encapsulates any conflicting file info and messages that occur when a merge-tree(1) command fails.

func (*MergeTreeConflictError) ConflictedFiles added in v16.2.0

func (c *MergeTreeConflictError) ConflictedFiles() []string

ConflictedFiles is used to get the list of the names of the conflicted files from the MergeTreeConflictError.

func (*MergeTreeConflictError) Error

func (c *MergeTreeConflictError) Error() string

Error returns the error string for a conflict error.

type MergeTreeOption

type MergeTreeOption func(*mergeTreeConfig)

MergeTreeOption is a function that sets a config in mergeTreeConfig.

func WithAllowUnrelatedHistories

func WithAllowUnrelatedHistories() MergeTreeOption

WithAllowUnrelatedHistories lets MergeTree accept two commits that do not share a common ancestor.

func WithConflictingFileNamesOnly

func WithConflictingFileNamesOnly() MergeTreeOption

WithConflictingFileNamesOnly lets MergeTree only parse the conflicting filenames and not the additional information.

func WithMergeBase added in v16.2.0

func WithMergeBase(base git.Revision) MergeTreeOption

WithMergeBase lets the caller pass a revision which will be passed with the --merge-base argument.

type MktagError

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

MktagError is used by WriteTag() below

func (MktagError) Error

func (e MktagError) Error() string

type ObjectReadError

type ObjectReadError struct {
	// ObjectID is the object id of the object that git failed to read
	ObjectID git.ObjectID
}

ObjectReadError is returned when reading an object fails.

func (ObjectReadError) Error

func (err ObjectReadError) Error() string

Error returns the error message.

type ObjectType

type ObjectType int

ObjectType is an Enum for the type of object of the ls-tree entry, which can be can be tree, blob or commit

const (
	Unknown ObjectType = iota
	Tree
	Blob
	Submodule
)

Enum values for ObjectType

func ObjectTypeFromString added in v16.4.0

func ObjectTypeFromString(s string) ObjectType

ObjectTypeFromString translates a string representation of the object type into an ObjectType enum.

type Parser

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

Parser holds the necessary state for parsing the ls-tree output

func NewParser

func NewParser(src io.Reader, objectHash git.ObjectHash) *Parser

NewParser returns a new Parser

func (*Parser) NextEntry

func (p *Parser) NextEntry() (*TreeEntry, error)

NextEntry reads a tree entry as it would be written by `git ls-tree -z`.

func (*Parser) NextEntryPath

func (p *Parser) NextEntryPath() ([]byte, error)

NextEntryPath reads the path of next entry as it would be written by `git ls-tree --name-only -z`.

type PushOptions

type PushOptions struct {
	// SSHCommand is the command line to use for git's SSH invocation. The command line is used
	// as is and must be verified by the caller to be safe.
	SSHCommand string
	// Force decides whether to force push all of the refspecs.
	Force bool
	// Config is the Git configuration which gets passed to the git-push(1) invocation.
	// Configuration is set up via `WithConfigEnv()`, so potential credentials won't be leaked
	// via the command line.
	Config []git.ConfigPair
}

PushOptions are options that can be configured for a push.

type ReadCommitOpt

type ReadCommitOpt func(*readCommitConfig)

ReadCommitOpt is an option for ReadCommit.

func WithTrailers

func WithTrailers() ReadCommitOpt

WithTrailers will cause ReadCommit to parse commit trailers.

type ReadTreeOption added in v16.1.0

type ReadTreeOption func(c *readTreeConfig)

ReadTreeOption is an option that modifies the behavior of ReadTree()

func WithRecursive added in v16.1.0

func WithRecursive() ReadTreeOption

WithRecursive returns all entries recursively, but "flattened" in the sense that all subtrees and their entries get returned as Entries, each entry with its full path.

func WithRelativePath added in v16.1.0

func WithRelativePath(relativePath string) ReadTreeOption

WithRelativePath will cause ReadTree to return a tree at the relative path.

type RebaseConflictError added in v16.3.0

type RebaseConflictError struct {
	Commit        string
	ConflictError *MergeTreeConflictError
}

RebaseConflictError encapsulates any conflicting file info and messages that occur when a git-merge-tree based rebase fails.

func (*RebaseConflictError) Error added in v16.3.0

func (c *RebaseConflictError) Error() string

Error returns the error string for a rebase conflict error. It is especially designed to keep compatible with git2go rebase.

type RebaseOption added in v16.3.0

type RebaseOption func(*rebaseConfig)

RebaseOption is a function that sets a config in rebaseConfig.

func RebaseWithCommitter added in v16.3.0

func RebaseWithCommitter(committer git.Signature) RebaseOption

RebaseWithCommitter provides a signature to be used as the committer for generated commits during rebase.

type Repo

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

Repo represents a local Git repository.

func New

func New(logger log.Logger, locator storage.Locator, gitCmdFactory git.CommandFactory, catfileCache catfile.Cache, repo storage.Repository) *Repo

New creates a new Repo from its protobuf representation.

func NewFrom added in v16.11.0

func NewFrom(other *Repo, repo storage.Repository) *Repo

NewFrom creates a new Repo from its protobuf representation using dependencies of another Repo.

func NewTestRepo

func NewTestRepo(tb testing.TB, cfg config.Cfg, repo storage.Repository, factoryOpts ...git.ExecCommandFactoryOption) *Repo

NewTestRepo constructs a Repo. It is intended as a helper function for tests which assembles dependencies ad-hoc from the given config.

func (*Repo) CloneBundle added in v16.3.0

func (repo *Repo) CloneBundle(ctx context.Context, reader io.Reader) error

CloneBundle clones a repository from a Git bundle with the mirror refspec.

func (*Repo) CreateBundle

func (repo *Repo) CreateBundle(ctx context.Context, out io.Writer, opts *CreateBundleOpts) error

CreateBundle creates a bundle that contains all refs. When the bundle would be empty ErrEmptyBundle is returned.

func (*Repo) Exec

func (repo *Repo) Exec(ctx context.Context, cmd git.Command, opts ...git.CmdOpt) (*command.Command, error)

Exec creates a git command with the given args and Repo, executed in the Repo. It validates the arguments in the command before executing.

func (*Repo) ExecAndWait

func (repo *Repo) ExecAndWait(ctx context.Context, cmd git.Command, opts ...git.CmdOpt) error

ExecAndWait is similar to Exec, but waits for the command to exit before returning.

func (*Repo) FetchBundle added in v16.1.0

func (repo *Repo) FetchBundle(ctx context.Context, txManager transaction.Manager, reader io.Reader, opts *FetchBundleOpts) error

FetchBundle fetches references from a bundle. Refs will be mirrored to the repository with the refspec "+refs/*:refs/*".

func (*Repo) FetchInternal

func (repo *Repo) FetchInternal(
	ctx context.Context,
	remoteRepo *gitalypb.Repository,
	refspecs []string,
	opts FetchOpts,
) error

FetchInternal performs a fetch from an internal Gitaly-hosted repository. Returns an FetchFailedError error in case git-fetch(1) failed.

func (*Repo) FetchRemote

func (repo *Repo) FetchRemote(ctx context.Context, remoteName string, opts FetchOpts) error

FetchRemote fetches changes from the specified remote. Returns an FetchFailedError error in case the fetch itself failed.

func (*Repo) GetBranches

func (repo *Repo) GetBranches(ctx context.Context) ([]git.Reference, error)

GetBranches returns all branches.

func (*Repo) GetDefaultBranch

func (repo *Repo) GetDefaultBranch(ctx context.Context) (git.ReferenceName, error)

GetDefaultBranch determines the default branch name

func (*Repo) GetReference

func (repo *Repo) GetReference(ctx context.Context, reference git.ReferenceName) (git.Reference, error)

GetReference looks up and returns the given reference. Returns a ReferenceNotFound error if the reference was not found.

func (*Repo) GetReferences

func (repo *Repo) GetReferences(ctx context.Context, patterns ...string) ([]git.Reference, error)

GetReferences returns references matching any of the given patterns. If no patterns are given, all references are returned.

func (*Repo) GetRemoteReferences

func (repo *Repo) GetRemoteReferences(ctx context.Context, remote string, opts ...GetRemoteReferencesOption) ([]git.Reference, error)

GetRemoteReferences lists references of the remote. Peeled tags are not returned.

func (*Repo) GitVersion

func (repo *Repo) GitVersion(ctx context.Context) (git.Version, error)

GitVersion returns the Git version in use.

func (*Repo) GuessHead

func (repo *Repo) GuessHead(ctx context.Context, head git.Reference) (git.ReferenceName, error)

GuessHead tries to guess what branch HEAD would be pointed at. If no reference is found git.ErrReferenceNotFound is returned.

This function should be roughly equivalent to the corresponding function in git: https://github.com/git/git/blob/2a97289ad8b103625d3a1a12f66c27f50df822ce/remote.c#L2198

func (*Repo) HasBranches

func (repo *Repo) HasBranches(ctx context.Context) (bool, error)

HasBranches determines whether there is at least one branch in the repository.

func (*Repo) HasRevision

func (repo *Repo) HasRevision(ctx context.Context, revision git.Revision) (bool, error)

HasRevision checks if a revision in the repository exists. This will not verify whether the target object exists. To do so, you can peel the revision to a given object type, e.g. by passing `refs/heads/master^{commit}`.

func (*Repo) HeadReference added in v16.1.0

func (repo *Repo) HeadReference(ctx context.Context) (git.ReferenceName, error)

HeadReference returns the current value of HEAD.

func (*Repo) InfoAlternatesPath

func (repo *Repo) InfoAlternatesPath() (string, error)

InfoAlternatesPath returns the full path of the alternates file.

func (*Repo) IsAncestor

func (repo *Repo) IsAncestor(ctx context.Context, parent, child git.Revision) (bool, error)

IsAncestor returns whether the parent is an ancestor of the child. InvalidCommitError is returned if either revision does not point to a commit in the repository.

func (*Repo) MergeTree

func (repo *Repo) MergeTree(
	ctx context.Context,
	ours, theirs string,
	mergeTreeOptions ...MergeTreeOption,
) (git.ObjectID, error)

MergeTree calls git-merge-tree(1) with arguments, and parses the results from stdout.

func (*Repo) ObjectDirectoryPath

func (repo *Repo) ObjectDirectoryPath() (string, error)

ObjectDirectoryPath returns the full path of the object directory. The errors returned are gRPC errors with relevant error codes and should be passed back to gRPC without further decoration.

func (*Repo) ObjectHash

func (repo *Repo) ObjectHash(ctx context.Context) (git.ObjectHash, error)

ObjectHash detects the object hash used by this particular repository.

func (*Repo) PackObjects

func (repo *Repo) PackObjects(ctx context.Context, objectIDs io.Reader, output io.Writer) error

PackObjects takes in object IDs separated by newlines. It packs the objects into a pack file and writes it into the output.

func (*Repo) Path

func (repo *Repo) Path() (string, error)

Path returns the on-disk path of the repository.

func (*Repo) Push

func (repo *Repo) Push(ctx context.Context, remote string, refspecs []string, options PushOptions) error

Push force pushes the refspecs to the remote.

func (*Repo) Quarantine

func (repo *Repo) Quarantine(quarantineDirectory string) (*Repo, error)

Quarantine return the repository quarantined. The quarantine directory becomes the repository's main object directory and the original object directory is configured as an alternate.

func (*Repo) QuarantineOnly added in v16.11.0

func (repo *Repo) QuarantineOnly() (*Repo, error)

QuarantineOnly returns the repository with only the quarantine directory configured as an object directory by dropping the alternate object directories. Returns an error if the repository doesn't have a quarantine directory configured.

Only the alternates configured in the *gitalypb.Repository object are dropped, not the alternates that could be in `objects/info/alternates`. Dropping the configured alternates does however also implicitly remove the `objects/info/alternates` in the alternate object directory since the file would exist there. The quarantine directory itself would not typically contain an `objects/info/alternates` file.

func (*Repo) ReadCommit

func (repo *Repo) ReadCommit(ctx context.Context, revision git.Revision, opts ...ReadCommitOpt) (*gitalypb.GitCommit, error)

ReadCommit reads the commit specified by the given revision. If no such revision exists, it will return an ErrObjectNotFound error.

func (*Repo) ReadObject

func (repo *Repo) ReadObject(ctx context.Context, oid git.ObjectID) ([]byte, error)

ReadObject reads an object from the repository's object database. InvalidObjectError is returned if the oid does not refer to a valid object.

func (*Repo) ReadObjectInfo added in v16.1.0

func (repo *Repo) ReadObjectInfo(ctx context.Context, rev git.Revision) (*catfile.ObjectInfo, error)

ReadObjectInfo attempts to read the object info based on a revision.

func (*Repo) ReadTree added in v16.1.0

func (repo *Repo) ReadTree(ctx context.Context, treeish git.Revision, options ...ReadTreeOption) (*TreeEntry, error)

ReadTree gets a tree object with all of the direct children populated. Walk can be called to populate every level of the tree.

func (*Repo) Rebase added in v16.3.0

func (repo *Repo) Rebase(ctx context.Context, upstream, branch string, options ...RebaseOption) (git.ObjectID, error)

Rebase implements a basic support for rebase using git-merge-tree(1), it follows what git-rebase(1) does but omits the abundant options. Our rebase roughly follows the core logic of git-rebase itself. Specifically, we check if fast-forward is possible firstly, if not, we 1. generate a *pick* only todo_list using git-rev-list 2. process the todo_list using git-merge-tree based cherry-pick

func (*Repo) ReferenceBackend added in v16.10.0

func (repo *Repo) ReferenceBackend(ctx context.Context) (git.ReferenceBackend, error)

ReferenceBackend detects the reference backend used by this repository.

func (*Repo) ResolveRevision

func (repo *Repo) ResolveRevision(ctx context.Context, revision git.Revision) (git.ObjectID, error)

ResolveRevision resolves the given revision to its object ID. This will not verify whether the target object exists. To do so, you can peel the reference to a given object type, e.g. by passing `refs/heads/master^{commit}`. Returns an ErrReferenceNotFound error in case the revision does not exist.

func (*Repo) SetConfig

func (repo *Repo) SetConfig(ctx context.Context, key, value string, txManager transaction.Manager) (returnedErr error)

SetConfig will set a configuration value. Any preexisting values will be overwritten with the new value. The change will use transactional semantics.

func (*Repo) SetDefaultBranch

func (repo *Repo) SetDefaultBranch(ctx context.Context, txManager transaction.Manager, reference git.ReferenceName) error

SetDefaultBranch sets the repository's HEAD to point to the given reference. It will not verify the reference actually exists.

func (*Repo) StorageTempDir

func (repo *Repo) StorageTempDir() (string, error)

StorageTempDir returns the temporary dir for the storage where the repo is on. When this directory does not exist yet, it's being created.

func (*Repo) UnpackObjects

func (repo *Repo) UnpackObjects(ctx context.Context, packFile io.Reader) error

UnpackObjects unpacks the objects from the pack file to the repository's object database.

func (*Repo) UnsetMatchingConfig

func (repo *Repo) UnsetMatchingConfig(
	ctx context.Context,
	regex string,
	txManager transaction.Manager,
) (returnedErr error)

UnsetMatchingConfig removes all config entries whose key match the given regular expression. If no matching keys are found, then this function returns an `git.ErrNotFound` error. The change will use transactional semantics.

func (*Repo) UpdateRef

func (repo *Repo) UpdateRef(ctx context.Context, reference git.ReferenceName, newValue, oldValue git.ObjectID) error

UpdateRef updates reference from oldValue to newValue. If oldValue is a non-empty string, the update will fail it the reference is not currently at that revision. If newValue is the ZeroOID, the reference will be deleted. If oldValue is the ZeroOID, the reference will created.

func (*Repo) WalkUnreachableObjects

func (repo *Repo) WalkUnreachableObjects(ctx context.Context, heads io.Reader, output io.Writer) error

WalkUnreachableObjects walks the object graph starting from heads and writes to the output object IDs that are included in the walk but unreachable from any of the repository's references. Heads should return object IDs separated with a newline. Output is object IDs separated by newlines.

func (*Repo) WriteBlob

func (repo *Repo) WriteBlob(ctx context.Context, content io.Reader, cfg WriteBlobConfig) (git.ObjectID, error)

WriteBlob writes a blob to the repository's object database and returns its object ID.

func (*Repo) WriteCommit

func (repo *Repo) WriteCommit(ctx context.Context, cfg WriteCommitConfig) (git.ObjectID, error)

WriteCommit writes a new commit into the target repository.

func (*Repo) WriteTag

func (repo *Repo) WriteTag(
	ctx context.Context,
	objectID git.ObjectID,
	objectType string,
	tagName, tagBody []byte,
	tagger git.Signature,
) (git.ObjectID, error)

WriteTag writes a tag to the repository's object database with git-mktag and returns its object ID.

It's important that this be git-mktag and not git-hash-object due to its fsck sanity checking semantics.

type StorageScopedFactory

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

StorageScopedFactory builds Repo instances for a given storage. The storage has been checked to exist.

func (StorageScopedFactory) Build

func (f StorageScopedFactory) Build(relativePath string) *Repo

Build builds a Repo instance for the repository at relativePath in the storage.

type TreeEntriesByPath added in v16.1.0

type TreeEntriesByPath []*TreeEntry

TreeEntriesByPath allows a slice of *TreeEntry to be sorted by Path

func (TreeEntriesByPath) Len added in v16.1.0

func (b TreeEntriesByPath) Len() int

func (TreeEntriesByPath) Less added in v16.1.0

func (b TreeEntriesByPath) Less(i, j int) bool

func (TreeEntriesByPath) Swap added in v16.1.0

func (b TreeEntriesByPath) Swap(i, j int)

type TreeEntry

type TreeEntry struct {
	// OID is the object ID the tree entry refers to.
	OID git.ObjectID
	// Mode is the file mode of the tree entry.
	Mode string
	// Path is the full path of the tree entry.
	Path string
	// Type is the type of the tree entry.
	Type ObjectType
	// Entries is a slice of this tree's entries.
	Entries []*TreeEntry
}

TreeEntry represents an entry of a git tree object.

func (*TreeEntry) Add added in v16.1.0

func (t *TreeEntry) Add(
	path string,
	newEntry TreeEntry,
	options ...AddTreeEntryOption,
) error

Add takes an entry and adds it to an existing TreeEntry based on path. It works by walking down the TreeEntry's Entries, layer by layer, based on path. If it reaches the limit when walking down the tree, that means the rest of the directories path will need to be created. If we're able to walk all the way down the tree based on path, then we either add the new entry to the last subtree's entries if it doesn't yet exist, or optionally overwrite the entry if it already exists.

func (*TreeEntry) Delete added in v16.1.0

func (t *TreeEntry) Delete(
	path string,
) error

Delete deletes the entry of a current tree based on the path. The parent entry is deleted if the entry is the last child of the parent, this propagates up to the root node, but the root node is never deleted.

func (*TreeEntry) Get added in v16.1.0

func (t *TreeEntry) Get(
	path string,
) (*TreeEntry, error)

Get gets an entry of a current tree based on the path.

func (*TreeEntry) IsBlob

func (t *TreeEntry) IsBlob() bool

IsBlob returns whether or not the TreeEntry is a blob.

func (*TreeEntry) Modify added in v16.1.0

func (t *TreeEntry) Modify(
	path string,
	modifyEntry func(*TreeEntry) error,
) error

Modify modifies an existing TreeEntry based on a path and a function to modify an entry.

func (*TreeEntry) Walk added in v16.1.0

func (t *TreeEntry) Walk(callback func(path string, entry *TreeEntry) error) error

Walk will walk the whole tree structure and call callback on every entry of the tree in a depth-first like fashion.

func (*TreeEntry) Write added in v16.1.0

func (t *TreeEntry) Write(
	ctx context.Context,
	repo *Repo,
) error

Write does a depth first walk, writing new trees when the OID of the TreeEntry is empty.

type WriteBlobConfig added in v16.4.0

type WriteBlobConfig = git.WriteBlobConfig

WriteBlobConfig is the configuration used to write blobs into the repository.

type WriteCommitConfig

type WriteCommitConfig struct {
	Reference          string
	Parents            []git.ObjectID
	AuthorDate         time.Time
	AuthorName         string
	AuthorEmail        string
	CommitterName      string
	CommitterEmail     string
	CommitterDate      time.Time
	Message            string
	TreeEntries        []TreeEntry
	TreeID             git.ObjectID
	AlternateObjectDir string
	GitConfig          config.Git
}

WriteCommitConfig contains fields for writing a commit

Jump to

Keyboard shortcuts

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