Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

enhance(tracing): customizable tasks sampler #1184

Merged
merged 3 commits into from
Sep 17, 2024

chore: remove example json

bc7cdf3
Select commit
Loading
Failed to load commit list.
Sign in for the full log view
Merged

enhance(tracing): customizable tasks sampler #1184

chore: remove example json
bc7cdf3
Select commit
Loading
Failed to load commit list.
GitHub Actions / golangci failed Sep 17, 2024 in 0s

reviewdog [golangci] report

reported by reviewdog 🐶

Findings (44)

secret/vault/refresh_test.go|45 col 74| unused-parameter: parameter 'r' seems to be unused, consider removing or renaming it as _ (revive)
secret/vault/refresh_test.go|71 col 40| unused-parameter: parameter 'in' seems to be unused, consider removing or renaming it as _ (revive)
secret/vault/refresh_test.go|108 col 40| unused-parameter: parameter 'in' seems to be unused, consider removing or renaming it as _ (revive)
secret/vault/count.go|17 col 24| unused-parameter: parameter 'ctx' seems to be unused, consider removing or renaming it as _ (revive)
secret/vault/refresh_test.go|128 col 40| unused-parameter: parameter 'in' seems to be unused, consider removing or renaming it as _ (revive)
secret/vault/delete.go|16 col 25| unused-parameter: parameter 'ctx' seems to be unused, consider removing or renaming it as _ (revive)
secret/vault/create.go|18 col 25| unused-parameter: parameter 'ctx' seems to be unused, consider removing or renaming it as _ (revive)
secret/vault/refresh_test.go|201 col 74| unused-parameter: parameter 'r' seems to be unused, consider removing or renaming it as _ (revive)
database/hook/get.go|3| 3-40 lines are duplicate of database/hook/get_webhook.go:3-40 (dupl)
database/hook/get_webhook.go|3| 3-40 lines are duplicate of database/hook/get.go:3-40 (dupl)
database/hook/create.go|3| 3-39 lines are duplicate of database/hook/update.go:3-42 (dupl)
database/hook/update.go|3| 3-42 lines are duplicate of database/hook/create.go:3-39 (dupl)
database/worker/create.go|3| 3-41 lines are duplicate of database/worker/update.go:3-41 (dupl)
database/worker/update.go|3| 3-41 lines are duplicate of database/worker/create.go:3-41 (dupl)
scm/github/authentication.go|81 col 32| Non-inherited new context, use function like context.WithXXX instead (contextcheck)
scm/github/authentication.go|158 col 45| Non-inherited new context, use function like context.WithXXX instead (contextcheck)
database/pipeline/create.go|3| 3-57 lines are duplicate of database/pipeline/update.go:3-58 (dupl)
database/pipeline/update.go|3| 3-58 lines are duplicate of database/pipeline/create.go:3-57 (dupl)
api/pipeline/validate.go|78| 78-110 lines are duplicate of api/pipeline/compile.go:80-112 (dupl)
api/pipeline/validate.go|3| 3-110 lines are duplicate of api/pipeline/expand.go:4-112 (dupl)
api/types/build.go|1211 col 30| SA1019: library.Build is deprecated: use Build from github.com/go-vela/server/api/types instead. (staticcheck)
api/types/build.go|1212 col 10| SA1019: library.Build is deprecated: use Build from github.com/go-vela/server/api/types instead. (staticcheck)
compiler/registry/github/template.go|39 col 52| Non-inherited new context, use function like context.WithXXX instead (contextcheck)
database/integration_test.go|2561 col 15| SA1019: library.Build is deprecated: use Build from github.com/go-vela/server/api/types instead. (staticcheck)
database/deployment/list.go|33| 33-63 lines are duplicate of database/deployment/list_repo.go:46-76 (dupl)
database/deployment/list_repo.go|46| 46-76 lines are duplicate of database/deployment/list.go:33-63 (dupl)
database/deployment/create.go|3| 3-37 lines are duplicate of database/deployment/update.go:3-37 (dupl)
database/deployment/update.go|3| 3-37 lines are duplicate of database/deployment/create.go:3-37 (dupl)
database/types/build.go|375 col 44| G115: integer overflow conversion int -> int32 (gosec)
database/types/build.go|376 col 44| G115: integer overflow conversion int -> int32 (gosec)
database/types/repo.go|336 col 43| G115: integer overflow conversion int -> int32 (gosec)
database/types/settings.go|134 col 35| G115: integer overflow conversion int64 -> uint64 (gosec)
database/types/settings.go|205 col 49| G115: integer overflow conversion uint64 -> int64 (gosec)
mock/server/schedule.go|3| 3-284 lines are duplicate of mock/server/secret.go:4-181 (dupl)
mock/server/authentication.go|84 col 9| string error has 4 occurrences, make it a constant (goconst)
compiler/native/compile.go|329 col 26| Function modifyConfig should pass the context parameter (contextcheck)
compiler/native/compile.go|424 col 26| Function modifyConfig should pass the context parameter (contextcheck)
compiler/template/starlark/starlark.go|131 col 4| only one cuddle assignment allowed before if statement (wsl)
database/service/create.go|3| 3-41 lines are duplicate of database/service/update.go:3-41 (dupl)
database/service/update.go|3| 3-41 lines are duplicate of database/service/create.go:3-41 (dupl)
router/middleware/logger.go|48 col 36| unused-parameter: parameter 'timeFormat' seems to be unused, consider removing or renaming it as _ (revive)
database/step/create.go|3| 3-41 lines are duplicate of database/step/update.go:3-41 (dupl)
database/step/update.go|3| 3-41 lines are duplicate of database/step/create.go:3-41 (dupl)
secret/vault/get.go|40 col 2| directive //nolint:ineffassign,staticcheck // ignore false positive is unused for linter "staticcheck" (nolintlint)

Filtered Findings (0)

Annotations

Check failure on line 45 in secret/vault/refresh_test.go

See this annotation in the file changed.

@github-actions github-actions / golangci

[golangci] secret/vault/refresh_test.go#L45

unused-parameter: parameter 'r' seems to be unused, consider removing or renaming it as _ (revive)
Raw output
secret/vault/refresh_test.go:45:74: unused-parameter: parameter 'r' seems to be unused, consider removing or renaming it as _ (revive)
			ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			                                                                      ^

Check failure on line 71 in secret/vault/refresh_test.go

See this annotation in the file changed.

@github-actions github-actions / golangci

[golangci] secret/vault/refresh_test.go#L71

unused-parameter: parameter 'in' seems to be unused, consider removing or renaming it as _ (revive)
Raw output
secret/vault/refresh_test.go:71:40: unused-parameter: parameter 'in' seems to be unused, consider removing or renaming it as _ (revive)
				mockGetCallerIdentityRequest: func(in *sts.GetCallerIdentityInput) (*request.Request, *sts.GetCallerIdentityOutput) {
				                                   ^

Check failure on line 108 in secret/vault/refresh_test.go

See this annotation in the file changed.

@github-actions github-actions / golangci

[golangci] secret/vault/refresh_test.go#L108

unused-parameter: parameter 'in' seems to be unused, consider removing or renaming it as _ (revive)
Raw output
secret/vault/refresh_test.go:108:40: unused-parameter: parameter 'in' seems to be unused, consider removing or renaming it as _ (revive)
				mockGetCallerIdentityRequest: func(in *sts.GetCallerIdentityInput) (*request.Request, *sts.GetCallerIdentityOutput) {
				                                   ^

Check failure on line 17 in secret/vault/count.go

See this annotation in the file changed.

@github-actions github-actions / golangci

[golangci] secret/vault/count.go#L17

unused-parameter: parameter 'ctx' seems to be unused, consider removing or renaming it as _ (revive)
Raw output
secret/vault/count.go:17:24: unused-parameter: parameter 'ctx' seems to be unused, consider removing or renaming it as _ (revive)
func (c *client) Count(ctx context.Context, sType, org, name string, _ []string) (i int64, err error) {
                       ^

Check failure on line 128 in secret/vault/refresh_test.go

See this annotation in the file changed.

@github-actions github-actions / golangci

[golangci] secret/vault/refresh_test.go#L128

unused-parameter: parameter 'in' seems to be unused, consider removing or renaming it as _ (revive)
Raw output
secret/vault/refresh_test.go:128:40: unused-parameter: parameter 'in' seems to be unused, consider removing or renaming it as _ (revive)
				mockGetCallerIdentityRequest: func(in *sts.GetCallerIdentityInput) (*request.Request, *sts.GetCallerIdentityOutput) {
				                                   ^

Check failure on line 16 in secret/vault/delete.go

See this annotation in the file changed.

@github-actions github-actions / golangci

[golangci] secret/vault/delete.go#L16

unused-parameter: parameter 'ctx' seems to be unused, consider removing or renaming it as _ (revive)
Raw output
secret/vault/delete.go:16:25: unused-parameter: parameter 'ctx' seems to be unused, consider removing or renaming it as _ (revive)
func (c *client) Delete(ctx context.Context, sType, org, name, path string) error {
                        ^

Check failure on line 18 in secret/vault/create.go

See this annotation in the file changed.

@github-actions github-actions / golangci

[golangci] secret/vault/create.go#L18

unused-parameter: parameter 'ctx' seems to be unused, consider removing or renaming it as _ (revive)
Raw output
secret/vault/create.go:18:25: unused-parameter: parameter 'ctx' seems to be unused, consider removing or renaming it as _ (revive)
func (c *client) Create(ctx context.Context, sType, org, name string, s *library.Secret) (*library.Secret, error) {
                        ^

Check failure on line 201 in secret/vault/refresh_test.go

See this annotation in the file changed.

@github-actions github-actions / golangci

[golangci] secret/vault/refresh_test.go#L201

unused-parameter: parameter 'r' seems to be unused, consider removing or renaming it as _ (revive)
Raw output
secret/vault/refresh_test.go:201:74: unused-parameter: parameter 'r' seems to be unused, consider removing or renaming it as _ (revive)
			ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
			                                                                      ^

Check failure on line 3 in database/hook/get.go

See this annotation in the file changed.

@github-actions github-actions / golangci

[golangci] database/hook/get.go#L3

3-40 lines are duplicate of `database/hook/get_webhook.go:3-40` (dupl)
Raw output
database/hook/get.go:3: 3-40 lines are duplicate of `database/hook/get_webhook.go:3-40` (dupl)
package hook

import (
	"context"

	api "github.com/go-vela/server/api/types"
	"github.com/go-vela/server/constants"
	"github.com/go-vela/server/database/types"
)

// GetHook gets a hook by ID from the database.
func (e *engine) GetHook(ctx context.Context, id int64) (*api.Hook, error) {
	e.logger.Tracef("getting hook %d", id)

	// variable to store query results
	h := new(types.Hook)

	// send query to the database and store result in variable
	err := e.client.
		WithContext(ctx).
		Table(constants.TableHook).
		Preload("Repo").
		Preload("Repo.Owner").
		Preload("Build").
		Where("id = ?", id).
		Take(h).
		Error
	if err != nil {
		return nil, err
	}

	err = h.Repo.Decrypt(e.config.EncryptionKey)
	if err != nil {
		e.logger.Errorf("unable to decrypt repo for hook %d: %v", h.ID.Int64, err)
	}

	return h.ToAPI(), nil
}

Check failure on line 3 in database/hook/get_webhook.go

See this annotation in the file changed.

@github-actions github-actions / golangci

[golangci] database/hook/get_webhook.go#L3

3-40 lines are duplicate of `database/hook/get.go:3-40` (dupl)
Raw output
database/hook/get_webhook.go:3: 3-40 lines are duplicate of `database/hook/get.go:3-40` (dupl)
package hook

import (
	"context"

	api "github.com/go-vela/server/api/types"
	"github.com/go-vela/server/constants"
	"github.com/go-vela/server/database/types"
)

// GetHookByWebhookID gets a single hook with a matching webhook id in the database.
func (e *engine) GetHookByWebhookID(ctx context.Context, webhookID int64) (*api.Hook, error) {
	e.logger.Tracef("getting a hook with webhook id %d", webhookID)

	// variable to store query results
	h := new(types.Hook)

	// send query to the database and store result in variable
	err := e.client.
		WithContext(ctx).
		Table(constants.TableHook).
		Preload("Repo").
		Preload("Repo.Owner").
		Preload("Build").
		Where("webhook_id = ?", webhookID).
		Take(h).
		Error
	if err != nil {
		return nil, err
	}

	err = h.Repo.Decrypt(e.config.EncryptionKey)
	if err != nil {
		e.logger.Errorf("unable to decrypt repo for hook %d: %v", h.ID.Int64, err)
	}

	return h.ToAPI(), nil
}

Check failure on line 3 in database/hook/create.go

See this annotation in the file changed.

@github-actions github-actions / golangci

[golangci] database/hook/create.go#L3

3-39 lines are duplicate of `database/hook/update.go:3-42` (dupl)
Raw output
database/hook/create.go:3: 3-39 lines are duplicate of `database/hook/update.go:3-42` (dupl)
package hook

import (
	"context"

	"github.com/sirupsen/logrus"

	api "github.com/go-vela/server/api/types"
	"github.com/go-vela/server/constants"
	"github.com/go-vela/server/database/types"
)

// CreateHook creates a new hook in the database.
func (e *engine) CreateHook(ctx context.Context, h *api.Hook) (*api.Hook, error) {
	e.logger.WithFields(logrus.Fields{
		"hook": h.GetNumber(),
	}).Tracef("creating hook %d", h.GetNumber())

	hook := types.HookFromAPI(h)

	err := hook.Validate()
	if err != nil {
		return nil, err
	}

	// send query to the database
	err = e.client.WithContext(ctx).Table(constants.TableHook).Create(hook).Error
	if err != nil {
		return nil, err
	}

	result := hook.ToAPI()
	result.SetRepo(h.GetRepo())
	result.SetBuild(h.GetBuild())

	return result, nil
}

Check failure on line 3 in database/hook/update.go

See this annotation in the file changed.

@github-actions github-actions / golangci

[golangci] database/hook/update.go#L3

3-42 lines are duplicate of `database/hook/create.go:3-39` (dupl)
Raw output
database/hook/update.go:3: 3-42 lines are duplicate of `database/hook/create.go:3-39` (dupl)
package hook

import (
	"context"

	"github.com/sirupsen/logrus"

	api "github.com/go-vela/server/api/types"
	"github.com/go-vela/server/constants"
	"github.com/go-vela/server/database/types"
)

// UpdateHook updates an existing hook in the database.
func (e *engine) UpdateHook(ctx context.Context, h *api.Hook) (*api.Hook, error) {
	e.logger.WithFields(logrus.Fields{
		"hook": h.GetNumber(),
	}).Tracef("updating hook %d", h.GetNumber())

	hook := types.HookFromAPI(h)

	// validate the necessary fields are populated
	//
	// https://pkg.go.dev/github.com/go-vela/types/database#Hook.Validate
	err := hook.Validate()
	if err != nil {
		return nil, err
	}

	// send query to the database
	err = e.client.WithContext(ctx).Table(constants.TableHook).Save(hook).Error
	if err != nil {
		return nil, err
	}

	result := hook.ToAPI()
	result.SetRepo(h.GetRepo())
	result.SetBuild(h.GetBuild())

	return result, nil
}

Check failure on line 3 in database/worker/create.go

See this annotation in the file changed.

@github-actions github-actions / golangci

[golangci] database/worker/create.go#L3

3-41 lines are duplicate of `database/worker/update.go:3-41` (dupl)
Raw output
database/worker/create.go:3: 3-41 lines are duplicate of `database/worker/update.go:3-41` (dupl)
package worker

import (
	"context"

	"github.com/sirupsen/logrus"

	api "github.com/go-vela/server/api/types"
	"github.com/go-vela/server/database/types"
	"github.com/go-vela/types/constants"
)

// CreateWorker creates a new worker in the database.
func (e *engine) CreateWorker(ctx context.Context, w *api.Worker) (*api.Worker, error) {
	e.logger.WithFields(logrus.Fields{
		"worker": w.GetHostname(),
	}).Tracef("creating worker %s", w.GetHostname())

	// cast the library type to database type
	//
	// https://pkg.go.dev/github.com/go-vela/types/database#WorkerFromLibrary
	worker := types.WorkerFromAPI(w)

	// validate the necessary fields are populated
	//
	// https://pkg.go.dev/github.com/go-vela/types/database#Worker.Validate
	err := worker.Validate()
	if err != nil {
		return nil, err
	}

	// send query to the database
	result := e.client.
		WithContext(ctx).
		Table(constants.TableWorker).
		Create(worker)

	return worker.ToAPI(w.GetRunningBuilds()), result.Error
}

Check failure on line 3 in database/worker/update.go

See this annotation in the file changed.

@github-actions github-actions / golangci

[golangci] database/worker/update.go#L3

3-41 lines are duplicate of `database/worker/create.go:3-41` (dupl)
Raw output
database/worker/update.go:3: 3-41 lines are duplicate of `database/worker/create.go:3-41` (dupl)
package worker

import (
	"context"

	"github.com/sirupsen/logrus"

	api "github.com/go-vela/server/api/types"
	"github.com/go-vela/server/database/types"
	"github.com/go-vela/types/constants"
)

// UpdateWorker updates an existing worker in the database.
func (e *engine) UpdateWorker(ctx context.Context, w *api.Worker) (*api.Worker, error) {
	e.logger.WithFields(logrus.Fields{
		"worker": w.GetHostname(),
	}).Tracef("updating worker %s", w.GetHostname())

	// cast the library type to database type
	//
	// https://pkg.go.dev/github.com/go-vela/types/database#WorkerFromLibrary
	worker := types.WorkerFromAPI(w)

	// validate the necessary fields are populated
	//
	// https://pkg.go.dev/github.com/go-vela/types/database#Worker.Validate
	err := worker.Validate()
	if err != nil {
		return nil, err
	}

	// send query to the database
	result := e.client.
		WithContext(ctx).
		Table(constants.TableWorker).
		Save(worker)

	return worker.ToAPI(w.GetRunningBuilds()), result.Error
}

Check failure on line 81 in scm/github/authentication.go

See this annotation in the file changed.

@github-actions github-actions / golangci

[golangci] scm/github/authentication.go#L81

Non-inherited new context, use function like `context.WithXXX` instead (contextcheck)
Raw output
scm/github/authentication.go:81:32: Non-inherited new context, use function like `context.WithXXX` instead (contextcheck)
	token, err := c.OAuth.Exchange(context.Background(), code)
	                              ^

Check failure on line 158 in scm/github/authentication.go

See this annotation in the file changed.

@github-actions github-actions / golangci

[golangci] scm/github/authentication.go#L158

Non-inherited new context, use function like `context.WithXXX` instead (contextcheck)
Raw output
scm/github/authentication.go:158:45: Non-inherited new context, use function like `context.WithXXX` instead (contextcheck)
	_, resp, err := client.Authorizations.Check(context.Background(), c.config.ClientID, token)
	                                           ^

Check failure on line 3 in database/pipeline/create.go

See this annotation in the file changed.

@github-actions github-actions / golangci

[golangci] database/pipeline/create.go#L3

3-57 lines are duplicate of `database/pipeline/update.go:3-58` (dupl)
Raw output
database/pipeline/create.go:3: 3-57 lines are duplicate of `database/pipeline/update.go:3-58` (dupl)
package pipeline

import (
	"context"

	"github.com/sirupsen/logrus"

	"github.com/go-vela/types/constants"
	"github.com/go-vela/types/database"
	"github.com/go-vela/types/library"
)

// CreatePipeline creates a new pipeline in the database.
func (e *engine) CreatePipeline(ctx context.Context, p *library.Pipeline) (*library.Pipeline, error) {
	e.logger.WithFields(logrus.Fields{
		"pipeline": p.GetCommit(),
	}).Tracef("creating pipeline %s in the database", p.GetCommit())

	// cast the library type to database type
	//
	// https://pkg.go.dev/github.com/go-vela/types/database#PipelineFromLibrary
	pipeline := database.PipelineFromLibrary(p)

	// validate the necessary fields are populated
	//
	// https://pkg.go.dev/github.com/go-vela/types/database#Pipeline.Validate
	err := pipeline.Validate()
	if err != nil {
		return nil, err
	}

	// compress data for the pipeline
	//
	// https://pkg.go.dev/github.com/go-vela/types/database#Pipeline.Compress
	err = pipeline.Compress(e.config.CompressionLevel)
	if err != nil {
		return nil, err
	}

	// send query to the database
	err = e.client.
		WithContext(ctx).
		Table(constants.TablePipeline).
		Create(pipeline).Error
	if err != nil {
		return nil, err
	}

	err = pipeline.Decompress()
	if err != nil {
		return nil, err
	}

	return pipeline.ToLibrary(), nil
}

Check failure on line 3 in database/pipeline/update.go

See this annotation in the file changed.

@github-actions github-actions / golangci

[golangci] database/pipeline/update.go#L3

3-58 lines are duplicate of `database/pipeline/create.go:3-57` (dupl)
Raw output
database/pipeline/update.go:3: 3-58 lines are duplicate of `database/pipeline/create.go:3-57` (dupl)
package pipeline

import (
	"context"

	"github.com/sirupsen/logrus"

	"github.com/go-vela/types/constants"
	"github.com/go-vela/types/database"
	"github.com/go-vela/types/library"
)

// UpdatePipeline updates an existing pipeline in the database.
func (e *engine) UpdatePipeline(ctx context.Context, p *library.Pipeline) (*library.Pipeline, error) {
	e.logger.WithFields(logrus.Fields{
		"pipeline": p.GetCommit(),
	}).Tracef("updating pipeline %s in the database", p.GetCommit())

	// cast the library type to database type
	//
	// https://pkg.go.dev/github.com/go-vela/types/database#PipelineFromLibrary
	pipeline := database.PipelineFromLibrary(p)

	// validate the necessary fields are populated
	//
	// https://pkg.go.dev/github.com/go-vela/types/database#Pipeline.Validate
	err := pipeline.Validate()
	if err != nil {
		return nil, err
	}

	// compress data for the pipeline
	//
	// https://pkg.go.dev/github.com/go-vela/types/database#Pipeline.Compress
	err = pipeline.Compress(e.config.CompressionLevel)
	if err != nil {
		return nil, err
	}

	// send query to the database
	err = e.client.
		WithContext(ctx).
		Table(constants.TablePipeline).
		Save(pipeline).Error
	if err != nil {
		return nil, err
	}

	// decompress pipeline to return
	err = pipeline.Decompress()
	if err != nil {
		return nil, err
	}

	return pipeline.ToLibrary(), nil
}

Check failure on line 78 in api/pipeline/validate.go

See this annotation in the file changed.

@github-actions github-actions / golangci

[golangci] api/pipeline/validate.go#L78

78-110 lines are duplicate of `api/pipeline/compile.go:80-112` (dupl)
Raw output
api/pipeline/validate.go:78: 78-110 lines are duplicate of `api/pipeline/compile.go:80-112` (dupl)
func ValidatePipeline(c *gin.Context) {
	// capture middleware values
	m := c.MustGet("metadata").(*internal.Metadata)
	l := c.MustGet("logger").(*logrus.Entry)
	p := pipeline.Retrieve(c)
	r := repo.Retrieve(c)
	u := user.Retrieve(c)
	ctx := c.Request.Context()

	entry := fmt.Sprintf("%s/%s", r.GetFullName(), p.GetCommit())

	l.Debugf("validating pipeline %s", entry)

	// ensure we use the expected pipeline type when compiling
	r.SetPipelineType(p.GetType())

	// create the compiler object
	compiler := compiler.FromContext(c).Duplicate().WithCommit(p.GetCommit()).WithMetadata(m).WithRepo(r).WithUser(u)

	ruleData := prepareRuleData(c)

	// validate the pipeline
	pipeline, _, err := compiler.CompileLite(ctx, p.GetData(), ruleData, false)
	if err != nil {
		retErr := fmt.Errorf("unable to validate pipeline %s: %w", entry, err)

		util.HandleError(c, http.StatusBadRequest, retErr)

		return
	}

	writeOutput(c, pipeline)
}

Check failure on line 3 in api/pipeline/validate.go

See this annotation in the file changed.

@github-actions github-actions / golangci

[golangci] api/pipeline/validate.go#L3

3-110 lines are duplicate of `api/pipeline/expand.go:4-112` (dupl)
Raw output
api/pipeline/validate.go:3: 3-110 lines are duplicate of `api/pipeline/expand.go:4-112` (dupl)
package pipeline

import (
	"fmt"
	"net/http"

	"github.com/gin-gonic/gin"
	"github.com/sirupsen/logrus"

	"github.com/go-vela/server/compiler"
	"github.com/go-vela/server/internal"
	"github.com/go-vela/server/router/middleware/pipeline"
	"github.com/go-vela/server/router/middleware/repo"
	"github.com/go-vela/server/router/middleware/user"
	"github.com/go-vela/server/util"
)

// swagger:operation POST /api/v1/pipelines/{org}/{repo}/{pipeline}/validate pipelines ValidatePipeline
//
// Get, expand and validate a pipeline
//
// ---
// produces:
// - application/yaml
// - application/json
// parameters:
// - in: path
//   name: org
//   description: Name of the organization
//   required: true
//   type: string
// - in: path
//   name: repo
//   description: Name of the repository
//   required: true
//   type: string
// - in: path
//   name: pipeline
//   description: Commit SHA for pipeline to retrieve
//   required: true
//   type: string
// - in: query
//   name: output
//   description: Output string for specifying output format
//   type: string
//   default: yaml
//   enum:
//   - json
//   - yaml
// security:
//   - ApiKeyAuth: []
// responses:
//   '200':
//     description: Successfully retrieved, expanded and validated the pipeline
//     schema:
//       type: string
//   '400':
//     description: Invalid request payload or path
//     schema:
//       "$ref": "#/definitions/Error"
//   '401':
//     description: Unauthorized
//     schema:
//       "$ref": "#/definitions/Error"
//   '404':
//     description: Not found
//     schema:
//       "$ref": "#/definitions/Error"
//   '500':
//     description: Unexpected server error
//     schema:
//       "$ref": "#/definitions/Error"

// ValidatePipeline represents the API handler to capture,
// expand and validate a pipeline configuration.
func ValidatePipeline(c *gin.Context) {
	// capture middleware values
	m := c.MustGet("metadata").(*internal.Metadata)
	l := c.MustGet("logger").(*logrus.Entry)
	p := pipeline.Retrieve(c)
	r := repo.Retrieve(c)
	u := user.Retrieve(c)
	ctx := c.Request.Context()

	entry := fmt.Sprintf("%s/%s", r.GetFullName(), p.GetCommit())

	l.Debugf("validating pipeline %s", entry)

	// ensure we use the expected pipeline type when compiling
	r.SetPipelineType(p.GetType())

	// create the compiler object
	compiler := compiler.FromContext(c).Duplicate().WithCommit(p.GetCommit()).WithMetadata(m).WithRepo(r).WithUser(u)

	ruleData := prepareRuleData(c)

	// validate the pipeline
	pipeline, _, err := compiler.CompileLite(ctx, p.GetData(), ruleData, false)
	if err != nil {
		retErr := fmt.Errorf("unable to validate pipeline %s: %w", entry, err)

		util.HandleError(c, http.StatusBadRequest, retErr)

		return
	}

	writeOutput(c, pipeline)
}

Check failure on line 1211 in api/types/build.go

See this annotation in the file changed.

@github-actions github-actions / golangci

[golangci] api/types/build.go#L1211

SA1019: library.Build is deprecated: use Build from github.com/go-vela/server/api/types instead. (staticcheck)
Raw output
api/types/build.go:1211:30: SA1019: library.Build is deprecated: use Build from github.com/go-vela/server/api/types instead. (staticcheck)
func (b *Build) ToLibrary() *library.Build {
                             ^

Check failure on line 1212 in api/types/build.go

See this annotation in the file changed.

@github-actions github-actions / golangci

[golangci] api/types/build.go#L1212

SA1019: library.Build is deprecated: use Build from github.com/go-vela/server/api/types instead. (staticcheck)
Raw output
api/types/build.go:1212:10: SA1019: library.Build is deprecated: use Build from github.com/go-vela/server/api/types instead. (staticcheck)
	return &library.Build{
	        ^

Check failure on line 39 in compiler/registry/github/template.go

See this annotation in the file changed.

@github-actions github-actions / golangci

[golangci] compiler/registry/github/template.go#L39

Non-inherited new context, use function like `context.WithXXX` instead (contextcheck)
Raw output
compiler/registry/github/template.go:39:52: Non-inherited new context, use function like `context.WithXXX` instead (contextcheck)
	data, _, resp, err := cli.Repositories.GetContents(context.Background(), s.Org, s.Repo, s.Name, opts)
	                                                  ^

Check failure on line 2561 in database/integration_test.go

See this annotation in the file changed.

@github-actions github-actions / golangci

[golangci] database/integration_test.go#L2561

SA1019: library.Build is deprecated: use Build from github.com/go-vela/server/api/types instead. (staticcheck)
Raw output
database/integration_test.go:2561:15: SA1019: library.Build is deprecated: use Build from github.com/go-vela/server/api/types instead. (staticcheck)
	builds := []*library.Build{}
	             ^

Check failure on line 33 in database/deployment/list.go

See this annotation in the file changed.

@github-actions github-actions / golangci

[golangci] database/deployment/list.go#L33

33-63 lines are duplicate of `database/deployment/list_repo.go:46-76` (dupl)
Raw output
database/deployment/list.go:33: 33-63 lines are duplicate of `database/deployment/list_repo.go:46-76` (dupl)
	for _, deployment := range *d {
		// https://golang.org/doc/faq#closures_and_goroutines
		tmp := deployment

		builds := []*library.Build{}

		for _, a := range tmp.Builds {
			bID, err := strconv.ParseInt(a, 10, 64)
			if err != nil {
				return nil, err
			}
			// variable to store query results
			b := new(database.Build)

			// send query to the database and store result in variable
			err = e.client.
				WithContext(ctx).
				Table(constants.TableBuild).
				Where("id = ?", bID).
				Take(b).
				Error
			if err != nil {
				return nil, err
			}

			builds = append(builds, b.ToLibrary())
		}

		// convert query result to library type
		deployments = append(deployments, tmp.ToLibrary(builds))
	}