Skip to content

Commit

Permalink
chore: add linters (#190)
Browse files Browse the repository at this point in the history
  • Loading branch information
remyleone authored Aug 27, 2024
1 parent 74a65bc commit e8efd72
Show file tree
Hide file tree
Showing 16 changed files with 223 additions and 151 deletions.
98 changes: 81 additions & 17 deletions .golangci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,9 @@ issues:
- lll
source: "^//go:generate "

exclude-files:
- ".*\\.hcl2spec\\.go$"

# Maximum issues count per one linter. Set to 0 to disable. Default is 50.
max-issues-per-linter: 0

Expand All @@ -27,14 +30,77 @@ issues:
linters:
disable-all: true
enable:
- errcheck
- goimports
- gosimple
- govet
- ineffassign
- staticcheck
- unconvert
- unused
- asasalint # check for pass []any as any in variadic func(...any) [fast: false, auto-fix: false]
- asciicheck # Simple linter to check that your code does not contain non-ASCII identifiers [fast: true, auto-fix: false]
- bidichk # Checks for dangerous unicode character sequences [fast: true, auto-fix: false]
- bodyclose # checks whether HTTP response body is closed successfully [fast: false, auto-fix: false]
- canonicalheader # canonicalheader checks whether net/http.Header uses canonical header [fast: false, auto-fix: false]
- containedctx # containedctx is a linter that detects struct contained context.Context field [fast: true, auto-fix: false]
- contextcheck # check the function whether use a non-inherited context [fast: false, auto-fix: false]
- copyloopvar # copyloopvar is a linter detects places where loop variables are copied [fast: true, auto-fix: false]
- decorder # check declaration order and count of types, constants, variables and functions [fast: true, auto-fix: false]
- dogsled # Checks assignments with too many blank identifiers (e.g. x, _, _, _, := f()) [fast: true, auto-fix: false]
- dupword # checks for duplicate words in the source code [fast: true, auto-fix: true]
- durationcheck # check for two durations multiplied together [fast: false, auto-fix: false]
- errcheck # Errcheck is a program for checking for unchecked errors in go programs. These unchecked errors can be critical bugs in some cases [fast: false, auto-fix: false]
- errchkjson # Checks types passed to the json encoding functions. Reports unsupported types and optionally reports occasions, where the check for the returned error can be omitted. [fast: false, auto-fix: false]
- errname # Checks that sentinel errors are prefixed with the `Err` and error types are suffixed with the `Error`. [fast: false, auto-fix: false]
- forbidigo # Forbids identifiers [fast: true, auto-fix: false]
- gci # Gci controls golang package import order and makes it always deterministic. [fast: true, auto-fix: false]
- gocheckcompilerdirectives # Checks that go compiler directive comments (//go:) are valid. [fast: true, auto-fix: false]
- gochecksumtype # Run exhaustiveness checks on Go "sum types" [fast: false, auto-fix: false]
- goconst # Finds repeated strings that could be replaced by a constant [fast: true, auto-fix: false]
- gocritic # Provides diagnostics that check for bugs, performance and style issues. [fast: false, auto-fix: false]
- gocyclo # Computes and checks the cyclomatic complexity of functions [fast: true, auto-fix: false]
- gofmt # Gofmt checks whether code was gofmt-ed. By default this tool runs with -s option to check for code simplification [fast: true, auto-fix: true]
- gofumpt # Gofumpt checks whether code was gofumpt-ed. [fast: true, auto-fix: true]
- goheader # Checks is file header matches to pattern [fast: true, auto-fix: false]
- goimports # In addition to fixing imports, goimports also formats your code in the same style as gofmt. [fast: true, auto-fix: true]
- gomodguard # Allow and block list linter for direct Go module dependencies. This is different from depguard where there are different block types for example version constraints and module recommendations. [fast: true, auto-fix: false]
- goprintffuncname # Checks that printf-like functions are named with `f` at the end [fast: true, auto-fix: false]
- gosec #(gas): Inspects source code for security problems [fast: false, auto-fix: false]
- gosimple #(megacheck): Linter for Go source code that specializes in simplifying a code [fast: false, auto-fix: false]
- govet #(vet, vetshadow): Vet examines Go source code and reports suspicious constructs, such as Printf calls whose arguments do not align with the format string [fast: false, auto-fix: false]
- grouper # An analyzer to analyze expression groups. [fast: true, auto-fix: false]
- importas # Enforces consistent import aliases [fast: false, auto-fix: false]
- ineffassign # Detects when assignments to existing variables are not used [fast: true, auto-fix: false]
- intrange # intrange is a linter to find places where for loops could make use of an integer range. [fast: true, auto-fix: false]
- ireturn # Accept Interfaces, Return Concrete Types [fast: false, auto-fix: false]
- loggercheck # (logrlint): Checks key value pairs for common logger libraries (kitlog,klog,logr,zap). [fast: false, auto-fix: false]
- makezero # Finds slice declarations with non-zero initial length [fast: false, auto-fix: false]
- mirror # reports wrong mirror patterns of bytes/strings usage [fast: false, auto-fix: false]
- misspell # Finds commonly misspelled English words in comments [fast: true, auto-fix: true]
- musttag # enforce field tags in (un)marshaled structs [fast: false, auto-fix: false]
- nakedret # Finds naked returns in functions greater than a specified function length [fast: true, auto-fix: false]
- nilerr # Finds the code that returns nil even if it checks that the error is not nil. [fast: false, auto-fix: false]
- noctx # noctx finds sending http request without context.Context [fast: false, auto-fix: false]
- nolintlint # Reports ill-formed or insufficient nolint directives [fast: true, auto-fix: false]
- nosprintfhostport # Checks for misuse of Sprintf to construct a host with port in a URL. [fast: true, auto-fix: false]
- perfsprint # Checks that fmt.Sprintf can be replaced with a faster alternative. [fast: false, auto-fix: false]
- prealloc # Finds slice declarations that could potentially be pre-allocated [fast: true, auto-fix: false]
- predeclared # find code that shadows one of Go's predeclared identifiers [fast: true, auto-fix: false]
- promlinter # Check Prometheus metrics naming via promlint [fast: true, auto-fix: false]
- protogetter # Reports direct reads from proto message fields when getters should be used [fast: false, auto-fix: true]
- reassign # Checks that package variables are not reassigned [fast: false, auto-fix: false]
- revive # Fast, configurable, extensible, flexible, and beautiful linter for Go. Drop-in replacement of golint. [fast: false, auto-fix: false]
- rowserrcheck # checks whether Err of rows is checked successfully [fast: false, auto-fix: false]
- sloglint # ensure consistent code style when using log/slog [fast: false, auto-fix: false]
- sqlclosecheck # Checks that sql.Rows and sql.Stmt are closed. [fast: false, auto-fix: false]
- staticcheck #(megacheck): Staticcheck is a go vet on steroids, applying a ton of static analysis checks [fast: false, auto-fix: false]
- stylecheck # Stylecheck is a replacement for golint [fast: false, auto-fix: false]
- tagliatelle # Checks the struct tags. [fast: true, auto-fix: false]
- tenv # tenv is analyzer that detects using os.Setenv instead of t.Setenv since Go1.17 [fast: false, auto-fix: false]
- testifylint # Checks usage of github.com/stretchr/testify. [fast: false, auto-fix: false]
- testpackage # linter that makes you use a separate _test package [fast: true, auto-fix: false]
- thelper # thelper detects golang test helpers without t.Helper() call and checks the consistency of test helpers [fast: false, auto-fix: false]
- tparallel # tparallel detects inappropriate usage of t.Parallel() method in your Go test codes [fast: false, auto-fix: false]
- typecheck # Like the front-end of a Go compiler, parses and type-checks Go code [fast: false, auto-fix: false]
- unconvert # Remove unnecessary type conversions [fast: false, auto-fix: false]
- unused #(megacheck): Checks Go code for unused constants, variables, functions and types [fast: false, auto-fix: false]
- usestdlibvars # A linter that detect the possibility to use variables/constants from the Go standard library. [fast: true, auto-fix: false]
- wastedassign # wastedassign finds wasted assignment statements. [fast: false, auto-fix: false]
- whitespace # Tool for detection of leading and trailing whitespace [fast: true, auto-fix: true]
- zerologlint # Detects the wrong usage of `zerolog` that a user forgets to dispatch with `Send` or `Msg` [fast: false, auto-fix: false]
fast: true

# options for analysis running
Expand Down Expand Up @@ -72,7 +138,7 @@ run:
# no need to include all autogenerated files, we confidently recognize
# autogenerated files. If it's not please let us know.
skip-files:
- ".*\\.hcl2spec\\.go$"

# - lib/bad.go

# by default isn't set. If set we pass it to "go list -mod={option}". From "go help modules":
Expand All @@ -85,11 +151,10 @@ run:
# the dependency descriptions in go.mod.
# modules-download-mode: vendor


# output configuration options
output:
# colored-line-number|line-number|json|tab|checkstyle|code-climate, default is "colored-line-number"
format: colored-line-number
formats: colored-line-number

# print lines of code with issue, default is true
print-issued-lines: true
Expand All @@ -100,10 +165,9 @@ output:
# make issues output unique by line, default is true
uniq-by-line: true


# all available settings of specific linters
linters-settings:
errcheck:
errcheck:
# report about not checking of errors in type assetions: `a := b.(MyStruct)`;
# default is false: such cases aren't reported by default.
check-type-assertions: false
Expand All @@ -115,8 +179,8 @@ linters-settings:
# [deprecated] comma-separated list of pairs of the form pkg:regex
# the regex is used to ignore names within pkg. (default "fmt:.*").
# see https://github.com/kisielk/errcheck#the-deprecated-method for details
ignore: fmt:.*,io/ioutil:^Read.*,io:Close
exclude-functions: fmt:.*,io/ioutil:^Read.*,io:Close

# path to a file containing a list of functions to exclude from checking
# see https://github.com/kisielk/errcheck#excluding-functions for details
#exclude: /path/to/file.txt
gosec:
excludes:
- G115
36 changes: 18 additions & 18 deletions builder/scaleway/artifact.go
Original file line number Diff line number Diff line change
Expand Up @@ -22,49 +22,49 @@ func (snap ArtifactSnapshot) String() string {

type Artifact struct {
// The name of the image
imageName string
ImageName string

// The ID of the image
imageID string
ImageID string

// Snapshots used by the generated image
snapshots []ArtifactSnapshot
Snapshots []ArtifactSnapshot

// The name of the zone
zoneName string
ZoneName string

// The client for making API calls
client *scw.Client
// The Client for making API calls
Client *scw.Client

// StateData should store data such as GeneratedData
// to be shared with post-processors
StateData map[string]interface{}
}

func (*Artifact) BuilderId() string {
return BuilderId
func (*Artifact) BuilderId() string { //nolint:revive,stylecheck
return BuilderID
}

func (*Artifact) Files() []string {
// No files with Scaleway
return nil
}

func (a *Artifact) Id() string {
return fmt.Sprintf("%s:%s", a.zoneName, a.imageID)
func (a *Artifact) Id() string { //nolint:revive,stylecheck
return fmt.Sprintf("%s:%s", a.ZoneName, a.ImageID)
}

func (a *Artifact) String() string {
return fmt.Sprintf("An image was created: '%v' (ID: %v) in zone '%v' based on snapshots %v",
a.imageName, a.imageID, a.zoneName, a.snapshots)
a.ImageName, a.ImageID, a.ZoneName, a.Snapshots)
}

func (a *Artifact) State(name string) interface{} {
if name == registryimage.ArtifactStateURI {
img, err := registryimage.FromArtifact(a,
registryimage.WithID(a.imageID),
registryimage.WithID(a.ImageID),
registryimage.WithProvider("scaleway"),
registryimage.WithRegion(a.zoneName),
registryimage.WithRegion(a.ZoneName),
)
if err != nil {
log.Printf("error when creating hcp registry image %v", err)
Expand All @@ -76,18 +76,18 @@ func (a *Artifact) State(name string) interface{} {
}

func (a *Artifact) Destroy() error {
instanceAPI := instance.NewAPI(a.client)
instanceAPI := instance.NewAPI(a.Client)

log.Printf("Destroying image: %s (%s)", a.imageID, a.imageName)
log.Printf("Destroying image: %s (%s)", a.ImageID, a.ImageName)
err := instanceAPI.DeleteImage(&instance.DeleteImageRequest{
ImageID: a.imageID,
ImageID: a.ImageID,
})
if err != nil {
return err
}

log.Printf("Destroying snapshots: %v", a.snapshots)
for _, snapshot := range a.snapshots {
log.Printf("Destroying snapshots: %v", a.Snapshots)
for _, snapshot := range a.Snapshots {
err = instanceAPI.DeleteSnapshot(&instance.DeleteSnapshotRequest{
SnapshotID: snapshot.ID,
})
Expand Down
23 changes: 13 additions & 10 deletions builder/scaleway/artifact_test.go
Original file line number Diff line number Diff line change
@@ -1,31 +1,33 @@
package scaleway
package scaleway_test

import (
"testing"

packersdk "github.com/hashicorp/packer-plugin-sdk/packer"
"github.com/scaleway/packer-plugin-scaleway/builder/scaleway"
)

func TestArtifact_Impl(t *testing.T) {
var raw interface{}
raw = &Artifact{}
raw = &scaleway.Artifact{}
if _, ok := raw.(packersdk.Artifact); !ok {
t.Fatalf("Artifact should be artifact")
}
}

func TestArtifactId(t *testing.T) {
generatedData := make(map[string]interface{})
a := &Artifact{
a := &scaleway.Artifact{
"packer-foobar-image",
"cc586e45-5156-4f71-b223-cf406b10dd1d",
[]ArtifactSnapshot{{
[]scaleway.ArtifactSnapshot{{
"packer-foobar-snapshot",
"cc586e45-5156-4f71-b223-cf406b10dd1c",
}},
"ams1",
nil,
generatedData}
generatedData,
}
expected := "ams1:cc586e45-5156-4f71-b223-cf406b10dd1d"

if a.Id() != expected {
Expand All @@ -35,10 +37,10 @@ func TestArtifactId(t *testing.T) {

func TestArtifactString(t *testing.T) {
generatedData := make(map[string]interface{})
a := &Artifact{
a := &scaleway.Artifact{
"packer-foobar-image",
"cc586e45-5156-4f71-b223-cf406b10dd1d",
[]ArtifactSnapshot{
[]scaleway.ArtifactSnapshot{
{
"cc586e45-5156-4f71-b223-cf406b10dd1c",
"packer-foobar-snapshot",
Expand All @@ -50,7 +52,8 @@ func TestArtifactString(t *testing.T) {
},
"ams1",
nil,
generatedData}
generatedData,
}
expected := "An image was created: 'packer-foobar-image' (ID: cc586e45-5156-4f71-b223-cf406b10dd1d) in zone 'ams1' based on snapshots [(packer-foobar-snapshot: cc586e45-5156-4f71-b223-cf406b10dd1c) (packer-foobar-snapshot2: cc586e45-5156-4f71-b223-cf406b10dd1e)]"

if a.String() != expected {
Expand All @@ -60,7 +63,7 @@ func TestArtifactString(t *testing.T) {

func TestArtifactState_StateData(t *testing.T) {
expectedData := "this is the data"
artifact := &Artifact{
artifact := &scaleway.Artifact{
StateData: map[string]interface{}{"state_data": expectedData},
}

Expand All @@ -77,7 +80,7 @@ func TestArtifactState_StateData(t *testing.T) {
}

// Nil StateData should not fail and should return nil
artifact = &Artifact{}
artifact = &scaleway.Artifact{}
result = artifact.State("key")
if result != nil {
t.Fatalf("Bad: State should be nil for nil StateData")
Expand Down
Loading

0 comments on commit e8efd72

Please sign in to comment.