Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

New features #174

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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 <post@steffenvogel.de>
# SPDX-FileCopyrightText: 2023-2024 Steffen Vogel <post@steffenvogel.de>
# 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 @@
// 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 @@
if strings.Contains(argv0, "/") {
err := syscall.Exec(argv0, argv, envp)

if err == syscall.ENOEXEC {
if errors.Is(err, syscall.ENOEXEC) {

Check warning on line 44 in internal/execvpe/execvpe.go

View check run for this annotation

Codecov / codecov/patch

internal/execvpe/execvpe.go#L44

Added line #L44 was not covered by tests
if err := maybeScriptExecute(argv0, argv, envp); err != nil {
return err
}
Expand All @@ -57,34 +58,34 @@
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) {

Check warning on line 61 in internal/execvpe/execvpe.go

View check run for this annotation

Codecov / codecov/patch

internal/execvpe/execvpe.go#L61

Added line #L61 was not covered by tests
err = maybeScriptExecute(argv0, argv, envp)
}

switch err {
case syscall.EACCES:
switch {
case errors.Is(err, syscall.EACCES):

Check warning on line 66 in internal/execvpe/execvpe.go

View check run for this annotation

Codecov / codecov/patch

internal/execvpe/execvpe.go#L65-L66

Added lines #L65 - L66 were not covered by tests
// 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):

Check warning on line 72 in internal/execvpe/execvpe.go

View check run for this annotation

Codecov / codecov/patch

internal/execvpe/execvpe.go#L72

Added line #L72 was not covered by tests
fallthrough
case syscall.ESTALE:
case errors.Is(err, syscall.ESTALE):

Check warning on line 74 in internal/execvpe/execvpe.go

View check run for this annotation

Codecov / codecov/patch

internal/execvpe/execvpe.go#L74

Added line #L74 was not covered by tests
fallthrough
case syscall.ENOTDIR:
case errors.Is(err, syscall.ENOTDIR):

Check warning on line 76 in internal/execvpe/execvpe.go

View check run for this annotation

Codecov / codecov/patch

internal/execvpe/execvpe.go#L76

Added line #L76 was not covered by tests
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):

Check warning on line 82 in internal/execvpe/execvpe.go

View check run for this annotation

Codecov / codecov/patch

internal/execvpe/execvpe.go#L82

Added line #L82 was not covered by tests
fallthrough
case syscall.ETIMEDOUT:
case errors.Is(err, syscall.ETIMEDOUT):

Check warning on line 84 in internal/execvpe/execvpe.go

View check run for this annotation

Codecov / codecov/patch

internal/execvpe/execvpe.go#L84

Added line #L84 was not covered by tests

// 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 @@
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)))

Check warning on line 22 in internal/utils/ip.go

View check run for this annotation

Codecov / codecov/patch

internal/utils/ip.go#L21-L22

Added lines #L21 - L22 were not covered by tests
}
}

Expand Down
Loading
Loading