Skip to content
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

Support git repo caching on package create #785

Merged
Show file tree
Hide file tree
Changes from 142 commits
Commits
Show all changes
148 commits
Select commit Hold shift + click to select a range
bf5eb9e
Layout initial todos
Racer159 Sep 22, 2022
2d27030
create InitOptions for init specific flags
YrrepNoj Jul 7, 2022
9463e01
fix Makefile dev-agent-image target
YrrepNoj Jul 25, 2022
ac9b174
save zarfState during init for future flux git url mutations
YrrepNoj Jul 25, 2022
4ecdc56
set GitServerInfo as we seed the cluster
YrrepNoj Jul 25, 2022
19ae80a
read git information from GitServerInfo within config
YrrepNoj Jul 26, 2022
205ff7e
check if we need to tunnel to external git server
YrrepNoj Jul 27, 2022
dbccfe3
add simple manual test for external-git on init
YrrepNoj Jul 28, 2022
7b56681
remove unnecessarly git-read-user flags on init
YrrepNoj Jul 28, 2022
4a93afa
add more explicit check to determin if url is an internal svc url
YrrepNoj Jul 29, 2022
131b7a3
fix typo in Makefile
YrrepNoj Aug 1, 2022
ed2af3d
have e2e test only make init-package if not already existing
YrrepNoj Aug 2, 2022
0d54d88
update zarfState json text for GitServer
YrrepNoj Aug 3, 2022
7b2754b
add back explicit creation of init package in github workflow pipeline
YrrepNoj Aug 8, 2022
87027bb
verify init-package exists during the 'test-e2e' make target
YrrepNoj Aug 8, 2022
1cf2d1f
rename get-admin-password command to get-git-password
YrrepNoj Aug 8, 2022
45ddcb6
update flag and usage text for git-account for the prepare command
YrrepNoj Aug 8, 2022
96ac579
add validation checking to init command flags
YrrepNoj Aug 8, 2022
ba201e6
fill in GitServer values without overriding
YrrepNoj Aug 8, 2022
87608f0
wip - registryInfo struct
YrrepNoj Jul 28, 2022
e1cb572
wip
YrrepNoj Aug 2, 2022
805160a
add json annotation to ContainerRegistryInfo
YrrepNoj Aug 3, 2022
b456b66
move nodeport from InitOptions to ContainerRegistryInfo
YrrepNoj Aug 3, 2022
8266771
simplify containerRegistryInfo var names
YrrepNoj Aug 3, 2022
f0fbb7d
check for external registry before seeding
YrrepNoj Aug 5, 2022
148b686
clean up workflow around seed registry a little
YrrepNoj Aug 5, 2022
d0f4705
change ready check for valuate template
YrrepNoj Aug 5, 2022
660cf70
set default value for nodeport flag during init
YrrepNoj Aug 8, 2022
0ff8cdb
update zarf agent to swap registry URL based on state values
YrrepNoj Aug 8, 2022
94a98a4
remove secret expansion logic
YrrepNoj Aug 8, 2022
6c77915
fill in ContainerRegistry values without overriding
YrrepNoj Aug 8, 2022
3155eae
standardize names of ContainerRegistry and GitServer struct fields
YrrepNoj Aug 9, 2022
f7f7811
tempalte gitea username
YrrepNoj Aug 9, 2022
fde2a27
clean up and help text for external git-server and container-registry…
YrrepNoj Aug 9, 2022
2a54bf6
check registry nodeport when returning registry addres
YrrepNoj Aug 12, 2022
bbbd56b
update read-only user creation to use usenames provided by init flags
YrrepNoj Aug 12, 2022
8019ed8
only output connect options for internal registry
YrrepNoj Aug 12, 2022
bccd617
bugfix: registry url in agent pod mutation
YrrepNoj Aug 12, 2022
3a75a54
add logic to test using zarf with an external registry
YrrepNoj Aug 12, 2022
c86e9af
shorten down function name
YrrepNoj Aug 13, 2022
cbe18c5
rename 'containerRegistry' to registry
YrrepNoj Aug 13, 2022
85cef08
add disclaimer about hardcoded credentials for testing purposes
YrrepNoj Aug 13, 2022
6107172
add registrySecret to the zarf state
YrrepNoj Aug 13, 2022
29ef269
make init flag option for registrySecret
YrrepNoj Aug 15, 2022
17022f8
add jsonschema descriptions of types
YrrepNoj Aug 15, 2022
d6bbf74
fix typo and bad description within external-init test comments/instr…
YrrepNoj Aug 15, 2022
7930574
remove explicit port variable for git-server url
YrrepNoj Aug 17, 2022
8d7209a
add workflow test for using external repository & registry
YrrepNoj Aug 23, 2022
febb20a
use temporary agent-image for this branch
YrrepNoj Aug 29, 2022
baccffd
use temporary agent-image for this branch - built from test pipeline
YrrepNoj Aug 29, 2022
92913b9
correct error message when unable to push to git server during deploy
YrrepNoj Aug 29, 2022
196da1e
standardize pull vs read verbage
YrrepNoj Aug 29, 2022
b540939
remove underscore characters from mutated reponames
YrrepNoj Aug 29, 2022
8daa189
add sha1 hash at the end of tranformed git url
YrrepNoj Aug 31, 2022
dd42784
add sha1 hash at the end of transformed container url
YrrepNoj Aug 31, 2022
7b32bb6
refactor component deploy so injector and agent images do not have sh…
YrrepNoj Sep 1, 2022
d353177
fix bug with datainjction waitgroup deferal
YrrepNoj Sep 1, 2022
bb6924f
install helm for external test workflow
YrrepNoj Sep 1, 2022
eedd3ed
fix external test using the wrong cli flags
YrrepNoj Sep 1, 2022
932a8d2
update agent image tag
YrrepNoj Sep 1, 2022
56cb158
skip injector components if using external registry
YrrepNoj Sep 1, 2022
93219f9
build flux package if not currently existing during external test wor…
YrrepNoj Sep 1, 2022
d9f2aa3
light cleanup around deploy logic
YrrepNoj Sep 2, 2022
8b54266
add usage examples for 'zarf init' command
YrrepNoj Sep 2, 2022
b68ae09
bugfix - remove deferal of postSeedRegistry and explicitly call the f…
YrrepNoj Sep 2, 2022
a4a1ed2
add .git to repo link in flux example
YrrepNoj Sep 4, 2022
8dcbb22
have external test use GitHub runners
YrrepNoj Sep 20, 2022
68396e6
update cli docs
YrrepNoj Sep 20, 2022
b30d6a1
fix kubectl install for external test
YrrepNoj Sep 20, 2022
f577c37
misc linter and styling cleanup
YrrepNoj Sep 21, 2022
8cbc925
add docs for init command examples
YrrepNoj Sep 21, 2022
48bcb10
misc code cleanup
YrrepNoj Sep 23, 2022
ad3303d
update api-types file
YrrepNoj Sep 23, 2022
35eb375
wip - temporarly comment out refs fetch when pushing repos
YrrepNoj Sep 23, 2022
2e6a7ed
change the expected reponame for the git test to include the sha suffix
YrrepNoj Sep 23, 2022
87928c2
cleanup external test
YrrepNoj Sep 23, 2022
e1b1df3
Merge branch 'master' into 560-external-registry-and-repository
Racer159 Sep 23, 2022
dcc661f
Merge branch 'master' into 560-external-registry-and-repository
jeff-mccoy Sep 25, 2022
09fc8c9
cleanup typos, regexp explanations, git fetch logic, and go.mod
YrrepNoj Sep 26, 2022
8c3b006
Merge branch 'master' into 560-external-registry-and-repository
Racer159 Sep 26, 2022
bc6e0b1
Zarf agent webhook no longer tries to update flux repo URL on updates
YrrepNoj Sep 26, 2022
6c73284
Merge branch 'master' into 750-support-a-git-cache-directory-similar-…
Racer159 Sep 26, 2022
849189d
update 'zarf tool' command docs
YrrepNoj Sep 26, 2022
5dedef9
update go.mod and go.sum
YrrepNoj Sep 26, 2022
9eb755f
Change image cache to cache
Racer159 Sep 26, 2022
ca4ee93
WIP: Add initial git caching support
Racer159 Sep 27, 2022
5dcccac
Merge branch 'master' into 750-support-a-git-cache-directory-similar-…
Racer159 Sep 27, 2022
e59ba38
Merge branch 'master' into 750-support-a-git-cache-directory-similar-…
Racer159 Sep 27, 2022
a671fc3
WIP: working but ugly code
Racer159 Sep 27, 2022
c1a3893
Merge branch 'master' into 750-support-a-git-cache-directory-similar-…
Racer159 Sep 27, 2022
933bfc8
Add a test for the git cache
Racer159 Sep 27, 2022
3738e13
Merge branch 'master' into 560-external-registry-and-repository
Racer159 Sep 27, 2022
2efec48
Refactor (mostly) completed
Racer159 Sep 27, 2022
fab4833
Merge in external git repos
Racer159 Sep 27, 2022
f1fc2f8
Post-rebase refactors
Racer159 Sep 28, 2022
4da8e17
Small refactor fix
Racer159 Sep 28, 2022
446366b
Make regex ungreedy
Racer159 Sep 28, 2022
c306c49
Update docs and schema
Racer159 Sep 28, 2022
a174b02
Merge branch 'master' into 560-external-registry-and-repository
jeff-mccoy Sep 28, 2022
4722489
Fix sha in test
Racer159 Sep 28, 2022
830eeba
Merge branch 'master' into 750-support-a-git-cache-directory-similar-…
Racer159 Sep 28, 2022
6239347
Small change to baseUrl to resolve flux issues
Racer159 Sep 28, 2022
173cd10
Fix test shasums
Racer159 Sep 28, 2022
86917b5
Fix issues with git repo matching in flux
Racer159 Sep 28, 2022
dc9eff1
Fix tests and sanitized URL
Racer159 Sep 28, 2022
162b505
Merge branch '560-external-registry-and-repository' into 750-support-…
Racer159 Sep 28, 2022
6b8df96
perform hostname mutation on flux webhook update trigger if the git u…
YrrepNoj Sep 29, 2022
367040d
Merge branch 'master' into 560-external-registry-and-repository
Racer159 Sep 29, 2022
9530176
cleanup flux webhook to check operation type -> more DRY code
YrrepNoj Sep 29, 2022
09f13ef
Tunnel Update
jeff-mccoy Sep 29, 2022
6cd9c67
Merge branch '560-external-registry-and-repository' into 750-support-…
Racer159 Sep 29, 2022
331b871
Add a clean cache command to tools
Racer159 Sep 29, 2022
4e03281
Merge branch 'master' into 750-support-a-git-cache-directory-similar-…
Racer159 Sep 29, 2022
5abf944
Address ExecCommandWithContext feedback
Racer159 Sep 29, 2022
3a261c9
Added named capture groups
Racer159 Sep 29, 2022
570935e
Canonicalize the cache dirs as constants
Racer159 Sep 29, 2022
e0c7cac
Merge branch 'master' into 750-support-a-git-cache-directory-similar-…
Racer159 Sep 29, 2022
d8b3ffe
Change to filepath.join
Racer159 Sep 29, 2022
0e875b0
Update docs
Racer159 Sep 29, 2022
59cc6fa
Merge branch 'master' into 750-support-a-git-cache-directory-similar-…
jeff-mccoy Sep 29, 2022
39bb538
Merge branch 'master' into 750-support-a-git-cache-directory-similar-…
Racer159 Sep 30, 2022
d72d9f7
Address more feedback (and cleanup)
Racer159 Sep 30, 2022
0c43e0c
Simplify clear cache
Racer159 Sep 30, 2022
9a92673
Update regex names in linked regex
Racer159 Sep 30, 2022
e31e775
Fix docs and schema
Racer159 Sep 30, 2022
91807a7
Further simplify the way determining the cache dir works
Racer159 Sep 30, 2022
d3594c4
Merge branch 'master' into 750-support-a-git-cache-directory-similar-…
Racer159 Sep 30, 2022
bc27d26
Fix merge issue
Racer159 Sep 30, 2022
f3d83cb
Fix space problem
Racer159 Sep 30, 2022
8a29003
Merge branch 'master' into 750-support-a-git-cache-directory-similar-…
Racer159 Sep 30, 2022
0e1f107
Merge branch 'master' into 750-support-a-git-cache-directory-similar-…
jeff-mccoy Sep 30, 2022
8326311
Merge branch 'master' into 750-support-a-git-cache-directory-similar-…
jeff-mccoy Oct 1, 2022
2292c1c
Merge branch 'master' into 750-support-a-git-cache-directory-similar-…
jeff-mccoy Oct 3, 2022
0ae9d5b
Merge branch 'master' into 750-support-a-git-cache-directory-similar-…
jeff-mccoy Oct 3, 2022
a23e878
Fix SHA hash in test from merge
Racer159 Oct 3, 2022
ed9f9e2
Merge branch 'master' into 750-support-a-git-cache-directory-similar-…
Racer159 Oct 3, 2022
667c157
Fix small docs error
Racer159 Oct 3, 2022
e49ee3c
Remove proto from sha1sum
Racer159 Oct 3, 2022
017919b
Fix #6
Racer159 Oct 3, 2022
b6904c7
Fix another issue
Racer159 Oct 3, 2022
6fee6ff
Merge branch 'master' into 750-support-a-git-cache-directory-similar-…
jeff-mccoy Oct 4, 2022
3b2086e
Merge branch 'master' into 750-support-a-git-cache-directory-similar-…
jeff-mccoy Oct 4, 2022
b19152b
Use OS temp path in tests
Racer159 Oct 4, 2022
937a286
Refactor cache path settings
Racer159 Oct 4, 2022
686ace8
replace string concat
Racer159 Oct 4, 2022
a710060
Remove dogsledding
Racer159 Oct 4, 2022
8801fc7
Improve readability of code
Racer159 Oct 4, 2022
65c5b8b
Fix Zarf Agent and test 22 timeout
Racer159 Oct 4, 2022
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
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ zarf package create [DIRECTORY] [flags]
--set stringToString Specify package variables to set on the command line (KEY=value) (default [])
--skip-sbom Skip generating SBOM for this package
--tmpdir string Specify the temporary directory to use for intermediate files
--zarf-cache string Specify the location of the Zarf image cache (default ".zarf-image-cache")
--zarf-cache string Specify the location of the Zarf artifact cache (images and git repositories) (default "~/.zarf-cache")
```

### Options inherited from parent commands
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ Collection of additional tools to make airgap easier

* [zarf](zarf.md) - DevSecOps Airgap Toolkit
* [zarf tools archiver](zarf_tools_archiver.md) - Compress/Decompress tools for Zarf packages
* [zarf tools clear-cache](zarf_tools_clear-cache.md) - Clears the configured git and image cache directory
* [zarf tools get-git-password](zarf_tools_get-git-password.md) - Returns the push user's password for the Git server
* [zarf tools monitor](zarf_tools_monitor.md) - Launch K9s tool for managing K8s clusters
* [zarf tools registry](zarf_tools_registry.md) - Collection of registry commands provided by Crane
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
## zarf tools clear-cache

Clears the configured git and image cache directory

```
zarf tools clear-cache [flags]
```

### Options

```
-h, --help help for clear-cache
--zarf-cache string Specify the location of the Zarf artifact cache (images and git repositories) (default "~/.zarf-cache")
```

### Options inherited from parent commands

```
-a, --architecture string Architecture for OCI images
-l, --log-level string Log level when running Zarf. Valid options are: warn, info, debug, trace
--no-progress Disable fancy UI progress bars, spinners, logos, etc.
```

### SEE ALSO

* [zarf tools](zarf_tools.md) - Collection of additional tools to make airgap easier

4 changes: 2 additions & 2 deletions docs/6-developer-guide/2-testing.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ APPLIANCE_MODE=true make test-e2e ARCH="[amd64|arm64]"
go test ./... -v

# Let's say you only want to run one test. You would run:
test ./... -v -run TestFooBarBaz
go test ./... -v -run TestFooBarBaz
```

:::note
Expand All @@ -58,4 +58,4 @@ The tests are run sequentially and the naming convention is set intentionally:
- 20 is reserved for `zarf init`
- 21 is reserved for logging tests so they can be removed first (they take the most resources in the cluster)
- 22 is reserved for tests required the git-server, which is removed at the end of the test
- 23-99 are for the remaining tests that only require a basic zarf cluster without logging for the git-server
- 23-99 are for the remaining tests that only require a basic zarf cluster without logging for the git-server
2 changes: 2 additions & 0 deletions examples/git-data/zarf.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -17,3 +17,5 @@ components:
- https://github.com/stefanprodan/podinfo.git
# Clone an azure repo that breaks in go-git and has to fall back to the host git
- https://[email protected]/me0515/zarf-public-test/_git/zarf-public-test
# Clone an azure repo (w/SHA) that breaks in go-git and has to fall back to the host git
- https://[email protected]/me0515/zarf-public-test/_git/zarf-public-test@524980951ff16e19dc25232e9aea8fd693989ba6
15 changes: 7 additions & 8 deletions src/cmd/package.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,6 @@ import (

var insecureDeploy bool
var shasum string
var zarfImageCache string

var packageCmd = &cobra.Command{
Use: "package",
Expand All @@ -46,8 +45,8 @@ var packageCreateCmd = &cobra.Command{
baseDir = args[0]
}

if zarfImageCache != config.ZarfDefaultImageCachePath && cachePathClean(zarfImageCache) {
config.SetImageCachePath(zarfImageCache)
if isCachePathClean(config.CreateOptions.CachePath) {
Racer159 marked this conversation as resolved.
Show resolved Hide resolved
config.SetCachePath(config.CreateOptions.CachePath)
Racer159 marked this conversation as resolved.
Show resolved Hide resolved
}

packager.Create(baseDir)
Expand Down Expand Up @@ -175,10 +174,10 @@ func choosePackage(args []string) string {
return path
}

func cachePathClean(cachePath string) bool {
var isCleanPath = regexp.MustCompile(`^[a-zA-Z0-9\_\-\/\.\~]+$`).MatchString
if !isCleanPath(cachePath) {
message.Warnf("Invalid characters in Zarf cache path, defaulting to ~/%s", config.ZarfDefaultImageCachePath)
func isCachePathClean(cachePath string) bool {
var isCleanPathRegex = regexp.MustCompile(`^[a-zA-Z0-9\_\-\/\.\~]+$`).MatchString
Racer159 marked this conversation as resolved.
Show resolved Hide resolved
if !isCleanPathRegex(cachePath) {
message.Warnf("Invalid characters in Zarf cache path, defaulting to %s", config.ZarfCachePath)
return false
}
return true
Expand All @@ -195,7 +194,7 @@ func init() {
packageCreateCmd.Flags().BoolVar(&config.CommonOptions.Confirm, "confirm", false, "Confirm package creation without prompting")
packageCreateCmd.Flags().StringVar(&config.CommonOptions.TempDirectory, "tmpdir", "", "Specify the temporary directory to use for intermediate files")
packageCreateCmd.Flags().StringToStringVar(&config.CommonOptions.SetVariables, "set", map[string]string{}, "Specify package variables to set on the command line (KEY=value)")
packageCreateCmd.Flags().StringVar(&zarfImageCache, "zarf-cache", config.ZarfDefaultImageCachePath, "Specify the location of the Zarf image cache")
packageCreateCmd.Flags().StringVar(&config.CreateOptions.CachePath, "zarf-cache", config.ZarfCachePath, "Specify the location of the Zarf artifact cache (images and git repositories)")
packageCreateCmd.Flags().StringVarP(&config.CreateOptions.OutputDirectory, "output-directory", "o", "", "Specify the output directory for the created Zarf package")
packageCreateCmd.Flags().BoolVar(&config.CreateOptions.SkipSBOM, "skip-sbom", false, "Skip generating SBOM for this package")
packageCreateCmd.Flags().BoolVar(&config.CreateOptions.Insecure, "insecure", false, "Allow insecure registry connections when pulling OCI images")
Expand Down
14 changes: 14 additions & 0 deletions src/cmd/tools.go
Original file line number Diff line number Diff line change
Expand Up @@ -95,13 +95,27 @@ var k9sCmd = &cobra.Command{
},
}

var clearCacheCmd = &cobra.Command{
Use: "clear-cache",
Aliases: []string{"c"},
Short: "Clears the configured git and image cache directory",
Run: func(cmd *cobra.Command, args []string) {
if err := os.RemoveAll(config.CreateOptions.CachePath); err != nil {
message.Fatalf("Unable to clear the cache driectory %s: %s", config.CreateOptions.CachePath, err.Error())
}
},
}

func init() {
rootCmd.AddCommand(toolsCmd)
toolsCmd.AddCommand(archiverCmd)
toolsCmd.AddCommand(readCredsCmd)
toolsCmd.AddCommand(k9sCmd)
toolsCmd.AddCommand(registryCmd)

toolsCmd.AddCommand(clearCacheCmd)
clearCacheCmd.Flags().StringVar(&config.CreateOptions.CachePath, "zarf-cache", config.ZarfCachePath, "Specify the location of the Zarf artifact cache (images and git repositories)")

archiverCmd.AddCommand(archiverCompressCmd)
archiverCmd.AddCommand(archiverDecompressCmd)

Expand Down
24 changes: 13 additions & 11 deletions src/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,9 +41,11 @@ const (
ZarfConnectAnnotationDescription = "zarf.dev/connect-description"
ZarfConnectAnnotationUrl = "zarf.dev/connect-url"

ZarfManagedByLabel = "app.kubernetes.io/managed-by"
ZarfCleanupScriptsPath = "/opt/zarf"
ZarfDefaultImageCachePath = ".zarf-image-cache"
ZarfManagedByLabel = "app.kubernetes.io/managed-by"
ZarfCleanupScriptsPath = "/opt/zarf"

ZarfImageCacheDir = "images"
ZarfGitCacheDir = "repos"

ZarfYAML = "zarf.yaml"
ZarfSBOMDir = "zarf-sbom"
Expand Down Expand Up @@ -89,6 +91,8 @@ var (
// Timestamp of when the CLI was started
operationStartTime = time.Now().Unix()
dataInjectionMarker = ".zarf-injection-%d"

ZarfCachePath = filepath.Join("~", ".zarf-cache")
)

// Timestamp of when the CLI was started
Expand Down Expand Up @@ -284,18 +288,16 @@ func BuildConfig(path string) error {
return utils.WriteYaml(path, active, 0400)
}

func SetImageCachePath(cachePath string) {
CreateOptions.ImageCachePath = cachePath
// SetCachePath sets the cache path for images and git repos.
func SetCachePath(cachePath string) {
ZarfCachePath = cachePath
}

func GetImageCachePath() string {
// GetCachePath gets the absolute cache path for images and git repos.
func GetCachePath() string {
homePath, _ := os.UserHomeDir()

if CreateOptions.ImageCachePath == "" {
return filepath.Join(homePath, ZarfDefaultImageCachePath)
}

return strings.Replace(CreateOptions.ImageCachePath, "~", homePath, 1)
return strings.Replace(ZarfCachePath, "~", homePath, 1)
}

func isCompatibleComponent(component types.ZarfComponent, filterByOS bool) bool {
Expand Down
66 changes: 66 additions & 0 deletions src/internal/git/clone.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
package git

import (
"context"
"errors"

"github.com/defenseunicorns/zarf/src/internal/message"
"github.com/defenseunicorns/zarf/src/internal/utils"
"github.com/go-git/go-git/v5"
)

// clone performs a `git clone` of a given repo.
func clone(gitDirectory string, gitURL string, onlyFetchRef bool, spinner *message.Spinner) (*git.Repository, error) {
cloneOptions := &git.CloneOptions{
URL: gitURL,
Progress: spinner,
RemoteName: onlineRemoteName,
}

if onlyFetchRef {
cloneOptions.Tags = git.NoTags
}

gitCred := FindAuthForHost(gitURL)

// Gracefully handle no git creds on the system (like our CI/CD)
if gitCred.Auth.Username != "" {
cloneOptions.Auth = &gitCred.Auth
Racer159 marked this conversation as resolved.
Show resolved Hide resolved
}

// Clone the given repo
repo, err := git.PlainClone(gitDirectory, false, cloneOptions)

if errors.Is(err, git.ErrRepositoryAlreadyExists) {
repo, err = git.PlainOpen(gitDirectory)

if err != nil {
return nil, err
}

return repo, git.ErrRepositoryAlreadyExists
} else if err != nil {
spinner.Debugf("Failed to clone repo: %s", err)
message.Infof("Falling back to host git for %s", gitURL)

// If we can't clone with go-git, fallback to the host clone
// Only support "all tags" due to the azure clone url format including a username
cmdArgs := []string{"clone", "--origin", onlineRemoteName, gitURL, gitDirectory}

if onlyFetchRef {
cmdArgs = append(cmdArgs, "--no-tags")
}

stdOut, stdErr, err := utils.ExecCommandWithContext(context.TODO(), false, "git", cmdArgs...)
spinner.Updatef(stdOut)
spinner.Debugf(stdErr)

if err != nil {
return nil, err
}

return git.PlainOpen(gitDirectory)
} else {
return repo, nil
}
}
36 changes: 28 additions & 8 deletions src/internal/git/fetch.go
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
package git

import (
"context"
"errors"
"path"

"github.com/defenseunicorns/zarf/src/internal/message"
"github.com/defenseunicorns/zarf/src/internal/utils"
"github.com/go-git/go-git/v5"
goConfig "github.com/go-git/go-git/v5/config"
)
Expand All @@ -16,9 +19,7 @@ func fetchTag(gitDirectory string, tag string) {

err := fetch(gitDirectory, refspec)

if err == git.ErrTagExists {
message.Debug("Tag already fetched")
} else if err != nil {
if err != nil {
message.Fatal(err, "Not a valid tag or unable to fetch")
}
}
Expand All @@ -36,8 +37,8 @@ func fetchHash(gitDirectory string, hash string) {
}
}

// fetch performs a `git fetch` of _only_ the provided git refspec.
func fetch(gitDirectory string, refspec goConfig.RefSpec) error {
// fetch performs a `git fetch` of _only_ the provided git refspec(s).
func fetch(gitDirectory string, refspecs ...goConfig.RefSpec) error {
repo, err := git.PlainOpen(gitDirectory)
if err != nil {
message.Fatal(err, "Unable to load the git repo")
Expand All @@ -51,18 +52,37 @@ func fetch(gitDirectory string, refspec goConfig.RefSpec) error {
}

gitURL := remotes[0].Config().URLs[0]
message.Debugf("Attempting to find ref: %s for %s", refspec.String(), gitURL)
message.Debugf("Attempting to find ref: %#v for %s", refspecs, gitURL)

gitCred := FindAuthForHost(gitURL)

fetchOptions := &git.FetchOptions{
RemoteName: onlineRemoteName,
RefSpecs: []goConfig.RefSpec{refspec},
RefSpecs: refspecs,
}

if gitCred.Auth.Username != "" {
fetchOptions.Auth = &gitCred.Auth
}

return repo.Fetch(fetchOptions)
err = repo.Fetch(fetchOptions)

if errors.Is(err, git.ErrTagExists) || errors.Is(err, git.NoErrAlreadyUpToDate) {
message.Debug("Already fetched requested ref")
} else if err != nil {
message.Debugf("Failed to fetch repo: %s", err)
message.Infof("Falling back to host git for %s", gitURL)

// If we can't fetch with go-git, fallback to the host fetch
// Only support "all tags" due to the azure fetch url format including a username
cmdArgs := []string{"fetch", onlineRemoteName}
for _, refspec := range refspecs {
cmdArgs = append(cmdArgs, refspec.String())
}
_, _, err := utils.ExecCommandWithContextAndDir(context.TODO(), gitDirectory, false, "git", cmdArgs...)

return err
}

return nil
}
Loading