diff --git a/.golangci.yml b/.golangci.yml
new file mode 100644
index 000000000..aedeaa770
--- /dev/null
+++ b/.golangci.yml
@@ -0,0 +1,21 @@
+# See for configurations: https://golangci-lint.run/usage/configuration/
+version: 2
+# See: https://golangci-lint.run/usage/formatters/
+formatters:
+ default: none
+ enable:
+ - gofmt # https://pkg.go.dev/cmd/gofmt
+ - gofumpt # https://github.com/mvdan/gofumpt
+ - goimports # https://pkg.go.dev/golang.org/x/tools/cmd/goimports
+
+ settings:
+ gofmt:
+ simplify: true # Simplify code: gofmt with `-s` option.
+
+ gofumpt:
+ # Module path which contains the source code being formatted.
+ # Default: ""
+ module-path: github.com/diggerhq/digger # Should match with module in go.mod
+ # Choose whether to use the extra rules.
+ # Default: false
+ extra-rules: true
diff --git a/backend/bootstrap/main.go b/backend/bootstrap/main.go
index e4203afa9..31af388f7 100644
--- a/backend/bootstrap/main.go
+++ b/backend/bootstrap/main.go
@@ -11,6 +11,7 @@ import (
"path/filepath"
"runtime"
"runtime/pprof"
+ "time"
"github.com/diggerhq/digger/backend/config"
"github.com/diggerhq/digger/backend/segment"
@@ -18,8 +19,6 @@ import (
pprof_gin "github.com/gin-contrib/pprof"
sloggin "github.com/samber/slog-gin"
- "time"
-
"github.com/diggerhq/digger/backend/controllers"
"github.com/diggerhq/digger/backend/middleware"
"github.com/diggerhq/digger/backend/models"
@@ -38,7 +37,7 @@ func setupProfiler(r *gin.Engine) {
pprof_gin.Register(r)
// Create profiles directory if it doesn't exist
- if err := os.MkdirAll("/tmp/profiles", 0755); err != nil {
+ if err := os.MkdirAll("/tmp/profiles", 0o755); err != nil {
slog.Error("Failed to create profiles directory", "error", err)
panic(err)
}
@@ -115,7 +114,7 @@ func Bootstrap(templates embed.FS, diggerController controllers.DiggerController
slog.Error("Sentry initialization failed", "error", err)
}
- //database migrations
+ // database migrations
models.ConnectDatabase()
r := gin.Default()
diff --git a/backend/ci_backends/ci_backends.go b/backend/ci_backends/ci_backends.go
index e366951a7..1af25f427 100644
--- a/backend/ci_backends/ci_backends.go
+++ b/backend/ci_backends/ci_backends.go
@@ -6,7 +6,7 @@ import (
)
type CiBackend interface {
- TriggerWorkflow(spec spec.Spec, runName string, vcsToken string) error
+ TriggerWorkflow(spec spec.Spec, runName, vcsToken string) error
GetWorkflowUrl(spec spec.Spec) (string, error)
}
diff --git a/backend/ci_backends/github_actions.go b/backend/ci_backends/github_actions.go
index 528d17e97..abc26f298 100644
--- a/backend/ci_backends/github_actions.go
+++ b/backend/ci_backends/github_actions.go
@@ -16,7 +16,7 @@ type GithubActionCi struct {
Client *github.Client
}
-func (g GithubActionCi) TriggerWorkflow(spec spec.Spec, runName string, vcsToken string) error {
+func (g GithubActionCi) TriggerWorkflow(spec spec.Spec, runName, vcsToken string) error {
slog.Info("TriggerGithubWorkflow", "repoOwner", spec.VCS.RepoOwner, "repoName", spec.VCS.RepoName, "commentId", spec.CommentId)
client := g.Client
specBytes, err := json.Marshal(spec)
diff --git a/backend/config/config.go b/backend/config/config.go
index 99e9c25f7..709f7a8e8 100644
--- a/backend/config/config.go
+++ b/backend/config/config.go
@@ -1,11 +1,12 @@
package config
import (
- "github.com/spf13/cast"
"os"
"strings"
"time"
+ "github.com/spf13/cast"
+
"github.com/spf13/viper"
)
diff --git a/backend/controllers/activity.go b/backend/controllers/activity.go
index 567c36713..a48ba3e7f 100644
--- a/backend/controllers/activity.go
+++ b/backend/controllers/activity.go
@@ -3,11 +3,12 @@ package controllers
import (
"errors"
"fmt"
+ "net/http"
+
"github.com/diggerhq/digger/backend/middleware"
"github.com/diggerhq/digger/backend/models"
"github.com/gin-gonic/gin"
"gorm.io/gorm"
- "net/http"
)
func GetActivity(c *gin.Context) {
diff --git a/backend/controllers/billing.go b/backend/controllers/billing.go
index 79943e451..261637f07 100644
--- a/backend/controllers/billing.go
+++ b/backend/controllers/billing.go
@@ -2,12 +2,13 @@ package controllers
import (
"errors"
+ "log/slog"
+ "net/http"
+
"github.com/diggerhq/digger/backend/middleware"
"github.com/diggerhq/digger/backend/models"
"github.com/gin-gonic/gin"
"gorm.io/gorm"
- "log/slog"
- "net/http"
)
func BillingStatusApi(c *gin.Context) {
diff --git a/backend/controllers/cache.go b/backend/controllers/cache.go
index 8f519fd03..a9749ee89 100644
--- a/backend/controllers/cache.go
+++ b/backend/controllers/cache.go
@@ -2,13 +2,14 @@ package controllers
import (
"fmt"
- "github.com/diggerhq/digger/libs/git_utils"
"log/slog"
"net/http"
"os"
"path"
"strings"
+ "github.com/diggerhq/digger/libs/git_utils"
+
"github.com/diggerhq/digger/backend/models"
"github.com/diggerhq/digger/backend/utils"
dg_configuration "github.com/diggerhq/digger/libs/digger_config"
@@ -78,7 +79,6 @@ func (d DiggerController) UpdateRepoCache(c *gin.Context) {
}
return nil
})
-
if err != nil {
slog.Error("Could not load digger config", "error", err)
return
diff --git a/backend/controllers/github.go b/backend/controllers/github.go
index 3fa638900..08e4d9132 100644
--- a/backend/controllers/github.go
+++ b/backend/controllers/github.go
@@ -6,7 +6,6 @@ import (
"encoding/json"
"errors"
"fmt"
- "github.com/diggerhq/digger/libs/git_utils"
"log/slog"
"math/rand"
"net/http"
@@ -20,6 +19,8 @@ import (
"strings"
"time"
+ "github.com/diggerhq/digger/libs/git_utils"
+
"github.com/diggerhq/digger/backend/ci_backends"
config2 "github.com/diggerhq/digger/backend/config"
"github.com/diggerhq/digger/backend/locking"
@@ -289,7 +290,7 @@ func (d DiggerController) GithubSetupExchangeCode(c *gin.Context) {
})
}
-func createOrGetDiggerRepoForGithubRepo(ghRepoFullName string, ghRepoOrganisation string, ghRepoName string, ghRepoUrl string, installationId int64, appId int64, defaultBranch string, cloneUrl string) (*models.Repo, *models.Organisation, error) {
+func createOrGetDiggerRepoForGithubRepo(ghRepoFullName, ghRepoOrganisation, ghRepoName, ghRepoUrl string, installationId, appId int64, defaultBranch, cloneUrl string) (*models.Repo, *models.Organisation, error) {
slog.Info("Creating or getting Digger repo for GitHub repo",
slog.Group("githubRepo",
slog.String("fullName", ghRepoFullName),
@@ -416,7 +417,6 @@ func handlePushEvent(gh utils.GithubClientProvider, payload *github.PushEvent, a
loadProjectsOnPush := os.Getenv("DIGGER_LOAD_PROJECTS_ON_PUSH")
if loadProjectsOnPush == "true" {
-
if strings.HasSuffix(ref, defaultBranch) {
slog.Debug("Loading projects from GitHub repo (push event)", "loadProjectsOnPush", loadProjectsOnPush, "ref", ref, "defaultBranch", defaultBranch)
err := services.LoadProjectsFromGithubRepo(gh, strconv.FormatInt(installationId, 10), repoFullName, repoOwner, repoName, cloneURL, defaultBranch)
@@ -737,7 +737,7 @@ func handlePullRequestEvent(gh utils.GithubClientProvider, payload *github.PullR
commentReporterManager.UpdateComment(fmt.Sprintf(":x: could not handle commentId: %v", err))
}
- var aiSummaryCommentId = ""
+ aiSummaryCommentId := ""
if config.Reporting.AiSummary {
slog.Info("Creating AI summary comment", "prNumber", prNumber)
aiSummaryComment, err := ghService.PublishComment(prNumber, "AI Summary will be posted here after completion")
@@ -894,7 +894,7 @@ func handlePullRequestEvent(gh utils.GithubClientProvider, payload *github.PullR
return nil
}
-func GetDiggerConfigForBranch(gh utils.GithubClientProvider, installationId int64, repoFullName string, repoOwner string, repoName string, cloneUrl string, branch string, changedFiles []string) (string, *dg_github.GithubService, *dg_configuration.DiggerConfig, graph.Graph[string, dg_configuration.Project], error) {
+func GetDiggerConfigForBranch(gh utils.GithubClientProvider, installationId int64, repoFullName, repoOwner, repoName, cloneUrl, branch string, changedFiles []string) (string, *dg_github.GithubService, *dg_configuration.DiggerConfig, graph.Graph[string, dg_configuration.Project], error) {
slog.Info("Getting Digger config for branch",
slog.Group("repository",
slog.String("fullName", repoFullName),
@@ -944,7 +944,6 @@ func GetDiggerConfigForBranch(gh utils.GithubClientProvider, installationId int6
}
return nil
})
-
if err != nil {
slog.Error("Error cloning and loading config",
"repoFullName", repoFullName,
@@ -969,7 +968,7 @@ func GetDiggerConfigForBranch(gh utils.GithubClientProvider, installationId int6
}
// TODO: Refactor this func to receive ghService as input
-func getDiggerConfigForPR(gh utils.GithubClientProvider, orgId uint, prLabels []string, installationId int64, repoFullName string, repoOwner string, repoName string, cloneUrl string, prNumber int) (string, *dg_github.GithubService, *dg_configuration.DiggerConfig, graph.Graph[string, dg_configuration.Project], *string, *string, []string, error) {
+func getDiggerConfigForPR(gh utils.GithubClientProvider, orgId uint, prLabels []string, installationId int64, repoFullName, repoOwner, repoName, cloneUrl string, prNumber int) (string, *dg_github.GithubService, *dg_configuration.DiggerConfig, graph.Graph[string, dg_configuration.Project], *string, *string, []string, error) {
slog.Info("Getting Digger config for PR",
slog.Group("repository",
slog.String("fullName", repoFullName),
@@ -1130,7 +1129,7 @@ func retrieveConfigFromCache(orgId uint, repoFullName string) (string, *dg_confi
return repoCache.DiggerYmlStr, &config, &projectsGraph, nil
}
-func GetRepoByInstllationId(installationId int64, repoOwner string, repoName string) (*models.Repo, error) {
+func GetRepoByInstllationId(installationId int64, repoOwner, repoName string) (*models.Repo, error) {
slog.Debug("Getting repo by installation ID",
"installationId", installationId,
"repoOwner", repoOwner,
@@ -1544,7 +1543,7 @@ func handleIssueCommentEvent(gh utils.GithubClientProvider, payload *github.Issu
return fmt.Errorf("comment reporter error: %v", err)
}
- var aiSummaryCommentId = ""
+ aiSummaryCommentId := ""
if config.Reporting.AiSummary {
slog.Info("Creating AI summary comment", "issueNumber", issueNumber)
aiSummaryComment, err := ghService.PublishComment(issueNumber, "AI Summary will be posted here after completion")
@@ -1725,7 +1724,7 @@ func handleIssueCommentEvent(gh utils.GithubClientProvider, payload *github.Issu
return nil
}
-func GenerateTerraformFromCode(payload *github.IssueCommentEvent, commentReporterManager utils.CommentReporterManager, config *dg_configuration.DiggerConfig, defaultBranch string, ghService *dg_github.GithubService, repoOwner string, repoName string, commitSha *string, issueNumber int, branch *string) error {
+func GenerateTerraformFromCode(payload *github.IssueCommentEvent, commentReporterManager utils.CommentReporterManager, config *dg_configuration.DiggerConfig, defaultBranch string, ghService *dg_github.GithubService, repoOwner, repoName string, commitSha *string, issueNumber int, branch *string) error {
if !strings.HasPrefix(*payload.Comment.Body, "digger generate") {
return nil
}
@@ -2009,7 +2008,7 @@ func GenerateTerraformFromCode(payload *github.IssueCommentEvent, commentReporte
return nil
}
-func TriggerDiggerJobs(ciBackend ci_backends.CiBackend, repoFullName string, repoOwner string, repoName string, batchId *uuid.UUID, prNumber int, prService ci.PullRequestService, gh utils.GithubClientProvider) error {
+func TriggerDiggerJobs(ciBackend ci_backends.CiBackend, repoFullName, repoOwner, repoName string, batchId *uuid.UUID, prNumber int, prService ci.PullRequestService, gh utils.GithubClientProvider) error {
slog.Info("Triggering Digger jobs for batch",
"batchId", batchId,
slog.Group("repository",
@@ -2323,7 +2322,7 @@ jobs:
func (d DiggerController) GithubAppCallbackPage(c *gin.Context) {
installationId := c.Request.URL.Query()["installation_id"][0]
- //setupAction := c.Request.URL.Query()["setup_action"][0]
+ // setupAction := c.Request.URL.Query()["setup_action"][0]
code := c.Request.URL.Query()["code"][0]
appId := c.Request.URL.Query().Get("state")
@@ -2663,7 +2662,7 @@ func (d DiggerController) GithubReposPage(c *gin.Context) {
// why this validation is needed: https://roadie.io/blog/avoid-leaking-github-org-data/
// validation based on https://docs.github.com/en/apps/creating-github-apps/authenticating-with-a-github-app/generating-a-user-access-token-for-a-github-app , step 3
-func validateGithubCallback(githubClientProvider utils.GithubClientProvider, clientId string, clientSecret string, code string, installationId int64) (bool, *github.Installation, error) {
+func validateGithubCallback(githubClientProvider utils.GithubClientProvider, clientId, clientSecret, code string, installationId int64) (bool, *github.Installation, error) {
slog.Debug("Validating GitHub callback",
"clientId", clientId,
"installationId", installationId,
diff --git a/backend/controllers/github_api.go b/backend/controllers/github_api.go
index ea58ea056..8bc29ec44 100644
--- a/backend/controllers/github_api.go
+++ b/backend/controllers/github_api.go
@@ -49,7 +49,6 @@ func LinkGithubInstallationToOrgApi(c *gin.Context) {
}
link, err := models.DB.GetGithubAppInstallationLink(installationId)
-
if err != nil {
slog.Error("Could not get installation link", "installationId", installationId, "error", err)
c.JSON(http.StatusInternalServerError, gin.H{"status": "Could not get installation link"})
diff --git a/backend/controllers/helpers.go b/backend/controllers/helpers.go
index 4d1e7aa38..3c6bcef6e 100644
--- a/backend/controllers/helpers.go
+++ b/backend/controllers/helpers.go
@@ -1,8 +1,9 @@
package controllers
import (
- "github.com/gin-gonic/gin"
"net/http"
+
+ "github.com/gin-gonic/gin"
)
func Home(c *gin.Context) {
diff --git a/backend/controllers/orgs.go b/backend/controllers/orgs.go
index cd386e704..3c47335eb 100644
--- a/backend/controllers/orgs.go
+++ b/backend/controllers/orgs.go
@@ -4,13 +4,14 @@ import (
"encoding/json"
"errors"
"fmt"
- "github.com/diggerhq/digger/backend/middleware"
- "gorm.io/gorm"
"log/slog"
"net/http"
"os"
"strings"
+ "github.com/diggerhq/digger/backend/middleware"
+ "gorm.io/gorm"
+
"github.com/diggerhq/digger/backend/models"
"github.com/gin-gonic/gin"
"github.com/golang-jwt/jwt"
@@ -180,7 +181,6 @@ func AssociateTenantIdToDiggerOrg(c *gin.Context) {
slog.Debug("Processing JWT claims", "name", nameStr, "tenantId", tenantIdStr)
org, err := models.DB.GetOrganisation(tenantId)
-
if err != nil {
slog.Error("Failed to get organisation by tenantId", "tenantId", tenantIdStr, "error", err)
c.AbortWithStatus(http.StatusInternalServerError)
diff --git a/backend/controllers/policies.go b/backend/controllers/policies.go
index fed19a455..d3a84778f 100644
--- a/backend/controllers/policies.go
+++ b/backend/controllers/policies.go
@@ -176,7 +176,6 @@ func upsertPolicyForOrg(c *gin.Context, policyType string) {
Type: policyType,
Policy: string(policyData),
}).Error
-
if err != nil {
slog.Error("Error creating policy", "organisation", organisation, "policyType", policyType, "error", err)
c.String(http.StatusInternalServerError, "Error creating policy")
@@ -317,7 +316,6 @@ func IssueAccessTokenForOrg(c *gin.Context) {
OrganisationID: org.ID,
Type: models.AccessPolicyType,
}).Error
-
if err != nil {
slog.Error("Error creating token", "orgId", org.ID, "error", err)
c.String(http.StatusInternalServerError, "Unexpected error")
@@ -329,7 +327,6 @@ func IssueAccessTokenForOrg(c *gin.Context) {
}
func loadDiggerConfig(configYaml *dg_configuration.DiggerConfigYaml) (*dg_configuration.DiggerConfig, graph.Graph[string, dg_configuration.Project], error) {
-
err := dg_configuration.ValidateDiggerConfigYaml(configYaml, "loaded config")
if err != nil {
slog.Error("Error validating config", "error", err)
@@ -343,7 +340,6 @@ func loadDiggerConfig(configYaml *dg_configuration.DiggerConfigYaml) (*dg_config
}
err = dg_configuration.ValidateDiggerConfig(config)
-
if err != nil {
slog.Error("Error validating converted config", "error", err)
return nil, nil, fmt.Errorf("error validating config: %v", err)
diff --git a/backend/controllers/policies_api.go b/backend/controllers/policies_api.go
index 19b04f0e6..fce8fb131 100644
--- a/backend/controllers/policies_api.go
+++ b/backend/controllers/policies_api.go
@@ -98,7 +98,6 @@ func PolicyOrgUpsertApi(c *gin.Context) {
Type: policyType,
Policy: policyData,
}).Error
-
if err != nil {
slog.Error("Error creating policy", "organisationId", organisationId, "orgId", org.ID, "policyType", policyType, "error", err)
c.String(http.StatusInternalServerError, "Error creating policy")
diff --git a/backend/controllers/projects.go b/backend/controllers/projects.go
index 3a68fa324..02765df86 100644
--- a/backend/controllers/projects.go
+++ b/backend/controllers/projects.go
@@ -49,7 +49,6 @@ func ListProjectsApi(c *gin.Context) {
Where("projects.organisation_id = ?", org.ID).
Order("name").
Find(&projects).Error
-
if err != nil {
slog.Error("Error fetching projects", "organisationId", organisationId, "orgId", org.ID, "error", err)
c.String(http.StatusInternalServerError, "Unknown error occurred while fetching database")
@@ -269,7 +268,6 @@ func FindProjectsForOrg(c *gin.Context) {
Order("repos.repo_full_name").
Order("name").
Find(&projects).Error
-
if err != nil {
slog.Error("Error fetching projects for organisation",
"orgId", org.ID,
@@ -428,7 +426,6 @@ func ReportProjectsForRepo(c *gin.Context) {
var repo models.Repo
err = models.DB.GormDB.Where("name = ? AND organisation_id = ?", repoName, orgId).First(&repo).Error
-
if err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
slog.Info("Repository not found, creating new one",
@@ -443,7 +440,6 @@ func ReportProjectsForRepo(c *gin.Context) {
}
err = models.DB.GormDB.Create(&repo).Error
-
if err != nil {
slog.Error("Error creating repository",
"repoName", repoName,
@@ -489,7 +485,6 @@ func ReportProjectsForRepo(c *gin.Context) {
}
err = models.DB.GormDB.Create(&project).Error
-
if err != nil {
slog.Error("Error creating project",
"projectName", request.Name,
@@ -559,7 +554,6 @@ func RunHistoryForProject(c *gin.Context) {
var repo models.Repo
err = models.DB.GormDB.Where("name = ? AND organisation_id = ?", repoName, orgId).First(&repo).Error
-
if err != nil {
slog.Error("Error fetching repository",
"repoName", repoName,
@@ -573,7 +567,6 @@ func RunHistoryForProject(c *gin.Context) {
var project models.Project
err = models.DB.GormDB.Where("name = ? AND repo_id = ? AND organisation_id = ?", projectName, repo.ID, org.ID).First(&project).Error
-
if err != nil {
slog.Error("Error fetching project",
"projectName", projectName,
@@ -587,7 +580,6 @@ func RunHistoryForProject(c *gin.Context) {
var runHistory []models.ProjectRun
err = models.DB.GormDB.Where("project_id = ?", project.ID).Find(&runHistory).Error
-
if err != nil {
slog.Error("Error fetching run history",
"projectId", project.ID,
@@ -637,7 +629,6 @@ func (d DiggerController) SetJobStatusForProject(c *gin.Context) {
var request SetJobStatusRequest
err := c.BindJSON(&request)
-
if err != nil {
slog.Error("Error binding JSON request", "jobId", jobId, "error", err)
c.JSON(http.StatusBadRequest, gin.H{"error": "Error binding JSON"})
@@ -1406,7 +1397,7 @@ func CreateTerraformOutputsSummary(gh utils.GithubClientProvider, batch *models.
"jobCount", len(jobs),
)
- var terraformOutputs = ""
+ terraformOutputs := ""
for _, job := range jobs {
var jobSpec orchestrator_scheduler.JobJson
err := json.Unmarshal(job.SerializedJobSpec, &jobSpec)
diff --git a/backend/controllers/repos.go b/backend/controllers/repos.go
index 01be84dfc..9a00eef26 100644
--- a/backend/controllers/repos.go
+++ b/backend/controllers/repos.go
@@ -36,7 +36,6 @@ func ListReposApi(c *gin.Context) {
Where("repos.organisation_id = ?", org.ID).
Order("name").
Find(&repos).Error
-
if err != nil {
slog.Error("Error fetching repos", "organisationId", organisationId, "orgId", org.ID, "error", err)
c.String(http.StatusInternalServerError, "Unknown error occurred while fetching database")
diff --git a/backend/locking/backend_locking.go b/backend/locking/backend_locking.go
index a54c8aad5..7139bd3da 100644
--- a/backend/locking/backend_locking.go
+++ b/backend/locking/backend_locking.go
@@ -3,6 +3,7 @@ package locking
import (
"errors"
"fmt"
+
"github.com/diggerhq/digger/backend/models"
"gorm.io/gorm"
)
diff --git a/backend/main.go b/backend/main.go
index 4c3baaf45..e1eda4af5 100644
--- a/backend/main.go
+++ b/backend/main.go
@@ -3,6 +3,7 @@ package main
import (
"embed"
"fmt"
+
"github.com/diggerhq/digger/backend/bootstrap"
"github.com/diggerhq/digger/backend/ci_backends"
"github.com/diggerhq/digger/backend/config"
diff --git a/backend/middleware/basic.go b/backend/middleware/basic.go
index a5c69554d..225126bd6 100644
--- a/backend/middleware/basic.go
+++ b/backend/middleware/basic.go
@@ -12,7 +12,6 @@ import (
)
func HttpBasicWebAuth() gin.HandlerFunc {
-
return func(c *gin.Context) {
slog.Info("Restricting access with HTTP Basic Auth")
username := os.Getenv("HTTP_BASIC_AUTH_USERNAME")
diff --git a/backend/middleware/headers.go b/backend/middleware/headers.go
index 3818d44c0..f77bb0949 100644
--- a/backend/middleware/headers.go
+++ b/backend/middleware/headers.go
@@ -1,8 +1,9 @@
package middleware
import (
- "github.com/gin-gonic/gin"
"net/http"
+
+ "github.com/gin-gonic/gin"
)
func HeadersApiAuth() gin.HandlerFunc {
diff --git a/backend/middleware/jwt.go b/backend/middleware/jwt.go
index 62e1b3266..dd6059ef0 100644
--- a/backend/middleware/jwt.go
+++ b/backend/middleware/jwt.go
@@ -175,7 +175,6 @@ func SecretCodeAuth() gin.HandlerFunc {
}
return []byte(os.Getenv("WEBHOOK_SECRET")), nil
})
-
if err != nil {
slog.Error("Error parsing webhook secret", "error", err)
c.String(http.StatusForbidden, "Invalid x-webhook-secret header provided")
@@ -262,7 +261,6 @@ func JWTBearerTokenAuth(auth services.Auth) gin.HandlerFunc {
}
return publicKey, nil
})
-
if err != nil {
slog.Error("Error while parsing token", "error", err)
c.String(http.StatusForbidden, "Authorization header is invalid")
@@ -323,8 +321,10 @@ func CORSMiddleware() gin.HandlerFunc {
}
}
-const ORGANISATION_ID_KEY = "organisation_ID"
-const ORGANISATION_SOURCE_KEY = "organisation_Source"
-const USER_ID_KEY = "user_ID"
-const ACCESS_LEVEL_KEY = "access_level"
-const JOB_TOKEN_KEY = "job_token"
+const (
+ ORGANISATION_ID_KEY = "organisation_ID"
+ ORGANISATION_SOURCE_KEY = "organisation_Source"
+ USER_ID_KEY = "user_ID"
+ ACCESS_LEVEL_KEY = "access_level"
+ JOB_TOKEN_KEY = "job_token"
+)
diff --git a/backend/middleware/noop.go b/backend/middleware/noop.go
index 4142b4519..391113b33 100644
--- a/backend/middleware/noop.go
+++ b/backend/middleware/noop.go
@@ -1,11 +1,12 @@
package middleware
import (
- "github.com/diggerhq/digger/backend/models"
- "github.com/gin-gonic/gin"
"log/slog"
"net/http"
"strings"
+
+ "github.com/diggerhq/digger/backend/models"
+ "github.com/gin-gonic/gin"
)
func NoopWebAuth() gin.HandlerFunc {
diff --git a/backend/middleware/webhook.go b/backend/middleware/webhook.go
index b109f0a76..bdedae092 100644
--- a/backend/middleware/webhook.go
+++ b/backend/middleware/webhook.go
@@ -1,10 +1,11 @@
package middleware
import (
- "github.com/gin-gonic/gin"
"net/http"
"os"
"strings"
+
+ "github.com/gin-gonic/gin"
)
func InternalApiAuth() gin.HandlerFunc {
diff --git a/backend/models/orgs.go b/backend/models/orgs.go
index ad5d9fbb6..94d0a5065 100644
--- a/backend/models/orgs.go
+++ b/backend/models/orgs.go
@@ -92,9 +92,11 @@ const (
type DriftStatus string
-const DriftStatusNewDrift DriftStatus = "new drift"
-const DriftStatusNoDrift DriftStatus = "no drift"
-const DriftStatusAcknowledgeDrift DriftStatus = "acknowledged drift"
+const (
+ DriftStatusNewDrift DriftStatus = "new drift"
+ DriftStatusNoDrift DriftStatus = "no drift"
+ DriftStatusAcknowledgeDrift DriftStatus = "acknowledged drift"
+)
type Project struct {
gorm.Model
@@ -151,11 +153,12 @@ func (p *Project) MapToJsonStruct() interface{} {
DriftTerraformPlan: p.DriftTerraformPlan,
LastActivityTimestamp: p.UpdatedAt.String(),
LastActivityAuthor: "unknown",
- //LastActivityStatus: string(status),
+ // LastActivityStatus: string(status),
IsGenerated: p.IsGenerated,
IsInMainBranch: p.IsInMainBranch,
}
}
+
func (r *Repo) MapToJsonStruct() interface{} {
OrganisationName := func() string {
if r.Organisation == nil {
diff --git a/backend/models/runs.go b/backend/models/runs.go
index 0a58de0b9..f20e275bc 100644
--- a/backend/models/runs.go
+++ b/backend/models/runs.go
@@ -66,7 +66,7 @@ type DiggerRunStage struct {
}
type SerializedRunStage struct {
- //DiggerRunId uint `json:"digger_run_id"`
+ // DiggerRunId uint `json:"digger_run_id"`
DiggerJobId string `json:"digger_job_id"`
Status orchestrator_scheduler.DiggerJobStatus `json:"status"`
ProjectName string `json:"project_name"`
@@ -126,7 +126,7 @@ func (r DiggerRunStage) MapToJsonStruct() (*SerializedRunStage, error) {
serialized := &SerializedRunStage{
DiggerJobId: job.DiggerJobID,
Status: job.Status,
- //ProjectName: r.Run.ProjectName,
+ // ProjectName: r.Run.ProjectName,
WorkflowRunUrl: job.WorkflowRunUrl,
ResourcesCreated: job.DiggerJobSummary.ResourcesCreated,
ResourcesUpdated: job.DiggerJobSummary.ResourcesUpdated,
diff --git a/backend/models/scheduler.go b/backend/models/scheduler.go
index a77844fa0..810c72adf 100644
--- a/backend/models/scheduler.go
+++ b/backend/models/scheduler.go
@@ -19,9 +19,11 @@ type DiggerJobParentLink struct {
type DiggerVCSType string
-const DiggerVCSGithub DiggerVCSType = "github"
-const DiggerVCSGitlab DiggerVCSType = "gitlab"
-const DiggerVCSBitbucket DiggerVCSType = "bitbucket"
+const (
+ DiggerVCSGithub DiggerVCSType = "github"
+ DiggerVCSGitlab DiggerVCSType = "gitlab"
+ DiggerVCSBitbucket DiggerVCSType = "bitbucket"
+)
type DiggerBatch struct {
gorm.Model
diff --git a/backend/models/setup.go b/backend/models/setup.go
index 8a3103d85..53b385071 100644
--- a/backend/models/setup.go
+++ b/backend/models/setup.go
@@ -1,13 +1,14 @@
package models
import (
+ "log/slog"
+ "os"
+ "time"
+
sloggorm "github.com/imdatngo/slog-gorm/v2"
"gorm.io/driver/postgres"
_ "gorm.io/driver/postgres"
"gorm.io/gorm"
- "log/slog"
- "os"
- "time"
)
type Database struct {
diff --git a/backend/models/storage.go b/backend/models/storage.go
index 5bdf92e8f..fd2956a3a 100644
--- a/backend/models/storage.go
+++ b/backend/models/storage.go
@@ -35,7 +35,6 @@ func (db *Database) GetProjectsFromContext(c *gin.Context, orgIdKey string) ([]P
Joins("INNER JOIN repos ON projects.repo_id = repos.id").
Joins("INNER JOIN organisations ON projects.organisation_id = organisations.id").
Where("projects.organisation_id = ?", loggedInOrganisationId).Find(&projects).Error
-
if err != nil {
slog.Error("error fetching projects from database", "error", err)
return nil, false
@@ -46,7 +45,6 @@ func (db *Database) GetProjectsFromContext(c *gin.Context, orgIdKey string) ([]P
}
func (db *Database) GetProjectsRemainingInFreePLan(orgId uint) (uint, uint, uint, error) {
-
var countOfMonitoredProjects int64
err := db.GormDB.Model(&Project{}).Where("organisation_id = ? AND drift_enabled = ?", orgId, true).Count(&countOfMonitoredProjects).Error
if err != nil {
@@ -73,7 +71,6 @@ func (db *Database) GetReposFromContext(c *gin.Context, orgIdKey string) ([]Repo
err := db.GormDB.Preload("Organisation").
Joins("INNER JOIN organisations ON repos.organisation_id = organisations.id").
Where("repos.organisation_id = ?", loggedInOrganisationId).Find(&repos).Error
-
if err != nil {
slog.Error("error fetching repos from database", "error", err)
return nil, false
@@ -100,7 +97,6 @@ func (db *Database) GetPoliciesFromContext(c *gin.Context, orgIdKey string) ([]P
Joins("LEFT JOIN repos ON projects.repo_id = repos.id").
Joins("LEFT JOIN organisations ON projects.organisation_id = organisations.id").
Where("projects.organisation_id = ?", loggedInOrganisationId).Find(&policies).Error
-
if err != nil {
slog.Error("error fetching policies from database", "error", err)
return nil, false
@@ -120,7 +116,6 @@ func (db *Database) GetProjectRunsForOrg(orgId int) ([]ProjectRun, error) {
Joins("INNER JOIN repos ON projects.repo_id = repos.id").
Joins("INNER JOIN organisations ON projects.organisation_id = organisations.id").
Where("projects.organisation_id = ?", orgId).Order("created_at desc").Limit(100).Find(&runs).Error
-
if err != nil {
slog.Error("error fetching project runs from database", "error", err, "organisationId", orgId)
return nil, fmt.Errorf("unknown error occurred while fetching database, %v", err)
@@ -166,7 +161,6 @@ func (db *Database) GetProjectByRunId(c *gin.Context, runId uint, orgIdKey strin
Joins("INNER JOIN organisations ON projects.organisation_id = organisations.id").
Where("projects.organisation_id = ?", loggedInOrganisationId).
Where("project_runs.id = ?", runId).First(&projectRun).Error
-
if err != nil {
slog.Error("error fetching project run from database",
"error", err,
@@ -196,7 +190,6 @@ func (db *Database) GetProjectByProjectId(c *gin.Context, projectId uint, orgIdK
Joins("INNER JOIN organisations ON projects.organisation_id = organisations.id").
Where("projects.organisation_id = ?", loggedInOrganisationId).
Where("projects.id = ?", projectId).First(&project).Error
-
if err != nil {
slog.Error("error fetching project from database",
"error", err,
@@ -216,7 +209,6 @@ func (db *Database) GetProject(projectId uint) (*Project, error) {
err := db.GormDB.Preload("Organisation").
Where("id = ?", projectId).
First(&project).Error
-
if err != nil {
slog.Error("error fetching project from database",
"error", err,
@@ -229,7 +221,7 @@ func (db *Database) GetProject(projectId uint) (*Project, error) {
// GetProjectByName return project for specified org and repo
// if record doesn't exist return nil
-func (db *Database) GetProjectByName(orgId any, repoFullName string, name string) (*Project, error) {
+func (db *Database) GetProjectByName(orgId any, repoFullName, name string) (*Project, error) {
slog.Info("getting project by name",
slog.Group("project",
"orgId", orgId,
@@ -243,7 +235,6 @@ func (db *Database) GetProjectByName(orgId any, repoFullName string, name string
Where("projects.organisation_id = ?", orgId).
Where("repo_full_name = ?", repoFullName).
Where("projects.name = ?", name).First(&project).Error
-
if err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
slog.Debug("project not found",
@@ -278,7 +269,6 @@ func (db *Database) GetProjectByRepo(orgId any, repo *Repo) ([]Project, error) {
Joins("INNER JOIN organisations ON projects.organisation_id = organisations.id").
Where("projects.organisation_id = ?", orgId).
Where("repos.id = ?", repo.ID).Find(&projects).Error
-
if err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
slog.Debug("no projects found for repo",
@@ -321,7 +311,6 @@ func (db *Database) GetPolicyByPolicyId(c *gin.Context, policyId uint, orgIdKey
Joins("INNER JOIN organisations ON projects.organisation_id = organisations.id").
Where("projects.organisation_id = ?", loggedInOrganisationId).
Where("policies.id = ?", policyId).First(&policy).Error
-
if err != nil {
slog.Error("error fetching policy from database",
"error", err,
@@ -346,7 +335,6 @@ func (db *Database) GetDefaultRepo(c *gin.Context, orgIdKey string) (*Repo, bool
err := db.GormDB.Preload("Organisation").
Joins("INNER JOIN organisations ON repos.organisation_id = organisations.id").
Where("organisations.id = ?", loggedInOrganisationId).First(&repo).Error
-
if err != nil {
slog.Error("error fetching default repo from database",
"error", err,
@@ -369,7 +357,6 @@ func (db *Database) GetRepo(orgIdKey any, repoName string) (*Repo, error) {
err := db.GormDB.Preload("Organisation").
Joins("INNER JOIN organisations ON repos.organisation_id = organisations.id").
Where("organisations.id = ? AND repos.name=?", orgIdKey, repoName).First(&repo).Error
-
if err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
slog.Debug("repo not found",
@@ -401,7 +388,6 @@ func (db *Database) GetRepoByFullName(orgIdKey any, repoFullName string) (*Repo,
err := db.GormDB.Preload("Organisation").
Joins("INNER JOIN organisations ON repos.organisation_id = organisations.id").
Where("organisations.id = ? AND repos.repo_full_name=?", orgIdKey, repoFullName).First(&repo).Error
-
if err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
slog.Debug("repo not found",
@@ -440,13 +426,12 @@ func (db *Database) GetRepoByInstallationIdAndRepoFullName(installationId int64,
}
// GetRepoById returns digger repo by organisationId and repo name (diggerhq-digger)
-func (db *Database) GetRepoById(orgIdKey any, repoId any) (*Repo, error) {
+func (db *Database) GetRepoById(orgIdKey, repoId any) (*Repo, error) {
var repo Repo
err := db.GormDB.Preload("Organisation").
Joins("INNER JOIN organisations ON repos.organisation_id = organisations.id").
Where("organisations.id = ? AND repos.ID=?", orgIdKey, repoId).First(&repo).Error
-
if err != nil {
slog.Error("failed to find digger repo by id", "error", err, "orgId", orgIdKey, "repoId", repoId)
return nil, err
@@ -455,7 +440,7 @@ func (db *Database) GetRepoById(orgIdKey any, repoId any) (*Repo, error) {
}
// GithubRepoAdded handles github drift that github repo has been added to the app installation
-func (db *Database) GithubRepoAdded(installationId int64, appId int64, login string, accountId int64, repoFullName string) (*GithubAppInstallation, error) {
+func (db *Database) GithubRepoAdded(installationId, appId int64, login string, accountId int64, repoFullName string) (*GithubAppInstallation, error) {
// check if item exist already
item := &GithubAppInstallation{}
result := db.GormDB.Where("github_installation_id = ? AND repo=? AND github_app_id=?", installationId, repoFullName, appId).First(item)
@@ -486,7 +471,7 @@ func (db *Database) GithubRepoAdded(installationId int64, appId int64, login str
return item, nil
}
-func (db *Database) GithubRepoRemoved(installationId int64, appId int64, repoFullName string) (*GithubAppInstallation, error) {
+func (db *Database) GithubRepoRemoved(installationId, appId int64, repoFullName string) (*GithubAppInstallation, error) {
item := &GithubAppInstallation{}
err := db.GormDB.Where("github_installation_id = ? AND status=? AND github_app_id=? AND repo=?", installationId, GithubAppInstallActive, appId, repoFullName).First(item).Error
if err != nil {
@@ -575,7 +560,7 @@ func (db *Database) GetGithubAppInstallationLink(installationId int64) (*GithubA
return &link, nil
}
-func (db *Database) CreateVCSConnection(name string, vcsType DiggerVCSType, githubId int64, ClientID string, ClientSecretEncrypted string, WebhookSecretEncrypted string, PrivateKeyEncrypted string, PrivateKeyBase64Encrypted string, Org string, url string, bitbucketAccessTokenEnc string, bitbucketWebhookSecretEnc string, gitlabWebhookSecret string, gitlabAccessToken string, orgId uint) (*VCSConnection, error) {
+func (db *Database) CreateVCSConnection(name string, vcsType DiggerVCSType, githubId int64, ClientID, ClientSecretEncrypted, WebhookSecretEncrypted, PrivateKeyEncrypted, PrivateKeyBase64Encrypted, Org, url, bitbucketAccessTokenEnc, bitbucketWebhookSecretEnc, gitlabWebhookSecret, gitlabAccessToken string, orgId uint) (*VCSConnection, error) {
app := VCSConnection{
Name: name,
VCSType: vcsType,
@@ -705,7 +690,7 @@ func (db *Database) MakeGithubAppInstallationLinkInactive(link *GithubAppInstall
return link, nil
}
-func (db *Database) CreateDiggerJobLink(diggerJobId string, repoFullName string) (*GithubDiggerJobLink, error) {
+func (db *Database) CreateDiggerJobLink(diggerJobId, repoFullName string) (*GithubDiggerJobLink, error) {
link := GithubDiggerJobLink{Status: DiggerJobLinkCreated, DiggerJobId: diggerJobId, RepoFullName: repoFullName}
result := db.GormDB.Save(&link)
if result.Error != nil {
@@ -736,7 +721,7 @@ func (db *Database) GetDiggerJobLink(diggerJobId string) (*GithubDiggerJobLink,
return &link, nil
}
-func (db *Database) UpdateDiggerJobLink(diggerJobId string, repoFullName string, githubJobId int64) (*GithubDiggerJobLink, error) {
+func (db *Database) UpdateDiggerJobLink(diggerJobId, repoFullName string, githubJobId int64) (*GithubDiggerJobLink, error) {
jobLink := GithubDiggerJobLink{}
// check if there is already a link to another org, and throw an error in this case
result := db.GormDB.Where("digger_job_id = ? AND repo_full_name=? ", diggerJobId, repoFullName).Find(&jobLink)
@@ -788,7 +773,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, coverAllImpactedProjects bool, VCSConnectionId *uint) (*DiggerBatch, error) {
+func (db *Database) CreateDiggerBatch(vcsType DiggerVCSType, githubInstallationId int64, repoOwner, repoName, repoFullname string, PRNumber int, diggerConfig, branchName string, batchType scheduler.DiggerCommand, commentId *int64, gitlabProjectId int, aiSummaryCommentId string, reportTerraformOutputs, coverAllImpactedProjects bool, VCSConnectionId *uint) (*DiggerBatch, error) {
uid := uuid.New()
batch := &DiggerBatch{
ID: uid,
@@ -876,8 +861,10 @@ func (db *Database) CreateDiggerJob(batchId uuid.UUID, serializedJob []byte, wor
}
workflowUrl := "#"
- job := &DiggerJob{DiggerJobID: jobId, Status: scheduler.DiggerJobCreated,
- BatchID: &batchIdStr, SerializedJobSpec: serializedJob, DiggerJobSummary: *summary, WorkflowRunUrl: &workflowUrl, WorkflowFile: workflowFile}
+ job := &DiggerJob{
+ DiggerJobID: jobId, Status: scheduler.DiggerJobCreated,
+ BatchID: &batchIdStr, SerializedJobSpec: serializedJob, DiggerJobSummary: *summary, WorkflowRunUrl: &workflowUrl, WorkflowFile: workflowFile,
+ }
result = db.GormDB.Save(job)
if result.Error != nil {
return nil, result.Error
@@ -896,7 +883,6 @@ func (db *Database) ListDiggerRunsForProject(projectName string, repoId uint) ([
err := db.GormDB.Preload("PlanStage").Preload("ApplyStage").
Where("project_name = ? AND repo_id = ?", projectName, repoId).Order("created_at desc").Find(&runs).Error
-
if err != nil {
slog.Error("error fetching digger runs for project",
"error", err,
@@ -912,7 +898,7 @@ func (db *Database) ListDiggerRunsForProject(projectName string, repoId uint) ([
return runs, nil
}
-func (db *Database) CreateDiggerRun(Triggertype string, PrNumber int, Status DiggerRunStatus, CommitId string, DiggerConfig string, GithubInstallationId int64, RepoId uint, ProjectName string, RunType RunType, planStageId *uint, applyStageId *uint) (*DiggerRun, error) {
+func (db *Database) CreateDiggerRun(Triggertype string, PrNumber int, Status DiggerRunStatus, CommitId, DiggerConfig string, GithubInstallationId int64, RepoId uint, ProjectName string, RunType RunType, planStageId, applyStageId *uint) (*DiggerRun, error) {
dr := &DiggerRun{
Triggertype: Triggertype,
PrNumber: &PrNumber,
@@ -993,7 +979,7 @@ func (db *Database) GetDiggerRun(id uint) (*DiggerRun, error) {
return dr, nil
}
-func (db *Database) CreateDiggerRunQueueItem(diggerRunId uint, projectId uint) (*DiggerRunQueueItem, error) {
+func (db *Database) CreateDiggerRunQueueItem(diggerRunId, projectId uint) (*DiggerRunQueueItem, error) {
drq := &DiggerRunQueueItem{
DiggerRunId: diggerRunId,
ProjectId: projectId,
@@ -1121,7 +1107,7 @@ WHERE
return runqueuesWithData, nil
}
-func (db *Database) UpdateDiggerJobSummary(diggerJobId string, resourcesCreated uint, resourcesUpdated uint, resourcesDeleted uint) (*DiggerJob, error) {
+func (db *Database) UpdateDiggerJobSummary(diggerJobId string, resourcesCreated, resourcesUpdated, resourcesDeleted uint) (*DiggerJob, error) {
diggerJob, err := db.GetDiggerJob(diggerJobId)
if err != nil {
slog.Error("could not get digger job for summary update",
@@ -1334,7 +1320,7 @@ func (db *Database) GetDiggerJobParentLinksByParentId(parentId *string) ([]Digge
return jobParentLinks, nil
}
-func (db *Database) CreateDiggerJobParentLink(parentJobId string, jobId string) error {
+func (db *Database) CreateDiggerJobParentLink(parentJobId, jobId string) error {
jobParentLink := DiggerJobParentLink{ParentDiggerJobId: parentJobId, DiggerJobId: jobId}
result := db.GormDB.Create(&jobParentLink)
if result.Error != nil {
@@ -1388,7 +1374,7 @@ func (db *Database) GetOrganisation(tenantId any) (*Organisation, error) {
return org, nil
}
-func (db *Database) CreateUser(email string, externalSource string, externalId string, orgId uint, username string) (*User, error) {
+func (db *Database) CreateUser(email, externalSource, externalId string, orgId uint, username string) (*User, error) {
user := &User{
Email: email,
ExternalId: externalId,
@@ -1413,7 +1399,7 @@ func (db *Database) CreateUser(email string, externalSource string, externalId s
return user, nil
}
-func (db *Database) CreateOrganisation(name string, externalSource string, tenantId string) (*Organisation, error) {
+func (db *Database) CreateOrganisation(name, externalSource, tenantId string) (*Organisation, error) {
org := &Organisation{Name: name, ExternalSource: externalSource, ExternalId: tenantId}
result := db.GormDB.Save(org)
if result.Error != nil {
@@ -1432,7 +1418,7 @@ func (db *Database) CreateOrganisation(name string, externalSource string, tenan
return org, nil
}
-func (db *Database) CreateProject(name string, directory string, org *Organisation, repoFullName string, isGenerated bool, isInMainBranch bool) (*Project, error) {
+func (db *Database) CreateProject(name, directory string, org *Organisation, repoFullName string, isGenerated, isInMainBranch bool) (*Project, error) {
project := &Project{
Name: name,
Directory: directory,
@@ -1477,7 +1463,7 @@ func (db *Database) UpdateProject(project *Project) error {
return nil
}
-func (db *Database) CreateRepo(name string, repoFullName string, repoOrganisation string, repoName string, repoUrl string, org *Organisation, diggerConfig string, installationId int64, githubAppId int64, defaultBranch string, cloneUrl string) (*Repo, error) {
+func (db *Database) CreateRepo(name, repoFullName, repoOrganisation, repoName, repoUrl string, org *Organisation, diggerConfig string, installationId, githubAppId int64, defaultBranch, cloneUrl string) (*Repo, error) {
var repo Repo
// check if repo exist already, do nothing in this case
result := db.GormDB.Where("name = ? AND organisation_id=?", name, org.ID).Find(&repo)
@@ -1628,7 +1614,7 @@ func (db *Database) GetJobArtefact(jobTokenId uint) (*JobArtefact, error) {
return &artefact, nil
}
-func (db *Database) CreateGithubAppInstallation(installationId int64, githubAppId int64, login string, accountId int, repoFullName string) (*GithubAppInstallation, error) {
+func (db *Database) CreateGithubAppInstallation(installationId, githubAppId int64, login string, accountId int, repoFullName string) (*GithubAppInstallation, error) {
installation := &GithubAppInstallation{
GithubInstallationId: installationId,
GithubAppId: githubAppId,
@@ -1695,7 +1681,6 @@ func (db *Database) RefreshProjectsFromRepo(orgId string, config configuration.D
}
return nil
})
-
if err != nil {
return fmt.Errorf("error while updating projects from config: %v", err)
}
@@ -1746,7 +1731,7 @@ func (db *Database) GetDiggerLock(resource string) (*DiggerLock, error) {
return lock, nil
}
-func (db *Database) UpsertRepoCache(orgId uint, repoFullName string, diggerYmlStr string, diggerConfig configuration.DiggerConfig) (*RepoCache, error) {
+func (db *Database) UpsertRepoCache(orgId uint, repoFullName, diggerYmlStr string, diggerConfig configuration.DiggerConfig) (*RepoCache, error) {
var repoCache RepoCache
configMarshalled, err := json.Marshal(diggerConfig)
@@ -1817,7 +1802,6 @@ func (db *Database) GetRepoCache(orgId uint, repoFullName string) (*RepoCache, e
err := db.GormDB.
Where("org_id = ? AND repo_full_name = ?", orgId, repoFullName).First(&repoCache).Error
-
if err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
slog.Debug("repo cache not found",
@@ -1858,5 +1842,4 @@ func (db *Database) GetDiggerBatchesForPR(repoFullName string, prNumber int) ([]
"jobCount", len(batches))
return batches, nil
-
}
diff --git a/backend/models/storage_dashboard.go b/backend/models/storage_dashboard.go
index 83d66b4b0..3eff17a50 100644
--- a/backend/models/storage_dashboard.go
+++ b/backend/models/storage_dashboard.go
@@ -1,8 +1,9 @@
package models
import (
- "github.com/diggerhq/digger/libs/scheduler"
"time"
+
+ "github.com/diggerhq/digger/libs/scheduler"
)
func (db *Database) GetRepoCount(orgID uint) (int64, error) {
diff --git a/backend/models/storage_digger_jobs.go b/backend/models/storage_digger_jobs.go
index 076434273..bfa7bcabe 100644
--- a/backend/models/storage_digger_jobs.go
+++ b/backend/models/storage_digger_jobs.go
@@ -4,10 +4,11 @@ import (
"encoding/json"
"errors"
"fmt"
+ "log"
+
orchestrator_scheduler "github.com/diggerhq/digger/libs/scheduler"
"github.com/diggerhq/digger/libs/spec"
"gorm.io/gorm"
- "log"
)
func (db *Database) GetDiggerCiJob(diggerJobId string) (*DiggerJob, error) {
@@ -15,7 +16,6 @@ func (db *Database) GetDiggerCiJob(diggerJobId string) (*DiggerJob, error) {
var ciJob DiggerJob
err := db.GormDB.Preload("Batch").Where("digger_job_id = ?", diggerJobId).First(&ciJob).Error
-
if err != nil {
if errors.Is(err, gorm.ErrRecordNotFound) {
return nil, fmt.Errorf("ci job not found")
@@ -27,8 +27,7 @@ func (db *Database) GetDiggerCiJob(diggerJobId string) (*DiggerJob, error) {
return &ciJob, nil
}
-func (db *Database) CreateCiJobFromSpec(spec spec.Spec, runName string, projectName string, batchId string) (*DiggerJob, error) {
-
+func (db *Database) CreateCiJobFromSpec(spec spec.Spec, runName, projectName, batchId string) (*DiggerJob, error) {
marshalledJobSpec, err := json.Marshal(spec.Job)
if err != nil {
log.Printf("failed to marshal job: %v", err)
diff --git a/backend/segment/segment.go b/backend/segment/segment.go
index bf7b85e62..af49b5fb9 100644
--- a/backend/segment/segment.go
+++ b/backend/segment/segment.go
@@ -28,7 +28,7 @@ func CloseClient() {
client.Close()
}
-func IdentifyClient(userId string, userFullName string, username string, email string, organisationName string, organisationId string, userPlan string) {
+func IdentifyClient(userId, userFullName, username, email, organisationName, organisationId, userPlan string) {
if client == nil {
return
}
@@ -45,7 +45,7 @@ func IdentifyClient(userId string, userFullName string, username string, email s
})
}
-func Track(userId string, action string) {
+func Track(userId, action string) {
if client == nil {
return
}
diff --git a/backend/service_clients/projects_service.go b/backend/service_clients/projects_service.go
index cec8c7719..f69f2f628 100644
--- a/backend/service_clients/projects_service.go
+++ b/backend/service_clients/projects_service.go
@@ -39,8 +39,7 @@ type QueuedResponse struct {
Queued string `json:"queued"`
}
-func TriggerProjectsRefreshService(cloneUrl string, branch string, githubToken string, repoFullName string, orgId string) (*MachineResponse, error) {
-
+func TriggerProjectsRefreshService(cloneUrl, branch, githubToken, repoFullName, orgId string) (*MachineResponse, error) {
slog.Debug("awaiting machine fetch")
// Prepare machine configuration
diff --git a/backend/services/messages.go b/backend/services/messages.go
index 5c3bc2f09..397bb392d 100644
--- a/backend/services/messages.go
+++ b/backend/services/messages.go
@@ -10,7 +10,7 @@ import (
/// Messages are stored to the session and displayed only once
-func addMessage(c *gin.Context, message string, key string) {
+func addMessage(c *gin.Context, message, key string) {
session := sessions.Default(c)
var messages []string
sessionMessages := session.Get(key)
diff --git a/backend/services/repos.go b/backend/services/repos.go
index dce68940f..87bec5b84 100644
--- a/backend/services/repos.go
+++ b/backend/services/repos.go
@@ -2,15 +2,16 @@ package services
import (
"fmt"
- "github.com/diggerhq/digger/backend/models"
- "github.com/diggerhq/digger/backend/service_clients"
- utils3 "github.com/diggerhq/digger/backend/utils"
"log/slog"
"strconv"
"strings"
+
+ "github.com/diggerhq/digger/backend/models"
+ "github.com/diggerhq/digger/backend/service_clients"
+ utils3 "github.com/diggerhq/digger/backend/utils"
)
-func LoadProjectsFromGithubRepo(gh utils3.GithubClientProvider, installationId string, repoFullName string, repoOwner string, repoName string, cloneUrl string, branch string) error {
+func LoadProjectsFromGithubRepo(gh utils3.GithubClientProvider, installationId, repoFullName, repoOwner, repoName, cloneUrl, branch string) error {
installationId64, err := strconv.ParseInt(installationId, 10, 64)
if err != nil {
slog.Error("failed to convert installation id %v to int64", "insallationId", installationId)
diff --git a/backend/services/scheduler.go b/backend/services/scheduler.go
index 62cc21d4f..11804ee54 100644
--- a/backend/services/scheduler.go
+++ b/backend/services/scheduler.go
@@ -16,7 +16,7 @@ import (
"github.com/google/uuid"
)
-func DiggerJobCompleted(client *github.Client, batchId *uuid.UUID, parentJob *models.DiggerJob, repoFullName string, repoOwner string, repoName string, workflowFileName string, gh utils.GithubClientProvider) error {
+func DiggerJobCompleted(client *github.Client, batchId *uuid.UUID, parentJob *models.DiggerJob, repoFullName, repoOwner, repoName, workflowFileName string, gh utils.GithubClientProvider) error {
slog.Info("Job completed", "parentJobId", parentJob.DiggerJobID)
jobLinksForParent, err := models.DB.GetDiggerJobParentLinksByParentId(&parentJob.DiggerJobID)
@@ -69,7 +69,7 @@ func DiggerJobCompleted(client *github.Client, batchId *uuid.UUID, parentJob *mo
return nil
}
-func ScheduleJob(ciBackend ci_backends.CiBackend, repoFullname string, repoOwner string, repoName string, batchId *uuid.UUID, job *models.DiggerJob, gh utils.GithubClientProvider) error {
+func ScheduleJob(ciBackend ci_backends.CiBackend, repoFullname, repoOwner, repoName string, batchId *uuid.UUID, job *models.DiggerJob, gh utils.GithubClientProvider) error {
maxConcurrencyForBatch := config.DiggerConfig.GetInt("max_concurrency_per_batch")
if maxConcurrencyForBatch == 0 {
@@ -118,7 +118,7 @@ func ScheduleJob(ciBackend ci_backends.CiBackend, repoFullname string, repoOwner
return nil
}
-func TriggerJob(gh utils.GithubClientProvider, ciBackend ci_backends.CiBackend, repoFullname string, repoOwner string, repoName string, batchId *uuid.UUID, job *models.DiggerJob) error {
+func TriggerJob(gh utils.GithubClientProvider, ciBackend ci_backends.CiBackend, repoFullname, repoOwner, repoName string, batchId *uuid.UUID, job *models.DiggerJob) error {
slog.Info("Triggering job",
"jobId", job.DiggerJobID,
slog.Group("repository",
diff --git a/backend/tasks/runs.go b/backend/tasks/runs.go
index 1981e9216..9f2fc0956 100644
--- a/backend/tasks/runs.go
+++ b/backend/tasks/runs.go
@@ -83,7 +83,7 @@ func RunQueuesStateMachine(queueItem *models.DiggerRunQueueItem, service ci.Pull
slog.Info("checking plan status", runContext)
// Check the status of the batch
- batchStatus := orchestrator_scheduler.BatchJobSucceeded //dr.PlanStage.Batch.Status
+ batchStatus := orchestrator_scheduler.BatchJobSucceeded // dr.PlanStage.Batch.Status
approvalRequired := true
// if failed then go straight to failed
diff --git a/backend/tasks/runs_test.go b/backend/tasks/runs_test.go
index 2ec8a88d4..3e710f4b0 100644
--- a/backend/tasks/runs_test.go
+++ b/backend/tasks/runs_test.go
@@ -16,10 +16,9 @@ import (
"gorm.io/gorm"
)
-type MockCiBackend struct {
-}
+type MockCiBackend struct{}
-func (m MockCiBackend) TriggerWorkflow(spec spec.Spec, runName string, vcsToken string) error {
+func (m MockCiBackend) TriggerWorkflow(spec spec.Spec, runName, vcsToken string) error {
return nil
}
@@ -153,5 +152,4 @@ func TestThatRunQueueItemMovesFromQueuedToPlanningAfterPickup(t *testing.T) {
diggerRunRefreshed, _ := models.DB.GetDiggerRun(diggerRun.ID)
assert.Equal(t, testParam.NextExpectedStatus, diggerRunRefreshed.Status)
}
-
}
diff --git a/backend/utils/ai.go b/backend/utils/ai.go
index 17b641d3f..48442066b 100644
--- a/backend/utils/ai.go
+++ b/backend/utils/ai.go
@@ -9,7 +9,7 @@ import (
"net/http"
)
-func GenerateTerraformCode(appCode string, generationEndpoint string, apiToken string) (string, error) {
+func GenerateTerraformCode(appCode, generationEndpoint, apiToken string) (string, error) {
slog.Debug("Generating Terraform code",
"endpoint", generationEndpoint,
"codeLength", len(appCode),
@@ -89,7 +89,7 @@ func GenerateTerraformCode(appCode string, generationEndpoint string, apiToken s
return response.Result, nil
}
-func GetAiSummaryFromTerraformPlans(plans string, summaryEndpoint string, apiToken string) (string, error) {
+func GetAiSummaryFromTerraformPlans(plans, summaryEndpoint, apiToken string) (string, error) {
slog.Debug("Generating AI summary for Terraform plans",
"endpoint", summaryEndpoint,
"plansLength", len(plans),
diff --git a/backend/utils/allowlist_test.go b/backend/utils/allowlist_test.go
index 00613609e..b61926a92 100644
--- a/backend/utils/allowlist_test.go
+++ b/backend/utils/allowlist_test.go
@@ -1,9 +1,10 @@
package utils
import (
- "github.com/stretchr/testify/assert"
"os"
"testing"
+
+ "github.com/stretchr/testify/assert"
)
func TestExtractRepoName(t *testing.T) {
@@ -29,5 +30,4 @@ func TestRepoAllowList(t *testing.T) {
url = "http://gitlab.com/diggerdev/digger-demo.git"
allowed = IsInRepoAllowList(url)
assert.True(t, allowed)
-
}
diff --git a/backend/utils/bitbucket.go b/backend/utils/bitbucket.go
index 7a14ab5ce..b78de133d 100644
--- a/backend/utils/bitbucket.go
+++ b/backend/utils/bitbucket.go
@@ -2,12 +2,13 @@ package utils
import (
"fmt"
- "github.com/diggerhq/digger/libs/git_utils"
"log/slog"
"net/http"
"os"
"path"
+ "github.com/diggerhq/digger/libs/git_utils"
+
orchestrator_bitbucket "github.com/diggerhq/digger/libs/ci/bitbucket"
dg_configuration "github.com/diggerhq/digger/libs/digger_config"
"github.com/dominikbraun/graph"
@@ -25,7 +26,7 @@ func (b BitbucketClientProvider) NewClient(token string) (*bitbucket.Client, err
return client, nil
}
-func GetBitbucketService(bb BitbucketProvider, token string, repoOwner string, repoName string, prNumber int) (*orchestrator_bitbucket.BitbucketAPI, error) {
+func GetBitbucketService(bb BitbucketProvider, token, repoOwner, repoName string, prNumber int) (*orchestrator_bitbucket.BitbucketAPI, error) {
slog.Debug("Creating Bitbucket service",
slog.Group("repository",
slog.String("owner", repoOwner),
@@ -34,7 +35,7 @@ func GetBitbucketService(bb BitbucketProvider, token string, repoOwner string, r
"prNumber", prNumber,
)
- //token := os.Getenv("DIGGER_BITBUCKET_ACCESS_TOKEN")
+ // token := os.Getenv("DIGGER_BITBUCKET_ACCESS_TOKEN")
//client, err := bb.NewClient(token)
//if err != nil {
@@ -54,7 +55,7 @@ func GetBitbucketService(bb BitbucketProvider, token string, repoOwner string, r
return &service, nil
}
-func GetDiggerConfigForBitbucketBranch(bb BitbucketProvider, token string, repoFullName string, repoOwner string, repoName string, cloneUrl string, branch string, prNumber int) (string, *dg_configuration.DiggerConfig, graph.Graph[string, dg_configuration.Project], error) {
+func GetDiggerConfigForBitbucketBranch(bb BitbucketProvider, token, repoFullName, repoOwner, repoName, cloneUrl, branch string, prNumber int) (string, *dg_configuration.DiggerConfig, graph.Graph[string, dg_configuration.Project], error) {
slog.Info("Getting Digger config for Bitbucket branch",
slog.Group("repository",
slog.String("fullName", repoFullName),
@@ -118,7 +119,6 @@ func GetDiggerConfigForBitbucketBranch(bb BitbucketProvider, token string, repoF
}
return nil
})
-
if err != nil {
slog.Error("Error cloning and loading config",
"repoFullName", repoFullName,
diff --git a/backend/utils/github.go b/backend/utils/github.go
index c45f7a568..c45575bf3 100644
--- a/backend/utils/github.go
+++ b/backend/utils/github.go
@@ -19,8 +19,7 @@ import (
)
// just a wrapper around github client to be able to use mocks
-type DiggerGithubRealClientProvider struct {
-}
+type DiggerGithubRealClientProvider struct{}
type DiggerGithubClientMockProvider struct {
MockedHTTPClient *net.Client
@@ -28,7 +27,7 @@ type DiggerGithubClientMockProvider struct {
type GithubClientProvider interface {
NewClient(netClient *net.Client) (*github.Client, error)
- Get(githubAppId int64, installationId int64) (*github.Client, *string, error)
+ Get(githubAppId, installationId int64) (*github.Client, *string, error)
FetchCredentials(githubAppId string) (string, string, string, string, error)
}
@@ -37,7 +36,7 @@ func (gh DiggerGithubRealClientProvider) NewClient(netClient *net.Client) (*gith
return ghClient, nil
}
-func (gh DiggerGithubRealClientProvider) Get(githubAppId int64, installationId int64) (*github.Client, *string, error) {
+func (gh DiggerGithubRealClientProvider) Get(githubAppId, installationId int64) (*github.Client, *string, error) {
slog.Debug("Getting GitHub client",
"githubAppId", githubAppId,
"installationId", installationId,
@@ -110,7 +109,7 @@ func (gh DiggerGithubClientMockProvider) NewClient(netClient *net.Client) (*gith
return ghClient, nil
}
-func (gh DiggerGithubClientMockProvider) Get(githubAppId int64, installationId int64) (*github.Client, *string, error) {
+func (gh DiggerGithubClientMockProvider) Get(githubAppId, installationId int64) (*github.Client, *string, error) {
ghClient, _ := gh.NewClient(gh.MockedHTTPClient)
token := "token"
return ghClient, &token, nil
@@ -135,12 +134,12 @@ func GetGithubClient(gh GithubClientProvider, installationId int64, repoFullName
return ghClient, token, err
}
-func GetGithubClientFromAppId(gh GithubClientProvider, installationId int64, githubAppId int64, repoFullName string) (*github.Client, *string, error) {
+func GetGithubClientFromAppId(gh GithubClientProvider, installationId, githubAppId int64, repoFullName string) (*github.Client, *string, error) {
ghClient, token, err := gh.Get(githubAppId, installationId)
return ghClient, token, err
}
-func GetGithubService(gh GithubClientProvider, installationId int64, repoFullName string, repoOwner string, repoName string) (*github2.GithubService, *string, error) {
+func GetGithubService(gh GithubClientProvider, installationId int64, repoFullName, repoOwner, repoName string) (*github2.GithubService, *string, error) {
ghClient, token, err := GetGithubClient(gh, installationId, repoFullName)
if err != nil {
slog.Error("Failed to create GitHub client",
@@ -245,7 +244,7 @@ func GetGithubHostname() string {
return githubHostname
}
-func GetWorkflowIdAndUrlFromDiggerJobId(client *github.Client, repoOwner string, repoName string, diggerJobID string) (int64, string, error) {
+func GetWorkflowIdAndUrlFromDiggerJobId(client *github.Client, repoOwner, repoName, diggerJobID string) (int64, string, error) {
slog.Debug("Looking for workflow for job",
"diggerJobId", diggerJobID,
slog.Group("repository",
diff --git a/backend/utils/github_test.go b/backend/utils/github_test.go
index 51c0510c8..a4620d10e 100644
--- a/backend/utils/github_test.go
+++ b/backend/utils/github_test.go
@@ -1,10 +1,11 @@
package utils
import (
- "github.com/diggerhq/digger/libs/git_utils"
"os"
"testing"
+ "github.com/diggerhq/digger/libs/git_utils"
+
"github.com/stretchr/testify/assert"
)
diff --git a/backend/utils/gitlab.go b/backend/utils/gitlab.go
index 78c9b8aff..cd40ef5f4 100644
--- a/backend/utils/gitlab.go
+++ b/backend/utils/gitlab.go
@@ -2,11 +2,12 @@ package utils
import (
"fmt"
- "github.com/diggerhq/digger/libs/git_utils"
"log/slog"
"os"
"path"
+ "github.com/diggerhq/digger/libs/git_utils"
+
orchestrator_gitlab "github.com/diggerhq/digger/libs/ci/gitlab"
dg_configuration "github.com/diggerhq/digger/libs/digger_config"
"github.com/dominikbraun/graph"
@@ -32,7 +33,7 @@ func (g GitlabClientProvider) NewClient(token string) (*gitlab.Client, error) {
}
}
-func GetGitlabService(gh GitlabProvider, projectId int, repoName string, repoFullName string, prNumber int, discussionId string) (*orchestrator_gitlab.GitLabService, error) {
+func GetGitlabService(gh GitlabProvider, projectId int, repoName, repoFullName string, prNumber int, discussionId string) (*orchestrator_gitlab.GitLabService, error) {
slog.Debug("Getting GitLab service",
slog.Group("repository",
slog.String("name", repoName),
@@ -68,7 +69,7 @@ func GetGitlabService(gh GitlabProvider, projectId int, repoName string, repoFul
return &service, nil
}
-func GetDiggerConfigForBranchGitlab(gh GitlabProvider, projectId int, repoFullName string, repoOwner string, repoName string, cloneUrl string, branch string, prNumber int, discussionId string) (string, *dg_configuration.DiggerConfig, graph.Graph[string, dg_configuration.Project], error) {
+func GetDiggerConfigForBranchGitlab(gh GitlabProvider, projectId int, repoFullName, repoOwner, repoName, cloneUrl, branch string, prNumber int, discussionId string) (string, *dg_configuration.DiggerConfig, graph.Graph[string, dg_configuration.Project], error) {
slog.Info("Getting Digger config for GitLab branch",
slog.Group("repository",
slog.String("fullName", repoFullName),
@@ -142,7 +143,6 @@ func GetDiggerConfigForBranchGitlab(gh GitlabProvider, projectId int, repoFullNa
}
return nil
})
-
if err != nil {
slog.Error("Failed to clone and load config",
"projectId", projectId,
diff --git a/backend/utils/graphs.go b/backend/utils/graphs.go
index 8c2f9991b..a2d0b866a 100644
--- a/backend/utils/graphs.go
+++ b/backend/utils/graphs.go
@@ -15,7 +15,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, coverAllImpactedProjects 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, repoName, repoFullName, commitSha string, commentId int64, diggerConfigStr string, gitlabProjectId int, aiSummaryCommentId string, reportTerraformOutput, coverAllImpactedProjects bool, VCSConnectionId *uint) (*uuid.UUID, map[string]*models.DiggerJob, error) {
slog.Info("Converting jobs to Digger jobs",
"jobType", jobType,
"vcsType", vcsType,
diff --git a/backend/utils/graphs_test.go b/backend/utils/graphs_test.go
index df83e7106..a3238a7a8 100644
--- a/backend/utils/graphs_test.go
+++ b/backend/utils/graphs_test.go
@@ -1,8 +1,9 @@
package utils
import (
- configuration "github.com/diggerhq/digger/libs/digger_config"
"testing"
+
+ configuration "github.com/diggerhq/digger/libs/digger_config"
)
func TestImpactedProjectsOnlyGraph(t *testing.T) {
@@ -17,19 +18,16 @@ func TestImpactedProjectsOnlyGraph(t *testing.T) {
impactedProjects := map[string]configuration.Project{"p1": p1, "p2": p2, "p3": p3}
dg, err := configuration.CreateProjectDependencyGraph(projects)
-
if err != nil {
t.Errorf("Error creating dependency graph: %v", err)
}
newGraph, err := ImpactedProjectsOnlyGraph(dg, impactedProjects)
-
if err != nil {
t.Errorf("Error creating impacted projects only graph: %v", err)
}
adjMap, err := newGraph.AdjacencyMap()
-
if err != nil {
t.Errorf("Error getting adjacency map: %v", err)
}
@@ -63,19 +61,16 @@ func TestImpactedProjectsOnlyGraph2(t *testing.T) {
impactedProjects := map[string]configuration.Project{"p1": p1, "p2": p2, "p3": p3, "p5": p5}
dg, err := configuration.CreateProjectDependencyGraph(projects)
-
if err != nil {
t.Errorf("Error creating dependency graph: %v", err)
}
newGraph, err := ImpactedProjectsOnlyGraph(dg, impactedProjects)
-
if err != nil {
t.Errorf("Error creating impacted projects only graph: %v", err)
}
adjMap, err := newGraph.AdjacencyMap()
-
if err != nil {
t.Errorf("Error getting adjacency map: %v", err)
}
@@ -113,19 +108,16 @@ func TestImpactedProjectsOnlyGraph3(t *testing.T) {
impactedProjects := map[string]configuration.Project{"p1": p1, "p3": p3, "p6": p6}
dg, err := configuration.CreateProjectDependencyGraph(projects)
-
if err != nil {
t.Errorf("Error creating dependency graph: %v", err)
}
newGraph, err := ImpactedProjectsOnlyGraph(dg, impactedProjects)
-
if err != nil {
t.Errorf("Error creating impacted projects only graph: %v", err)
}
adjMap, err := newGraph.AdjacencyMap()
-
if err != nil {
t.Errorf("Error getting adjacency map: %v", err)
}
@@ -159,7 +151,6 @@ func TestTraverseGraphVisitAllParentsFirst(t *testing.T) {
projects := []configuration.Project{p1, p2, p3, p4, p5, p6, p7, p8}
dg, err := configuration.CreateProjectDependencyGraph(projects)
-
if err != nil {
t.Errorf("Error creating dependency graph: %v", err)
}
@@ -173,7 +164,6 @@ func TestTraverseGraphVisitAllParentsFirst(t *testing.T) {
}
err = TraverseGraphVisitAllParentsFirst(dg, visit)
-
if err != nil {
t.Errorf("Error traversing graph: %v", err)
}
diff --git a/backend/utils/pr_comment.go b/backend/utils/pr_comment.go
index 563f7e32c..568d2624c 100644
--- a/backend/utils/pr_comment.go
+++ b/backend/utils/pr_comment.go
@@ -96,7 +96,7 @@ func InitCommentReporter(prService ci.PullRequestService, prNumber int, commentM
return nil, fmt.Errorf("count not initialize comment reporter: %v", err)
}
- //commentId, err := strconv.ParseInt(fmt.Sprintf("%v", comment.Id), 10, 64)
+ // commentId, err := strconv.ParseInt(fmt.Sprintf("%v", comment.Id), 10, 64)
if err != nil {
slog.Error("Could not convert comment ID to int64", "commentId", comment.Id, "error", err)
return nil, fmt.Errorf("could not convert to int64, %v", err)
diff --git a/background/projects-refresh-service/projects_refesh_main.go b/background/projects-refresh-service/projects_refesh_main.go
index 0623237c5..e8fdb0c5d 100644
--- a/background/projects-refresh-service/projects_refesh_main.go
+++ b/background/projects-refresh-service/projects_refesh_main.go
@@ -2,11 +2,12 @@ package main
import (
"fmt"
+ "log/slog"
+ "os"
+
"github.com/diggerhq/digger/backend/models"
dg_configuration "github.com/diggerhq/digger/libs/digger_config"
utils3 "github.com/diggerhq/digger/libs/git_utils"
- "log/slog"
- "os"
)
func init() {
@@ -64,5 +65,4 @@ func main() {
slog.Error("error while cloning repo: %v", err)
os.Exit(1)
}
-
}
diff --git a/cli/cmd/digger/default.go b/cli/cmd/digger/default.go
index 737029a09..d16f08f8f 100644
--- a/cli/cmd/digger/default.go
+++ b/cli/cmd/digger/default.go
@@ -3,6 +3,10 @@ package main
import (
"encoding/json"
"fmt"
+ "log/slog"
+ "os"
+ "runtime/debug"
+
"github.com/diggerhq/digger/cli/pkg/digger"
"github.com/diggerhq/digger/cli/pkg/drift"
"github.com/diggerhq/digger/cli/pkg/github"
@@ -13,13 +17,9 @@ import (
"github.com/diggerhq/digger/libs/policy"
lib_spec "github.com/diggerhq/digger/libs/spec"
"github.com/spf13/cobra"
- "log/slog"
- "os"
- "runtime/debug"
)
func initLogger() {
-
logLevel := os.Getenv("DIGGER_LOG_LEVEL")
var level slog.Leveler
if logLevel == "DEBUG" {
@@ -34,7 +34,6 @@ func initLogger() {
}))
slog.SetDefault(logger)
-
}
var defaultCmd = &cobra.Command{
@@ -70,7 +69,7 @@ var defaultCmd = &cobra.Command{
usage.ReportErrorAndExit(spec.VCS.Actor, "Successfully ran spec", 0)
}
- var logLeader = "Unknown CI"
+ logLeader := "Unknown CI"
ci := digger.DetectCI()
switch ci {
diff --git a/cli/cmd/digger/main.go b/cli/cmd/digger/main.go
index 3eeed4bb3..fed76f12f 100644
--- a/cli/cmd/digger/main.go
+++ b/cli/cmd/digger/main.go
@@ -2,8 +2,9 @@ package main
import (
"fmt"
- "github.com/diggerhq/digger/cli/pkg/usage"
"os"
+
+ "github.com/diggerhq/digger/cli/pkg/usage"
)
/*
@@ -27,5 +28,4 @@ func main() {
if err := rootCmd.Execute(); err != nil {
usage.ReportErrorAndExit("", fmt.Sprintf("Error occurred during command exec: %v", err), 8)
}
-
}
diff --git a/cli/cmd/digger/main_test.go b/cli/cmd/digger/main_test.go
index 6b3e5352f..88be2296c 100644
--- a/cli/cmd/digger/main_test.go
+++ b/cli/cmd/digger/main_test.go
@@ -1,15 +1,17 @@
package main
import (
+ "log"
+ "testing"
+
"github.com/diggerhq/digger/libs/backendapi"
"github.com/diggerhq/digger/libs/ci"
"github.com/diggerhq/digger/libs/ci/generic"
"github.com/diggerhq/digger/libs/comment_utils/reporting"
- "github.com/diggerhq/digger/libs/comment_utils/summary"
+ comment_updater "github.com/diggerhq/digger/libs/comment_utils/summary"
"github.com/diggerhq/digger/libs/locking"
"github.com/diggerhq/digger/libs/policy"
"github.com/diggerhq/digger/libs/storage"
- "log"
"github.com/diggerhq/digger/cli/pkg/digger"
"github.com/diggerhq/digger/cli/pkg/github/models"
@@ -19,8 +21,6 @@ import (
"github.com/google/go-github/v61/github"
- "testing"
-
"github.com/davecgh/go-spew/spew"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
@@ -875,7 +875,6 @@ var githubInvalidContextJson = `{
`
func TestGitHubNewPullRequestContext(t *testing.T) {
-
actionContext, err := models.GetGitHubContext(githubContextNewPullRequestJson)
context := actionContext.ToEventPackage()
@@ -1020,7 +1019,7 @@ func TestGitHubTestPRCommandCaseInsensitivity(t *testing.T) {
var impactedProjects []configuration.Project
impactedProjects = make([]configuration.Project, 1)
impactedProjects[0] = project
- var requestedProject = project
+ requestedProject := project
workflows := make(map[string]configuration.Workflow, 1)
workflows["default"] = configuration.Workflow{}
jobs, _, err := generic.ConvertIssueCommentEventToJobs("", "", 0, "digger plan", impactedProjects, &requestedProject, workflows, "prbranch", "main")
diff --git a/cli/cmd/digger/root.go b/cli/cmd/digger/root.go
index 0936f7e3c..143c06c33 100644
--- a/cli/cmd/digger/root.go
+++ b/cli/cmd/digger/root.go
@@ -2,6 +2,11 @@ package main
import (
"fmt"
+ "log/slog"
+ "net/http"
+ "os"
+ "time"
+
"github.com/diggerhq/digger/cli/pkg/utils"
"github.com/diggerhq/digger/libs/backendapi"
"github.com/diggerhq/digger/libs/ci"
@@ -11,10 +16,6 @@ import (
locking2 "github.com/diggerhq/digger/libs/locking"
core_policy "github.com/diggerhq/digger/libs/policy"
"github.com/spf13/cobra"
- "log/slog"
- "net/http"
- "os"
- "time"
)
type RunConfig struct {
@@ -76,10 +77,12 @@ func (r *RunConfig) GetServices() (*ci.PullRequestService, *ci.OrgService, *repo
return &prService, &orgService, &reporter, nil
}
-var PolicyChecker core_policy.Checker
-var BackendApi backendapi.Api
-var ReportStrategy reporting.ReportStrategy
-var lock locking2.Lock
+var (
+ PolicyChecker core_policy.Checker
+ BackendApi backendapi.Api
+ ReportStrategy reporting.ReportStrategy
+ lock locking2.Lock
+)
func PreRun(cmd *cobra.Command, args []string) {
if cmd.Name() == "run_spec" {
@@ -88,9 +91,9 @@ func PreRun(cmd *cobra.Command, args []string) {
hostName := os.Getenv("DIGGER_HOSTNAME")
token := os.Getenv("DIGGER_TOKEN")
- //orgName := os.Getenv("DIGGER_ORGANISATION")
+ // orgName := os.Getenv("DIGGER_ORGANISATION")
BackendApi = backendapi.NewBackendApi(hostName, token)
- //PolicyChecker = policy.NewPolicyChecker(hostName, orgName, token)
+ // PolicyChecker = policy.NewPolicyChecker(hostName, orgName, token)
if os.Getenv("REPORTING_STRATEGY") == "comments_per_run" || os.Getenv("ACCUMULATE_PLANS") == "true" {
ReportStrategy = &reporting.CommentPerRunStrategy{
diff --git a/cli/cmd/digger/run_spec.go b/cli/cmd/digger/run_spec.go
index f6988da36..6cb674284 100644
--- a/cli/cmd/digger/run_spec.go
+++ b/cli/cmd/digger/run_spec.go
@@ -3,6 +3,8 @@ package main
import (
"encoding/json"
"fmt"
+ "strings"
+
spec2 "github.com/diggerhq/digger/cli/pkg/spec"
"github.com/diggerhq/digger/cli/pkg/usage"
comment_summary "github.com/diggerhq/digger/libs/comment_utils/summary"
@@ -10,7 +12,6 @@ import (
"github.com/spf13/cobra"
"github.com/spf13/pflag"
"github.com/spf13/viper"
- "strings"
)
var viperRunSpec *viper.Viper
diff --git a/cli/pkg/core/drift/drift.go b/cli/pkg/core/drift/drift.go
index f33fc78aa..510aa301f 100644
--- a/cli/pkg/core/drift/drift.go
+++ b/cli/pkg/core/drift/drift.go
@@ -1,5 +1,5 @@
package drift
type Notification interface {
- Send(projectName string, plan string) error
+ Send(projectName, plan string) error
}
diff --git a/cli/pkg/digger/digger.go b/cli/pkg/digger/digger.go
index 42dc0542b..90368fc64 100644
--- a/cli/pkg/digger/digger.go
+++ b/cli/pkg/digger/digger.go
@@ -45,7 +45,6 @@ func (ci CIName) String() string {
}
func DetectCI() CIName {
-
notEmpty := func(key string) bool {
return os.Getenv(key) != ""
}
@@ -63,10 +62,9 @@ func DetectCI() CIName {
return Azure
}
return None
-
}
-func RunJobs(jobs []orchestrator.Job, prService ci.PullRequestService, orgService ci.OrgService, lock locking2.Lock, reporter reporting.Reporter, planStorage storage.PlanStorage, policyChecker policy.Checker, commentUpdater comment_updater.CommentUpdater, backendApi backendapi.Api, jobId string, reportFinalStatusToBackend bool, reportTerraformOutput bool, prCommentId string, workingDir string) (bool, bool, error) {
+func RunJobs(jobs []orchestrator.Job, prService ci.PullRequestService, orgService ci.OrgService, lock locking2.Lock, reporter reporting.Reporter, planStorage storage.PlanStorage, policyChecker policy.Checker, commentUpdater comment_updater.CommentUpdater, backendApi backendapi.Api, jobId string, reportFinalStatusToBackend, reportTerraformOutput bool, prCommentId, workingDir string) (bool, bool, error) {
defer reporter.Flush()
slog.Debug("Variable info", "TF_PLUGIN_CACHE_DIR", os.Getenv("TF_PLUGIN_CACHE_DIR"))
@@ -85,7 +83,6 @@ func RunJobs(jobs []orchestrator.Job, prService ci.PullRequestService, orgServic
for _, command := range job.Commands {
allowedToPerformCommand, err := policyChecker.CheckAccessPolicy(orgService, &prService, SCMOrganisation, SCMrepository, job.ProjectName, job.ProjectDir, command, job.PullRequestNumber, job.RequestedBy, []string{})
-
if err != nil {
return false, false, fmt.Errorf("error checking policy: %v", err)
}
@@ -177,7 +174,7 @@ func RunJobs(jobs []orchestrator.Job, prService ci.PullRequestService, orgServic
return allAppliesSuccess, atLeastOneApply, nil
}
-func reportPolicyError(projectName string, command string, requestedBy string, reporter reporting.Reporter) string {
+func reportPolicyError(projectName, command, 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 %v - %v", projectName, command), false))
@@ -193,11 +190,10 @@ func reportPolicyError(projectName string, command string, requestedBy string, r
return msg
}
-func run(command string, job orchestrator.Job, policyChecker policy.Checker, orgService ci.OrgService, SCMOrganisation string, SCMrepository string, PRNumber *int, requestedBy string, reporter reporting.Reporter, lock locking2.Lock, prService ci.PullRequestService, projectNamespace string, workingDir string, planStorage storage.PlanStorage, appliesPerProject map[string]bool) (*execution.DiggerExecutorResult, string, error) {
+func run(command string, job orchestrator.Job, policyChecker policy.Checker, orgService ci.OrgService, SCMOrganisation, SCMrepository string, PRNumber *int, requestedBy string, reporter reporting.Reporter, lock locking2.Lock, prService ci.PullRequestService, projectNamespace, workingDir string, planStorage storage.PlanStorage, appliesPerProject map[string]bool) (*execution.DiggerExecutorResult, string, error) {
slog.Info("Running command for project", "command", command, "project name", job.ProjectName, "project workflow", job.ProjectWorkflow)
allowedToPerformCommand, err := policyChecker.CheckAccessPolicy(orgService, &prService, SCMOrganisation, SCMrepository, job.ProjectName, job.ProjectDir, command, job.PullRequestNumber, requestedBy, []string{})
-
if err != nil {
return nil, "error checking policy", fmt.Errorf("error checking policy: %v", err)
}
@@ -323,7 +319,6 @@ func run(command string, job orchestrator.Job, policyChecker policy.Checker, org
}
planReportMessage = planReportMessage + strings.Join(preformattedMessaged, "
")
_, _, err = reporter.Report(planReportMessage, planPolicyFormatter)
-
if err != nil {
slog.Error("Failed to report plan.", "error", err)
}
@@ -426,7 +421,7 @@ func run(command string, job orchestrator.Job, policyChecker policy.Checker, org
applySummary, applyPerformed, output, err := diggerExecutor.Apply()
if err != nil {
- //TODO reuse executor error handling
+ // TODO reuse executor error handling
slog.Error("Failed to Run digger apply command.", "error", err)
err := prService.SetStatus(*job.PullRequestNumber, "failure", job.ProjectName+"/apply")
if err != nil {
@@ -458,7 +453,6 @@ func run(command string, job orchestrator.Job, policyChecker policy.Checker, org
slog.Error("Failed to send usage report.", "error", err)
}
_, err = diggerExecutor.Destroy()
-
if err != nil {
slog.Error("Failed to Run digger destroy command.", "error", err)
msg := fmt.Sprintf("failed to run digger destroy command: %v", err)
@@ -520,7 +514,7 @@ func reportApplyMergeabilityError(reporter reporting.Reporter) string {
return comment
}
-func reportTerraformPlanOutput(reporter reporting.Reporter, projectId string, plan string) {
+func reportTerraformPlanOutput(reporter reporting.Reporter, projectId, plan string) {
var formatter func(string) string
if reporter.SupportsMarkdown() {
@@ -580,7 +574,6 @@ func RunJob(
for _, command := range job.Commands {
allowedToPerformCommand, err := policyChecker.CheckAccessPolicy(orgService, nil, SCMOrganisation, SCMrepository, job.ProjectName, job.ProjectDir, command, nil, requestedBy, []string{})
-
if err != nil {
return fmt.Errorf("error checking policy: %v", err)
}
@@ -733,7 +726,7 @@ func RunJob(
return nil
}
-func runDriftDetection(policyChecker policy.Checker, SCMOrganisation string, SCMrepository string, projectName string, requestedBy string, eventName string, diggerExecutor execution.Executor, notification *core_drift.Notification) (string, error) {
+func runDriftDetection(policyChecker policy.Checker, SCMOrganisation, SCMrepository, projectName, requestedBy, eventName string, diggerExecutor execution.Executor, notification *core_drift.Notification) (string, error) {
err := usage.SendUsageRecord(requestedBy, eventName, "drift-detect")
if err != nil {
slog.Error("Failed to send usage report.", "error", err)
@@ -776,7 +769,7 @@ func runDriftDetection(policyChecker policy.Checker, SCMOrganisation string, SCM
func SortedCommandsByDependency(project []orchestrator.Job, dependencyGraph *graph.Graph[string, config.Project]) []orchestrator.Job {
var sortedCommands []orchestrator.Job
- sortedGraph, err := graph.StableTopologicalSort(*dependencyGraph, func(s string, s2 string) bool {
+ sortedGraph, err := graph.StableTopologicalSort(*dependencyGraph, func(s, s2 string) bool {
return s < s2
})
if err != nil {
@@ -805,7 +798,6 @@ func MergePullRequest(ciService ci.PullRequestService, prNumber int, mergeStrate
if !isMerged {
combinedStatus, err := ciService.GetCombinedPullRequestStatus(prNumber)
-
if err != nil {
log.Fatalf("failed to get combined status, %v", err)
}
@@ -815,7 +807,6 @@ func MergePullRequest(ciService ci.PullRequestService, prNumber int, mergeStrate
}
prIsMergeable, err := ciService.IsMergeable(prNumber)
-
if err != nil {
log.Fatalf("failed to check if PR is mergeable, %v", err)
}
diff --git a/cli/pkg/digger/digger_test.go b/cli/pkg/digger/digger_test.go
index 7b89c2e62..17764af99 100644
--- a/cli/pkg/digger/digger_test.go
+++ b/cli/pkg/digger/digger_test.go
@@ -30,7 +30,7 @@ type MockCommandRunner struct {
Commands []RunInfo
}
-func (m *MockCommandRunner) Run(workDir string, shell string, commands []string, envs map[string]string) (string, string, error) {
+func (m *MockCommandRunner) Run(workDir, shell string, commands []string, envs map[string]string) (string, string, error) {
m.Commands = append(m.Commands, RunInfo{"Run", workDir + " " + shell + " " + strings.Join(commands, " "), time.Now()})
return "", "", nil
}
@@ -72,7 +72,7 @@ type MockPRManager struct {
Commands []RunInfo
}
-func (m *MockPRManager) GetUserTeams(organisation string, user string) ([]string, error) {
+func (m *MockPRManager) GetUserTeams(organisation, user string) ([]string, error) {
return []string{}, nil
}
@@ -101,16 +101,16 @@ func (m *MockPRManager) ListIssues() ([]*ci.Issue, error) {
return nil, nil
}
-func (m *MockPRManager) PublishIssue(title string, body string, labels *[]string) (int64, error) {
+func (m *MockPRManager) PublishIssue(title, body string, labels *[]string) (int64, error) {
m.Commands = append(m.Commands, RunInfo{"PublishComment", body, time.Now()})
return 0, nil
}
-func (m *MockPRManager) UpdateIssue(ID int64, title string, body string) (int64, error) {
+func (m *MockPRManager) UpdateIssue(ID int64, title, body string) (int64, error) {
return 0, fmt.Errorf("implement me")
}
-func (m *MockPRManager) SetStatus(prNumber int, status string, statusContext string) error {
+func (m *MockPRManager) SetStatus(prNumber int, status, statusContext string) error {
m.Commands = append(m.Commands, RunInfo{"SetStatus", strconv.Itoa(prNumber) + " " + status + " " + statusContext, time.Now()})
return nil
}
@@ -150,7 +150,7 @@ func (m *MockPRManager) GetComments(prNumber int) ([]ci.Comment, error) {
return []ci.Comment{}, nil
}
-func (m *MockPRManager) EditComment(prNumber int, id string, comment string) error {
+func (m *MockPRManager) EditComment(prNumber int, id, comment string) error {
m.Commands = append(m.Commands, RunInfo{"EditComment", id + " " + comment, time.Now()})
return nil
}
@@ -159,7 +159,7 @@ func (m *MockPRManager) DeleteComment(id string) error {
return nil
}
-func (m *MockPRManager) CreateCommentReaction(id string, reaction string) error {
+func (m *MockPRManager) CreateCommentReaction(id, reaction string) error {
m.Commands = append(m.Commands, RunInfo{"EditComment", id + " " + reaction, time.Now()})
return nil
}
@@ -169,10 +169,9 @@ func (m *MockPRManager) GetBranchName(prNumber int) (string, string, error) {
return "", "", nil
}
-func (m *MockPRManager) SetOutput(prNumber int, key string, value string) error {
+func (m *MockPRManager) SetOutput(prNumber int, key, value string) error {
m.Commands = append(m.Commands, RunInfo{"SetOutput", strconv.Itoa(prNumber), time.Now()})
return nil
-
}
type MockProjectLock struct {
@@ -203,7 +202,7 @@ type MockZipper struct {
Commands []RunInfo
}
-func (m *MockZipper) GetFileFromZip(zipFile string, filename string) (string, error) {
+func (m *MockZipper) GetFileFromZip(zipFile, filename string) (string, error) {
m.Commands = append(m.Commands, RunInfo{"GetFileFromZip", zipFile + " " + filename, time.Now()})
return "plan", nil
}
@@ -212,22 +211,22 @@ type MockPlanStorage struct {
Commands []RunInfo
}
-func (m *MockPlanStorage) StorePlanFile(fileContents []byte, artifactName string, fileName string) error {
+func (m *MockPlanStorage) StorePlanFile(fileContents []byte, artifactName, fileName string) error {
m.Commands = append(m.Commands, RunInfo{"StorePlanFile", artifactName, time.Now()})
return nil
}
-func (m *MockPlanStorage) RetrievePlan(localPlanFilePath string, artifactName string, storedPlanFilePath string) (*string, error) {
+func (m *MockPlanStorage) RetrievePlan(localPlanFilePath, artifactName, storedPlanFilePath string) (*string, error) {
m.Commands = append(m.Commands, RunInfo{"RetrievePlan", localPlanFilePath, time.Now()})
return nil, nil
}
-func (m *MockPlanStorage) DeleteStoredPlan(artifactName string, storedPlanFilePath string) error {
+func (m *MockPlanStorage) DeleteStoredPlan(artifactName, storedPlanFilePath string) error {
m.Commands = append(m.Commands, RunInfo{"DeleteStoredPlan", storedPlanFilePath, time.Now()})
return nil
}
-func (m *MockPlanStorage) PlanExists(artifactName string, storedPlanFilePath string) (bool, error) {
+func (m *MockPlanStorage) PlanExists(artifactName, storedPlanFilePath string) (bool, error) {
m.Commands = append(m.Commands, RunInfo{"PlanExists", storedPlanFilePath, time.Now()})
return false, nil
}
@@ -252,7 +251,6 @@ func (m MockPlanPathProvider) LocalPlanFilePath() string {
}
func TestCorrectCommandExecutionWhenApplying(t *testing.T) {
-
commandRunner := &MockCommandRunner{}
terraformExecutor := &MockTerraformExecutor{}
prManager := &MockPRManager{}
@@ -302,7 +300,6 @@ func TestCorrectCommandExecutionWhenApplying(t *testing.T) {
}
func TestCorrectCommandExecutionWhenDestroying(t *testing.T) {
-
commandRunner := &MockCommandRunner{}
terraformExecutor := &MockTerraformExecutor{}
prManager := &MockPRManager{}
@@ -384,7 +381,7 @@ func TestCorrectCommandExecutionWhenPlanning(t *testing.T) {
IacUtils: iac_utils.TerraformUtils{},
}
- os.WriteFile(planPathProvider.LocalPlanFilePath(), []byte{123}, 0644)
+ os.WriteFile(planPathProvider.LocalPlanFilePath(), []byte{123}, 0o644)
defer os.Remove(planPathProvider.LocalPlanFilePath())
executor.Plan()
@@ -478,11 +475,10 @@ func TestSortedCommandByDependency(t *testing.T) {
assert.Equal(t, "project4", sortedCommands[1].ProjectName)
assert.Equal(t, "project2", sortedCommands[2].ProjectName)
assert.Equal(t, "project1", sortedCommands[3].ProjectName)
-
}
func TestParseWorkspace(t *testing.T) {
- var commentTests = []struct {
+ commentTests := []struct {
in string
out string
err bool
@@ -508,5 +504,4 @@ func TestParseWorkspace(t *testing.T) {
}
}
}
-
}
diff --git a/cli/pkg/digger/io.go b/cli/pkg/digger/io.go
index 214b4116a..30b0cffc0 100644
--- a/cli/pkg/digger/io.go
+++ b/cli/pkg/digger/io.go
@@ -2,9 +2,10 @@ package digger
import (
"fmt"
+ "log"
+
"github.com/diggerhq/digger/libs/ci"
"github.com/diggerhq/digger/libs/scheduler"
- "log"
)
func UpdateAggregateStatus(batch *scheduler.SerializedBatch, prService ci.PullRequestService) error {
diff --git a/cli/pkg/drift/Provider.go b/cli/pkg/drift/Provider.go
index a1949a31a..7345498df 100644
--- a/cli/pkg/drift/Provider.go
+++ b/cli/pkg/drift/Provider.go
@@ -2,9 +2,10 @@ package drift
import (
"fmt"
+ "os"
+
core_drift "github.com/diggerhq/digger/cli/pkg/core/drift"
"github.com/diggerhq/digger/libs/ci"
- "os"
)
type DriftNotificationProvider interface {
diff --git a/cli/pkg/drift/slack.go b/cli/pkg/drift/slack.go
index a344c2777..cfb1e3dd9 100644
--- a/cli/pkg/drift/slack.go
+++ b/cli/pkg/drift/slack.go
@@ -40,7 +40,7 @@ func SplitCodeBlocks(message string) []string {
return res
}
-func (slack SlackNotification) Send(projectName string, plan string) error {
+func (slack SlackNotification) Send(projectName, plan string) error {
message := fmt.Sprintf(":bangbang: Drift detected in digger project %v details below: \n\n```\n%v\n```", projectName, plan)
httpClient := &http.Client{}
type SlackMessage struct {
diff --git a/cli/pkg/drift/slack_test.go b/cli/pkg/drift/slack_test.go
index 47466bfdf..5656dd6f1 100644
--- a/cli/pkg/drift/slack_test.go
+++ b/cli/pkg/drift/slack_test.go
@@ -1,10 +1,11 @@
package drift
import (
- "github.com/stretchr/testify/assert"
"os"
"strings"
"testing"
+
+ "github.com/stretchr/testify/assert"
)
func TestSlackSplitLargerMessage(t *testing.T) {
diff --git a/cli/pkg/github/github.go b/cli/pkg/github/github.go
index 0ce2ad8e8..96965ca18 100644
--- a/cli/pkg/github/github.go
+++ b/cli/pkg/github/github.go
@@ -3,6 +3,10 @@ package github
import (
"errors"
"fmt"
+ "log/slog"
+ "os"
+ "strings"
+
"github.com/diggerhq/digger/cli/pkg/digger"
"github.com/diggerhq/digger/cli/pkg/drift"
github_models "github.com/diggerhq/digger/cli/pkg/github/models"
@@ -21,9 +25,6 @@ import (
"github.com/google/go-github/v61/github"
"github.com/samber/lo"
"gopkg.in/yaml.v3"
- "log/slog"
- "os"
- "strings"
)
func initLogger() {
@@ -55,7 +56,7 @@ func GitHubCI(lock core_locking.Lock, policyCheckerProvider core_policy.PolicyCh
hostName := os.Getenv("DIGGER_HOSTNAME")
token := os.Getenv("DIGGER_TOKEN")
orgName := os.Getenv("DIGGER_ORGANISATION")
- var policyChecker, _ = policyCheckerProvider.Get(hostName, token, orgName)
+ policyChecker, _ := policyCheckerProvider.Get(hostName, token, orgName)
ghToken := os.Getenv("GITHUB_TOKEN")
if ghToken == "" {
@@ -281,7 +282,6 @@ func GitHubCI(lock core_locking.Lock, policyCheckerProvider core_policy.PolicyCh
jobs, coversAllImpactedProjects, err = dg_github.ConvertGithubPullRequestEventToJobs(&prEvent, impactedProjects, requestedProject, *diggerConfig, true)
} else if commentEvent, ok := ghEvent.(github.IssueCommentEvent); ok {
prBranchName, _, err := githubPrService.GetBranchName(*commentEvent.Issue.Number)
-
if err != nil {
usage.ReportErrorAndExit(githubActor, fmt.Sprintf("Error while retrieving default branch from Issue: %v", err), 6)
}
diff --git a/cli/pkg/github/models/models.go b/cli/pkg/github/models/models.go
index 4c7d04522..56a744773 100644
--- a/cli/pkg/github/models/models.go
+++ b/cli/pkg/github/models/models.go
@@ -35,6 +35,7 @@ func (g *GithubAction) ToEventPackage() models.EventPackage {
Repository: g.Repository,
}
}
+
func (g *GithubAction) UnmarshalJSON(data []byte) error {
type Alias GithubAction
aux := struct {
diff --git a/cli/pkg/integration/integration_test.go b/cli/pkg/integration/integration_test.go
index 9c45bf4a2..405249adf 100644
--- a/cli/pkg/integration/integration_test.go
+++ b/cli/pkg/integration/integration_test.go
@@ -2,18 +2,19 @@ package integration
import (
"context"
- "github.com/diggerhq/digger/libs/ci/generic"
- "github.com/diggerhq/digger/libs/execution"
- "github.com/diggerhq/digger/libs/locking"
- "github.com/diggerhq/digger/libs/locking/aws"
- "github.com/diggerhq/digger/libs/storage"
"log"
"math/rand"
"os"
"testing"
"time"
- "github.com/diggerhq/digger/libs/comment_utils/summary"
+ "github.com/diggerhq/digger/libs/ci/generic"
+ "github.com/diggerhq/digger/libs/execution"
+ "github.com/diggerhq/digger/libs/locking"
+ "github.com/diggerhq/digger/libs/locking/aws"
+ "github.com/diggerhq/digger/libs/storage"
+
+ comment_updater "github.com/diggerhq/digger/libs/comment_utils/summary"
"github.com/diggerhq/digger/cli/pkg/digger"
"github.com/diggerhq/digger/cli/pkg/github/models"
@@ -690,7 +691,6 @@ func TestUnLock(t *testing.T) {
}
func TestNonExistentGitHubEvent(t *testing.T) {
-
unknownEventContext := githubContextUnknownEventJson
_, err := models.GetGitHubContext(unknownEventContext)
println(err.Error())
diff --git a/cli/pkg/spec/manual.go b/cli/pkg/spec/manual.go
index 49f20ec5c..ec92cdb33 100644
--- a/cli/pkg/spec/manual.go
+++ b/cli/pkg/spec/manual.go
@@ -2,6 +2,10 @@ package spec
import (
"fmt"
+ "log/slog"
+ "os"
+ "os/exec"
+
"github.com/diggerhq/digger/cli/pkg/digger"
"github.com/diggerhq/digger/cli/pkg/usage"
"github.com/diggerhq/digger/cli/pkg/utils"
@@ -12,9 +16,6 @@ import (
"github.com/diggerhq/digger/libs/scheduler"
"github.com/diggerhq/digger/libs/spec"
"github.com/diggerhq/digger/libs/storage"
- "log/slog"
- "os"
- "os/exec"
)
func RunSpecManualCommand(
@@ -28,7 +29,6 @@ func RunSpecManualCommand(
PlanStorageProvider spec.PlanStorageProvider,
commentUpdaterProvider comment_summary.CommentUpdaterProvider,
) error {
-
job, err := jobProvider.GetJob(spec.Job)
if err != nil {
usage.ReportErrorAndExit(spec.VCS.Actor, fmt.Sprintf("could not get job: %v", err), 1)
@@ -37,7 +37,6 @@ func RunSpecManualCommand(
lock, err := lockProvider.GetLock(spec.Lock)
if err != nil {
usage.ReportErrorAndExit(spec.VCS.Actor, fmt.Sprintf("could not get job: %v", err), 1)
-
}
//prService, err := vcsProvider.GetPrService(spec.VCS)
diff --git a/cli/pkg/spec/spec.go b/cli/pkg/spec/spec.go
index 822d1a579..b31e4f756 100644
--- a/cli/pkg/spec/spec.go
+++ b/cli/pkg/spec/spec.go
@@ -2,6 +2,11 @@ package spec
import (
"fmt"
+ "log/slog"
+ "os"
+ "os/exec"
+ "time"
+
"github.com/diggerhq/digger/cli/pkg/digger"
"github.com/diggerhq/digger/cli/pkg/usage"
backend2 "github.com/diggerhq/digger/libs/backendapi"
@@ -9,10 +14,6 @@ import (
"github.com/diggerhq/digger/libs/scheduler"
"github.com/diggerhq/digger/libs/spec"
"github.com/samber/lo"
- "log/slog"
- "os"
- "os/exec"
- "time"
)
func reportError(spec spec.Spec, backendApi backend2.Api, message string, err error) {
@@ -36,7 +37,6 @@ func RunSpec(
variablesProvider spec.VariablesProvider,
commentUpdaterProvider comment_summary.CommentUpdaterProvider,
) error {
-
backendApi, err := backedProvider.GetBackendApi(spec.Backend)
if err != nil {
slog.Error("could not get backend api", "error", err)
diff --git a/cli/pkg/usage/usage.go b/cli/pkg/usage/usage.go
index 7325f4315..c2ed2708a 100644
--- a/cli/pkg/usage/usage.go
+++ b/cli/pkg/usage/usage.go
@@ -5,14 +5,17 @@ import (
"crypto/sha256"
"encoding/hex"
"encoding/json"
- configuration "github.com/diggerhq/digger/libs/digger_config"
"log/slog"
"net/http"
"os"
+
+ configuration "github.com/diggerhq/digger/libs/digger_config"
)
-var telemetry = true
-var source = "unknown"
+var (
+ telemetry = true
+ source = "unknown"
+)
type UsageRecord struct {
UserId interface{} `json:"userid"`
@@ -21,7 +24,7 @@ type UsageRecord struct {
Token string `json:"token"`
}
-func SendUsageRecord(repoOwner string, eventName string, action string) error {
+func SendUsageRecord(repoOwner, eventName, action string) error {
h := sha256.New()
h.Write([]byte(repoOwner))
sha := h.Sum(nil)
@@ -35,7 +38,7 @@ func SendUsageRecord(repoOwner string, eventName string, action string) error {
return sendPayload(payload)
}
-func SendLogRecord(repoOwner string, message string) error {
+func SendLogRecord(repoOwner, message string) error {
h := sha256.New()
h.Write([]byte(repoOwner))
sha := h.Sum(nil)
@@ -112,7 +115,7 @@ func init() {
}
}
-func ReportErrorAndExit(repoOwner string, message string, exitCode int) {
+func ReportErrorAndExit(repoOwner, message string, exitCode int) {
if exitCode == 0 {
slog.Info(message)
} else {
diff --git a/cli/pkg/usage/usage_test.go b/cli/pkg/usage/usage_test.go
index 5e7555a01..8c086a0b1 100644
--- a/cli/pkg/usage/usage_test.go
+++ b/cli/pkg/usage/usage_test.go
@@ -1,9 +1,10 @@
package usage
import (
- "github.com/stretchr/testify/assert"
"os"
"testing"
+
+ "github.com/stretchr/testify/assert"
)
// util function for testing of send usage record
diff --git a/cli/pkg/utils/io.go b/cli/pkg/utils/io.go
index 70d764f2a..5a65bdd84 100644
--- a/cli/pkg/utils/io.go
+++ b/cli/pkg/utils/io.go
@@ -8,8 +8,7 @@ import (
"path/filepath"
)
-func ExtractZip(zipFilePath string, outDir string) error {
-
+func ExtractZip(zipFilePath, outDir string) error {
// Open the zip file
zipReader, err := zip.OpenReader(zipFilePath)
if err != nil {
diff --git a/cli_e2e/plan_storage_test.go b/cli_e2e/plan_storage_test.go
index f8601912e..f2e1dfbb9 100644
--- a/cli_e2e/plan_storage_test.go
+++ b/cli_e2e/plan_storage_test.go
@@ -2,13 +2,14 @@ package cli_e2e
import (
"fmt"
- "github.com/diggerhq/digger/libs/locking/gcp"
- storage2 "github.com/diggerhq/digger/libs/storage"
"log"
"os"
"strings"
"testing"
+ "github.com/diggerhq/digger/libs/locking/gcp"
+ storage2 "github.com/diggerhq/digger/libs/storage"
+
"github.com/stretchr/testify/assert"
)
diff --git a/dgctl/cmd/exec.go b/dgctl/cmd/exec.go
index e2259c63e..9540a0230 100644
--- a/dgctl/cmd/exec.go
+++ b/dgctl/cmd/exec.go
@@ -8,13 +8,6 @@ import (
"context"
"encoding/json"
"fmt"
- "github.com/diggerhq/digger/dgctl/utils"
- "github.com/diggerhq/digger/libs/backendapi"
- orchestrator_scheduler "github.com/diggerhq/digger/libs/scheduler"
- "github.com/diggerhq/digger/libs/spec"
- "github.com/google/go-github/v61/github"
- "github.com/spf13/pflag"
- "github.com/spf13/viper"
"io"
"log"
"net/http"
@@ -25,6 +18,14 @@ import (
"strings"
"time"
+ "github.com/diggerhq/digger/dgctl/utils"
+ "github.com/diggerhq/digger/libs/backendapi"
+ orchestrator_scheduler "github.com/diggerhq/digger/libs/scheduler"
+ "github.com/diggerhq/digger/libs/spec"
+ "github.com/google/go-github/v61/github"
+ "github.com/spf13/pflag"
+ "github.com/spf13/viper"
+
"github.com/diggerhq/digger/libs/digger_config"
"github.com/spf13/cobra"
)
@@ -82,7 +83,7 @@ func GetUrlContents(url string) (string, error) {
return content, nil
}
-func GetSpec(diggerUrl string, authToken string, command string, actor string, projectMarshalled string, diggerConfigMarshalled string, repoFullName string) ([]byte, error) {
+func GetSpec(diggerUrl, authToken, command, actor, projectMarshalled, diggerConfigMarshalled, repoFullName string) ([]byte, error) {
payload := spec.GetSpecPayload{
Command: command,
RepoFullName: repoFullName,
@@ -104,7 +105,6 @@ func GetSpec(diggerUrl string, authToken string, command string, actor string, p
}
req, err := http.NewRequest("POST", u.String(), bytes.NewBuffer(jsonData))
-
if err != nil {
return nil, fmt.Errorf("error while creating request: %v", err)
}
@@ -114,7 +114,6 @@ func GetSpec(diggerUrl string, authToken string, command string, actor string, p
client := http.DefaultClient
resp, err := client.Do(req)
-
if err != nil {
return nil, fmt.Errorf("error while sending request: %v", err)
}
@@ -131,7 +130,7 @@ func GetSpec(diggerUrl string, authToken string, command string, actor string, p
return body, nil
}
-func GetWorkflowIdAndUrlFromDiggerJobId(client *github.Client, repoOwner string, repoName string, diggerJobID string) (*int64, *int64, *string, error) {
+func GetWorkflowIdAndUrlFromDiggerJobId(client *github.Client, repoOwner, repoName, diggerJobID string) (*int64, *int64, *string, error) {
timeFilter := time.Now().Add(-5 * time.Minute)
runs, _, err := client.Actions.ListRepositoryWorkflowRuns(context.Background(), repoOwner, repoName, &github.ListWorkflowRunsOptions{
Created: ">=" + timeFilter.Format(time.RFC3339),
@@ -160,7 +159,6 @@ func GetWorkflowIdAndUrlFromDiggerJobId(client *github.Client, repoOwner string,
}
func cleanupDiggerOutput(output string) string {
-
startingDelimiter := "<========= DIGGER RUNNING IN MANUAL MODE =========>"
endingDelimiter := "<========= DIGGER COMPLETED =========>"
@@ -332,7 +330,6 @@ var execCmd = &cobra.Command{
log.Printf("streaming logs from remote job:")
logsContent, err := GetUrlContents(logs.String())
-
if err != nil {
log.Printf("error while fetching logs: %v", err)
os.Exit(1)
@@ -360,5 +357,4 @@ func init() {
}
rootCmd.AddCommand(execCmd)
-
}
diff --git a/dgctl/cmd/root.go b/dgctl/cmd/root.go
index d0f76d928..a9c68e029 100644
--- a/dgctl/cmd/root.go
+++ b/dgctl/cmd/root.go
@@ -53,5 +53,5 @@ func init() {
// Cobra also supports local flags, which will only run
// when this action is called directly.
- //rootCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
+ // rootCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
}
diff --git a/dgctl/main.go b/dgctl/main.go
index c7dc1d1a9..d3c648f23 100644
--- a/dgctl/main.go
+++ b/dgctl/main.go
@@ -16,9 +16,10 @@ limitations under the License.
package main
import (
- "github.com/diggerhq/digger/dgctl/cmd"
"log"
"os"
+
+ "github.com/diggerhq/digger/dgctl/cmd"
)
func init() {
diff --git a/dgctl/utils/gitio.go b/dgctl/utils/gitio.go
index c4f10b150..9efae8c02 100644
--- a/dgctl/utils/gitio.go
+++ b/dgctl/utils/gitio.go
@@ -17,7 +17,7 @@ func ArchiveGitRepo(sourcePath string) (string, error) {
return "", fmt.Errorf("failed to create temp dir: %v", err)
}
// Create the temp directory
- if err := os.MkdirAll(tempDir, 0755); err != nil {
+ if err := os.MkdirAll(tempDir, 0o755); err != nil {
return "", fmt.Errorf("failed to create temp directory: %w", err)
}
diff --git a/ee/backend/ci_backends/bitbucket_pipeline.go b/ee/backend/ci_backends/bitbucket_pipeline.go
index 83930b152..1a8679825 100644
--- a/ee/backend/ci_backends/bitbucket_pipeline.go
+++ b/ee/backend/ci_backends/bitbucket_pipeline.go
@@ -3,6 +3,7 @@ package ci_backends
import (
"encoding/json"
"fmt"
+
orchestrator_bitbucket "github.com/diggerhq/digger/libs/ci/bitbucket"
"github.com/diggerhq/digger/libs/spec"
)
@@ -14,7 +15,7 @@ type BitbucketPipelineCI struct {
Branch string
}
-func (bbp BitbucketPipelineCI) TriggerWorkflow(spec spec.Spec, runName string, vcsToken string) error {
+func (bbp BitbucketPipelineCI) TriggerWorkflow(spec spec.Spec, runName, vcsToken string) error {
specBytes, err := json.Marshal(spec)
if err != nil {
return fmt.Errorf("could not serialize spec: %v", err)
diff --git a/ee/backend/ci_backends/buildkite.go b/ee/backend/ci_backends/buildkite.go
index bda487327..0febcf587 100644
--- a/ee/backend/ci_backends/buildkite.go
+++ b/ee/backend/ci_backends/buildkite.go
@@ -2,6 +2,7 @@ package ci_backends
import (
"encoding/json"
+
"github.com/buildkite/go-buildkite/v3/buildkite"
"github.com/diggerhq/digger/libs/spec"
)
@@ -12,8 +13,7 @@ type BuildkiteCi struct {
Pipeline string
}
-func (b BuildkiteCi) TriggerWorkflow(spec spec.Spec, runName string, vcsToken string) error {
-
+func (b BuildkiteCi) TriggerWorkflow(spec spec.Spec, runName, vcsToken string) error {
specBytes, err := json.Marshal(spec)
client := b.Client
_, _, err = client.Builds.Create(b.Org, b.Pipeline, &buildkite.CreateBuild{
@@ -29,7 +29,6 @@ func (b BuildkiteCi) TriggerWorkflow(spec spec.Spec, runName string, vcsToken st
})
return err
-
}
func (b BuildkiteCi) GetWorkflowUrl(spec spec.Spec) (string, error) {
diff --git a/ee/backend/ci_backends/gitlab_pipeline.go b/ee/backend/ci_backends/gitlab_pipeline.go
index 05ca09ad1..78b217626 100644
--- a/ee/backend/ci_backends/gitlab_pipeline.go
+++ b/ee/backend/ci_backends/gitlab_pipeline.go
@@ -3,9 +3,10 @@ package ci_backends
import (
"encoding/json"
"fmt"
+ "strconv"
+
"github.com/diggerhq/digger/libs/spec"
"github.com/xanzy/go-gitlab"
- "strconv"
)
type GitlabPipelineCI struct {
@@ -23,7 +24,7 @@ type GitlabPipelineCI struct {
GitlabDiscussionId string
}
-func (gl GitlabPipelineCI) TriggerWorkflow(spec spec.Spec, runName string, vcsToken string) error {
+func (gl GitlabPipelineCI) TriggerWorkflow(spec spec.Spec, runName, vcsToken string) error {
specBytes, err := json.Marshal(spec)
if err != nil {
return fmt.Errorf("could not serialize spec: %v", err)
diff --git a/ee/backend/ci_backends/provider.go b/ee/backend/ci_backends/provider.go
index abac53968..c1ff6e1ce 100644
--- a/ee/backend/ci_backends/provider.go
+++ b/ee/backend/ci_backends/provider.go
@@ -2,11 +2,12 @@ package ci_backends
import (
"fmt"
+ "log"
+ "os"
+
"github.com/buildkite/go-buildkite/v3/buildkite"
"github.com/diggerhq/digger/backend/ci_backends"
"github.com/diggerhq/digger/backend/utils"
- "log"
- "os"
)
type EEBackendProvider struct{}
diff --git a/ee/backend/controllers/artefacts.go b/ee/backend/controllers/artefacts.go
index f4d359d9a..b7054c4f9 100644
--- a/ee/backend/controllers/artefacts.go
+++ b/ee/backend/controllers/artefacts.go
@@ -2,13 +2,14 @@ package controllers
import (
"fmt"
+ "io"
+ "log"
+ "net/http"
+
"github.com/diggerhq/digger/backend/middleware"
"github.com/diggerhq/digger/backend/models"
"github.com/gin-gonic/gin"
"github.com/google/uuid"
- "io"
- "log"
- "net/http"
)
func SetJobArtefact(c *gin.Context) {
@@ -70,7 +71,6 @@ func SetJobArtefact(c *gin.Context) {
}
c.JSON(http.StatusOK, gin.H{"message": "File uploaded successfully", "id": artefactRecord.ID})
-
}
func DownloadJobArtefact(c *gin.Context) {
diff --git a/ee/backend/controllers/bitbucket.go b/ee/backend/controllers/bitbucket.go
index 6c312f39d..4603644de 100644
--- a/ee/backend/controllers/bitbucket.go
+++ b/ee/backend/controllers/bitbucket.go
@@ -100,9 +100,9 @@ func (ee DiggerEEController) BitbucketWebhookHandler(c *gin.Context) {
return
}
- var pullRequestCommentCreated = BitbucketCommentCreatedEvent{}
- var repoPush = BitbucketPushEvent{}
- var pullRequestCreated = BitbucketPullRequestCreatedEvent{}
+ pullRequestCommentCreated := BitbucketCommentCreatedEvent{}
+ repoPush := BitbucketPushEvent{}
+ pullRequestCreated := BitbucketPullRequestCreatedEvent{}
bodyBytes, err := io.ReadAll(c.Request.Body)
if err != nil {
@@ -162,10 +162,10 @@ func handleIssueCommentEventBB(bitbucketProvider utils.BitbucketProvider, payloa
commentBody := payload.Comment.Content.Raw
branch := payload.PullRequest.Source.Branch.Name
// TODO: figure why git fetch fails in bb pipeline
- commitSha := "" //payload.PullRequest.Source.Commit.Hash
+ commitSha := "" // payload.PullRequest.Source.Commit.Hash
defaultBranch := payload.PullRequest.Source.Branch.Name
actor := payload.Actor.Nickname
- //discussionId := payload.Comment.ID
+ // discussionId := payload.Comment.ID
if !strings.HasPrefix(commentBody, "digger") {
log.Printf("comment is not a Digger command, ignoring")
diff --git a/ee/backend/controllers/github.go b/ee/backend/controllers/github.go
index 1fbf7fd22..0362b6a1f 100644
--- a/ee/backend/controllers/github.go
+++ b/ee/backend/controllers/github.go
@@ -5,15 +5,16 @@ import (
"encoding/base64"
"encoding/json"
"fmt"
- "github.com/diggerhq/digger/backend/models"
- "github.com/diggerhq/digger/backend/utils"
- "github.com/diggerhq/digger/ee/drift/middleware"
- "github.com/gin-gonic/gin"
"log"
"math/rand"
"net/http"
"net/url"
"os"
+
+ "github.com/diggerhq/digger/backend/models"
+ "github.com/diggerhq/digger/backend/utils"
+ "github.com/diggerhq/digger/ee/drift/middleware"
+ "github.com/gin-gonic/gin"
)
func GithubAppConnections(c *gin.Context) {
@@ -148,7 +149,6 @@ func (d DiggerEEController) GithubAppConnectionsConfirm(c *gin.Context) {
PemBase64 := base64.StdEncoding.EncodeToString([]byte(PEM))
encrypt := func(val string) (string, error) {
-
secret := os.Getenv("DIGGER_ENCRYPTION_SECRET")
if secret == "" {
log.Printf("ERROR: no encryption secret specified, please specify DIGGER_ENCRYPTION_SECRET as 32 bytes base64 string")
diff --git a/ee/backend/controllers/gitlab.go b/ee/backend/controllers/gitlab.go
index 8cd099a95..e15bbdfe7 100644
--- a/ee/backend/controllers/gitlab.go
+++ b/ee/backend/controllers/gitlab.go
@@ -39,7 +39,7 @@ func (d DiggerEEController) GitlabWebHookHandler(c *gin.Context) {
c.Header("Content-Type", "application/json")
log.Printf("GitlabWebhook")
- //temp to get orgID TODO: fetch from db
+ // temp to get orgID TODO: fetch from db
organisation, err := models.DB.GetOrganisation(models.DEFAULT_ORG_NAME)
if err != nil {
c.String(http.StatusInternalServerError, "Failed to get default organisation")
@@ -103,7 +103,7 @@ func (d DiggerEEController) GitlabWebHookHandler(c *gin.Context) {
}
func GetGitlabRepoUrl(event interface{}) string {
- var repoUrl = ""
+ repoUrl := ""
switch event := event.(type) {
case *gitlab.MergeCommentEvent:
repoUrl = event.Project.GitHTTPURL
@@ -127,10 +127,10 @@ func handlePullRequestEvent(gitlabProvider utils.GitlabProvider, payload *gitlab
branch := payload.ObjectAttributes.SourceBranch
commitSha := payload.ObjectAttributes.LastCommit.ID
action := payload.ObjectAttributes.Action
- //defaultBranch := payload.Repository.DefaultBranch
- //actor := payload.User.Username
- //discussionId := ""
- //action := payload.ObjectAttributes.Action
+ // defaultBranch := payload.Repository.DefaultBranch
+ // actor := payload.User.Username
+ // discussionId := ""
+ // action := payload.ObjectAttributes.Action
// temp hack: we initialize glService to publish an initial comment and then use that as a discussionId onwards (
glService, glerr := utils.GetGitlabService(gitlabProvider, projectId, repoName, repoFullName, prNumber, "")
@@ -308,10 +308,10 @@ func handlePullRequestEvent(gitlabProvider utils.GitlabProvider, payload *gitlab
GitlabCIMergeRequestIID: payload.ObjectAttributes.IID,
GitlabciprojectId: payload.Project.ID,
GitlabciprojectNamespace: payload.Project.Namespace,
- //GitlabciprojectNamespaceId: 0,
+ // GitlabciprojectNamespaceId: 0,
GitlabmergeRequestEventName: payload.EventType,
- //GitlabCIPipelineID: ,
- //GitlabCIPipelineIID: "",
+ // GitlabCIPipelineID: ,
+ // GitlabCIPipelineIID: "",
GitlabCIProjectName: payload.Project.Name,
GitlabDiscussionId: discussionId,
},
@@ -530,10 +530,10 @@ func handleIssueCommentEvent(gitlabProvider utils.GitlabProvider, payload *gitla
GitlabCIMergeRequestIID: payload.MergeRequest.IID,
GitlabciprojectId: payload.ProjectID,
GitlabciprojectNamespace: payload.Project.Namespace,
- //GitlabciprojectNamespaceId: payload.Project.Namespace,
+ // GitlabciprojectNamespaceId: payload.Project.Namespace,
GitlabmergeRequestEventName: payload.EventType,
- //GitlabCIPipelineID: ,
- //GitlabCIPipelineIID: "",
+ // GitlabCIPipelineID: ,
+ // GitlabCIPipelineIID: "",
GitlabCIProjectName: payload.Project.Name,
GitlabDiscussionId: discussionId,
},
diff --git a/ee/backend/controllers/spec.go b/ee/backend/controllers/spec.go
index 929ae5a06..aa5a76da2 100644
--- a/ee/backend/controllers/spec.go
+++ b/ee/backend/controllers/spec.go
@@ -3,6 +3,11 @@ package controllers
import (
"encoding/json"
"fmt"
+ "log"
+ "net/http"
+ "os"
+ "strings"
+
"github.com/dchest/uniuri"
"github.com/diggerhq/digger/backend/models"
"github.com/diggerhq/digger/libs/ci/generic"
@@ -10,10 +15,6 @@ import (
"github.com/diggerhq/digger/libs/scheduler"
"github.com/diggerhq/digger/libs/spec"
"github.com/gin-gonic/gin"
- "log"
- "net/http"
- "os"
- "strings"
)
func (d DiggerEEController) GetSpec(c *gin.Context) {
@@ -32,9 +33,9 @@ func (d DiggerEEController) GetSpec(c *gin.Context) {
actor := payload.Actor
commitSha := ""
- //defaultBranch := payload.DefaultBranch
- //prBranch := payload.PrBranch
- issueNumber := 000
+ // defaultBranch := payload.DefaultBranch
+ // prBranch := payload.PrBranch
+ issueNumber := 0o00
config := digger_config.DiggerConfig{}
err := json.Unmarshal([]byte(payload.DiggerConfig), &config)
@@ -62,7 +63,7 @@ func (d DiggerEEController) GetSpec(c *gin.Context) {
}
job := jobs[0]
- //temp to get orgID TODO: fetch from db
+ // temp to get orgID TODO: fetch from db
org, err := models.DB.GetOrganisation(models.DEFAULT_ORG_NAME)
if err != nil {
c.String(http.StatusInternalServerError, "Failed to get default organisation")
@@ -82,7 +83,7 @@ func (d DiggerEEController) GetSpec(c *gin.Context) {
spec := spec.Spec{
SpecType: spec.SpecTypeManualJob,
JobId: uniuri.New(),
- //CommentId: "",
+ // CommentId: "",
Job: jobSpec,
Reporter: spec.ReporterSpec{
ReportingStrategy: "comments_per_run",
@@ -116,5 +117,4 @@ func (d DiggerEEController) GetSpec(c *gin.Context) {
log.Printf("specBytes: %v", spec)
c.String(200, string(specBytes))
return
-
}
diff --git a/ee/backend/main.go b/ee/backend/main.go
index 64267c8cd..fd73064a2 100644
--- a/ee/backend/main.go
+++ b/ee/backend/main.go
@@ -4,6 +4,10 @@ import (
"crypto/fips140"
"embed"
"fmt"
+ "log"
+ "net/http"
+ "os"
+
"github.com/diggerhq/digger/backend/bootstrap"
"github.com/diggerhq/digger/backend/config"
ce_controllers "github.com/diggerhq/digger/backend/controllers"
@@ -15,9 +19,6 @@ import (
"github.com/diggerhq/digger/ee/backend/providers/github"
"github.com/diggerhq/digger/libs/license"
"github.com/gin-gonic/gin"
- "log"
- "net/http"
- "os"
)
// based on https://www.digitalocean.com/community/tutorials/using-ldflags-to-set-version-information-for-go-applications
@@ -100,7 +101,6 @@ func main() {
c.HTML(http.StatusOK, "healthy.tmpl", gin.H{})
return
})
-
}
jobArtefactsGroup := r.Group("/job_artefacts")
diff --git a/ee/backend/providers/github/providers.go b/ee/backend/providers/github/providers.go
index 845c2506b..bb74b2568 100644
--- a/ee/backend/providers/github/providers.go
+++ b/ee/backend/providers/github/providers.go
@@ -4,17 +4,17 @@ import (
"context"
"encoding/base64"
"fmt"
+ "log"
+ net "net/http"
+ "os"
+
"github.com/bradleyfalzon/ghinstallation/v2"
"github.com/diggerhq/digger/backend/models"
"github.com/diggerhq/digger/backend/utils"
"github.com/google/go-github/v61/github"
- "log"
- net "net/http"
- "os"
)
-type DiggerGithubEEClientProvider struct {
-}
+type DiggerGithubEEClientProvider struct{}
func (gh DiggerGithubEEClientProvider) NewClient(netClient *net.Client) (*github.Client, error) {
ghClient := github.NewClient(netClient)
@@ -38,7 +38,7 @@ func getGithubEnterpriseUrls(githubHostname string) (string, string) {
return githubEnterpriseBaseUrl, githubEnterpriseUploadUrl
}
-func (gh DiggerGithubEEClientProvider) Get(githubAppId int64, installationId int64) (*github.Client, *string, error) {
+func (gh DiggerGithubEEClientProvider) Get(githubAppId, installationId int64) (*github.Client, *string, error) {
githubAppPrivateKey := ""
githubAppPrivateKeyB64 := os.Getenv("GITHUB_APP_PRIVATE_KEY_BASE64")
diff --git a/ee/cli/cmd/digger/default.go b/ee/cli/cmd/digger/default.go
index ee6060a62..405796ff5 100644
--- a/ee/cli/cmd/digger/default.go
+++ b/ee/cli/cmd/digger/default.go
@@ -4,6 +4,10 @@ import (
"crypto/fips140"
"encoding/json"
"fmt"
+ "log"
+ "os"
+ "runtime/debug"
+
"github.com/diggerhq/digger/cli/pkg/digger"
"github.com/diggerhq/digger/cli/pkg/github"
spec2 "github.com/diggerhq/digger/cli/pkg/spec"
@@ -17,9 +21,6 @@ import (
comment_summary "github.com/diggerhq/digger/libs/comment_utils/summary"
lib_spec "github.com/diggerhq/digger/libs/spec"
"github.com/spf13/cobra"
- "log"
- "os"
- "runtime/debug"
)
var defaultCmd = &cobra.Command{
@@ -62,7 +63,7 @@ var defaultCmd = &cobra.Command{
usage.ReportErrorAndExit(spec.VCS.Actor, "Successfully ran spec", 0)
}
- var logLeader = "Unknown CI"
+ logLeader := "Unknown CI"
ci := digger.DetectCI()
switch ci {
diff --git a/ee/cli/cmd/digger/main.go b/ee/cli/cmd/digger/main.go
index 0f5dfd7f9..d8cafa20d 100644
--- a/ee/cli/cmd/digger/main.go
+++ b/ee/cli/cmd/digger/main.go
@@ -2,10 +2,11 @@ package main
import (
"fmt"
- "github.com/diggerhq/digger/cli/pkg/usage"
- "github.com/diggerhq/digger/libs/license"
"log"
"os"
+
+ "github.com/diggerhq/digger/cli/pkg/usage"
+ "github.com/diggerhq/digger/libs/license"
)
/*
@@ -34,7 +35,6 @@ func main() {
if err := rootCmd.Execute(); err != nil {
usage.ReportErrorAndExit("", fmt.Sprintf("Error occurred during command exec: %v", err), 8)
}
-
}
func init() {
diff --git a/ee/cli/cmd/digger/main_test.go b/ee/cli/cmd/digger/main_test.go
index 2e8cd98f2..9269904bc 100644
--- a/ee/cli/cmd/digger/main_test.go
+++ b/ee/cli/cmd/digger/main_test.go
@@ -1,26 +1,26 @@
package main
import (
+ "log"
+ "testing"
+
"github.com/diggerhq/digger/libs/backendapi"
"github.com/diggerhq/digger/libs/ci"
"github.com/diggerhq/digger/libs/ci/generic"
"github.com/diggerhq/digger/libs/locking"
"github.com/diggerhq/digger/libs/policy"
"github.com/diggerhq/digger/libs/storage"
- "log"
"github.com/diggerhq/digger/cli/pkg/digger"
"github.com/diggerhq/digger/cli/pkg/github/models"
ghmodels "github.com/diggerhq/digger/cli/pkg/github/models"
dggithub "github.com/diggerhq/digger/libs/ci/github"
"github.com/diggerhq/digger/libs/comment_utils/reporting"
- "github.com/diggerhq/digger/libs/comment_utils/summary"
+ comment_updater "github.com/diggerhq/digger/libs/comment_utils/summary"
configuration "github.com/diggerhq/digger/libs/digger_config"
"github.com/google/go-github/v61/github"
- "testing"
-
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
@@ -874,7 +874,6 @@ var githubInvalidContextJson = `{
`
func TestGitHubNewPullRequestContext(t *testing.T) {
-
actionContext, err := models.GetGitHubContext(githubContextNewPullRequestJson)
context := actionContext.ToEventPackage()
@@ -997,7 +996,7 @@ func TestGitHubNewPullRequestInMultiEnvProjectContext(t *testing.T) {
// PullRequestManager Mock
prManager := ci.MockPullRequestManager{ChangedFiles: []string{"dev/test.tf"}}
- //lock := locking.MockLock{}
+ // lock := locking.MockLock{}
impactedProjects, requestedProject, prNumber, err := dggithub.ProcessGitHubEvent(ghEvent, &diggerConfig, &prManager)
assert.NoError(t, err)
event := context.Event.(github.PullRequestEvent)
@@ -1029,7 +1028,7 @@ func TestGitHubTestPRCommandCaseInsensitivity(t *testing.T) {
var impactedProjects []configuration.Project
impactedProjects = make([]configuration.Project, 1)
impactedProjects[0] = project
- var requestedProject = project
+ requestedProject := project
workflows := make(map[string]configuration.Workflow, 1)
workflows["default"] = configuration.Workflow{}
jobs, _, err := generic.ConvertIssueCommentEventToJobs(*repo.FullName, *user.Login, *issue.Number, "digger plan", impactedProjects, &requestedProject, workflows, "prbranch", "main")
diff --git a/ee/cli/cmd/digger/root.go b/ee/cli/cmd/digger/root.go
index 30ca27146..095e509e1 100644
--- a/ee/cli/cmd/digger/root.go
+++ b/ee/cli/cmd/digger/root.go
@@ -2,6 +2,11 @@ package main
import (
"fmt"
+ "log"
+ "net/http"
+ "os"
+ "time"
+
"github.com/diggerhq/digger/cli/pkg/utils"
"github.com/diggerhq/digger/libs/backendapi"
"github.com/diggerhq/digger/libs/ci"
@@ -11,10 +16,6 @@ import (
"github.com/diggerhq/digger/libs/locking"
"github.com/diggerhq/digger/libs/policy"
"github.com/spf13/cobra"
- "log"
- "net/http"
- "os"
- "time"
)
type RunConfig struct {
@@ -76,12 +77,13 @@ func (r *RunConfig) GetServices() (*ci.PullRequestService, *ci.OrgService, *repo
return &prService, &orgService, &reporter, nil
}
-var BackendApi backendapi.Api
-var ReportStrategy reporting.ReportStrategy
-var lock locking.Lock
+var (
+ BackendApi backendapi.Api
+ ReportStrategy reporting.ReportStrategy
+ lock locking.Lock
+)
func PreRun(cmd *cobra.Command, args []string) {
-
hostName := os.Getenv("DIGGER_HOSTNAME")
token := os.Getenv("DIGGER_TOKEN")
BackendApi = NewBackendApi(hostName, token)
@@ -113,7 +115,7 @@ func PreRun(cmd *cobra.Command, args []string) {
log.Println("Lock provider has been created successfully")
}
-func NewBackendApi(hostName string, authToken string) backendapi.Api {
+func NewBackendApi(hostName, authToken string) backendapi.Api {
var backendApi backendapi.Api
if os.Getenv("NO_BACKEND") == "true" {
log.Println("WARNING: running in 'backendless' mode. Features that require backend will not be available.")
@@ -128,7 +130,7 @@ func NewBackendApi(hostName string, authToken string) backendapi.Api {
return backendApi
}
-func NewPolicyChecker(hostname string, organisationName string, authToken string) policy.Checker {
+func NewPolicyChecker(hostname, organisationName, authToken string) policy.Checker {
var policyChecker policy.Checker
if os.Getenv("NO_BACKEND") == "true" {
log.Println("WARNING: running in 'backendless' mode. Features that require backend will not be available.")
@@ -140,7 +142,8 @@ func NewPolicyChecker(hostname string, organisationName string, authToken string
DiggerOrganisation: organisationName,
AuthToken: authToken,
HttpClient: http.DefaultClient,
- }}
+ },
+ }
}
return policyChecker
}
diff --git a/ee/cli/cmd/digger/run_spec.go b/ee/cli/cmd/digger/run_spec.go
index 8cc624305..d88f72bca 100644
--- a/ee/cli/cmd/digger/run_spec.go
+++ b/ee/cli/cmd/digger/run_spec.go
@@ -3,6 +3,8 @@ package main
import (
"encoding/json"
"fmt"
+ "strings"
+
spec2 "github.com/diggerhq/digger/cli/pkg/spec"
"github.com/diggerhq/digger/cli/pkg/usage"
"github.com/diggerhq/digger/ee/cli/pkg/policy"
@@ -11,7 +13,6 @@ import (
"github.com/spf13/cobra"
"github.com/spf13/pflag"
"github.com/spf13/viper"
- "strings"
)
var viperRunSpec *viper.Viper
diff --git a/ee/cli/pkg/comment_updater/provider.go b/ee/cli/pkg/comment_updater/provider.go
index 84f9a91fa..83b295076 100644
--- a/ee/cli/pkg/comment_updater/provider.go
+++ b/ee/cli/pkg/comment_updater/provider.go
@@ -2,12 +2,12 @@ package comment_updater
import (
"fmt"
+
comment_updater "github.com/diggerhq/digger/libs/comment_utils/summary"
"github.com/diggerhq/digger/libs/digger_config"
)
-type CommentUpdaterProviderAdvanced struct {
-}
+type CommentUpdaterProviderAdvanced struct{}
func (c CommentUpdaterProviderAdvanced) Get(renderMode string) (comment_updater.CommentUpdater, error) {
if renderMode == digger_config.CommentRenderModeBasic {
diff --git a/ee/cli/pkg/comment_updater/updater.go b/ee/cli/pkg/comment_updater/updater.go
index 98d955863..c36a32d0c 100644
--- a/ee/cli/pkg/comment_updater/updater.go
+++ b/ee/cli/pkg/comment_updater/updater.go
@@ -3,14 +3,14 @@ package comment_updater
import (
"encoding/json"
"fmt"
- "github.com/diggerhq/digger/libs/ci"
- "github.com/diggerhq/digger/libs/scheduler"
"log"
"strings"
+
+ "github.com/diggerhq/digger/libs/ci"
+ "github.com/diggerhq/digger/libs/scheduler"
)
-type AdvancedCommentUpdater struct {
-}
+type AdvancedCommentUpdater struct{}
func DriftSummaryString(projectName string, issuesMap *map[string]*ci.Issue) string {
driftStatusForProject := (*issuesMap)[projectName]
@@ -22,7 +22,6 @@ func DriftSummaryString(projectName string, issuesMap *map[string]*ci.Issue) str
}
func (a AdvancedCommentUpdater) UpdateComment(jobs []scheduler.SerializedJob, prNumber int, prService ci.PullRequestService, prCommentId string) error {
-
issuesMap, err := getDriftStatusesFromPRIssues(jobs, prService)
if err != nil {
return fmt.Errorf("error while fetching drift status: %v", err)
diff --git a/ee/cli/pkg/drift/github_issue.go b/ee/cli/pkg/drift/github_issue.go
index ada018071..702c67e82 100644
--- a/ee/cli/pkg/drift/github_issue.go
+++ b/ee/cli/pkg/drift/github_issue.go
@@ -2,9 +2,10 @@ package drift
import (
"fmt"
+ "log"
+
orchestrator "github.com/diggerhq/digger/libs/ci"
"github.com/samber/lo"
- "log"
)
type GithubIssueNotification struct {
@@ -12,7 +13,7 @@ type GithubIssueNotification struct {
RelatedPrNumber *int64
}
-func (ghi GithubIssueNotification) Send(projectName string, plan string) error {
+func (ghi GithubIssueNotification) Send(projectName, plan string) error {
log.Printf("Info: Sending drift notification regarding project: %v", projectName)
title := fmt.Sprintf("Drift detected in project: %v", projectName)
message := fmt.Sprintf(":bangbang: Drift detected in digger project %v details below: \n\n```\n%v\n```", projectName, plan)
diff --git a/ee/cli/pkg/drift/provider.go b/ee/cli/pkg/drift/provider.go
index f5f3a173f..a31edd873 100644
--- a/ee/cli/pkg/drift/provider.go
+++ b/ee/cli/pkg/drift/provider.go
@@ -2,10 +2,11 @@ package drift
import (
"fmt"
+ "os"
+
core_drift "github.com/diggerhq/digger/cli/pkg/core/drift"
"github.com/diggerhq/digger/cli/pkg/drift"
"github.com/diggerhq/digger/libs/ci"
- "os"
)
type DriftNotificationProviderAdvanced struct{}
diff --git a/ee/cli/pkg/github/providers.go b/ee/cli/pkg/github/providers.go
index 6560b2b3b..70a9d657a 100644
--- a/ee/cli/pkg/github/providers.go
+++ b/ee/cli/pkg/github/providers.go
@@ -2,15 +2,16 @@ package github
import (
"fmt"
- dg_github "github.com/diggerhq/digger/libs/ci/github"
- "github.com/google/go-github/v61/github"
"log"
"os"
+
+ dg_github "github.com/diggerhq/digger/libs/ci/github"
+ "github.com/google/go-github/v61/github"
)
type GithubServiceProviderAdvanced struct{}
-func (_ GithubServiceProviderAdvanced) NewService(ghToken string, repoName string, owner string) (dg_github.GithubService, error) {
+func (_ GithubServiceProviderAdvanced) NewService(ghToken, repoName, owner string) (dg_github.GithubService, error) {
client := github.NewClient(nil)
if ghToken != "" {
client = client.WithAuthToken(ghToken)
diff --git a/ee/cli/pkg/gitlab/gitlab.go b/ee/cli/pkg/gitlab/gitlab.go
index 501984052..5c0cd5d47 100644
--- a/ee/cli/pkg/gitlab/gitlab.go
+++ b/ee/cli/pkg/gitlab/gitlab.go
@@ -2,6 +2,9 @@ package gitlab
import (
"fmt"
+ "log"
+ "os"
+
"github.com/diggerhq/digger/cli/pkg/digger"
"github.com/diggerhq/digger/cli/pkg/drift"
"github.com/diggerhq/digger/cli/pkg/usage"
@@ -13,8 +16,6 @@ import (
core_locking "github.com/diggerhq/digger/libs/locking"
core_policy "github.com/diggerhq/digger/libs/policy"
"github.com/diggerhq/digger/libs/scheduler"
- "log"
- "os"
)
func GitLabCI(lock core_locking.Lock, policyCheckerProvider core_policy.PolicyCheckerProvider, backendApi core_backend.Api, reportingStrategy reporting.ReportStrategy, githubServiceProvider dg_github.GithubServiceProvider, commentUpdaterProvider comment_updater.CommentUpdaterProvider, driftNotificationProvider drift.DriftNotificationProvider) {
@@ -42,7 +43,7 @@ func GitLabCI(lock core_locking.Lock, policyCheckerProvider core_policy.PolicyCh
log.Printf("Digger digger_config read successfully\n")
// default policy checker for backwards compatibility, will be overridden in orchestrator flow
- var policyChecker = core_policy.NoOpPolicyChecker{}
+ policyChecker := core_policy.NoOpPolicyChecker{}
currentDir, err := os.Getwd()
if err != nil {
@@ -66,7 +67,6 @@ func GitLabCI(lock core_locking.Lock, policyCheckerProvider core_policy.PolicyCh
runningMode := os.Getenv("INPUT_DIGGER_MODE")
if runningMode == "drift-detection" {
-
for _, projectConfig := range diggerConfig.Projects {
if !projectConfig.DriftDetection {
continue
@@ -125,5 +125,4 @@ func GitLabCI(lock core_locking.Lock, policyCheckerProvider core_policy.PolicyCh
println("Commands executed successfully")
usage.ReportErrorAndExit(repoOwner, "Digger finished successfully", 0)
-
}
diff --git a/ee/cli/pkg/policy/policy.go b/ee/cli/pkg/policy/policy.go
index 3919fcdef..fc26bf377 100644
--- a/ee/cli/pkg/policy/policy.go
+++ b/ee/cli/pkg/policy/policy.go
@@ -1,13 +1,14 @@
package policy
import (
- "github.com/diggerhq/digger/libs/git_utils"
- "github.com/samber/lo"
"os"
"path"
"path/filepath"
"slices"
"strings"
+
+ "github.com/diggerhq/digger/libs/git_utils"
+ "github.com/samber/lo"
)
const DefaultAccessPolicy = `
@@ -40,7 +41,7 @@ func getContents(filePath string) (string, error) {
// /dev/vpc/subnets/access.rego
// /dev/vpc/access.rego
// /dev/access.rego
-func GetPrefixesForPath(path string, fileName string) []string {
+func GetPrefixesForPath(path, fileName string) []string {
var prefixes []string
parts := strings.Split(filepath.Clean(path), string(filepath.Separator))
for i := range parts {
@@ -60,7 +61,7 @@ func GetPrefixesForPath(path string, fileName string) []string {
return prefixes
}
-func (p DiggerRepoPolicyProvider) getPolicyFileContents(repo string, projectName string, projectDir string, fileName string) (string, error) {
+func (p DiggerRepoPolicyProvider) getPolicyFileContents(repo, projectName, projectDir, fileName string) (string, error) {
var contents string
err := git_utils.CloneGitRepoAndDoAction(p.ManagementRepoUrl, "main", "", p.GitToken, "", func(basePath string) error {
// we start with the project directory path prefixes as the highest priority
@@ -96,7 +97,7 @@ func (p DiggerRepoPolicyProvider) getPolicyFileContents(repo string, projectName
}
// GetPolicy fetches policy for particular project, if not found then it will fallback to org level policy
-func (p DiggerRepoPolicyProvider) GetAccessPolicy(organisation string, repo string, projectName string, projectDir string) (string, error) {
+func (p DiggerRepoPolicyProvider) GetAccessPolicy(organisation, repo, projectName, projectDir string) (string, error) {
policy, err := p.getPolicyFileContents(repo, projectName, projectDir, "access.rego")
if err != nil {
return policy, err
@@ -107,7 +108,7 @@ func (p DiggerRepoPolicyProvider) GetAccessPolicy(organisation string, repo stri
return policy, err
}
-func (p DiggerRepoPolicyProvider) GetPlanPolicy(organisation string, repository string, projectname string, projectDir string) (string, error) {
+func (p DiggerRepoPolicyProvider) GetPlanPolicy(organisation, repository, projectname, projectDir string) (string, error) {
policy, err := p.getPolicyFileContents(repository, projectname, projectDir, "plan.rego")
if err != nil {
return policy, err
@@ -117,7 +118,6 @@ func (p DiggerRepoPolicyProvider) GetPlanPolicy(organisation string, repository
func (p DiggerRepoPolicyProvider) GetDriftPolicy() (string, error) {
return "", nil
-
}
func (p DiggerRepoPolicyProvider) GetOrganisation() string {
diff --git a/ee/cli/pkg/policy/policy_test.go b/ee/cli/pkg/policy/policy_test.go
index a46fe22e0..5ac482f31 100644
--- a/ee/cli/pkg/policy/policy_test.go
+++ b/ee/cli/pkg/policy/policy_test.go
@@ -1,10 +1,11 @@
package policy
import (
- "github.com/stretchr/testify/assert"
"log"
"os"
"testing"
+
+ "github.com/stretchr/testify/assert"
)
func init() {
diff --git a/ee/cli/pkg/policy/providers.go b/ee/cli/pkg/policy/providers.go
index 8226a3fd8..42bd80ff1 100644
--- a/ee/cli/pkg/policy/providers.go
+++ b/ee/cli/pkg/policy/providers.go
@@ -2,20 +2,21 @@ package policy
import (
"fmt"
- "github.com/diggerhq/digger/libs/policy"
- lib_spec "github.com/diggerhq/digger/libs/spec"
"log"
"os"
+
+ "github.com/diggerhq/digger/libs/policy"
+ lib_spec "github.com/diggerhq/digger/libs/spec"
)
type AdvancedPolicyProvider struct{}
-func (p AdvancedPolicyProvider) GetPolicyProvider(policySpec lib_spec.PolicySpec, diggerHost string, diggerOrg string, token string, vcsType string) (policy.Checker, error) {
+func (p AdvancedPolicyProvider) GetPolicyProvider(policySpec lib_spec.PolicySpec, diggerHost, diggerOrg, token, vcsType string) (policy.Checker, error) {
managementRepo := os.Getenv("DIGGER_MANAGEMENT_REPO")
if managementRepo != "" {
log.Printf("info: using management repo policy provider")
- var token = ""
- var tokenName = ""
+ token := ""
+ tokenName := ""
switch vcsType {
case "github":
token = os.Getenv("GITHUB_TOKEN")
@@ -45,7 +46,7 @@ func (p AdvancedPolicyProvider) GetPolicyProvider(policySpec lib_spec.PolicySpec
type PolicyCheckerProviderAdvanced struct{}
-func (p PolicyCheckerProviderAdvanced) Get(hostname string, organisationName string, authToken string) (policy.Checker, error) {
+func (p PolicyCheckerProviderAdvanced) Get(hostname, organisationName, authToken string) (policy.Checker, error) {
managementRepo := os.Getenv("DIGGER_MANAGEMENT_REPO")
if managementRepo != "" {
token := os.Getenv("GITHUB_TOKEN")
diff --git a/ee/cli/pkg/vcs/providers.go b/ee/cli/pkg/vcs/providers.go
index d74700e15..839a9edc9 100644
--- a/ee/cli/pkg/vcs/providers.go
+++ b/ee/cli/pkg/vcs/providers.go
@@ -2,11 +2,12 @@ package vcs
import (
"fmt"
+ "os"
+
github2 "github.com/diggerhq/digger/ee/cli/pkg/github"
"github.com/diggerhq/digger/libs/ci"
"github.com/diggerhq/digger/libs/ci/gitlab"
"github.com/diggerhq/digger/libs/spec"
- "os"
)
type VCSProviderAdvanced struct{}
diff --git a/ee/drift/controllers/ci_jobs.go b/ee/drift/controllers/ci_jobs.go
index 83af7373d..9d6135f63 100644
--- a/ee/drift/controllers/ci_jobs.go
+++ b/ee/drift/controllers/ci_jobs.go
@@ -1,14 +1,15 @@
package controllers
import (
- "github.com/diggerhq/digger/backend/models"
- "github.com/diggerhq/digger/ee/drift/middleware"
- orchestrator_scheduler "github.com/diggerhq/digger/libs/scheduler"
"log"
"log/slog"
"net/http"
"time"
+ "github.com/diggerhq/digger/backend/models"
+ "github.com/diggerhq/digger/ee/drift/middleware"
+ orchestrator_scheduler "github.com/diggerhq/digger/libs/scheduler"
+
"github.com/diggerhq/digger/libs/iac_utils"
"github.com/gin-gonic/gin"
)
@@ -35,7 +36,6 @@ func (mc MainController) SetJobStatusForProject(c *gin.Context) {
var request SetJobStatusRequest
err := c.BindJSON(&request)
-
if err != nil {
log.Printf("Error binding JSON: %v", err)
c.JSON(http.StatusInternalServerError, gin.H{"error": "Error binding JSON"})
@@ -116,7 +116,7 @@ func (mc MainController) SetJobStatusForProject(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{})
}
-func ProjectDriftStateMachineApply(project models.Project, tfplan string, resourcesCreated uint, resourcesUpdated uint, resourcesDeleted uint) error {
+func ProjectDriftStateMachineApply(project models.Project, tfplan string, resourcesCreated, resourcesUpdated, resourcesDeleted uint) error {
isEmptyPlan := resourcesCreated == 0 && resourcesUpdated == 0 && resourcesDeleted == 0
wasEmptyPlan := project.DriftToCreate == 0 && project.DriftToUpdate == 0 && project.DriftToDelete == 0
if isEmptyPlan {
diff --git a/ee/drift/controllers/drift.go b/ee/drift/controllers/drift.go
index 6f79fe798..9079455d4 100644
--- a/ee/drift/controllers/drift.go
+++ b/ee/drift/controllers/drift.go
@@ -4,13 +4,14 @@ import (
"bytes"
"encoding/json"
"fmt"
- "github.com/diggerhq/digger/backend/models"
"log"
"net/http"
"net/url"
"os"
"time"
+ "github.com/diggerhq/digger/backend/models"
+
"github.com/diggerhq/digger/backend/ci_backends"
services2 "github.com/diggerhq/digger/ee/drift/services"
"github.com/diggerhq/digger/ee/drift/utils"
@@ -186,7 +187,6 @@ func (mc MainController) TriggerDriftRunForProject(c *gin.Context) {
c.JSON(http.StatusInternalServerError, gin.H{"error": fmt.Sprintf("Trigger workflow error")})
return
}
-
}
func (mc MainController) ProcessAllDrift(c *gin.Context) {
@@ -335,7 +335,6 @@ func (mc MainController) ProcessDriftForOrg(c *gin.Context) {
log.Printf("got unexpected drift status for project: %v - status: %v", projectId, statusCode)
}
}
-
}
c.String(200, "success")
}
diff --git a/ee/drift/controllers/notifications.go b/ee/drift/controllers/notifications.go
index 0a63fec04..735aa8155 100644
--- a/ee/drift/controllers/notifications.go
+++ b/ee/drift/controllers/notifications.go
@@ -4,15 +4,16 @@ import (
"bytes"
"encoding/json"
"fmt"
- "github.com/diggerhq/digger/backend/models"
- utils2 "github.com/diggerhq/digger/next/utils"
- "github.com/gin-gonic/gin"
- "github.com/slack-go/slack"
"log"
"net/http"
"net/url"
"os"
"time"
+
+ "github.com/diggerhq/digger/backend/models"
+ utils2 "github.com/diggerhq/digger/next/utils"
+ "github.com/gin-gonic/gin"
+ "github.com/slack-go/slack"
)
func sendTestSlackWebhook(webhookURL string) error {
diff --git a/ee/drift/main.go b/ee/drift/main.go
index be98d4903..8d7e0fac6 100644
--- a/ee/drift/main.go
+++ b/ee/drift/main.go
@@ -2,13 +2,14 @@ package main
import (
"fmt"
- "github.com/diggerhq/digger/backend/models"
- utils2 "github.com/diggerhq/digger/backend/utils"
"log"
"log/slog"
"net/http"
"os"
+ "github.com/diggerhq/digger/backend/models"
+ utils2 "github.com/diggerhq/digger/backend/utils"
+
"github.com/diggerhq/digger/backend/ci_backends"
"github.com/diggerhq/digger/ee/drift/controllers"
"github.com/diggerhq/digger/ee/drift/middleware"
@@ -42,7 +43,6 @@ func init() {
var Version = "dev"
func main() {
-
sentryDsn := os.Getenv("SENTRY_DSN")
if sentryDsn != "" {
if err := sentry.Init(sentry.ClientOptions{
@@ -84,8 +84,8 @@ func main() {
"commit_sha": Version,
})
})
- //authorized := r.Group("/")
- //authorized.Use(middleware.GetApiMiddleware(), middleware.AccessLevel(dbmodels.CliJobAccessType, dbmodels.AccessPolicyType, models.AdminPolicyType))
+ // authorized := r.Group("/")
+ // authorized.Use(middleware.GetApiMiddleware(), middleware.AccessLevel(dbmodels.CliJobAccessType, dbmodels.AccessPolicyType, models.AdminPolicyType))
r.POST("/repos/:repo/projects/:projectName/jobs/:jobId/set-status", middleware.JobTokenAuth(), controller.SetJobStatusForProject)
@@ -102,5 +102,4 @@ func main() {
port = "3000"
}
r.Run(fmt.Sprintf(":%v", port))
-
}
diff --git a/ee/drift/middleware/job_token.go b/ee/drift/middleware/job_token.go
index d0ea650be..0d8b34335 100644
--- a/ee/drift/middleware/job_token.go
+++ b/ee/drift/middleware/job_token.go
@@ -2,12 +2,13 @@ package middleware
import (
"fmt"
- "github.com/diggerhq/digger/backend/models"
- "github.com/gin-gonic/gin"
"log"
"net/http"
"strings"
"time"
+
+ "github.com/diggerhq/digger/backend/models"
+ "github.com/gin-gonic/gin"
)
func CheckJobToken(c *gin.Context, token string) (*models.JobToken, error) {
diff --git a/ee/drift/middleware/middleware.go b/ee/drift/middleware/middleware.go
index 3f3fb079b..1f467e23b 100644
--- a/ee/drift/middleware/middleware.go
+++ b/ee/drift/middleware/middleware.go
@@ -1,4 +1,6 @@
package middleware
-const ORGANISATION_ID_KEY = "organisation_ID"
-const ACCESS_LEVEL_KEY = "access_level"
+const (
+ ORGANISATION_ID_KEY = "organisation_ID"
+ ACCESS_LEVEL_KEY = "access_level"
+)
diff --git a/ee/drift/middleware/webhooks.go b/ee/drift/middleware/webhooks.go
index 60ff1afac..c46694b09 100644
--- a/ee/drift/middleware/webhooks.go
+++ b/ee/drift/middleware/webhooks.go
@@ -1,10 +1,11 @@
package middleware
import (
- "github.com/gin-gonic/gin"
"net/http"
"os"
"strings"
+
+ "github.com/gin-gonic/gin"
)
func WebhookAuth() gin.HandlerFunc {
diff --git a/ee/drift/services/spec.go b/ee/drift/services/spec.go
index ec63e8056..2c6a4ce57 100644
--- a/ee/drift/services/spec.go
+++ b/ee/drift/services/spec.go
@@ -2,10 +2,11 @@ package services
import (
"fmt"
+ "os"
+
utils2 "github.com/diggerhq/digger/backend/utils"
"github.com/diggerhq/digger/ee/drift/utils"
"github.com/diggerhq/digger/libs/spec"
- "os"
)
func GetRunNameFromJob(spec spec.Spec) (*string, error) {
@@ -13,14 +14,14 @@ func GetRunNameFromJob(spec spec.Spec) (*string, error) {
diggerCommand := fmt.Sprintf("digger %v", jobSpec.JobType)
jobIdShort := spec.JobId[:8]
projectName := jobSpec.ProjectName
- //requestedBy := jobSpec.RequestedBy
- //prNumber := *jobSpec.PullRequestNumber
+ // requestedBy := jobSpec.RequestedBy
+ // prNumber := *jobSpec.PullRequestNumber
runName := fmt.Sprintf("[%v] %v %v (drift)", jobIdShort, diggerCommand, projectName)
return &runName, nil
}
-func GetVCSToken(vcsType string, repoFullName string, repoOwner string, repoName string, installationId int64, gh utils2.GithubClientProvider) (*string, error) {
+func GetVCSToken(vcsType, repoFullName, repoOwner, repoName string, installationId int64, gh utils2.GithubClientProvider) (*string, error) {
var token string
switch vcsType {
case "github":
diff --git a/ee/drift/tasks/github.go b/ee/drift/tasks/github.go
index 90a0011ea..fc43a300a 100644
--- a/ee/drift/tasks/github.go
+++ b/ee/drift/tasks/github.go
@@ -2,17 +2,18 @@ package tasks
import (
"fmt"
+ "log"
+ "strconv"
+ "strings"
+
"github.com/diggerhq/digger/backend/models/dbmodels"
"github.com/diggerhq/digger/ee/drift/utils"
dg_configuration "github.com/diggerhq/digger/libs/digger_config"
utils3 "github.com/diggerhq/digger/libs/git_utils"
utils2 "github.com/diggerhq/digger/next/utils"
- "log"
- "strconv"
- "strings"
)
-func LoadProjectsFromGithubRepo(gh utils2.GithubClientProvider, installationId string, repoFullName string, repoOwner string, repoName string, cloneUrl string, branch string) error {
+func LoadProjectsFromGithubRepo(gh utils2.GithubClientProvider, installationId, repoFullName, repoOwner, repoName, cloneUrl, branch string) error {
link, err := dbmodels.DB.GetGithubAppInstallationLink(installationId)
if err != nil {
log.Printf("Error getting GetGithubAppInstallationLink: %v", err)
diff --git a/ee/drift/utils/github.go b/ee/drift/utils/github.go
index 993545aa9..5e8b51f77 100644
--- a/ee/drift/utils/github.go
+++ b/ee/drift/utils/github.go
@@ -4,6 +4,12 @@ import (
"context"
"encoding/base64"
"fmt"
+ "log"
+ "log/slog"
+ net "net/http"
+ "os"
+ "path"
+
"github.com/bradleyfalzon/ghinstallation/v2"
"github.com/diggerhq/digger/backend/models"
github2 "github.com/diggerhq/digger/libs/ci/github"
@@ -12,11 +18,6 @@ import (
"github.com/diggerhq/digger/next/utils"
"github.com/dominikbraun/graph"
"github.com/google/go-github/v61/github"
- "log"
- "log/slog"
- net "net/http"
- "os"
- "path"
)
func GetGithubClient(gh utils.GithubClientProvider, installationId int64, repoFullName string) (*github.Client, *string, error) {
@@ -33,7 +34,7 @@ func GetGithubClient(gh utils.GithubClientProvider, installationId int64, repoFu
return ghClient, token, err
}
-func GetGithubService(gh utils.GithubClientProvider, installationId int64, repoFullName string, repoOwner string, repoName string) (*github2.GithubService, *string, error) {
+func GetGithubService(gh utils.GithubClientProvider, installationId int64, repoFullName, repoOwner, repoName string) (*github2.GithubService, *string, error) {
slog.Debug("getting github client", "installationId", installationId, "repoFullName", repoFullName)
ghClient, token, err := GetGithubClient(gh, installationId, repoFullName)
if err != nil {
@@ -50,15 +51,14 @@ func GetGithubService(gh utils.GithubClientProvider, installationId int64, repoF
return &ghService, token, nil
}
-type DiggerGithubRealClientProvider struct {
-}
+type DiggerGithubRealClientProvider struct{}
func (gh DiggerGithubRealClientProvider) NewClient(netClient *net.Client) (*github.Client, error) {
ghClient := github.NewClient(netClient)
return ghClient, nil
}
-func (gh DiggerGithubRealClientProvider) Get(githubAppId int64, installationId int64) (*github.Client, *string, error) {
+func (gh DiggerGithubRealClientProvider) Get(githubAppId, installationId int64) (*github.Client, *string, error) {
githubAppPrivateKey := ""
githubAppPrivateKeyB64 := os.Getenv("GITHUB_APP_PRIVATE_KEY_BASE64")
if githubAppPrivateKeyB64 != "" {
@@ -94,7 +94,7 @@ func (gh DiggerGithubRealClientProvider) Get(githubAppId int64, installationId i
return ghClient, &token, nil
}
-func GetDiggerConfigForBranch(gh utils.GithubClientProvider, installationId int64, repoFullName string, repoOwner string, repoName string, cloneUrl string, branch string) (string, *github2.GithubService, *dg_configuration.DiggerConfig, graph.Graph[string, dg_configuration.Project], error) {
+func GetDiggerConfigForBranch(gh utils.GithubClientProvider, installationId int64, repoFullName, repoOwner, repoName, cloneUrl, branch string) (string, *github2.GithubService, *dg_configuration.DiggerConfig, graph.Graph[string, dg_configuration.Project], error) {
ghService, token, err := GetGithubService(gh, installationId, repoFullName, repoOwner, repoName)
if err != nil {
log.Printf("Error getting github service: %v", err)
diff --git a/libs/backendapi/backend.go b/libs/backendapi/backend.go
index 3bf9bfbd3..d0b251080 100644
--- a/libs/backendapi/backend.go
+++ b/libs/backendapi/backend.go
@@ -1,15 +1,16 @@
package backendapi
import (
+ "time"
+
"github.com/diggerhq/digger/libs/iac_utils"
"github.com/diggerhq/digger/libs/scheduler"
- "time"
)
type Api interface {
- ReportProject(repo string, projectName string, configuration string) error
- ReportProjectRun(repo string, projectName string, startedAt time.Time, endedAt time.Time, status string, command string, output string) error
- ReportProjectJobStatus(repo string, projectName string, jobId string, status string, timestamp time.Time, summary *iac_utils.IacSummary, planJson string, PrCommentUrl string, PrCommentId string, terraformOutput string, iacUtils iac_utils.IacUtils) (*scheduler.SerializedBatch, error)
+ ReportProject(repo, projectName, configuration string) error
+ ReportProjectRun(repo, projectName string, startedAt, endedAt time.Time, status, command, output string) error
+ ReportProjectJobStatus(repo, projectName, jobId, status string, timestamp time.Time, summary *iac_utils.IacSummary, planJson, PrCommentUrl, PrCommentId, terraformOutput string, iacUtils iac_utils.IacUtils) (*scheduler.SerializedBatch, error)
UploadJobArtefact(zipLocation string) (*int, *string, error)
DownloadJobArtefact(downloadTo string) (*string, error)
}
diff --git a/libs/backendapi/diggerapi.go b/libs/backendapi/diggerapi.go
index 7fe252ae8..ec2c77a1f 100644
--- a/libs/backendapi/diggerapi.go
+++ b/libs/backendapi/diggerapi.go
@@ -20,18 +20,17 @@ import (
"github.com/diggerhq/digger/libs/scheduler"
)
-type NoopApi struct {
-}
+type NoopApi struct{}
-func (n NoopApi) ReportProject(namespace string, projectName string, configurationYaml string) error {
+func (n NoopApi) ReportProject(namespace, projectName, configurationYaml string) error {
return nil
}
-func (n NoopApi) ReportProjectRun(namespace string, projectName string, startedAt time.Time, endedAt time.Time, status string, command string, output string) error {
+func (n NoopApi) ReportProjectRun(namespace, projectName string, startedAt, endedAt time.Time, status, command, output string) error {
return nil
}
-func (n NoopApi) ReportProjectJobStatus(repo string, projectName string, jobId string, status string, timestamp time.Time, summary *iac_utils.IacSummary, planJson string, PrCommentUrl string, PrCommentId string, terraformOutput string, iacUtils iac_utils.IacUtils) (*scheduler.SerializedBatch, error) {
+func (n NoopApi) ReportProjectJobStatus(repo, projectName, jobId, status string, timestamp time.Time, summary *iac_utils.IacSummary, planJson, PrCommentUrl, PrCommentId, terraformOutput string, iacUtils iac_utils.IacUtils) (*scheduler.SerializedBatch, error) {
return nil, nil
}
@@ -49,7 +48,7 @@ type DiggerApi struct {
HttpClient *http.Client
}
-func (d DiggerApi) ReportProject(namespace string, projectName string, configurationYaml string) error {
+func (d DiggerApi) ReportProject(namespace, projectName, configurationYaml string) error {
u, err := url.Parse(d.DiggerHost)
if err != nil {
slog.Error("not able to parse digger cloud url", "error", err)
@@ -69,7 +68,6 @@ func (d DiggerApi) ReportProject(namespace string, projectName string, configura
}
req, err := http.NewRequest("POST", u.String(), bytes.NewBuffer(jsonData))
-
if err != nil {
return fmt.Errorf("error while creating request: %v", err)
}
@@ -78,7 +76,6 @@ func (d DiggerApi) ReportProject(namespace string, projectName string, configura
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", d.AuthToken))
resp, err := d.HttpClient.Do(req)
-
if err != nil {
return fmt.Errorf("error while sending request: %v", err)
}
@@ -90,7 +87,7 @@ func (d DiggerApi) ReportProject(namespace string, projectName string, configura
return nil
}
-func (d DiggerApi) ReportProjectRun(namespace string, projectName string, startedAt time.Time, endedAt time.Time, status string, command string, output string) error {
+func (d DiggerApi) ReportProjectRun(namespace, projectName string, startedAt, endedAt time.Time, status, command, output string) error {
u, err := url.Parse(d.DiggerHost)
if err != nil {
slog.Error("not able to parse digger cloud url", "error", err)
@@ -114,7 +111,6 @@ func (d DiggerApi) ReportProjectRun(namespace string, projectName string, starte
}
req, err := http.NewRequest("POST", u.String(), bytes.NewBuffer(jsonData))
-
if err != nil {
return fmt.Errorf("error while creating request: %v", err)
}
@@ -123,7 +119,6 @@ func (d DiggerApi) ReportProjectRun(namespace string, projectName string, starte
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", d.AuthToken))
resp, err := d.HttpClient.Do(req)
-
if err != nil {
return fmt.Errorf("error while sending request: %v", err)
}
@@ -135,7 +130,7 @@ func (d DiggerApi) ReportProjectRun(namespace string, projectName string, starte
return nil
}
-func (d DiggerApi) ReportProjectJobStatus(repo string, projectName string, jobId string, status string, timestamp time.Time, summary *iac_utils.IacSummary, planJson string, PrCommentUrl string, PrCommentId string, terraformOutput string, iacUtils iac_utils.IacUtils) (*scheduler.SerializedBatch, error) {
+func (d DiggerApi) ReportProjectJobStatus(repo, projectName, jobId, status string, timestamp time.Time, summary *iac_utils.IacSummary, planJson, PrCommentUrl, PrCommentId, terraformOutput string, iacUtils iac_utils.IacUtils) (*scheduler.SerializedBatch, error) {
repoNameForBackendReporting := strings.ReplaceAll(repo, "/", "-")
u, err := url.Parse(d.DiggerHost)
if err != nil {
@@ -144,7 +139,7 @@ func (d DiggerApi) ReportProjectJobStatus(repo string, projectName string, jobId
}
var planSummaryJson interface{}
- var planFootprint = &iac_utils.IacPlanFootprint{}
+ planFootprint := &iac_utils.IacPlanFootprint{}
if summary == nil {
slog.Warn("warning: nil passed to plan result, sending empty")
planSummaryJson = nil
@@ -178,7 +173,6 @@ func (d DiggerApi) ReportProjectJobStatus(repo string, projectName string, jobId
}
req, err := http.NewRequest("POST", u.String(), bytes.NewBuffer(jsonData))
-
if err != nil {
return nil, fmt.Errorf("error while creating request: %v", err)
}
@@ -187,7 +181,6 @@ func (d DiggerApi) ReportProjectJobStatus(repo string, projectName string, jobId
req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", d.AuthToken))
resp, err := d.HttpClient.Do(req)
-
if err != nil {
return nil, fmt.Errorf("error while sending request: %v", err)
}
@@ -335,7 +328,7 @@ func (d DiggerApi) DownloadJobArtefact(downloadTo string) (*string, error) {
return &fileName, nil
}
-func NewBackendApi(hostName string, authToken string) Api {
+func NewBackendApi(hostName, authToken string) Api {
var backendApi Api
if os.Getenv("NO_BACKEND") == "true" {
slog.Warn("running in 'backendless' mode - features that require backend will not be available")
diff --git a/libs/backendapi/mocks.go b/libs/backendapi/mocks.go
index e9b358ad8..b6da8fd9d 100644
--- a/libs/backendapi/mocks.go
+++ b/libs/backendapi/mocks.go
@@ -1,23 +1,23 @@
package backendapi
import (
+ "time"
+
"github.com/diggerhq/digger/libs/iac_utils"
"github.com/diggerhq/digger/libs/scheduler"
- "time"
)
-type MockBackendApi struct {
-}
+type MockBackendApi struct{}
-func (t MockBackendApi) ReportProject(namespace string, projectName string, configuration string) error {
+func (t MockBackendApi) ReportProject(namespace, projectName, configuration string) error {
return nil
}
-func (t MockBackendApi) ReportProjectRun(repo string, projectName string, startedAt time.Time, endedAt time.Time, status string, command string, output string) error {
+func (t MockBackendApi) ReportProjectRun(repo, projectName string, startedAt, endedAt time.Time, status, command, output string) error {
return nil
}
-func (t MockBackendApi) ReportProjectJobStatus(repo string, projectName string, jobId string, status string, timestamp time.Time, summary *iac_utils.IacSummary, planJson string, PrCommentUrl string, PrCommentId string, terraformOutput string, iacUtils iac_utils.IacUtils) (*scheduler.SerializedBatch, error) {
+func (t MockBackendApi) ReportProjectJobStatus(repo, projectName, jobId, status string, timestamp time.Time, summary *iac_utils.IacSummary, planJson, PrCommentUrl, PrCommentId, terraformOutput string, iacUtils iac_utils.IacUtils) (*scheduler.SerializedBatch, error) {
return nil, nil
}
diff --git a/libs/ci/azure/azure.go b/libs/ci/azure/azure.go
index dd1b72cef..0beee288d 100644
--- a/libs/ci/azure/azure.go
+++ b/libs/ci/azure/azure.go
@@ -5,11 +5,12 @@ import (
"encoding/json"
"errors"
"fmt"
- "github.com/diggerhq/digger/libs/ci"
- "github.com/diggerhq/digger/libs/scheduler"
"strconv"
"strings"
+ "github.com/diggerhq/digger/libs/ci"
+ "github.com/diggerhq/digger/libs/scheduler"
+
digger_config2 "github.com/diggerhq/digger/libs/digger_config"
"github.com/microsoft/azure-devops-go-api/azuredevops"
"github.com/microsoft/azure-devops-go-api/azuredevops/git"
@@ -117,9 +118,8 @@ func (a *Azure) UnmarshalJSON(data []byte) error {
return nil
}
-func NewAzureReposService(patToken string, baseUrl string, projectName string, repositoryId string) (*AzureReposService, error) {
+func NewAzureReposService(patToken, baseUrl, projectName, repositoryId string) (*AzureReposService, error) {
client, err := git.NewClient(context.Background(), azuredevops.NewPatConnection(baseUrl, patToken))
-
if err != nil {
return nil, err
}
@@ -136,12 +136,11 @@ type AzureReposService struct {
RepositoryId string
}
-func (a *AzureReposService) GetUserTeams(organisation string, user string) ([]string, error) {
+func (a *AzureReposService) GetUserTeams(organisation, user string) ([]string, error) {
return make([]string, 0), nil
}
func (a *AzureReposService) GetChangedFiles(prNumber int) ([]string, error) {
-
pullRequest, err := a.Client.GetPullRequestById(context.Background(), git.GetPullRequestByIdArgs{
Project: &a.ProjectName,
PullRequestId: &prNumber,
@@ -192,15 +191,15 @@ func (svc *AzureReposService) ListIssues() ([]*ci.Issue, error) {
return nil, fmt.Errorf("implement me")
}
-func (svc *AzureReposService) PublishIssue(title string, body string, labels *[]string) (int64, error) {
+func (svc *AzureReposService) PublishIssue(title, body string, labels *[]string) (int64, error) {
return 0, fmt.Errorf("implement me")
}
-func (svc *AzureReposService) UpdateIssue(ID int64, title string, body string) (int64, error) {
+func (svc *AzureReposService) UpdateIssue(ID int64, title, body string) (int64, error) {
return 0, fmt.Errorf("implement me")
}
-func (a *AzureReposService) SetStatus(prNumber int, status string, statusContext string) error {
+func (a *AzureReposService) SetStatus(prNumber int, status, statusContext string) error {
var gitStatusState git.GitStatusState
if status == "success" {
gitStatusState = git.GitStatusStateValues.Succeeded
@@ -259,7 +258,7 @@ func (a *AzureReposService) GetCombinedPullRequestStatus(prNumber int) (string,
}
}
- var allSuccess = true
+ allSuccess := true
for _, status := range latestUniqueRequestStatuses {
if status.State != nil || *status.State != git.GitStatusStateValues.Succeeded {
allSuccess = false
@@ -326,7 +325,7 @@ func (a *AzureReposService) IsMerged(prNumber int) (bool, error) {
return *pullRequest.Status == git.PullRequestStatusValues.Completed, nil
}
-func (a *AzureReposService) EditComment(prNumber int, id string, comment string) error {
+func (a *AzureReposService) EditComment(prNumber int, id, comment string) error {
threadId, err := strconv.Atoi(id)
if err != nil {
return err
@@ -351,18 +350,18 @@ func (a *AzureReposService) DeleteComment(id string) error {
return nil
}
-func (a *AzureReposService) CreateCommentReaction(id string, reaction string) error {
+func (a *AzureReposService) CreateCommentReaction(id, reaction string) error {
// TODO implement me
return nil
}
func (a *AzureReposService) GetBranchName(prNumber int) (string, string, error) {
- //TODO implement me
+ // TODO implement me
return "", "", nil
}
-func (svc *AzureReposService) SetOutput(prNumber int, key string, value string) error {
- //TODO implement me
+func (svc *AzureReposService) SetOutput(prNumber int, key, value string) error {
+ // TODO implement me
return nil
}
@@ -383,7 +382,6 @@ func (a *AzureReposService) GetComments(prNumber int) ([]ci.Comment, error) {
})
}
return result, nil
-
}
func (svc *AzureReposService) GetApprovals(prNumber int) ([]string, error) {
@@ -400,7 +398,6 @@ func ProcessAzureReposEvent(azureEvent interface{}, diggerConfig *digger_config2
case AzurePrEvent:
prNumber = azureEvent.(AzurePrEvent).Resource.PullRequestId
changedFiles, err := ciService.GetChangedFiles(prNumber)
-
if err != nil {
return nil, nil, 0, fmt.Errorf("could not get changed files: %v", err)
}
@@ -409,7 +406,6 @@ func ProcessAzureReposEvent(azureEvent interface{}, diggerConfig *digger_config2
case AzureCommentEvent:
prNumber = azureEvent.(AzureCommentEvent).Resource.PullRequest.PullRequestId
changedFiles, err := ciService.GetChangedFiles(prNumber)
-
if err != nil {
return nil, nil, 0, fmt.Errorf("could not get changed files: %v", err)
}
diff --git a/libs/ci/azure/azure_test.go b/libs/ci/azure/azure_test.go
index b3ad4264a..b90e162c0 100644
--- a/libs/ci/azure/azure_test.go
+++ b/libs/ci/azure/azure_test.go
@@ -1,12 +1,12 @@
package azure
import (
- "github.com/stretchr/testify/assert"
"testing"
+
+ "github.com/stretchr/testify/assert"
)
func TestGetAzureReposContext(t *testing.T) {
-
context := "{\n \"id\": \"a5425068-eade-4753-a703-2a7670b94fca\",\n \"eventType\": \"ms.vss-code.git-pullrequest-comment-event\",\n \"publisherId\": \"tfs\",\n \"message\": {\n \"text\": \"Mohamed Habib has commented on a pull request\",\n \"html\": \"Mohamed Habib has commented on a pull request\",\n \"markdown\": \"Mohamed Habib has [commented](https://dev.azure.com/moehabib9/digger-test/_git/digger-test/pullrequest/1?discussionId=1) on a pull request\"\n },\n \"detailedMessage\": {\n \"text\": \"Mohamed Habib has commented on a pull request\\r\\ndigger plan\\r\\n\",\n \"html\": \"Mohamed Habib has commented on a pull request
digger plan
\",\n \"markdown\": \"Mohamed Habib has [commented](https://dev.azure.com/moehabib9/digger-test/_git/digger-test/pullrequest/1?discussionId=1) on a pull request\\r\\ndigger plan\\r\\n\"\n },\n \"resource\": {\n \"comment\": {\n \"id\": 1,\n \"parentCommentId\": 0,\n \"author\": {\n \"displayName\": \"Mohamed Habib\",\n \"url\": \"https://spsprodweu5.vssps.visualstudio.com/A8e479c0b-ee1b-43c7-9ed8-98f2a7ec6d01/_apis/Identities/d08e23e0-8b42-6ab5-a2b4-5f1dd4d1ed68\",\n \"_links\": {\n \"avatar\": {\n \"href\": \"https://dev.azure.com/moehabib9/_apis/GraphProfile/MemberAvatars/msa.ZDA4ZTIzZTAtOGI0Mi03YWI1LWEyYjQtNWYxZGQ0ZDFlZDY4\"\n }\n },\n \"id\": \"d08e23e0-8b42-6ab5-a2b4-5f1dd4d1ed68\",\n \"uniqueName\": \"moe.habib9@gmail.com\",\n \"imageUrl\": \"https://dev.azure.com/moehabib9/_apis/GraphProfile/MemberAvatars/msa.ZDA4ZTIzZTAtOGI0Mi03YWI1LWEyYjQtNWYxZGQ0ZDFlZDY4\",\n \"descriptor\": \"msa.ZDA4ZTIzZTAtOGI0Mi03YWI1LWEyYjQtNWYxZGQ0ZDFlZDY4\"\n },\n \"content\": \"digger plan\",\n \"publishedDate\": \"2023-05-31T14:43:11.517Z\",\n \"lastUpdatedDate\": \"2023-05-31T14:43:11.517Z\",\n \"lastContentUpdatedDate\": \"2023-05-31T14:43:11.517Z\",\n \"commentType\": \"text\",\n \"usersLiked\": [],\n \"_links\": {\n \"self\": {\n \"href\": \"https://dev.azure.com/moehabib9/_apis/git/repositories/7eca30de-5afd-48e0-8c1f-e557c437d331/pullRequests/1/threads/1/comments/1\"\n },\n \"repository\": {\n \"href\": \"https://dev.azure.com/moehabib9/a2def61f-157f-4382-b12f-184921223688/_apis/git/repositories/7eca30de-5afd-48e0-8c1f-e557c437d331\"\n },\n \"threads\": {\n \"href\": \"https://dev.azure.com/moehabib9/_apis/git/repositories/7eca30de-5afd-48e0-8c1f-e557c437d331/pullRequests/1/threads/1\"\n },\n \"pullRequests\": {\n \"href\": \"https://dev.azure.com/moehabib9/_apis/git/pullRequests/1\"\n }\n }\n },\n \"pullRequest\": {\n \"repository\": {\n \"id\": \"7eca30de-5afd-48e0-8c1f-e557c437d331\",\n \"name\": \"digger-test\",\n \"url\": \"https://dev.azure.com/moehabib9/a2def61f-157f-4382-b12f-184921223688/_apis/git/repositories/7eca30de-5afd-48e0-8c1f-e557c437d331\",\n \"project\": {\n \"id\": \"a2def61f-157f-4382-b12f-184921223688\",\n \"name\": \"digger-test\",\n \"url\": \"https://dev.azure.com/moehabib9/_apis/projects/a2def61f-157f-4382-b12f-184921223688\",\n \"state\": \"wellFormed\",\n \"revision\": 37,\n \"visibility\": \"private\",\n \"lastUpdateTime\": \"2023-05-31T14:04:47.047Z\"\n },\n \"size\": 44640,\n \"remoteUrl\": \"https://moehabib9@dev.azure.com/moehabib9/digger-test/_git/digger-test\",\n \"sshUrl\": \"git@ssh.dev.azure.com:v3/moehabib9/digger-test/digger-test\",\n \"webUrl\": \"https://dev.azure.com/moehabib9/digger-test/_git/digger-test\",\n \"isDisabled\": false,\n \"isInMaintenance\": false\n },\n \"pullRequestId\": 1,\n \"codeReviewId\": 1,\n \"status\": \"active\",\n \"createdBy\": {\n \"displayName\": \"Mohamed Habib\",\n \"url\": \"https://spsprodweu5.vssps.visualstudio.com/A8e479c0b-ee1b-43c7-9ed8-98f2a7ec6d01/_apis/Identities/d08e23e0-8b42-6ab5-a2b4-5f1dd4d1ed68\",\n \"_links\": {\n \"avatar\": {\n \"href\": \"https://dev.azure.com/moehabib9/_apis/GraphProfile/MemberAvatars/msa.ZDA4ZTIzZTAtOGI0Mi03YWI1LWEyYjQtNWYxZGQ0ZDFlZDY4\"\n }\n },\n \"id\": \"d08e23e0-8b42-6ab5-a2b4-5f1dd4d1ed68\",\n \"uniqueName\": \"moe.habib9@gmail.com\",\n \"imageUrl\": \"https://dev.azure.com/moehabib9/_api/_common/identityImage?id=d08e23e0-8b42-6ab5-a2b4-5f1dd4d1ed68\",\n \"descriptor\": \"msa.ZDA4ZTIzZTAtOGI0Mi03YWI1LWEyYjQtNWYxZGQ0ZDFlZDY4\"\n },\n \"creationDate\": \"2023-05-31T14:41:30.7525172Z\",\n \"title\": \"Updated main.tf\",\n \"description\": \"Updated main.tf\",\n \"sourceRefName\": \"refs/heads/test-1\",\n \"targetRefName\": \"refs/heads/main\",\n \"mergeStatus\": \"succeeded\",\n \"isDraft\": false,\n \"mergeId\": \"58795d35-ab4e-445b-9c73-859a3eea1bbe\",\n \"lastMergeSourceCommit\": {\n \"commitId\": \"881bdbdda340529887c8ad46c06b0342715c4653\",\n \"url\": \"https://dev.azure.com/moehabib9/a2def61f-157f-4382-b12f-184921223688/_apis/git/repositories/7eca30de-5afd-48e0-8c1f-e557c437d331/commits/881bdbdda340529887c8ad46c06b0342715c4653\"\n },\n \"lastMergeTargetCommit\": {\n \"commitId\": \"c254effb63be65b0f924b473385c45f4dc4c4e96\",\n \"url\": \"https://dev.azure.com/moehabib9/a2def61f-157f-4382-b12f-184921223688/_apis/git/repositories/7eca30de-5afd-48e0-8c1f-e557c437d331/commits/c254effb63be65b0f924b473385c45f4dc4c4e96\"\n },\n \"lastMergeCommit\": {\n \"commitId\": \"dccb8e2c3232118d6023d862472afb4bf146dc39\",\n \"author\": {\n \"name\": \"Mohamed Habib\",\n \"email\": \"moe.habib9@gmail.com\",\n \"date\": \"2023-05-31T14:41:30Z\"\n },\n \"committer\": {\n \"name\": \"Mohamed Habib\",\n \"email\": \"moe.habib9@gmail.com\",\n \"date\": \"2023-05-31T14:41:30Z\"\n },\n \"comment\": \"Merge pull request 1 from test-1 into main\",\n \"url\": \"https://dev.azure.com/moehabib9/a2def61f-157f-4382-b12f-184921223688/_apis/git/repositories/7eca30de-5afd-48e0-8c1f-e557c437d331/commits/dccb8e2c3232118d6023d862472afb4bf146dc39\"\n },\n \"reviewers\": [],\n \"url\": \"https://dev.azure.com/moehabib9/a2def61f-157f-4382-b12f-184921223688/_apis/git/repositories/7eca30de-5afd-48e0-8c1f-e557c437d331/pullRequests/1\",\n \"supportsIterations\": true,\n \"artifactId\": \"vstfs:///Git/PullRequestId/a2def61f-157f-4382-b12f-184921223688%2f7eca30de-5afd-48e0-8c1f-e557c437d331%2f1\"\n }\n },\n \"resourceVersion\": \"2.0\",\n \"resourceContainers\": {\n \"collection\": {\n \"id\": \"f658bb7d-1dad-4fd9-b188-2fe9e914b810\",\n \"baseUrl\": \"https://dev.azure.com/moehabib9/\"\n },\n \"account\": {\n \"id\": \"8e479c0b-ee1b-43c7-9ed8-98f2a7ec6d01\",\n \"baseUrl\": \"https://dev.azure.com/moehabib9/\"\n },\n \"project\": {\n \"id\": \"a2def61f-157f-4382-b12f-184921223688\",\n \"baseUrl\": \"https://dev.azure.com/moehabib9/\"\n }\n },\n \"createdDate\": \"2023-05-31T14:43:18.079Z\"\n}" az, _ := GetAzureReposContext(context) diff --git a/libs/ci/bitbucket/bitbucket.go b/libs/ci/bitbucket/bitbucket.go index 024f17c2d..2f9864869 100644 --- a/libs/ci/bitbucket/bitbucket.go +++ b/libs/ci/bitbucket/bitbucket.go @@ -4,12 +4,13 @@ import ( "bytes" "encoding/json" "fmt" - "github.com/diggerhq/digger/libs/ci" - configuration "github.com/diggerhq/digger/libs/digger_config" "io/ioutil" "net/http" "strconv" "time" + + "github.com/diggerhq/digger/libs/ci" + configuration "github.com/diggerhq/digger/libs/digger_config" ) // Define the base URL for the Bitbucket API. @@ -148,15 +149,15 @@ func (svc BitbucketAPI) ListIssues() ([]*ci.Issue, error) { return nil, fmt.Errorf("implement me") } -func (svc BitbucketAPI) PublishIssue(title string, body string, labels *[]string) (int64, error) { +func (svc BitbucketAPI) PublishIssue(title, body string, labels *[]string) (int64, error) { return 0, fmt.Errorf("implement me") } -func (svc BitbucketAPI) UpdateIssue(ID int64, title string, body string) (int64, error) { +func (svc BitbucketAPI) UpdateIssue(ID int64, title, body string) (int64, error) { return 0, fmt.Errorf("implement me") } -func (b BitbucketAPI) EditComment(prNumber int, id string, comment string) error { +func (b BitbucketAPI) EditComment(prNumber int, id, comment string) error { url := fmt.Sprintf("%s/repositories/%s/%s/pullrequests/%d/comments/%s", bitbucketBaseURL, b.RepoWorkspace, b.RepoName, prNumber, id) commentBody := map[string]interface{}{ @@ -187,7 +188,7 @@ func (b BitbucketAPI) DeleteComment(id string) error { return nil } -func (b BitbucketAPI) CreateCommentReaction(id string, reaction string) error { +func (b BitbucketAPI) CreateCommentReaction(id, reaction string) error { // TODO implement me return nil } @@ -207,7 +208,6 @@ type Comment struct { } func (b BitbucketAPI) GetComments(prNumber int) ([]ci.Comment, error) { - url := fmt.Sprintf("%s/repositories/%s/%s/pullrequests/%d/comments", bitbucketBaseURL, b.RepoWorkspace, b.RepoName, prNumber) resp, err := b.sendRequest("GET", url, nil) @@ -236,7 +236,6 @@ func (b BitbucketAPI) GetComments(prNumber int) ([]ci.Comment, error) { } return comments, nil - } func (svc BitbucketAPI) GetApprovals(prNumber int) ([]string, error) { @@ -254,7 +253,7 @@ type PullRequest struct { } } -func (b BitbucketAPI) SetStatus(prNumber int, status string, statusContext string) error { +func (b BitbucketAPI) SetStatus(prNumber int, status, statusContext string) error { prUrl := fmt.Sprintf("%s/repositories/%s/%s/pullrequests/%d", bitbucketBaseURL, b.RepoWorkspace, b.RepoName, prNumber) resp, err := b.sendRequest("GET", prUrl, nil) @@ -322,7 +321,6 @@ func (b BitbucketAPI) GetCombinedPullRequestStatus(prNumber int) (string, error) url := fmt.Sprintf("%s/repositories/%s/%s/commit/%d/statuses", bitbucketBaseURL, b.RepoWorkspace, b.RepoName, prNumber) resp, err := b.sendRequest("GET", url, nil) - if err != nil { return "", err } @@ -336,7 +334,6 @@ func (b BitbucketAPI) GetCombinedPullRequestStatus(prNumber int) (string, error) var statuses CommitStatuses err = json.NewDecoder(resp.Body).Decode(&statuses) - if err != nil { return "", err } @@ -370,7 +367,7 @@ func (b BitbucketAPI) GetCombinedPullRequestStatus(prNumber int) (string, error) } } - var allSuccess = true + allSuccess := true for _, status := range latestStatusByKey { if status.State != "SUCCESSFUL" { allSuccess = false @@ -382,7 +379,6 @@ func (b BitbucketAPI) GetCombinedPullRequestStatus(prNumber int) (string, error) } return "pending", nil - } func (b BitbucketAPI) MergePullRequest(prNumber int, mergeStrategy string) error { @@ -427,7 +423,6 @@ func (b BitbucketAPI) IsMergeable(prNumber int) (bool, error) { } func (b BitbucketAPI) IsMerged(prNumber int) (bool, error) { - url := fmt.Sprintf("%s/repositories/%s/%s/pullrequests/%d", bitbucketBaseURL, b.RepoWorkspace, b.RepoName, prNumber) resp, err := b.sendRequest("GET", url, nil) @@ -506,14 +501,14 @@ func (b BitbucketAPI) GetBranchName(prNumber int) (string, string, error) { return pullRequest.Source.Branch.Name, "", nil } -func (svc BitbucketAPI) SetOutput(prNumber int, key string, value string) error { - //TODO implement me +func (svc BitbucketAPI) SetOutput(prNumber int, key, value string) error { + // TODO implement me return nil } // Implement the OrgService interface. -func (b BitbucketAPI) GetUserTeams(organisation string, user string) ([]string, error) { +func (b BitbucketAPI) GetUserTeams(organisation, user string) ([]string, error) { return nil, fmt.Errorf("not implemented") } @@ -641,12 +636,10 @@ func (b BitbucketAPI) TriggerPipeline(branch string, variables []interface{}) (s } return "", nil - } func FindImpactedProjectsInBitbucket(diggerConfig *configuration.DiggerConfig, prNumber int, prService ci.PullRequestService) ([]configuration.Project, error) { changedFiles, err := prService.GetChangedFiles(prNumber) - if err != nil { fmt.Printf("Error getting changed files: %v", err) return nil, err diff --git a/libs/ci/ci.go b/libs/ci/ci.go index 5a86c46b9..0fc24d0d8 100644 --- a/libs/ci/ci.go +++ b/libs/ci/ci.go @@ -6,15 +6,15 @@ type PullRequestService interface { GetChangedFiles(prNumber int) ([]string, error) PublishComment(prNumber int, comment string) (*Comment, error) ListIssues() ([]*Issue, error) - PublishIssue(title string, body string, labels *[]string) (int64, error) - UpdateIssue(ID int64, title string, body string) (int64, error) - EditComment(prNumber int, id string, comment string) error + PublishIssue(title, body string, labels *[]string) (int64, error) + UpdateIssue(ID int64, title, body string) (int64, error) + EditComment(prNumber int, id, comment string) error DeleteComment(id string) error - CreateCommentReaction(id string, reaction string) error + CreateCommentReaction(id, reaction string) error GetComments(prNumber int) ([]Comment, error) GetApprovals(prNumber int) ([]string, error) // SetStatus set status of specified pull/merge request, status could be: "pending", "failure", "success" - SetStatus(prNumber int, status string, statusContext string) error + SetStatus(prNumber int, status, statusContext string) error GetCombinedPullRequestStatus(prNumber int) (string, error) MergePullRequest(prNumber int, mergeStrategy string) error // IsMergeable is still open and ready to be merged @@ -24,11 +24,11 @@ type PullRequestService interface { // IsClosed closed without merging IsClosed(prNumber int) (bool, error) GetBranchName(prNumber int) (string, string, error) - SetOutput(prNumber int, key string, value string) error + SetOutput(prNumber int, key, value string) error } type OrgService interface { - GetUserTeams(organisation string, user string) ([]string, error) + GetUserTeams(organisation, user string) ([]string, error) } type Issue struct { diff --git a/libs/ci/generic/events.go b/libs/ci/generic/events.go index a1d585d9e..24ea244c8 100644 --- a/libs/ci/generic/events.go +++ b/libs/ci/generic/events.go @@ -2,14 +2,15 @@ package generic import ( "fmt" + "strings" + "github.com/diggerhq/digger/libs/ci" "github.com/diggerhq/digger/libs/digger_config" "github.com/diggerhq/digger/libs/scheduler" "github.com/dominikbraun/graph" - "strings" ) -func GetRunEnvVars(defaultBranch string, prBranch string, projectName string, projectDir string) map[string]string { +func GetRunEnvVars(defaultBranch, prBranch, projectName, projectDir string) map[string]string { return map[string]string{ "DEFAULT_BRANCH": defaultBranch, "PR_BRANCH": prBranch, @@ -21,7 +22,6 @@ func GetRunEnvVars(defaultBranch string, prBranch string, projectName string, pr func ProcessIssueCommentEvent(prNumber int, commentBody string, diggerConfig *digger_config.DiggerConfig, dependencyGraph graph.Graph[string, digger_config.Project], ciService ci.PullRequestService) ([]digger_config.Project, map[string]digger_config.ProjectToSourceMapping, *digger_config.Project, int, error) { var impactedProjects []digger_config.Project changedFiles, err := ciService.GetChangedFiles(prNumber) - if err != nil { return nil, nil, nil, 0, fmt.Errorf("could not get changed files") } @@ -97,7 +97,7 @@ func FindAllProjectsDependantOnImpactedProjects(impactedProjects []digger_config return impactedProjectsWithDependantProjects, nil } -func ConvertIssueCommentEventToJobs(repoFullName string, requestedBy string, prNumber int, commentBody string, impactedProjects []digger_config.Project, requestedProject *digger_config.Project, workflows map[string]digger_config.Workflow, prBranchName string, defaultBranch string) ([]scheduler.Job, bool, error) { +func ConvertIssueCommentEventToJobs(repoFullName, requestedBy string, prNumber int, commentBody string, impactedProjects []digger_config.Project, requestedProject *digger_config.Project, workflows map[string]digger_config.Workflow, prBranchName, defaultBranch string) ([]scheduler.Job, bool, error) { jobs := make([]scheduler.Job, 0) prBranch := prBranchName @@ -135,10 +135,9 @@ func ConvertIssueCommentEventToJobs(repoFullName string, requestedBy string, prN } return jobs, coversAllImpactedProjects, nil - } -func CreateJobsForProjects(projects []digger_config.Project, command string, event string, repoFullName string, requestedBy string, workflows map[string]digger_config.Workflow, issueNumber *int, commitSha *string, defaultBranch string, prBranch string, performEnvVarsInterpolations bool) ([]scheduler.Job, error) { +func CreateJobsForProjects(projects []digger_config.Project, command, event, repoFullName, requestedBy string, workflows map[string]digger_config.Workflow, issueNumber *int, commitSha *string, defaultBranch, prBranch string, performEnvVarsInterpolations bool) ([]scheduler.Job, error) { jobs := make([]scheduler.Job, 0) for _, project := range projects { diff --git a/libs/ci/github/github.go b/libs/ci/github/github.go index d7213e196..1e48647ac 100644 --- a/libs/ci/github/github.go +++ b/libs/ci/github/github.go @@ -19,12 +19,12 @@ import ( ) type GithubServiceProvider interface { - NewService(ghToken string, repoName string, owner string) (GithubService, error) + NewService(ghToken, repoName, owner string) (GithubService, error) } type GithubServiceProviderBasic struct{} -func (_ GithubServiceProviderBasic) NewService(ghToken string, repoName string, owner string) (GithubService, error) { +func (_ GithubServiceProviderBasic) NewService(ghToken, repoName, owner string) (GithubService, error) { client := github.NewClient(nil) if ghToken != "" { client = client.WithAuthToken(ghToken) @@ -43,7 +43,7 @@ type GithubService struct { Owner string } -func (svc GithubService) GetUserTeams(organisation string, user string) ([]string, error) { +func (svc GithubService) GetUserTeams(organisation, user string) ([]string, error) { teamsResponse, _, err := svc.Client.Teams.ListTeams(context.Background(), organisation, nil) if err != nil { return nil, fmt.Errorf("failed to list github teams: %v", err) @@ -86,7 +86,7 @@ func (svc GithubService) GetChangedFiles(prNumber int) ([]string, error) { return fileNames, nil } -func (svc GithubService) GetChangedFilesForCommit(owner string, repo string, commitID string) ([]string, error) { +func (svc GithubService) GetChangedFilesForCommit(owner, repo, commitID string) ([]string, error) { var fileNames []string opts := github.ListOptions{PerPage: 100} @@ -139,7 +139,7 @@ func (svc GithubService) ListIssues() ([]*ci.Issue, error) { return allIssues, nil } -func (svc GithubService) PublishIssue(title string, body string, labels *[]string) (int64, error) { +func (svc GithubService) PublishIssue(title, body string, labels *[]string) (int64, error) { githubissue, _, err := svc.Client.Issues.Create(context.Background(), svc.Owner, svc.RepoName, &github.IssueRequest{Title: &title, Body: &body, Labels: labels}) if err != nil { return 0, fmt.Errorf("could not publish issue: %v", err) @@ -147,7 +147,7 @@ func (svc GithubService) PublishIssue(title string, body string, labels *[]strin return *githubissue.ID, err } -func (svc GithubService) UpdateIssue(ID int64, title string, body string) (int64, error) { +func (svc GithubService) UpdateIssue(ID int64, title, body string) (int64, error) { githubissue, _, err := svc.Client.Issues.Edit(context.Background(), svc.Owner, svc.RepoName, int(ID), &github.IssueRequest{Title: &title, Body: &body}) if err != nil { return 0, fmt.Errorf("could not edit issue: %v", err) @@ -191,7 +191,7 @@ func (svc GithubService) GetApprovals(prNumber int) ([]string, error) { return approvals, err } -func (svc GithubService) EditComment(prNumber int, id string, comment string) error { +func (svc GithubService) EditComment(prNumber int, id, comment string) error { commentId, err := strconv.ParseInt(id, 10, 64) if err != nil { return fmt.Errorf("could not convert id %v to i64: %v", id, err) @@ -211,16 +211,18 @@ func (svc GithubService) DeleteComment(id string) error { type GithubCommentReaction string -const GithubCommentPlusOneReaction GithubCommentReaction = "+1" -const GithubCommentMinusOneReaction GithubCommentReaction = "-1" -const GithubCommentLaughReaction GithubCommentReaction = "laugh" -const GithubCommentConfusedReaction GithubCommentReaction = "confused" -const GithubCommentHeartReaction GithubCommentReaction = "heart" -const GithubCommentHoorayReaction GithubCommentReaction = "hooray" -const GithubCommentRocketReaction GithubCommentReaction = "rocket" -const GithubCommentEyesReaction GithubCommentReaction = "eyes" +const ( + GithubCommentPlusOneReaction GithubCommentReaction = "+1" + GithubCommentMinusOneReaction GithubCommentReaction = "-1" + GithubCommentLaughReaction GithubCommentReaction = "laugh" + GithubCommentConfusedReaction GithubCommentReaction = "confused" + GithubCommentHeartReaction GithubCommentReaction = "heart" + GithubCommentHoorayReaction GithubCommentReaction = "hooray" + GithubCommentRocketReaction GithubCommentReaction = "rocket" + GithubCommentEyesReaction GithubCommentReaction = "eyes" +) -func (svc GithubService) CreateCommentReaction(id string, reaction string) error { +func (svc GithubService) CreateCommentReaction(id, reaction string) error { commentId, err := strconv.ParseInt(id, 10, 64) if err != nil { return fmt.Errorf("could not convert id %v to i64: %v", id, err) @@ -243,7 +245,7 @@ func (svc GithubService) IsPullRequest(PrNumber int) (bool, error) { return issue.IsPullRequest(), nil } -func (svc GithubService) SetStatus(prNumber int, status string, statusContext string) error { +func (svc GithubService) SetStatus(prNumber int, status, statusContext string) error { // we have to check if prNumber is an issue or not isPullRequest, err := svc.IsPullRequest(prNumber) if err != nil { @@ -392,12 +394,12 @@ func (svc GithubService) IsClosed(prNumber int) (bool, error) { return pr.GetState() == "closed", nil } -func (svc GithubService) SetOutput(prNumber int, key string, value string) error { +func (svc GithubService) SetOutput(prNumber int, key, value string) error { gout := os.Getenv("GITHUB_ENV") if gout == "" { return fmt.Errorf("GITHUB_ENV not set, could not set the output in digger step") } - f, err := os.OpenFile(gout, os.O_APPEND|os.O_WRONLY, 0644) + f, err := os.OpenFile(gout, os.O_APPEND|os.O_WRONLY, 0o644) if err != nil { return fmt.Errorf("could not open file for writing during digger step") } @@ -631,7 +633,6 @@ func ProcessGitHubEvent(ghEvent interface{}, diggerConfig *digger_config.DiggerC "action", *event.Action) changedFiles, err := ciService.GetChangedFiles(prNumber) - if err != nil { slog.Error("could not get changed files", "error", err, "prNumber", prNumber) return nil, nil, 0, fmt.Errorf("could not get changed files") @@ -649,7 +650,6 @@ func ProcessGitHubEvent(ghEvent interface{}, diggerConfig *digger_config.DiggerC "comment", *event.Comment.Body) changedFiles, err := ciService.GetChangedFiles(prNumber) - if err != nil { slog.Error("could not get changed files", "error", err, "prNumber", prNumber) return nil, nil, 0, fmt.Errorf("could not get changed files") @@ -702,7 +702,6 @@ func ProcessGitHubPullRequestEvent(payload *github.PullRequestEvent, diggerConfi "action", *payload.Action) changedFiles, err := ciService.GetChangedFiles(prNumber) - if err != nil { slog.Error("could not get changed files", "error", err, "prNumber", prNumber) return nil, nil, prNumber, fmt.Errorf("could not get changed files") diff --git a/libs/ci/github/github_test.go b/libs/ci/github/github_test.go index 238e7441a..08908b632 100644 --- a/libs/ci/github/github_test.go +++ b/libs/ci/github/github_test.go @@ -1,15 +1,15 @@ package github import ( - "github.com/diggerhq/digger/libs/ci/generic" "testing" + "github.com/diggerhq/digger/libs/ci/generic" + "github.com/diggerhq/digger/libs/digger_config" "github.com/stretchr/testify/assert" ) func TestFindAllProjectsDependantOnImpactedProjects(t *testing.T) { - projects := []digger_config.Project{ { Name: "a", @@ -57,7 +57,6 @@ func TestFindAllProjectsDependantOnImpactedProjects(t *testing.T) { } dependencyGraph, err := digger_config.CreateProjectDependencyGraph(projects) - if err != nil { t.Errorf("Error creating dependency graph: %v", err) } diff --git a/libs/ci/github/mocks.go b/libs/ci/github/mocks.go index 9d25ba119..bd0b5f7fc 100644 --- a/libs/ci/github/mocks.go +++ b/libs/ci/github/mocks.go @@ -2,15 +2,16 @@ package github import ( "fmt" - "github.com/diggerhq/digger/libs/ci" "strconv" + + "github.com/diggerhq/digger/libs/ci" ) type MockCiService struct { CommentsPerPr map[int][]*ci.Comment } -func (t MockCiService) GetUserTeams(organisation string, user string) ([]string, error) { +func (t MockCiService) GetUserTeams(organisation, user string) ([]string, error) { return nil, nil } @@ -21,8 +22,8 @@ func (t MockCiService) GetApprovals(prNumber int) ([]string, error) { func (t MockCiService) GetChangedFiles(prNumber int) ([]string, error) { return nil, nil } -func (t MockCiService) PublishComment(prNumber int, comment string) (*ci.Comment, error) { +func (t MockCiService) PublishComment(prNumber int, comment string) (*ci.Comment, error) { latestId := 0 for _, comments := range t.CommentsPerPr { @@ -43,15 +44,15 @@ func (t MockCiService) ListIssues() ([]*ci.Issue, error) { return nil, fmt.Errorf("implement me") } -func (t MockCiService) PublishIssue(title string, body string, labels *[]string) (int64, error) { +func (t MockCiService) PublishIssue(title, body string, labels *[]string) (int64, error) { return 0, fmt.Errorf("implement me") } -func (svc MockCiService) UpdateIssue(ID int64, title string, body string) (int64, error) { +func (svc MockCiService) UpdateIssue(ID int64, title, body string) (int64, error) { return 0, fmt.Errorf("implement me") } -func (t MockCiService) SetStatus(prNumber int, status string, statusContext string) error { +func (t MockCiService) SetStatus(prNumber int, status, statusContext string) error { return nil } @@ -87,7 +88,7 @@ func (t MockCiService) GetComments(prNumber int) ([]ci.Comment, error) { return comments, nil } -func (t MockCiService) EditComment(prNumber int, id string, comment string) error { +func (t MockCiService) EditComment(prNumber int, id, comment string) error { for _, comments := range t.CommentsPerPr { for _, c := range comments { if c.Id == id { @@ -103,7 +104,7 @@ func (t MockCiService) DeleteComment(id string) error { return nil } -func (t MockCiService) CreateCommentReaction(id string, reaction string) error { +func (t MockCiService) CreateCommentReaction(id, reaction string) error { // TODO implement me return nil } @@ -112,7 +113,7 @@ func (t MockCiService) GetBranchName(prNumber int) (string, string, error) { return "", "", nil } -func (svc MockCiService) SetOutput(prNumber int, key string, value string) error { - //TODO implement me +func (svc MockCiService) SetOutput(prNumber int, key, value string) error { + // TODO implement me return nil } diff --git a/libs/ci/gitlab/gitlab.go b/libs/ci/gitlab/gitlab.go index 53f418f92..c78e8435b 100644 --- a/libs/ci/gitlab/gitlab.go +++ b/libs/ci/gitlab/gitlab.go @@ -114,7 +114,6 @@ func ProcessGitLabEvent(gitlabContext *GitLabContext, diggerConfig *digger_confi "mergeRequestId", *mergeRequestId) changedFiles, err := service.GetChangedFiles(*mergeRequestId) - if err != nil { slog.Error("could not get changed files", "error", err, "mergeRequestId", *mergeRequestId) return nil, nil, fmt.Errorf("could not get changed files") @@ -163,7 +162,6 @@ func (gitlabService GitLabService) GetChangedFiles(mergeRequestId int) ([]string "mergeRequestId", mergeRequestId) mergeRequestChanges, _, err := gitlabService.Client.MergeRequests.ListMergeRequestDiffs(*gitlabService.Context.ProjectId, mergeRequestId, opt) - if err != nil { slog.Error("error getting GitLab merge request diffs", "error", err, "mergeRequestId", mergeRequestId) return nil, fmt.Errorf("error getting gitlab's merge request: %v", err) @@ -179,7 +177,7 @@ func (gitlabService GitLabService) GetChangedFiles(mergeRequestId int) ([]string return fileNames, nil } -func (gitlabService GitLabService) GetUserTeams(organisation string, user string) ([]string, error) { +func (gitlabService GitLabService) GetUserTeams(organisation, user string) ([]string, error) { return make([]string, 0), nil } @@ -218,19 +216,19 @@ func (svc GitLabService) ListIssues() ([]*ci.Issue, error) { return nil, fmt.Errorf("implement me") } -func (svc GitLabService) PublishIssue(title string, body string, labels *[]string) (int64, error) { +func (svc GitLabService) PublishIssue(title, body string, labels *[]string) (int64, error) { return 0, fmt.Errorf("implement me") } -func (svc GitLabService) UpdateIssue(ID int64, title string, body string) (int64, error) { +func (svc GitLabService) UpdateIssue(ID int64, title, body string) (int64, error) { return 0, fmt.Errorf("implement me") } // SetStatus GitLab implementation is using https://docs.gitlab.com/15.11/ee/api/status_checks.html (external status checks) // https://docs.gitlab.com/ee/user/project/merge_requests/status_checks.html#add-a-status-check-service // only supported by 'Ultimate' plan -func (gitlabService GitLabService) SetStatus(mergeRequestID int, status string, statusContext string) error { - //TODO implement me +func (gitlabService GitLabService) SetStatus(mergeRequestID int, status, statusContext string) error { + // TODO implement me slog.Debug("setting status (not implemented)", "mergeRequestID", mergeRequestID, "status", status, @@ -239,7 +237,7 @@ func (gitlabService GitLabService) SetStatus(mergeRequestID int, status string, } func (gitlabService GitLabService) GetCombinedPullRequestStatus(mergeRequestID int) (string, error) { - //TODO implement me + // TODO implement me return "success", nil } @@ -303,7 +301,7 @@ func (gitlabService GitLabService) IsMerged(mergeRequestIID int) (bool, error) { return false, nil } -func (gitlabService GitLabService) EditComment(prNumber int, id string, comment string) error { +func (gitlabService GitLabService) EditComment(prNumber int, id, comment string) error { discussionId := gitlabService.Context.DiscussionID projectId := *gitlabService.Context.ProjectId mergeRequestIID := *gitlabService.Context.MergeRequestIId @@ -333,13 +331,13 @@ func (gitlabService GitLabService) DeleteComment(id string) error { return nil } -func (gitlabService GitLabService) CreateCommentReaction(id string, reaction string) error { +func (gitlabService GitLabService) CreateCommentReaction(id, reaction string) error { // TODO implement me return nil } func (gitlabService GitLabService) GetComments(prNumber int) ([]ci.Comment, error) { - //TODO implement me + // TODO implement me return nil, nil } @@ -350,7 +348,7 @@ func (gitlabService GitLabService) GetApprovals(prNumber int) ([]string, error) } func (gitlabService GitLabService) GetBranchName(prNumber int) (string, string, error) { - //TODO implement me + // TODO implement me projectId := *gitlabService.Context.ProjectId slog.Debug("getting branch name", "prNumber", prNumber, "projectId", projectId) @@ -378,8 +376,8 @@ func (gitlabService GitLabService) CheckBranchExists(branchName string) (bool, e return true, nil } -func (svc GitLabService) SetOutput(prNumber int, key string, value string) error { - //TODO implement me +func (svc GitLabService) SetOutput(prNumber int, key, value string) error { + // TODO implement me return nil } diff --git a/libs/ci/gitlab/gitlab_test.go b/libs/ci/gitlab/gitlab_test.go index 90cb0d172..1f649666b 100644 --- a/libs/ci/gitlab/gitlab_test.go +++ b/libs/ci/gitlab/gitlab_test.go @@ -1,8 +1,9 @@ package gitlab import ( - "github.com/stretchr/testify/assert" "testing" + + "github.com/stretchr/testify/assert" ) func TestParseGitLabContext(t *testing.T) { diff --git a/libs/ci/gitlab/webhooks.go b/libs/ci/gitlab/webhooks.go index 778512101..dc3486bdc 100644 --- a/libs/ci/gitlab/webhooks.go +++ b/libs/ci/gitlab/webhooks.go @@ -2,6 +2,7 @@ package gitlab import ( "fmt" + "github.com/diggerhq/digger/libs/ci" "github.com/diggerhq/digger/libs/ci/generic" "github.com/diggerhq/digger/libs/digger_config" @@ -15,7 +16,6 @@ func ProcessGitlabPullRequestEvent(payload *gitlab.MergeEvent, diggerConfig *dig var prNumber int prNumber = payload.ObjectAttributes.IID changedFiles, err := ciService.GetChangedFiles(prNumber) - if err != nil { return nil, nil, prNumber, fmt.Errorf("could not get changed files") } diff --git a/libs/ci/mocks.go b/libs/ci/mocks.go index 1e01a3e19..49c3805e5 100644 --- a/libs/ci/mocks.go +++ b/libs/ci/mocks.go @@ -8,13 +8,14 @@ type MockPullRequestManager struct { Approvals []string } -func (t MockPullRequestManager) GetUserTeams(organisation string, user string) ([]string, error) { +func (t MockPullRequestManager) GetUserTeams(organisation, user string) ([]string, error) { return t.Teams, nil } func (t MockPullRequestManager) GetChangedFiles(prNumber int) ([]string, error) { return t.ChangedFiles, nil } + func (t MockPullRequestManager) PublishComment(prNumber int, comment string) (*Comment, error) { return nil, nil } @@ -23,15 +24,15 @@ func (t MockPullRequestManager) ListIssues() ([]*Issue, error) { return nil, nil } -func (t MockPullRequestManager) PublishIssue(title string, body string, labels *[]string) (int64, error) { +func (t MockPullRequestManager) PublishIssue(title, body string, labels *[]string) (int64, error) { return 0, nil } -func (t MockPullRequestManager) UpdateIssue(ID int64, title string, body string) (int64, error) { +func (t MockPullRequestManager) UpdateIssue(ID int64, title, body string) (int64, error) { return 0, fmt.Errorf("implement me") } -func (t MockPullRequestManager) SetStatus(prNumber int, status string, statusContext string) error { +func (t MockPullRequestManager) SetStatus(prNumber int, status, statusContext string) error { return nil } @@ -67,7 +68,7 @@ func (t MockPullRequestManager) GetComments(prNumber int) ([]Comment, error) { return []Comment{}, nil } -func (t MockPullRequestManager) EditComment(prNumber int, id string, comment string) error { +func (t MockPullRequestManager) EditComment(prNumber int, id, comment string) error { return nil } @@ -75,7 +76,7 @@ func (t MockPullRequestManager) DeleteComment(id string) error { return nil } -func (t MockPullRequestManager) CreateCommentReaction(id string, reaction string) error { +func (t MockPullRequestManager) CreateCommentReaction(id, reaction string) error { return nil } @@ -83,6 +84,6 @@ func (t MockPullRequestManager) GetBranchName(prNumber int) (string, string, err return "", "", nil } -func (t MockPullRequestManager) SetOutput(prNumber int, key string, value string) error { +func (t MockPullRequestManager) SetOutput(prNumber int, key, value string) error { return nil } diff --git a/libs/comment_utils/reporting/core.go b/libs/comment_utils/reporting/core.go index adfdbdce1..3ff91ef36 100644 --- a/libs/comment_utils/reporting/core.go +++ b/libs/comment_utils/reporting/core.go @@ -1,7 +1,7 @@ package reporting type Reporter interface { - Report(report string, reportFormatting func(report string) string) (commentId string, commentUrl string, error error) + Report(report string, reportFormatting func(report string) string) (commentId, commentUrl string, error error) Flush() (string, string, error) Suppress() error SupportsMarkdown() bool diff --git a/libs/comment_utils/reporting/reporting.go b/libs/comment_utils/reporting/reporting.go index df43b79f9..35d22cdb6 100644 --- a/libs/comment_utils/reporting/reporting.go +++ b/libs/comment_utils/reporting/reporting.go @@ -105,7 +105,7 @@ func (reporter StdOutReporter) Suppress() error { } type ReportStrategy interface { - Report(ciService ci.PullRequestService, PrNumber int, report string, reportFormatter func(report string) string, supportsCollapsibleComment bool) (commentId string, commentUrl string, error error) + Report(ciService ci.PullRequestService, PrNumber int, report string, reportFormatter func(report string) string, supportsCollapsibleComment bool) (commentId, commentUrl string, error error) } type CommentPerRunStrategy struct { @@ -174,7 +174,6 @@ func upsertComment(ciService ci.PullRequestService, PrNumber int, report string, } err := ciService.EditComment(PrNumber, commentIdForThisRun, completeComment) - if err != nil { slog.Error("error editing comment", "error", err, "commentId", commentIdForThisRun, "prNumber", PrNumber) return "", "", fmt.Errorf("error editing comment: %v", err) diff --git a/libs/comment_utils/reporting/reporting_test.go b/libs/comment_utils/reporting/reporting_test.go index 5a20899e1..efb15a056 100644 --- a/libs/comment_utils/reporting/reporting_test.go +++ b/libs/comment_utils/reporting/reporting_test.go @@ -2,15 +2,16 @@ package reporting import ( "fmt" - "github.com/diggerhq/digger/libs/ci" "strconv" + + "github.com/diggerhq/digger/libs/ci" ) type MockCiService struct { CommentsPerPr map[int][]*ci.Comment } -func (t MockCiService) GetUserTeams(organisation string, user string) ([]string, error) { +func (t MockCiService) GetUserTeams(organisation, user string) ([]string, error) { return nil, nil } @@ -21,8 +22,8 @@ func (t MockCiService) GetApprovals(prNumber int) ([]string, error) { func (t MockCiService) GetChangedFiles(prNumber int) ([]string, error) { return nil, nil } -func (t MockCiService) PublishComment(prNumber int, comment string) (*ci.Comment, error) { +func (t MockCiService) PublishComment(prNumber int, comment string) (*ci.Comment, error) { latestId := 0 for _, comments := range t.CommentsPerPr { @@ -43,15 +44,15 @@ func (t MockCiService) ListIssues() ([]*ci.Issue, error) { return nil, fmt.Errorf("implement me") } -func (t MockCiService) PublishIssue(title string, body string, labels *[]string) (int64, error) { +func (t MockCiService) PublishIssue(title, body string, labels *[]string) (int64, error) { return 0, fmt.Errorf("implement me") } -func (svc MockCiService) UpdateIssue(ID int64, title string, body string) (int64, error) { +func (svc MockCiService) UpdateIssue(ID int64, title, body string) (int64, error) { return 0, fmt.Errorf("implement me") } -func (t MockCiService) SetStatus(prNumber int, status string, statusContext string) error { +func (t MockCiService) SetStatus(prNumber int, status, statusContext string) error { return nil } @@ -87,7 +88,7 @@ func (t MockCiService) GetComments(prNumber int) ([]ci.Comment, error) { return comments, nil } -func (t MockCiService) EditComment(prNumber int, id string, comment string) error { +func (t MockCiService) EditComment(prNumber int, id, comment string) error { for _, comments := range t.CommentsPerPr { for _, c := range comments { if c.Id == id { @@ -103,7 +104,7 @@ func (svc MockCiService) DeleteComment(id string) error { return nil } -func (svc MockCiService) CreateCommentReaction(id string, reaction string) error { +func (svc MockCiService) CreateCommentReaction(id, reaction string) error { // TODO implement me return nil } @@ -112,6 +113,6 @@ func (svc MockCiService) GetBranchName(prNumber int) (string, string, error) { return "", "", nil } -func (svc MockCiService) SetOutput(prNumber int, key string, value string) error { +func (svc MockCiService) SetOutput(prNumber int, key, value string) error { return nil } diff --git a/libs/comment_utils/summary/provider.go b/libs/comment_utils/summary/provider.go index 1d4b8d452..d9fe2e9b5 100644 --- a/libs/comment_utils/summary/provider.go +++ b/libs/comment_utils/summary/provider.go @@ -2,6 +2,7 @@ package comment_updater import ( "fmt" + "github.com/diggerhq/digger/libs/digger_config" ) diff --git a/libs/comment_utils/summary/updater.go b/libs/comment_utils/summary/updater.go index e2cc88b50..b871c1f28 100644 --- a/libs/comment_utils/summary/updater.go +++ b/libs/comment_utils/summary/updater.go @@ -14,8 +14,7 @@ type CommentUpdater interface { UpdateComment(jobs []scheduler.SerializedJob, prNumber int, prService ci.PullRequestService, prCommentId string) error } -type BasicCommentUpdater struct { -} +type BasicCommentUpdater struct{} func (b BasicCommentUpdater) UpdateComment(jobs []scheduler.SerializedJob, prNumber int, prService ci.PullRequestService, prCommentId string) error { jobSpecs, err := scheduler.GetJobSpecs(jobs) @@ -41,13 +40,13 @@ func (b BasicCommentUpdater) UpdateComment(jobs []scheduler.SerializedJob, prNum for i, job := range jobs { jobSpec := jobSpecs[i] prCommentUrl := job.PRCommentUrl - + // Safe handling of WorkflowRunUrl pointer workflowUrl := "#" if job.WorkflowRunUrl != nil { workflowUrl = *job.WorkflowRunUrl } - + message = message + fmt.Sprintf("|%v **%v** |%v | %v | %v | %v | %v|\n", job.Status.ToEmoji(), jobSpec.ProjectName, @@ -89,8 +88,7 @@ func (b BasicCommentUpdater) UpdateComment(jobs []scheduler.SerializedJob, prNum return nil } -type NoopCommentUpdater struct { -} +type NoopCommentUpdater struct{} func (b NoopCommentUpdater) UpdateComment(jobs []scheduler.SerializedJob, prNumber int, prService ci.PullRequestService, prCommentId string) error { slog.Debug("noop comment updater called, no action taken", diff --git a/libs/crypto/decrypt.go b/libs/crypto/decrypt.go index 195e38cab..206b986a7 100644 --- a/libs/crypto/decrypt.go +++ b/libs/crypto/decrypt.go @@ -10,7 +10,7 @@ import ( "fmt" ) -func DecryptValueUsingPrivateKey(encryptedDataBase64 string, privateKeyPEM string) (string, error) { +func DecryptValueUsingPrivateKey(encryptedDataBase64, privateKeyPEM string) (string, error) { // Decode the Base64-encoded encrypted data encryptedData, err := base64.StdEncoding.DecodeString(encryptedDataBase64) if err != nil { diff --git a/libs/digger_config/config.go b/libs/digger_config/config.go index ff3715f83..e59c7fc70 100644 --- a/libs/digger_config/config.go +++ b/libs/digger_config/config.go @@ -1,13 +1,17 @@ package digger_config -const CommentRenderModeBasic = "basic" -const CommentRenderModeGroupByModule = "group_by_module" +const ( + CommentRenderModeBasic = "basic" + CommentRenderModeGroupByModule = "group_by_module" +) type AutomergeStrategy string -const AutomergeStrategySquash AutomergeStrategy = "squash" -const AutomergeStrategyMerge AutomergeStrategy = "merge" -const AutomergeStrategyRebase AutomergeStrategy = "rebase" +const ( + AutomergeStrategySquash AutomergeStrategy = "squash" + AutomergeStrategyMerge AutomergeStrategy = "merge" + AutomergeStrategyRebase AutomergeStrategy = "rebase" +) type DiggerConfig struct { ApplyAfterMerge bool diff --git a/libs/digger_config/converters.go b/libs/digger_config/converters.go index eedb4a1db..4c9900ac0 100644 --- a/libs/digger_config/converters.go +++ b/libs/digger_config/converters.go @@ -183,7 +183,6 @@ func copyReporterConfig(r *ReportingConfigYaml) ReporterConfig { return ReporterConfig{ AiSummary: r.AiSummary, } - } func ConvertDiggerYamlToConfig(diggerYaml *DiggerConfigYaml) (*DiggerConfig, graph.Graph[string, Project], error) { @@ -363,7 +362,6 @@ func CreateProjectDependencyGraph(projects []Project) (graph.Graph[string, Proje return nil, fmt.Errorf("project '%s' does not exist", dependency) } err := g.AddVertex(dependencyProject) - if err != nil { return nil, err } diff --git a/libs/digger_config/digger_config.go b/libs/digger_config/digger_config.go index 4f6d31a5f..6f7467ad1 100644 --- a/libs/digger_config/digger_config.go +++ b/libs/digger_config/digger_config.go @@ -22,14 +22,11 @@ type DirWalker interface { GetDirs(workingDir string, config DiggerConfigYaml) ([]string, error) } -type FileSystemTopLevelTerraformDirWalker struct { -} +type FileSystemTopLevelTerraformDirWalker struct{} -type FileSystemTerragruntDirWalker struct { -} +type FileSystemTerragruntDirWalker struct{} -type FileSystemModuleDirWalker struct { -} +type FileSystemModuleDirWalker struct{} func ReadDiggerYmlFileContents(dir string) (string, error) { var diggerYmlBytes []byte @@ -77,7 +74,7 @@ func CheckOrCreateDiggerFile(dir string) error { return nil } -func GetFilesWithExtension(workingDir string, ext string) ([]string, error) { +func GetFilesWithExtension(workingDir, ext string) ([]string, error) { var files []string listOfFiles, err := os.ReadDir(workingDir) if err != nil { @@ -243,7 +240,7 @@ func LoadDiggerConfig(workingDir string, generateProjects bool, changedFiles []s return config, configYaml, projectDependencyGraph, nil } -func LoadDiggerConfigFromString(yamlString string, terraformDir string) (*DiggerConfig, *DiggerConfigYaml, graph.Graph[string, Project], error) { +func LoadDiggerConfigFromString(yamlString, terraformDir string) (*DiggerConfig, *DiggerConfigYaml, graph.Graph[string, Project], error) { slog.Info("loading digger configuration from string", "terraformDir", terraformDir) config := &DiggerConfig{} @@ -344,11 +341,10 @@ func HandleYamlProjectGeneration(config *DiggerConfigYaml, terraformDir string, return err } } else if config.GenerateProjectsConfig != nil { - var dirWalker = &FileSystemTopLevelTerraformDirWalker{} + dirWalker := &FileSystemTopLevelTerraformDirWalker{} slog.Info("finding terraform directories for project generation", "terraformDir", terraformDir) dirs, err := dirWalker.GetDirs(terraformDir, config) - if err != nil { slog.Error("error walking through directories", "error", err, "terraformDir", terraformDir) return fmt.Errorf("error while walking through directories: %v", err) @@ -699,7 +695,7 @@ func ValidateDiggerConfig(config *DiggerConfig) error { return nil } -func hydrateDiggerConfigYamlWithTerragrunt(configYaml *DiggerConfigYaml, parsingConfig TerragruntParsingConfig, workingDir string, blockName string) error { +func hydrateDiggerConfigYamlWithTerragrunt(configYaml *DiggerConfigYaml, parsingConfig TerragruntParsingConfig, workingDir, blockName string) error { slog.Info("hydrating config with terragrunt projects", "workingDir", workingDir, "filterPath", parsingConfig.FilterPath) @@ -792,7 +788,6 @@ func hydrateDiggerConfigYamlWithTerragrunt(configYaml *DiggerConfigYaml, parsing // normalize paths projectDir := path.Join(pathPrefix, atlantisProject.Dir) atlantisProject.Autoplan.WhenModified, err = GetPatternsRelativeToRepo(projectDir, atlantisProject.Autoplan.WhenModified) - if err != nil { slog.Error("could not normalize patterns", "error", err, diff --git a/libs/digger_config/digger_config_test.go b/libs/digger_config/digger_config_test.go index b9efe32a7..24428ba79 100644 --- a/libs/digger_config/digger_config_test.go +++ b/libs/digger_config/digger_config_test.go @@ -67,7 +67,6 @@ func TestDiggerConfigWhenCustomFileName(t *testing.T) { assert.Equal(t, configPath, path.Join(tempDir, "digger-custom.yml")) os.Unsetenv("DIGGER_FILENAME") - } func TestDiggerConfigWhenOnlyYamlExists(t *testing.T) { @@ -578,7 +577,6 @@ workflows: assert.NotNil(t, workflow) assert.NotNil(t, workflow.Plan) assert.NotNil(t, workflow.Apply) - } func TestDiggerConfigMissingProjectsWorkflow(t *testing.T) { @@ -602,7 +600,6 @@ workflows: _, _, _, err := LoadDiggerConfig(tempDir, true, nil) assert.Equal(t, "failed to find workflow digger_config 'my_custom_workflow' for project 'my-first-app'", err.Error()) - } func TestDiggerConfigWithEmptyInitBlock(t *testing.T) { @@ -664,7 +661,7 @@ func TestDiggerConfigDependencyGraph(t *testing.T) { assert.NoError(t, err, "expected error to be nil") - orderedProjects, _ := graph.StableTopologicalSort(g, func(s string, s2 string) bool { + orderedProjects, _ := graph.StableTopologicalSort(g, func(s, s2 string) bool { return s < s2 }) @@ -744,7 +741,7 @@ func TestDiggerConfigDependencyGraph2(t *testing.T) { assert.NoError(t, err, "expected error to be nil") - orderedProjects, _ := graph.StableTopologicalSort(g, func(s string, s2 string) bool { + orderedProjects, _ := graph.StableTopologicalSort(g, func(s, s2 string) bool { return s > s2 }) @@ -887,7 +884,7 @@ func deleteTempDir(name string) { } } -func createFile(filepath string, content string) func() { +func createFile(filepath, content string) func() { f, err := os.Create(filepath) if err != nil { panic(err) @@ -906,7 +903,7 @@ func createFile(filepath string, content string) func() { } } -func createAndCloseFile(filepath string, content string) error { +func createAndCloseFile(filepath, content string) error { f, err := os.Create(filepath) if err != nil { return err @@ -1308,7 +1305,7 @@ projects: func TestGetModifiedProjectsReturnsCorrectSourceMappingWithDotFile(t *testing.T) { changedFiles := []string{"prod/main.tf", "dev/test/main.tf"} projects := []Project{ - Project{ + { Name: "dev", Dir: ".", }, @@ -1316,7 +1313,7 @@ func TestGetModifiedProjectsReturnsCorrectSourceMappingWithDotFile(t *testing.T) c := DiggerConfig{ Projects: projects, } - //expectedImpactingLocations := map[string]ProjectToSourceMapping{} + // expectedImpactingLocations := map[string]ProjectToSourceMapping{} impactedProjects, _ := c.GetModifiedProjects(changedFiles) assert.Equal(t, 0, len(impactedProjects)) @@ -1325,12 +1322,12 @@ func TestGetModifiedProjectsReturnsCorrectSourceMappingWithDotFile(t *testing.T) func TestGetModifiedProjectsReturnsCorrectSourceMapping(t *testing.T) { changedFiles := []string{"modules/bucket/main.tf", "dev/main.tf"} projects := []Project{ - Project{ + { Name: "dev", Dir: "dev", IncludePatterns: []string{"modules/**"}, }, - Project{ + { Name: "prod", Dir: "prod", IncludePatterns: []string{"modules/**"}, @@ -1351,7 +1348,6 @@ func TestGetModifiedProjectsReturnsCorrectSourceMapping(t *testing.T) { assert.Equal(t, 1, len(projectSourceMapping["prod"].ImpactingLocations)) assert.Equal(t, expectedImpactingLocations["dev"].ImpactingLocations, projectSourceMapping["dev"].ImpactingLocations) assert.Equal(t, expectedImpactingLocations["prod"].ImpactingLocations, projectSourceMapping["prod"].ImpactingLocations) - } func TestCognitoTokenSetFromMinConfig(t *testing.T) { diff --git a/libs/digger_config/terragrunt/atlantis/base_blocks.go b/libs/digger_config/terragrunt/atlantis/base_blocks.go index 9cac060b2..55b2fe157 100644 --- a/libs/digger_config/terragrunt/atlantis/base_blocks.go +++ b/libs/digger_config/terragrunt/atlantis/base_blocks.go @@ -2,6 +2,9 @@ package atlantis import ( "fmt" + "log/slog" + "strings" + "github.com/gruntwork-io/go-commons/errors" "github.com/gruntwork-io/terragrunt/config" "github.com/gruntwork-io/terragrunt/options" @@ -11,8 +14,6 @@ import ( "github.com/hashicorp/hcl/v2/hclsyntax" "github.com/zclconf/go-cty/cty" "github.com/zclconf/go-cty/cty/gocty" - "log/slog" - "strings" ) const ( diff --git a/libs/digger_config/terragrunt/atlantis/generate.go b/libs/digger_config/terragrunt/atlantis/generate.go index a73f41024..30869cc28 100644 --- a/libs/digger_config/terragrunt/atlantis/generate.go +++ b/libs/digger_config/terragrunt/atlantis/generate.go @@ -3,8 +3,12 @@ package atlantis import ( "context" "log/slog" + "os" + "path/filepath" "regexp" "sort" + "strings" + "sync" "github.com/gruntwork-io/terragrunt/cli/commands/terraform" "github.com/gruntwork-io/terragrunt/config" @@ -14,11 +18,6 @@ import ( "github.com/hashicorp/go-getter" "golang.org/x/sync/singleflight" - - "os" - "path/filepath" - "strings" - "sync" ) // getEnvs: Parse env vars into a map @@ -36,7 +35,7 @@ func getEnvs() map[string]string { // Terragrunt imports can be relative or absolute // This makes relative paths absolute -func makePathAbsolute(gitRoot string, path string, parentPath string) string { +func makePathAbsolute(gitRoot, path, parentPath string) string { if strings.HasPrefix(path, filepath.ToSlash(gitRoot)) { return path } @@ -118,7 +117,7 @@ func sliceUnion(a, b []string) []string { } // Parses the terragrunt digger_config at `path` to find all modules it depends on -func getDependencies(ignoreParentTerragrunt bool, ignoreDependencyBlocks bool, gitRoot string, cascadeDependencies bool, path string, terragruntOptions *options.TerragruntOptions) ([]string, error) { +func getDependencies(ignoreParentTerragrunt, ignoreDependencyBlocks bool, gitRoot string, cascadeDependencies bool, path string, terragruntOptions *options.TerragruntOptions) ([]string, error) { res, err, _ := requestGroup.Do(path, func() (interface{}, error) { // Check if this path has already been computed cachedResult, ok := getDependenciesCache.get(path) @@ -167,7 +166,7 @@ func getDependencies(ignoreParentTerragrunt bool, ignoreDependencyBlocks bool, g getDependenciesCache.set(path, getDependenciesOutput{nil, err}) return nil, err } - //locals := ResolvedLocals{} + // locals := ResolvedLocals{} // Get deps from locals if locals.ExtraAtlantisDependencies != nil { @@ -316,7 +315,7 @@ func getDependencies(ignoreParentTerragrunt bool, ignoreDependencyBlocks bool, g } } -func createBaseProject(dir string, workflow string, terraformVersion string, applyRequirements *[]string, autoPlan bool, dependencies []string, createProjectName bool, createWorkspace bool) *AtlantisProject { +func createBaseProject(dir, workflow, terraformVersion string, applyRequirements *[]string, autoPlan bool, dependencies []string, createProjectName, createWorkspace bool) *AtlantisProject { project := &AtlantisProject{ Dir: filepath.ToSlash(dir), Workflow: workflow, @@ -342,7 +341,7 @@ func createBaseProject(dir string, workflow string, terraformVersion string, app } // Creates an AtlantisProject for a directory -func createProject(ignoreParentTerragrunt bool, ignoreDependencyBlocks bool, gitRoot string, cascadeDependencies bool, defaultWorkflow string, defaultApplyRequirements []string, autoPlan bool, defaultTerraformVersion string, createProjectName bool, createWorkspace bool, sourcePath string, triggerProjectsFromDirOnly bool) (*AtlantisProject, []string, error) { +func createProject(ignoreParentTerragrunt, ignoreDependencyBlocks bool, gitRoot string, cascadeDependencies bool, defaultWorkflow string, defaultApplyRequirements []string, autoPlan bool, defaultTerraformVersion string, createProjectName, createWorkspace bool, sourcePath string, triggerProjectsFromDirOnly bool) (*AtlantisProject, []string, error) { options, err := options.NewTerragruntOptionsWithConfigPath(sourcePath) var potentialProjectDependencies []string @@ -482,7 +481,7 @@ func projectNameFromDir(projectDir string) string { return projectName } -func createHclProject(defaultWorkflow string, defaultApplyRequirements []string, autoplan bool, useProjectMarkers bool, defaultTerraformVersion string, ignoreParentTerragrunt bool, ignoreDependencyBlocks bool, gitRoot string, cascadeDependencies bool, createProjectName bool, createWorkspace bool, sourcePaths []string, workingDir string, projectHcl string) (*AtlantisProject, error) { +func createHclProject(defaultWorkflow string, defaultApplyRequirements []string, autoplan, useProjectMarkers bool, defaultTerraformVersion string, ignoreParentTerragrunt, ignoreDependencyBlocks bool, gitRoot string, cascadeDependencies, createProjectName, createWorkspace bool, sourcePaths []string, workingDir, projectHcl string) (*AtlantisProject, error) { var projectHclDependencies []string var childDependencies []string workflow := defaultWorkflow @@ -693,7 +692,6 @@ func getAllTerragruntProjectHclFiles(projectHclFiles []string, gitRoot string) m return nil }) - if err != nil { slog.Error("failed to walk directory tree", "error", err, "gitRoot", gitRoot) panic(err) @@ -711,7 +709,7 @@ func getAllTerragruntProjectHclFiles(projectHclFiles []string, gitRoot string) m return uniqueHclFileAbsPaths } -func Parse(gitRoot string, projectHclFiles []string, createHclProjectExternalChilds bool, autoMerge bool, parallel bool, filterPath string, createHclProjectChilds bool, ignoreParentTerragrunt bool, ignoreDependencyBlocks bool, cascadeDependencies bool, defaultWorkflow string, defaultApplyRequirements []string, autoPlan bool, defaultTerraformVersion string, createProjectName bool, createWorkspace bool, preserveProjects bool, useProjectMarkers bool, executionOrderGroups bool, triggerProjectsFromDirOnly bool) (*AtlantisConfig, map[string][]string, error) { +func Parse(gitRoot string, projectHclFiles []string, createHclProjectExternalChilds, autoMerge, parallel bool, filterPath string, createHclProjectChilds, ignoreParentTerragrunt, ignoreDependencyBlocks, cascadeDependencies bool, defaultWorkflow string, defaultApplyRequirements []string, autoPlan bool, defaultTerraformVersion string, createProjectName, createWorkspace, preserveProjects, useProjectMarkers, executionOrderGroups, triggerProjectsFromDirOnly bool) (*AtlantisConfig, map[string][]string, error) { // Ensure the gitRoot has a trailing slash and is an absolute path absoluteGitRoot, err := filepath.Abs(gitRoot) if err != nil { diff --git a/libs/digger_config/terragrunt/atlantis/generate_test.go b/libs/digger_config/terragrunt/atlantis/generate_test.go index b2dc2012e..be4bb92a7 100644 --- a/libs/digger_config/terragrunt/atlantis/generate_test.go +++ b/libs/digger_config/terragrunt/atlantis/generate_test.go @@ -1,12 +1,13 @@ package atlantis import ( - "github.com/stretchr/testify/assert" - "golang.org/x/sync/singleflight" - "gopkg.in/yaml.v3" "log/slog" "os" "testing" + + "github.com/stretchr/testify/assert" + "golang.org/x/sync/singleflight" + "gopkg.in/yaml.v3" ) func init() { @@ -20,14 +21,13 @@ func init() { } func resetForRun() error { - // reset caches getDependenciesCache = newGetDependenciesCache() requestGroup = singleflight.Group{} return nil } -func runTest(t *testing.T, goldenFile string, testPath string, createProjectName bool, workflowName string, withWorkspace bool, parallel bool, ignoreParentTerragrunt bool, ignoreDependencyBlocks bool, cascadeDependencies bool) { +func runTest(t *testing.T, goldenFile, testPath string, createProjectName bool, workflowName string, withWorkspace, parallel, ignoreParentTerragrunt, ignoreDependencyBlocks, cascadeDependencies bool) { resetForRun() atlantisConfig, _, err := Parse( testPath, @@ -51,7 +51,6 @@ func runTest(t *testing.T, goldenFile string, testPath string, createProjectName false, false, ) - if err != nil { slog.Error("failed to parse terragrunt configuration", "error", err) t.Fatal(err) diff --git a/libs/digger_config/terragrunt/atlantis/parse_hcl.go b/libs/digger_config/terragrunt/atlantis/parse_hcl.go index b38ad6b90..6a4428879 100644 --- a/libs/digger_config/terragrunt/atlantis/parse_hcl.go +++ b/libs/digger_config/terragrunt/atlantis/parse_hcl.go @@ -1,6 +1,9 @@ package atlantis import ( + "log/slog" + "path/filepath" + "github.com/gruntwork-io/go-commons/errors" "github.com/gruntwork-io/terragrunt/config" "github.com/gruntwork-io/terragrunt/options" @@ -9,8 +12,6 @@ import ( "github.com/hashicorp/hcl/v2/gohcl" "github.com/hashicorp/hcl/v2/hclparse" "github.com/hashicorp/hcl/v2/hclwrite" - "log/slog" - "path/filepath" ) const bareIncludeKey = "" diff --git a/libs/digger_config/terragrunt/atlantis/parse_locals.go b/libs/digger_config/terragrunt/atlantis/parse_locals.go index 0c5a633ac..425024224 100644 --- a/libs/digger_config/terragrunt/atlantis/parse_locals.go +++ b/libs/digger_config/terragrunt/atlantis/parse_locals.go @@ -5,6 +5,9 @@ package atlantis // parses the `locals` blocks and evaluates their contents. import ( + "log/slog" + "path/filepath" + "github.com/gruntwork-io/go-commons/errors" "github.com/gruntwork-io/terragrunt/config" "github.com/gruntwork-io/terragrunt/options" @@ -12,9 +15,6 @@ import ( "github.com/hashicorp/hcl/v2" "github.com/hashicorp/hcl/v2/hclparse" "github.com/zclconf/go-cty/cty" - "log/slog" - - "path/filepath" ) // ResolvedLocals are the parsed result of local values this module cares about @@ -42,8 +42,7 @@ type ResolvedLocals struct { } // parseHcl uses the HCL2 parser to parse the given string into an HCL file body. -func parseHcl(parser *hclparse.Parser, hcl string, filename string) (file *hcl.File, err error) { - +func parseHcl(parser *hclparse.Parser, hcl, filename string) (file *hcl.File, err error) { // The HCL2 parser and especially cty conversions will panic in many types of errors, so we have to recover from // those panics here and convert them to normal errors defer func() { @@ -70,7 +69,7 @@ func parseHcl(parser *hclparse.Parser, hcl string, filename string) (file *hcl.F } // Merges in values from a child into a parent set of `local` values -func mergeResolvedLocals(parent ResolvedLocals, child ResolvedLocals) ResolvedLocals { +func mergeResolvedLocals(parent, child ResolvedLocals) ResolvedLocals { if child.AtlantisWorkflow != "" { parent.AtlantisWorkflow = child.AtlantisWorkflow } @@ -107,7 +106,7 @@ func parseLocals(path string, terragruntOptions *options.TerragruntOptions, incl return ResolvedLocals{}, err } - //Parse the HCL string into an AST body + // Parse the HCL string into an AST body parser := hclparse.NewParser() file, err := parseHcl(parser, configString, path) if err != nil { diff --git a/libs/digger_config/terragrunt/atlantis/parse_tf.go b/libs/digger_config/terragrunt/atlantis/parse_tf.go index 9d5bf310d..51695f5d1 100644 --- a/libs/digger_config/terragrunt/atlantis/parse_tf.go +++ b/libs/digger_config/terragrunt/atlantis/parse_tf.go @@ -2,9 +2,10 @@ package atlantis import ( "errors" + "strings" + "github.com/gruntwork-io/terragrunt/util" "github.com/hashicorp/terraform-config-inspect/tfconfig" - "strings" ) var localModuleSourcePrefixes = []string{ @@ -21,7 +22,7 @@ func parseTerraformLocalModuleSource(path string) ([]string, error) { return nil, errors.New(diags.Error()) } - var sourceMap = map[string]bool{} + sourceMap := map[string]bool{} for _, mc := range module.ModuleCalls { if isLocalTerraformModuleSource(mc.Source) { modulePath := util.JoinPath(path, mc.Source) @@ -44,7 +45,7 @@ func parseTerraformLocalModuleSource(path string) ([]string, error) { } } - var sources = []string{} + sources := []string{} for source := range sourceMap { sources = append(sources, source) } diff --git a/libs/digger_config/terragrunt/atlantis/partial_parse.go b/libs/digger_config/terragrunt/atlantis/partial_parse.go index f88134e2e..49fe7ebb2 100644 --- a/libs/digger_config/terragrunt/atlantis/partial_parse.go +++ b/libs/digger_config/terragrunt/atlantis/partial_parse.go @@ -3,6 +3,8 @@ package atlantis import ( "encoding/json" "fmt" + "path/filepath" + "github.com/gruntwork-io/go-commons/errors" "github.com/gruntwork-io/terragrunt/config" "github.com/gruntwork-io/terragrunt/options" @@ -12,7 +14,6 @@ import ( "github.com/hashicorp/hcl/v2/hclparse" "github.com/zclconf/go-cty/cty" ctyjson "github.com/zclconf/go-cty/cty/json" - "path/filepath" ) // terragruntDependencies is a struct that can be used to only decode the dependencies block. @@ -418,8 +419,8 @@ func TerragruntConfigFromPartialConfigString( decodeList []config.PartialDecodeSectionType, ) (*config.TerragruntConfig, error) { if terragruntOptions.UsePartialParseConfigCache { - var cacheKey = fmt.Sprintf("%#v-%#v-%#v-%#v", filename, configString, includeFromChild, decodeList) - var config, found = terragruntConfigCache.Get(cacheKey) + cacheKey := fmt.Sprintf("%#v-%#v-%#v-%#v", filename, configString, includeFromChild, decodeList) + config, found := terragruntConfigCache.Get(cacheKey) if !found { terragruntOptions.Logger.Debugf("Cache miss for '%s' (partial parsing), decodeList: '%v'.", filename, decodeList) diff --git a/libs/digger_config/utils.go b/libs/digger_config/utils.go index 3ca28b841..4194ef51a 100644 --- a/libs/digger_config/utils.go +++ b/libs/digger_config/utils.go @@ -25,7 +25,7 @@ func NormalizeFileName(fileName string) string { return res } -func MatchIncludeExcludePatternsToFile(fileToMatch string, includePatterns []string, excludePatterns []string) bool { +func MatchIncludeExcludePatternsToFile(fileToMatch string, includePatterns, excludePatterns []string) bool { fileToMatch = NormalizeFileName(fileToMatch) for i := range includePatterns { includePatterns[i] = NormalizeFileName(includePatterns[i]) diff --git a/libs/digger_config/utils_test.go b/libs/digger_config/utils_test.go index 7c5d857d6..4fe2e85ac 100644 --- a/libs/digger_config/utils_test.go +++ b/libs/digger_config/utils_test.go @@ -1,8 +1,9 @@ package digger_config import ( - "github.com/stretchr/testify/assert" "testing" + + "github.com/stretchr/testify/assert" ) func TestMatchIncludeExcludePatternsToFile(t *testing.T) { @@ -25,7 +26,6 @@ func TestMatchIncludeExcludePatternsToFile(t *testing.T) { var ep []string result = MatchIncludeExcludePatternsToFile("/projects/dev/test1", ip, ep) assert.Equal(t, false, result) - } func TestGetPatternsRelativeToRepo(t *testing.T) { @@ -43,5 +43,4 @@ func TestGetPatternsRelativeToRepo(t *testing.T) { includePatterns = []string{"*.hcl"} res, _ = GetPatternsRelativeToRepo(projectDir, includePatterns) assert.Equal(t, "myProject/terraform/environments/devel/*.hcl", res[0]) - } diff --git a/libs/digger_config/yaml.go b/libs/digger_config/yaml.go index 155d19756..31fdaf204 100644 --- a/libs/digger_config/yaml.go +++ b/libs/digger_config/yaml.go @@ -167,7 +167,7 @@ type TerragruntParsingConfig struct { PreserveProjects bool `yaml:"preserveProjects"` CascadeDependencies *bool `yaml:"cascadeDependencies,omitempty"` DefaultApplyRequirements []string `yaml:"defaultApplyRequirements"` - //NumExecutors int64 `yaml:"numExecutors"` + // NumExecutors int64 `yaml:"numExecutors"` ProjectHclFiles []string `yaml:"projectHclFiles"` CreateHclProjectChilds bool `yaml:"createHclProjectChilds"` CreateHclProjectExternalChilds *bool `yaml:"createHclProjectExternalChilds,omitempty"` @@ -253,7 +253,6 @@ func validateWorkflowConfigurationYaml(config *WorkflowConfigurationYaml) error } func (s *StepYaml) UnmarshalYAML(value *yaml.Node) error { - if value.Kind == yaml.ScalarNode { return value.Decode(&s.Action) } diff --git a/libs/execution/execution.go b/libs/execution/execution.go index 4583a2153..06c7a522a 100644 --- a/libs/execution/execution.go +++ b/libs/execution/execution.go @@ -108,8 +108,10 @@ type DiggerExecutor struct { type DiggerOperationType string -var DiggerOparationTypePlan DiggerOperationType = "plan" -var DiggerOparationTypeApply DiggerOperationType = "apply" +var ( + DiggerOparationTypePlan DiggerOperationType = "plan" + DiggerOparationTypeApply DiggerOperationType = "apply" +) type DiggerExecutorResult struct { OperationType DiggerOperationType @@ -161,7 +163,6 @@ func (d ProjectPathProvider) StoredPlanFilePath() string { } else { return strings.ReplaceAll(d.ProjectNamespace, "/", "-") + "-" + d.ProjectName + ".tfplan" } - } func (d ProjectPathProvider) LocalPlanFilePath() string { @@ -399,7 +400,7 @@ func reportApplyError(r reporting.Reporter, err error) { } } -func reportTerraformApplyOutput(r reporting.Reporter, projectId string, applyOutput string) { +func reportTerraformApplyOutput(r reporting.Reporter, projectId, applyOutput string) { var formatter func(string) string if r.SupportsMarkdown() { formatter = utils.GetTerraformOutputAsCollapsibleComment("Apply output", false) @@ -456,7 +457,6 @@ func reportAdditionalOutput(r reporting.Reporter, projectId string) { } func (d DiggerExecutor) Destroy() (bool, error) { - destroySteps := []configuration.Step{ { Action: "init", @@ -483,7 +483,7 @@ func (d DiggerExecutor) Destroy() (bool, error) { return true, nil } -func cleanupTerraformOutput(nonEmptyOutput bool, planError error, stdout string, stderr string, regexStr *string) string { +func cleanupTerraformOutput(nonEmptyOutput bool, planError error, stdout, stderr string, regexStr *string) string { var errorStr string // removes output of terraform -version command that terraform-exec executes on every run @@ -534,11 +534,11 @@ func cleanupTerraformOutput(nonEmptyOutput bool, planError error, stdout string, return stdout[startPos:endPos] } -func cleanupTerraformApply(nonEmptyPlan bool, planError error, stdout string, stderr string) string { +func cleanupTerraformApply(nonEmptyPlan bool, planError error, stdout, stderr string) string { return cleanupTerraformOutput(nonEmptyPlan, planError, stdout, stderr, nil) } -func cleanupTerraformPlan(nonEmptyPlan bool, planError error, stdout string, stderr string) string { +func cleanupTerraformPlan(nonEmptyPlan bool, planError error, stdout, stderr string) string { regex := `───────────.+` return cleanupTerraformOutput(nonEmptyPlan, planError, stdout, stderr, ®ex) } diff --git a/libs/execution/execution_test.go b/libs/execution/execution_test.go index 096f5c0ed..2936bbdf3 100644 --- a/libs/execution/execution_test.go +++ b/libs/execution/execution_test.go @@ -1,9 +1,10 @@ package execution import ( - "github.com/stretchr/testify/assert" "strings" "testing" + + "github.com/stretchr/testify/assert" ) func TestCorrectCleanUpWithoutRegexDoesNotProduceException(t *testing.T) { diff --git a/libs/execution/io_writer_filtered_test.go b/libs/execution/io_writer_filtered_test.go index 2ecc87d7f..75a7aa4d8 100644 --- a/libs/execution/io_writer_filtered_test.go +++ b/libs/execution/io_writer_filtered_test.go @@ -2,9 +2,10 @@ package execution import ( "bytes" - "github.com/stretchr/testify/assert" "regexp" "testing" + + "github.com/stretchr/testify/assert" ) func TestNewFilteringWriter(t *testing.T) { @@ -24,5 +25,4 @@ func TestNewFilteringWriter(t *testing.T) { writer.Write([]byte("output")) assert.Equal(t, "