Skip to content

Commit

Permalink
Merge pull request #1478 from diggerhq/feat/override-reporting-strategy
Browse files Browse the repository at this point in the history
Reporting: add project tile in report by digger
  • Loading branch information
ZIJ committed May 16, 2024
2 parents 1f8ae9f + abfe1e6 commit 00125e7
Show file tree
Hide file tree
Showing 8 changed files with 49 additions and 180 deletions.
9 changes: 8 additions & 1 deletion cli/cmd/digger/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -159,10 +159,17 @@ func gitHubCI(lock core_locking.Lock, policyChecker core_policy.Checker, backend

planStorage := newPlanStorage(ghToken, repoOwner, repositoryName, githubActor, job.PullRequestNumber)

log.Printf("Warn: Overriding commenting strategy to Comments-per-run")

strategy := &reporting.CommentPerRunStrategy{
Project: job.ProjectName,
IsPlan: job.IsPlan(),
TimeOfRun: time.Now(),
}
cireporter := &reporting.CiReporter{
CiService: &githubPrService,
PrNumber: *job.PullRequestNumber,
ReportStrategy: reportingStrategy,
ReportStrategy: strategy,
IsSupportMarkdown: true,
}
// using lazy reporter to be able to suppress empty plans
Expand Down
12 changes: 6 additions & 6 deletions cli/pkg/core/execution/execution.go
Original file line number Diff line number Diff line change
Expand Up @@ -271,7 +271,7 @@ func (d DiggerExecutor) Plan() (*terraform.PlanSummary, bool, bool, string, stri

func reportError(r reporting.Reporter, stderr string) {
if r.SupportsMarkdown() {
commentErr := r.Report(stderr, utils.AsCollapsibleComment("Error during init."))
commentErr := r.Report(stderr, utils.AsCollapsibleComment("Error during init.", false))
if commentErr != nil {
log.Printf("error publishing comment: %v", commentErr)
}
Expand Down Expand Up @@ -347,7 +347,7 @@ func (d DiggerExecutor) Apply() (bool, string, error) {

func reportApplyError(r reporting.Reporter, err error) {
if r.SupportsMarkdown() {
commentErr := r.Report(err.Error(), utils.AsCollapsibleComment("Error during applying."))
commentErr := r.Report(err.Error(), utils.AsCollapsibleComment("Error during applying.", false))
if commentErr != nil {
log.Printf("error publishing comment: %v", err)
}
Expand All @@ -362,9 +362,9 @@ func reportApplyError(r reporting.Reporter, err error) {
func reportTerraformApplyOutput(r reporting.Reporter, projectId string, applyOutput string) {
var formatter func(string) string
if r.SupportsMarkdown() {
formatter = utils.GetTerraformOutputAsCollapsibleComment("Apply for <b>" + projectId + "</b>")
formatter = utils.GetTerraformOutputAsCollapsibleComment("Apply output", false)
} else {
formatter = utils.GetTerraformOutputAsComment("Apply for " + projectId)
formatter = utils.GetTerraformOutputAsComment("Apply output")
}

commentErr := r.Report(applyOutput, formatter)
Expand All @@ -375,7 +375,7 @@ func reportTerraformApplyOutput(r reporting.Reporter, projectId string, applyOut

func reportTerraformError(r reporting.Reporter, stderr string) {
if r.SupportsMarkdown() {
commentErr := r.Report(stderr, utils.GetTerraformOutputAsCollapsibleComment("Error during init."))
commentErr := r.Report(stderr, utils.GetTerraformOutputAsCollapsibleComment("Error during init.", false))
if commentErr != nil {
log.Printf("error publishing comment: %v", commentErr)
}
Expand All @@ -390,7 +390,7 @@ func reportTerraformError(r reporting.Reporter, stderr string) {
func reportAdditionalOutput(r reporting.Reporter, projectId string) {
var formatter func(string) string
if r.SupportsMarkdown() {
formatter = utils.GetTerraformOutputAsCollapsibleComment("Additional output for <b>" + projectId + "</b>")
formatter = utils.GetTerraformOutputAsCollapsibleComment("Additional output for <b>"+projectId+"</b>", false)
} else {
formatter = utils.GetTerraformOutputAsComment("Additional output for " + projectId)
}
Expand Down
23 changes: 12 additions & 11 deletions cli/pkg/core/utils/comments.go
Original file line number Diff line number Diff line change
@@ -1,14 +1,16 @@
package utils

func GetTerraformOutputAsCollapsibleComment(summary string) func(string) string {
import "fmt"

func GetTerraformOutputAsCollapsibleComment(summary string, open bool) func(string) string {

return func(comment string) string {
return `<details><summary>` + summary + `</summary>
` + "```terraform" + `
` + comment + `
` + "```" + `
</details>`
return fmt.Sprintf(`<details open="%v"><summary>`+summary+`</summary>
`+"```terraform"+`
`+comment+`
`+"```"+`
</details>`, open)
}
}

Expand All @@ -18,12 +20,11 @@ func GetTerraformOutputAsComment(summary string) func(string) string {
}
}

func AsCollapsibleComment(summary string) func(string) string {

func AsCollapsibleComment(summary string, open bool) func(string) string {
return func(comment string) string {
return `<details><summary>` + summary + `</summary>
return fmt.Sprintf(`<details><summary>` + summary + `</summary>
` + comment + `
</details>`
</details>`)
}
}

Expand Down
10 changes: 5 additions & 5 deletions cli/pkg/digger/digger.go
Original file line number Diff line number Diff line change
Expand Up @@ -171,7 +171,7 @@ func RunJobs(
func reportPolicyError(projectName string, command string, requestedBy string, reporter core_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)))
err := reporter.Report(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)
}
Expand Down Expand Up @@ -287,7 +287,7 @@ func run(command string, job orchestrator.Job, policyChecker policy.Checker, org
var planPolicyFormatter func(report string) string
summary := fmt.Sprintf("Terraform plan validation check (%v)", job.ProjectName)
if reporter.SupportsMarkdown() {
planPolicyFormatter = coreutils.AsCollapsibleComment(summary)
planPolicyFormatter = coreutils.AsCollapsibleComment(summary, false)
} else {
planPolicyFormatter = coreutils.AsComment(summary)
}
Expand Down Expand Up @@ -474,7 +474,7 @@ func reportApplyMergeabilityError(reporter core_reporting.Reporter) string {
log.Println(comment)

if reporter.SupportsMarkdown() {
err := reporter.Report(comment, coreutils.AsCollapsibleComment("Apply error"))
err := reporter.Report(comment, coreutils.AsCollapsibleComment("Apply error", false))
if err != nil {
log.Printf("error publishing comment: %v\n", err)
}
Expand All @@ -491,9 +491,9 @@ func reportTerraformPlanOutput(reporter core_reporting.Reporter, projectId strin
var formatter func(string) string

if reporter.SupportsMarkdown() {
formatter = coreutils.GetTerraformOutputAsCollapsibleComment("Plan for <b>" + projectId + "</b>")
formatter = coreutils.GetTerraformOutputAsCollapsibleComment("Plan output", true)
} else {
formatter = coreutils.GetTerraformOutputAsComment("Plan for " + projectId)
formatter = coreutils.GetTerraformOutputAsComment("Plan output")
}

err := reporter.Report(plan, formatter)
Expand Down
2 changes: 1 addition & 1 deletion cli/pkg/digger/digger_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -276,7 +276,7 @@ func TestCorrectCommandExecutionWhenApplying(t *testing.T) {

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

assert.Equal(t, []string{"RetrievePlan plan", "Init ", "Apply -lock-timeout=3m", "PublishComment 1 <details><summary>Apply for <b>#</b></summary>\n \n```terraform\n\n ```\n</details>", "Run echo"}, commandStrings)
assert.Equal(t, []string{"RetrievePlan plan", "Init ", "Apply -lock-timeout=3m", "PublishComment 1 <details open=\"false\"><summary>Apply output</summary>\n\n```terraform\n\n```\n</details>", "Run echo"}, commandStrings)
}

func TestCorrectCommandExecutionWhenDestroying(t *testing.T) {
Expand Down
6 changes: 3 additions & 3 deletions cli/pkg/locking/locking.go
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,7 @@ func (projectLock *PullRequestLock) Lock() (bool, error) {

func reportingLockingSuccess(r reporting.Reporter, comment string) {
if r.SupportsMarkdown() {
err := r.Report(comment, utils.AsCollapsibleComment("Locking successful"))
err := r.Report(comment, utils.AsCollapsibleComment("Locking successful", false))
if err != nil {
log.Println("failed to publish comment: " + err.Error())
}
Expand All @@ -111,7 +111,7 @@ func reportingLockingSuccess(r reporting.Reporter, comment string) {

func reportLockingFailed(r reporting.Reporter, comment string) {
if r.SupportsMarkdown() {
err := r.Report(comment, utils.AsCollapsibleComment("Locking failed"))
err := r.Report(comment, utils.AsCollapsibleComment("Locking failed", false))
if err != nil {
log.Println("failed to publish comment: " + err.Error())
}
Expand Down Expand Up @@ -183,7 +183,7 @@ func (projectLock *PullRequestLock) Unlock() (bool, error) {

func reportSuccessfulUnlocking(r reporting.Reporter, comment string) {
if r.SupportsMarkdown() {
err := r.Report(comment, utils.AsCollapsibleComment("Unlocking successful"))
err := r.Report(comment, utils.AsCollapsibleComment("Unlocking successful", false))
if err != nil {
log.Println("failed to publish comment: " + err.Error())
}
Expand Down
17 changes: 14 additions & 3 deletions cli/pkg/reporting/reporting.go
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,8 @@ type ReportStrategy interface {
}

type CommentPerRunStrategy struct {
IsPlan bool
Project string
TimeOfRun time.Time
}

Expand All @@ -111,7 +113,16 @@ func (strategy *CommentPerRunStrategy) Report(ciService orchestrator.PullRequest
return fmt.Errorf("error getting comments: %v", err)
}

reportTitle := "Digger run report at " + strategy.TimeOfRun.Format("2006-01-02 15:04:05 (MST)")
var reportTitle string
if strategy.Project != "" {
if strategy.IsPlan {
reportTitle = fmt.Sprintf("Plan for %v (%v)", strategy.Project, strategy.TimeOfRun.Format("2006-01-02 15:04:05 (MST)"))
} else {
reportTitle = fmt.Sprintf("Apply for %v (%v)", strategy.Project, strategy.TimeOfRun.Format("2006-01-02 15:04:05 (MST)"))
}
} else {
reportTitle = "Digger run report at " + strategy.TimeOfRun.Format("2006-01-02 15:04:05 (MST)")
}
return upsertComment(ciService, PrNumber, report, reportFormatter, comments, reportTitle, supportsCollapsibleComment)
}

Expand All @@ -132,7 +143,7 @@ func upsertComment(ciService orchestrator.PullRequestService, PrNumber int, repo
if !supportsCollapsible {
comment = utils.AsComment(reportTitle)(report)
} else {
comment = utils.AsCollapsibleComment(reportTitle)(report)
comment = utils.AsCollapsibleComment(reportTitle, false)(report)
}
_, err := ciService.PublishComment(PrNumber, comment)
if err != nil {
Expand All @@ -152,7 +163,7 @@ func upsertComment(ciService orchestrator.PullRequestService, PrNumber int, repo
if !supportsCollapsible {
completeComment = utils.AsComment(reportTitle)(commentBody)
} else {
completeComment = utils.AsCollapsibleComment(reportTitle)(commentBody)
completeComment = utils.AsCollapsibleComment(reportTitle, false)(commentBody)
}

err := ciService.EditComment(PrNumber, commentIdForThisRun, completeComment)
Expand Down
150 changes: 0 additions & 150 deletions cli/pkg/reporting/reporting_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,159 +2,9 @@ package reporting

import (
"fmt"
"testing"
"time"

"github.com/diggerhq/digger/cli/pkg/core/utils"
"github.com/diggerhq/digger/libs/orchestrator"

"github.com/stretchr/testify/assert"
)

func TestCommentPerRunStrategyReport(t *testing.T) {
timeOfRun := time.Now()
strategy := CommentPerRunStrategy{
TimeOfRun: timeOfRun,
}
existingCommentForOtherRun := utils.AsCollapsibleComment("Digger run report at some other time")("")

prNumber := 1
ciService := &MockCiService{
CommentsPerPr: map[int][]*orchestrator.Comment{
prNumber: {
{
Id: 1,
Body: &existingCommentForOtherRun,
},
},
},
}

report := "resource \"null_resource\" \"test\" {}"
reportFormatter := utils.GetTerraformOutputAsCollapsibleComment("run1")
err := strategy.Report(ciService, prNumber, report, reportFormatter, true)
if err != nil {
t.Errorf("Error: %v", err)
}
report2 := "resource \"null_resource\" \"test\" {}"
reportFormatter2 := utils.GetTerraformOutputAsCollapsibleComment("run2")
err = strategy.Report(ciService, prNumber, report2, reportFormatter2, true)
if err != nil {
t.Errorf("Error: %v", err)
}
report3 := "resource \"null_resource\" \"test\" {}"
reportFormatter3 := utils.GetTerraformOutputAsCollapsibleComment("run3")
err = strategy.Report(ciService, prNumber, report3, reportFormatter3, true)
if err != nil {
t.Errorf("Error: %v", err)
}
report4 := "resource \"null_resource\" \"test\" {}"
reportFormatter4 := utils.GetTerraformOutputAsCollapsibleComment("run4")
err = strategy.Report(ciService, prNumber, report4, reportFormatter4, true)

if err != nil {
t.Errorf("Error: %v", err)
}

assert.Equal(t, 2, len(ciService.CommentsPerPr[prNumber]))
assert.Equal(t, "<details><summary>Digger run report at "+timeOfRun.Format("2006-01-02 15:04:05 (MST)")+"</summary>\n <details><summary>run1</summary>\n \n```terraform\nresource \"null_resource\" \"test\" {}\n ```\n</details>\n\n<details><summary>run2</summary>\n \n```terraform\nresource \"null_resource\" \"test\" {}\n ```\n</details>\n\n\n<details><summary>run3</summary>\n \n```terraform\nresource \"null_resource\" \"test\" {}\n ```\n</details>\n\n\n<details><summary>run4</summary>\n \n```terraform\nresource \"null_resource\" \"test\" {}\n ```\n</details>\n\n</details>", *ciService.CommentsPerPr[prNumber][1].Body)
}

func TestLatestCommentStrategyReport(t *testing.T) {
timeOfRun := time.Now()
strategy := LatestRunCommentStrategy{
TimeOfRun: timeOfRun,
}
existingCommentForOtherRun := utils.AsCollapsibleComment("Digger run report at some other time")("")

prNumber := 1
ciService := &MockCiService{
CommentsPerPr: map[int][]*orchestrator.Comment{
prNumber: {
{
Id: 1,
Body: &existingCommentForOtherRun,
},
},
},
}

report := "resource \"null_resource\" \"test\" {}"
reportFormatter := utils.GetTerraformOutputAsCollapsibleComment("run1")
err := strategy.Report(ciService, prNumber, report, reportFormatter, true)
if err != nil {
t.Errorf("Error: %v", err)
}
report2 := "resource \"null_resource\" \"test\" {}"
reportFormatter2 := utils.GetTerraformOutputAsCollapsibleComment("run2")
err = strategy.Report(ciService, prNumber, report2, reportFormatter2, true)
if err != nil {
t.Errorf("Error: %v", err)
}
report3 := "resource \"null_resource\" \"test\" {}"
reportFormatter3 := utils.GetTerraformOutputAsCollapsibleComment("run3")
err = strategy.Report(ciService, prNumber, report3, reportFormatter3, true)
if err != nil {
t.Errorf("Error: %v", err)
}
report4 := "resource \"null_resource\" \"test\" {}"
reportFormatter4 := utils.GetTerraformOutputAsCollapsibleComment("run4")
err = strategy.Report(ciService, prNumber, report4, reportFormatter4, true)

if err != nil {
t.Errorf("Error: %v", err)
}

assert.Equal(t, 2, len(ciService.CommentsPerPr[prNumber]))
assert.Equal(t, "<details><summary>Digger latest run report</summary>\n <details><summary>run1</summary>\n \n```terraform\nresource \"null_resource\" \"test\" {}\n ```\n</details>\n\n<details><summary>run2</summary>\n \n```terraform\nresource \"null_resource\" \"test\" {}\n ```\n</details>\n\n\n<details><summary>run3</summary>\n \n```terraform\nresource \"null_resource\" \"test\" {}\n ```\n</details>\n\n\n<details><summary>run4</summary>\n \n```terraform\nresource \"null_resource\" \"test\" {}\n ```\n</details>\n\n</details>", *ciService.CommentsPerPr[prNumber][1].Body)
}

func TestMultipleCommentStrategyReport(t *testing.T) {
strategy := MultipleCommentsStrategy{}
existingCommentForOtherRun := utils.AsCollapsibleComment("Digger run report at some other time")("")

prNumber := 1
ciService := &MockCiService{
CommentsPerPr: map[int][]*orchestrator.Comment{
prNumber: {
{
Id: 1,
Body: &existingCommentForOtherRun,
},
},
},
}

report := "resource \"null_resource\" \"test\" {}"
reportFormatter := utils.GetTerraformOutputAsCollapsibleComment("run1")
err := strategy.Report(ciService, prNumber, report, reportFormatter, true)
if err != nil {
t.Errorf("Error: %v", err)
}
report2 := "resource \"null_resource\" \"test\" {}"
reportFormatter2 := utils.GetTerraformOutputAsCollapsibleComment("run2")
err = strategy.Report(ciService, prNumber, report2, reportFormatter2, true)
if err != nil {
t.Errorf("Error: %v", err)
}
report3 := "resource \"null_resource\" \"test\" {}"
reportFormatter3 := utils.GetTerraformOutputAsCollapsibleComment("run3")
err = strategy.Report(ciService, prNumber, report3, reportFormatter3, true)
if err != nil {
t.Errorf("Error: %v", err)
}
report4 := "resource \"null_resource\" \"test\" {}"
reportFormatter4 := utils.GetTerraformOutputAsCollapsibleComment("run4")
err = strategy.Report(ciService, prNumber, report4, reportFormatter4, true)

if err != nil {
t.Errorf("Error: %v", err)
}

assert.Equal(t, 5, len(ciService.CommentsPerPr[prNumber]))
assert.Equal(t, "<details><summary>run4</summary>\n \n```terraform\nresource \"null_resource\" \"test\" {}\n ```\n</details>", *ciService.CommentsPerPr[prNumber][4].Body)
}

type MockCiService struct {
CommentsPerPr map[int][]*orchestrator.Comment
}
Expand Down

0 comments on commit 00125e7

Please sign in to comment.