From 503f375d40fb1fbd458a08c53cecd30e51ba4092 Mon Sep 17 00:00:00 2001 From: Vyom-Yadav Date: Sun, 21 Jan 2024 18:39:59 +0530 Subject: [PATCH] Checkout back to the original branch to reset the filesystem preventing ingest cache from corrupting * The filesystem is shared between remediator and evaluator. Checking out back to the original branch would allow evaluator to access filesystem on the correct branch * The data is technically modified after being cached, but the state of the branch is preserved using git Signed-off-by: Vyom-Yadav --- .../remediate/pull_request/pull_request.go | 27 +++++++++++++++++++ internal/engine/ingester/git/git_test.go | 1 - 2 files changed, 27 insertions(+), 1 deletion(-) diff --git a/internal/engine/actions/remediate/pull_request/pull_request.go b/internal/engine/actions/remediate/pull_request/pull_request.go index 6342b56516..71944ef460 100644 --- a/internal/engine/actions/remediate/pull_request/pull_request.go +++ b/internal/engine/actions/remediate/pull_request/pull_request.go @@ -267,6 +267,16 @@ func (r *Remediator) runGit( return fmt.Errorf("cannot get primary email: %w", err) } + currentHeadReference, err := repo.Head() + if err != nil { + return fmt.Errorf("cannot get current HEAD: %w", err) + } + currHeadName := currentHeadReference.Name() + + // This resets the worktree so we don't corrupt the ingest cache (at least the main/originally-fetched branch). + // This also makes sure, all new remediations check out from main branch rather than prev remediation branch. + defer checkoutToOriginallyFetchedBranch(&logger, wt, currHeadName) + logger.Debug().Str("branch", branchBaseName(title)).Msg("Checking out branch") err = wt.Checkout(&git.CheckoutOptions{ Branch: plumbing.NewBranchReferenceName(branchBaseName(title)), @@ -508,3 +518,20 @@ func getPrimaryEmail(ctx context.Context, cli provifv1.GitHub) (string, error) { return fallback, nil } + +func checkoutToOriginallyFetchedBranch( + logger *zerolog.Logger, + wt *git.Worktree, + originallyFetchedBranch plumbing.ReferenceName, +) { + err := wt.Checkout(&git.CheckoutOptions{ + Branch: originallyFetchedBranch, + }) + if err != nil { + logger.Err(err).Msg( + "unable to checkout to the previous head, this can corrupt the ingest cache, should not happen", + ) + } else { + logger.Info().Msg(fmt.Sprintf("checked out back to %s branch", originallyFetchedBranch)) + } +} diff --git a/internal/engine/ingester/git/git_test.go b/internal/engine/ingester/git/git_test.go index f7ad26c840..75722d89f5 100644 --- a/internal/engine/ingester/git/git_test.go +++ b/internal/engine/ingester/git/git_test.go @@ -11,7 +11,6 @@ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. -// Package rule provides the CLI subcommand for managing rules package git_test