Skip to content

Commit 00ca53c

Browse files
authored
Merge pull request #327 from fluxcd/fetch-submodules
Add support for Git submodules with go-git
2 parents 5486321 + 681ddd5 commit 00ca53c

11 files changed

+274
-29
lines changed

api/v1beta1/gitrepository_types.go

+6
Original file line numberDiff line numberDiff line change
@@ -81,6 +81,12 @@ type GitRepositorySpec struct {
8181
// +kubebuilder:default:=go-git
8282
// +optional
8383
GitImplementation string `json:"gitImplementation,omitempty"`
84+
85+
// When enabled, after the clone is created, initializes all submodules within,
86+
// using their default settings.
87+
// This option is available only when using the 'go-git' GitImplementation.
88+
// +optional
89+
RecurseSubmodules bool `json:"recurseSubmodules,omitempty"`
8490
}
8591

8692
// GitRepositoryRef defines the Git ref used for pull and checkout operations.

config/crd/bases/source.toolkit.fluxcd.io_gitrepositories.yaml

+5
Original file line numberDiff line numberDiff line change
@@ -66,6 +66,11 @@ spec:
6666
interval:
6767
description: The interval at which to check for repository updates.
6868
type: string
69+
recurseSubmodules:
70+
description: When enabled, after the clone is created, initializes
71+
all submodules within, using their default settings. This option
72+
is available only when using the 'go-git' GitImplementation.
73+
type: boolean
6974
ref:
7075
description: The Git reference to checkout and monitor for changes,
7176
defaults to master branch.

controllers/gitrepository_controller.go

+12-2
Original file line numberDiff line numberDiff line change
@@ -183,7 +183,12 @@ func (r *GitRepositoryReconciler) reconcile(ctx context.Context, repository sour
183183
// determine auth method
184184
auth := &git.Auth{}
185185
if repository.Spec.SecretRef != nil {
186-
authStrategy, err := strategy.AuthSecretStrategyForURL(repository.Spec.URL, repository.Spec.GitImplementation)
186+
authStrategy, err := strategy.AuthSecretStrategyForURL(
187+
repository.Spec.URL,
188+
git.CheckoutOptions{
189+
GitImplementation: repository.Spec.GitImplementation,
190+
RecurseSubmodules: repository.Spec.RecurseSubmodules,
191+
})
187192
if err != nil {
188193
return sourcev1.GitRepositoryNotReady(repository, sourcev1.AuthenticationFailedReason, err.Error()), err
189194
}
@@ -207,7 +212,12 @@ func (r *GitRepositoryReconciler) reconcile(ctx context.Context, repository sour
207212
}
208213
}
209214

210-
checkoutStrategy, err := strategy.CheckoutStrategyForRef(repository.Spec.Reference, repository.Spec.GitImplementation)
215+
checkoutStrategy, err := strategy.CheckoutStrategyForRef(
216+
repository.Spec.Reference,
217+
git.CheckoutOptions{
218+
GitImplementation: repository.Spec.GitImplementation,
219+
RecurseSubmodules: repository.Spec.RecurseSubmodules,
220+
})
211221
if err != nil {
212222
return sourcev1.GitRepositoryNotReady(repository, sourcev1.GitOperationFailedReason, err.Error()), err
213223
}

controllers/gitrepository_controller_test.go

+137-3
Original file line numberDiff line numberDiff line change
@@ -20,10 +20,13 @@ import (
2020
"context"
2121
"crypto/tls"
2222
"fmt"
23+
"io/ioutil"
2324
"net/http"
2425
"net/url"
2526
"os"
27+
"os/exec"
2628
"path"
29+
"path/filepath"
2730
"strings"
2831
"time"
2932

@@ -42,9 +45,10 @@ import (
4245
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
4346
"k8s.io/apimachinery/pkg/types"
4447

48+
"github.com/fluxcd/pkg/apis/meta"
4549
"github.com/fluxcd/pkg/gittestserver"
50+
"github.com/fluxcd/pkg/untar"
4651

47-
"github.com/fluxcd/pkg/apis/meta"
4852
sourcev1 "github.com/fluxcd/source-controller/api/v1beta1"
4953
)
5054

@@ -136,8 +140,6 @@ var _ = Describe("GitRepositoryReconciler", func() {
136140
}})
137141
Expect(err).NotTo(HaveOccurred())
138142

139-
gitrepo.Worktree()
140-
141143
for _, ref := range t.createRefs {
142144
hRef := plumbing.NewHashReference(plumbing.ReferenceName(ref), commit)
143145
err = gitrepo.Storer.SetReference(hRef)
@@ -410,5 +412,137 @@ var _ = Describe("GitRepositoryReconciler", func() {
410412
gitImplementation: sourcev1.GoGitImplementation,
411413
}),
412414
)
415+
416+
Context("recurse submodules", func() {
417+
It("downloads submodules when asked", func() {
418+
Expect(gitServer.StartHTTP()).To(Succeed())
419+
defer gitServer.StopHTTP()
420+
421+
u, err := url.Parse(gitServer.HTTPAddress())
422+
Expect(err).NotTo(HaveOccurred())
423+
424+
subRepoURL := *u
425+
subRepoURL.Path = path.Join(u.Path, fmt.Sprintf("subrepository-%s.git", randStringRunes(5)))
426+
427+
// create the git repo to use as a submodule
428+
fs := memfs.New()
429+
subRepo, err := git.Init(memory.NewStorage(), fs)
430+
Expect(err).NotTo(HaveOccurred())
431+
432+
wt, err := subRepo.Worktree()
433+
Expect(err).NotTo(HaveOccurred())
434+
435+
ff, _ := fs.Create("fixture")
436+
_ = ff.Close()
437+
_, err = wt.Add(fs.Join("fixture"))
438+
Expect(err).NotTo(HaveOccurred())
439+
440+
_, err = wt.Commit("Sample", &git.CommitOptions{Author: &object.Signature{
441+
Name: "John Doe",
442+
Email: "john@example.com",
443+
When: time.Now(),
444+
}})
445+
Expect(err).NotTo(HaveOccurred())
446+
447+
remote, err := subRepo.CreateRemote(&config.RemoteConfig{
448+
Name: "origin",
449+
URLs: []string{subRepoURL.String()},
450+
})
451+
Expect(err).NotTo(HaveOccurred())
452+
453+
err = remote.Push(&git.PushOptions{
454+
RefSpecs: []config.RefSpec{"refs/heads/*:refs/heads/*", "refs/tags/*:refs/tags/*"},
455+
})
456+
Expect(err).NotTo(HaveOccurred())
457+
458+
// this one is linked to a real directory, so that I can
459+
// exec `git submodule add` later
460+
tmp, err := ioutil.TempDir("", "flux-test")
461+
Expect(err).NotTo(HaveOccurred())
462+
defer os.RemoveAll(tmp)
463+
464+
repoDir := filepath.Join(tmp, "git")
465+
repo, err := git.PlainInit(repoDir, false)
466+
Expect(err).NotTo(HaveOccurred())
467+
468+
wt, err = repo.Worktree()
469+
Expect(err).NotTo(HaveOccurred())
470+
_, err = wt.Commit("Initial revision", &git.CommitOptions{
471+
Author: &object.Signature{
472+
Name: "John Doe",
473+
Email: "john@example.com",
474+
When: time.Now(),
475+
}})
476+
Expect(err).NotTo(HaveOccurred())
477+
478+
submodAdd := exec.Command("git", "submodule", "add", "-b", "master", subRepoURL.String(), "sub")
479+
submodAdd.Dir = repoDir
480+
out, err := submodAdd.CombinedOutput()
481+
os.Stdout.Write(out)
482+
Expect(err).NotTo(HaveOccurred())
483+
484+
_, err = wt.Commit("Add submodule", &git.CommitOptions{
485+
Author: &object.Signature{
486+
Name: "John Doe",
487+
Email: "john@example.com",
488+
When: time.Now(),
489+
}})
490+
Expect(err).NotTo(HaveOccurred())
491+
492+
mainRepoURL := *u
493+
mainRepoURL.Path = path.Join(u.Path, fmt.Sprintf("repository-%s.git", randStringRunes(5)))
494+
remote, err = repo.CreateRemote(&config.RemoteConfig{
495+
Name: "origin",
496+
URLs: []string{mainRepoURL.String()},
497+
})
498+
Expect(err).NotTo(HaveOccurred())
499+
500+
err = remote.Push(&git.PushOptions{
501+
RefSpecs: []config.RefSpec{"refs/heads/*:refs/heads/*", "refs/tags/*:refs/tags/*"},
502+
})
503+
Expect(err).NotTo(HaveOccurred())
504+
505+
key := types.NamespacedName{
506+
Name: fmt.Sprintf("git-ref-test-%s", randStringRunes(5)),
507+
Namespace: namespace.Name,
508+
}
509+
created := &sourcev1.GitRepository{
510+
ObjectMeta: metav1.ObjectMeta{
511+
Name: key.Name,
512+
Namespace: key.Namespace,
513+
},
514+
Spec: sourcev1.GitRepositorySpec{
515+
URL: mainRepoURL.String(),
516+
Interval: metav1.Duration{Duration: indexInterval},
517+
Reference: &sourcev1.GitRepositoryRef{Branch: "master"},
518+
GitImplementation: sourcev1.GoGitImplementation, // only works with go-git
519+
RecurseSubmodules: true,
520+
},
521+
}
522+
Expect(k8sClient.Create(context.Background(), created)).Should(Succeed())
523+
defer k8sClient.Delete(context.Background(), created)
524+
525+
got := &sourcev1.GitRepository{}
526+
Eventually(func() bool {
527+
_ = k8sClient.Get(context.Background(), key, got)
528+
for _, c := range got.Status.Conditions {
529+
if c.Reason == sourcev1.GitOperationSucceedReason {
530+
return true
531+
}
532+
}
533+
return false
534+
}, timeout, interval).Should(BeTrue())
535+
536+
// check that the downloaded artifact includes the
537+
// file from the submodule
538+
res, err := http.Get(got.Status.URL)
539+
Expect(err).NotTo(HaveOccurred())
540+
Expect(res.StatusCode).To(Equal(http.StatusOK))
541+
542+
_, err = untar.Untar(res.Body, filepath.Join(tmp, "tar"))
543+
Expect(err).NotTo(HaveOccurred())
544+
Expect(filepath.Join(tmp, "tar", "sub", "fixture")).To(BeAnExistingFile())
545+
})
546+
})
413547
})
414548
})

controllers/suite_test.go

+6-1
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ package controllers
1919
import (
2020
"io/ioutil"
2121
"math/rand"
22+
"net/http"
2223
"os"
2324
"path/filepath"
2425
"testing"
@@ -99,8 +100,12 @@ var _ = BeforeSuite(func(done Done) {
99100
tmpStoragePath, err := ioutil.TempDir("", "source-controller-storage-")
100101
Expect(err).NotTo(HaveOccurred(), "failed to create tmp storage dir")
101102

102-
storage, err = NewStorage(tmpStoragePath, "localhost", time.Second*30)
103+
storage, err = NewStorage(tmpStoragePath, "localhost:5050", time.Second*30)
103104
Expect(err).NotTo(HaveOccurred(), "failed to create tmp storage")
105+
// serve artifacts from the filesystem, as done in main.go
106+
fs := http.FileServer(http.Dir(tmpStoragePath))
107+
http.Handle("/", fs)
108+
go http.ListenAndServe(":5050", nil)
104109

105110
k8sManager, err = ctrl.NewManager(cfg, ctrl.Options{
106111
Scheme: scheme.Scheme,

docs/api/source.md

+28
Original file line numberDiff line numberDiff line change
@@ -400,6 +400,20 @@ string
400400
Defaults to go-git, valid values are (&lsquo;go-git&rsquo;, &lsquo;libgit2&rsquo;).</p>
401401
</td>
402402
</tr>
403+
<tr>
404+
<td>
405+
<code>recurseSubmodules</code><br>
406+
<em>
407+
bool
408+
</em>
409+
</td>
410+
<td>
411+
<em>(Optional)</em>
412+
<p>When enabled, after the clone is created, initializes all submodules within,
413+
using their default settings.
414+
This option is available only when using the &lsquo;go-git&rsquo; GitImplementation.</p>
415+
</td>
416+
</tr>
403417
</table>
404418
</td>
405419
</tr>
@@ -1246,6 +1260,20 @@ string
12461260
Defaults to go-git, valid values are (&lsquo;go-git&rsquo;, &lsquo;libgit2&rsquo;).</p>
12471261
</td>
12481262
</tr>
1263+
<tr>
1264+
<td>
1265+
<code>recurseSubmodules</code><br>
1266+
<em>
1267+
bool
1268+
</em>
1269+
</td>
1270+
<td>
1271+
<em>(Optional)</em>
1272+
<p>When enabled, after the clone is created, initializes all submodules within,
1273+
using their default settings.
1274+
This option is available only when using the &lsquo;go-git&rsquo; GitImplementation.</p>
1275+
</td>
1276+
</tr>
12491277
</tbody>
12501278
</table>
12511279
</div>

docs/spec/v1beta1/gitrepositories.md

+41
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,11 @@ type GitRepositorySpec struct {
5757
// +kubebuilder:default:=go-git
5858
// +optional
5959
GitImplementation string `json:"gitImplementation,omitempty"`
60+
61+
// When enabled, after the clone is created, initializes all submodules within.
62+
// This option is available only when using the 'go-git' GitImplementation.
63+
// +optional
64+
RecurseSubmodules bool `json:"recurseSubmodules,omitempty"`
6065
}
6166
```
6267

@@ -434,6 +439,42 @@ kubectl create secret generic pgp-public-keys \
434439
--from-file=author2.asc
435440
```
436441

442+
### Git submodules
443+
444+
With `spec.recurseSubmodules` you can configure the controller to
445+
clone a specific branch including its Git submodules:
446+
447+
```yaml
448+
apiVersion: source.toolkit.fluxcd.io/v1beta1
449+
kind: GitRepository
450+
metadata:
451+
name: repo-with-submodules
452+
namespace: default
453+
spec:
454+
interval: 1m
455+
url: https://github.com/<organization>/<repository>
456+
secretRef:
457+
name: https-credentials
458+
ref:
459+
branch: main
460+
recurseSubmodules: true
461+
---
462+
apiVersion: v1
463+
kind: Secret
464+
metadata:
465+
name: https-credentials
466+
namespace: default
467+
type: Opaque
468+
data:
469+
username: <GitHub Username>
470+
password: <GitHub Token>
471+
```
472+
473+
Note that deploy keys can't be used to pull submodules from private repositories
474+
as GitHub and GitLab doesn't allow a deploy key to be reused across repositories.
475+
You have to use either HTTPS token-based authentication, or an SSH key belonging
476+
to a user that has access to the main repository and all its submodules.
477+
437478
## Status examples
438479

439480
Successful sync:

pkg/git/git.go

+5
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,11 @@ type CheckoutStrategy interface {
4040
Checkout(ctx context.Context, path, url string, auth *Auth) (Commit, string, error)
4141
}
4242

43+
type CheckoutOptions struct {
44+
GitImplementation string
45+
RecurseSubmodules bool
46+
}
47+
4348
// TODO(hidde): candidate for refactoring, so that we do not directly
4449
// depend on implementation specifics here.
4550
type Auth struct {

0 commit comments

Comments
 (0)