Skip to content

Commit

Permalink
fix(controller)!: check create setting when attempting to clone non-e…
Browse files Browse the repository at this point in the history
…xistent remote branch (#3012)

Signed-off-by: Kent Rancourt <[email protected]>
  • Loading branch information
krancour authored Nov 27, 2024
1 parent 59c2db9 commit ad139d2
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 4 deletions.
20 changes: 16 additions & 4 deletions internal/directives/git_cloner.go
Original file line number Diff line number Diff line change
Expand Up @@ -140,7 +140,7 @@ func (g *gitCloner) runPromotionStep(
switch {
case checkout.Branch != "":
ref = checkout.Branch
if err = ensureRemoteBranch(repo, ref); err != nil {
if err = ensureRemoteBranch(repo, ref, checkout.Create); err != nil {
return PromotionStepResult{Status: kargoapi.PromotionPhaseErrored},
fmt.Errorf("error ensuring existence of remote branch %s: %w", ref, err)
}
Expand Down Expand Up @@ -222,9 +222,12 @@ func mustCloneRepo(stepCtx *PromotionStepContext, cfg GitCloneConfig) (bool, err
return false, nil
}

// ensureRemoteBranch ensures the existence of a remote branch. If the branch
// does not exist, an empty orphaned branch is created and pushed to the remote.
func ensureRemoteBranch(repo git.BareRepo, branch string) error {
// ensureRemoteBranch checks for the existence of a remote branch. If the remote
// branch exists, no action is taken and nil is returned. If the branch does not
// exist and create == true, an empty orphaned branch is created and pushed to
// the remote. If the branch does not exist and create == false, an error is
// returned.
func ensureRemoteBranch(repo git.BareRepo, branch string, create bool) error {
exists, err := repo.RemoteBranchExists(branch)
if err != nil {
return fmt.Errorf(
Expand All @@ -235,6 +238,15 @@ func ensureRemoteBranch(repo git.BareRepo, branch string) error {
if exists {
return nil
}
if !create {
return fmt.Errorf(
"remote branch %q of repo %s does not exist; set create=true if you'd "+
"like a non-existent remote branch to be automatically created at "+
"checkout",
branch,
repo.URL(),
)
}
tmpDir, err := os.MkdirTemp("", "repo-")
if err != nil {
return fmt.Errorf("error creating temporary directory: %w", err)
Expand Down
1 change: 1 addition & 0 deletions internal/directives/git_cloner_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -346,6 +346,7 @@ func Test_gitCloner_runPromotionStep(t *testing.T) {
{
Branch: "stage/dev",
Path: "out",
Create: true,
},
},
},
Expand Down

0 comments on commit ad139d2

Please sign in to comment.