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
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
# run: bash -c 'test -z "$(gofmt -s -l .)"'

View file

@ -33,6 +33,9 @@ linters:
- wsl
linters-settings:
revive:
# See https://github.com/mgechev/revive#available-rules for details.
enable-all-rules: true
gci:
# put imports beginning with prefix after 3rd-party packages;
# only support one prefix
@ -43,3 +46,20 @@ linters-settings:
# might be left in the code accidentally and should be resolved before merging
keywords:
- 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:
state.Error("")
}
state.wsConn.Close()
_ = state.wsConn.Close()
state.wg.Wait()
return nil

View file

@ -251,7 +251,7 @@ func (api *DatabaseAPI) shutdown(err error) error {
// Trigger shutdown.
close(api.shutdownSignal)
api.conn.Close()
_ = api.conn.Close()
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)
}
// clean up and exit
os.RemoveAll(tmpDir)
_ = os.RemoveAll(tmpDir)
os.Exit(exitCode)
}

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -101,7 +101,9 @@ func writeMetricsTo(ctx context.Context, url string) error {
if err != nil {
return err
}
defer resp.Body.Close()
defer func() {
_ = resp.Body.Close()
}()
// Check return status.
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
os.RemoveAll(tmpDir)
_ = os.RemoveAll(tmpDir)
}

View file

@ -58,7 +58,7 @@ func prep() 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 {
return fmt.Errorf("failed to open output file: %w", err)
}
@ -106,13 +106,13 @@ func fortuna(_ context.Context) error {
bytesWritten += 64
if bytesWritten%1024 == 0 {
os.Stderr.WriteString(".")
_, _ = os.Stderr.WriteString(".")
}
if bytesWritten%65536 == 0 {
fmt.Fprintf(os.Stderr, "\n%d bytes written\n", bytesWritten)
}
if bytesWritten >= outputSize {
os.Stderr.WriteString("\n")
_, _ = os.Stderr.WriteString("\n")
break
}
}
@ -145,7 +145,7 @@ func tickfeeder(ctx context.Context) error {
}
bytesWritten += 8
if bytesWritten%1024 == 0 {
os.Stderr.WriteString(".")
_, _ = os.Stderr.WriteString(".")
}
if bytesWritten%65536 == 0 {
fmt.Fprintf(os.Stderr, "\n%d bytes written\n", bytesWritten)
@ -154,7 +154,7 @@ func tickfeeder(ctx context.Context) error {
}
if bytesWritten >= outputSize {
os.Stderr.WriteString("\n")
_, _ = os.Stderr.WriteString("\n")
break
}
}

View file

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

9
test
View file

@ -104,8 +104,6 @@ fi
# install
if [[ $install -eq 1 ]]; then
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
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
@ -122,12 +120,6 @@ if [[ $testonly -eq 0 ]]; then
echo "gofmt command not found"
exit 1
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
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"
@ -160,7 +152,6 @@ for package in $packages; do
echo ""
echo $package
if [[ $testonly -eq 0 ]]; then
run golint -set_exit_status -min_confidence 1.0 $package
run go vet $package
run golangci-lint run $packagename
fi

View file

@ -45,7 +45,9 @@ func (reg *ResourceRegistry) fetchFile(ctx context.Context, client *http.Client,
if err != nil {
return err
}
defer resp.Body.Close()
defer func() {
_ = resp.Body.Close()
}()
// download and write file
n, err := io.Copy(atomicFile, resp.Body)
@ -64,7 +66,7 @@ func (reg *ResourceRegistry) fetchFile(ctx context.Context, client *http.Client,
// set permissions
if !onWindows {
// 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 {
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 {
return nil, err
}
defer resp.Body.Close()
defer func() {
_ = resp.Body.Close()
}()
// download and write file
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
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)
}

View file

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

View file

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

View file

@ -117,7 +117,9 @@ func (res *Resource) unpackZipArchive() (err error) {
if err != nil {
return
}
defer archiveReader.Close()
defer func() {
_ = archiveReader.Close()
}()
// Save all files to the tmp dir.
for _, file := range archiveReader.File {
@ -161,14 +163,18 @@ func copyFromZipArchive(archiveFile *zip.File, dstPath string) error {
if err != nil {
return err
}
defer fileReader.Close()
defer func() {
_ = fileReader.Close()
}()
// Open destination file for writing.
dstFile, err := os.OpenFile(dstPath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, archiveFile.Mode())
if err != nil {
return err
}
defer dstFile.Close()
defer func() {
_ = dstFile.Close()
}()
// Copy full file from archive to dst.
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 {
return err
}
defer f.Close()
defer func() {
_ = f.Close()
}()
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) {
// Check if we need a spacer.
if di.Len() > 0 {
di.WriteString("\n\n")
_, _ = di.WriteString("\n\n")
}
// Write section to buffer.
// Write section header.
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 {
di.WriteString(fmt.Sprintf("**%s**:\n\n", name))
_, _ = di.WriteString(fmt.Sprintf("**%s**:\n\n", name))
}
// Write section content.
if useCodeSection(flags) {
// Write code header: Needs one empty line between previous data.
di.WriteString("```\n")
_, _ = di.WriteString("```\n")
}
for i, part := range content {
di.WriteString(part)
_, _ = di.WriteString(part)
if addContentLineBreaks(flags) && i < len(content)-1 {
di.WriteString("\n")
_, _ = di.WriteString("\n")
}
}
if useCodeSection(flags) {
// Write code footer: Needs one empty line between next data.
di.WriteString("\n```\n")
_, _ = di.WriteString("\n```\n")
}
// Write section header.
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
defer func() {
if cleanup {
os.Remove(testsrc.Name())
_ = os.Remove(testsrc.Name())
}
}()
testsrc.Close()
_ = testsrc.Close()
testdest, err := ioutil.TempFile(filepath.Dir(dest), "."+filepath.Base(dest))
if err != nil {
return fallback
}
defer os.Remove(testdest.Name())
testdest.Close()
defer func() {
_ = os.Remove(testdest.Name())
}()
_ = testdest.Close()
if err := os.Rename(testsrc.Name(), testdest.Name()); err != nil {
return fallback
@ -149,7 +151,7 @@ func Symlink(oldname, newname string) error {
cleanup := true
defer func() {
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 {
t.Cleanup(func() {
os.Setenv("TMPDIR", tmpdir) // restore
_ = os.Setenv("TMPDIR", tmpdir) // restore
})
} else {
t.Cleanup(func() {
os.Unsetenv("TMPDIR") // restore
_ = os.Unsetenv("TMPDIR") // restore
})
}
@ -28,7 +28,7 @@ func TestTempDir(t *testing.T) {
t.Fatal(err)
}
t.Cleanup(func() {
os.RemoveAll(mount1)
_ = os.RemoveAll(mount1)
})
mount2, err := ioutil.TempDir("", "test-renameio-testtempdir2")
@ -36,7 +36,7 @@ func TestTempDir(t *testing.T) {
t.Fatal(err)
}
t.Cleanup(func() {
os.RemoveAll(mount2)
_ = os.RemoveAll(mount2)
})
if err := syscall.Mount("tmpfs", mount1, "tmpfs", 0, ""); err != nil {
@ -103,9 +103,9 @@ func TestTempDir(t *testing.T) {
t.Parallel()
if testCase.TMPDIR == "" {
os.Unsetenv("TMPDIR")
_ = os.Unsetenv("TMPDIR")
} else {
os.Setenv("TMPDIR", testCase.TMPDIR)
_ = os.Setenv("TMPDIR", testCase.TMPDIR)
}
if got := tempDir(testCase.dir, testCase.path); got != testCase.want {

View file

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