From c1c41992d0e3b069e7bb9cc90f61356a583cd98c Mon Sep 17 00:00:00 2001 From: kzadorozhny Date: Fri, 21 Jun 2024 17:26:57 -0700 Subject: [PATCH] track branches before fetch --- gitops/git/git.go | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) diff --git a/gitops/git/git.go b/gitops/git/git.go index a89003f9..57e3d4db 100644 --- a/gitops/git/git.go +++ b/gitops/git/git.go @@ -36,7 +36,8 @@ func Clone(repo, dir, mirrorDir, primaryBranch, gitopsPath string) (*Repo, error if err := os.RemoveAll(dir); err != nil { return nil, fmt.Errorf("Unable to clone repo: %w", err) } - args := []string{"clone", "--no-checkout", "--single-branch", "--branch", primaryBranch, "--filter=blob:none", "--no-tags"} + remoteName := "origin" + args := []string{"clone", "--no-checkout", "--single-branch", "--branch", primaryBranch, "--filter=blob:none", "--no-tags", "--origin", remoteName} if mirrorDir != "" { args = append(args, "--reference", mirrorDir) } @@ -48,9 +49,9 @@ func Clone(repo, dir, mirrorDir, primaryBranch, gitopsPath string) (*Repo, error return nil, fmt.Errorf("Unable to create .git/info/sparse-checkout: %w", err) } exec.Mustex(dir, "git", "checkout", primaryBranch) - return &Repo{ - Dir: dir, + Dir: dir, + RemoteName: remoteName, }, nil } @@ -59,6 +60,8 @@ func Clone(repo, dir, mirrorDir, primaryBranch, gitopsPath string) (*Repo, error type Repo struct { // Dir is the location of the git repo. Dir string + // RemoteName is the name of the remote that tracks upstream repository. + RemoteName string } // Clean cleans up the repo @@ -67,9 +70,10 @@ func (r *Repo) Clean() error { } // Fetch branches from the remote repository based on a specified pattern. +// The branches will be be added to the list tracked remote branches ready to be pushed. func (r *Repo) Fetch(pattern string) { - refSpec := fmt.Sprintf("+refs/heads/%s:refs/remotes/origin/%s", pattern, pattern) - exec.Mustex(r.Dir, "git", "fetch", "--force", "--filter=blob:none", "--no-tags", "origin", refSpec) + exec.Mustex(r.Dir, "git", "remote", "set-branches", "--add", r.RemoteName, pattern) + exec.Mustex(r.Dir, "git", "fetch", "--force", "--filter=blob:none", "--no-tags", r.RemoteName) } // SwitchToBranch switch the repo to specified branch and checkout primaryBranch files over it. @@ -124,6 +128,6 @@ func (r *Repo) IsClean() bool { // Push pushes all local changes to the remote repository // all changes should be already commited func (r *Repo) Push(branches []string) { - args := append([]string{"push", "origin", "-f", "--set-upstream"}, branches...) + args := append([]string{"push", r.RemoteName, "-f", "--set-upstream"}, branches...) exec.Mustex(r.Dir, "git", args...) }