-
Notifications
You must be signed in to change notification settings - Fork 58
feat: add git submodule support #485
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Changes from 10 commits
81b6fd7
5de553d
adbdccf
18384d5
4d3e529
e183aff
2d1df11
5407a5b
463fd91
04f798b
db5e40d
223d3e4
5c59408
8134964
442477e
fb31cac
68ace4b
149ae9a
3f81838
ea25253
cb11759
76138b0
79d1fc5
92783ef
92f5137
6f87394
ad64adf
334ade4
e371318
afcce7f
b82aee0
d6ec3d5
f711af5
4d93f13
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -7,14 +7,17 @@ import ( | |
| "fmt" | ||
| "io" | ||
| "net" | ||
| "net/url" | ||
| "os" | ||
| "path" | ||
| "strings" | ||
|
|
||
| "github.com/coder/envbuilder/options" | ||
|
|
||
| giturls "github.com/chainguard-dev/git-urls" | ||
| "github.com/go-git/go-billy/v5" | ||
| "github.com/go-git/go-git/v5" | ||
| "github.com/go-git/go-git/v5/config" | ||
| "github.com/go-git/go-git/v5/plumbing" | ||
| "github.com/go-git/go-git/v5/plumbing/cache" | ||
| "github.com/go-git/go-git/v5/plumbing/protocol/packp/capability" | ||
|
|
@@ -41,6 +44,7 @@ type CloneRepoOptions struct { | |
| Depth int | ||
| CABundle []byte | ||
| ProxyOptions transport.ProxyOptions | ||
| Submodules bool | ||
| } | ||
|
|
||
| // CloneRepo will clone the repository at the given URL into the given path. | ||
|
|
@@ -119,7 +123,7 @@ func CloneRepo(ctx context.Context, logf func(string, ...any), opts CloneRepoOpt | |
| return false, nil | ||
| } | ||
|
|
||
| _, err = git.CloneContext(ctx, gitStorage, fs, &git.CloneOptions{ | ||
| repo, err = git.CloneContext(ctx, gitStorage, fs, &git.CloneOptions{ | ||
| URL: parsed.String(), | ||
| Auth: opts.RepoAuth, | ||
| Progress: opts.Progress, | ||
|
|
@@ -136,6 +140,15 @@ func CloneRepo(ctx context.Context, logf func(string, ...any), opts CloneRepoOpt | |
| if err != nil { | ||
| return false, fmt.Errorf("clone %q: %w", opts.RepoURL, err) | ||
| } | ||
|
|
||
|
mafredri marked this conversation as resolved.
|
||
| // Initialize submodules if requested | ||
| if opts.Submodules { | ||
| err = initSubmodules(ctx, logf, repo, opts) | ||
| if err != nil { | ||
| return true, fmt.Errorf("init submodules: %w", err) | ||
| } | ||
| } | ||
|
mafredri marked this conversation as resolved.
Outdated
mafredri marked this conversation as resolved.
Outdated
|
||
|
|
||
| return true, nil | ||
| } | ||
|
|
||
|
|
@@ -361,6 +374,7 @@ func CloneOptionsFromOptions(logf func(string, ...any), options options.Options) | |
| ThinPack: options.GitCloneThinPack, | ||
| Depth: int(options.GitCloneDepth), | ||
| CABundle: caBundle, | ||
| Submodules: options.GitCloneSubmodules, | ||
| } | ||
|
|
||
| cloneOpts.RepoAuth = SetupRepoAuth(logf, &options) | ||
|
|
@@ -418,3 +432,271 @@ func ProgressWriter(write func(line string, args ...any)) io.WriteCloser { | |
| done: done, | ||
| } | ||
| } | ||
|
|
||
| // resolveSubmoduleURL resolves a potentially relative submodule URL against the parent repository URL | ||
|
mafredri marked this conversation as resolved.
Outdated
|
||
| // ResolveSubmoduleURLForTest is exported for testing resolveSubmoduleURL logic | ||
| func ResolveSubmoduleURLForTest(parentURL, submoduleURL string) (string, error) { | ||
|
mafredri marked this conversation as resolved.
Outdated
|
||
| // If the submodule URL is absolute (contains ://) or doesn't start with ./ or ../, return it as-is | ||
| if strings.Contains(submoduleURL, "://") || (!strings.HasPrefix(submoduleURL, "../") && !strings.HasPrefix(submoduleURL, "./")) { | ||
| return submoduleURL, nil | ||
| } | ||
|
|
||
| // Parse the parent URL | ||
| parentParsed, err := url.Parse(parentURL) | ||
|
mafredri marked this conversation as resolved.
Outdated
|
||
| if err != nil { | ||
| return "", fmt.Errorf("parse parent URL: %w", err) | ||
| } | ||
|
|
||
| // For relative URLs, we need to resolve them against the parent's path | ||
| // The parent path represents a repository (like a file in filesystem terms) | ||
| // So ../something means "sibling repository" | ||
| parentPath := strings.TrimSuffix(parentParsed.Path, "/") | ||
|
|
||
| // Split the submodule URL into components | ||
| // and manually walk up the directory tree for each ../ | ||
| currentPath := parentPath | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. P3 [ENVB-9] The code starts resolution at the full parent path ( The discrepancy primarily affects HTTPS-format parent URLs with relative submodule references. For SCP-format remotes, go-git's endpoint normalization coincidentally compensates. Since
|
||
| relativeParts := strings.Split(submoduleURL, "/") | ||
|
|
||
| for _, part := range relativeParts { | ||
| if part == ".." { | ||
| // Go up one directory | ||
| currentPath = path.Dir(currentPath) | ||
| } else if part == "." { | ||
|
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. P2 [DEREM-2] The Git's behavior: both Fix: before the loop, set The test
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Verified against native git that go-git uses the same rule ( Closing as not a bug; happy to revisit if you have a reproducer showing a different behavior from upstream git.
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. P2 [ENVB-5] The Trace for Result: Both RFC 3986 and git's native The test expectations for
|
||
| // Stay in current directory | ||
| continue | ||
| } else if part != "" { | ||
| // Add this component to the path | ||
| currentPath = currentPath + "/" + part | ||
| } | ||
| } | ||
|
|
||
| // Clean the final path | ||
| resolvedPath := path.Clean(currentPath) | ||
|
|
||
| // Construct the absolute URL | ||
| resolvedParsed := &url.URL{ | ||
| Scheme: parentParsed.Scheme, | ||
| User: parentParsed.User, | ||
| Host: parentParsed.Host, | ||
| Path: resolvedPath, | ||
| } | ||
|
|
||
| return resolvedParsed.String(), nil | ||
| } | ||
|
|
||
| // initSubmodules recursively initializes and updates all submodules in the repository. | ||
| func initSubmodules(ctx context.Context, logf func(string, ...any), repo *git.Repository, opts CloneRepoOptions) error { | ||
|
mafredri marked this conversation as resolved.
Outdated
|
||
| logf("🔗 Initializing git submodules...") | ||
|
|
||
| w, err := repo.Worktree() | ||
| if err != nil { | ||
| return fmt.Errorf("get worktree: %w", err) | ||
| } | ||
|
|
||
| subs, err := w.Submodules() | ||
| if err != nil { | ||
| return fmt.Errorf("get submodules: %w", err) | ||
| } | ||
|
|
||
| if len(subs) == 0 { | ||
| logf("No submodules found") | ||
| return nil | ||
| } | ||
|
|
||
| logf("Found %d submodule(s)", len(subs)) | ||
|
|
||
| // Get the parent repository URL for resolving relative submodule URLs | ||
| cfg, err := repo.Config() | ||
| if err != nil { | ||
| return fmt.Errorf("get repo config: %w", err) | ||
| } | ||
|
|
||
| parentURL := opts.RepoURL | ||
| if origin, hasOrigin := cfg.Remotes["origin"]; hasOrigin && len(origin.URLs) > 0 { | ||
| parentURL = origin.URLs[0] | ||
| } | ||
| logf("Parent repository URL: %s", parentURL) | ||
|
mafredri marked this conversation as resolved.
Outdated
|
||
|
|
||
| for _, sub := range subs { | ||
|
mafredri marked this conversation as resolved.
|
||
| subConfig := sub.Config() | ||
| logf("📦 Initializing submodule: %s", subConfig.Name) | ||
| logf(" Submodule path: %s", subConfig.Path) | ||
| logf(" Submodule URL (from .gitmodules): %s", subConfig.URL) | ||
|
|
||
| // Get the expected commit hash | ||
| subStatus, err := sub.Status() | ||
| if err != nil { | ||
| return fmt.Errorf("get submodule status for %q: %w", subConfig.Name, err) | ||
| } | ||
| logf(" Expected commit: %s", subStatus.Expected) | ||
|
|
||
| // Resolve the submodule URL | ||
| resolvedURL, err := ResolveSubmoduleURLForTest(parentURL, subConfig.URL) | ||
| if err != nil { | ||
| return fmt.Errorf("resolve submodule URL for %q: %w", subConfig.Name, err) | ||
| } | ||
| logf(" Resolved URL: %s", resolvedURL) | ||
|
|
||
| // Clone the submodule manually | ||
| err = cloneSubmodule(ctx, logf, w, subConfig, subStatus.Expected, resolvedURL, opts) | ||
| if err != nil { | ||
| return fmt.Errorf("clone submodule %q: %w", subConfig.Name, err) | ||
| } | ||
|
|
||
| logf("✓ Submodule initialized: %s", subConfig.Name) | ||
|
|
||
| // Recursively handle nested submodules | ||
| subRepo, err := sub.Repository() | ||
|
mafredri marked this conversation as resolved.
Outdated
|
||
| if err != nil { | ||
| logf(" ⚠ Could not open submodule repository %s: %v", subConfig.Name, err) | ||
| continue | ||
| } | ||
|
|
||
| // Check for nested submodules | ||
| subWorktree, err := subRepo.Worktree() | ||
| if err == nil { | ||
|
mafredri marked this conversation as resolved.
Outdated
|
||
| nestedSubs, err := subWorktree.Submodules() | ||
| if err == nil && len(nestedSubs) > 0 { | ||
| logf(" Found %d nested submodule(s) in %s", len(nestedSubs), subConfig.Name) | ||
| // Create new opts with the submodule's URL as the parent | ||
| nestedOpts := opts | ||
|
mafredri marked this conversation as resolved.
Outdated
|
||
| nestedOpts.RepoURL = resolvedURL | ||
| err = initSubmodules(ctx, logf, subRepo, nestedOpts) | ||
| if err != nil { | ||
| return fmt.Errorf("init nested submodules in %q: %w", subConfig.Name, err) | ||
| } | ||
| } | ||
| } | ||
| } | ||
|
|
||
| logf("✓ All submodules initialized successfully") | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. P3 [ENVB-11] When Track whether any warnings were emitted and adjust the final message. (Chopper)
|
||
| return nil | ||
| } | ||
|
|
||
| // cloneSubmodule manually clones a submodule repository | ||
| func cloneSubmodule(ctx context.Context, logf func(string, ...any), parentWorktree *git.Worktree, subConfig *config.Submodule, expectedHash plumbing.Hash, resolvedURL string, opts CloneRepoOptions) error { | ||
| // Get the submodule directory within the parent worktree | ||
| submodulePath := subConfig.Path | ||
|
|
||
| // Create the submodule directory | ||
| subFS, err := parentWorktree.Filesystem.Chroot(submodulePath) | ||
| if err != nil { | ||
| return fmt.Errorf("chroot to submodule path: %w", err) | ||
| } | ||
|
|
||
| // Check if already cloned | ||
| _, err = subFS.Stat(".git") | ||
| if err == nil { | ||
| logf(" Submodule already cloned, checking out expected commit...") | ||
| // Open the existing repository | ||
| subRepo, err := git.Open( | ||
|
mafredri marked this conversation as resolved.
|
||
| filesystem.NewStorage(subFS, cache.NewObjectLRU(cache.DefaultMaxSize)), | ||
| subFS, | ||
| ) | ||
| if err != nil { | ||
| return fmt.Errorf("open existing submodule: %w", err) | ||
| } | ||
|
|
||
| subWorktree, err := subRepo.Worktree() | ||
| if err != nil { | ||
| return fmt.Errorf("get submodule worktree: %w", err) | ||
| } | ||
|
|
||
| // Checkout the expected commit | ||
| err = subWorktree.Checkout(&git.CheckoutOptions{ | ||
| Hash: expectedHash, | ||
| }) | ||
| if err != nil { | ||
| return fmt.Errorf("checkout expected commit: %w", err) | ||
|
mafredri marked this conversation as resolved.
Outdated
|
||
| } | ||
| return nil | ||
| } | ||
|
|
||
| // Clone the submodule | ||
| logf(" Cloning submodule from: %s", resolvedURL) | ||
|
|
||
| // Create .git directory for the submodule | ||
| err = subFS.MkdirAll(".git", 0o755) | ||
| if err != nil { | ||
| return fmt.Errorf("create .git directory: %w", err) | ||
| } | ||
|
|
||
| subGitDir, err := subFS.Chroot(".git") | ||
| if err != nil { | ||
| return fmt.Errorf("chroot to .git: %w", err) | ||
| } | ||
|
|
||
| gitStorage := filesystem.NewStorage(subGitDir, cache.NewObjectLRU(cache.DefaultMaxSize*10)) | ||
|
|
||
| // Clone the submodule repository | ||
| // Use SingleBranch=false to fetch all branches so we can find the commit | ||
| subRepo, err := git.CloneContext(ctx, gitStorage, subFS, &git.CloneOptions{ | ||
|
mafredri marked this conversation as resolved.
|
||
| URL: resolvedURL, | ||
| Auth: opts.RepoAuth, | ||
|
mafredri marked this conversation as resolved.
Outdated
|
||
| Progress: opts.Progress, | ||
| InsecureSkipTLS: opts.Insecure, | ||
| CABundle: opts.CABundle, | ||
| ProxyOptions: opts.ProxyOptions, | ||
| SingleBranch: false, // Fetch all branches | ||
| NoCheckout: true, // Don't checkout yet, we'll do it manually | ||
| }) | ||
| if err != nil && !errors.Is(err, git.ErrRepositoryAlreadyExists) { | ||
|
mafredri marked this conversation as resolved.
Outdated
|
||
| return fmt.Errorf("clone submodule repository: %w", err) | ||
| } | ||
|
|
||
| // Verify the commit exists | ||
| logf(" Verifying commit exists: %s", expectedHash) | ||
| _, err = subRepo.CommitObject(expectedHash) | ||
| if err != nil { | ||
| // Commit not found, try fetching with the specific hash | ||
| logf(" Commit not found, attempting to fetch it directly...") | ||
| err = subRepo.FetchContext(ctx, &git.FetchOptions{ | ||
| RemoteName: "origin", | ||
| RefSpecs: []config.RefSpec{ | ||
| config.RefSpec("+" + expectedHash.String() + ":" + expectedHash.String()), | ||
| }, | ||
| Auth: opts.RepoAuth, | ||
| Progress: opts.Progress, | ||
| InsecureSkipTLS: opts.Insecure, | ||
| CABundle: opts.CABundle, | ||
| ProxyOptions: opts.ProxyOptions, | ||
| }) | ||
| if err != nil && err != git.NoErrAlreadyUpToDate { | ||
|
mafredri marked this conversation as resolved.
Outdated
|
||
| // If that fails, try fetching all refs | ||
| logf(" Direct fetch failed, fetching all refs...") | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. P3 [ENVB-10] Fix:
|
||
| err = subRepo.FetchContext(ctx, &git.FetchOptions{ | ||
| RemoteName: "origin", | ||
| Auth: opts.RepoAuth, | ||
| Progress: opts.Progress, | ||
| InsecureSkipTLS: opts.Insecure, | ||
| CABundle: opts.CABundle, | ||
| ProxyOptions: opts.ProxyOptions, | ||
| }) | ||
| if err != nil && err != git.NoErrAlreadyUpToDate { | ||
| return fmt.Errorf("fetch commit %s: %w", expectedHash, err) | ||
| } | ||
| } | ||
|
|
||
| // Verify again | ||
| _, err = subRepo.CommitObject(expectedHash) | ||
| if err != nil { | ||
| return fmt.Errorf("commit %s still not found after fetch: %w", expectedHash, err) | ||
| } | ||
| } | ||
|
|
||
| // Checkout the specific commit expected by the parent repository | ||
| logf(" Checking out commit: %s", expectedHash) | ||
| subWorktree, err := subRepo.Worktree() | ||
| if err != nil { | ||
| return fmt.Errorf("get submodule worktree: %w", err) | ||
| } | ||
|
|
||
| err = subWorktree.Checkout(&git.CheckoutOptions{ | ||
| Hash: expectedHash, | ||
| }) | ||
| if err != nil { | ||
| return fmt.Errorf("checkout expected commit %s: %w", expectedHash, err) | ||
| } | ||
|
|
||
| return nil | ||
| } | ||
Uh oh!
There was an error while loading. Please reload this page.