From 9a4003b4acc4062127169024ab4f4d0bcad56937 Mon Sep 17 00:00:00 2001 From: Easton Crupper <65553218+ecrupper@users.noreply.github.com> Date: Mon, 4 Nov 2024 11:07:09 -0500 Subject: [PATCH] chore(lint): address existing linter issues (#1218) * chore(lint): address existing linter issues * remove dupl from exclusion list --- .golangci.yml | 4 +- api/admin/service.go | 1 - api/admin/step.go | 1 - api/admin/user.go | 1 - api/build/enqueue.go | 4 +- api/log/create_service.go | 1 - api/log/create_step.go | 1 - api/log/delete_service.go | 1 - api/log/delete_step.go | 1 - api/log/get_service.go | 1 - api/log/get_step.go | 1 - api/log/update_service.go | 1 - api/log/update_step.go | 1 - api/pipeline/compile.go | 1 - api/pipeline/expand.go | 1 - api/repo/repair.go | 2 +- api/types/actions/deploy.go | 2 - api/types/actions/schedule.go | 2 - api/types/build.go | 4 +- api/types/service.go | 2 +- api/types/settings/compiler.go | 6 +-- api/types/step.go | 2 +- api/types/template.go | 1 - api/user/create_token.go | 1 - api/user/delete_token.go | 1 - api/webhook/post.go | 44 ++++++++++----------- compiler/native/compile.go | 4 ++ compiler/native/native.go | 2 +- compiler/registry/github/template.go | 4 +- compiler/template/starlark/render.go | 30 ++++++++------ compiler/template/starlark/render_test.go | 2 +- compiler/template/starlark/starlark.go | 1 + compiler/types/pipeline/ruleset.go | 40 +++++++++++++------ compiler/types/yaml/service.go | 2 - compiler/types/yaml/stage.go | 2 + compiler/types/yaml/step.go | 2 - constants/errors.go | 12 ++++++ database/build/create.go | 1 - database/build/update.go | 1 - database/log/create.go | 1 - database/log/get_service.go | 1 - database/log/get_step.go | 1 - database/log/update.go | 1 - database/repo/create.go | 1 - database/repo/update.go | 1 - database/resource.go | 30 +++++++------- database/secret/create.go | 1 - database/secret/update.go | 1 - database/types/build.go | 18 ++++----- database/types/build_test.go | 10 ++--- database/types/repo.go | 6 +-- database/types/repo_test.go | 2 +- database/types/service.go | 18 ++++----- database/types/service_test.go | 16 ++++---- database/types/settings.go | 4 +- database/types/step.go | 18 ++++----- database/types/step_test.go | 16 ++++---- database/user/create.go | 1 - database/user/update.go | 1 - internal/token/generate_rsa.go | 2 +- mock/server/authentication.go | 8 ++-- mock/server/hook.go | 1 - mock/server/secret.go | 1 - mock/server/service.go | 1 - mock/server/step.go | 1 - queue/redis/opts.go | 4 -- router/middleware/logger.go | 2 +- router/middleware/perm/perm_test.go | 48 +++++++++++------------ router/service.go | 1 - router/step.go | 1 - scm/github/authentication.go | 6 +-- scm/github/repo.go | 4 -- scm/github/webhook.go | 4 +- secret/vault/count.go | 2 +- secret/vault/create.go | 2 +- secret/vault/delete.go | 2 +- secret/vault/get.go | 5 +-- secret/vault/refresh_test.go | 16 ++++---- 78 files changed, 217 insertions(+), 233 deletions(-) create mode 100644 constants/errors.go diff --git a/.golangci.yml b/.golangci.yml index 23cf2547f..3eccaf51e 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -80,10 +80,9 @@ linters: - bidichk # checks for dangerous unicode character sequences - bodyclose # checks whether HTTP response body is closed successfully - contextcheck # check the function whether use a non-inherited context - - dupl # code clone detection + - copyloopvar # checks for loop variables - errcheck # checks for unchecked errors - errorlint # find misuses of errors - - exportloopref # check for exported loop vars - funlen # detects long functions - gci # consistent import ordering - goconst # finds repeated strings that could be replaced by a constant @@ -169,7 +168,6 @@ issues: # prevent linters from running on *_test.go files - path: _test\.go linters: - - dupl - funlen - goconst - gocyclo diff --git a/api/admin/service.go b/api/admin/service.go index 5e5e5dcba..8d4d56d1b 100644 --- a/api/admin/service.go +++ b/api/admin/service.go @@ -1,6 +1,5 @@ // SPDX-License-Identifier: Apache-2.0 -//nolint:dupl // ignore similar code package admin import ( diff --git a/api/admin/step.go b/api/admin/step.go index 6e7ad4cdb..67311d091 100644 --- a/api/admin/step.go +++ b/api/admin/step.go @@ -1,6 +1,5 @@ // SPDX-License-Identifier: Apache-2.0 -//nolint:dupl // ignore similar code with user.go package admin import ( diff --git a/api/admin/user.go b/api/admin/user.go index 3f6d1b1ca..5f480495e 100644 --- a/api/admin/user.go +++ b/api/admin/user.go @@ -1,6 +1,5 @@ // SPDX-License-Identifier: Apache-2.0 -//nolint:dupl // ignore similar code package admin import ( diff --git a/api/build/enqueue.go b/api/build/enqueue.go index aa87f4473..695967ca0 100644 --- a/api/build/enqueue.go +++ b/api/build/enqueue.go @@ -39,11 +39,11 @@ func Enqueue(ctx context.Context, queue queue.Service, db database.Interface, it l.Debugf("pushing item for build to queue route %s", route) // push item on to the queue - err = queue.Push(context.Background(), route, byteItem) + err = queue.Push(ctx, route, byteItem) if err != nil { l.Errorf("retrying; failed to publish build: %v", err) - err = queue.Push(context.Background(), route, byteItem) + err = queue.Push(ctx, route, byteItem) if err != nil { l.Errorf("failed to publish build: %v", err) diff --git a/api/log/create_service.go b/api/log/create_service.go index fda667ae5..578663c64 100644 --- a/api/log/create_service.go +++ b/api/log/create_service.go @@ -1,6 +1,5 @@ // SPDX-License-Identifier: Apache-2.0 -//nolint:dupl // ignore similar code to step package log import ( diff --git a/api/log/create_step.go b/api/log/create_step.go index 507d19798..799122d8e 100644 --- a/api/log/create_step.go +++ b/api/log/create_step.go @@ -1,6 +1,5 @@ // SPDX-License-Identifier: Apache-2.0 -//nolint:dupl // ignore similar code to service package log import ( diff --git a/api/log/delete_service.go b/api/log/delete_service.go index 598874def..34e61f811 100644 --- a/api/log/delete_service.go +++ b/api/log/delete_service.go @@ -1,6 +1,5 @@ // SPDX-License-Identifier: Apache-2.0 -//nolint:dupl // ignore similar code with step package log import ( diff --git a/api/log/delete_step.go b/api/log/delete_step.go index 28b8b6cd5..221ccffa3 100644 --- a/api/log/delete_step.go +++ b/api/log/delete_step.go @@ -1,6 +1,5 @@ // SPDX-License-Identifier: Apache-2.0 -//nolint:dupl // ignore similar code with service package log import ( diff --git a/api/log/get_service.go b/api/log/get_service.go index a82f268ec..f512fbc60 100644 --- a/api/log/get_service.go +++ b/api/log/get_service.go @@ -1,6 +1,5 @@ // SPDX-License-Identifier: Apache-2.0 -//nolint:dupl // ignore similar code with step package log import ( diff --git a/api/log/get_step.go b/api/log/get_step.go index 2a8f0f5e0..f5d5b60b4 100644 --- a/api/log/get_step.go +++ b/api/log/get_step.go @@ -1,6 +1,5 @@ // SPDX-License-Identifier: Apache-2.0 -//nolint:dupl // ignore similar code with service package log import ( diff --git a/api/log/update_service.go b/api/log/update_service.go index 646a0d031..f51bf6084 100644 --- a/api/log/update_service.go +++ b/api/log/update_service.go @@ -1,6 +1,5 @@ // SPDX-License-Identifier: Apache-2.0 -//nolint:dupl // ignore similar code with step package log import ( diff --git a/api/log/update_step.go b/api/log/update_step.go index 7204afdb0..824544627 100644 --- a/api/log/update_step.go +++ b/api/log/update_step.go @@ -1,6 +1,5 @@ // SPDX-License-Identifier: Apache-2.0 -//nolint:dupl // ignore similar code with service package log import ( diff --git a/api/pipeline/compile.go b/api/pipeline/compile.go index 23f997fcc..57d66c0aa 100644 --- a/api/pipeline/compile.go +++ b/api/pipeline/compile.go @@ -1,6 +1,5 @@ // SPDX-License-Identifier: Apache-2.0 -//nolint:dupl // ignore similar code with expand package pipeline import ( diff --git a/api/pipeline/expand.go b/api/pipeline/expand.go index f50bb6c14..966ef8cc2 100644 --- a/api/pipeline/expand.go +++ b/api/pipeline/expand.go @@ -1,6 +1,5 @@ // SPDX-License-Identifier: Apache-2.0 -//nolint:dupl // ignore similar code with compile package pipeline import ( diff --git a/api/repo/repair.go b/api/repo/repair.go index 2fd99f9e2..f48ceea2c 100644 --- a/api/repo/repair.go +++ b/api/repo/repair.go @@ -156,7 +156,7 @@ func RepairRepo(c *gin.Context) { sourceRepo.SetPreviousName(r.GetName()) } - r, err = wh.RenameRepository(ctx, h, sourceRepo, c, m) + r, err = wh.RenameRepository(ctx, l, database.FromContext(c), h, sourceRepo, m) if err != nil { util.HandleError(c, http.StatusInternalServerError, err) return diff --git a/api/types/actions/deploy.go b/api/types/actions/deploy.go index 1664c39d3..409e24d1b 100644 --- a/api/types/actions/deploy.go +++ b/api/types/actions/deploy.go @@ -1,6 +1,4 @@ // SPDX-License-Identifier: Apache-2.0 -// -//nolint:dupl // similar code to schedule.go package actions import "github.com/go-vela/server/constants" diff --git a/api/types/actions/schedule.go b/api/types/actions/schedule.go index 296f0ba16..4d30ce384 100644 --- a/api/types/actions/schedule.go +++ b/api/types/actions/schedule.go @@ -1,6 +1,4 @@ // SPDX-License-Identifier: Apache-2.0 -// -//nolint:dupl // similar code to deploy.go package actions import "github.com/go-vela/server/constants" diff --git a/api/types/build.go b/api/types/build.go index f5af28911..70c33b8e7 100644 --- a/api/types/build.go +++ b/api/types/build.go @@ -57,7 +57,7 @@ type Build struct { func (b *Build) Duration() string { // check if the build doesn't have a started timestamp if b.GetStarted() == 0 { - return "..." + return constants.ErrorEmptyDuration } // capture started unix timestamp from the build @@ -1128,8 +1128,6 @@ func (b *Build) SetApprovedBy(v string) { } // String implements the Stringer interface for the Build type. -// -//nolint:dupl // this is duplicated in the test func (b *Build) String() string { return fmt.Sprintf(`{ ApprovedAt: %d, diff --git a/api/types/service.go b/api/types/service.go index 075beb44f..92360a662 100644 --- a/api/types/service.go +++ b/api/types/service.go @@ -37,7 +37,7 @@ type Service struct { func (s *Service) Duration() string { // check if the service doesn't have a started timestamp if s.GetStarted() == 0 { - return "..." + return constants.ErrorEmptyDuration } // capture started unix timestamp from the service diff --git a/api/types/settings/compiler.go b/api/types/settings/compiler.go index 7b6db1239..3a945c637 100644 --- a/api/types/settings/compiler.go +++ b/api/types/settings/compiler.go @@ -7,7 +7,7 @@ import "fmt" type Compiler struct { CloneImage *string `json:"clone_image,omitempty" yaml:"clone_image,omitempty"` TemplateDepth *int `json:"template_depth,omitempty" yaml:"template_depth,omitempty"` - StarlarkExecLimit *uint64 `json:"starlark_exec_limit,omitempty" yaml:"starlark_exec_limit,omitempty"` + StarlarkExecLimit *int64 `json:"starlark_exec_limit,omitempty" yaml:"starlark_exec_limit,omitempty"` } // GetCloneImage returns the CloneImage field. @@ -40,7 +40,7 @@ func (cs *Compiler) GetTemplateDepth() int { // // When the provided Compiler type is nil, or the field within // the type is nil, it returns the zero value for the field. -func (cs *Compiler) GetStarlarkExecLimit() uint64 { +func (cs *Compiler) GetStarlarkExecLimit() int64 { // return zero value if Compiler type or StarlarkExecLimit field is nil if cs == nil || cs.StarlarkExecLimit == nil { return 0 @@ -79,7 +79,7 @@ func (cs *Compiler) SetTemplateDepth(v int) { // // When the provided Compiler type is nil, it // will set nothing and immediately return. -func (cs *Compiler) SetStarlarkExecLimit(v uint64) { +func (cs *Compiler) SetStarlarkExecLimit(v int64) { // return if Compiler type is nil if cs == nil { return diff --git a/api/types/step.go b/api/types/step.go index 52d96f45c..4f1dcab06 100644 --- a/api/types/step.go +++ b/api/types/step.go @@ -39,7 +39,7 @@ type Step struct { func (s *Step) Duration() string { // check if the step doesn't have a started timestamp if s.GetStarted() == 0 { - return "..." + return constants.ErrorEmptyDuration } // capture started unix timestamp from the step diff --git a/api/types/template.go b/api/types/template.go index 2090e5ae7..9b435dad8 100644 --- a/api/types/template.go +++ b/api/types/template.go @@ -1,6 +1,5 @@ // SPDX-License-Identifier: Apache-2.0 -//nolint:dupl // ignore false positive with build_queue.go package types import ( diff --git a/api/user/create_token.go b/api/user/create_token.go index bb1345193..240f2ef9a 100644 --- a/api/user/create_token.go +++ b/api/user/create_token.go @@ -1,6 +1,5 @@ // SPDX-License-Identifier: Apache-2.0 -//nolint:dupl // ignore similar code with delete token package user import ( diff --git a/api/user/delete_token.go b/api/user/delete_token.go index 6a03d21e8..56e799dd1 100644 --- a/api/user/delete_token.go +++ b/api/user/delete_token.go @@ -1,6 +1,5 @@ // SPDX-License-Identifier: Apache-2.0 -//nolint:dupl // ignore similar code with create token package user import ( diff --git a/api/webhook/post.go b/api/webhook/post.go index d8ca86ab7..3cb1017d2 100644 --- a/api/webhook/post.go +++ b/api/webhook/post.go @@ -145,9 +145,11 @@ func PostWebhook(c *gin.Context) { l.Debugf("hook generated from SCM: %v", h) l.Debugf("repo generated from SCM: %v", r) + db := database.FromContext(c) + // if event is repository event, handle separately and return if strings.EqualFold(h.GetEvent(), constants.EventRepository) { - r, err = handleRepositoryEvent(ctx, c, m, h, r) + r, err = handleRepositoryEvent(ctx, l, db, m, h, r) if err != nil { util.HandleError(c, http.StatusInternalServerError, err) return @@ -189,6 +191,8 @@ func PostWebhook(c *gin.Context) { defer func() { // send API call to update the webhook + // + //nolint:contextcheck // false positive _, err = database.FromContext(c).UpdateHook(ctx, h) if err != nil { l.Errorf("unable to update webhook %s/%d: %v", r.GetFullName(), h.GetNumber(), err) @@ -617,9 +621,7 @@ func PostWebhook(c *gin.Context) { // the database resources with any relevant changes resulting from the event, such as name changes, transfers, etc. // // the caller is responsible for returning errors to the client. -func handleRepositoryEvent(ctx context.Context, c *gin.Context, m *internal.Metadata, h *types.Hook, r *types.Repo) (*types.Repo, error) { - l := c.MustGet("logger").(*logrus.Entry) - +func handleRepositoryEvent(ctx context.Context, l *logrus.Entry, db database.Interface, m *internal.Metadata, h *types.Hook, r *types.Repo) (*types.Repo, error) { l = l.WithFields(logrus.Fields{ "event_type": h.GetEvent(), }) @@ -628,7 +630,7 @@ func handleRepositoryEvent(ctx context.Context, c *gin.Context, m *internal.Meta defer func() { // send API call to update the webhook - hr, err := database.FromContext(c).CreateHook(ctx, h) + hr, err := db.CreateHook(ctx, h) if err != nil { l.Errorf("unable to create webhook %s/%d: %v", r.GetFullName(), h.GetNumber(), err) } @@ -645,7 +647,7 @@ func handleRepositoryEvent(ctx context.Context, c *gin.Context, m *internal.Meta switch h.GetEventAction() { // if action is renamed or transferred, go through rename routine case constants.ActionRenamed, constants.ActionTransferred: - r, err := RenameRepository(ctx, h, r, c, m) + r, err := RenameRepository(ctx, l, db, h, r, m) if err != nil { h.SetStatus(constants.StatusFailure) h.SetError(err.Error()) @@ -658,7 +660,7 @@ func handleRepositoryEvent(ctx context.Context, c *gin.Context, m *internal.Meta case "archived", "unarchived", constants.ActionEdited: l.Debugf("repository action %s for %s", h.GetEventAction(), r.GetFullName()) // send call to get repository from database - dbRepo, err := database.FromContext(c).GetRepoForOrg(ctx, r.GetOrg(), r.GetName()) + dbRepo, err := db.GetRepoForOrg(ctx, r.GetOrg(), r.GetName()) if err != nil { retErr := fmt.Errorf("%s: failed to get repo %s: %w", baseErr, r.GetFullName(), err) @@ -669,7 +671,7 @@ func handleRepositoryEvent(ctx context.Context, c *gin.Context, m *internal.Meta } // send API call to capture the last hook for the repo - lastHook, err := database.FromContext(c).LastHookForRepo(ctx, dbRepo) + lastHook, err := db.LastHookForRepo(ctx, dbRepo) if err != nil { retErr := fmt.Errorf("unable to get last hook for repo %s: %w", r.GetFullName(), err) @@ -702,7 +704,7 @@ func handleRepositoryEvent(ctx context.Context, c *gin.Context, m *internal.Meta } // update repo object in the database after applying edits - dbRepo, err = database.FromContext(c).UpdateRepo(ctx, dbRepo) + dbRepo, err = db.UpdateRepo(ctx, dbRepo) if err != nil { retErr := fmt.Errorf("%s: failed to update repo %s: %w", baseErr, r.GetFullName(), err) @@ -731,9 +733,7 @@ func handleRepositoryEvent(ctx context.Context, c *gin.Context, m *internal.Meta // associated with that repo as well as build links for the UI. // // the caller is responsible for returning errors to the client. -func RenameRepository(ctx context.Context, h *types.Hook, r *types.Repo, c *gin.Context, m *internal.Metadata) (*types.Repo, error) { - l := c.MustGet("logger").(*logrus.Entry) - +func RenameRepository(ctx context.Context, l *logrus.Entry, db database.Interface, h *types.Hook, r *types.Repo, m *internal.Metadata) (*types.Repo, error) { l = l.WithFields(logrus.Fields{ "event_type": h.GetEvent(), }) @@ -741,13 +741,13 @@ func RenameRepository(ctx context.Context, h *types.Hook, r *types.Repo, c *gin. l.Debugf("renaming repository from %s to %s", r.GetPreviousName(), r.GetName()) // get any matching hook with the repo's unique webhook ID in the SCM - hook, err := database.FromContext(c).GetHookByWebhookID(ctx, h.GetWebhookID()) + hook, err := db.GetHookByWebhookID(ctx, h.GetWebhookID()) if err != nil { return nil, fmt.Errorf("%s: failed to get hook with webhook ID %d from database", baseErr, h.GetWebhookID()) } // get the repo from the database using repo id of matching hook - dbR, err := database.FromContext(c).GetRepo(ctx, hook.GetRepo().GetID()) + dbR, err := db.GetRepo(ctx, hook.GetRepo().GetID()) if err != nil { return nil, fmt.Errorf("%s: failed to get repo %d from database", baseErr, hook.GetRepo().GetID()) } @@ -756,7 +756,7 @@ func RenameRepository(ctx context.Context, h *types.Hook, r *types.Repo, c *gin. h.SetRepo(r) // send API call to capture the last hook for the repo - lastHook, err := database.FromContext(c).LastHookForRepo(ctx, dbR) + lastHook, err := db.LastHookForRepo(ctx, dbR) if err != nil { retErr := fmt.Errorf("unable to get last hook for repo %s: %w", r.GetFullName(), err) @@ -774,7 +774,7 @@ func RenameRepository(ctx context.Context, h *types.Hook, r *types.Repo, c *gin. } // get total number of secrets associated with repository - t, err := database.FromContext(c).CountSecretsForRepo(ctx, dbR, map[string]interface{}{}) + t, err := db.CountSecretsForRepo(ctx, dbR, map[string]interface{}{}) if err != nil { return nil, fmt.Errorf("unable to get secret count for repo %s/%s: %w", dbR.GetOrg(), dbR.GetName(), err) } @@ -783,7 +783,7 @@ func RenameRepository(ctx context.Context, h *types.Hook, r *types.Repo, c *gin. page := 1 // capture all secrets belonging to certain repo in database for repoSecrets := int64(0); repoSecrets < t; repoSecrets += 100 { - s, _, err := database.FromContext(c).ListSecretsForRepo(ctx, dbR, map[string]interface{}{}, page, 100) + s, _, err := db.ListSecretsForRepo(ctx, dbR, map[string]interface{}{}, page, 100) if err != nil { return nil, fmt.Errorf("unable to get secret list for repo %s/%s: %w", dbR.GetOrg(), dbR.GetName(), err) } @@ -798,7 +798,7 @@ func RenameRepository(ctx context.Context, h *types.Hook, r *types.Repo, c *gin. secret.SetOrg(r.GetOrg()) secret.SetRepo(r.GetName()) - _, err = database.FromContext(c).UpdateSecret(ctx, secret) + _, err = db.UpdateSecret(ctx, secret) if err != nil { return nil, fmt.Errorf("unable to update secret for repo %s/%s: %w", dbR.GetOrg(), dbR.GetName(), err) } @@ -811,7 +811,7 @@ func RenameRepository(ctx context.Context, h *types.Hook, r *types.Repo, c *gin. } // get total number of builds associated with repository - t, err = database.FromContext(c).CountBuildsForRepo(ctx, dbR, nil) + t, err = db.CountBuildsForRepo(ctx, dbR, nil) if err != nil { return nil, fmt.Errorf("unable to get build count for repo %s: %w", dbR.GetFullName(), err) } @@ -820,7 +820,7 @@ func RenameRepository(ctx context.Context, h *types.Hook, r *types.Repo, c *gin. page = 1 // capture all builds belonging to repo in database for build := int64(0); build < t; build += 100 { - b, _, err := database.FromContext(c).ListBuildsForRepo(ctx, dbR, nil, time.Now().Unix(), 0, page, 100) + b, _, err := db.ListBuildsForRepo(ctx, dbR, nil, time.Now().Unix(), 0, page, 100) if err != nil { return nil, fmt.Errorf("unable to get build list for repo %s: %w", dbR.GetFullName(), err) } @@ -836,7 +836,7 @@ func RenameRepository(ctx context.Context, h *types.Hook, r *types.Repo, c *gin. fmt.Sprintf("%s/%s/%d", m.Vela.WebAddress, r.GetFullName(), build.GetNumber()), ) - _, err = database.FromContext(c).UpdateBuild(ctx, build) + _, err = db.UpdateBuild(ctx, build) if err != nil { return nil, fmt.Errorf("unable to update build for repo %s: %w", dbR.GetFullName(), err) } @@ -859,7 +859,7 @@ func RenameRepository(ctx context.Context, h *types.Hook, r *types.Repo, c *gin. dbR.SetPreviousName(r.GetPreviousName()) // update the repo in the database - dbR, err = database.FromContext(c).UpdateRepo(ctx, dbR) + dbR, err = db.UpdateRepo(ctx, dbR) if err != nil { retErr := fmt.Errorf("%s: failed to update repo %s/%s", baseErr, dbR.GetOrg(), dbR.GetName()) diff --git a/compiler/native/compile.go b/compiler/native/compile.go index 49d071431..13ad8eba7 100644 --- a/compiler/native/compile.go +++ b/compiler/native/compile.go @@ -330,6 +330,8 @@ func (c *client) compileSteps(ctx context.Context, p *yaml.Build, _pipeline *api if c.ModificationService.Endpoint != "" { // send config to external endpoint for modification + // + //nolint:contextcheck // modification service has its own context with a set timeout p, err = c.modifyConfig(p, c.build, c.repo) if err != nil { return nil, _pipeline, err @@ -425,6 +427,8 @@ func (c *client) compileStages(ctx context.Context, p *yaml.Build, _pipeline *ap if c.ModificationService.Endpoint != "" { // send config to external endpoint for modification + // + //nolint:contextcheck // modification service has its own context with a set timeout p, err = c.modifyConfig(p, c.build, c.repo) if err != nil { return nil, _pipeline, err diff --git a/compiler/native/native.go b/compiler/native/native.go index 0c83b0728..ec6d78366 100644 --- a/compiler/native/native.go +++ b/compiler/native/native.go @@ -88,7 +88,7 @@ func FromCLIContext(ctx *cli.Context) (*client, error) { c.SetTemplateDepth(ctx.Int("max-template-depth")) // set the starlark execution step limit for compiling starlark pipelines - c.SetStarlarkExecLimit(ctx.Uint64("compiler-starlark-exec-limit")) + c.SetStarlarkExecLimit(ctx.Int64("compiler-starlark-exec-limit")) if ctx.Bool("github-driver") { logrus.Tracef("setting up Private GitHub Client for %s", ctx.String("github-url")) diff --git a/compiler/registry/github/template.go b/compiler/registry/github/template.go index cd3dfc75f..44bc0d1e8 100644 --- a/compiler/registry/github/template.go +++ b/compiler/registry/github/template.go @@ -34,9 +34,7 @@ func (c *client) Template(ctx context.Context, u *api.User, s *registry.Source) } // send API call to capture the templated pipeline configuration - // - - data, _, resp, err := cli.Repositories.GetContents(context.Background(), s.Org, s.Repo, s.Name, opts) + data, _, resp, err := cli.Repositories.GetContents(ctx, s.Org, s.Repo, s.Name, opts) if err != nil { if resp != nil && resp.StatusCode != http.StatusNotFound { // return different error message depending on if a branch was provided diff --git a/compiler/template/starlark/render.go b/compiler/template/starlark/render.go index 325e49c53..edd822463 100644 --- a/compiler/template/starlark/render.go +++ b/compiler/template/starlark/render.go @@ -10,6 +10,7 @@ import ( yaml "github.com/buildkite/yaml" "go.starlark.net/starlark" "go.starlark.net/starlarkstruct" + "go.starlark.net/syntax" "github.com/go-vela/server/compiler/types/raw" types "github.com/go-vela/server/compiler/types/yaml" @@ -30,19 +31,20 @@ var ( ) // Render combines the template with the step in the yaml pipeline. -func Render(tmpl string, name string, tName string, environment raw.StringSliceMap, variables map[string]interface{}, limit uint64) (*types.Build, error) { +func Render(tmpl string, name string, tName string, environment raw.StringSliceMap, variables map[string]interface{}, limit int64) (*types.Build, error) { config := new(types.Build) thread := &starlark.Thread{Name: name} - // arbitrarily limiting the steps of the thread to 5000 to help prevent infinite loops - // may need to further investigate spawning a separate POSIX process if user input is problematic - // see https://github.com/google/starlark-go/issues/160#issuecomment-466794230 for further details - thread.SetMaxExecutionSteps(limit) - predeclared := starlark.StringDict{"struct": starlark.NewBuiltin("struct", starlarkstruct.Make)} + if limit < 0 { + return nil, fmt.Errorf("starlark exec limit must be non-negative") + } - globals, err := starlark.ExecFile(thread, tName, tmpl, predeclared) + thread.SetMaxExecutionSteps(uint64(limit)) + + predeclared := starlark.StringDict{"struct": starlark.NewBuiltin("struct", starlarkstruct.Make)} + globals, err := starlark.ExecFileOptions(syntax.LegacyFileOptions(), thread, "templated-base", tmpl, predeclared) if err != nil { return nil, err } @@ -138,18 +140,20 @@ func Render(tmpl string, name string, tName string, environment raw.StringSliceM // RenderBuild renders the templated build. // //nolint:lll // ignore function length due to input args -func RenderBuild(tmpl string, b string, envs map[string]string, variables map[string]interface{}, limit uint64) (*types.Build, error) { +func RenderBuild(tmpl string, b string, envs map[string]string, variables map[string]interface{}, limit int64) (*types.Build, error) { config := new(types.Build) thread := &starlark.Thread{Name: "templated-base"} - // arbitrarily limiting the steps of the thread to 5000 to help prevent infinite loops - // may need to further investigate spawning a separate POSIX process if user input is problematic - // see https://github.com/google/starlark-go/issues/160#issuecomment-466794230 for further details - thread.SetMaxExecutionSteps(limit) + + if limit < 0 { + return nil, fmt.Errorf("starlark exec limit must be non-negative") + } + + thread.SetMaxExecutionSteps(uint64(limit)) predeclared := starlark.StringDict{"struct": starlark.NewBuiltin("struct", starlarkstruct.Make)} - globals, err := starlark.ExecFile(thread, "templated-base", b, predeclared) + globals, err := starlark.ExecFileOptions(syntax.LegacyFileOptions(), thread, "templated-base", b, predeclared) if err != nil { return nil, err } diff --git a/compiler/template/starlark/render_test.go b/compiler/template/starlark/render_test.go index 2f34e88f0..33db5a7f0 100644 --- a/compiler/template/starlark/render_test.go +++ b/compiler/template/starlark/render_test.go @@ -142,7 +142,7 @@ func TestNative_RenderBuild(t *testing.T) { args args wantFile string wantErr bool - execLimit uint64 + execLimit int64 }{ { name: "steps", diff --git a/compiler/template/starlark/starlark.go b/compiler/template/starlark/starlark.go index 98b9a2c64..954c7df96 100644 --- a/compiler/template/starlark/starlark.go +++ b/compiler/template/starlark/starlark.go @@ -127,6 +127,7 @@ func toStarlark(value interface{}) (starlark.Value, error) { } var m map[string]interface{} + err = json.Unmarshal(data, &m) if err != nil { return nil, err diff --git a/compiler/types/pipeline/ruleset.go b/compiler/types/pipeline/ruleset.go index 36d6c1302..a830ba6ff 100644 --- a/compiler/types/pipeline/ruleset.go +++ b/compiler/types/pipeline/ruleset.go @@ -135,15 +135,9 @@ func (r *Rules) Empty() bool { // both operators, when none of the ruletypes from the rules // match the provided ruledata, the function returns false. func (r *Rules) Match(from *RuleData, matcher, op string) (bool, error) { - status := true - - var err error - - if len(from.Status) != 0 { - status, err = r.Status.MatchSingle(from.Status, matcher, op) - if err != nil { - return false, err - } + status, err := r.matchStatus(from, matcher, op) + if err != nil { + return false, err } matchBranch, err := r.Branch.MatchSingle(from.Branch, matcher, op) @@ -196,11 +190,35 @@ func (r *Rules) Match(from *RuleData, matcher, op string) (bool, error) { return false, err } + return r.evaluateMatches(op, status, matchBranch, matchComment, matchEvent, matchPath, matchRepo, matchSender, matchTag, matchTarget, matchLabel, matchInstance), nil +} + +func (r *Rules) matchStatus(from *RuleData, matcher, op string) (bool, error) { + if len(from.Status) == 0 { + return true, nil + } + + return r.Status.MatchSingle(from.Status, matcher, op) +} + +func (r *Rules) evaluateMatches(op string, matches ...bool) bool { switch op { case constants.OperatorOr: - return (matchBranch || matchComment || matchEvent || matchPath || matchRepo || matchSender || matchTag || matchTarget || matchLabel || matchInstance || status), nil + for _, match := range matches { + if match { + return true + } + } + + return false default: - return (matchBranch && matchComment && matchEvent && matchPath && matchRepo && matchSender && matchTag && matchTarget && matchLabel && matchInstance && status), nil + for _, match := range matches { + if !match { + return false + } + } + + return true } } diff --git a/compiler/types/yaml/service.go b/compiler/types/yaml/service.go index 3d08e8cba..a727cc32e 100644 --- a/compiler/types/yaml/service.go +++ b/compiler/types/yaml/service.go @@ -56,8 +56,6 @@ func (s *ServiceSlice) ToPipeline() *pipeline.ContainerSlice { } // UnmarshalYAML implements the Unmarshaler interface for the ServiceSlice type. -// -//nolint:dupl // accepting duplicative code that exists in step.go as well func (s *ServiceSlice) UnmarshalYAML(unmarshal func(interface{}) error) error { // service slice we try unmarshalling to serviceSlice := new([]*Service) diff --git a/compiler/types/yaml/stage.go b/compiler/types/yaml/stage.go index f62ce6353..93bc8c8ca 100644 --- a/compiler/types/yaml/stage.go +++ b/compiler/types/yaml/stage.go @@ -88,12 +88,14 @@ func (s *StageSlice) UnmarshalYAML(unmarshal func(interface{}) error) error { return needs } } + return append(needs, "clone") }(stage.Needs) } // append stage to stage slice *s = append(*s, stage) } + return nil } diff --git a/compiler/types/yaml/step.go b/compiler/types/yaml/step.go index ea583fe95..405e6d598 100644 --- a/compiler/types/yaml/step.go +++ b/compiler/types/yaml/step.go @@ -71,8 +71,6 @@ func (s *StepSlice) ToPipeline() *pipeline.ContainerSlice { } // UnmarshalYAML implements the Unmarshaler interface for the StepSlice type. -// -//nolint:dupl // accepting duplicative code that exits in service.go as well func (s *StepSlice) UnmarshalYAML(unmarshal func(interface{}) error) error { // step slice we try unmarshalling to stepSlice := new([]*Step) diff --git a/constants/errors.go b/constants/errors.go new file mode 100644 index 000000000..d0e142df7 --- /dev/null +++ b/constants/errors.go @@ -0,0 +1,12 @@ +// SPDX-License-Identifier: Apache-2.0 + +package constants + +// Error messages for the Vela API. +const ( + // ErrorEmptyDuration defines the error message for a duration calculation without a started value. + ErrorEmptyDuration = "..." + + // ErrorMock defines the error message returned by mock API functions. + ErrorMock = "error" +) diff --git a/database/build/create.go b/database/build/create.go index d8f122470..63e5509a1 100644 --- a/database/build/create.go +++ b/database/build/create.go @@ -1,6 +1,5 @@ // SPDX-License-Identifier: Apache-2.0 -//nolint:dupl // ignore similar code with update.go package build import ( diff --git a/database/build/update.go b/database/build/update.go index 2d838d9db..005855eda 100644 --- a/database/build/update.go +++ b/database/build/update.go @@ -1,6 +1,5 @@ // SPDX-License-Identifier: Apache-2.0 -//nolint:dupl // ignore similar code with create.go package build import ( diff --git a/database/log/create.go b/database/log/create.go index 98ec63beb..fc42ed748 100644 --- a/database/log/create.go +++ b/database/log/create.go @@ -1,6 +1,5 @@ // SPDX-License-Identifier: Apache-2.0 -//nolint:dupl // ignore similar code with create.go package log import ( diff --git a/database/log/get_service.go b/database/log/get_service.go index f760af06e..92c9ec3d7 100644 --- a/database/log/get_service.go +++ b/database/log/get_service.go @@ -1,6 +1,5 @@ // SPDX-License-Identifier: Apache-2.0 -//nolint:dupl // ignore similar code with get_step.go package log import ( diff --git a/database/log/get_step.go b/database/log/get_step.go index ff92bac10..a6ed23659 100644 --- a/database/log/get_step.go +++ b/database/log/get_step.go @@ -1,6 +1,5 @@ // SPDX-License-Identifier: Apache-2.0 -//nolint:dupl // ignore similar code with get_service.go package log import ( diff --git a/database/log/update.go b/database/log/update.go index 0854a9c2d..b2ae9ce0d 100644 --- a/database/log/update.go +++ b/database/log/update.go @@ -1,6 +1,5 @@ // SPDX-License-Identifier: Apache-2.0 -//nolint:dupl // ignore similar code with update.go package log import ( diff --git a/database/repo/create.go b/database/repo/create.go index 2768a72be..2dec53bfa 100644 --- a/database/repo/create.go +++ b/database/repo/create.go @@ -1,6 +1,5 @@ // SPDX-License-Identifier: Apache-2.0 -//nolint:dupl // ignore similar code with update.go package repo import ( diff --git a/database/repo/update.go b/database/repo/update.go index 8168bf404..ddcaac2bd 100644 --- a/database/repo/update.go +++ b/database/repo/update.go @@ -1,6 +1,5 @@ // SPDX-License-Identifier: Apache-2.0 -//nolint:dupl // ignore similar code with create.go package repo import ( diff --git a/database/resource.go b/database/resource.go index 43e659fd9..ecdf8731b 100644 --- a/database/resource.go +++ b/database/resource.go @@ -31,7 +31,7 @@ func (e *engine) NewResources(ctx context.Context) error { // create the database agnostic engine for settings e.SettingsInterface, err = settings.New( - settings.WithContext(e.ctx), + settings.WithContext(ctx), settings.WithClient(e.client), settings.WithLogger(e.logger), settings.WithSkipCreation(e.config.SkipCreation), @@ -42,7 +42,7 @@ func (e *engine) NewResources(ctx context.Context) error { // create the database agnostic engine for builds e.BuildInterface, err = build.New( - build.WithContext(e.ctx), + build.WithContext(ctx), build.WithClient(e.client), build.WithLogger(e.logger), build.WithSkipCreation(e.config.SkipCreation), @@ -53,7 +53,7 @@ func (e *engine) NewResources(ctx context.Context) error { } e.DashboardInterface, err = dashboard.New( - dashboard.WithContext(e.ctx), + dashboard.WithContext(ctx), dashboard.WithClient(e.client), dashboard.WithLogger(e.logger), dashboard.WithSkipCreation(e.config.SkipCreation), @@ -64,7 +64,7 @@ func (e *engine) NewResources(ctx context.Context) error { // create the database agnostic engine for build_executables e.BuildExecutableInterface, err = executable.New( - executable.WithContext(e.ctx), + executable.WithContext(ctx), executable.WithClient(e.client), executable.WithLogger(e.logger), executable.WithSkipCreation(e.config.SkipCreation), @@ -77,7 +77,7 @@ func (e *engine) NewResources(ctx context.Context) error { // create the database agnostic engine for deployments e.DeploymentInterface, err = deployment.New( - deployment.WithContext(e.ctx), + deployment.WithContext(ctx), deployment.WithClient(e.client), deployment.WithLogger(e.logger), deployment.WithSkipCreation(e.config.SkipCreation), @@ -89,7 +89,7 @@ func (e *engine) NewResources(ctx context.Context) error { // create the database agnostic engine for hooks e.HookInterface, err = hook.New( - hook.WithContext(e.ctx), + hook.WithContext(ctx), hook.WithClient(e.client), hook.WithLogger(e.logger), hook.WithEncryptionKey(e.config.EncryptionKey), @@ -101,7 +101,7 @@ func (e *engine) NewResources(ctx context.Context) error { // create the database agnostic engine for JWKs e.JWKInterface, err = jwk.New( - jwk.WithContext(e.ctx), + jwk.WithContext(ctx), jwk.WithClient(e.client), jwk.WithLogger(e.logger), jwk.WithSkipCreation(e.config.SkipCreation), @@ -112,7 +112,7 @@ func (e *engine) NewResources(ctx context.Context) error { // create the database agnostic engine for logs e.LogInterface, err = log.New( - log.WithContext(e.ctx), + log.WithContext(ctx), log.WithClient(e.client), log.WithCompressionLevel(e.config.CompressionLevel), log.WithLogger(e.logger), @@ -124,7 +124,7 @@ func (e *engine) NewResources(ctx context.Context) error { // create the database agnostic engine for pipelines e.PipelineInterface, err = pipeline.New( - pipeline.WithContext(e.ctx), + pipeline.WithContext(ctx), pipeline.WithClient(e.client), pipeline.WithCompressionLevel(e.config.CompressionLevel), pipeline.WithEncryptionKey(e.config.EncryptionKey), @@ -137,7 +137,7 @@ func (e *engine) NewResources(ctx context.Context) error { // create the database agnostic engine for repos e.RepoInterface, err = repo.New( - repo.WithContext(e.ctx), + repo.WithContext(ctx), repo.WithClient(e.client), repo.WithEncryptionKey(e.config.EncryptionKey), repo.WithLogger(e.logger), @@ -149,7 +149,7 @@ func (e *engine) NewResources(ctx context.Context) error { // create the database agnostic engine for schedules e.ScheduleInterface, err = schedule.New( - schedule.WithContext(e.ctx), + schedule.WithContext(ctx), schedule.WithClient(e.client), schedule.WithEncryptionKey(e.config.EncryptionKey), schedule.WithLogger(e.logger), @@ -163,7 +163,7 @@ func (e *engine) NewResources(ctx context.Context) error { // // https://pkg.go.dev/github.com/go-vela/server/database/secret#New e.SecretInterface, err = secret.New( - secret.WithContext(e.ctx), + secret.WithContext(ctx), secret.WithClient(e.client), secret.WithEncryptionKey(e.config.EncryptionKey), secret.WithLogger(e.logger), @@ -185,7 +185,7 @@ func (e *engine) NewResources(ctx context.Context) error { // create the database agnostic engine for steps e.StepInterface, err = step.New( - step.WithContext(e.ctx), + step.WithContext(ctx), step.WithClient(e.client), step.WithLogger(e.logger), step.WithSkipCreation(e.config.SkipCreation), @@ -196,7 +196,7 @@ func (e *engine) NewResources(ctx context.Context) error { // create the database agnostic engine for users e.UserInterface, err = user.New( - user.WithContext(e.ctx), + user.WithContext(ctx), user.WithClient(e.client), user.WithEncryptionKey(e.config.EncryptionKey), user.WithLogger(e.logger), @@ -208,7 +208,7 @@ func (e *engine) NewResources(ctx context.Context) error { // create the database agnostic engine for workers e.WorkerInterface, err = worker.New( - worker.WithContext(e.ctx), + worker.WithContext(ctx), worker.WithClient(e.client), worker.WithLogger(e.logger), worker.WithSkipCreation(e.config.SkipCreation), diff --git a/database/secret/create.go b/database/secret/create.go index c0ac65dc7..74e8bae53 100644 --- a/database/secret/create.go +++ b/database/secret/create.go @@ -1,6 +1,5 @@ // SPDX-License-Identifier: Apache-2.0 -//nolint:dupl // ignore similar code with update.go package secret import ( diff --git a/database/secret/update.go b/database/secret/update.go index d512e7e33..8ab516ba8 100644 --- a/database/secret/update.go +++ b/database/secret/update.go @@ -1,6 +1,5 @@ // SPDX-License-Identifier: Apache-2.0 -//nolint:dupl // ignore similar code with create.go package secret import ( diff --git a/database/types/build.go b/database/types/build.go index 43471e34e..f3aa22cd3 100644 --- a/database/types/build.go +++ b/database/types/build.go @@ -35,8 +35,8 @@ type Build struct { ID sql.NullInt64 `sql:"id"` RepoID sql.NullInt64 `sql:"repo_id"` PipelineID sql.NullInt64 `sql:"pipeline_id"` - Number sql.NullInt32 `sql:"number"` - Parent sql.NullInt32 `sql:"parent"` + Number sql.NullInt64 `sql:"number"` + Parent sql.NullInt64 `sql:"parent"` Event sql.NullString `sql:"event"` EventAction sql.NullString `sql:"event_action"` Status sql.NullString `sql:"status"` @@ -121,12 +121,12 @@ func (b *Build) Nullify() *Build { } // check if the Number field should be false - if b.Number.Int32 == 0 { + if b.Number.Int64 == 0 { b.Number.Valid = false } // check if the Parent field should be false - if b.Parent.Int32 == 0 { + if b.Parent.Int64 == 0 { b.Parent.Valid = false } @@ -295,8 +295,8 @@ func (b *Build) ToAPI() *api.Build { build.SetID(b.ID.Int64) build.SetRepo(repo) build.SetPipelineID(b.PipelineID.Int64) - build.SetNumber(int(b.Number.Int32)) - build.SetParent(int(b.Parent.Int32)) + build.SetNumber(int(b.Number.Int64)) + build.SetParent(int(b.Parent.Int64)) build.SetEvent(b.Event.String) build.SetEventAction(b.EventAction.String) build.SetStatus(b.Status.String) @@ -340,7 +340,7 @@ func (b *Build) Validate() error { } // verify the Number field is populated - if b.Number.Int32 <= 0 { + if b.Number.Int64 <= 0 { return ErrEmptyBuildNumber } @@ -381,8 +381,8 @@ func BuildFromAPI(b *api.Build) *Build { ID: sql.NullInt64{Int64: b.GetID(), Valid: true}, RepoID: sql.NullInt64{Int64: b.GetRepo().GetID(), Valid: true}, PipelineID: sql.NullInt64{Int64: b.GetPipelineID(), Valid: true}, - Number: sql.NullInt32{Int32: int32(b.GetNumber()), Valid: true}, - Parent: sql.NullInt32{Int32: int32(b.GetParent()), Valid: true}, + Number: sql.NullInt64{Int64: int64(b.GetNumber()), Valid: true}, + Parent: sql.NullInt64{Int64: int64(b.GetParent()), Valid: true}, Event: sql.NullString{String: b.GetEvent(), Valid: true}, EventAction: sql.NullString{String: b.GetEventAction(), Valid: true}, Status: sql.NullString{String: b.GetStatus(), Valid: true}, diff --git a/database/types/build_test.go b/database/types/build_test.go index 84cababf8..372e09fc4 100644 --- a/database/types/build_test.go +++ b/database/types/build_test.go @@ -47,8 +47,8 @@ func TestTypes_Build_Nullify(t *testing.T) { ID: sql.NullInt64{Int64: 0, Valid: false}, RepoID: sql.NullInt64{Int64: 0, Valid: false}, PipelineID: sql.NullInt64{Int64: 0, Valid: false}, - Number: sql.NullInt32{Int32: 0, Valid: false}, - Parent: sql.NullInt32{Int32: 0, Valid: false}, + Number: sql.NullInt64{Int64: 0, Valid: false}, + Parent: sql.NullInt64{Int64: 0, Valid: false}, Event: sql.NullString{String: "", Valid: false}, EventAction: sql.NullString{String: "", Valid: false}, Status: sql.NullString{String: "", Valid: false}, @@ -170,7 +170,7 @@ func TestTypes_Build_Validate(t *testing.T) { failure: true, build: &Build{ ID: sql.NullInt64{Int64: 1, Valid: true}, - Number: sql.NullInt32{Int32: 1, Valid: true}, + Number: sql.NullInt64{Int64: 1, Valid: true}, }, }, { // no number set for build @@ -274,8 +274,8 @@ func testBuild() *Build { ID: sql.NullInt64{Int64: 1, Valid: true}, RepoID: sql.NullInt64{Int64: 1, Valid: true}, PipelineID: sql.NullInt64{Int64: 1, Valid: true}, - Number: sql.NullInt32{Int32: 1, Valid: true}, - Parent: sql.NullInt32{Int32: 1, Valid: true}, + Number: sql.NullInt64{Int64: 1, Valid: true}, + Parent: sql.NullInt64{Int64: 1, Valid: true}, Event: sql.NullString{String: "push", Valid: true}, EventAction: sql.NullString{String: "", Valid: false}, Status: sql.NullString{String: "running", Valid: true}, diff --git a/database/types/repo.go b/database/types/repo.go index d769f0c52..96f45caf9 100644 --- a/database/types/repo.go +++ b/database/types/repo.go @@ -58,7 +58,7 @@ type Repo struct { Topics pq.StringArray `sql:"topics" gorm:"type:varchar(1020)"` BuildLimit sql.NullInt64 `sql:"build_limit"` Timeout sql.NullInt64 `sql:"timeout"` - Counter sql.NullInt32 `sql:"counter"` + Counter sql.NullInt64 `sql:"counter"` Visibility sql.NullString `sql:"visibility"` Private sql.NullBool `sql:"private"` Trusted sql.NullBool `sql:"trusted"` @@ -241,7 +241,7 @@ func (r *Repo) ToAPI() *api.Repo { repo.SetTopics(r.Topics) repo.SetBuildLimit(r.BuildLimit.Int64) repo.SetTimeout(r.Timeout.Int64) - repo.SetCounter(int(r.Counter.Int32)) + repo.SetCounter(int(r.Counter.Int64)) repo.SetVisibility(r.Visibility.String) repo.SetPrivate(r.Private.Bool) repo.SetTrusted(r.Trusted.Bool) @@ -333,7 +333,7 @@ func RepoFromAPI(r *api.Repo) *Repo { Topics: pq.StringArray(r.GetTopics()), BuildLimit: sql.NullInt64{Int64: r.GetBuildLimit(), Valid: true}, Timeout: sql.NullInt64{Int64: r.GetTimeout(), Valid: true}, - Counter: sql.NullInt32{Int32: int32(r.GetCounter()), Valid: true}, + Counter: sql.NullInt64{Int64: int64(r.GetCounter()), Valid: true}, Visibility: sql.NullString{String: r.GetVisibility(), Valid: true}, Private: sql.NullBool{Bool: r.GetPrivate(), Valid: true}, Trusted: sql.NullBool{Bool: r.GetTrusted(), Valid: true}, diff --git a/database/types/repo_test.go b/database/types/repo_test.go index 949985490..c9a8b6afd 100644 --- a/database/types/repo_test.go +++ b/database/types/repo_test.go @@ -373,7 +373,7 @@ func testRepo() *Repo { Topics: []string{"cloud", "security"}, BuildLimit: sql.NullInt64{Int64: 10, Valid: true}, Timeout: sql.NullInt64{Int64: 30, Valid: true}, - Counter: sql.NullInt32{Int32: 0, Valid: true}, + Counter: sql.NullInt64{Int64: 0, Valid: true}, Visibility: sql.NullString{String: "public", Valid: true}, Private: sql.NullBool{Bool: false, Valid: true}, Trusted: sql.NullBool{Bool: false, Valid: true}, diff --git a/database/types/service.go b/database/types/service.go index f3b508ed6..4d7ea46c5 100644 --- a/database/types/service.go +++ b/database/types/service.go @@ -37,12 +37,12 @@ type Service struct { ID sql.NullInt64 `sql:"id"` BuildID sql.NullInt64 `sql:"build_id"` RepoID sql.NullInt64 `sql:"repo_id"` - Number sql.NullInt32 `sql:"number"` + Number sql.NullInt64 `sql:"number"` Name sql.NullString `sql:"name"` Image sql.NullString `sql:"image"` Status sql.NullString `sql:"status"` Error sql.NullString `sql:"error"` - ExitCode sql.NullInt32 `sql:"exit_code"` + ExitCode sql.NullInt64 `sql:"exit_code"` Created sql.NullInt64 `sql:"created"` Started sql.NullInt64 `sql:"started"` Finished sql.NullInt64 `sql:"finished"` @@ -78,7 +78,7 @@ func (s *Service) Nullify() *Service { } // check if the Number field should be false - if s.Number.Int32 == 0 { + if s.Number.Int64 == 0 { s.Number.Valid = false } @@ -103,7 +103,7 @@ func (s *Service) Nullify() *Service { } // check if the ExitCode field should be false - if s.ExitCode.Int32 == 0 { + if s.ExitCode.Int64 == 0 { s.ExitCode.Valid = false } @@ -148,12 +148,12 @@ func (s *Service) ToAPI() *api.Service { service.SetID(s.ID.Int64) service.SetBuildID(s.BuildID.Int64) service.SetRepoID(s.RepoID.Int64) - service.SetNumber(int(s.Number.Int32)) + service.SetNumber(int(s.Number.Int64)) service.SetName(s.Name.String) service.SetImage(s.Image.String) service.SetStatus(s.Status.String) service.SetError(s.Error.String) - service.SetExitCode(int(s.ExitCode.Int32)) + service.SetExitCode(int(s.ExitCode.Int64)) service.SetCreated(s.Created.Int64) service.SetStarted(s.Started.Int64) service.SetFinished(s.Finished.Int64) @@ -178,7 +178,7 @@ func (s *Service) Validate() error { } // verify the Number field is populated - if s.Number.Int32 <= 0 { + if s.Number.Int64 <= 0 { return ErrEmptyServiceNumber } @@ -213,12 +213,12 @@ func ServiceFromAPI(s *api.Service) *Service { ID: sql.NullInt64{Int64: s.GetID(), Valid: true}, BuildID: sql.NullInt64{Int64: s.GetBuildID(), Valid: true}, RepoID: sql.NullInt64{Int64: s.GetRepoID(), Valid: true}, - Number: sql.NullInt32{Int32: int32(s.GetNumber()), Valid: true}, + Number: sql.NullInt64{Int64: int64(s.GetNumber()), Valid: true}, Name: sql.NullString{String: s.GetName(), Valid: true}, Image: sql.NullString{String: s.GetImage(), Valid: true}, Status: sql.NullString{String: s.GetStatus(), Valid: true}, Error: sql.NullString{String: s.GetError(), Valid: true}, - ExitCode: sql.NullInt32{Int32: int32(s.GetExitCode()), Valid: true}, + ExitCode: sql.NullInt64{Int64: int64(s.GetExitCode()), Valid: true}, Created: sql.NullInt64{Int64: s.GetCreated(), Valid: true}, Started: sql.NullInt64{Int64: s.GetStarted(), Valid: true}, Finished: sql.NullInt64{Int64: s.GetFinished(), Valid: true}, diff --git a/database/types/service_test.go b/database/types/service_test.go index ce39d90db..518b9ddb5 100644 --- a/database/types/service_test.go +++ b/database/types/service_test.go @@ -18,12 +18,12 @@ func TestDatabase_Service_Nullify(t *testing.T) { ID: sql.NullInt64{Int64: 0, Valid: false}, BuildID: sql.NullInt64{Int64: 0, Valid: false}, RepoID: sql.NullInt64{Int64: 0, Valid: false}, - Number: sql.NullInt32{Int32: 0, Valid: false}, + Number: sql.NullInt64{Int64: 0, Valid: false}, Name: sql.NullString{String: "", Valid: false}, Image: sql.NullString{String: "", Valid: false}, Status: sql.NullString{String: "", Valid: false}, Error: sql.NullString{String: "", Valid: false}, - ExitCode: sql.NullInt32{Int32: 0, Valid: false}, + ExitCode: sql.NullInt64{Int64: 0, Valid: false}, Created: sql.NullInt64{Int64: 0, Valid: false}, Started: sql.NullInt64{Int64: 0, Valid: false}, Finished: sql.NullInt64{Int64: 0, Valid: false}, @@ -103,7 +103,7 @@ func TestDatabase_Service_Validate(t *testing.T) { service: &Service{ ID: sql.NullInt64{Int64: 1, Valid: true}, RepoID: sql.NullInt64{Int64: 1, Valid: true}, - Number: sql.NullInt32{Int32: 1, Valid: true}, + Number: sql.NullInt64{Int64: 1, Valid: true}, Name: sql.NullString{String: "postgres", Valid: true}, Image: sql.NullString{String: "postgres:12-alpine", Valid: true}, }, @@ -113,7 +113,7 @@ func TestDatabase_Service_Validate(t *testing.T) { service: &Service{ ID: sql.NullInt64{Int64: 1, Valid: true}, BuildID: sql.NullInt64{Int64: 1, Valid: true}, - Number: sql.NullInt32{Int32: 1, Valid: true}, + Number: sql.NullInt64{Int64: 1, Valid: true}, Name: sql.NullString{String: "postgres", Valid: true}, Image: sql.NullString{String: "postgres:12-alpine", Valid: true}, }, @@ -134,7 +134,7 @@ func TestDatabase_Service_Validate(t *testing.T) { ID: sql.NullInt64{Int64: 1, Valid: true}, BuildID: sql.NullInt64{Int64: 1, Valid: true}, RepoID: sql.NullInt64{Int64: 1, Valid: true}, - Number: sql.NullInt32{Int32: 1, Valid: true}, + Number: sql.NullInt64{Int64: 1, Valid: true}, Image: sql.NullString{String: "postgres:12-alpine", Valid: true}, }, }, @@ -144,7 +144,7 @@ func TestDatabase_Service_Validate(t *testing.T) { ID: sql.NullInt64{Int64: 1, Valid: true}, BuildID: sql.NullInt64{Int64: 1, Valid: true}, RepoID: sql.NullInt64{Int64: 1, Valid: true}, - Number: sql.NullInt32{Int32: 1, Valid: true}, + Number: sql.NullInt64{Int64: 1, Valid: true}, Name: sql.NullString{String: "postgres", Valid: true}, }, }, @@ -205,12 +205,12 @@ func testService() *Service { ID: sql.NullInt64{Int64: 1, Valid: true}, BuildID: sql.NullInt64{Int64: 1, Valid: true}, RepoID: sql.NullInt64{Int64: 1, Valid: true}, - Number: sql.NullInt32{Int32: 1, Valid: true}, + Number: sql.NullInt64{Int64: 1, Valid: true}, Name: sql.NullString{String: "postgres", Valid: true}, Image: sql.NullString{String: "postgres:12-alpine", Valid: true}, Status: sql.NullString{String: "running", Valid: true}, Error: sql.NullString{String: "", Valid: false}, - ExitCode: sql.NullInt32{Int32: 0, Valid: false}, + ExitCode: sql.NullInt64{Int64: 0, Valid: false}, Created: sql.NullInt64{Int64: 1563474076, Valid: true}, Started: sql.NullInt64{Int64: 1563474078, Valid: true}, Finished: sql.NullInt64{Int64: 1563474079, Valid: true}, diff --git a/database/types/settings.go b/database/types/settings.go index 7bc29a6ca..637b1d17d 100644 --- a/database/types/settings.go +++ b/database/types/settings.go @@ -131,7 +131,7 @@ func (ps *Platform) ToAPI() *settings.Platform { psAPI.Compiler = &settings.Compiler{} psAPI.SetCloneImage(ps.CloneImage.String) psAPI.SetTemplateDepth(int(ps.TemplateDepth.Int64)) - psAPI.SetStarlarkExecLimit(uint64(ps.StarlarkExecLimit.Int64)) + psAPI.SetStarlarkExecLimit(ps.StarlarkExecLimit.Int64) psAPI.Queue = &settings.Queue{} psAPI.SetRoutes(ps.Routes) @@ -202,7 +202,7 @@ func SettingsFromAPI(s *settings.Platform) *Platform { Compiler: Compiler{ CloneImage: sql.NullString{String: s.GetCloneImage(), Valid: true}, TemplateDepth: sql.NullInt64{Int64: int64(s.GetTemplateDepth()), Valid: true}, - StarlarkExecLimit: sql.NullInt64{Int64: int64(s.GetStarlarkExecLimit()), Valid: true}, + StarlarkExecLimit: sql.NullInt64{Int64: s.GetStarlarkExecLimit(), Valid: true}, }, Queue: Queue{ Routes: pq.StringArray(s.GetRoutes()), diff --git a/database/types/step.go b/database/types/step.go index 4bd09c0b5..1ce8ab6d9 100644 --- a/database/types/step.go +++ b/database/types/step.go @@ -37,13 +37,13 @@ type Step struct { ID sql.NullInt64 `sql:"id"` BuildID sql.NullInt64 `sql:"build_id"` RepoID sql.NullInt64 `sql:"repo_id"` - Number sql.NullInt32 `sql:"number"` + Number sql.NullInt64 `sql:"number"` Name sql.NullString `sql:"name"` Image sql.NullString `sql:"image"` Stage sql.NullString `sql:"stage"` Status sql.NullString `sql:"status"` Error sql.NullString `sql:"error"` - ExitCode sql.NullInt32 `sql:"exit_code"` + ExitCode sql.NullInt64 `sql:"exit_code"` Created sql.NullInt64 `sql:"created"` Started sql.NullInt64 `sql:"started"` Finished sql.NullInt64 `sql:"finished"` @@ -80,7 +80,7 @@ func (s *Step) Nullify() *Step { } // check if the Number field should be false - if s.Number.Int32 == 0 { + if s.Number.Int64 == 0 { s.Number.Valid = false } @@ -110,7 +110,7 @@ func (s *Step) Nullify() *Step { } // check if the ExitCode field should be false - if s.ExitCode.Int32 == 0 { + if s.ExitCode.Int64 == 0 { s.ExitCode.Valid = false } @@ -160,13 +160,13 @@ func (s *Step) ToAPI() *api.Step { step.SetID(s.ID.Int64) step.SetBuildID(s.BuildID.Int64) step.SetRepoID(s.RepoID.Int64) - step.SetNumber(int(s.Number.Int32)) + step.SetNumber(int(s.Number.Int64)) step.SetName(s.Name.String) step.SetImage(s.Image.String) step.SetStage(s.Stage.String) step.SetStatus(s.Status.String) step.SetError(s.Error.String) - step.SetExitCode(int(s.ExitCode.Int32)) + step.SetExitCode(int(s.ExitCode.Int64)) step.SetCreated(s.Created.Int64) step.SetStarted(s.Started.Int64) step.SetFinished(s.Finished.Int64) @@ -192,7 +192,7 @@ func (s *Step) Validate() error { } // verify the Number field is populated - if s.Number.Int32 <= 0 { + if s.Number.Int64 <= 0 { return ErrEmptyStepNumber } @@ -229,13 +229,13 @@ func StepFromAPI(s *api.Step) *Step { ID: sql.NullInt64{Int64: s.GetID(), Valid: true}, BuildID: sql.NullInt64{Int64: s.GetBuildID(), Valid: true}, RepoID: sql.NullInt64{Int64: s.GetRepoID(), Valid: true}, - Number: sql.NullInt32{Int32: int32(s.GetNumber()), Valid: true}, + Number: sql.NullInt64{Int64: int64(s.GetNumber()), Valid: true}, Name: sql.NullString{String: s.GetName(), Valid: true}, Image: sql.NullString{String: s.GetImage(), Valid: true}, Stage: sql.NullString{String: s.GetStage(), Valid: true}, Status: sql.NullString{String: s.GetStatus(), Valid: true}, Error: sql.NullString{String: s.GetError(), Valid: true}, - ExitCode: sql.NullInt32{Int32: int32(s.GetExitCode()), Valid: true}, + ExitCode: sql.NullInt64{Int64: int64(s.GetExitCode()), Valid: true}, Created: sql.NullInt64{Int64: s.GetCreated(), Valid: true}, Started: sql.NullInt64{Int64: s.GetStarted(), Valid: true}, Finished: sql.NullInt64{Int64: s.GetFinished(), Valid: true}, diff --git a/database/types/step_test.go b/database/types/step_test.go index d2614effe..cc27030ca 100644 --- a/database/types/step_test.go +++ b/database/types/step_test.go @@ -18,13 +18,13 @@ func TestDatabase_Step_Nullify(t *testing.T) { ID: sql.NullInt64{Int64: 0, Valid: false}, BuildID: sql.NullInt64{Int64: 0, Valid: false}, RepoID: sql.NullInt64{Int64: 0, Valid: false}, - Number: sql.NullInt32{Int32: 0, Valid: false}, + Number: sql.NullInt64{Int64: 0, Valid: false}, Name: sql.NullString{String: "", Valid: false}, Image: sql.NullString{String: "", Valid: false}, Stage: sql.NullString{String: "", Valid: false}, Status: sql.NullString{String: "", Valid: false}, Error: sql.NullString{String: "", Valid: false}, - ExitCode: sql.NullInt32{Int32: 0, Valid: false}, + ExitCode: sql.NullInt64{Int64: 0, Valid: false}, Created: sql.NullInt64{Int64: 0, Valid: false}, Started: sql.NullInt64{Int64: 0, Valid: false}, Finished: sql.NullInt64{Int64: 0, Valid: false}, @@ -108,7 +108,7 @@ func TestDatabase_Step_Validate(t *testing.T) { step: &Step{ ID: sql.NullInt64{Int64: 1, Valid: true}, RepoID: sql.NullInt64{Int64: 1, Valid: true}, - Number: sql.NullInt32{Int32: 1, Valid: true}, + Number: sql.NullInt64{Int64: 1, Valid: true}, Name: sql.NullString{String: "clone", Valid: true}, Image: sql.NullString{String: "target/vela-git:v0.3.0", Valid: true}, }, @@ -118,7 +118,7 @@ func TestDatabase_Step_Validate(t *testing.T) { step: &Step{ ID: sql.NullInt64{Int64: 1, Valid: true}, BuildID: sql.NullInt64{Int64: 1, Valid: true}, - Number: sql.NullInt32{Int32: 1, Valid: true}, + Number: sql.NullInt64{Int64: 1, Valid: true}, Name: sql.NullString{String: "clone", Valid: true}, Image: sql.NullString{String: "target/vela-git:v0.3.0", Valid: true}, }, @@ -129,7 +129,7 @@ func TestDatabase_Step_Validate(t *testing.T) { ID: sql.NullInt64{Int64: 1, Valid: true}, BuildID: sql.NullInt64{Int64: 1, Valid: true}, RepoID: sql.NullInt64{Int64: 1, Valid: true}, - Number: sql.NullInt32{Int32: 1, Valid: true}, + Number: sql.NullInt64{Int64: 1, Valid: true}, Image: sql.NullString{String: "target/vela-git:v0.3.0", Valid: true}, }, }, @@ -149,7 +149,7 @@ func TestDatabase_Step_Validate(t *testing.T) { ID: sql.NullInt64{Int64: 1, Valid: true}, BuildID: sql.NullInt64{Int64: 1, Valid: true}, RepoID: sql.NullInt64{Int64: 1, Valid: true}, - Number: sql.NullInt32{Int32: 1, Valid: true}, + Number: sql.NullInt64{Int64: 1, Valid: true}, Name: sql.NullString{String: "clone", Valid: true}, }, }, @@ -212,13 +212,13 @@ func testStep() *Step { ID: sql.NullInt64{Int64: 1, Valid: true}, BuildID: sql.NullInt64{Int64: 1, Valid: true}, RepoID: sql.NullInt64{Int64: 1, Valid: true}, - Number: sql.NullInt32{Int32: 1, Valid: true}, + Number: sql.NullInt64{Int64: 1, Valid: true}, Name: sql.NullString{String: "clone", Valid: true}, Image: sql.NullString{String: "target/vela-git:v0.3.0", Valid: true}, Stage: sql.NullString{String: "", Valid: false}, Status: sql.NullString{String: "running", Valid: true}, Error: sql.NullString{String: "", Valid: false}, - ExitCode: sql.NullInt32{Int32: 0, Valid: false}, + ExitCode: sql.NullInt64{Int64: 0, Valid: false}, Created: sql.NullInt64{Int64: 1563474076, Valid: true}, Started: sql.NullInt64{Int64: 1563474078, Valid: true}, Finished: sql.NullInt64{Int64: 1563474079, Valid: true}, diff --git a/database/user/create.go b/database/user/create.go index ce2162d96..924a6f5f2 100644 --- a/database/user/create.go +++ b/database/user/create.go @@ -1,6 +1,5 @@ // SPDX-License-Identifier: Apache-2.0 -//nolint:dupl // ignore similar code in update.go package user import ( diff --git a/database/user/update.go b/database/user/update.go index bd8850502..10c3cc02f 100644 --- a/database/user/update.go +++ b/database/user/update.go @@ -1,6 +1,5 @@ // SPDX-License-Identifier: Apache-2.0 -//nolint:dupl // ignore similar code in create.go package user import ( diff --git a/internal/token/generate_rsa.go b/internal/token/generate_rsa.go index 483f0074f..3bb28b8f8 100644 --- a/internal/token/generate_rsa.go +++ b/internal/token/generate_rsa.go @@ -42,7 +42,7 @@ func (tm *Manager) GenerateRSA(ctx context.Context, db database.Interface) error } // create the JWK in the database - err = db.CreateJWK(context.TODO(), j) + err = db.CreateJWK(ctx, j) if err != nil { return err } diff --git a/mock/server/authentication.go b/mock/server/authentication.go index 8d940934e..2d9b87fbb 100644 --- a/mock/server/authentication.go +++ b/mock/server/authentication.go @@ -79,7 +79,7 @@ func getAuthenticate(c *gin.Context) { state := c.Request.FormValue("state") code := c.Request.FormValue("code") - err := "error" + err := constants.ErrorMock if len(state) == 0 && len(code) == 0 { c.AbortWithStatusJSON(http.StatusUnauthorized, api.Error{Message: &err}) @@ -100,7 +100,7 @@ func getAuthenticate(c *gin.Context) { // Don't pass "Token" in header to receive an error message. func getAuthenticateFromToken(c *gin.Context) { data := []byte(TokenRefreshResp) - err := "error" + err := constants.ErrorMock token := c.Request.Header.Get("Token") if len(token) == 0 { @@ -117,7 +117,7 @@ func getAuthenticateFromToken(c *gin.Context) { // // Don't pass "Authorization" in header to receive an unauthorized error message. func validateToken(c *gin.Context) { - err := "error" + err := constants.ErrorMock token := c.Request.Header.Get("Authorization") if len(token) == 0 { @@ -131,7 +131,7 @@ func validateToken(c *gin.Context) { // // Don't pass "Authorization" in header to receive an unauthorized error message. func validateOAuthToken(c *gin.Context) { - err := "error" + err := constants.ErrorMock token := c.Request.Header.Get("Authorization") if len(token) == 0 { diff --git a/mock/server/hook.go b/mock/server/hook.go index 0721a8a8f..c239bf471 100644 --- a/mock/server/hook.go +++ b/mock/server/hook.go @@ -1,6 +1,5 @@ // SPDX-License-Identifier: Apache-2.0 -//nolint:dupl // ignore duplicate with user code package server import ( diff --git a/mock/server/secret.go b/mock/server/secret.go index 5410a4a75..72082cef1 100644 --- a/mock/server/secret.go +++ b/mock/server/secret.go @@ -1,6 +1,5 @@ // SPDX-License-Identifier: Apache-2.0 -//nolint:dupl // ignore duplicate with user code package server import ( diff --git a/mock/server/service.go b/mock/server/service.go index bd241bf73..24b685aec 100644 --- a/mock/server/service.go +++ b/mock/server/service.go @@ -1,6 +1,5 @@ // SPDX-License-Identifier: Apache-2.0 -//nolint:dupl // ignore duplicate with user code package server import ( diff --git a/mock/server/step.go b/mock/server/step.go index 9b4a67e3f..c2c26e88b 100644 --- a/mock/server/step.go +++ b/mock/server/step.go @@ -1,6 +1,5 @@ // SPDX-License-Identifier: Apache-2.0 -//nolint:dupl // ignore duplicate with user code package server import ( diff --git a/queue/redis/opts.go b/queue/redis/opts.go index f58dab06a..a417de06c 100644 --- a/queue/redis/opts.go +++ b/queue/redis/opts.go @@ -71,8 +71,6 @@ func WithTimeout(timeout time.Duration) ClientOpt { } // WithPrivateKey sets the private key in the queue client for Redis. -// -//nolint:dupl // ignore similar code func WithPrivateKey(key string) ClientOpt { return func(c *client) error { c.Logger.Trace("configuring private key in redis queue client") @@ -111,8 +109,6 @@ func WithPrivateKey(key string) ClientOpt { } // WithPublicKey sets the public key in the queue client for Redis. -// -//nolint:dupl // ignore similar code func WithPublicKey(key string) ClientOpt { return func(c *client) error { c.Logger.Tracef("configuring public key in redis queue client") diff --git a/router/middleware/logger.go b/router/middleware/logger.go index 2e6a518f8..d549b87b4 100644 --- a/router/middleware/logger.go +++ b/router/middleware/logger.go @@ -45,7 +45,7 @@ type ECSFormatter struct { // // It receives: // 1. A time package format string (e.g. time.RFC3339). -func Logger(logger *logrus.Logger, timeFormat string) gin.HandlerFunc { +func Logger(logger *logrus.Logger, _ string) gin.HandlerFunc { return func(c *gin.Context) { start := time.Now() // some evil middlewares modify this values diff --git a/router/middleware/perm/perm_test.go b/router/middleware/perm/perm_test.go index a39c3a1b2..dad92845f 100644 --- a/router/middleware/perm/perm_test.go +++ b/router/middleware/perm/perm_test.go @@ -444,11 +444,11 @@ func TestPerm_MustBuildAccess(t *testing.T) { defer func() { _ = db.DeleteBuild(ctx, b) - _ = db.DeleteRepo(_context.TODO(), r) + _ = db.DeleteRepo(ctx, r) db.Close() }() - _, _ = db.CreateRepo(_context.TODO(), r) + _, _ = db.CreateRepo(ctx, r) _, _ = db.CreateBuild(ctx, b) context.Request, _ = http.NewRequest(http.MethodGet, "/test/foo/bar/builds/1", nil) @@ -537,14 +537,14 @@ func TestPerm_MustBuildAccess_PlatAdmin(t *testing.T) { defer func() { _ = db.DeleteBuild(ctx, b) - _ = db.DeleteRepo(_context.TODO(), r) - _ = db.DeleteUser(_context.TODO(), u) + _ = db.DeleteRepo(ctx, r) + _ = db.DeleteUser(ctx, u) db.Close() }() - _, _ = db.CreateRepo(_context.TODO(), r) + _, _ = db.CreateRepo(ctx, r) _, _ = db.CreateBuild(ctx, b) - _, _ = db.CreateUser(_context.TODO(), u) + _, _ = db.CreateUser(ctx, u) context.Request, _ = http.NewRequest(http.MethodGet, "/test/foo/bar/builds/1", nil) context.Request.Header.Add("Authorization", fmt.Sprintf("Bearer %s", tok)) @@ -631,11 +631,11 @@ func TestPerm_MustBuildToken_WrongBuild(t *testing.T) { defer func() { _ = db.DeleteBuild(ctx, b) - _ = db.DeleteRepo(_context.TODO(), r) + _ = db.DeleteRepo(ctx, r) db.Close() }() - _, _ = db.CreateRepo(_context.TODO(), r) + _, _ = db.CreateRepo(ctx, r) _, _ = db.CreateBuild(ctx, b) context.Request, _ = http.NewRequest(http.MethodGet, "/test/foo/bar/builds/1", nil) @@ -725,11 +725,11 @@ func TestPerm_MustIDRequestToken(t *testing.T) { defer func() { _ = db.DeleteBuild(ctx, b) - _ = db.DeleteRepo(_context.TODO(), r) + _ = db.DeleteRepo(ctx, r) db.Close() }() - _, _ = db.CreateRepo(_context.TODO(), r) + _, _ = db.CreateRepo(ctx, r) _, _ = db.CreateBuild(ctx, b) context.Request, _ = http.NewRequest(http.MethodGet, "/test/foo/bar/builds/1", nil) @@ -822,14 +822,14 @@ func TestPerm_MustIDRequestToken_NotRunning(t *testing.T) { defer func() { _ = db.DeleteBuild(ctx, b) - _ = db.DeleteRepo(_context.TODO(), r) - _ = db.DeleteUser(_context.TODO(), u) + _ = db.DeleteRepo(ctx, r) + _ = db.DeleteUser(ctx, u) db.Close() }() - _, _ = db.CreateRepo(_context.TODO(), r) + _, _ = db.CreateRepo(ctx, r) _, _ = db.CreateBuild(ctx, b) - _, _ = db.CreateUser(_context.TODO(), u) + _, _ = db.CreateUser(ctx, u) context.Request, _ = http.NewRequest(http.MethodGet, "/test/foo/bar/builds/1", nil) context.Request.Header.Add("Authorization", fmt.Sprintf("Bearer %s", tok)) @@ -916,11 +916,11 @@ func TestPerm_MustIDRequestToken_WrongBuild(t *testing.T) { defer func() { _ = db.DeleteBuild(ctx, b) - _ = db.DeleteRepo(_context.TODO(), r) + _ = db.DeleteRepo(ctx, r) db.Close() }() - _, _ = db.CreateRepo(_context.TODO(), r) + _, _ = db.CreateRepo(ctx, r) _, _ = db.CreateBuild(ctx, b) context.Request, _ = http.NewRequest(http.MethodGet, "/test/foo/bar/builds/1", nil) @@ -1005,11 +1005,11 @@ func TestPerm_MustSecretAdmin_BuildToken_Repo(t *testing.T) { defer func() { _ = db.DeleteBuild(ctx, b) - _ = db.DeleteRepo(_context.TODO(), r) + _ = db.DeleteRepo(ctx, r) db.Close() }() - _, _ = db.CreateRepo(_context.TODO(), r) + _, _ = db.CreateRepo(ctx, r) _, _ = db.CreateBuild(ctx, b) context.Request, _ = http.NewRequest(http.MethodGet, "/test/native/repo/foo/bar/baz", nil) @@ -1091,11 +1091,11 @@ func TestPerm_MustSecretAdmin_BuildToken_Org(t *testing.T) { defer func() { _ = db.DeleteBuild(ctx, b) - _ = db.DeleteRepo(_context.TODO(), r) + _ = db.DeleteRepo(ctx, r) db.Close() }() - _, _ = db.CreateRepo(_context.TODO(), r) + _, _ = db.CreateRepo(ctx, r) _, _ = db.CreateBuild(ctx, b) context.Request, _ = http.NewRequest(http.MethodGet, "/test/native/org/foo/*/baz", nil) @@ -1177,11 +1177,11 @@ func TestPerm_MustSecretAdmin_BuildToken_Shared(t *testing.T) { defer func() { _ = db.DeleteBuild(ctx, b) - _ = db.DeleteRepo(_context.TODO(), r) + _ = db.DeleteRepo(ctx, r) db.Close() }() - _, _ = db.CreateRepo(_context.TODO(), r) + _, _ = db.CreateRepo(ctx, r) _, _ = db.CreateBuild(ctx, b) context.Request, _ = http.NewRequest(http.MethodGet, "/test/native/shared/foo/*/*", nil) @@ -2163,12 +2163,12 @@ func TestPerm_MustRead_WorkerBuildToken(t *testing.T) { defer func() { _ = db.DeleteBuild(ctx, b) - _ = db.DeleteRepo(_context.TODO(), r) + _ = db.DeleteRepo(ctx, r) db.Close() }() _, _ = db.CreateBuild(ctx, b) - _, _ = db.CreateRepo(_context.TODO(), r) + _, _ = db.CreateRepo(ctx, r) context.Request, _ = http.NewRequest(http.MethodGet, "/test/foo/bar/builds/1", nil) context.Request.Header.Add("Authorization", fmt.Sprintf("Bearer %s", tok)) diff --git a/router/service.go b/router/service.go index 48787d19d..8aa09889c 100644 --- a/router/service.go +++ b/router/service.go @@ -1,6 +1,5 @@ // SPDX-License-Identifier: Apache-2.0 -//nolint:dupl // ignore similar code with step package router import ( diff --git a/router/step.go b/router/step.go index 934e61d81..70bfad3dc 100644 --- a/router/step.go +++ b/router/step.go @@ -1,6 +1,5 @@ // SPDX-License-Identifier: Apache-2.0 -//nolint:dupl // ignore similar code with service package router import ( diff --git a/scm/github/authentication.go b/scm/github/authentication.go index f7e86bb89..30376991f 100644 --- a/scm/github/authentication.go +++ b/scm/github/authentication.go @@ -33,7 +33,7 @@ func (c *client) Authorize(ctx context.Context, token string) (string, error) { } // Login begins the authentication workflow for the session. -func (c *client) Login(ctx context.Context, w http.ResponseWriter, r *http.Request) (string, error) { +func (c *client) Login(_ context.Context, w http.ResponseWriter, r *http.Request) (string, error) { c.Logger.Trace("processing login request") // generate a random string for creating the OAuth state @@ -78,7 +78,7 @@ func (c *client) Authenticate(ctx context.Context, _ http.ResponseWriter, r *htt } // exchange OAuth code for token - token, err := c.OAuth.Exchange(context.Background(), code) + token, err := c.OAuth.Exchange(ctx, code) if err != nil { return nil, err } @@ -155,7 +155,7 @@ func (c *client) ValidateOAuthToken(ctx context.Context, token string) (bool, er client.UploadURL = enterpriseURL } // check if the provided token was created by Vela - _, resp, err := client.Authorizations.Check(context.Background(), c.config.ClientID, token) + _, resp, err := client.Authorizations.Check(ctx, c.config.ClientID, token) // check if the error is of type ErrorResponse var gerr *github.ErrorResponse if errors.As(err, &gerr) { diff --git a/scm/github/repo.go b/scm/github/repo.go index 31fa2b9e8..3cf9dc760 100644 --- a/scm/github/repo.go +++ b/scm/github/repo.go @@ -636,10 +636,6 @@ func (c *client) GetHTMLURL(ctx context.Context, u *api.User, org, repo, name, r if data != nil { URL := data.GetHTMLURL() - if err != nil { - return "", err - } - return URL, nil } diff --git a/scm/github/webhook.go b/scm/github/webhook.go index b6f6556fe..632a42e1b 100644 --- a/scm/github/webhook.go +++ b/scm/github/webhook.go @@ -83,7 +83,7 @@ func (c *client) ProcessWebhook(ctx context.Context, request *http.Request) (*in } // VerifyWebhook verifies the webhook from a repo. -func (c *client) VerifyWebhook(ctx context.Context, request *http.Request, r *api.Repo) error { +func (c *client) VerifyWebhook(_ context.Context, request *http.Request, r *api.Repo) error { c.Logger.WithFields(logrus.Fields{ "org": r.GetOrg(), "repo": r.GetName(), @@ -131,7 +131,7 @@ func (c *client) RedeliverWebhook(ctx context.Context, u *api.User, h *api.Hook) } // processPushEvent is a helper function to process the push event. -func (c *client) processPushEvent(ctx context.Context, h *api.Hook, payload *github.PushEvent) (*internal.Webhook, error) { +func (c *client) processPushEvent(_ context.Context, h *api.Hook, payload *github.PushEvent) (*internal.Webhook, error) { c.Logger.WithFields(logrus.Fields{ "org": payload.GetRepo().GetOwner().GetLogin(), "repo": payload.GetRepo().GetName(), diff --git a/secret/vault/count.go b/secret/vault/count.go index 927a1da85..4947b3848 100644 --- a/secret/vault/count.go +++ b/secret/vault/count.go @@ -14,7 +14,7 @@ import ( ) // Count counts a list of secrets. -func (c *client) Count(ctx context.Context, sType, org, name string, _ []string) (i int64, err error) { +func (c *client) Count(_ context.Context, sType, org, name string, _ []string) (i int64, err error) { // create log fields from secret metadata fields := logrus.Fields{ "org": org, diff --git a/secret/vault/create.go b/secret/vault/create.go index 2a3e94a2b..0fcede885 100644 --- a/secret/vault/create.go +++ b/secret/vault/create.go @@ -15,7 +15,7 @@ import ( ) // Create creates a new secret. -func (c *client) Create(ctx context.Context, sType, org, name string, s *api.Secret) (*api.Secret, error) { +func (c *client) Create(_ context.Context, sType, org, name string, s *api.Secret) (*api.Secret, error) { // create log fields from secret metadata fields := logrus.Fields{ "org": org, diff --git a/secret/vault/delete.go b/secret/vault/delete.go index 246393764..6f1cd8546 100644 --- a/secret/vault/delete.go +++ b/secret/vault/delete.go @@ -13,7 +13,7 @@ import ( ) // Delete deletes a secret. -func (c *client) Delete(ctx context.Context, sType, org, name, path string) error { +func (c *client) Delete(_ context.Context, sType, org, name, path string) error { // create log fields from secret metadata fields := logrus.Fields{ "org": org, diff --git a/secret/vault/get.go b/secret/vault/get.go index dd3b08591..129cf6ec2 100644 --- a/secret/vault/get.go +++ b/secret/vault/get.go @@ -15,7 +15,7 @@ import ( ) // Get captures a secret. -func (c *client) Get(ctx context.Context, sType, org, name, path string) (s *velaAPI.Secret, err error) { +func (c *client) Get(_ context.Context, sType, org, name, path string) (s *velaAPI.Secret, err error) { // create log fields from secret metadata fields := logrus.Fields{ "org": org, @@ -37,8 +37,7 @@ func (c *client) Get(ctx context.Context, sType, org, name, path string) (s *vel c.Logger.WithFields(fields).Tracef("getting vault %s secret %s for %s/%s", sType, path, org, name) - //nolint:ineffassign,staticcheck // ignore false positive - vault := new(api.Secret) + var vault *api.Secret // capture the secret from the Vault service switch sType { diff --git a/secret/vault/refresh_test.go b/secret/vault/refresh_test.go index 9fa3f62d1..176d1f06c 100644 --- a/secret/vault/refresh_test.go +++ b/secret/vault/refresh_test.go @@ -42,7 +42,7 @@ func Test_client_initialize(t *testing.T) { // run tests for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { data, err := os.ReadFile(fmt.Sprintf("testdata/refresh/%s", tt.responseFile)) if err != nil { t.Error(err) @@ -68,7 +68,7 @@ func Test_client_initialize(t *testing.T) { c.config.AuthMethod = tt.vaultAuthMethod c.AWS.StsClient = &mockSTSClient{ - mockGetCallerIdentityRequest: func(in *sts.GetCallerIdentityInput) (*request.Request, *sts.GetCallerIdentityOutput) { + mockGetCallerIdentityRequest: func(_ *sts.GetCallerIdentityInput) (*request.Request, *sts.GetCallerIdentityOutput) { return &request.Request{ HTTPRequest: &http.Request{ Host: "sts.amazonaws.com", @@ -105,7 +105,7 @@ func Test_client_getAwsToken(t *testing.T) { responseFile: "auth-response-success.json", responseCode: 200, stsClient: &mockSTSClient{ - mockGetCallerIdentityRequest: func(in *sts.GetCallerIdentityInput) (*request.Request, *sts.GetCallerIdentityOutput) { + mockGetCallerIdentityRequest: func(_ *sts.GetCallerIdentityInput) (*request.Request, *sts.GetCallerIdentityOutput) { return &request.Request{ HTTPRequest: &http.Request{ Host: "sts.amazonaws.com", @@ -125,7 +125,7 @@ func Test_client_getAwsToken(t *testing.T) { responseFile: "auth-response-error-role-not-found.json", responseCode: 400, stsClient: &mockSTSClient{ - mockGetCallerIdentityRequest: func(in *sts.GetCallerIdentityInput) (*request.Request, *sts.GetCallerIdentityOutput) { + mockGetCallerIdentityRequest: func(_ *sts.GetCallerIdentityInput) (*request.Request, *sts.GetCallerIdentityOutput) { return &request.Request{ HTTPRequest: &http.Request{ Host: "sts.amazonaws.com", @@ -143,7 +143,7 @@ func Test_client_getAwsToken(t *testing.T) { responseFile: "auth-response-error-no-auth-values.json", responseCode: 400, stsClient: &mockSTSClient{ - mockGetCallerIdentityRequest: func(in *sts.GetCallerIdentityInput) (*request.Request, *sts.GetCallerIdentityOutput) { + mockGetCallerIdentityRequest: func(_ *sts.GetCallerIdentityInput) (*request.Request, *sts.GetCallerIdentityOutput) { return &request.Request{ HTTPRequest: &http.Request{ Host: "sts.amazonaws.com", @@ -161,7 +161,7 @@ func Test_client_getAwsToken(t *testing.T) { responseFile: "auth-response-error-nil-secret.json", responseCode: 200, stsClient: &mockSTSClient{ - mockGetCallerIdentityRequest: func(in *sts.GetCallerIdentityInput) (*request.Request, *sts.GetCallerIdentityOutput) { + mockGetCallerIdentityRequest: func(_ *sts.GetCallerIdentityInput) (*request.Request, *sts.GetCallerIdentityOutput) { return &request.Request{ HTTPRequest: &http.Request{ Host: "sts.amazonaws.com", @@ -179,7 +179,7 @@ func Test_client_getAwsToken(t *testing.T) { responseFile: "testdata/auth-response-error-no-auth-values.json", responseCode: 400, stsClient: &mockSTSClient{ - mockGetCallerIdentityRequest: func(in *sts.GetCallerIdentityInput) (*request.Request, *sts.GetCallerIdentityOutput) { + mockGetCallerIdentityRequest: func(_ *sts.GetCallerIdentityInput) (*request.Request, *sts.GetCallerIdentityOutput) { return &request.Request{ HTTPRequest: &http.Request{ Host: "sts.amazonaws.com", @@ -198,7 +198,7 @@ func Test_client_getAwsToken(t *testing.T) { // run tests for _, tt := range tests { t.Run(tt.name, func(*testing.T) { - ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { data, err := os.ReadFile(fmt.Sprintf("testdata/refresh/%s", tt.responseFile)) if err != nil { t.Error(err)