gitcmd

package
v18.6.1 Latest Latest
Warning

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

Go to latest
Published: Nov 25, 2025 License: MIT Imports: 44 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// ReferenceTransactionHook represents the reference-transaction git hook.
	ReferenceTransactionHook = Hook(1 << iota)
	// UpdateHook represents the update git hook.
	UpdateHook
	// PreReceiveHook represents the pre-receive git hook.
	PreReceiveHook
	// PostReceiveHook represents the post-receive git hook.
	PostReceiveHook
	// PackObjectsHook represents the pack-objects git hook.
	PackObjectsHook
	// ProcReceiveHook represents the proc-receive git hook.
	ProcReceiveHook

	// AllHooks is the bitwise set of all hooks supported by Gitaly.
	AllHooks = ReferenceTransactionHook | UpdateHook | PreReceiveHook | PostReceiveHook | PackObjectsHook
	// ReceivePackHooks includes the set of hooks which shall be executed in
	// a typical "push" or an emulation thereof (e.g. `updateReferenceWithHooks()`).
	ReceivePackHooks = ReferenceTransactionHook | UpdateHook | PreReceiveHook | PostReceiveHook
)
View Source
const (
	// ProtocolV1 is the special value used by Git clients to request protocol v1
	ProtocolV1 = "version=1"
	// ProtocolV2 is the special value used by Git clients to request protocol v2
	ProtocolV2 = "version=2"
)
View Source
const (
	// BigFileThresholdMB is the threshold we configure via `core.bigFileThreshold` and determines the maximum size
	// after which Git considers files to be big. Please refer to `GlobalConfiguration()` for more details.
	BigFileThresholdMB = 50
)
View Source
const (
	// EnvHooksPayload is the name of the environment variable used
	// to hold the hooks payload.
	EnvHooksPayload = "GITALY_HOOKS_PAYLOAD"
)
View Source
const (
	// InternalGitalyURL is a special URL that indicates Gitaly wants to push to or fetch from
	// another internal Gitaly instance.
	InternalGitalyURL = "ssh://gitaly/internal.git"
)

Variables

View Source
var (
	// ErrInvalidArg represent family of errors to report about bad argument used to make a call.
	ErrInvalidArg = errors.New("invalid argument")
	// ErrHookPayloadRequired indicates a HookPayload is needed but
	// absent from the command.
	ErrHookPayloadRequired = errors.New("hook payload is required but not configured")
)
View Source
var (
	// ErrNotConfigured may be returned by an ExecutionEnvironmentConstructor in case an
	// environment was not configured.
	ErrNotConfigured = errors.New("execution environment is not configured")

	// BundledGitConstructors defines the versions of Git that we embed into the Gitaly
	// binary.
	BundledGitConstructors = []BundledGitEnvironmentConstructor{
		{
			Suffix: "-master",
			FeatureFlags: []featureflag.FeatureFlag{
				featureflag.GitMaster,
			},
		},
		{
			Suffix: "-v2.50",
		},
	}
)
View Source
var ErrPayloadNotFound = errors.New("no hooks payload found in environment")

ErrPayloadNotFound is returned by HooksPayloadFromEnv if the given environment variables don't have a hooks payload.

View Source
var OutputToStdout = StaticOption{/* contains filtered or unexported fields */}

OutputToStdout is used indicate the output should be sent to STDOUT Seen in: git bundle create

ValidRefUpdateTypes returns a list of struct of the seven valid types of update

Functions

func BuildSSHInvocation

func BuildSSHInvocation(ctx context.Context, logger log.Logger, sshKey, knownHosts string) (string, func(), error)

BuildSSHInvocation builds a command line to invoke SSH with the provided key and known hosts. Both are optional.

func ConfigPairsToGitEnvironment

func ConfigPairsToGitEnvironment(configPairs []ConfigPair) []string

ConfigPairsToGitEnvironment converts the given config pairs into a set of environment variables that can be injected into a Git executable.

func DefaultTrace2HooksFor

func DefaultTrace2HooksFor(ctx context.Context, subCmd string, logger log.Logger, rl *rate.Limiter) []trace2.Hook

DefaultTrace2HooksFor creates a list of all Trace2 hooks. It doesn't mean all hooks are triggered. Each hook's activation status will be evaluated before the command starts.

func DetectObjectHash

func DetectObjectHash(ctx context.Context, repoPath string) (_ git.ObjectHash, returnedErr error)

DetectObjectHash detects the object-hash used by the given repository. It plucks out the first objectformat configuration value from the repository's configuration file and doesn't validate the configuration.

Note: It is recommended to use localrepo.ObjectHash since that value is cached for a given repository.

func DetectReferenceBackend

func DetectReferenceBackend(ctx context.Context, repoPath string) (_ git.ReferenceBackend, returnedErr error)

DetectReferenceBackend detects the reference backend used by the repository. It plucks out the first refstorage configuration value from the repository's configuration file and doesn't validate the configuration.

Note: It is recommended to use localrepo.ReferenceBackend since that value is cached for a given repository.

func GetReferences

func GetReferences(ctx context.Context, repoExecutor RepositoryExecutor, cfg GetReferencesConfig) ([]git.Reference, error)

GetReferences enumerates references in the given repository. By default, it returns all references that exist in the repository. This behaviour can be tweaked via the `GetReferencesConfig`.

func GetSymbolicRef

func GetSymbolicRef(ctx context.Context, repoExecutor RepositoryExecutor, refname git.ReferenceName) (git.Reference, error)

GetSymbolicRef reads the symbolic reference.

func IsInvalidArgErr

func IsInvalidArgErr(err error) bool

IsInvalidArgErr relays if the error is due to an argument validation failure

func WarnIfTooManyBitmaps

func WarnIfTooManyBitmaps(ctx context.Context, logger log.Logger, locator storage.Locator, storageName, repoPath string)

WarnIfTooManyBitmaps checks for too many (more than one) bitmaps in repoPath, and if it finds any, it logs a warning. This is to help us investigate https://gitlab.com/gitlab-org/gitaly/issues/1728.

func WriteBlob

func WriteBlob(ctx context.Context, repoExecutor RepositoryExecutor, content io.Reader, cfg WriteBlobConfig) (git.ObjectID, error)

WriteBlob writes a blob into the given repository.

Types

type BundledGitEnvironmentConstructor

type BundledGitEnvironmentConstructor struct {
	// Suffix is the version suffix used for this specific bundled Git environment. In case
	// multiple sets of bundled Git versions are installed it is possible to also have multiple
	// of these bundled Git environments with different suffixes.
	Suffix string
	// FeatureFlags is the set of feature flags which must be enabled in order for the bundled
	// Git environment to be enabled. Note that _all_ feature flags must be set to `true` in the
	// context.
	FeatureFlags []featureflag.FeatureFlag
}

BundledGitEnvironmentConstructor sets up an ExecutionEnvironment for a bundled Git installation. Bundled Git is a partial Git installation, where only a subset of Git binaries are installed into Gitaly's binary directory. The binaries must have a `gitaly-` prefix like e.g. `gitaly-git`. Bundled Git installations can be installed with Gitaly's Makefile via `make install WITH_BUNDLED_GIT=YesPlease`.

func (BundledGitEnvironmentConstructor) Construct

func (c BundledGitEnvironmentConstructor) Construct(cfg config.Cfg) (_ ExecutionEnvironment, returnedErr error)

Construct sets up an ExecutionEnvironment for a bundled Git installation. Because bundled Git installations are not complete Git installations we need to set up a usable environment at runtime. This is done by creating a temporary directory into which we symlink the bundled binaries with their usual names as expected by Git. Furthermore, we configure the GIT_EXEC_PATH environment variable to point to that directory such that Git is able to locate its auxiliary binaries.

type CmdOpt

type CmdOpt func(context.Context, config.Cfg, CommandFactory, *cmdCfg) error

CmdOpt is an option for running a command

func ConvertGlobalOptions

func ConvertGlobalOptions(options *gitalypb.GlobalOptions) []CmdOpt

ConvertGlobalOptions converts a protobuf message to a CmdOpt.

func WithCompletionErrorLogFilter

func WithCompletionErrorLogFilter(fn func(cmd *command.Command, stderr string) bool) CmdOpt

WithCompletionErrorLogFilter configures a function that should return true if an errored command should not produce logs.

func WithConfig

func WithConfig(configPairs ...ConfigPair) CmdOpt

WithConfig adds git configuration entries to the command.

func WithConfigEnv

func WithConfigEnv(configPairs ...ConfigPair) CmdOpt

WithConfigEnv adds git configuration entries to the command's environment. This should be used in place of `WithConfig()` in case config entries may contain secrets which shouldn't leak e.g. via the process's command line.

func WithDisabledHooks

func WithDisabledHooks() CmdOpt

WithDisabledHooks returns an option that satisfies the requirement to set up hooks, but won't in fact set up hook execution.

func WithEnv

func WithEnv(envs ...string) CmdOpt

WithEnv adds environment variables to the command.

func WithFinalizer

func WithFinalizer(finalizer func(context.Context, *command.Command)) CmdOpt

WithFinalizer sets up the finalizer to be run when the command is being wrapped up. It will be called after `Wait()` has returned.

func WithGitProtocol

func WithGitProtocol(logger log.Logger, req RequestWithGitProtocol) CmdOpt

WithGitProtocol checks whether the request has Git protocol v2 and sets this in the environment.

func WithGitalyGPG

func WithGitalyGPG() CmdOpt

WithGitalyGPG sets gpg.prgoram to gitaly-gpg for commit signing

func WithGlobalOption

func WithGlobalOption(opts ...GlobalOption) CmdOpt

WithGlobalOption adds the global options to the command. These are universal options which work across all git commands.

func WithInternalFetchWithSidechannel

func WithInternalFetchWithSidechannel(req *gitalypb.SSHUploadPackWithSidechannelRequest) CmdOpt

WithInternalFetchWithSidechannel returns an option which sets up git-fetch(1) to fetch from another internal Gitaly node. In contrast to WithInternalFetch, this will call SSHUploadPackWithSidechannel instead of SSHUploadPack.

func WithPackObjectsHookEnv

func WithPackObjectsHookEnv(objectHash git.ObjectHash, repo *gitalypb.Repository, protocol string) CmdOpt

WithPackObjectsHookEnv provides metadata for gitaly-hooks so it can act as a pack-objects hook.

func WithReceivePackHooks

func WithReceivePackHooks(objectHash git.ObjectHash, req ReceivePackRequest, protocol string, enableProcReceive bool) CmdOpt

WithReceivePackHooks returns an option that populates the safe command with the environment variables necessary to properly execute the pre-receive, update, post-receive, and proc-receive (if enabled) hooks for git-receive-pack(1).

func WithRefTxHook

func WithRefTxHook(objectHash git.ObjectHash, repo storage.Repository) CmdOpt

WithRefTxHook returns an option that populates the safe command with the environment variables necessary to properly execute a reference hook for repository changes that may possibly update references

func WithReferenceBackend

func WithReferenceBackend(refBackend git.ReferenceBackend) CmdOpt

WithReferenceBackend sets the 'reference_backend' metric label on the command.

func WithSetupStdin

func WithSetupStdin() CmdOpt

WithSetupStdin sets up the command so that it can be `Write()`en to.

func WithSetupStdout

func WithSetupStdout() CmdOpt

WithSetupStdout sets up the command so that it can be `Read()` from.

func WithStderr

func WithStderr(w io.Writer) CmdOpt

WithStderr sets the command's stderr.

func WithStdin

func WithStdin(r io.Reader) CmdOpt

WithStdin sets the command's stdin. Pass `command.SetupStdin` to make the command suitable for `Write()`ing to.

func WithStdout

func WithStdout(w io.Writer) CmdOpt

WithStdout sets the command's stdout.

func WithWorktree

func WithWorktree(worktreePath string) CmdOpt

WithWorktree sets up the Git command to run in the given worktree path by using the `-C` switch.

type Command

type Command struct {
	// Name is the name of the Git command to run, e.g. "log", "cat-file" or "worktree".
	Name string
	// Action is the action of the Git command, e.g. "set-url" in `git remote set-url`
	Action string
	// Flags is the number of optional flags to pass before positional arguments, e.g.
	// `--oneline` or `--format=fuller`.
	Flags []Option
	// Args is the arguments that shall be passed after all flags. These arguments must not be
	// flags and thus cannot start with `-`. Note that it may be unsafe to use this field in the
	// case where arguments are directly user-controlled. In that case it is advisable to use
	// `PostSepArgs` instead.
	Args []string
	// PostSepArgs is the arguments that shall be passed as positional arguments after the `--`
	// separator. Git recognizes that separator as the point where it should stop expecting any
	// options and treat the remaining arguments as positionals. This should be used when
	// passing user-controlled input of arbitrary form like for example paths, which may start
	// with a `-`.
	PostSepArgs []string
}

Command represent a Git command.

func (Command) CommandArgs

func (c Command) CommandArgs() ([]string, error)

CommandArgs checks all arguments in the sub command and validates them

type CommandFactory

type CommandFactory interface {
	// New creates a new command for the repo repository.
	New(ctx context.Context, repo storage.Repository, sc Command, opts ...CmdOpt) (*command.Command, error)
	// NewWithoutRepo creates a command without a target repository.
	NewWithoutRepo(ctx context.Context, sc Command, opts ...CmdOpt) (*command.Command, error)
	// GetExecutionEnvironment returns parameters required to execute Git commands.
	GetExecutionEnvironment(context.Context) ExecutionEnvironment
	// HooksPath returns the path where Gitaly's Git hooks reside.
	HooksPath(context.Context) string
	// GitVersion returns the Git version used by the command factory.
	GitVersion(context.Context) (git.Version, error)
}

CommandFactory is designed to create and run git commands in a protected and fully managed manner.

type ConfigPair

type ConfigPair = config.GitConfig

ConfigPair is a GlobalOption that can be passed to Git commands to inject per-command config entries via the `git -c` switch.

func ConvertConfigOptions

func ConvertConfigOptions(options []string) ([]ConfigPair, error)

ConvertConfigOptions converts `<key>=<value>` config entries into `ConfigPairs`.

func GetURLAndResolveConfig

func GetURLAndResolveConfig(remoteURL string, resolvedAddress string) (string, []ConfigPair, error)

GetURLAndResolveConfig parses the given repository's URL and resolved address to generate the modified URL and configuration to avoid DNS rebinding.

In Git v2.37.0 we added the functionality for `http.curloptResolve` which like its curl counterpart when provided with a `HOST:PORT:ADDRESS` value, uses the IP Address provided directly for the given HOST:PORT combination for HTTP/HTTPS protocols, without requiring DNS resolution.

This functions currently does the following operations:

- Git Protocol: Replaces the hostname with the resolved IP address. - SSH Protocol: Replaces the hostname with the resolved IP address (supports both the regular syntax `ssh://[user@]server/project.git` and scp-like syntax `[user@]server:project.git`). - HTTP/HTTPS Protocol: Keeps the URL as is, but adds the `http.curloptResolve` flag.

SideNote: We cannot replace the hostname with IP in HTTPS protocol because the protocol demands the hostname to be present, as it is required for the SSL verification.

type DistributedGitEnvironmentConstructor

type DistributedGitEnvironmentConstructor struct{}

DistributedGitEnvironmentConstructor creates ExecutionEnvironments via the Git binary path configured in the Gitaly configuration. This expects a complete Git installation with all its components. The installed distribution must either have its prefix compiled into the binaries or alternatively be compiled with runtime-detection of the prefix such that Git is able to locate its auxiliary helper binaries correctly.

func (DistributedGitEnvironmentConstructor) Construct

Construct sets up an ExecutionEnvironment for a complete Git distribution. No setup needs to be performed given that the Git environment is expected to be self-contained.

For testing purposes, this function overrides the configured Git binary path if the `GITALY_TESTING_GIT_BINARY` environment variable is set.

type ExecCommandFactory

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

ExecCommandFactory knows how to properly construct different types of commands.

func NewExecCommandFactory

func NewExecCommandFactory(cfg config.Cfg, logger log.Logger, opts ...ExecCommandFactoryOption) (_ *ExecCommandFactory, _ func(), returnedErr error)

NewExecCommandFactory returns a new instance of initialized ExecCommandFactory. The returned cleanup function shall be executed when the server shuts down.

func (*ExecCommandFactory) AttrTreeConfig

func (cf *ExecCommandFactory) AttrTreeConfig(ctx context.Context, repo storage.Repository, sc Command, opts ...CmdOpt) *ConfigPair

AttrTreeConfig adds `attr.tree = HEAD` to the commands in the whiteList have, others has `attr.tree = emptyTreeHash`.

func (*ExecCommandFactory) Collect

func (cf *ExecCommandFactory) Collect(metrics chan<- prometheus.Metric)

Collect is used to collect Prometheus metrics.

func (*ExecCommandFactory) Describe

func (cf *ExecCommandFactory) Describe(descs chan<- *prometheus.Desc)

Describe is used to describe Prometheus metrics.

func (*ExecCommandFactory) GetExecutionEnvironment

func (cf *ExecCommandFactory) GetExecutionEnvironment(ctx context.Context) ExecutionEnvironment

GetExecutionEnvironment returns parameters required to execute Git commands.

func (*ExecCommandFactory) GitVersion

func (cf *ExecCommandFactory) GitVersion(ctx context.Context) (git.Version, error)

GitVersion returns the Git version in use. The version is cached as long as the binary remains unchanged as determined by stat(3P).

func (*ExecCommandFactory) GlobalConfiguration

func (cf *ExecCommandFactory) GlobalConfiguration(ctx context.Context) ([]ConfigPair, error)

GlobalConfiguration returns the global Git configuration that should be applied to every Git command.

func (*ExecCommandFactory) HooksPath

func (cf *ExecCommandFactory) HooksPath(ctx context.Context) string

HooksPath returns the path where Gitaly's Git hooks reside.

func (*ExecCommandFactory) New

func (cf *ExecCommandFactory) New(ctx context.Context, repo storage.Repository, sc Command, opts ...CmdOpt) (*command.Command, error)

New creates a new command for the repo repository.

func (*ExecCommandFactory) NewWithoutRepo

func (cf *ExecCommandFactory) NewWithoutRepo(ctx context.Context, sc Command, opts ...CmdOpt) (*command.Command, error)

NewWithoutRepo creates a command without a target repository.

type ExecCommandFactoryOption

type ExecCommandFactoryOption func(*execCommandFactoryConfig)

ExecCommandFactoryOption is an option that can be passed to NewExecCommandFactory.

func WithCgroupsManager

func WithCgroupsManager(cgroupsManager cgroups.Manager) ExecCommandFactoryOption

WithCgroupsManager overrides the Cgroups manager used by the command factory.

func WithExecutionEnvironmentConstructors

func WithExecutionEnvironmentConstructors(constructors ...ExecutionEnvironmentConstructor) ExecCommandFactoryOption

WithExecutionEnvironmentConstructors overrides the default Git execution environments used by the command factory.

func WithGitBinaryPath

func WithGitBinaryPath(path string) ExecCommandFactoryOption

WithGitBinaryPath overrides the path to the Git binary that shall be executed.

func WithHooksPath

func WithHooksPath(hooksPath string) ExecCommandFactoryOption

WithHooksPath will override the path where hooks are to be found.

func WithSkipHooks

func WithSkipHooks() ExecCommandFactoryOption

WithSkipHooks will skip any use of hooks in this command factory.

func WithTrace2Hooks

func WithTrace2Hooks(hooks []trace2.Hook) ExecCommandFactoryOption

WithTrace2Hooks overrides default trace2 hooks used by trace2 manager

type ExecutionEnvironment

type ExecutionEnvironment struct {
	// BinaryPath is the path to the Git binary.
	BinaryPath string
	// EnvironmentVariables are variables which must be set when running the Git binary.
	EnvironmentVariables []string
	// contains filtered or unexported fields
}

ExecutionEnvironment describes the environment required to execute a Git command

func (ExecutionEnvironment) Cleanup

func (e ExecutionEnvironment) Cleanup() error

Cleanup cleans up any state set up by this ExecutionEnvironment.

func (ExecutionEnvironment) IsEnabled

func (e ExecutionEnvironment) IsEnabled(ctx context.Context) bool

IsEnabled checks whether the ExecutionEnvironment is enabled in the given context. An execution environment will typically be enabled by default, except if it's feature-flagged.

type ExecutionEnvironmentConstructor

type ExecutionEnvironmentConstructor interface {
	Construct(config.Cfg) (ExecutionEnvironment, error)
}

ExecutionEnvironmentConstructor is an interface for constructors of Git execution environments. A constructor should be able to set up an environment in which it is possible to run Git executables.

type FallbackGitEnvironmentConstructor

type FallbackGitEnvironmentConstructor struct{}

FallbackGitEnvironmentConstructor sets up a fallback execution environment where Git is resolved via the `PATH` environment variable. This is only intended as a last resort in case no other environments have been set up.

func (FallbackGitEnvironmentConstructor) Construct

Construct sets up an execution environment by searching `PATH` for a `git` executable.

type FeatureFlagWithValue

type FeatureFlagWithValue struct {
	// Flag is the feature flag.
	Flag featureflag.FeatureFlag `json:"flag"`
	// Enabled indicates whether the flag is enabled or not.
	Enabled bool `json:"enabled"`
}

FeatureFlagWithValue is used as part of the HooksPayload to pass on feature flags with their values to gitaly-hooks.

type FetchPorcelainScanner

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

FetchPorcelainScanner scans the output of `git fetch` when the porcelain option is enabled, allowing information about references to be gathered.

func NewFetchPorcelainScanner

func NewFetchPorcelainScanner(r io.Reader, hash git.ObjectHash) *FetchPorcelainScanner

NewFetchPorcelainScanner returns a FetchPorcelainScanner.

func (*FetchPorcelainScanner) Err

func (f *FetchPorcelainScanner) Err() error

Err returns any error encountered while scanning.

func (*FetchPorcelainScanner) Scan

func (f *FetchPorcelainScanner) Scan() bool

Scan parses the next fetch status line from the fetch command output.

func (*FetchPorcelainScanner) StatusLine

StatusLine returns the status line information from the last scanned line.

type FetchPorcelainStatusLine

type FetchPorcelainStatusLine struct {
	Type      RefUpdateType
	OldOID    git.ObjectID
	NewOID    git.ObjectID
	Reference string
}

FetchPorcelainStatusLine represents a line of status output from `git fetch` when the porcelain option is enabled.

type FetchScanner

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

FetchScanner scans the output of `git fetch`, allowing information about the updated refs to be gathered

func NewFetchScanner

func NewFetchScanner(r io.Reader) *FetchScanner

NewFetchScanner returns a new FetchScanner

func (*FetchScanner) Err

func (f *FetchScanner) Err() error

Err returns any error encountered while scanning the reader supplied to NewFetchScanner(). Note that lines not matching the expected format are not an error.

func (*FetchScanner) Scan

func (f *FetchScanner) Scan() bool

Scan looks for the next fetch status line in the reader supplied to NewFetchScanner(). Any lines that are not valid status lines are discarded without error. It returns true if you should call Scan() again, and false if scanning has come to an end.

func (*FetchScanner) StatusLine

func (f *FetchScanner) StatusLine() FetchStatusLine

StatusLine returns the most recent fetch status line encountered by the FetchScanner. It changes after each call to Scan(), unless there is an error.

type FetchStatusLine

type FetchStatusLine struct {
	// Type encodes the kind of change that git fetch has made
	Type RefUpdateType
	// Summary is a brief description of the change. This may be text such as
	// [new tag], or a compact-form SHA range showing the old and new values of
	// the updated reference, depending on the type of update
	Summary string
	// From is usually the name of the remote ref being fetched from, missing
	// the refs/<type>/ prefix. If a ref is being deleted, this will be "(none)"
	From string
	// To is the name of the local ref being updated, missing the refs/<type>/
	// prefix.
	To string
	// Reason optionally contains human-readable information about the change. It
	// is typically used to explain why making a given change failed (e.g., the
	// type will be RefUpdateTypeUpdateFailed). It may be empty.
	Reason string
}

FetchStatusLine represents a line of status output from `git fetch`, as documented here: https://git-scm.com/docs/git-fetch/2.30.0#_output. Each line is a change to a git reference in the local repository that was caused by the fetch

func (FetchStatusLine) IsTagAdded

func (f FetchStatusLine) IsTagAdded() bool

IsTagAdded returns true if this status line indicates a new tag was added

func (FetchStatusLine) IsTagUpdated

func (f FetchStatusLine) IsTagUpdated() bool

IsTagUpdated returns true if this status line indicates a tag was changed

type Flag

type Flag struct {
	Name string
}

Flag is a single token optional command line argument that enables or disables functionality (e.g. "-L")

func (Flag) GlobalArgs

func (f Flag) GlobalArgs() ([]string, error)

GlobalArgs returns the arguments for the given flag, which should typically only be the flag itself. It returns an error if the flag is not sanitary.

func (Flag) OptionArgs

func (f Flag) OptionArgs() ([]string, error)

OptionArgs returns an error if the flag is not sanitary

type GetReferencesConfig

type GetReferencesConfig struct {
	// Patterns limits the returned references to only those which match the given pattern. If no patterns are given
	// then all references will be returned.
	Patterns []string
	// Limit limits
	Limit uint
}

GetReferencesConfig is configuration that can be passed to GetReferences in order to change its default behaviour.

type GlobalOption

type GlobalOption interface {
	GlobalArgs() ([]string, error)
}

GlobalOption is an interface for all options which can be globally applied to git commands. This is the command-inspecific part before the actual command that's being run, e.g. the `-c` part in `git -c foo.bar=value command`.

type Hook

type Hook uint

Hook represents a git hook. See githooks(5) for more information about existing hooks.

type HooksPayload

type HooksPayload struct {
	// RequestedHooks is a bitfield of requested Hooks. Hooks which
	// were not requested will not get executed.
	RequestedHooks Hook `json:"requested_hooks"`
	// FeatureFlagsWithValue contains feature flags with their values. They are set into the
	// outgoing context when calling HookService.
	FeatureFlagsWithValue []FeatureFlagWithValue `json:"feature_flags_with_value,omitempty"`

	// Repo is the repository in which the hook is running.
	Repo *gitalypb.Repository `json:"-"`
	// ObjectFormat is the object format used by the repository. Some hooks use it in order to
	// verify object IDs part of their input.
	ObjectFormat string `json:"object_format"`

	// RuntimeDir is the path to Gitaly's runtime directory.
	RuntimeDir string `json:"runtime_dir"`
	// InternalSocket is the path to Gitaly's internal socket.
	InternalSocket string `json:"internal_socket"`
	// InternalSocketToken is the token required to authenticate with
	// Gitaly's internal socket.
	InternalSocketToken string `json:"internal_socket_token"`

	// Transaction is used to identify a reference transaction. This is an optional field -- if
	// it's not set, no transactional voting will happen.
	Transaction *txinfo.Transaction `json:"transaction"`

	// UserDetails contains information required when executing
	// git-receive-pack or git-upload-pack
	UserDetails *UserDetails `json:"user_details"`

	// TransactionID identifies the storage transaction this hooks call runs in. It's
	// used to access the transaction in the hook manager.
	TransactionID storage.TransactionID `json:"transaction_id,omitempty"`

	// GitalyClientContext contains the context passed through the RPCs.
	GitalyClientContext []byte `json:"gitaly_client_context,omitempty"`

	// LogFields contains the log fields in the current context. They are passed
	// to the HookService so the calls can be correlated with the main RPC call.
	LogFields log.Fields
}

HooksPayload holds parameters required for all hooks.

func HooksPayloadFromEnv

func HooksPayloadFromEnv(envs []string) (HooksPayload, error)

HooksPayloadFromEnv extracts the HooksPayload from the given environment variables. If no HooksPayload exists, it returns a ErrPayloadNotFound error.

func NewHooksPayload

func NewHooksPayload(
	ctx context.Context,
	cfg config.Cfg,
	repo storage.Repository,
	objectHash git.ObjectHash,
	tx *txinfo.Transaction,
	userDetails *UserDetails,
	requestedHooks Hook,
	featureFlagsWithValue map[featureflag.FeatureFlag]bool,
	transactionID storage.TransactionID,
) HooksPayload

NewHooksPayload creates a new hooks payload which can then be encoded and passed to Git hooks.

func (HooksPayload) Env

func (p HooksPayload) Env() (string, error)

Env encodes the given HooksPayload into an environment variable.

func (HooksPayload) IsHookRequested

func (p HooksPayload) IsHookRequested(hook Hook) bool

IsHookRequested returns whether the HooksPayload is requesting execution of the given git hook.

type Option

type Option interface {
	OptionArgs() ([]string, error)
}

Option is a git command line flag with validation logic

type ReceivePackRequest

type ReceivePackRequest interface {
	GetGlId() string
	GetGlUsername() string
	GetGlRepository() string
	GetRepository() *gitalypb.Repository
}

ReceivePackRequest abstracts away the different requests that end up spawning git-receive-pack.

type RefUpdateType

type RefUpdateType byte

RefUpdateType represents the type of update a FetchStatusLine is. The valid types are documented here: https://git-scm.com/docs/git-fetch/2.30.0#Documentation/git-fetch.txt-flag

const (
	// RefUpdateTypeFastForwardUpdate represents a 'fast forward update' fetch status line
	RefUpdateTypeFastForwardUpdate RefUpdateType = ' '
	// RefUpdateTypeForcedUpdate represents a 'forced update' fetch status line
	RefUpdateTypeForcedUpdate RefUpdateType = '+'
	// RefUpdateTypePruned represents a 'pruned' fetch status line
	RefUpdateTypePruned RefUpdateType = '-'
	// RefUpdateTypeTagUpdate represents a 'tag update' fetch status line
	RefUpdateTypeTagUpdate RefUpdateType = 't'
	// RefUpdateTypeFetched represents a 'fetched' fetch status line. This
	// indicates that a new reference has been created in the local repository
	RefUpdateTypeFetched RefUpdateType = '*'
	// RefUpdateTypeUpdateFailed represents an 'update failed' fetch status line
	RefUpdateTypeUpdateFailed RefUpdateType = '!'
	// RefUpdateTypeUnchanged represents an 'unchanged' fetch status line
	RefUpdateTypeUnchanged RefUpdateType = '='
)

func (RefUpdateType) Valid

func (t RefUpdateType) Valid() bool

Valid checks whether the RefUpdateType is one of the seven valid types of update

type Repository

type Repository interface {
	// ResolveRevision tries to resolve the given revision to its object
	// ID. This uses the typical DWIM mechanism of git, see gitrevisions(1)
	// for accepted syntax. This will not verify whether the object ID
	// exists. To do so, you can peel the reference to a given object type,
	// e.g. by passing `refs/heads/master^{commit}`.
	ResolveRevision(ctx context.Context, revision git.Revision) (git.ObjectID, error)
	// HasBranches returns whether the repository has branches.
	HasBranches(ctx context.Context) (bool, error)
	// GetDefaultBranch returns the default branch of the repository.
	GetDefaultBranch(ctx context.Context) (git.ReferenceName, error)
	// HeadReference returns the reference that HEAD points to for the
	// repository.
	HeadReference(ctx context.Context) (git.ReferenceName, error)
}

Repository is the common interface of different repository implementations.

type RepositoryExecutor

type RepositoryExecutor interface {
	storage.Repository
	Exec(ctx context.Context, cmd Command, opts ...CmdOpt) (*command.Command, error)
	ExecAndWait(ctx context.Context, cmd Command, opts ...CmdOpt) error
	GitVersion(ctx context.Context) (git.Version, error)
	ObjectHash(ctx context.Context) (git.ObjectHash, error)
	ReferenceBackend(ctx context.Context) (git.ReferenceBackend, error)
}

RepositoryExecutor is an interface which allows execution of Git commands in a specific repository.

type RequestWithGitProtocol

type RequestWithGitProtocol interface {
	GetGitProtocol() string
}

RequestWithGitProtocol holds requests that respond to GitProtocol

type ShowRefDecoder

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

ShowRefDecoder parses the output format of git-show-ref

func NewShowRefDecoder

func NewShowRefDecoder(r io.Reader) *ShowRefDecoder

NewShowRefDecoder returns a new ShowRefDecoder

func (*ShowRefDecoder) Decode

func (d *ShowRefDecoder) Decode(ref *git.Reference) error

Decode reads and parses the next reference. Returns io.EOF when the end of the reader has been reached.

type StaticOption

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

StaticOption are reusable trusted options

func (StaticOption) OptionArgs

func (sa StaticOption) OptionArgs() ([]string, error)

OptionArgs just passes through the already trusted value. This never returns an error.

type UserDetails

type UserDetails struct {
	// Username contains the name of the user who has caused the hook to be executed.
	Username string `json:"username"`
	// UserID contains the ID of the user who has caused the hook to be executed.
	UserID string `json:"userid"`
	// Protocol contains the protocol via which the hook was executed. This
	// can be one of "web", "ssh" or "smarthttp".
	Protocol string `json:"protocol"`
	// RemoteIP contains the original IP of the client who initiated the flow leading to this
	// target hook.
	RemoteIP string `json:"remote_ip"`
}

UserDetails contains all information which is required for hooks executed by git-receive-pack, namely the pre-receive, update or post-receive hook.

type ValueFlag

type ValueFlag struct {
	Name  string
	Value string
}

ValueFlag is an optional command line argument that is comprised of pair of tokens (e.g. "-n 50")

func (ValueFlag) GlobalArgs

func (vf ValueFlag) GlobalArgs() ([]string, error)

GlobalArgs returns the arguments for the given value flag, which should typically be two arguments: the flag and its value. It returns an error if the value flag is not sanitary.

func (ValueFlag) OptionArgs

func (vf ValueFlag) OptionArgs() ([]string, error)

OptionArgs returns an error if the flag is not sanitary

type WriteBlobConfig

type WriteBlobConfig struct {
	//  Path is used by git to decide which filters to run on the content.
	Path string
}

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

Jump to

Keyboard shortcuts

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