Skip to content

Commit

Permalink
fix: Linter warnings
Browse files Browse the repository at this point in the history
Signed-off-by: Steffen Vogel <[email protected]>
  • Loading branch information
stv0g committed Oct 27, 2024
1 parent ab7c9bf commit 99b1c02
Show file tree
Hide file tree
Showing 36 changed files with 299 additions and 126 deletions.
129 changes: 112 additions & 17 deletions .golangci.yaml
Original file line number Diff line number Diff line change
@@ -1,23 +1,118 @@
# SPDX-FileCopyrightText: 2023 Steffen Vogel <[email protected]>
# SPDX-FileCopyrightText: 2023-2024 Steffen Vogel <[email protected]>
# SPDX-License-Identifier: Apache-2.0

linters-settings:
misspell:
locale: US

exhaustive:
default-signifies-exhaustive: true

gomodguard:
blocked:
modules:
- github.com/pkg/errors:
recommendations:
- errors

tagliatelle:
case:
use-field-name: true
rules:
json: snake
yaml: snake
xml: snake

gci:
sections:
- standard
- default
- prefix(cunicu.li/skeleton)
- blank
- dot

custom-order: true

linters:
enable:
- errname
- asciicheck # Simple linter to check that your code does not contain non-ASCII identifiers
- bidichk # Checks for dangerous unicode character sequences
- bodyclose # checks whether HTTP response body is closed successfully
- contextcheck # check the function whether use a non-inherited context
- decorder # check declaration order and count of types, constants, variables and functions
- dogsled # Checks assignments with too many blank identifiers (e.g. x, _, _, _, := f())
- dupl # Tool for code clone detection
- durationcheck # check for two durations multiplied together
- errcheck # Errcheck is a program for checking for unchecked errors in go programs. These unchecked errors can be critical bugs in some cases
- 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.
- errname # Checks that sentinel errors are prefixed with the `Err` and error types are suffixed with the `Error`.
- errorlint # errorlint is a linter for that can be used to find code that will cause problems with the error wrapping scheme introduced in Go 1.13.
- exhaustive # check exhaustiveness of enum switch statements
- copyloopvar
- gci
- gochecknoglobals
- gocognit
- gofmt
- misspell
- tagliatelle
- whitespace
- revive
- gosec
- nestif
- nolintlint
- prealloc
- forcetypeassert # finds forced type assertions
- gci # Gci control golang package import order and make it always deterministic.
- gochecknoglobals # Checks that no globals are present in Go code
- gochecknoinits # Checks that no init functions are present in Go code
- gocognit # Computes and checks the cognitive complexity of functions
- goconst # Finds repeated strings that could be replaced by a constant
- gocritic # The most opinionated Go source code linter
- err113 # Golang linter to check the errors handling expressions
- gofmt # Gofmt checks whether code was gofmt-ed. By default this tool runs with -s option to check for code simplification
- gofumpt # Gofumpt checks whether code was gofumpt-ed.
- goheader # Checks is file header matches to pattern
- goimports # Goimports does everything that gofmt does. Additionally it checks unused imports
- gomoddirectives # Manage the use of 'replace', 'retract', and 'excludes' directives in go.mod.
- 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.
- goprintffuncname # Checks that printf-like functions are named with `f` at the end
- gosec # Inspects source code for security problems
- gosimple # Linter for Go source code that specializes in simplifying a code
- govet # Vet examines Go source code and reports suspicious constructs, such as Printf calls whose arguments do not align with the format string
- grouper # An analyzer to analyze expression groups.
- importas # Enforces consistent import aliases
- ineffassign # Detects when assignments to existing variables are not used
- misspell # Finds commonly misspelled English words in comments
- nakedret # Finds naked returns in functions greater than a specified function length
- nilerr # Finds the code that returns nil even if it checks that the error is not nil.
- nilnil # Checks that there is no simultaneous return of `nil` error and an invalid value.
- noctx # noctx finds sending http request without context.Context
- predeclared # find code that shadows one of Go's predeclared identifiers
- revive # golint replacement, finds style mistakes
- staticcheck # Staticcheck is a go vet on steroids, applying a ton of static analysis checks
- stylecheck # Stylecheck is a replacement for golint
- tagliatelle # Checks the struct tags.
- tenv # tenv is analyzer that detects using os.Setenv instead of t.Setenv since Go1.17
- tparallel # tparallel detects inappropriate usage of t.Parallel() method in your Go test codes
- typecheck # Like the front-end of a Go compiler, parses and type-checks Go code
- unconvert # Remove unnecessary type conversions
- unparam # Reports unused function parameters
- unused # Checks Go code for unused constants, variables, functions and types
- wastedassign # wastedassign finds wasted assignment statements
- whitespace # Tool for detection of leading and trailing whitespace

linters-settings:
revive:
severity: warning
disable:
- containedctx # containedctx is a linter that detects struct contained context.Context field
- cyclop # checks function and package cyclomatic complexity
- depguard # Go linter that checks if package imports are in a list of acceptable packages
- forbidigo # Forbids identifiers
- funlen # Tool for detection of long functions
- gocyclo # Computes and checks the cyclomatic complexity of functions
- godot # Check if comments end in a period
- godox # Tool for detection of FIXME, TODO and other comment keywords
- gomnd # An analyzer to detect magic numbers.
- ireturn # Accept Interfaces, Return Concrete Types
- lll # Reports long lines
- maintidx # maintidx measures the maintainability index of each function.
- makezero # Finds slice declarations with non-zero initial length
- nestif # Reports deeply nested if statements
- nlreturn # nlreturn checks for a new line before return and branch statements to increase code clarity
- nolintlint # Reports ill-formed or insufficient nolint directives
- paralleltest # paralleltest detects missing usage of t.Parallel() method in your Go test
- prealloc # Finds slice declarations that could potentially be preallocated
- promlinter # Check Prometheus metrics naming via promlint
- rowserrcheck # checks whether Err of rows is checked successfully
- sqlclosecheck # Checks that sql.Rows and sql.Stmt are closed.
- testpackage # linter that makes you use a separate _test package
- thelper # thelper detects golang test helpers without t.Helper() call and checks the consistency of test helpers
- varnamelen # checks that the length of a variable's name matches its scope
- wrapcheck # Checks that errors returned from external packages are wrapped
- wsl # Whitespace Linter - Forces you to use empty lines!
22 changes: 14 additions & 8 deletions cmd/gontc/gontc.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,13 @@ import (
"golang.org/x/exp/slices"
)

var (
ErrNonExistingNetwork = errors.New("non-existing Gont network")
ErrNonExistingNode = errors.New("non-existing Gont node")
ErrNotEnoughArguments = errors.New("not enough arguments")
ErrUnknownSubCommand = errors.New("unknown sub-command")
)

// Set via ldflags (see Makefile)
var tag string //nolint:gochecknoglobals

Expand Down Expand Up @@ -53,8 +60,7 @@ func main() {
var err error
var network, node string

logger := internal.SetupLogging()
defer logger.Sync() //nolint:errcheck
internal.SetupLogging()

if err := g.CheckCaps(); err != nil {
fmt.Printf("error: %s\n", err)
Expand Down Expand Up @@ -102,7 +108,7 @@ func main() {
err = nil

default:
err = fmt.Errorf("unknown sub-command: %s", subcmd)
err = fmt.Errorf("%w: %s", ErrUnknownSubCommand, subcmd)
}

if err != nil {
Expand All @@ -119,7 +125,7 @@ func networkNode(args []string) (string, string, error) {
c := strings.SplitN(args[1], "/", 2)
if len(c) == 1 { // no network in name
if len(networks) == 0 {
return "", "", errors.New("no-existing Gont network")
return "", "", ErrNonExistingNetwork
}

network = networks[0]
Expand All @@ -129,14 +135,14 @@ func networkNode(args []string) (string, string, error) {
node = c[1]

if !slices.Contains(networks, network) {
return "", "", fmt.Errorf("non-existing network '%s'", network)
return "", "", fmt.Errorf("%w: %s", ErrNonExistingNetwork, network)
}
}

nodes := g.NodeNames(network)

if !slices.Contains(nodes, node) {
return "", "", fmt.Errorf("non-existing node '%s' in network '%s'", node, network)
return "", "", fmt.Errorf("%w '%s' in network '%s'", ErrNonExistingNode, node, network)
}

return network, node, nil
Expand Down Expand Up @@ -188,11 +194,11 @@ func clean(args []string) error {

func exec(network, node string, args []string) error {
if len(flag.Args()) <= 1 {
return fmt.Errorf("not enough arguments")
return ErrNotEnoughArguments
}

if network == "" {
return fmt.Errorf("there is no active Gont network")
return ErrNonExistingNetwork
}

if err := os.Setenv("GONT_NETWORK", network); err != nil {
Expand Down
23 changes: 12 additions & 11 deletions internal/execvpe/execvpe.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ package execvpe
// See: https://sourceware.org/git/?p=glibc.git;a=blob;f=posix/execvpe.c

import (
"errors"
"os"
"path/filepath"
"strings"
Expand Down Expand Up @@ -40,7 +41,7 @@ func Execvpe(argv0 string, argv []string, envp []string) error {
if strings.Contains(argv0, "/") {
err := syscall.Exec(argv0, argv, envp)

if err == syscall.ENOEXEC {
if errors.Is(err, syscall.ENOEXEC) {
if err := maybeScriptExecute(argv0, argv, envp); err != nil {
return err
}
Expand All @@ -57,34 +58,34 @@ func Execvpe(argv0 string, argv []string, envp []string) error {
gotEacces := false
for _, p := range strings.Split(path, ":") {
argv0 := filepath.Join(p, argv0)
if err = syscall.Exec(argv0, argv, envp); err == syscall.ENOEXEC {
if err = syscall.Exec(argv0, argv, envp); errors.Is(err, syscall.ENOEXEC) {
err = maybeScriptExecute(argv0, argv, envp)
}

switch err {
case syscall.EACCES:
switch {
case errors.Is(err, syscall.EACCES):
// Record that we got a 'Permission denied' error. If we end
// up finding no executable we can use, we want to diagnose
// that we did find one but were denied access.
gotEacces = true

case syscall.ENOENT:
case errors.Is(err, syscall.ENOENT):
fallthrough
case syscall.ESTALE:
case errors.Is(err, syscall.ESTALE):
fallthrough
case syscall.ENOTDIR:
case errors.Is(err, syscall.ENOTDIR):
fallthrough

// Those errors indicate the file is missing or not executable
// by us, in which case we want to just try the next path
// directory.

case syscall.ENODEV:
case errors.Is(err, syscall.ENODEV):
fallthrough
case syscall.ETIMEDOUT:
case errors.Is(err, syscall.ETIMEDOUT):

// Some strange file systems like AFS return even
// stranger error numbers. They cannot reasonably mean
// anything else so ignore those, too.

default:
// Some other error means we found an executable file, but
// something went wrong executing it; return the error to our
Expand Down
6 changes: 2 additions & 4 deletions internal/prque/prque.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ func (q heapl) Swap(i, j int) {
}

func (q *heapl) Push(x any) {
*q = append(*q, x.(Item))
*q = append(*q, x.(Item)) //nolint:forcetypeassert
}

func (q *heapl) Pop() any {
Expand Down Expand Up @@ -64,9 +64,7 @@ func (q *PriorityQueue) Pop() Item {
q.lock.Lock()
defer q.lock.Unlock()

item := heap.Pop(&q.heap).(Item)

return item
return heap.Pop(&q.heap).(Item) //nolint:forcetypeassert
}

func (q *PriorityQueue) Oldest() time.Time {
Expand Down
10 changes: 6 additions & 4 deletions internal/utils/ip.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,12 +12,14 @@ import (
func ipToInt(ip net.IP) (*big.Int, int) {
val := &big.Int{}
val.SetBytes([]byte(ip))
if len(ip) == net.IPv4len {

switch {
case len(ip) == net.IPv4len:
return val, 32
} else if len(ip) == net.IPv6len {
case len(ip) == net.IPv6len:
return val, 128
} else {
panic(fmt.Errorf("Unsupported address length %d", len(ip)))
default:
panic(fmt.Sprintf("unsupported address length %d", len(ip)))
}
}

Expand Down
12 changes: 9 additions & 3 deletions pkg/capture.go
Original file line number Diff line number Diff line change
Expand Up @@ -126,12 +126,15 @@ func NewCapture(opts ...CaptureOption) *Capture {

// Count returns the total number of captured packets
func (c *Capture) Count() uint64 {
return uint64(c.count.Load())
return c.count.Load()
}

func (c *Capture) Flush() error {
for c.queue.Len() > 0 {
p := c.queue.Pop().(CapturePacket)
p, ok := c.queue.Pop().(CapturePacket)
if !ok {
continue
}

if err := c.writePacket(p); err != nil {
return err
Expand Down Expand Up @@ -239,7 +242,10 @@ out:
break
}

p := c.queue.Pop().(CapturePacket)
p, ok := c.queue.Pop().(CapturePacket)
if !ok {
continue
}

if err := c.writePacket(p); err != nil {
c.logger.Error("Failed to handle packet. Stop capturing...", zap.Error(err))
Expand Down
6 changes: 3 additions & 3 deletions pkg/capture_interface.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,10 +37,10 @@ func (ci *captureInterface) readPackets(c *Capture) {
if err := ci.readPacket(c); err != nil {
if errors.Is(err, io.EOF) {
break
} else {
c.logger.Error("Failed to read packet data", zap.Error(err))
continue
}

c.logger.Error("Failed to read packet data", zap.Error(err))
continue
}
}
}
Expand Down
7 changes: 5 additions & 2 deletions pkg/capture_pcapgo.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,16 @@
package gont

import (
"errors"
"fmt"

"github.com/gopacket/gopacket/layers"
"github.com/gopacket/gopacket/pcapgo"
"golang.org/x/net/bpf"
)

var ErrFilterExpressionsRequireCGO = errors.New("libpcap filter expressions require CGo")

const CGoPCAP = false

type pcapgoPacketSource struct {
Expand All @@ -25,7 +28,7 @@ func (c *Capture) createPCAPHandle(name string) (packetSource, error) {
return nil, fmt.Errorf("failed to open PCAP handle: %w", err)
}

if err := hdl.SetCaptureLength(int(c.SnapshotLength)); err != nil {
if err := hdl.SetCaptureLength(c.SnapshotLength); err != nil {
return nil, fmt.Errorf("failed to set capture length: %w", err)
}

Expand All @@ -34,7 +37,7 @@ func (c *Capture) createPCAPHandle(name string) (packetSource, error) {
}

if c.FilterExpression != "" {
return nil, fmt.Errorf("libpcap filter expressions require CGo")
return nil, ErrFilterExpressionsRequireCGO
}

if c.FilterInstructions != nil {
Expand Down
Loading

0 comments on commit 99b1c02

Please sign in to comment.