Update linter settings and fix warnings

This commit is contained in:
Daniel 2022-02-02 14:58:27 +01:00
parent 22c59c50cc
commit 6650fb3b19
26 changed files with 102 additions and 81 deletions

View file

@ -54,7 +54,14 @@ jobs:
- name: Run golint - name: Run golint
run: ./golint -set_exit_status -min_confidence 1.0 ./... run: ./golint -set_exit_status -min_confidence 1.0 ./...
# TODO: Enable gofmt again when all environments are up to date. # golint is run (sufficiently; with excludes) as a part of golangci-lint.
# - name: Install golint
# run: bash -c "GOBIN=$(pwd) go get -u golang.org/x/lint/golint"
#
# - name: Run golint
# run: ./golint -set_exit_status -min_confidence 1.0 ./...
# gofmt is run (sufficiently; with excludes) as a part of golangci-lint.
# - name: Run gofmt # - name: Run gofmt
# run: bash -c 'test -z "$(gofmt -s -l .)"' # run: bash -c 'test -z "$(gofmt -s -l .)"'

View file

@ -33,6 +33,9 @@ linters:
- wsl - wsl
linters-settings: linters-settings:
revive:
# See https://github.com/mgechev/revive#available-rules for details.
enable-all-rules: true
gci: gci:
# put imports beginning with prefix after 3rd-party packages; # put imports beginning with prefix after 3rd-party packages;
# only support one prefix # only support one prefix
@ -43,3 +46,20 @@ linters-settings:
# might be left in the code accidentally and should be resolved before merging # might be left in the code accidentally and should be resolved before merging
keywords: keywords:
- FIXME - FIXME
gosec:
# To specify a set of rules to explicitly exclude.
# Available rules: https://github.com/securego/gosec#available-rules
excludes:
- G204 # Variables in commands.
- G304 # Variables in file paths.
- G505 # We need crypto/sha1 for non-security stuff. Using `nolint:` triggers another linter.
issues:
exclude-use-default: false
exclude-rules:
- text: "a blank import .*"
linters:
- golint
- text: "ST1000: at least one file in a package should have a package comment.*"
linters:
- stylecheck

View file

@ -41,7 +41,7 @@ func (c *Client) wsConnect() error {
case <-c.shutdownSignal: case <-c.shutdownSignal:
state.Error("") state.Error("")
} }
state.wsConn.Close() _ = state.wsConn.Close()
state.wg.Wait() state.wg.Wait()
return nil return nil

View file

@ -251,7 +251,7 @@ func (api *DatabaseAPI) shutdown(err error) error {
// Trigger shutdown. // Trigger shutdown.
close(api.shutdownSignal) close(api.shutdownSignal)
api.conn.Close() _ = api.conn.Close()
return nil return nil
} }

View file

@ -52,6 +52,6 @@ func TestMain(m *testing.M) {
fmt.Fprintf(os.Stderr, "failed to cleanly shutdown test: %s\n", err) fmt.Fprintf(os.Stderr, "failed to cleanly shutdown test: %s\n", err)
} }
// clean up and exit // clean up and exit
os.RemoveAll(tmpDir) _ = os.RemoveAll(tmpDir)
os.Exit(exitCode) os.Exit(exitCode)
} }

View file

@ -1,4 +1,4 @@
//nolint:goconst,errcheck //nolint:goconst
package config package config
import "testing" import "testing"
@ -83,7 +83,7 @@ func TestLayersSetters(t *testing.T) { //nolint:paralleltest
// reset // reset
options = make(map[string]*Option) options = make(map[string]*Option)
Register(&Option{ _ = Register(&Option{
Name: "name", Name: "name",
Key: "monkey", Key: "monkey",
Description: "description", Description: "description",
@ -93,7 +93,7 @@ func TestLayersSetters(t *testing.T) { //nolint:paralleltest
DefaultValue: "banana", DefaultValue: "banana",
ValidationRegex: "^(banana|water)$", ValidationRegex: "^(banana|water)$",
}) })
Register(&Option{ _ = Register(&Option{
Name: "name", Name: "name",
Key: "zebras/zebra", Key: "zebras/zebra",
Description: "description", Description: "description",
@ -103,7 +103,7 @@ func TestLayersSetters(t *testing.T) { //nolint:paralleltest
DefaultValue: []string{"black", "white"}, DefaultValue: []string{"black", "white"},
ValidationRegex: "^[a-z]+$", ValidationRegex: "^[a-z]+$",
}) })
Register(&Option{ _ = Register(&Option{
Name: "name", Name: "name",
Key: "elephant", Key: "elephant",
Description: "description", Description: "description",
@ -113,7 +113,7 @@ func TestLayersSetters(t *testing.T) { //nolint:paralleltest
DefaultValue: 2, DefaultValue: 2,
ValidationRegex: "", ValidationRegex: "",
}) })
Register(&Option{ _ = Register(&Option{
Name: "name", Name: "name",
Key: "hot", Key: "hot",
Description: "description", Description: "description",

View file

@ -36,7 +36,7 @@ func TestMain(m *testing.M) {
// Clean up the test directory. // Clean up the test directory.
// Do not defer, as we end this function with a os.Exit call. // Do not defer, as we end this function with a os.Exit call.
os.RemoveAll(testDir) _ = os.RemoveAll(testDir)
os.Exit(exitCode) os.Exit(exitCode)
} }

View file

@ -207,7 +207,7 @@ func parseAndOr(getSnippet func() (*snippet, error), remainingSnippets func() in
for { for {
if !expectingMore && rootCondition && remainingSnippets() == 0 { if !expectingMore && rootCondition && remainingSnippets() == 0 {
// advance snippetsPos by one, as it will be set back by 1 // advance snippetsPos by one, as it will be set back by 1
getSnippet() //nolint:errcheck _, _ = getSnippet()
if len(conditions) == 1 { if len(conditions) == 1 {
return conditions[0], nil return conditions[0], nil
} }

View file

@ -2,15 +2,6 @@ package record
import ( import (
"fmt" "fmt"
"io"
"time"
"unsafe"
)
var (
_ = unsafe.Sizeof(0)
_ = io.ReadFull
_ = time.Now()
) )
// GenCodeSize returns the size of the gencode marshalled byte slice. // GenCodeSize returns the size of the gencode marshalled byte slice.

View file

@ -45,7 +45,9 @@ func TestBadger(t *testing.T) {
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
defer os.RemoveAll(testDir) // clean up defer func() {
_ = os.RemoveAll(testDir) // clean up
}()
// start // start
db, err := NewBadger("test", testDir) db, err := NewBadger("test", testDir)

View file

@ -47,7 +47,9 @@ func TestBBolt(t *testing.T) {
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
defer os.RemoveAll(testDir) // clean up defer func() {
_ = os.RemoveAll(testDir) // clean up
}()
// start // start
db, err := NewBBolt("test", testDir) db, err := NewBBolt("test", testDir)

View file

@ -1,18 +1,6 @@
//nolint:nakedret,unconvert,gocognit,wastedassign,gofumpt //nolint:nakedret,unconvert,gocognit,wastedassign,gofumpt
package dsd package dsd
import (
"io"
"time"
"unsafe"
)
var (
_ = unsafe.Sizeof(0)
_ = io.ReadFull
_ = time.Now()
)
func (d *SimpleTestStruct) Size() (s uint64) { func (d *SimpleTestStruct) Size() (s uint64) {
{ {

View file

@ -101,7 +101,9 @@ func writeMetricsTo(ctx context.Context, url string) error {
if err != nil { if err != nil {
return err return err
} }
defer resp.Body.Close() defer func() {
_ = resp.Body.Close()
}()
// Check return status. // Check return status.
if resp.StatusCode >= 200 && resp.StatusCode <= 299 { if resp.StatusCode >= 200 && resp.StatusCode <= 299 {

View file

@ -120,5 +120,5 @@ func TestSubsystems(t *testing.T) { //nolint:paralleltest // Too much interferen
} }
// clean up and exit // clean up and exit
os.RemoveAll(tmpDir) _ = os.RemoveAll(tmpDir)
} }

View file

@ -58,7 +58,7 @@ func prep() error {
} }
var err error var err error
outputFile, err = os.OpenFile(os.Args[2], os.O_CREATE|os.O_WRONLY, 0o0644) outputFile, err = os.OpenFile(os.Args[2], os.O_CREATE|os.O_WRONLY, 0o0644) //nolint:gosec
if err != nil { if err != nil {
return fmt.Errorf("failed to open output file: %w", err) return fmt.Errorf("failed to open output file: %w", err)
} }
@ -106,13 +106,13 @@ func fortuna(_ context.Context) error {
bytesWritten += 64 bytesWritten += 64
if bytesWritten%1024 == 0 { if bytesWritten%1024 == 0 {
os.Stderr.WriteString(".") _, _ = os.Stderr.WriteString(".")
} }
if bytesWritten%65536 == 0 { if bytesWritten%65536 == 0 {
fmt.Fprintf(os.Stderr, "\n%d bytes written\n", bytesWritten) fmt.Fprintf(os.Stderr, "\n%d bytes written\n", bytesWritten)
} }
if bytesWritten >= outputSize { if bytesWritten >= outputSize {
os.Stderr.WriteString("\n") _, _ = os.Stderr.WriteString("\n")
break break
} }
} }
@ -145,7 +145,7 @@ func tickfeeder(ctx context.Context) error {
} }
bytesWritten += 8 bytesWritten += 8
if bytesWritten%1024 == 0 { if bytesWritten%1024 == 0 {
os.Stderr.WriteString(".") _, _ = os.Stderr.WriteString(".")
} }
if bytesWritten%65536 == 0 { if bytesWritten%65536 == 0 {
fmt.Fprintf(os.Stderr, "\n%d bytes written\n", bytesWritten) fmt.Fprintf(os.Stderr, "\n%d bytes written\n", bytesWritten)
@ -154,7 +154,7 @@ func tickfeeder(ctx context.Context) error {
} }
if bytesWritten >= outputSize { if bytesWritten >= outputSize {
os.Stderr.WriteString("\n") _, _ = os.Stderr.WriteString("\n")
break break
} }
} }

View file

@ -50,6 +50,6 @@ func TestMain(m *testing.M) {
fmt.Fprintf(os.Stderr, "failed to cleanly shutdown test: %s\n", err) fmt.Fprintf(os.Stderr, "failed to cleanly shutdown test: %s\n", err)
} }
// clean up and exit // clean up and exit
os.RemoveAll(tmpDir) _ = os.RemoveAll(tmpDir)
os.Exit(exitCode) os.Exit(exitCode)
} }

9
test
View file

@ -104,8 +104,6 @@ fi
# install # install
if [[ $install -eq 1 ]]; then if [[ $install -eq 1 ]]; then
echo "installing dependencies..." echo "installing dependencies..."
echo "$ go get -u golang.org/x/lint/golint"
go get -u golang.org/x/lint/golint
# TODO: update golangci-lint version regularly # TODO: update golangci-lint version regularly
echo "$ curl -sfL https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh | sh -s -- -b $(go env GOPATH)/bin v1.44.0" echo "$ curl -sfL https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh | sh -s -- -b $(go env GOPATH)/bin v1.44.0"
curl -sfL https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh | sh -s -- -b $(go env GOPATH)/bin v1.44.0 curl -sfL https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh | sh -s -- -b $(go env GOPATH)/bin v1.44.0
@ -122,12 +120,6 @@ if [[ $testonly -eq 0 ]]; then
echo "gofmt command not found" echo "gofmt command not found"
exit 1 exit 1
fi fi
if [[ $(which golint) == "" ]]; then
echo "golint command not found"
echo "install with: go get -u golang.org/x/lint/golint"
echo "or run: ./test install"
exit 1
fi
if [[ $(which golangci-lint) == "" ]]; then if [[ $(which golangci-lint) == "" ]]; then
echo "golangci-lint command not found" echo "golangci-lint command not found"
echo "install with: curl -sfL https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh | sh -s -- -b $(go env GOPATH)/bin vX.Y.Z" echo "install with: curl -sfL https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh | sh -s -- -b $(go env GOPATH)/bin vX.Y.Z"
@ -160,7 +152,6 @@ for package in $packages; do
echo "" echo ""
echo $package echo $package
if [[ $testonly -eq 0 ]]; then if [[ $testonly -eq 0 ]]; then
run golint -set_exit_status -min_confidence 1.0 $package
run go vet $package run go vet $package
run golangci-lint run $packagename run golangci-lint run $packagename
fi fi

View file

@ -45,7 +45,9 @@ func (reg *ResourceRegistry) fetchFile(ctx context.Context, client *http.Client,
if err != nil { if err != nil {
return err return err
} }
defer resp.Body.Close() defer func() {
_ = resp.Body.Close()
}()
// download and write file // download and write file
n, err := io.Copy(atomicFile, resp.Body) n, err := io.Copy(atomicFile, resp.Body)
@ -64,7 +66,7 @@ func (reg *ResourceRegistry) fetchFile(ctx context.Context, client *http.Client,
// set permissions // set permissions
if !onWindows { if !onWindows {
// TODO: only set executable files to 0755, set other to 0644 // TODO: only set executable files to 0755, set other to 0644
err = os.Chmod(rv.storagePath(), 0o0755) err = os.Chmod(rv.storagePath(), 0o0755) //nolint:gosec // See TODO above.
if err != nil { if err != nil {
log.Warningf("%s: failed to set permissions on downloaded file %s: %s", reg.Name, rv.storagePath(), err) log.Warningf("%s: failed to set permissions on downloaded file %s: %s", reg.Name, rv.storagePath(), err)
} }
@ -89,7 +91,9 @@ func (reg *ResourceRegistry) fetchData(ctx context.Context, client *http.Client,
if err != nil { if err != nil {
return nil, err return nil, err
} }
defer resp.Body.Close() defer func() {
_ = resp.Body.Close()
}()
// download and write file // download and write file
buf := bytes.NewBuffer(make([]byte, 0, resp.ContentLength)) buf := bytes.NewBuffer(make([]byte, 0, resp.ContentLength))
@ -135,7 +139,7 @@ func (reg *ResourceRegistry) makeRequest(ctx context.Context, client *http.Clien
// check return code // check return code
if resp.StatusCode != http.StatusOK { if resp.StatusCode != http.StatusOK {
resp.Body.Close() _ = resp.Body.Close()
return nil, "", fmt.Errorf("failed to fetch %q: %d %s", downloadURL, resp.StatusCode, resp.Status) return nil, "", fmt.Errorf("failed to fetch %q: %d %s", downloadURL, resp.StatusCode, resp.Status)
} }

View file

@ -92,7 +92,9 @@ func (file *File) Unpack(suffix string, unpacker Unpacker) (string, error) {
if err != nil { if err != nil {
return "", err return "", err
} }
defer f.Close() defer func() {
_ = f.Close()
}()
r, err := unpacker(f) r, err := unpacker(f)
if err != nil { if err != nil {

View file

@ -31,6 +31,6 @@ func TestMain(m *testing.M) {
ret := m.Run() ret := m.Run()
// teardown // teardown
os.RemoveAll(tmpDir) _ = os.RemoveAll(tmpDir)
os.Exit(ret) os.Exit(ret)
} }

View file

@ -117,7 +117,9 @@ func (res *Resource) unpackZipArchive() (err error) {
if err != nil { if err != nil {
return return
} }
defer archiveReader.Close() defer func() {
_ = archiveReader.Close()
}()
// Save all files to the tmp dir. // Save all files to the tmp dir.
for _, file := range archiveReader.File { for _, file := range archiveReader.File {
@ -161,14 +163,18 @@ func copyFromZipArchive(archiveFile *zip.File, dstPath string) error {
if err != nil { if err != nil {
return err return err
} }
defer fileReader.Close() defer func() {
_ = fileReader.Close()
}()
// Open destination file for writing. // Open destination file for writing.
dstFile, err := os.OpenFile(dstPath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, archiveFile.Mode()) dstFile, err := os.OpenFile(dstPath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, archiveFile.Mode())
if err != nil { if err != nil {
return err return err
} }
defer dstFile.Close() defer func() {
_ = dstFile.Close()
}()
// Copy full file from archive to dst. // Copy full file from archive to dst.
if _, err := io.CopyN(dstFile, fileReader, MaxUnpackSize); err != nil { if _, err := io.CopyN(dstFile, fileReader, MaxUnpackSize); err != nil {

View file

@ -74,7 +74,9 @@ func CopyFileAtomic(dest string, src string, opts *AtomicFileOptions) error {
if err != nil { if err != nil {
return err return err
} }
defer f.Close() defer func() {
_ = f.Close()
}()
return CreateAtomic(dest, f, opts) return CreateAtomic(dest, f, opts)
} }

View file

@ -51,37 +51,37 @@ func addContentLineBreaks(flags InfoFlag) bool {
func (di *Info) AddSection(name string, flags InfoFlag, content ...string) { func (di *Info) AddSection(name string, flags InfoFlag, content ...string) {
// Check if we need a spacer. // Check if we need a spacer.
if di.Len() > 0 { if di.Len() > 0 {
di.WriteString("\n\n") _, _ = di.WriteString("\n\n")
} }
// Write section to buffer. // Write section to buffer.
// Write section header. // Write section header.
if di.Style == "github" { if di.Style == "github" {
di.WriteString(fmt.Sprintf("<details>\n<summary>%s</summary>\n\n", name)) _, _ = di.WriteString(fmt.Sprintf("<details>\n<summary>%s</summary>\n\n", name))
} else { } else {
di.WriteString(fmt.Sprintf("**%s**:\n\n", name)) _, _ = di.WriteString(fmt.Sprintf("**%s**:\n\n", name))
} }
// Write section content. // Write section content.
if useCodeSection(flags) { if useCodeSection(flags) {
// Write code header: Needs one empty line between previous data. // Write code header: Needs one empty line between previous data.
di.WriteString("```\n") _, _ = di.WriteString("```\n")
} }
for i, part := range content { for i, part := range content {
di.WriteString(part) _, _ = di.WriteString(part)
if addContentLineBreaks(flags) && i < len(content)-1 { if addContentLineBreaks(flags) && i < len(content)-1 {
di.WriteString("\n") _, _ = di.WriteString("\n")
} }
} }
if useCodeSection(flags) { if useCodeSection(flags) {
// Write code footer: Needs one empty line between next data. // Write code footer: Needs one empty line between next data.
di.WriteString("\n```\n") _, _ = di.WriteString("\n```\n")
} }
// Write section header. // Write section header.
if di.Style == "github" { if di.Style == "github" {
di.WriteString("\n</details>") _, _ = di.WriteString("\n</details>")
} }
} }

View file

@ -38,17 +38,19 @@ func tempDir(dir, dest string) string {
cleanup := true cleanup := true
defer func() { defer func() {
if cleanup { if cleanup {
os.Remove(testsrc.Name()) _ = os.Remove(testsrc.Name())
} }
}() }()
testsrc.Close() _ = testsrc.Close()
testdest, err := ioutil.TempFile(filepath.Dir(dest), "."+filepath.Base(dest)) testdest, err := ioutil.TempFile(filepath.Dir(dest), "."+filepath.Base(dest))
if err != nil { if err != nil {
return fallback return fallback
} }
defer os.Remove(testdest.Name()) defer func() {
testdest.Close() _ = os.Remove(testdest.Name())
}()
_ = testdest.Close()
if err := os.Rename(testsrc.Name(), testdest.Name()); err != nil { if err := os.Rename(testsrc.Name(), testdest.Name()); err != nil {
return fallback return fallback
@ -149,7 +151,7 @@ func Symlink(oldname, newname string) error {
cleanup := true cleanup := true
defer func() { defer func() {
if cleanup { if cleanup {
os.RemoveAll(d) _ = os.RemoveAll(d)
} }
}() }()

View file

@ -15,11 +15,11 @@ func TestTempDir(t *testing.T) {
if tmpdir, ok := os.LookupEnv("TMPDIR"); ok { if tmpdir, ok := os.LookupEnv("TMPDIR"); ok {
t.Cleanup(func() { t.Cleanup(func() {
os.Setenv("TMPDIR", tmpdir) // restore _ = os.Setenv("TMPDIR", tmpdir) // restore
}) })
} else { } else {
t.Cleanup(func() { t.Cleanup(func() {
os.Unsetenv("TMPDIR") // restore _ = os.Unsetenv("TMPDIR") // restore
}) })
} }
@ -28,7 +28,7 @@ func TestTempDir(t *testing.T) {
t.Fatal(err) t.Fatal(err)
} }
t.Cleanup(func() { t.Cleanup(func() {
os.RemoveAll(mount1) _ = os.RemoveAll(mount1)
}) })
mount2, err := ioutil.TempDir("", "test-renameio-testtempdir2") mount2, err := ioutil.TempDir("", "test-renameio-testtempdir2")
@ -36,7 +36,7 @@ func TestTempDir(t *testing.T) {
t.Fatal(err) t.Fatal(err)
} }
t.Cleanup(func() { t.Cleanup(func() {
os.RemoveAll(mount2) _ = os.RemoveAll(mount2)
}) })
if err := syscall.Mount("tmpfs", mount1, "tmpfs", 0, ""); err != nil { if err := syscall.Mount("tmpfs", mount1, "tmpfs", 0, ""); err != nil {
@ -103,9 +103,9 @@ func TestTempDir(t *testing.T) {
t.Parallel() t.Parallel()
if testCase.TMPDIR == "" { if testCase.TMPDIR == "" {
os.Unsetenv("TMPDIR") _ = os.Unsetenv("TMPDIR")
} else { } else {
os.Setenv("TMPDIR", testCase.TMPDIR) _ = os.Setenv("TMPDIR", testCase.TMPDIR)
} }
if got := tempDir(testCase.dir, testCase.path); got != testCase.want { if got := tempDir(testCase.dir, testCase.path); got != testCase.want {

View file

@ -17,7 +17,9 @@ func TestWriteFile(t *testing.T) {
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
defer os.RemoveAll(d) defer func() {
_ = os.RemoveAll(d)
}()
filename := filepath.Join(d, "hello.sh") filename := filepath.Join(d, "hello.sh")