Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 13 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -26,11 +26,21 @@ fmt.Println(clone.Head(ctx, dst))

Pass `true` as the final argument for a full clone, including when an existing shallow checkout needs to be unshallowed. Clone and fetch errors are returned as `*clone.UnreachableError`, except when the context was canceled or reached its deadline. `errors.As` retrieves the URL and underlying Git error. `ValidateURL` accepts `https://` URLs, while `ValidateRef` rejects leading hyphens, `..`, and characters outside letters, digits, `.`, `_`, `/`, and `-`.

Use `EnsureWithOptions` to include submodules. Submodules are initialized and updated recursively with depth 1 after both a new clone and an existing checkout update. This step is best-effort because submodules may be large or refer to unavailable URLs; failures leave the parent checkout usable. Context cancellation is still returned. Recursion is bounded: submodules are fetched one nesting level at a time, at most 8 levels deep and 256 submodules in total. When fetching a repository's submodules would exceed either limit, the submodule step stops before fetching them; submodules already fetched are kept and `Submodules` reports the rest as unavailable. Submodule URLs come from the cloned repository's `.gitmodules`, so submodules are fetched with the ambient credential helper disabled. Other ambient Git credentials are not disabled: an unscoped `http.extraHeader`, `GIT_ASKPASS` or `core.askPass` can still authenticate a repository-chosen submodule URL. Callers that fetch untrusted repositories with `RecurseSubmodules` should scope those credentials to trusted URLs or remove them. Callers that need authenticated submodules can supply credentials through the environment.
Use `EnsureWithOptions` to include submodules. Submodules are initialized and updated recursively with depth 1 after both a new clone and an existing checkout update. This step is best-effort because submodules may be large or refer to unavailable URLs; failures leave the parent checkout usable. Context cancellation is still returned. Recursion is bounded: submodules are fetched one nesting level at a time, at most 8 levels deep and 256 submodules in total. When fetching a repository's submodules would exceed either limit, the submodule step stops before fetching them; submodules already fetched are kept and `Submodules` reports the rest as unavailable. Submodule URLs come from the cloned repository's `.gitmodules`, so submodules are fetched with the ambient credential helper disabled. Other ambient Git credentials are not disabled: an unscoped `http.extraHeader`, `GIT_ASKPASS` or `core.askPass` can still authenticate a repository-chosen submodule URL. Callers that fetch untrusted repositories with `RecurseSubmodules` should scope those credentials to trusted URLs or remove them.

To fetch private submodules, list trusted URL prefixes in `SubmoduleCredentialURLs`. A submodule whose resolved URL is under one of them is fetched with the ambient credential helper; prefixes match on path segment boundaries, so `https://github.com/my-org` covers `https://github.com/my-org/lib.git` but not `https://github.com/my-org-two/lib.git`. Any repository can name a trusted URL in its `.gitmodules`, so every repository the helper can read under those prefixes may end up in a checkout of an untrusted repository. Prefixes must be `https://` with no userinfo, query, fragment or dot segments; `ValidateSubmoduleCredentialURLs` checks a list up front. The prefix is matched against the URL in `.gitmodules`, before Git applies `url.<base>.insteadOf`, so the caller's own rewrites of a trusted prefix also receive credentials.

Set `OnSubmoduleIssue` to learn which submodules are missing. It is called once per submodule with its path relative to `dst`, its credential-free URL, a reason (`SubmoduleIssueFetchFailed`, `SubmoduleIssueDepthLimit` or `SubmoduleIssueModuleLimit`) and, for a failed fetch, Git's output with URL userinfo redacted. Submodules nested beneath a skipped one are not reported.

```go
err := clone.EnsureWithOptions(ctx, clone.Retry{}, url, dst, "main",
clone.EnsureOptions{RecurseSubmodules: true},
clone.EnsureOptions{
RecurseSubmodules: true,
SubmoduleCredentialURLs: []string{"https://github.com/my-org"},
OnSubmoduleIssue: func(issue clone.SubmoduleIssue) {
log.Printf("submodule %s %s: %s", issue.Path, issue.Reason, issue.Output)
},
},
)
if err != nil {
log.Fatal(err)
Expand Down Expand Up @@ -61,7 +71,7 @@ an invalid tag or another local repository error. `CheckoutTag` does not fetch.

## Persistent cache

`Cache` stores one checkout per URL under `Root`. `Prepare` holds a per-URL lock while updating the shallow checkout, then replaces `dst` with a copy and returns its commit. The destination must be outside `Root`. Set `RecurseSubmodules` to copy best-effort shallow submodule checkouts into each destination.
`Cache` stores one checkout per URL under `Root`. `Prepare` holds a per-URL lock while updating the shallow checkout, then replaces `dst` with a copy and returns its commit. The destination must be outside `Root`. Set `RecurseSubmodules` to copy best-effort shallow submodule checkouts into each destination; `SubmoduleCredentialURLs` and `OnSubmoduleIssue` behave as in `EnsureOptions`.

```go
cache := clone.Cache{
Expand Down
12 changes: 10 additions & 2 deletions cache.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,11 @@ 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.
mu sync.Map
// SubmoduleCredentialURLs and OnSubmoduleIssue are passed to
// EnsureWithOptions; see EnsureOptions.
SubmoduleCredentialURLs []string
OnSubmoduleIssue func(SubmoduleIssue)
mu sync.Map
}

// Dir returns the persistent directory for url under c.Root.
Expand Down Expand Up @@ -45,7 +49,11 @@ func (c *Cache) Prepare(ctx context.Context, url, ref, dst string) (string, erro
return "", err
}
cacheSrc := filepath.Join(cacheDir, "src")
options := EnsureOptions{RecurseSubmodules: c.RecurseSubmodules}
options := EnsureOptions{
RecurseSubmodules: c.RecurseSubmodules,
SubmoduleCredentialURLs: c.SubmoduleCredentialURLs,
OnSubmoduleIssue: c.OnSubmoduleIssue,
}
if err := EnsureWithOptions(ctx, c.Retry, url, cacheSrc, ref, options); err != nil {
return "", err
}
Expand Down
170 changes: 122 additions & 48 deletions ensure.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"fmt"
"os"
"path/filepath"
"slices"
"sort"
"strings"
)
Expand All @@ -30,6 +31,13 @@ func (e *UnreachableError) Unwrap() error {
type EnsureOptions struct {
Full bool // Clone full history and unshallow an existing checkout.
RecurseSubmodules bool // Initialize and update submodules recursively at depth 1.
// SubmoduleCredentialURLs lists https URL prefixes, matched on path
// segment boundaries, whose submodules are fetched with the ambient
// credential helper. All other submodules are fetched without it.
SubmoduleCredentialURLs []string
// OnSubmoduleIssue, when set, is called for each submodule left out of
// the checkout.
OnSubmoduleIssue func(SubmoduleIssue)
}

// Ensure clones url into dst on its first call, then fetches and resets the
Expand Down Expand Up @@ -62,11 +70,20 @@ func ensure(ctx context.Context, retry Retry, url, dst, ref string, options Ensu
if err := ValidateRef(ref); err != nil {
return err
}
trusted, err := parseCredentialPrefixes(options.SubmoduleCredentialURLs)
if err != nil {
return err
}
update := submoduleUpdate{
budget: submoduleBudget{maxDepth: maxSubmoduleDepth, maxModules: maxSubmodules},
trusted: trusted,
onIssue: options.OnSubmoduleIssue,
}
if _, err := os.Stat(filepath.Join(dst, ".git")); err == nil {
if err := fetchRef(ctx, retry, url, dst, ref, options.Full); err != nil {
return err
}
return updateSubmodules(ctx, retry, dst, options.RecurseSubmodules)
return updateSubmodules(ctx, retry, dst, options.RecurseSubmodules, update)
}
if err := os.MkdirAll(filepath.Dir(dst), dirPerm); err != nil {
return err
Expand Down Expand Up @@ -97,7 +114,7 @@ func ensure(ctx context.Context, retry Retry, url, dst, ref string, options Ensu
return err
}
}
return updateSubmodules(ctx, retry, dst, options.RecurseSubmodules)
return updateSubmodules(ctx, retry, dst, options.RecurseSubmodules, update)
}

// Limits on recursive submodule updates, so nested or repeated gitlinks in a
Expand All @@ -112,35 +129,28 @@ type submoduleBudget struct {
maxModules int
}

// updateSubmodules fetches dst's submodules within the default limits when enabled.
func updateSubmodules(ctx context.Context, retry Retry, dst string, enabled bool) error {
// updateSubmodules fetches dst's submodules when enabled.
func updateSubmodules(ctx context.Context, retry Retry, dst string, enabled bool, update submoduleUpdate) error {
if !enabled {
return nil
}
return updateSubmodulesWithin(ctx, retry, dst, submoduleBudget{
maxDepth: maxSubmoduleDepth,
maxModules: maxSubmodules,
})
return updateSubmodulesWithin(ctx, retry, dst, update)
}

// updateSubmodulesWithin walks submodules breadth first, one repository's
// submodules per Git call. Each batch is counted before it is fetched, and the
// walk stops before exceeding the budget, keeping what was already fetched.
// Like git's own --recursive, it descends only into submodules checked out at
// their gitlink. Only context errors are returned.
func updateSubmodulesWithin(ctx context.Context, retry Retry, dst string, budget submoduleBudget) error {
type pending struct {
dir string
depth int // depth of the submodules declared in dir
}
func updateSubmodulesWithin(ctx context.Context, retry Retry, dst string, update submoduleUpdate) error {
policy := retry.Resolved()
queue := []pending{{dir: dst, depth: 1}}
queue := []pendingSubmodules{{dir: dst, depth: 1}}
fetched := 0
for len(queue) > 0 {
current := queue[0]
queue = queue[1:]
if current.depth > budget.maxDepth {
return nil
if current.depth > update.budget.maxDepth {
return update.reportPending(ctx, policy, append([]pendingSubmodules{current}, queue...), SubmoduleIssueDepthLimit)
}
links, err := submoduleGitlinks(ctx, policy, current.dir)
if err != nil {
Expand All @@ -149,15 +159,15 @@ func updateSubmodulesWithin(ctx context.Context, retry Retry, dst string, budget
if len(links) == 0 {
continue
}
if fetched+len(links) > budget.maxModules {
return nil
if fetched+len(links) > update.budget.maxModules {
if err := update.reportSkipped(ctx, policy, current, links, SubmoduleIssueModuleLimit); err != nil {
return err
}
return update.reportPending(ctx, policy, queue, SubmoduleIssueModuleLimit)
}
fetched += len(links)
paths := make([]string, len(links))
for i, link := range links {
paths[i] = link.path
}
if err := updateSubmoduleLevel(ctx, policy, current.dir, paths); err != nil {
outputs, err := updateSubmoduleLevel(ctx, policy, current.dir, links, update.trusted)
if err != nil {
return err
}
for _, link := range links {
Expand All @@ -167,42 +177,94 @@ func updateSubmodulesWithin(ctx context.Context, retry Retry, dst string, budget
return err
}
if ok {
queue = append(queue, pending{dir: child, depth: current.depth + 1})
queue = append(queue, pendingSubmodules{
dir: child,
prefix: joinSlash(current.prefix, link.path),
depth: current.depth + 1,
})
continue
}
update.reportLinks(ctx, policy, current, []gitlink{link}, SubmoduleIssueFetchFailed, outputs[link.path])
}
}
return nil
// Issue URL lookups swallow their own errors, so a cancellation during
// the last report surfaces here.
return ctx.Err()
}

// updateSubmoduleLevel syncs and updates exactly the given submodules of dir.
// Submodule URLs come from the cloned .gitmodules, so the ambient credential
// helper is disabled. Literal pathspecs keep a path from matching more
// submodules than were counted.
func updateSubmoduleLevel(ctx context.Context, policy Retry, dir string, paths []string) error {
// updateSubmoduleLevel syncs and updates exactly the given submodules of dir,
// returning the update output for each path. Submodule URLs come from the
// cloned .gitmodules, so the ambient credential helper is disabled except for
// URLs under a trusted prefix. Literal pathspecs keep a path from matching
// more submodules than were counted.
func updateSubmoduleLevel(ctx context.Context, policy Retry, dir string, links []gitlink, trusted []credentialPrefix) (map[string]string, error) {
env := append(remoteEnv(), "GIT_LITERAL_PATHSPECS=1")
syncArgs := append([]string{"-c", "credential.helper=", "submodule", "sync", "--"}, paths...)
paths := make([]string, len(links))
for i, link := range links {
paths[i] = link.path
}
noHelper := []string{"-c", "credential.helper="}
syncArgs := slices.Concat(noHelper, []string{"submodule", "sync", "--"}, paths)
if _, err := policy.Run(ctx, dir, env, longPathArgs(syncArgs...)...); err != nil {
if ctxErr := ctx.Err(); ctxErr != nil {
return ctxErr
return nil, ctxErr
}
}
updateArgs := append([]string{"-c", "credential.helper=", "submodule", "update", "--init", "--depth", "1", "--"}, paths...)
if _, err := policy.Do(ctx, Command{
Label: "submodule",
Dir: dir,
Env: env,
Args: longPathArgs(updateArgs...),
}); err != nil {
if ctxErr := ctx.Err(); ctxErr != nil {
return ctxErr

anonymous, authenticated := paths, []string(nil)
if len(trusted) > 0 {
// init resolves relative URLs into .git/config without fetching, so
// the URL matched here is the one update will fetch.
initArgs := append([]string{"submodule", "init", "--"}, paths...)
if _, err := policy.Run(ctx, dir, env, longPathArgs(initArgs...)...); err != nil {
if ctxErr := ctx.Err(); ctxErr != nil {
return nil, ctxErr
}
}
anonymous = nil
for _, link := range links {
if !link.ambiguous && credentialAllowed(trusted, submoduleURLConfig(ctx, policy, dir, link.name)) {
authenticated = append(authenticated, link.path)
} else {
anonymous = append(anonymous, link.path)
}
}
}
return nil

outputs := make(map[string]string, len(paths))
for _, batch := range []struct {
paths []string
config []string
}{{anonymous, noHelper}, {authenticated, nil}} {
if len(batch.paths) == 0 {
continue
}
args := slices.Concat(batch.config, []string{"submodule", "update", "--init", "--depth", "1", "--"}, batch.paths)
out, err := policy.Do(ctx, Command{
Label: "submodule",
Dir: dir,
Env: env,
Args: longPathArgs(args...),
})
if err != nil {
if ctxErr := ctx.Err(); ctxErr != nil {
return nil, ctxErr
}
}
for _, p := range batch.paths {
outputs[p] = out
}
}
return outputs, nil
}

type gitlink struct {
name string
path string
commit string
// ambiguous is set when .gitmodules gives path more than one name. Git
// registers the last, so name may not be the submodule Git fetches.
ambiguous bool
}

// submoduleGitlinks returns the paths that dir's .gitmodules declares and HEAD
Expand All @@ -215,18 +277,26 @@ func submoduleGitlinks(ctx context.Context, policy Retry, dir string) ([]gitlink
if err != nil {
return nil, ctx.Err()
}
declared := map[string]bool{}
declared := map[string]string{} // path to submodule name
ambiguous := map[string]bool{}
var candidates []string
for entry := range strings.SplitSeq(strings.TrimSuffix(out, "\x00"), "\x00") {
_, value, ok := strings.Cut(entry, "\n")
key, value, ok := strings.Cut(entry, "\n")
if !ok {
continue
}
submodulePath, ok := SanitizePath(value)
if !ok || declared[submodulePath] {
if !ok {
continue
}
name := strings.TrimSuffix(strings.TrimPrefix(key, "submodule."), ".path")
if prior, seen := declared[submodulePath]; seen {
if prior != name {
ambiguous[submodulePath] = true
}
continue
}
declared[submodulePath] = true
declared[submodulePath] = name
candidates = append(candidates, submodulePath)
}
if len(candidates) == 0 {
Expand All @@ -241,12 +311,16 @@ func submoduleGitlinks(ctx context.Context, policy Retry, dir string) ([]gitlink
var links []gitlink
for entry := range strings.SplitSeq(strings.TrimSuffix(out, "\x00"), "\x00") {
metadata, treePath, ok := strings.Cut(entry, "\t")
if !ok || !declared[treePath] {
if !ok {
continue
}
name, ok := declared[treePath]
if !ok {
continue
}
fields := strings.Fields(metadata)
if len(fields) == 3 && fields[0] == "160000" && fields[1] == "commit" && ValidCommit(fields[2]) {
links = append(links, gitlink{path: treePath, commit: fields[2]})
links = append(links, gitlink{name: name, path: treePath, commit: fields[2], ambiguous: ambiguous[treePath]})
}
}
sort.Slice(links, func(i, j int) bool {
Expand Down
Loading
Loading