From 48bcca59c7560406b55bb03995d88793d483f82b Mon Sep 17 00:00:00 2001 From: Paulo Gomes Date: Fri, 27 May 2022 22:14:38 +0100 Subject: [PATCH] Fix regression on push branches Fixes regression in which IAC will fail to update push branch when the push branch already exists and checkout branch is ahead. The reconciliation errors with: 'cannot push because a reference that you are trying to update on the remote contains commits that are not present locally.' Regression introduced on #330. Signed-off-by: Paulo Gomes --- controllers/imageupdateautomation_controller.go | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/controllers/imageupdateautomation_controller.go b/controllers/imageupdateautomation_controller.go index b80fdee7..801be227 100644 --- a/controllers/imageupdateautomation_controller.go +++ b/controllers/imageupdateautomation_controller.go @@ -735,6 +735,12 @@ var errRemoteBranchMissing = errors.New("remote branch missing") // switchToBranch switches to a branch after fetching latest from upstream. // If the branch does not exist, it is created using the head as the starting point. func switchToBranch(repo *libgit2.Repository, ctx context.Context, branch string, access repoAccess) error { + origin, err := repo.Remotes.Lookup(originRemote) + if err != nil { + return fmt.Errorf("cannot lookup remote: %w", err) + } + defer origin.Free() + callbacks := access.remoteCallbacks(ctx) if managed.Enabled() { // Override callbacks with dummy ones as they are not needed within Managed Transport. @@ -743,6 +749,14 @@ func switchToBranch(repo *libgit2.Repository, ctx context.Context, branch string } branchRef := fmt.Sprintf("origin/%s", branch) + // Force the fetching of the remote branch. + err = origin.Fetch([]string{branch}, &libgit2.FetchOptions{ + RemoteCallbacks: callbacks, + }, "") + if err != nil { + return fmt.Errorf("cannot fetch remote branch: %w", err) + } + remoteBranch, err := repo.LookupBranch(branchRef, libgit2.BranchRemote) if err != nil && !libgit2.IsErrorCode(err, libgit2.ErrorCodeNotFound) { return err