Skip to content
Merged
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
24 changes: 24 additions & 0 deletions .golangci.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
version: "2"

issues:
max-same-issues: 50

formatters:
enable:
- goimports # checks if the code and import statements are formatted according to the 'goimports' command
- gofumpt # Or "gofmt", # Enforce standard formatting

linters:
enable:
- errcheck #Errcheck is a program for checking for unchecked errors in Go code. These unchecked errors can be critical bugs in some cases.
- govet # Vet examines Go source code and reports suspicious constructs. It is roughly the same as 'go vet' and uses its passes. [auto-fix]
- ineffassign # Detects when assignments to existing variables are not used. [fast]
- staticcheck # It's a set of rules from staticcheck. It's not the same thing as the staticcheck binary. The author of staticcheck doesn't support or approve the use of staticcheck as a library inside golangci-lint. [auto-fix]
- unused # Checks Go code for unused constants, variables, functions and types.
# Subective additional linters
- gocyclo # or "cyclop", # Detect cyclomatic complexity
- goconst # Detect repeated values that can be made constants
- misspell # Fix spelling errors
Comment thread
krixlion marked this conversation as resolved.
- unconvert # Detect unnecessary type conversions
- unparam # Detect unused function parameters
- dupword # Detect duplicate words in comments and string literals (e.g. “the the”, “is is”)
21 changes: 20 additions & 1 deletion Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ endef

all: info

.PHONY: build local_build logs major minor patch push run stop test version
.PHONY: build local_build logs major minor patch push run stop test version lint lint-fix format
info:
@echo -e "\n${GREEN} ${PROJECT_NAME} / Makefile ${RESET}\n"

Expand Down Expand Up @@ -115,6 +115,25 @@ push:
@git tag -fa 'v${APP_VERSION}' -m 'v${APP_VERSION}'
@git push --follow-tags --set-upstream origin master

format:
@echo "\n>>> Formating code with golangci-lint…"
@golangci-lint fmt \
--config .golangci.yaml \
./...

lint:
@echo "\n>>> Running golangci-lint…"
@golangci-lint run \
--config .golangci.yaml \
--timeout 2m \
./...
Comment thread
ZwangaMukwevho marked this conversation as resolved.

lint-fix:
@echo "\n>>> Auto-fixing with golangci-lint…"
@golangci-lint run --fix \
--config .golangci.yaml \
--timeout 2m \
./...

MAJOR := $(shell echo ${APP_VERSION} | cut -d. -f1)
MINOR := $(shell echo ${APP_VERSION} | cut -d. -f2)
Expand Down
13 changes: 10 additions & 3 deletions cmd/dish/cli_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,16 +10,23 @@ import (

func TestPrintHelp(t *testing.T) {
oldStdout := os.Stdout
r, w, _ := os.Pipe()
r, w, err := os.Pipe()
if err != nil {
t.Errorf("failed to process pipe: %v", err)
}

os.Stdout = w

printHelp()

w.Close()
if err := w.Close(); err != nil {
t.Errorf("pipe close: %v", err)
}
Comment thread
krixlion marked this conversation as resolved.

os.Stdout = oldStdout

var buf bytes.Buffer
_, err := io.Copy(&buf, r)
_, err = io.Copy(&buf, r)
if err != nil {
t.Fatalf("failed to read from pipe: %v", err)
}
Expand Down
2 changes: 1 addition & 1 deletion cmd/dish/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ func run(fs *flag.FlagSet, args []string, _, stderr io.Writer) int {
return 1
}
// Otherwise, print the error
fmt.Fprintln(stderr, "error loading config:", err)
fmt.Fprintln(stderr, "error loading config:", err) //nolint:errcheck
return 2
}

Expand Down
1 change: 0 additions & 1 deletion cmd/dish/runner_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,6 @@ func compareResults(expected, actual []socket.Result) bool {
}

func TestFanInChannels(t *testing.T) {

testChannels := []chan socket.Result{}

for range 3 {
Expand Down
4 changes: 1 addition & 3 deletions pkg/alert/alerter_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,7 @@ import (
)

func TestNewAlerter(t *testing.T) {
var (
mockLogger = MockLogger{}
)
mockLogger := MockLogger{}

if alerterNil := NewAlerter(nil); alerterNil != nil {
t.Error("expected nil, got alerter")
Expand Down
8 changes: 3 additions & 5 deletions pkg/alert/api_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,15 +10,14 @@ import (
func TestNewAPISender(t *testing.T) {
mockHTTPClient := &SuccessStatusHTTPClient{}

url := "https://abc123.xyz.com"
headerName := "X-Api-Key"
headerValue := "abc123"
notifySuccess := false
verbose := false

expected := &apiSender{
httpClient: mockHTTPClient,
url: url,
url: pushgatewayURL,
headerName: headerName,
headerValue: headerValue,
notifySuccess: notifySuccess,
Expand All @@ -27,7 +26,7 @@ func TestNewAPISender(t *testing.T) {
}

cfg := &config.Config{
ApiURL: url,
ApiURL: pushgatewayURL,
ApiHeaderName: headerName,
ApiHeaderValue: headerValue,
MachineNotifySuccess: notifySuccess,
Expand All @@ -42,7 +41,6 @@ func TestNewAPISender(t *testing.T) {
}

func TestSend_API(t *testing.T) {
url := "https://abc123.xyz.com"
headerName := "X-Api-Key"
headerValue := "abc123"

Expand All @@ -65,7 +63,7 @@ func TestSend_API(t *testing.T) {

newConfig := func(headerName, headerValue string, notifySuccess, verbose bool) *config.Config {
return &config.Config{
ApiURL: url,
ApiURL: pushgatewayURL,
MachineNotifySuccess: notifySuccess,
Verbose: verbose,
ApiHeaderName: headerName,
Expand Down
2 changes: 0 additions & 2 deletions pkg/alert/discord.go
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,6 @@ func NewDiscordSender(httpClient HTTPClient, config *config.Config, logger logge
notifySuccess: config.TextNotifySuccess,
url: parsedURL.String(),
}, nil

}

func (s *discordSender) send(message string, failedCount int) error {
Expand All @@ -69,7 +68,6 @@ func (s *discordSender) send(message string, failedCount int) error {
resp, err := handleSubmit(s.httpClient, http.MethodPost, s.url, bytes.NewBuffer(body), func(o *submitOptions) {
o.headers["Authorization"] = "Bot " + strings.TrimSpace(s.botToken)
})

if err != nil {
return fmt.Errorf("error submitting discord alert: %w", err)
}
Expand Down
1 change: 0 additions & 1 deletion pkg/alert/formatter.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ import (
)

func FormatMessengerText(result socket.Result) string {

status := "failed"
if result.Passed {
status = "success"
Expand Down
12 changes: 6 additions & 6 deletions pkg/alert/pushgateway_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,18 +7,19 @@ import (
"go.vxn.dev/dish/pkg/config"
)

const pushgatewayURL = "https://abc123.xyz.com"

func TestNewPushgatewaySender(t *testing.T) {
mockHTTPClient := &SuccessStatusHTTPClient{}
mockLogger := &MockLogger{}

url := "https://abc123.xyz.com"
instanceName := "test-instance"
verbose := false
notifySuccess := false

expected := &pushgatewaySender{
httpClient: mockHTTPClient,
url: url,
url: pushgatewayURL,
instanceName: "test-instance",
notifySuccess: notifySuccess,
verbose: verbose,
Expand All @@ -27,7 +28,7 @@ func TestNewPushgatewaySender(t *testing.T) {
}

cfg := &config.Config{
PushgatewayURL: url,
PushgatewayURL: pushgatewayURL,
InstanceName: instanceName,
Verbose: verbose,
MachineNotifySuccess: notifySuccess,
Expand Down Expand Up @@ -60,7 +61,6 @@ func TestNewPushgatewaySender(t *testing.T) {
}

func TestSend_Pushgateway(t *testing.T) {
url := "https://abc123.xyz.com"
instanceName := "test-instance"

successResults := Results{
Expand Down Expand Up @@ -213,7 +213,7 @@ func TestSend_Pushgateway(t *testing.T) {

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
cfg := newConfig(url, tt.instanceName, tt.notifySuccess, tt.verbose)
cfg := newConfig(pushgatewayURL, tt.instanceName, tt.notifySuccess, tt.verbose)
sender, err := NewPushgatewaySender(tt.client, cfg, &MockLogger{})
if err != nil {
t.Fatalf("failed to create Pushgateway sender instance: %v", err)
Expand All @@ -229,7 +229,7 @@ func TestSend_Pushgateway(t *testing.T) {

func TestCreateMessage(t *testing.T) {
cfg := &config.Config{
PushgatewayURL: "https://abc123.xyz.com",
PushgatewayURL: pushgatewayURL,
InstanceName: "test-instance",
MachineNotifySuccess: false,
Verbose: false,
Expand Down
2 changes: 1 addition & 1 deletion pkg/alert/telegram_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,8 @@ func TestNewTelegramSender(t *testing.T) {
mockHTTPClient := &SuccessStatusHTTPClient{}
mockLogger := &MockLogger{}

chatID := "-123"
token := "abc123"
chatID := "-123"
verbose := false
notifySuccess := false

Expand Down
6 changes: 5 additions & 1 deletion pkg/alert/transport.go
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,11 @@ func handleSubmit(client HTTPClient, method string, url string, body io.Reader,

// handleRead reads an HTTP response, ensures the status code is within the expected <200, 299> range and if not, logs the response body.
func handleRead(res *http.Response, logger logger.Logger) error {
defer res.Body.Close()
defer func() {
if err := res.Body.Close(); err != nil {
logger.Errorf("failed to close response body: %v", err)
}
}()

if res.StatusCode < http.StatusOK || res.StatusCode >= http.StatusMultipleChoices {
body, err := io.ReadAll(res.Body)
Expand Down
2 changes: 1 addition & 1 deletion pkg/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@ func defineFlags(fs *flag.FlagSet, cfg *Config) {
// If a flag is used for a supported config parameter, the config parameter's value is set according to the provided flag. Otherwise, a default value is used for the given parameter.
func NewConfig(fs *flag.FlagSet, args []string) (*Config, error) {
if fs == nil {
//fs = flag.CommandLine
// fs = flag.CommandLine
return nil, fmt.Errorf("flagset argument cannot be nil")
}

Expand Down
2 changes: 1 addition & 1 deletion pkg/logger/console_logger.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ func NewConsoleLogger(verbose bool, out io.Writer) *consoleLogger {

l := &consoleLogger{
stdLogger: log.New(out, "", log.LstdFlags),
withColors: !(os.Getenv("NO_COLOR") == "true") && verbose,
withColors: os.Getenv("NO_COLOR") != "true" && verbose,
}

l.logLevel = INFO
Expand Down
6 changes: 4 additions & 2 deletions pkg/logger/console_logger_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,10 @@ func TestNewConsoleLogger(t *testing.T) {
}
logger.Info("hello stderr")

w.Close()
if err := w.Close(); err != nil {
t.Errorf("failed to close capture pipe writer: %v", err)
}

var buf bytes.Buffer
_, err := buf.ReadFrom(r)
if err != nil {
Expand Down Expand Up @@ -65,7 +68,6 @@ func TestNewConsoleLogger(t *testing.T) {
if actual != expected {
t.Fatalf("expected %s, got %s", expected, actual)
}

})

t.Run("with colors when verbose and no env set", func(t *testing.T) {
Expand Down
17 changes: 15 additions & 2 deletions pkg/netrunner/runner.go
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,15 @@ func (runner *tcpRunner) RunTest(ctx context.Context, sock socket.Socket) socket
if err != nil {
return socket.Result{Socket: sock, Error: err, Passed: false}
}
defer conn.Close()

defer func() {
if err := conn.Close(); err != nil {
runner.logger.Errorf(
"failed to close TCP connection to %s: %v",
endpoint, err,
)
}
}()

return socket.Result{Socket: sock, Passed: true}
}
Expand Down Expand Up @@ -120,7 +128,12 @@ func (runner *httpRunner) RunTest(ctx context.Context, sock socket.Socket) socke
if err != nil {
return socket.Result{Socket: sock, Passed: false, Error: err}
}
defer resp.Body.Close()

defer func() {
if cerr := resp.Body.Close(); cerr != nil {
runner.logger.Errorf("failed to close body for %v", cerr)
}
}()

if !slices.Contains(sock.ExpectedHTTPCodes, resp.StatusCode) {
err = fmt.Errorf("expected codes: %v, got %d", sock.ExpectedHTTPCodes, resp.StatusCode)
Expand Down
18 changes: 14 additions & 4 deletions pkg/netrunner/runner_posix.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,9 +24,11 @@ const (
echoRequest ICMPType = 8
)

const ipStripHdr = 23
const testID = 0x1234
const testSeq = 0x0001
const (
ipStripHdr = 23
testID = 0x1234
testSeq = 0x0001
)

type icmpRunner struct {
logger logger.Logger
Expand Down Expand Up @@ -64,7 +66,15 @@ func (runner *icmpRunner) RunTest(ctx context.Context, sock socket.Socket) socke
if err != nil {
return socket.Result{Socket: sock, Error: fmt.Errorf("failed to create a non-privileged icmp socket: %w", err)}
}
defer syscall.Close(sysSocket)

defer func() {
if cerr := syscall.Close(sysSocket); cerr != nil {
runner.logger.Errorf(
"error closing ICMP socket (fd %d) for %s:%d: %v",
sysSocket, sock.Host, sock.Port, cerr,
)
}
}()

if runtime.GOOS == "darwin" {
if err := syscall.SetsockoptInt(sysSocket, syscall.IPPROTO_IP, ipStripHdr, 1); err != nil {
Expand Down
Loading
Loading