Skip to content

fix: auto_merge not working properly with orchestrator backend #1871

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

Open
wants to merge 7 commits into
base: develop
Choose a base branch
from

Conversation

duy0611
Copy link

@duy0611 duy0611 commented Jan 15, 2025

When running with Digger backend mode, PR is merged when auto_merge is enabled even though not all impacted projects have been applied. This is caused because Digger batch does not have context whether all the needed jobs have been triggered when using digger apply with -p flag.

Unlike in backendless mode, where all the jobs are run sequentially and the parent one does have context if all the impacted projects have been applied, in backend mode jobs are triggered via the Batch one, which does not have this context. This PR addresses the issue by adding one more column to store this context, which will then be used in the subsequent run.

Summary by CodeRabbit

  • New Features

    • Added a new setting to track whether all impacted projects are covered in batch operations, visible in batch-related actions and behaviors.
  • Bug Fixes

    • Improved handling of batch auto-merge conditions to ensure merges only occur when all impacted projects are included.
  • Tests

    • Enhanced test coverage for batch creation and auto-merge scenarios, including new conditions for impacted project coverage.
  • Chores

    • Updated database schema to support the new impacted projects tracking field.
    • Refined internal logic to consistently handle the new batch coverage setting across the platform.

When running with Digger backend mode, PR is merged when `auto_merge`
is enabled even though not all impacted projects have been applied.
This is caused because Digger batch does not have context whether all
the needed jobs have been triggered when using `digger apply` with `-p` flag.
Unlike in backendless mode, where all the jobs are run sequentially and the parent one
does have context if all the impacted projects have been applied, in backend mode
jobs are triggered via the Batch one, which does have this context. This PR addresses
the issue by adding one more column to store this context, which will then be used in the
subsequent run.
Copy link
Contributor

coderabbitai bot commented Jan 15, 2025

Walkthrough

This change introduces a new boolean field, CoverAllImpactedProjects, to the DiggerBatch struct and propagates it throughout the backend job and batch creation flow. The field is added to the database schema, model definitions, and relevant function signatures. Logic for handling pull request and issue comment events is updated to capture and pass this flag, and auto-merge behavior is modified to require that all impacted projects are covered before merging. Tests and function calls are updated accordingly to support the new parameter and to verify the new conditional logic.

Changes

File(s) Change Summary
backend/models/scheduler.go
backend/migrations/20250416152705.sql
Added CoverAllImpactedProjects boolean field to DiggerBatch struct and corresponding nullable boolean column to the digger_batches database table.
backend/models/storage.go
backend/utils/graphs.go
Updated CreateDiggerBatch and ConvertJobsToDiggerJobs function signatures to accept and handle the new coverAllImpactedProjects boolean parameter.
backend/controllers/github.go
ee/backend/controllers/gitlab.go
ee/.../bitbucket.go
ee/backend/hooks/github.go
Updated event handler functions to capture and propagate the coverAllImpactedProjects flag from job conversion functions to batch creation.
backend/controllers/projects.go Modified auto-merge logic in AutomergePRforBatchIfEnabled to require batch.CoverAllImpactedProjects to be true in addition to existing conditions.
backend/controllers/github_test.go
backend/controllers/projects_test.go
backend/models/storage_test.go
backend/tasks/runs_test.go
Updated tests to include the new boolean parameter in function calls and to add/modify test cases verifying behavior based on the CoverAllImpactedProjects flag.
libs/ci/github/github.go Introduced and returned a new coversAllImpactedProjects variable (always true in this diff) from ConvertGithubPullRequestEventToJobs.

Sequence Diagram(s)

sequenceDiagram
    participant EventHandler as Event Handler (GitHub/GitLab/Bitbucket)
    participant JobConverter as Job Conversion Function
    participant Utils as utils.ConvertJobsToDiggerJobs
    participant DB as Database

    EventHandler->>JobConverter: Convert Event to Jobs, get coverAllImpactedProjects
    JobConverter-->>EventHandler: jobs, coverAllImpactedProjects
    EventHandler->>Utils: ConvertJobsToDiggerJobs(..., coverAllImpactedProjects, ...)
    Utils->>DB: CreateDiggerBatch(..., coverAllImpactedProjects, ...)
    DB-->>Utils: DiggerBatch
    Utils-->>EventHandler: DiggerBatch, DiggerJobs
Loading
sequenceDiagram
    participant BatchRunner as Batch Runner
    participant Batch as DiggerBatch
    participant PR as Pull Request

    BatchRunner->>Batch: Check status and type
    BatchRunner->>Batch: Check CoverAllImpactedProjects == true
    alt All conditions met
        BatchRunner->>PR: Auto-merge PR
    else Not all conditions met
        BatchRunner-->>PR: No merge
    end
Loading

Possibly related issues

Possibly related PRs

  • Feat bitbucket support #1890: Both PRs modify ConvertJobsToDiggerJobs and its call sites to include a boolean parameter for covering all impacted projects, directly overlapping in functionality and code changes.

Suggested reviewers

  • motatoes

Poem

In fields of code where diggers roam,
A flag was raised to keep things known—
"Cover all projects!" the rabbits cheer,
Before we merge, let's make it clear.
Now batches wait, their checks complete,
So all our carrots taste so sweet!
🥕

Tip

⚡💬 Agentic Chat (Pro Plan, General Availability)
  • We're introducing multi-step agentic chat in review comments and issue comments, within and outside of PR's. This feature enhances review and issue discussions with the CodeRabbit agentic chat by enabling advanced interactions, including the ability to create pull requests directly from comments and add commits to existing pull requests.
✨ Finishing Touches
  • 📝 Generate Docstrings

🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (10)
backend/controllers/github.go (1)

401-401: Consider reducing parameter passing complexity.

The introduction of coverAllImpactedProjects as an additional return value increases the number of variables passed between functions. Consider grouping related parameters into a struct to enhance code readability and maintainability.

Apply this diff to define a struct and update the function signature:

+type EventConversionResult struct {
+  JobsForImpactedProjects []Job
+  CoverAllImpactedProjects bool
+}

-func ConvertGithubPullRequestEventToJobs(...) ([]Job, bool, error) {
+func ConvertGithubPullRequestEventToJobs(...) (EventConversionResult, error) {

-  jobsForImpactedProjects, coverAllImpactedProjects, err := dg_github.ConvertGithubPullRequestEventToJobs(...)
+  result, err := dg_github.ConvertGithubPullRequestEventToJobs(...)
backend/models/storage_test.go (1)

155-155: Add test cases for the new coverAllImpactedProjects parameter.

The test only verifies batch creation with coverAllImpactedProjects set to true. Consider adding test cases that verify the behavior when this parameter is false to ensure both scenarios work correctly.

Would you like me to help generate additional test cases to cover both scenarios?

backend/tasks/runs_test.go (1)

147-147: Enhance test coverage for batch creation with coverAllImpactedProjects.

The test should verify that the state machine transitions correctly based on the value of coverAllImpactedProjects. Consider adding test cases that cover both true and false scenarios.

Would you like me to help generate additional test cases to verify the state machine behavior with different coverAllImpactedProjects values?

backend/utils/graphs.go (2)

18-18: Consider documenting the new parameter in the function signature.

Add a comment explaining the purpose and impact of the coverAllImpactedProjects parameter to help future maintainers understand its significance.


47-50: Enhance error handling for batch creation.

The error message could be more descriptive. Consider including the value of coverAllImpactedProjects in the error message to help with debugging.

-		return nil, nil, fmt.Errorf("failed to create batch: %v", err)
+		return nil, nil, fmt.Errorf("failed to create batch (coverAllImpactedProjects=%v): %v", coverAllImpactedProjects, err)
ee/backend/hooks/github.go (2)

Line range hint 124-129: Enhance error handling for job conversion.

Consider logging the value of coverAllImpactedProjects when an error occurs to help with debugging.

 	if err != nil {
-		log.Printf("Error converting event to jobs: %v", err)
+		log.Printf("Error converting event to jobs (coverAllImpactedProjects=%v): %v", coverAllImpactedProjects, err)
 		utils.InitCommentReporter(ghService, issueNumber, fmt.Sprintf(":x: Error converting event to jobs: %v", err))
 		return fmt.Errorf("error converting event to jobs")
 	}

Line range hint 155-159: Improve error reporting for job conversion.

The error message in the comment reporter could be more descriptive to help users understand the issue.

 	if err != nil {
 		log.Printf("ConvertJobsToDiggerJobs error: %v", err)
-		utils.InitCommentReporter(ghService, issueNumber, fmt.Sprintf(":x: ConvertJobsToDiggerJobs error: %v", err))
+		utils.InitCommentReporter(ghService, issueNumber, fmt.Sprintf(":x: Failed to process jobs for all impacted projects: %v", err))
 		return fmt.Errorf("error convertingjobs")
 	}
backend/controllers/projects.go (1)

734-734: Simplify boolean comparison and verify auto-merge condition.

The boolean comparison can be simplified. Additionally, the new condition ensures safer auto-merge behavior by requiring all impacted projects to be covered.

Apply this diff to simplify the boolean comparison:

-if batch.Status == orchestrator_scheduler.BatchJobSucceeded && batch.BatchType == orchestrator_scheduler.DiggerCommandApply && batch.CoverAllImpactedProjects == true && automerge == true {
+if batch.Status == orchestrator_scheduler.BatchJobSucceeded && batch.BatchType == orchestrator_scheduler.DiggerCommandApply && batch.CoverAllImpactedProjects && automerge {
🧰 Tools
🪛 golangci-lint (1.62.2)

734-734: S1002: should omit comparison to bool constant, can be simplified to batch.CoverAllImpactedProjects

(gosimple)

backend/controllers/github_test.go (1)

735-735: Add test cases for coverAllImpactedProjects=false.

The test suite only covers scenarios where coverAllImpactedProjects is true. Consider adding test cases that verify the behavior when coverAllImpactedProjects is false, especially for auto-merge scenarios.

Also applies to: 764-764, 797-797, 842-842

ee/backend/controllers/gitlab.go (1)

337-337: Consider improving parameter clarity in ConvertJobsToDiggerJobs.

The function calls have two boolean parameters next to each other (false, coverAllImpactedProjects). This could lead to confusion and potential errors when maintaining the code.

Consider one of these improvements:

  1. Use named parameters or a config struct to make the intent clearer
  2. Reorder parameters to separate the boolean flags
  3. Add comments explaining the purpose of each boolean parameter

Example with a config struct:

type ConversionConfig struct {
    IsForceApply bool
    CoverAllImpactedProjects bool
}

func ConvertJobsToDiggerJobs(
    command scheduler.DiggerCommand,
    // ... other parameters ...
-   forceApply bool,
-   coverAllImpactedProjects bool,
+   config ConversionConfig,
) (uint, error)

Also applies to: 528-528

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 1e88db8 and 3c4e108.

⛔ Files ignored due to path filters (1)
  • backend/migrations/atlas.sum is excluded by !**/*.sum
📒 Files selected for processing (12)
  • backend/controllers/github.go (5 hunks)
  • backend/controllers/github_test.go (5 hunks)
  • backend/controllers/projects.go (2 hunks)
  • backend/controllers/projects_test.go (3 hunks)
  • backend/migrations/20250115155205.sql (1 hunks)
  • backend/models/scheduler.go (2 hunks)
  • backend/models/storage.go (2 hunks)
  • backend/models/storage_test.go (2 hunks)
  • backend/tasks/runs_test.go (2 hunks)
  • backend/utils/graphs.go (2 hunks)
  • ee/backend/controllers/gitlab.go (5 hunks)
  • ee/backend/hooks/github.go (3 hunks)
✅ Files skipped from review due to trivial changes (1)
  • backend/migrations/20250115155205.sql
🧰 Additional context used
🪛 golangci-lint (1.62.2)
backend/controllers/projects.go

734-734: S1002: should omit comparison to bool constant, can be simplified to batch.CoverAllImpactedProjects

(gosimple)

🔇 Additional comments (12)
backend/controllers/github.go (4)

9-20: Necessary imports added.

The added import statements are necessary for the updated functionalities and are correctly included.


526-526: Passing coverAllImpactedProjects appropriately.

Including coverAllImpactedProjects in the call to ConvertJobsToDiggerJobs ensures that the batch creation process is aware of the coverage context.


831-831: Ensure consistent error handling with new return values.

The function generic.ConvertIssueCommentEventToJobs now returns coverAllImpactedProjects. Verify that any errors or exceptions related to this new return value are properly handled downstream to prevent unintended behavior.


934-934: Consistent usage of coverAllImpactedProjects in batch processing.

Passing coverAllImpactedProjects into ConvertJobsToDiggerJobs aligns with the updated logic, ensuring batch creation correctly accounts for all impacted projects.

backend/controllers/projects_test.go (3)

4-6: Import statements consolidated.

Duplicate imports of net/http and testing have been removed, improving code cleanliness.


72-77: Test setup enhanced with new fields.

Added fields such as GithubInstallationId, RepoFullName, RepoOwner, RepoName, BatchType, and CoverAllImpactedProjects provide a more comprehensive context for the tests.


103-113: Extended test coverage for CoverAllImpactedProjects.

The new test case where CoverAllImpactedProjects is set to false effectively verifies the behavior of AutomergePRforBatchIfEnabled when not all impacted projects are covered, ensuring the merge action is appropriately controlled.

backend/models/scheduler.go (1)

6-8: Reorganized import statements.

Moved log and time imports to the top, adhering to Go's import grouping conventions.

backend/models/storage.go (1)

621-640: LGTM! Clean integration of coverage tracking.

The coverAllImpactedProjects field is properly integrated into the batch creation process, maintaining a clean and consistent structure.

ee/backend/controllers/gitlab.go (3)

6-12: LGTM! Import statements are well-organized.

The added standard library imports are necessary for the implemented functionality.


241-241: LGTM! Function call updated to support auto_merge fix.

The addition of coverAllImpactedProjects parameter aligns with the PR objectives to fix auto_merge functionality in backend mode.


484-484: LGTM! Consistent implementation with pull request handling.

The addition of coverAllImpactedProjects parameter maintains consistency with the pull request event handling changes.

RepoName string
BatchType orchestrator_scheduler.DiggerCommand
ReportTerraformOutputs bool
CoverAllImpactedProjects bool
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codebase verification

CoverAllImpactedProjects is not included in serialization

The MapToJsonStruct method in DiggerBatch does not include the CoverAllImpactedProjects field in its serialization output, which could lead to data loss. The field needs to be added to the SerializedBatch struct returned by the method.

🔗 Analysis chain

Verify serialization of CoverAllImpactedProjects.

Ensure that the new field CoverAllImpactedProjects in the DiggerBatch struct is correctly handled during serialization, especially in the MapToJsonStruct method, to prevent data inconsistencies.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Search for serialization of 'CoverAllImpactedProjects' in methods.

# Look for occurrences where DiggerBatch is converted without including 'CoverAllImpactedProjects'.
ast-grep --pattern $'func ($_ *DiggerBatch) MapToJsonStruct() {...}' --json | jq '.captures[] | select(.value | test("CoverAllImpactedProjects")) | .value'

Length of output: 224


Script:

#!/bin/bash
# Find the MapToJsonStruct method implementation and surrounding context
rg -U "func.*MapToJsonStruct.*DiggerBatch" -A 20

# Search for struct definition and JSON tags
rg "CoverAllImpactedProjects.*\`json:" 

# Look for test files that might verify serialization
rg "TestDiggerBatch.*MapToJsonStruct" -l

Length of output: 133


Script:

#!/bin/bash
# Show the content of scheduler.go
cat backend/models/scheduler.go

# Find any JSON-related code in the models directory
rg "json" backend/models/ -A 5 -B 5

# Look for test files in the models directory
fd ".*_test.go" backend/models/

Length of output: 12644

@duy0611 duy0611 changed the title fix: auto_merge not working properly iwith orchestrator backend fix: auto_merge not working properly with orchestrator backend Jan 15, 2025
Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (1)
backend/controllers/projects_test.go (1)

104-113: Consider extracting repeated config to a constant.

While the test case correctly verifies auto-merge behavior when all projects are covered, the digger config string is duplicated multiple times in the test. Consider extracting it to a constant for better maintainability.

+ const autoMergeEnabledConfig = "" +
+   "projects:\n" +
+   "  - name: dev\n" +
+   "    dir: dev\n" +
+   "auto_merge: true"

  func TestAutomergeWhenBatchIsSuccessfulStatus(t *testing.T) {
    // ... existing code ...
-   batch.DiggerConfig = "" +
-     "projects:\n" +
-     "  - name: dev\n" +
-     "    dir: dev\n" +
-     "auto_merge: true"
+   batch.DiggerConfig = autoMergeEnabledConfig
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 3c4e108 and da512e3.

📒 Files selected for processing (1)
  • backend/controllers/projects_test.go (3 hunks)
🔇 Additional comments (3)
backend/controllers/projects_test.go (3)

4-6: Clean import organization looks good!

The consolidation of import statements improves code organization.


99-102: Test case correctly verifies auto-merge prevention.

Good test coverage for the scenario where not all impacted projects are covered, ensuring auto-merge is prevented.


72-77: Verify field initialization aligns with production code.

The addition of CoverAllImpactedProjects and its initialization look good. This change aligns with the PR objectives to fix auto-merge behavior.

Let's verify the field is consistently initialized in production code:

✅ Verification successful

Field initialization and usage verified successfully

The CoverAllImpactedProjects field is consistently used in both production and test code:

  • Used in auto-merge logic alongside other required conditions
  • Test cases cover both true/false scenarios with appropriate assertions
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for CoverAllImpactedProjects initialization patterns
rg -A 3 "CoverAllImpactedProjects.*=.*" --type go

Length of output: 1083

@motatoes
Copy link
Contributor

Hi @duy0611 thanks for much for this PR! Please allow me a few days to review it as im currently loaded with stuff

@motatoes
Copy link
Contributor

hi @duy0611 sorry I just got to start reviewing now! I took a quick look and I have a few small comments:

  • Firstly we need to ensure that the atlas migrations file is in the right order since I think other migrations have been merged since, we would need to delete and regenerate migrations after fixing merge conflicts
  • We need to fix merge conflicts with develop branch unfrotunately!
  • I think some changes from the libs/ folder are missing in this PR, I saw some changes to the signature of ConvertGithubPullRequestEventToJobs function but I don't see the respective changes in the function, could you please review if some changes have not been commited?

@motatoes
Copy link
Contributor

Hi @duy0611 ! unfortunately I came back too late to this PR and now there are merge conflicts. I have reviewed the changes in general and I have some comments:

  • I think some changes to libs/ are not present in this contribution. Could you please that libs/ changes is also in there? Specifically the changes you made to ConvertGithubPullRequestEventToJobs
  • Regarding the migration, I think it needs to be rebased from develop and re-generated to preserve migration fils order!

Looking forward to your updated contribution!

@duy0611
Copy link
Author

duy0611 commented Apr 16, 2025

Hi @motatoes . Thanks for the reviewing. I'll fix the conflict and work on the comments as you have mentioned. Would be great to have this fix in as auto_merge feature is very curcial in our gitops workflow!

duy0611 and others added 2 commits April 16, 2025 14:49
remove unexpected indentation

fix indetation

fix indentation

fix indentation

fix: missing input parameter in CreateDiggerBatch
@duy0611 duy0611 force-pushed the fix/auto-merge-mode-in-batch-type branch from d0c843e to 547f50f Compare April 16, 2025 12:09
@duy0611 duy0611 marked this pull request as draft April 16, 2025 12:18
@duy0611 duy0611 marked this pull request as ready for review April 16, 2025 13:03
Copy link
Contributor

@greptile-apps greptile-apps bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

PR Summary

This PR fixes auto-merge functionality in Digger's backend mode by adding tracking of impacted project coverage before merging PRs.

Key changes:

  • Added cover_all_impacted_projects column to digger_batches table to track complete project coverage
  • Modified AutomergePRforBatchIfEnabled to require both auto_merge enabled AND CoverAllImpactedProjects true
  • Updated job conversion functions across GitHub, GitLab and Bitbucket controllers to pass coverage information
  • Added migration file 20250416152705.sql to add the new column with proper schema tracking
  • Added test cases in projects_test.go to verify auto-merge behavior with the new coverage requirement

The changes ensure PRs only auto-merge after all impacted projects have been properly applied in backend mode.

💡 (1/5) You can manually trigger the bot by mentioning @greptileai in a comment!

15 file(s) reviewed, 2 comment(s)
Edit PR Review Bot Settings | Greptile

@@ -0,0 +1,2 @@
-- Modify "digger_batches" table
ALTER TABLE "public"."digger_batches" ADD COLUMN "cover_all_impacted_projects" boolean NULL;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

style: Consider setting a default value for cover_all_impacted_projects since NULL could lead to ambiguous states

Comment on lines 17 to +18
// ConvertJobsToDiggerJobs jobs is map with project name as a key and a Job as a value
func ConvertJobsToDiggerJobs(jobType scheduler.DiggerCommand, vcsType models.DiggerVCSType, organisationId uint, jobsMap map[string]scheduler.Job, projectMap map[string]configuration.Project, projectsGraph graph.Graph[string, configuration.Project], githubInstallationId int64, branch string, prNumber int, repoOwner string, repoName string, repoFullName string, commitSha string, commentId int64, diggerConfigStr string, gitlabProjectId int, aiSummaryCommentId string, reportTerraformOutput bool, VCSConnectionId *uint) (*uuid.UUID, map[string]*models.DiggerJob, error) {
func ConvertJobsToDiggerJobs(jobType scheduler.DiggerCommand, vcsType models.DiggerVCSType, organisationId uint, jobsMap map[string]scheduler.Job, projectMap map[string]configuration.Project, projectsGraph graph.Graph[string, configuration.Project], githubInstallationId int64, branch string, prNumber int, repoOwner string, repoName string, repoFullName string, commitSha string, commentId int64, diggerConfigStr string, gitlabProjectId int, aiSummaryCommentId string, reportTerraformOutput bool, coverAllImpactedProjects bool, VCSConnectionId *uint) (*uuid.UUID, map[string]*models.DiggerJob, error) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

style: Function signature is getting quite long with 19 parameters. Consider grouping related parameters into a config struct to improve maintainability

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (1)
backend/controllers/projects.go (1)

1386-1389: Important addition of CoverAllImpactedProjects flag for auto-merge condition.

This change ensures that pull requests are only auto-merged when all impacted projects have been successfully applied, which fixes the issue described in the PR objectives. The check prevents PRs from being merged prematurely when some impacted projects haven't been fully processed.

You can simplify the boolean comparison:

-	batch.CoverAllImpactedProjects == true &&
+	batch.CoverAllImpactedProjects &&
🧰 Tools
🪛 golangci-lint (1.64.8)

1388-1388: S1002: should omit comparison to bool constant, can be simplified to batch.CoverAllImpactedProjects

(gosimple)


1389-1389: S1002: should omit comparison to bool constant, can be simplified to automerge

(gosimple)

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 547f50f and fcc924e.

⛔ Files ignored due to path filters (1)
  • backend/migrations/atlas.sum is excluded by !**/*.sum
📒 Files selected for processing (6)
  • backend/controllers/github.go (4 hunks)
  • backend/controllers/github_test.go (4 hunks)
  • backend/controllers/projects.go (1 hunks)
  • backend/migrations/20250416152705.sql (1 hunks)
  • ee/backend/controllers/bitbucket.go (2 hunks)
  • libs/ci/github/github.go (2 hunks)
✅ Files skipped from review due to trivial changes (1)
  • backend/migrations/20250416152705.sql
🚧 Files skipped from review as they are similar to previous changes (2)
  • backend/controllers/github_test.go
  • backend/controllers/github.go
🧰 Additional context used
🧬 Code Graph Analysis (1)
ee/backend/controllers/bitbucket.go (2)
backend/utils/graphs.go (1)
  • ConvertJobsToDiggerJobs (18-191)
backend/models/scheduler.go (1)
  • DiggerVCSBitbucket (24-24)
🪛 golangci-lint (1.64.8)
backend/controllers/projects.go

1388-1388: S1002: should omit comparison to bool constant, can be simplified to batch.CoverAllImpactedProjects

(gosimple)

🔇 Additional comments (4)
libs/ci/github/github.go (2)

445-446: Introduction of coverAllImpactedProjects flag.

A new boolean flag is added to track whether all impacted projects are covered. This is correctly initialized to true by default.


610-610:

✅ Verification successful

Updated return value to include coverage flag.

The function now returns the coversAllImpactedProjects flag instead of a hardcoded true. This provides the necessary context for the auto-merge functionality.

Let's verify that this flag value is properly used in other parts of the codebase:


🏁 Script executed:

#!/bin/bash
# Search for function calls that receive this return value
rg -A 2 "ConvertGithubPullRequestEventToJobs\(" 

Length of output: 4700


Verified: Updated flag usage confirmed.

The updated return value now correctly propagates the coversAllImpactedProjects flag across the codebase. Our search results show that this return value is being appropriately received and handled in multiple locations (e.g., in controllers and integration tests). No discrepancies or issues were found, and the flag is now used to control the auto-merge functionality as intended.

ee/backend/controllers/bitbucket.go (2)

3-16: Import statements reordered.

Standard library imports are now grouped at the top, which follows Go's recommended best practices for import organization.


299-299: Added coverAllImpactedProjects parameter to ConvertJobsToDiggerJobs call.

The function call is updated to pass true for the coverAllImpactedProjects parameter, which is consistent with the changes in other VCS controllers. This ensures that the Bitbucket controller properly contributes to the auto-merge context checking.

@duy0611
Copy link
Author

duy0611 commented Apr 16, 2025

Hi @motatoes . I updated my PR now to reflect your comments. Could you review this PR again? Thank you.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants