Skip to content

Commit

Permalink
Enable golangci linter gomnd
Browse files Browse the repository at this point in the history
  • Loading branch information
xoxys committed Jan 13, 2024
1 parent b9c2c28 commit 33ce69d
Show file tree
Hide file tree
Showing 41 changed files with 214 additions and 155 deletions.
10 changes: 10 additions & 0 deletions .golangci.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -163,8 +163,18 @@ linters:
- gocritic
- nolintlint
- stylecheck
<<<<<<< HEAD:.golangci.yaml
- contextcheck
- forcetypeassert
=======
- gomnd

issues:
exclude-rules:
- path: 'cmd/agent/flags.go|cmd/server/flags.go|pipeline/backend/kubernetes/flags.go|_test.go'
linters:
- gomnd
>>>>>>> 5705bca74 (Enable golangci linter gomnd):.golangci.yml

run:
timeout: 15m
2 changes: 1 addition & 1 deletion agent/rpc/auth_client_grpc.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ func NewAuthGrpcClient(conn *grpc.ClientConn, agentToken string, agentID int64)
}

func (c *AuthClient) Auth() (string, int64, error) {
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) //nolint: gomnd
defer cancel()

req := &proto.AuthRequest{
Expand Down
4 changes: 2 additions & 2 deletions agent/rpc/client_grpc.go
Original file line number Diff line number Diff line change
Expand Up @@ -53,8 +53,8 @@ func (c *client) Close() error {

func (c *client) newBackOff() backoff.BackOff {
b := backoff.NewExponentialBackOff()
b.MaxInterval = 10 * time.Second
b.InitialInterval = 10 * time.Millisecond
b.MaxInterval = 10 * time.Second //nolint: gomnd
b.InitialInterval = 10 * time.Millisecond //nolint: gomnd
return b
}

Expand Down
4 changes: 2 additions & 2 deletions agent/runner.go
Original file line number Diff line number Diff line change
Expand Up @@ -158,15 +158,15 @@ func (r *Runner) Run(runnerCtx context.Context) error {

if canceled.IsSet() {
state.Error = ""
state.ExitCode = 137
state.ExitCode = pipeline.ExitCodeKilled
} else if err != nil {
pExitError := &pipeline.ExitError{}
switch {
case errors.As(err, &pExitError):
state.ExitCode = pExitError.Code
case errors.Is(err, pipeline.ErrCancel):
state.Error = ""
state.ExitCode = 137
state.ExitCode = pipeline.ExitCodeKilled
canceled.SetTo(true)
default:
state.ExitCode = 1
Expand Down
3 changes: 2 additions & 1 deletion cli/deploy/deploy.go
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,8 @@ func deploy(c *cli.Context) error {
}
}

env := c.Args().Get(2)
envArgIndex := 2
env := c.Args().Get(envArgIndex)
if env == "" {
return fmt.Errorf("please specify the target environment (i.e. production)")
}
Expand Down
10 changes: 5 additions & 5 deletions cli/exec/exec.go
Original file line number Diff line number Diff line change
Expand Up @@ -124,13 +124,13 @@ func execWithAxis(c *cli.Context, file, repoPath string, axis matrix.Axis) error

pipelineEnv := make(map[string]string)
for _, env := range c.StringSlice("env") {
envs := strings.SplitN(env, "=", 2)
pipelineEnv[envs[0]] = envs[1]
if oldVar, exists := environ[envs[0]]; exists {
before, after, _ := strings.Cut(env, "=")
pipelineEnv[before] = after
if oldVar, exists := environ[before]; exists {
// override existing values, but print a warning
log.Warn().Msgf("environment variable '%s' had value '%s', but got overwritten", envs[0], oldVar)
log.Warn().Msgf("environment variable '%s' had value '%s', but got overwritten", before, oldVar)
}
environ[envs[0]] = envs[1]
environ[before] = after
}

tmpl, err := envsubst.ParseFile(file)
Expand Down
6 changes: 3 additions & 3 deletions cli/internal/util.go
Original file line number Diff line number Diff line change
Expand Up @@ -107,11 +107,11 @@ func ParseRepo(client woodpecker.Client, str string) (repoID int64, err error) {
func ParseKeyPair(p []string) map[string]string {
params := map[string]string{}
for _, i := range p {
parts := strings.SplitN(i, "=", 2)
if len(parts) != 2 {
before, after, ok := strings.Cut(i, "=")
if !ok || before == "" {
continue
}
params[parts[0]] = parts[1]
params[before] = after
}
return params
}
6 changes: 3 additions & 3 deletions cli/pipeline/create.go
Original file line number Diff line number Diff line change
Expand Up @@ -61,9 +61,9 @@ func pipelineCreate(c *cli.Context) error {
variables := make(map[string]string)

for _, vaz := range c.StringSlice("var") {
sp := strings.SplitN(vaz, "=", 2)
if len(sp) == 2 {
variables[sp[0]] = sp[1]
before, after, _ := strings.Cut(vaz, "=")
if before != "" && after != "" {
variables[before] = after
}
}

Expand Down
1 change: 1 addition & 0 deletions cli/pipeline/list.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ import (
"go.woodpecker-ci.org/woodpecker/v2/cli/internal"
)

//nolint:gomnd
var pipelineListCmd = &cli.Command{
Name: "ls",
Usage: "show pipeline history",
Expand Down
6 changes: 4 additions & 2 deletions cli/pipeline/logs.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,12 +41,14 @@ func pipelineLogs(c *cli.Context) error {
return err
}

number, err := strconv.ParseInt(c.Args().Get(1), 10, 64)
numberArgIndex := 1
number, err := strconv.ParseInt(c.Args().Get(numberArgIndex), 10, 64)
if err != nil {
return err
}

step, err := strconv.ParseInt(c.Args().Get(2), 10, 64)
stepArgIndex := 2
step, err := strconv.ParseInt(c.Args().Get(stepArgIndex), 10, 64)
if err != nil {
return err
}
Expand Down
14 changes: 7 additions & 7 deletions cmd/agent/agent.go
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@ func run(c *cli.Context) error {

agentToken := c.String("grpc-token")
authClient := agentRpc.NewAuthGrpcClient(authConn, agentToken, agentConfig.AgentID)
authInterceptor, err := agentRpc.NewAuthInterceptor(authClient, 30*time.Minute)
authInterceptor, err := agentRpc.NewAuthInterceptor(authClient, 30*time.Minute) //nolint: gomnd
if err != nil {
return err
}
Expand Down Expand Up @@ -294,12 +294,12 @@ func stringSliceAddToMap(sl []string, m map[string]string) error {
m = make(map[string]string)
}
for _, v := range sl {
parts := strings.SplitN(v, "=", 2)
switch len(parts) {
case 2:
m[parts[0]] = parts[1]
case 1:
return fmt.Errorf("key '%s' does not have a value assigned", parts[0])
before, after, _ := strings.Cut(v, "=")
switch {
case before != "" && after != "":
m[before] = after
case after != "":
return fmt.Errorf("key '%s' does not have a value assigned", before)
default:
return fmt.Errorf("empty string in slice")
}
Expand Down
14 changes: 7 additions & 7 deletions cmd/agent/health.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,14 +39,14 @@ func initHealth() {

func handleHeartbeat(w http.ResponseWriter, _ *http.Request) {
if counter.Healthy() {
w.WriteHeader(200)
w.WriteHeader(http.StatusOK)
} else {
w.WriteHeader(500)
w.WriteHeader(http.StatusInternalServerError)
}
}

func handleVersion(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(200)
w.WriteHeader(http.StatusOK)
w.Header().Add("Content-Type", "text/json")
err := json.NewEncoder(w).Encode(versionResp{
Source: "https://github.com/woodpecker-ci/woodpecker",
Expand All @@ -59,9 +59,9 @@ func handleVersion(w http.ResponseWriter, _ *http.Request) {

func handleStats(w http.ResponseWriter, _ *http.Request) {
if counter.Healthy() {
w.WriteHeader(200)
w.WriteHeader(http.StatusOK)
} else {
w.WriteHeader(500)
w.WriteHeader(http.StatusInternalServerError)
}
w.Header().Add("Content-Type", "text/json")
if _, err := counter.WriteTo(w); err != nil {
Expand Down Expand Up @@ -92,8 +92,8 @@ func pinger(c *cli.Context) error {
return err
}
defer resp.Body.Close()
if resp.StatusCode != 200 {
return fmt.Errorf("agent returned non-200 status code")
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("agent returned non-http.StatusOK status code")
}
return nil
}
8 changes: 4 additions & 4 deletions pipeline/backend/kubernetes/kubernetes.go
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,8 @@ import (

const (
EngineName = "kubernetes"
// TODO 5 seconds is against best practice, k3s didn't work otherwise
defaultResyncDuration = 5 * time.Second
)

var defaultDeleteOptions = newDefaultDeleteOptions()
Expand Down Expand Up @@ -234,8 +236,7 @@ func (e *kube) WaitStep(ctx context.Context, step *types.Step, taskUUID string)
}
}

// TODO 5 seconds is against best practice, k3s didn't work otherwise
si := informers.NewSharedInformerFactoryWithOptions(e.client, 5*time.Second, informers.WithNamespace(e.config.Namespace))
si := informers.NewSharedInformerFactoryWithOptions(e.client, defaultResyncDuration, informers.WithNamespace(e.config.Namespace))
if _, err := si.Core().V1().Pods().Informer().AddEventHandler(
cache.ResourceEventHandlerFuncs{
UpdateFunc: podUpdated,
Expand Down Expand Up @@ -295,8 +296,7 @@ func (e *kube) TailStep(ctx context.Context, step *types.Step, taskUUID string)
}
}

// TODO 5 seconds is against best practice, k3s didn't work otherwise
si := informers.NewSharedInformerFactoryWithOptions(e.client, 5*time.Second, informers.WithNamespace(e.config.Namespace))
si := informers.NewSharedInformerFactoryWithOptions(e.client, defaultResyncDuration, informers.WithNamespace(e.config.Namespace))
if _, err := si.Core().V1().Pods().Informer().AddEventHandler(
cache.ResourceEventHandlerFuncs{
UpdateFunc: podUpdated,
Expand Down
33 changes: 33 additions & 0 deletions pipeline/const.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
// Copyright 2023 Woodpecker Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package pipeline

// StatusValue represent pipeline states woodpecker know
type StatusValue string // @name StatusValue

const (
StatusSkipped StatusValue = "skipped" // skipped as another step failed
StatusPending StatusValue = "pending" // pending to be executed
StatusRunning StatusValue = "running" // currently running
StatusSuccess StatusValue = "success" // successfully finished
StatusFailure StatusValue = "failure" // failed to finish (exit code != 0)
StatusKilled StatusValue = "killed" // killed by user
StatusError StatusValue = "error" // error with the config / while parsing / some other system problem
StatusBlocked StatusValue = "blocked" // waiting for approval
StatusDeclined StatusValue = "declined" // blocked and declined
StatusCreated StatusValue = "created" // created / internal use only
)

const ExitCodeKilled int = 137
6 changes: 3 additions & 3 deletions pipeline/frontend/metadata/drone_compatibility_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -112,11 +112,11 @@ DRONE_TARGET_BRANCH=main`
func convertListToEnvMap(t *testing.T, list string) map[string]string {
result := make(map[string]string)
for _, s := range strings.Split(list, "\n") {
ss := strings.SplitN(strings.TrimSpace(s), "=", 2)
if len(ss) != 2 {
before, after, _ := strings.Cut(strings.TrimSpace(s), "=")
if before == "" || after == "" {
t.Fatal("helper function got invalid test data")
}
result[ss[0]] = ss[1]
result[before] = after
}
return result
}
2 changes: 1 addition & 1 deletion pipeline/frontend/metadata/environment.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ func (m *Metadata) Environ() map[string]string {
)

branchParts := strings.Split(m.Curr.Commit.Refspec, ":")
if len(branchParts) == 2 {
if len(branchParts) == 2 { //nolint: gomnd
sourceBranch = branchParts[0]
targetBranch = branchParts[1]
}
Expand Down
8 changes: 1 addition & 7 deletions pipeline/frontend/yaml/types/base/map.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,13 +31,7 @@ func (s *SliceOrMap) UnmarshalYAML(unmarshal func(any) error) error {
for _, s := range sliceType {
if str, ok := s.(string); ok {
str := strings.TrimSpace(str)
keyValueSlice := strings.SplitN(str, "=", 2)

key := keyValueSlice[0]
val := ""
if len(keyValueSlice) == 2 {
val = keyValueSlice[1]
}
key, val, _ := strings.Cut(str, "=")
parts[key] = val
} else {
return fmt.Errorf("cannot unmarshal '%v' of type %T into a string value", s, s)
Expand Down
1 change: 1 addition & 0 deletions pipeline/frontend/yaml/types/volume.go
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,7 @@ func (v *Volumes) UnmarshalYAML(unmarshal func(any) error) error {
}
elts := strings.SplitN(name, ":", 3)
var vol *Volume
//nolint: gomnd
switch {
case len(elts) == 1:
vol = &Volume{
Expand Down
4 changes: 2 additions & 2 deletions server/api/login.go
Original file line number Diff line number Diff line change
Expand Up @@ -80,8 +80,8 @@ func HandleAuth(c *gin.Context) {
if server.Config.Permissions.Orgs.IsConfigured {
teams, terr := _forge.Teams(c, tmpuser)
if terr != nil || !server.Config.Permissions.Orgs.IsMember(teams) {
log.Error().Err(terr).Msgf("cannot verify team membership for %s", u.Login)
c.Redirect(303, server.Config.Server.RootPath+"/login?error=access_denied")
log.Error().Err(terr).Msgf("cannot verify team membership for %s.", u.Login)
c.Redirect(http.StatusSeeOther, server.Config.Server.RootPath+"/login?error=access_denied")
return
}
}
Expand Down
2 changes: 1 addition & 1 deletion server/api/registry.go
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ func GetRegistry(c *gin.Context) {
handleDBError(c, err)
return
}
c.JSON(200, registry.Copy())
c.JSON(http.StatusOK, registry.Copy())
}

// PostRegistry
Expand Down
1 change: 1 addition & 0 deletions server/cache/membership.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ type membershipCache struct {

// NewMembershipService creates a new membership service.
func NewMembershipService(f forge.Forge) MembershipService {
//nolint:gomnd
return &membershipCache{
ttl: 10 * time.Minute,
forge: f,
Expand Down
5 changes: 3 additions & 2 deletions server/forge/bitbucket/bitbucket.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ import (
const (
DefaultAPI = "https://api.bitbucket.org"
DefaultURL = "https://bitbucket.org"
pageSize = 100
)

// Opts are forge options for bitbucket
Expand Down Expand Up @@ -142,7 +143,7 @@ func (c *config) Refresh(ctx context.Context, user *model.User) (bool, error) {
func (c *config) Teams(ctx context.Context, u *model.User) ([]*model.Team, error) {
return shared_utils.Paginate(func(page int) ([]*model.Team, error) {
opts := &internal.ListWorkspacesOpts{
PageLen: 100,
PageLen: pageSize,
Page: page,
Role: "member",
}
Expand Down Expand Up @@ -191,7 +192,7 @@ func (c *config) Repos(ctx context.Context, u *model.User) ([]*model.Repo, error
workspaces, err := shared_utils.Paginate(func(page int) ([]*internal.Workspace, error) {
resp, err := client.ListWorkspaces(&internal.ListWorkspacesOpts{
Page: page,
PageLen: 100,
PageLen: pageSize,
Role: "member",
})
if err != nil {
Expand Down
Loading

0 comments on commit 33ce69d

Please sign in to comment.