Skip to content
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

WIP: support single comment summary with orchestrator mode #1850

Open
wants to merge 14 commits into
base: develop
Choose a base branch
from
20 changes: 18 additions & 2 deletions backend/controllers/github.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,9 +34,7 @@ import (
"net/http"
"net/url"
"os"
"path/filepath"
"reflect"
"runtime/debug"
"slices"
"strconv"
"strings"
Expand Down Expand Up @@ -430,6 +428,7 @@ func handlePullRequestEvent(gh utils.GithubClientProvider, payload *github.PullR
return fmt.Errorf("error processing event")
}
}

diggerCommand, err := orchestrator_scheduler.GetCommandFromJob(jobsForImpactedProjects[0])
if err != nil {
log.Printf("could not determine digger command from job: %v", jobsForImpactedProjects[0].Commands)
Expand Down Expand Up @@ -523,6 +522,15 @@ func handlePullRequestEvent(gh utils.GithubClientProvider, payload *github.PullR
}

batchId, _, err := utils.ConvertJobsToDiggerJobs(*diggerCommand, models.DiggerVCSGithub, organisationId, impactedJobsMap, impactedProjectsMap, projectsGraph, installationId, branch, prNumber, repoOwner, repoName, repoFullName, commitSha, commentId, diggerYmlStr, 0, aiSummaryCommentId, config.ReportTerraformOutputs)

placeholderComment, err := ghService.PublishComment(prNumber, "digger report placehoder")
if err != nil {
log.Printf("strconv.ParseInt error: %v", err)
commentReporterManager.UpdateComment(fmt.Sprintf(":x: could not create placeholder commentId for report: %v", err))
return fmt.Errorf("comment reporter error: %v", err)
}
Comment on lines +525 to +531
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fix incorrect error message in placeholder comment creation

The error message incorrectly references "strconv.ParseInt" when the error is from publishing a comment.

Apply this fix:

 	placeholderComment, err := ghService.PublishComment(prNumber, "digger report placehoder")
 	if err != nil {
-		log.Printf("strconv.ParseInt error: %v", err)
+		log.Printf("failed to publish placeholder comment: %v", err)
 		commentReporterManager.UpdateComment(fmt.Sprintf(":x: could not create placeholder commentId for report: %v", err))
 		return fmt.Errorf("comment reporter error: %v", err)
 	}
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
placeholderComment, err := ghService.PublishComment(prNumber, "digger report placehoder")
if err != nil {
log.Printf("strconv.ParseInt error: %v", err)
commentReporterManager.UpdateComment(fmt.Sprintf(":x: could not create placeholder commentId for report: %v", err))
return fmt.Errorf("comment reporter error: %v", err)
}
placeholderComment, err := ghService.PublishComment(prNumber, "digger report placehoder")
if err != nil {
log.Printf("failed to publish placeholder comment: %v", err)
commentReporterManager.UpdateComment(fmt.Sprintf(":x: could not create placeholder commentId for report: %v", err))
return fmt.Errorf("comment reporter error: %v", err)
}


batchId, _, err := utils.ConvertJobsToDiggerJobs(*diggerCommand, models.DiggerVCSGithub, organisationId, impactedJobsMap, impactedProjectsMap, projectsGraph, installationId, branch, prNumber, repoOwner, repoName, repoFullName, commitSha, commentId, &placeholderComment.Id, diggerYmlStr, 0)
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Fix redeclaration of batchId variable

The batchId variable is redeclared using := operator when it's already defined. This will cause a compilation error.

-batchId, _, err := utils.ConvertJobsToDiggerJobs(
+batchId, _, err = utils.ConvertJobsToDiggerJobs(

Also applies to: 958-958

🧰 Tools
🪛 golangci-lint (1.62.2)

538-538: no new variables on left side of :=

(typecheck)

Comment on lines +525 to +533
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Extract duplicate placeholder comment logic into a helper function

The placeholder comment creation logic is duplicated between handlePullRequestEvent and handleIssueCommentEvent. This violates the DRY principle.

Extract the logic into a helper function:

func createPlaceholderComment(ghService *dg_github.GithubService, number int, commentReporterManager utils.CommentReporterManager) (*github.IssueComment, error) {
    placeholderComment, err := ghService.PublishComment(number, "digger report placeholder")
    if err != nil {
        log.Printf("failed to publish placeholder comment: %v", err)
        commentReporterManager.UpdateComment(fmt.Sprintf(":x: could not create placeholder commentId for report: %v", err))
        return nil, fmt.Errorf("comment reporter error: %v", err)
    }
    return placeholderComment, nil
}

Also applies to: 942-949

if err != nil {
log.Printf("ConvertJobsToDiggerJobs error: %v", err)
commentReporterManager.UpdateComment(fmt.Sprintf(":x: ConvertJobsToDiggerJobs error: %v", err))
Expand Down Expand Up @@ -931,6 +939,14 @@ func handleIssueCommentEvent(gh utils.GithubClientProvider, payload *github.Issu
}

batchId, _, err := utils.ConvertJobsToDiggerJobs(*diggerCommand, "github", orgId, impactedProjectsJobMap, impactedProjectsMap, projectsGraph, installationId, *branch, issueNumber, repoOwner, repoName, repoFullName, *commitSha, reporterCommentId, diggerYmlStr, 0, aiSummaryCommentId, config.ReportTerraformOutputs)
placeholderComment, err := ghService.PublishComment(issueNumber, "digger report placehoder")
if err != nil {
log.Printf("strconv.ParseInt error: %v", err)
commentReporterManager.UpdateComment(fmt.Sprintf(":x: could not create placeholder commentId for report: %v", err))
return fmt.Errorf("comment reporter error: %v", err)
}
Comment on lines +942 to +947
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

⚠️ Potential issue

Fix incorrect error message and consider refactoring duplicated code

  1. The error message incorrectly references "strconv.ParseInt" when the error is from publishing a comment.
  2. This code block is duplicated from the handlePullRequestEvent function.

First, fix the error message:

 	placeholderComment, err := ghService.PublishComment(issueNumber, "digger report placehoder")
 	if err != nil {
-		log.Printf("strconv.ParseInt error: %v", err)
+		log.Printf("failed to publish placeholder comment: %v", err)
 		commentReporterManager.UpdateComment(fmt.Sprintf(":x: could not create placeholder commentId for report: %v", err))
 		return fmt.Errorf("comment reporter error: %v", err)
 	}

Consider extracting the placeholder comment creation into a shared helper function to avoid code duplication:

func createPlaceholderComment(ghService *dg_github.GithubService, number int, commentReporterManager *utils.CommentReporterManager) (*github.IssueComment, error) {
    placeholderComment, err := ghService.PublishComment(number, "digger report placeholder")
    if err != nil {
        log.Printf("failed to publish placeholder comment: %v", err)
        commentReporterManager.UpdateComment(fmt.Sprintf(":x: could not create placeholder commentId for report: %v", err))
        return nil, fmt.Errorf("comment reporter error: %v", err)
    }
    return placeholderComment, nil
}


batchId, _, err := utils.ConvertJobsToDiggerJobs(*diggerCommand, "github", orgId, impactedProjectsJobMap, impactedProjectsMap, projectsGraph, installationId, *branch, issueNumber, repoOwner, repoName, repoFullName, *commitSha, reporterCommentId, &placeholderComment.Id, diggerYmlStr, 0)
if err != nil {
log.Printf("ConvertJobsToDiggerJobs error: %v", err)
commentReporterManager.UpdateComment(fmt.Sprintf(":x: ConvertJobsToDiggerJobs error: %v", err))
Expand Down
2 changes: 2 additions & 0 deletions backend/migrations/20241204194016.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
-- Modify "digger_batches" table
ALTER TABLE "public"."digger_batches" ADD COLUMN "placeholder_comment_id_for_report" text NULL;
27 changes: 14 additions & 13 deletions backend/models/scheduler.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,20 +22,21 @@ const DiggerVCSGithub DiggerVCSType = "github"
const DiggerVCSGitlab DiggerVCSType = "gitlab"

type DiggerBatch struct {
ID uuid.UUID `gorm:"primary_key"`
VCS DiggerVCSType
PrNumber int
CommentId *int64
ID uuid.UUID `gorm:"primary_key"`
VCS DiggerVCSType
PrNumber int
CommentId *int64
AiSummaryCommentId string
Status orchestrator_scheduler.DiggerBatchStatus
BranchName string
DiggerConfig string
GithubInstallationId int64
GitlabProjectId int
RepoFullName string
RepoOwner string
RepoName string
BatchType orchestrator_scheduler.DiggerCommand
PlaceholderCommentIdForReport *string
Status orchestrator_scheduler.DiggerBatchStatus
BranchName string
DiggerConfig string
GithubInstallationId int64
GitlabProjectId int
RepoFullName string
RepoOwner string
RepoName string
BatchType orchestrator_scheduler.DiggerCommand
ReportTerraformOutputs bool
// used for module source grouping comments
SourceDetails []byte
Expand Down
3 changes: 2 additions & 1 deletion backend/models/storage.go
Original file line number Diff line number Diff line change
Expand Up @@ -617,7 +617,7 @@ func (db *Database) GetDiggerBatch(batchId *uuid.UUID) (*DiggerBatch, error) {
return batch, nil
}

func (db *Database) CreateDiggerBatch(vcsType DiggerVCSType, githubInstallationId int64, repoOwner string, repoName string, repoFullname string, PRNumber int, diggerConfig string, branchName string, batchType scheduler.DiggerCommand, commentId *int64, gitlabProjectId int, aiSummaryCommentId string, reportTerraformOutputs bool) (*DiggerBatch, error) {
func (db *Database) CreateDiggerBatch(vcsType DiggerVCSType, githubInstallationId int64, repoOwner string, repoName string, repoFullname string, PRNumber int, diggerConfig string, branchName string, batchType scheduler.DiggerCommand, commentId *int64, placeholderCommentIdForReport *string, gitlabProjectId int, aiSummaryCommentId string, reportTerraformOutputs bool) (*DiggerBatch, error) {
uid := uuid.New()
batch := &DiggerBatch{
ID: uid,
Expand All @@ -628,6 +628,7 @@ func (db *Database) CreateDiggerBatch(vcsType DiggerVCSType, githubInstallationI
RepoFullName: repoFullname,
PrNumber: PRNumber,
CommentId: commentId,
PlaceholderCommentIdForReport: placeholderCommentIdForReport,
Status: scheduler.BatchJobCreated,
BranchName: branchName,
DiggerConfig: diggerConfig,
Expand Down
6 changes: 3 additions & 3 deletions backend/services/spec.go
Original file line number Diff line number Diff line change
Expand Up @@ -116,9 +116,9 @@ func GetSpecFromJob(job models.DiggerJob) (*spec.Spec, error) {
CommentId: strconv.FormatInt(*batch.CommentId, 10),
Job: jobSpec,
Reporter: spec.ReporterSpec{
ReportingStrategy: "comments_per_run",
ReporterType: "lazy",
ReportTerraformOutput: batch.ReportTerraformOutputs,
ReportingStrategy: "comments_per_run",
ReporterType: "basic",
ReportCommentId: job.Batch.PlaceholderCommentIdForReport,
},
Lock: spec.LockSpec{
LockType: "noop",
Expand Down
4 changes: 2 additions & 2 deletions backend/utils/graphs.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ import (
)

// 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) (*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, placeholderCommentIdForReport *string, diggerConfigStr string, gitlabProjectId int, aiSummaryCommentId string, reportTerraformOutput bool) (*uuid.UUID, map[string]*models.DiggerJob, error) {
result := make(map[string]*models.DiggerJob)
organisation, err := models.DB.GetOrganisationById(organisationId)
if err != nil {
Expand Down Expand Up @@ -43,7 +43,7 @@ func ConvertJobsToDiggerJobs(jobType scheduler.DiggerCommand, vcsType models.Dig

log.Printf("marshalledJobsMap: %v\n", marshalledJobsMap)

batch, err := models.DB.CreateDiggerBatch(vcsType, githubInstallationId, repoOwner, repoName, repoFullName, prNumber, diggerConfigStr, branch, jobType, &commentId, gitlabProjectId, aiSummaryCommentId, reportTerraformOutput)
batch, err := models.DB.CreateDiggerBatch(vcsType, githubInstallationId, repoOwner, repoName, repoFullName, prNumber, diggerConfigStr, branch, jobType, &commentId, placeholderCommentIdForReport, gitlabProjectId, aiSummaryCommentId, reportTerraformOutput)
if err != nil {
return nil, nil, fmt.Errorf("failed to create batch: %v", err)
}
Expand Down
14 changes: 10 additions & 4 deletions cli/cmd/digger/main_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -895,8 +895,11 @@ func TestGitHubNewPullRequestContext(t *testing.T) {
impactedProjects, requestedProject, prNumber, err := dggithub.ProcessGitHubEvent(ghEvent, &diggerConfig, &prManager)

reporter := &reporting.CiReporter{
CiService: &prManager,
PrNumber: prNumber,
CiService: &prManager,
PrNumber: prNumber,
IsSupportMarkdown: true,
IsSuppressed: false,
ReportStrategy: reporting.NewMultipleCommentsStrategy(),
Comment on lines +898 to +902
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

Add test coverage for single comment strategy

The PR aims to support single comment summary, but the test initializes MultipleCommentsStrategy. Consider:

  1. Adding test cases that verify the single comment strategy
  2. Validating the reporting behavior with different strategies
 reporter := &reporting.CiReporter{
 	CiService:         &prManager,
 	PrNumber:          prNumber,
 	IsSupportMarkdown: true,
 	IsSuppressed:      false,
-	ReportStrategy:    reporting.NewMultipleCommentsStrategy(),
+	ReportStrategy:    reporting.NewSingleCommentStrategy(),
 }

+func TestGitHubNewPullRequestContextWithSingleComment(t *testing.T) {
+	// Add test case for single comment strategy
+	// Verify the reporting behavior
+}

Committable suggestion skipped: line range outside the PR's diff.

}

event := context.Event.(github.PullRequestEvent)
Expand All @@ -923,8 +926,11 @@ func TestGitHubNewCommentContext(t *testing.T) {
planStorage := storage.MockPlanStorage{}
impactedProjects, requestedProject, prNumber, err := dggithub.ProcessGitHubEvent(ghEvent, &diggerConfig, &prManager)
reporter := &reporting.CiReporter{
CiService: &prManager,
PrNumber: prNumber,
CiService: &prManager,
PrNumber: prNumber,
ReportStrategy: reporting.NewMultipleCommentsStrategy(),
IsSuppressed: false,
IsSupportMarkdown: true,
}

policyChecker := policy.MockPolicyChecker{}
Expand Down
13 changes: 4 additions & 9 deletions cli/cmd/digger/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@ import (
"log"
"net/http"
"os"
"time"
)

type RunConfig struct {
Expand Down Expand Up @@ -93,15 +92,11 @@ func PreRun(cmd *cobra.Command, args []string) {
//PolicyChecker = policy.NewPolicyChecker(hostName, orgName, token)

if os.Getenv("REPORTING_STRATEGY") == "comments_per_run" || os.Getenv("ACCUMULATE_PLANS") == "true" {
ReportStrategy = &reporting.CommentPerRunStrategy{
TimeOfRun: time.Now(),
}
} else if os.Getenv("REPORTING_STRATEGY") == "latest_run_comment" {
ReportStrategy = &reporting.LatestRunCommentStrategy{
TimeOfRun: time.Now(),
}
strategy := reporting.NewSingleCommentStrategy()
ReportStrategy = &strategy
} else {
ReportStrategy = &reporting.MultipleCommentsStrategy{}
strategy := reporting.NewMultipleCommentsStrategy()
ReportStrategy = &strategy
}

var err error
Expand Down
39 changes: 20 additions & 19 deletions cli/pkg/digger/digger.go
Original file line number Diff line number Diff line change
Expand Up @@ -124,13 +124,14 @@ func RunJobs(jobs []orchestrator.Job, prService ci.PullRequestService, orgServic
}

if allAppliesSuccess == true && reportFinalStatusToBackend == true {
_, jobPrCommentUrl, err := reporter.Flush()
_, jobPrCommentUrls, err := reporter.Flush()
if err != nil {
log.Printf("error while sending job comments %v", err)
return false, false, fmt.Errorf("error while sending job comments %v", err)
}

currentJob := jobs[0]
jobPrCommentUrl := jobPrCommentUrls[0]
Comment on lines +127 to +134
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Add bounds checking for jobPrCommentUrls array

The code assumes jobPrCommentUrls has at least one element. This could lead to a panic if the array is empty.

Add a bounds check before accessing the first element:

 _, jobPrCommentUrls, err := reporter.Flush()
 if err != nil {
     log.Printf("error while sending job comments %v", err)
     return false, false, fmt.Errorf("error while sending job comments %v", err)
 }
+if len(jobPrCommentUrls) == 0 {
+    return false, false, fmt.Errorf("no comment URLs returned from reporter")
+}
 currentJob := jobs[0]
 jobPrCommentUrl := jobPrCommentUrls[0]
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
_, jobPrCommentUrls, err := reporter.Flush()
if err != nil {
log.Printf("error while sending job comments %v", err)
return false, false, fmt.Errorf("error while sending job comments %v", err)
}
currentJob := jobs[0]
jobPrCommentUrl := jobPrCommentUrls[0]
_, jobPrCommentUrls, err := reporter.Flush()
if err != nil {
log.Printf("error while sending job comments %v", err)
return false, false, fmt.Errorf("error while sending job comments %v", err)
}
if len(jobPrCommentUrls) == 0 {
return false, false, fmt.Errorf("no comment URLs returned from reporter")
}
currentJob := jobs[0]
jobPrCommentUrl := jobPrCommentUrls[0]

repoNameForBackendReporting := strings.ReplaceAll(currentJob.Namespace, "/", "-")
projectNameForBackendReporting := currentJob.ProjectName
// TODO: handle the apply result summary as well to report it to backend. Possibly reporting changed resources as well
Expand Down Expand Up @@ -170,12 +171,12 @@ func RunJobs(jobs []orchestrator.Job, prService ci.PullRequestService, orgServic
func reportPolicyError(projectName string, command string, requestedBy string, reporter reporting.Reporter) string {
msg := fmt.Sprintf("User %s is not allowed to perform action: %s. Check your policies :x:", requestedBy, command)
if reporter.SupportsMarkdown() {
_, _, err := reporter.Report(msg, coreutils.AsCollapsibleComment(fmt.Sprintf("Policy violation for <b>%v - %v</b>", projectName, command), false))
err := reporter.Report(projectName, msg, coreutils.AsCollapsibleComment(fmt.Sprintf("Policy violation for <b>%v - %v</b>", projectName, command), false))
if err != nil {
log.Printf("Error publishing comment: %v", err)
}
} else {
_, _, err := reporter.Report(msg, coreutils.AsComment(fmt.Sprintf("Policy violation for %v - %v", projectName, command)))
err := reporter.Report(projectName, msg, coreutils.AsComment(fmt.Sprintf("Policy violation for %v - %v", projectName, command)))
if err != nil {
log.Printf("Error publishing comment: %v", err)
}
Expand Down Expand Up @@ -284,7 +285,7 @@ func run(command string, job orchestrator.Job, policyChecker policy.Checker, org
return nil, msg, fmt.Errorf(msg)
} else if planPerformed {
if isNonEmptyPlan {
reportTerraformPlanOutput(reporter, projectLock.LockId(), plan)
reportTerraformPlanOutput(reporter, job.ProjectName, plan)
planIsAllowed, messages, err := policyChecker.CheckPlanPolicy(SCMrepository, SCMOrganisation, job.ProjectName, job.ProjectDir, planJsonOutput)
if err != nil {
msg := fmt.Sprintf("Failed to validate plan. %v", err)
Expand All @@ -311,7 +312,7 @@ func run(command string, job orchestrator.Job, policyChecker policy.Checker, org
preformattedMessaged = append(preformattedMessaged, fmt.Sprintf(" %v", message))
}
planReportMessage = planReportMessage + strings.Join(preformattedMessaged, "<br>")
_, _, err = reporter.Report(planReportMessage, planPolicyFormatter)
err = reporter.Report(job.ProjectName, planReportMessage, planPolicyFormatter)

if err != nil {
log.Printf("Failed to report plan. %v", err)
Expand All @@ -320,14 +321,14 @@ func run(command string, job orchestrator.Job, policyChecker policy.Checker, org
log.Printf(msg)
return nil, msg, fmt.Errorf(msg)
} else {
_, _, err := reporter.Report("Terraform plan validation checks succeeded :white_check_mark:", planPolicyFormatter)
err := reporter.Report(job.ProjectName, "Terraform plan validation checks succeeded :white_check_mark:", planPolicyFormatter)
if err != nil {
log.Printf("Failed to report plan. %v", err)
}
reportPlanSummary(reporter, planSummary)
reportPlanSummary(job.ProjectName, reporter, planSummary)
}
} else {
reportEmptyPlanOutput(reporter, projectLock.LockId())
reportEmptyPlanOutput(job.ProjectName, reporter, projectLock.LockId())
}
err := prService.SetStatus(*job.PullRequestNumber, "success", job.ProjectName+"/plan")
if err != nil {
Expand Down Expand Up @@ -370,7 +371,7 @@ func run(command string, job orchestrator.Job, policyChecker policy.Checker, org
}
log.Printf("PR status, mergeable: %v, merged: %v and skipMergeCheck %v\n", isMergeable, isMerged, job.SkipMergeCheck)
if !isMergeable && !isMerged && !job.SkipMergeCheck {
comment := reportApplyMergeabilityError(reporter)
comment := reportApplyMergeabilityError(job.ProjectName, reporter)
prService.SetStatus(*job.PullRequestNumber, "failure", job.ProjectName+"/apply")

return nil, comment, fmt.Errorf(comment)
Expand Down Expand Up @@ -491,25 +492,25 @@ func run(command string, job orchestrator.Job, policyChecker policy.Checker, org
return &execution.DiggerExecutorResult{}, "", nil
}

func reportApplyMergeabilityError(reporter reporting.Reporter) string {
func reportApplyMergeabilityError(projectName string, reporter reporting.Reporter) string {
comment := "cannot perform Apply since the PR is not currently mergeable"
log.Println(comment)

if reporter.SupportsMarkdown() {
_, _, err := reporter.Report(comment, coreutils.AsCollapsibleComment("Apply error", false))
err := reporter.Report(projectName, comment, coreutils.AsCollapsibleComment("Apply error", false))
if err != nil {
log.Printf("error publishing comment: %v\n", err)
}
} else {
_, _, err := reporter.Report(comment, coreutils.AsComment("Apply error"))
err := reporter.Report(projectName, comment, coreutils.AsComment("Apply error"))
if err != nil {
log.Printf("error publishing comment: %v\n", err)
}
}
return comment
}

func reportTerraformPlanOutput(reporter reporting.Reporter, projectId string, plan string) {
func reportTerraformPlanOutput(reporter reporting.Reporter, projectName string, plan string) {
var formatter func(string) string

if reporter.SupportsMarkdown() {
Expand All @@ -518,13 +519,13 @@ func reportTerraformPlanOutput(reporter reporting.Reporter, projectId string, pl
formatter = coreutils.GetTerraformOutputAsComment("Plan output")
}

_, _, err := reporter.Report(plan, formatter)
err := reporter.Report(projectName, plan, formatter)
if err != nil {
log.Printf("Failed to report plan. %v", err)
}
}

func reportPlanSummary(reporter reporting.Reporter, summary string) {
func reportPlanSummary(projectName string, reporter reporting.Reporter, summary string) {
var formatter func(string) string

if reporter.SupportsMarkdown() {
Expand All @@ -533,19 +534,19 @@ func reportPlanSummary(reporter reporting.Reporter, summary string) {
formatter = coreutils.AsComment("Plan summary")
}

_, _, err := reporter.Report("\n"+summary, formatter)
err := reporter.Report(projectName, "\n"+summary, formatter)
if err != nil {
log.Printf("Failed to report plan summary. %v", err)
}
}

func reportEmptyPlanOutput(reporter reporting.Reporter, projectId string) {
func reportEmptyPlanOutput(projectName string, reporter reporting.Reporter, projectId string) {
identityFormatter := func(comment string) string {
return comment
}
_, _, err := reporter.Report("→ No changes in terraform output for "+projectId, identityFormatter)
err := reporter.Report(projectName, "→ No changes in terraform output for "+projectId, identityFormatter)
// suppress the comment (if reporter is suppressible)
reporter.Suppress()
reporter.Suppress("")
if err != nil {
log.Printf("Failed to report plan. %v", err)
}
Comment on lines +543 to 552
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue

Handle error return value from reporter.Suppress

The error return value from reporter.Suppress is not checked, which could hide important errors.

Add error handling:

 func reportEmptyPlanOutput(projectName string, reporter reporting.Reporter, projectId string) {
     identityFormatter := func(comment string) string {
         return comment
     }
     err := reporter.Report(projectName, "→ No changes in terraform output for "+projectId, identityFormatter)
-    reporter.Suppress("")
+    if err := reporter.Suppress(""); err != nil {
+        log.Printf("Failed to suppress report: %v", err)
+    }
     if err != nil {
         log.Printf("Failed to report plan. %v", err)
     }
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
func reportEmptyPlanOutput(projectName string, reporter reporting.Reporter, projectId string) {
identityFormatter := func(comment string) string {
return comment
}
_, _, err := reporter.Report("→ No changes in terraform output for "+projectId, identityFormatter)
err := reporter.Report(projectName, "→ No changes in terraform output for "+projectId, identityFormatter)
// suppress the comment (if reporter is suppressible)
reporter.Suppress()
reporter.Suppress("")
if err != nil {
log.Printf("Failed to report plan. %v", err)
}
func reportEmptyPlanOutput(projectName string, reporter reporting.Reporter, projectId string) {
identityFormatter := func(comment string) string {
return comment
}
err := reporter.Report(projectName, "→ No changes in terraform output for "+projectId, identityFormatter)
// suppress the comment (if reporter is suppressible)
if err := reporter.Suppress(""); err != nil {
log.Printf("Failed to suppress report: %v", err)
}
if err != nil {
log.Printf("Failed to report plan. %v", err)
}
🧰 Tools
🪛 golangci-lint (1.62.2)

549-549: Error return value of reporter.Suppress is not checked

(errcheck)

Expand Down
16 changes: 11 additions & 5 deletions cli/pkg/digger/digger_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,12 @@ func (m *MockPRManager) GetApprovals(prNumber int) ([]string, error) {

func (m *MockPRManager) PublishComment(prNumber int, comment string) (*ci.Comment, error) {
m.Commands = append(m.Commands, RunInfo{"PublishComment", strconv.Itoa(prNumber) + " " + comment, time.Now()})
return nil, nil
return &ci.Comment{
Id: "",
DiscussionId: "",
Body: nil,
Url: "",
}, nil
}

func (m *MockPRManager) ListIssues() ([]*ci.Issue, error) {
Expand Down Expand Up @@ -241,16 +246,16 @@ func (m MockPlanPathProvider) LocalPlanFilePath() string {
}

func TestCorrectCommandExecutionWhenApplying(t *testing.T) {

commandRunner := &MockCommandRunner{}
terraformExecutor := &MockTerraformExecutor{}
prManager := &MockPRManager{}
lock := &MockProjectLock{}
planStorage := &MockPlanStorage{}
strategy := reporting.NewMultipleCommentsStrategy()
reporter := &reporting.CiReporter{
CiService: prManager,
PrNumber: 1,
ReportStrategy: &reporting.MultipleCommentsStrategy{},
ReportStrategy: &strategy,
IsSupportMarkdown: true,
}
planPathProvider := &MockPlanPathProvider{}
Expand Down Expand Up @@ -287,7 +292,7 @@ func TestCorrectCommandExecutionWhenApplying(t *testing.T) {

commandStrings := allCommandsInOrderWithParams(terraformExecutor, commandRunner, prManager, lock, planStorage, planPathProvider)

assert.Equal(t, []string{"RetrievePlan plan", "Init ", "Apply ", "PublishComment 1 <details ><summary>Apply output</summary>\n\n```terraform\n\n```\n</details>", "Run echo"}, commandStrings)
assert.Equal(t, []string{"RetrievePlan plan", "Init ", "Apply ", "Run echo"}, commandStrings)
}

func TestCorrectCommandExecutionWhenDestroying(t *testing.T) {
Expand All @@ -297,10 +302,11 @@ func TestCorrectCommandExecutionWhenDestroying(t *testing.T) {
prManager := &MockPRManager{}
lock := &MockProjectLock{}
planStorage := &MockPlanStorage{}
strategy := reporting.NewMultipleCommentsStrategy()
reporter := &reporting.CiReporter{
CiService: prManager,
PrNumber: 1,
ReportStrategy: &reporting.MultipleCommentsStrategy{},
ReportStrategy: &strategy,
}
planPathProvider := &MockPlanPathProvider{}
executor := execution.DiggerExecutor{
Expand Down
Loading
Loading