Skip to content

Commit

Permalink
Add golangci-lint.
Browse files Browse the repository at this point in the history
  • Loading branch information
patrickdappollonio committed Nov 12, 2024
1 parent 6baa801 commit 83d968d
Show file tree
Hide file tree
Showing 10 changed files with 175 additions and 26 deletions.
26 changes: 26 additions & 0 deletions .github/workflows/testing.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
name: Go unit tests

on: [push, workflow_dispatch]

permissions:
checks: write
contents: read

jobs:
run-tests:
runs-on: ubuntu-latest
steps:
- name: Clone repository
uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Set up Go
uses: actions/setup-go@v5
with:
go-version-file: go.mod
- name: Run GolangCI-Lint
uses: golangci/golangci-lint-action@v6
with:
version: v1.60
- name: Test application
run: go test -short -v ./...
113 changes: 113 additions & 0 deletions .golangci.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
run:
tests: false
concurrency: 5
timeout: 3m

linters:
disable-all: true
enable:
- gosimple
- govet
- ineffassign
- staticcheck
- unused
- asasalint
- asciicheck
- bidichk
- bodyclose
- contextcheck
- decorder
- dogsled
- dupl
- dupword
- durationcheck
- errchkjson
- errname
- errorlint
- exhaustive
- copyloopvar
- forcetypeassert
- ginkgolinter
- gocheckcompilerdirectives
- gochecksumtype
- gocritic
- gocyclo
- gofmt
- gofumpt
- goheader
- goimports
- gomodguard
- goprintffuncname
- gosec
- gosmopolitan
- grouper
- importas
- ireturn
- loggercheck
- makezero
- mirror
- misspell
- musttag
- nakedret
- nilerr
- nilnil
- noctx
- nolintlint
- nonamedreturns
- nosprintfhostport
- paralleltest
- perfsprint
- prealloc
- predeclared
- promlinter
- protogetter
- reassign
- revive
- rowserrcheck
- sloglint
- spancheck
- sqlclosecheck
- stylecheck
- tenv
- testableexamples
- testifylint
- testpackage
- thelper
- tparallel
- unconvert
- unparam
- usestdlibvars
- wastedassign
- whitespace
- wrapcheck
- zerologlint

linters-settings:
perfsprint:
int-conversion: false
err-error: false
errorf: true
sprintf1: true
strconcat: false

ireturn:
allow:
- ssh.PublicKey
- tea.Model
- error

gosec:
confidence: medium
excludes:
- G107 # Potential HTTP request made with variable url: these are often false positives or intentional
- G110 # Decompression bombs: we can check these manually when submitting code
- G306 # Poor file permissions used when creating a directory: we can check these manually when submitting code
- G404 # Use of weak random number generator (math/rand instead of crypto/rand): we can live with these

stylecheck:
checks:
- "all"
- "-ST1003" # this is covered by a different linter

gocyclo:
min-complexity: 60
2 changes: 1 addition & 1 deletion cmd/destroy.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ func getDestroyCommand() *cobra.Command {
Use: "destroy",
Short: "remove colony deployment from your host",
Long: `remove colony deployment from your host`,
RunE: func(cmd *cobra.Command, args []string) error {
RunE: func(cmd *cobra.Command, _ []string) error {
ctx := cmd.Context()
log := logger.New(logger.Debug)

Expand Down
8 changes: 4 additions & 4 deletions cmd/init.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ func getInitCommand() *cobra.Command {
Use: "init",
Short: "initialize colony on your host to provision in your data center",
Long: `initialize colony on your host to provision in your data center`,
RunE: func(cmd *cobra.Command, args []string) error {
RunE: func(cmd *cobra.Command, _ []string) error {
log := logger.New(logger.Debug)
ctx := cmd.Context()

Expand All @@ -36,8 +36,8 @@ func getInitCommand() *cobra.Command {
apiKey = os.Getenv("COLONY_API_KEY")
}

colonyApi := colony.New(apiURL, apiKey)
if err := colonyApi.ValidateAPIKey(ctx); err != nil {
colonyAPI := colony.New(apiURL, apiKey)
if err := colonyAPI.ValidateAPIKey(ctx); err != nil {
return fmt.Errorf("error validating colony api key: %q %w \n visit https://colony.konstruct.io to get a valid api key", apiKey, err)
}

Expand Down Expand Up @@ -110,7 +110,7 @@ func getInitCommand() *cobra.Command {
Namespace: "tink-system",
},
Data: map[string][]byte{
"kubeconfig": []byte(k8sconfig),
"kubeconfig": k8sconfig,
},
}

Expand Down
3 changes: 1 addition & 2 deletions cmd/version.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,8 @@ func getVersionCommand() *cobra.Command {
Use: "version",
Short: "print the version for colony cli",
Long: `print the version for colony cli`,
RunE: func(cmd *cobra.Command, args []string) error {
RunE: func(_ *cobra.Command, _ []string) error {
log := logger.New(logger.Debug)

log.Info("colony cli version: ", configs.Version)
return nil
},
Expand Down
2 changes: 1 addition & 1 deletion internal/colony/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ func New(baseURL, token string) *API {
MaxIdleConns: 100,
MaxConnsPerHost: 100,
MaxIdleConnsPerHost: 100,
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, //nolint:gosec
},
},
}
Expand Down
7 changes: 4 additions & 3 deletions internal/docker/docker.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package docker

import (
"context"
"errors"
"fmt"
"html/template"
"io"
Expand All @@ -20,7 +21,7 @@ import (
"github.com/konstructio/colony/internal/logger"
)

var ErrK3sContainerNotFound = fmt.Errorf("colony k3s container not found")
var ErrK3sContainerNotFound = errors.New("colony k3s container not found")

type Client struct {
cli *client.Client
Expand All @@ -45,7 +46,7 @@ func New(logger *logger.Logger) (*Client, error) {
}

func (c *Client) Close() error {
return c.cli.Close()
return c.cli.Close() //nolint:wrapcheck // exposing the close to upstream callers
}

func getColonyK3sContainer(ctx context.Context, c *Client) (*types.Container, error) {
Expand Down Expand Up @@ -119,7 +120,7 @@ func (c *Client) CreateColonyK3sContainer(ctx context.Context, loadBalancerIP, l
return fmt.Errorf("%q container already exists. please remove before continuing or run `colony destroy`", constants.ColonyK3sContainerName)
}

if err != nil && err != ErrK3sContainerNotFound {
if err != nil && !errors.Is(err, ErrK3sContainerNotFound) {
return fmt.Errorf("docker error: %w", err)
}

Expand Down
25 changes: 17 additions & 8 deletions internal/download/download.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,28 +5,37 @@ import (
"io"
"net/http"
"os"
"time"
)

func FileFromURL(url, filename string) error {
var client = &http.Client{
Transport: &http.Transport{
Proxy: http.ProxyFromEnvironment,
ResponseHeaderTimeout: 10 * time.Second,
ExpectContinueTimeout: 10 * time.Second,
},
}

func FileFromURL(url, filename string) error {
out, err := os.Create(filename)
if err != nil {
return err
return fmt.Errorf("failed to create file %q: %w", filename, err)
}
defer out.Close()

resp, err := http.Get(url)
resp, err := client.Get(url) //nolint:noctx // the client is already configured with a timeout
if err != nil {
return err
return fmt.Errorf("failed to download file: %w", err)
}
defer resp.Body.Close()

if resp.StatusCode != http.StatusOK {
return fmt.Errorf("failed to download file: %s", resp.Status)
return fmt.Errorf("failed to download file: got non-200 status code: %s", resp.Status)
}

_, err = io.Copy(out, resp.Body)
if _, err := io.Copy(out, resp.Body); err != nil {
return fmt.Errorf("failed to write file: %w", err)
}

// Copy returns err == nil..
return err
return nil
}
1 change: 1 addition & 0 deletions internal/exec/fs.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ func DeleteFile(location string) error {
}

func ReadFilesInDir(dir string) ([]string, error) {
//nolint:prealloc // We don't know the number of files in the directory
var templateFiles []string

// Open the directory
Expand Down
14 changes: 7 additions & 7 deletions internal/k8s/k8s.go
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,6 @@ func (c *Client) CreateAPIKeySecret(ctx context.Context, apiKey string) error {
}

func (c *Client) PatchClusterRole(ctx context.Context, clusterRoleName string, clusterRolePatchBytes []byte) error {

updatedRole, err := c.clientSet.RbacV1().ClusterRoles().Patch(
ctx,
clusterRoleName,
Expand All @@ -117,7 +116,6 @@ func (c *Client) PatchClusterRole(ctx context.Context, clusterRoleName string, c
}

func (c *Client) CreateSecret(ctx context.Context, secret *v1.Secret) error {

s, err := c.clientSet.CoreV1().Secrets(secret.GetNamespace()).Create(ctx, secret, metav1.CreateOptions{})
if err != nil {
return fmt.Errorf("error creating secret: %w", err)
Expand All @@ -129,7 +127,6 @@ func (c *Client) CreateSecret(ctx context.Context, secret *v1.Secret) error {
}

func (c *Client) CreateConfigMap(ctx context.Context, configMap *v1.ConfigMap) error {

_, err := c.clientSet.CoreV1().ConfigMaps(configMap.GetNamespace()).Create(ctx, configMap, metav1.CreateOptions{})
if err != nil {
return fmt.Errorf("error creating ConfigMap: %w", err)
Expand All @@ -141,7 +138,6 @@ func (c *Client) CreateConfigMap(ctx context.Context, configMap *v1.ConfigMap) e
}

func (c *Client) CreateJob(ctx context.Context, job *batchv1.Job) error {

job, err := c.clientSet.BatchV1().Jobs(job.GetNamespace()).Create(ctx, job, metav1.CreateOptions{})
if err != nil {
return fmt.Errorf("error creating Job: %w", err)
Expand Down Expand Up @@ -181,11 +177,16 @@ func (c *Client) ApplyManifests(ctx context.Context, manifests []string) error {
retryErr := retry.RetryOnConflict(retry.DefaultRetry, func() error {
existingObj, getErr := c.dynamic.Resource(gvr).Namespace(obj.GetNamespace()).Get(ctx, obj.GetName(), metav1.GetOptions{})
if getErr != nil {
return getErr
return fmt.Errorf("error getting existing resource: %w", getErr)
}

obj.SetResourceVersion(existingObj.GetResourceVersion())
_, err := c.dynamic.Resource(gvr).Namespace(obj.GetNamespace()).Update(ctx, &obj, metav1.UpdateOptions{})
return err
if err != nil {
return fmt.Errorf("error updating resource: %w", err)
}

return nil
})

if retryErr != nil {
Expand Down Expand Up @@ -268,7 +269,6 @@ func (c *Client) ReturnDeploymentObject(ctx context.Context, matchLabel string,
var deployment *appsv1.Deployment

err := wait.PollUntilContextTimeout(ctx, 15*time.Second, time.Duration(timeoutSeconds)*time.Second, true, func(ctx context.Context) (bool, error) {

deployments, err := c.clientSet.AppsV1().Deployments(namespace).List(ctx, metav1.ListOptions{
LabelSelector: fmt.Sprintf("%s=%s", matchLabel, matchLabelValue),
})
Expand Down

0 comments on commit 83d968d

Please sign in to comment.