Documentation
¶
Overview ¶
Package clone keeps local checkouts of HTTPS Git repositories. It provides shallow clone-or-fetch, optional shallow submodules, exact temporary tag checkouts, bounded retries for network failures, a persistent cache, and capped reads and content classification for files from commits. Operations shell out to the git binary, which must be on PATH. The github.com/git-pkgs/clone/gogit module provides in-process blob reads.
Index ¶
- Constants
- Variables
- func Blob(ctx context.Context, dir, commit, blobPath string, maxBytes int64) (content []byte, binary, truncated bool, err error)
- func CheckoutTag(ctx context.Context, dir, tag string) (restore func(context.Context) error, err error)
- func CopyTree(src, dst string) error
- func DestReset(dst string) func() error
- func Ensure(ctx context.Context, retry Retry, url, dst, ref string, full bool) error
- func EnsureWithOptions(ctx context.Context, retry Retry, url, dst, ref string, options EnsureOptions) error
- func Head(ctx context.Context, dir string) string
- func RedactURL(raw string) string
- func RemoteBranches(ctx context.Context, retry Retry, url string) ([]string, error)
- func RemoteHead(ctx context.Context, retry Retry, url string) (string, error)
- func Run(ctx context.Context, dir string, env []string, args ...string) (string, error)
- func SanitizePath(value string) (string, bool)
- func TransientFailure(out string) bool
- func ValidCommit(sha string) bool
- func ValidateRef(ref string) error
- func ValidateURL(raw string) error
- type BlobResult
- type Cache
- type Command
- type EnsureOptions
- type Notice
- type Retry
- type Runner
- type UnreachableError
Constants ¶
const ( DefaultAttempts = 3 DefaultBaseDelay = 500 * time.Millisecond DefaultMaxDelay = 4 * time.Second )
const DefaultWaitDelay = 10 * time.Second
Variables ¶
var ErrTagNotFound = errors.New("tag not found")
ErrTagNotFound reports that an exact local tag does not exist.
Functions ¶
func Blob ¶
func Blob(ctx context.Context, dir, commit, blobPath string, maxBytes int64) (content []byte, binary, truncated bool, err error)
Blob reads path from commit in dir through the git binary. It caps content at maxBytes and reports whether the blob is binary or was truncated. commit and path are validated with ValidCommit and SanitizePath before invoking Git.
func CheckoutTag ¶ added in v0.4.0
func CheckoutTag(ctx context.Context, dir, tag string) (restore func(context.Context) error, err error)
CheckoutTag force-checks out the commit named by an exact local tag in detached-HEAD state. It returns a function that force-restores the previous HEAD commit and reattaches its branch when that branch has not moved.
CheckoutTag does not fetch. It discards tracked working-tree and index changes both when checking out the tag and when restoring the previous HEAD. The caller supplies the restoration context so cleanup can continue with a fresh context after the original operation is cancelled.
func CopyTree ¶
CopyTree recursively copies src to dst, preserving permissions but not ownership or timestamps. Symlinks are recreated with their original target.
func DestReset ¶
DestReset returns the cleanup to run after a failed clone attempt, or nil when there is nothing safe to clean. A clone that dies partway can leave the destination behind, and `git clone` refuses a non-empty target, so the cleanup is needed both before retries and before a terminal error return.
Removal is offered only when dst is absent or empty at this point. Callers reach the clone path exactly when dst holds no .git, so an absent or empty dst can only ever gain content this call put there. A non-empty one belongs to the caller, and Git would reject it as a permanent error that is never retried anyway.
func Ensure ¶
Ensure clones url into dst on its first call, then fetches and resets the checkout on later calls. A shallow clone is used unless full is true. An existing shallow clone is unshallowed when full changes to true. ref may be a branch, tag, commit ID, or empty for the remote's default branch.
func EnsureWithOptions ¶ added in v0.6.0
func EnsureWithOptions(ctx context.Context, retry Retry, url, dst, ref string, options EnsureOptions) error
EnsureWithOptions clones or updates a checkout like Ensure. When RecurseSubmodules is enabled, it also makes a best-effort attempt to initialize and update nested submodules with depth 1. A submodule failure does not fail the checkout, but context cancellation still does.
func Head ¶
Head returns the object ID at HEAD in dir, or an empty string when dir is not a Git repository.
func RedactURL ¶ added in v0.1.1
RedactURL replaces any userinfo in raw with a fixed placeholder so error messages and logs cannot leak an embedded token. A URL that fails to parse is returned unchanged: url.Parse does not accept control bytes, so an unparseable string here is one ValidateURL would already have rejected for a reason unrelated to its credential.
func RemoteBranches ¶
RemoteBranches returns the sorted branch names advertised by url. It disables terminal prompts and the ambient credential helper.
func RemoteHead ¶
RemoteHead returns the object ID advertised as HEAD by url.
func SanitizePath ¶
SanitizePath returns a slash-form path safe to use in a Git object expression. It rejects empty and absolute paths, NUL bytes, and traversal.
func TransientFailure ¶
TransientFailure reports whether Git's combined output describes a failure worth another attempt.
The classification fails closed. A permanent marker wins over a transient one, and output matching nothing at all is treated as permanent, so an unfamiliar message keeps today's single-attempt behavior rather than turning into repeated remote traffic.
func ValidCommit ¶
ValidCommit reports whether sha is a lowercase hexadecimal object ID or abbreviated object ID between 4 and 64 characters long.
func ValidateRef ¶
ValidateRef restricts refs to a conservative branch and tag name character set before they are passed to Git.
func ValidateURL ¶
ValidateURL rejects Git URLs that do not use HTTPS, do not parse, or contain control bytes. Embedded userinfo is accepted (some callers use https://<token>@host/... for private repos) but should be redacted before logging; UnreachableError.Error and this package's own error strings do so via RedactURL.
Types ¶
type BlobResult ¶ added in v0.2.0
BlobResult contains a bounded blob read and its content classification.
func InspectBlob ¶ added in v0.2.0
func InspectBlob(ctx context.Context, dir, commit, blobPath string, maxBytes int64) (BlobResult, error)
InspectBlob reads path from commit in dir through the git binary and classifies the returned bytes. It uses prefix detection when maxBytes truncates the blob. commit and path are validated with ValidCommit and SanitizePath before invoking Git.
type Cache ¶
type Cache struct {
Root string // Parent directory for per-URL checkouts.
Retry Retry // Retry policy for clone and fetch operations.
RecurseSubmodules bool // Best-effort inclusion of nested shallow submodules.
// contains filtered or unexported fields
}
Cache keeps one persistent checkout per repository URL. A Cache must not be copied after its first use.
func (*Cache) DiskBytes ¶
DiskBytes returns the number of bytes used by regular files in url's cache directory. It returns zero when the directory is absent.
func (*Cache) EnsureCommit ¶
EnsureCommit unshallows the cached checkout when commit is not already reachable. It does nothing when the checkout is absent or already complete.
type Command ¶
type Command struct {
Label string
Dir string
Env []string
Args []string
// Reset runs after a failed attempt, before either another attempt or a
// terminal error return. It must only clean command-owned state.
Reset func() error
// Confirm may recognize that an operation succeeded despite an ambiguous
// transient error. A confirmation error does not replace the original Git
// error; the normal retry budget continues unless the context ended.
Confirm func(context.Context) (bool, error)
}
Command is one remote Git invocation plus operation-specific hooks.
type EnsureOptions ¶ added in v0.6.0
type EnsureOptions struct {
Full bool // Clone full history and unshallow an existing checkout.
RecurseSubmodules bool // Initialize and update submodules recursively at depth 1.
}
EnsureOptions configures an EnsureWithOptions operation.
type Retry ¶
type Retry struct {
Attempts int
BaseDelay time.Duration
MaxDelay time.Duration
Run Runner
Sleep func(context.Context, time.Duration) error
Notify func(Notice)
}
Retry bounds how a remote Git invocation is retried. Its zero value uses the default policy. Fields are exposed so callers can use a tighter budget or deterministic runners and sleepers in tests.
type Runner ¶
Runner runs one Git invocation and returns its combined output.
func RunnerWithWaitDelay ¶
RunnerWithWaitDelay returns a Runner with a bounded wait for transport children that retain Git's output pipe after Git itself exits.
type UnreachableError ¶
UnreachableError reports a clone or fetch failure for URL.
func (*UnreachableError) Error ¶
func (e *UnreachableError) Error() string
func (*UnreachableError) Unwrap ¶
func (e *UnreachableError) Unwrap() error