Skip to content

Commit

Permalink
Enable some linters (#3129)
Browse files Browse the repository at this point in the history
Mostly those that did not require much work.

From #2960

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
  • Loading branch information
qwerty287 and pre-commit-ci[bot] authored Jan 9, 2024
1 parent 631b7c2 commit 768fd71
Show file tree
Hide file tree
Showing 21 changed files with 121 additions and 63 deletions.
42 changes: 42 additions & 0 deletions .golangci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,24 @@ linters-settings:
- pkg: 'go.woodpecker-ci.org/woodpecker/v2/cmd/agent'
- pkg: 'go.woodpecker-ci.org/woodpecker/v2/cmd/cli'
- pkg: 'go.woodpecker-ci.org/woodpecker/v2/woodpecker-go/woodpecker'
gci:
sections:
- standard
- default
- prefix(go.woodpecker-ci.org/woodpecker)
gomnd:
ignored-numbers:
- '0o600'
- '0o660'
- '0o644'
- '0o755'
- '0o700'
ignored-functions:
- make
- time.*
- strings.Split
- callerName
- securecookie.GenerateRandomKey

linters:
disable-all: true
Expand All @@ -124,6 +142,25 @@ linters:
- forbidigo
- zerologlint
- depguard
- asciicheck
- bodyclose
- dogsled
- durationcheck
- errchkjson
- gochecknoinits
- goheader
- gomoddirectives
- gomodguard
- goprintffuncname
- importas
- makezero
- rowserrcheck
- sqlclosecheck
- tenv
- unconvert
- unparam
- wastedassign
- whitespace

run:
timeout: 15m
Expand All @@ -140,7 +177,12 @@ issues:
- path: 'cmd/*|cli/*'
linters:
- forbidigo

# allow some setup functions to use log.Fatal()
- path: 'server/web/web.go|server/plugins/encryption/tink_keyset_watcher.go|shared/logger/logger.go'
linters:
- forbidigo

- path: '_test.go'
linters:
- forcetypeassert
5 changes: 4 additions & 1 deletion agent/state.go
Original file line number Diff line number Diff line change
Expand Up @@ -74,8 +74,11 @@ func (s *State) Healthy() bool {

func (s *State) WriteTo(w io.Writer) (int64, error) {
s.Lock()
out, _ := json.Marshal(s)
out, err := json.Marshal(s)
s.Unlock()
if err != nil {
return 0, err
}
ret, err := w.Write(out)
return int64(ret), err
}
2 changes: 2 additions & 0 deletions cmd/agent/agent.go
Original file line number Diff line number Diff line change
Expand Up @@ -271,6 +271,8 @@ func getBackendEngine(backendCtx context.Context, backendName string, addons []s
}

func runWithRetry(context *cli.Context) error {
initHealth()

retryCount := context.Int("connect-retry-count")
retryDelay := context.Duration("connect-retry-delay")
var err error
Expand Down
7 changes: 5 additions & 2 deletions cmd/agent/health.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ import (
// following specification:
// https://github.com/mozilla-services/Dockerflow

func init() {
func initHealth() {
http.HandleFunc("/varz", handleStats)
http.HandleFunc("/healthz", handleHeartbeat)
http.HandleFunc("/version", handleVersion)
Expand All @@ -48,10 +48,13 @@ func handleHeartbeat(w http.ResponseWriter, _ *http.Request) {
func handleVersion(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(200)
w.Header().Add("Content-Type", "text/json")
_ = json.NewEncoder(w).Encode(versionResp{
err := json.NewEncoder(w).Encode(versionResp{
Source: "https://github.com/woodpecker-ci/woodpecker",
Version: version.String(),
})
if err != nil {
log.Error().Err(err).Msg("handleVersion")
}
}

func handleStats(w http.ResponseWriter, _ *http.Request) {
Expand Down
7 changes: 2 additions & 5 deletions cmd/server/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -87,10 +87,7 @@ func run(c *cli.Context) error {
log.Fatal().Err(err).Msg("can't setup forge")
}

_store, err := setupStore(c)
if err != nil {
log.Fatal().Err(err).Msg("can't setup database store")
}
_store := setupStore(c)
defer func() {
if err := _store.Close(); err != nil {
log.Error().Err(err).Msg("could not close store")
Expand Down Expand Up @@ -317,7 +314,7 @@ func setupEvilGlobals(c *cli.Context, v store.Store, f forge.Forge) error {

// Execution
_events := c.StringSlice("default-cancel-previous-pipeline-events")
events := make([]model.WebhookEvent, len(_events))
events := make([]model.WebhookEvent, len(_events), 0)
for _, v := range _events {
events = append(events, model.WebhookEvent(v))
}
Expand Down
4 changes: 2 additions & 2 deletions cmd/server/setup.go
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ import (
addonTypes "go.woodpecker-ci.org/woodpecker/v2/shared/addon/types"
)

func setupStore(c *cli.Context) (store.Store, error) {
func setupStore(c *cli.Context) store.Store {
datasource := c.String("datasource")
driver := c.String("driver")
xorm := store.XORM{
Expand Down Expand Up @@ -95,7 +95,7 @@ func setupStore(c *cli.Context) (store.Store, error) {
log.Fatal().Err(err).Msg("could not migrate datastore")
}

return store, nil
return store
}

func checkSqliteFileExist(path string) error {
Expand Down
4 changes: 2 additions & 2 deletions docs/docs/30-administration/10-server-config.md
Original file line number Diff line number Diff line change
Expand Up @@ -586,9 +586,9 @@ Specify a configuration service endpoint, see [Configuration Extension](./100-ex

### `WOODPECKER_FORGE_TIMEOUT`

> Default: 3sec
> Default: 3s
Specify how many seconds before timeout when fetching the Woodpecker configuration from a Forge
Specify timeout when fetching the Woodpecker configuration from forge. See <https://pkg.go.dev/time#ParseDuration> for syntax reference.

### `WOODPECKER_ENABLE_SWAGGER`

Expand Down
9 changes: 3 additions & 6 deletions pipeline/backend/kubernetes/service.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ import (
"k8s.io/apimachinery/pkg/util/intstr"
)

func mkService(namespace, name string, ports []uint16, selector map[string]string) (*v1.Service, error) {
func mkService(namespace, name string, ports []uint16, selector map[string]string) *v1.Service {
log.Trace().Str("name", name).Interface("selector", selector).Interface("ports", ports).Msg("Creating service")

var svcPorts []v1.ServicePort
Expand All @@ -48,7 +48,7 @@ func mkService(namespace, name string, ports []uint16, selector map[string]strin
Selector: selector,
Ports: svcPorts,
},
}, nil
}
}

func serviceName(step *types.Step) (string, error) {
Expand All @@ -69,10 +69,7 @@ func startService(ctx context.Context, engine *kube, step *types.Step) (*v1.Serv
StepLabel: podName,
}

svc, err := mkService(engine.config.Namespace, name, step.Ports, selector)
if err != nil {
return nil, err
}
svc := mkService(engine.config.Namespace, name, step.Ports, selector)

return engine.client.CoreV1().Services(engine.config.Namespace).Create(ctx, svc, metav1.CreateOptions{})
}
Expand Down
2 changes: 1 addition & 1 deletion pipeline/backend/kubernetes/service_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ func TestService(t *testing.T) {
}
}`

s, _ := mkService("foo", "bar", []uint16{1, 2, 3}, map[string]string{"step": "baz"})
s := mkService("foo", "bar", []uint16{1, 2, 3}, map[string]string{"step": "baz"})
j, err := json.Marshal(s)
assert.NoError(t, err)
assert.JSONEq(t, expected, string(j))
Expand Down
7 changes: 6 additions & 1 deletion pipeline/frontend/metadata/environment.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@ import (
"regexp"
"strconv"
"strings"

"github.com/rs/zerolog/log"
)

var (
Expand Down Expand Up @@ -136,7 +138,10 @@ func (m *Metadata) Environ() map[string]string {
params["CI_PIPELINE_FILES"] = "[]"
} else if len(m.Curr.Commit.ChangedFiles) <= maxChangedFiles {
// we have to use json, as other separators like ;, or space are valid filename chars
changedFiles, _ := json.Marshal(m.Curr.Commit.ChangedFiles)
changedFiles, err := json.Marshal(m.Curr.Commit.ChangedFiles)
if err != nil {
log.Error().Err(err).Msg("marshal changed files")
}
params["CI_PIPELINE_FILES"] = string(changedFiles)
}

Expand Down
2 changes: 1 addition & 1 deletion server/forge/configFetcher.go
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ func (cf *configFetcher) Fetch(ctx context.Context) (files []*types.FileMeta, er

// try to fetch 3 times
for i := 0; i < 3; i++ {
files, err = cf.fetch(ctx, time.Second*cf.timeout, strings.TrimSpace(cf.configPath))
files, err = cf.fetch(ctx, cf.timeout, strings.TrimSpace(cf.configPath))
if err != nil {
log.Trace().Err(err).Msgf("%d. try failed", i+1)
}
Expand Down
2 changes: 1 addition & 1 deletion server/forge/gitea/helper.go
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ func pipelineFromPush(hook *pushHook) *model.Pipeline {
fixMalformedAvatar(hook.Sender.AvatarURL),
)

message := ""
var message string
link := hook.Compare
if len(hook.Commits) > 0 {
message = hook.Commits[0].Message
Expand Down
15 changes: 5 additions & 10 deletions server/forge/github/convert_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -232,8 +232,7 @@ func Test_helper(t *testing.T) {
from.Sender.Login = github.String("octocat")
from.Sender.AvatarURL = github.String("https://avatars1.githubusercontent.com/u/583231")

_, pipeline, err := parseDeployHook(from)
g.Assert(err).IsNil()
_, pipeline := parseDeployHook(from)
g.Assert(pipeline.Event).Equal(model.EventDeploy)
g.Assert(pipeline.Branch).Equal("main")
g.Assert(pipeline.Ref).Equal("refs/heads/main")
Expand All @@ -255,8 +254,7 @@ func Test_helper(t *testing.T) {
from.HeadCommit.ID = github.String("f72fc19")
from.Ref = github.String("refs/heads/main")

_, pipeline, err := parsePushHook(from)
g.Assert(err).IsNil()
_, pipeline := parsePushHook(from)
g.Assert(pipeline.Event).Equal(model.EventPush)
g.Assert(pipeline.Branch).Equal("main")
g.Assert(pipeline.Ref).Equal("refs/heads/main")
Expand All @@ -273,8 +271,7 @@ func Test_helper(t *testing.T) {
from := &github.PushEvent{}
from.Ref = github.String("refs/tags/v1.0.0")

_, pipeline, err := parsePushHook(from)
g.Assert(err).IsNil()
_, pipeline := parsePushHook(from)
g.Assert(pipeline.Event).Equal(model.EventTag)
g.Assert(pipeline.Ref).Equal("refs/tags/v1.0.0")
})
Expand All @@ -284,8 +281,7 @@ func Test_helper(t *testing.T) {
from.Ref = github.String("refs/tags/v1.0.0")
from.BaseRef = github.String("refs/heads/main")

_, pipeline, err := parsePushHook(from)
g.Assert(err).IsNil()
_, pipeline := parsePushHook(from)
g.Assert(pipeline.Event).Equal(model.EventTag)
g.Assert(pipeline.Branch).Equal("main")
})
Expand All @@ -295,8 +291,7 @@ func Test_helper(t *testing.T) {
from.Ref = github.String("refs/tags/v1.0.0")
from.BaseRef = github.String("refs/refs/main")

_, pipeline, err := parsePushHook(from)
g.Assert(err).IsNil()
_, pipeline := parsePushHook(from)
g.Assert(pipeline.Event).Equal(model.EventTag)
g.Assert(pipeline.Branch).Equal("refs/tags/v1.0.0")
})
Expand Down
18 changes: 9 additions & 9 deletions server/forge/github/parse.go
Original file line number Diff line number Diff line change
Expand Up @@ -61,11 +61,11 @@ func parseHook(r *http.Request, merge bool) (*github.PullRequest, *model.Repo, *

switch hook := payload.(type) {
case *github.PushEvent:
repo, pipeline, err := parsePushHook(hook)
return nil, repo, pipeline, err
repo, pipeline := parsePushHook(hook)
return nil, repo, pipeline, nil
case *github.DeploymentEvent:
repo, pipeline, err := parseDeployHook(hook)
return nil, repo, pipeline, err
repo, pipeline := parseDeployHook(hook)
return nil, repo, pipeline, nil
case *github.PullRequestEvent:
return parsePullHook(hook, merge)
default:
Expand All @@ -75,9 +75,9 @@ func parseHook(r *http.Request, merge bool) (*github.PullRequest, *model.Repo, *

// parsePushHook parses a push hook and returns the Repo and Pipeline details.
// If the commit type is unsupported nil values are returned.
func parsePushHook(hook *github.PushEvent) (*model.Repo, *model.Pipeline, error) {
func parsePushHook(hook *github.PushEvent) (*model.Repo, *model.Pipeline) {
if hook.Deleted != nil && *hook.Deleted {
return nil, nil, nil
return nil, nil
}

pipeline := &model.Pipeline{
Expand Down Expand Up @@ -110,12 +110,12 @@ func parsePushHook(hook *github.PushEvent) (*model.Repo, *model.Pipeline, error)
}
}

return convertRepoHook(hook.GetRepo()), pipeline, nil
return convertRepoHook(hook.GetRepo()), pipeline
}

// parseDeployHook parses a deployment and returns the Repo and Pipeline details.
// If the commit type is unsupported nil values are returned.
func parseDeployHook(hook *github.DeploymentEvent) (*model.Repo, *model.Pipeline, error) {
func parseDeployHook(hook *github.DeploymentEvent) (*model.Repo, *model.Pipeline) {
pipeline := &model.Pipeline{
Event: model.EventDeploy,
Commit: hook.GetDeployment().GetSHA(),
Expand All @@ -138,7 +138,7 @@ func parseDeployHook(hook *github.DeploymentEvent) (*model.Repo, *model.Pipeline
pipeline.Ref = fmt.Sprintf("refs/heads/%s", pipeline.Branch)
}

return convertRepo(hook.GetRepo()), pipeline, nil
return convertRepo(hook.GetRepo()), pipeline
}

// parsePullHook parses a pull request hook and returns the Repo and Pipeline
Expand Down
4 changes: 2 additions & 2 deletions server/grpc/filter.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ import (
"go.woodpecker-ci.org/woodpecker/v2/server/queue"
)

func createFilterFunc(agentFilter rpc.Filter) (queue.FilterFn, error) {
func createFilterFunc(agentFilter rpc.Filter) queue.FilterFn {
return func(task *model.Task) bool {
for taskLabel, taskLabelValue := range task.Labels {
// if a task label is empty it will be ignored
Expand All @@ -44,5 +44,5 @@ func createFilterFunc(agentFilter rpc.Filter) (queue.FilterFn, error) {
}
}
return true
}, nil
}
}
6 changes: 1 addition & 5 deletions server/grpc/filter_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -84,11 +84,7 @@ func TestCreateFilterFunc(t *testing.T) {

for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
fn, err := createFilterFunc(rpc.Filter{Labels: test.agentLabels})
if !assert.NoError(t, err) {
t.Fail()
}

fn := createFilterFunc(rpc.Filter{Labels: test.agentLabels})
assert.EqualValues(t, test.exp, fn(&test.task))
})
}
Expand Down
Loading

0 comments on commit 768fd71

Please sign in to comment.