Skip to content

Commit

Permalink
Golangci: Add ci config and fixed linter issues
Browse files Browse the repository at this point in the history
  • Loading branch information
donutloop committed May 9, 2021
1 parent 169097d commit 204d6c8
Show file tree
Hide file tree
Showing 23 changed files with 180 additions and 53 deletions.
75 changes: 75 additions & 0 deletions .golangci.yml
@@ -0,0 +1,75 @@
run:
tests: false
skip-dirs:
- examples
- vendor

linters:
enable:
- bodyclose
- deadcode
- depguard
- dogsled
- dupl
- errcheck
- exhaustive
- funlen
- gochecknoinits
- goconst
- gocritic
- gocyclo
- gofmt
- goimports
- golint
- gomnd
- goprintffuncname
- gosec
- gosimple
- govet
- ineffassign
- interfacer
- lll
- misspell
- nakedret
- noctx
- nolintlint
- rowserrcheck
- scopelint
- staticcheck
- structcheck
- stylecheck
- typecheck
- unconvert
- unparam
- unused
- varcheck
- whitespace
- asciicheck
- gochecknoglobals
- gocognit
- godot
- godox
- goerr113
- maligned
- nestif
- prealloc
- testpackage
- wsl

linters-settings:
# see all options at https://github.com/bombsimon/wsl/blob/master/doc/configuration.md
# Even the default values have been copied here to give us control and fine tunning on them
wsl:
strict-append: false
allow-assign-and-call: true
allow-assign-and-anything: false
allow-multiline-assign: true
force-case-trailing-whitespace: 0
allow-cuddle-declarations: false
allow-case-trailing-whitespace: false
allow-trailing-comment: false
enforce-err-cuddling: false

issues:
exclude:
- '^singleCaseSwitch'
16 changes: 14 additions & 2 deletions bus/bus.go
Expand Up @@ -41,7 +41,7 @@ func (b *InProcBus) Dispatch(msg Msg) error {

handler, ok := b.handlers[nameOfMsg.String()]
if !ok {
return fmt.Errorf("handler not found for %s", nameOfMsg)
return &HandlerNotFoundError{Name: nameOfMsg.Name()}
}

params := make([]reflect.Value, 0, 1)
Expand Down Expand Up @@ -85,7 +85,7 @@ func (b *InProcBus) AddHandler(handler HandlerFunc) error {

typeOfMsg := handlerType.In(0)
if _, ok := b.handlers[typeOfMsg.String()]; ok {
return fmt.Errorf("handler exists for %s", typeOfMsg)
return &OverwriteHandlerError{Name: typeOfMsg.Name()}
}

b.handlers[typeOfMsg.String()] = reflect.ValueOf(handler)
Expand Down Expand Up @@ -128,3 +128,15 @@ type BadFuncError string
func (bhf BadFuncError) Error() string {
return fmt.Sprintf("bad handler func: %s", string(bhf))
}

type HandlerNotFoundError struct {
Name string
}

func (e *HandlerNotFoundError) Error() string { return e.Name + ": not found" }

type OverwriteHandlerError struct {
Name string
}

func (e *OverwriteHandlerError) Error() string { return e.Name + ": handler exists" }
28 changes: 18 additions & 10 deletions bus/bus_test.go
Expand Up @@ -15,27 +15,32 @@ type msg struct {
func TestHandlerReturnsError(t *testing.T) {
b := bus.New()

b.AddHandler(func(m *msg) error {
err := b.AddHandler(func(m *msg) error {
return errors.New("handler error")
})
if err != nil {
t.Fatal(err)
}

err := b.Dispatch(new(msg))
err = b.Dispatch(new(msg))
if err == nil {
t.Fatalf("dispatch msg failed (%s)", err.Error())
t.Fatalf("dispatch msg failed (%v)", err)
}
}

func TestHandlerReturn(t *testing.T) {
b := bus.New()

b.AddHandler(func(m *msg) error {
err := b.AddHandler(func(m *msg) error {
m.body = "Hello, world!"
return nil
})
if err != nil {
t.Fatal(err)
}

msg := new(msg)
err := b.Dispatch(msg)

err = b.Dispatch(msg)
if err != nil {
t.Fatalf("dispatch msg failed (%s)", err.Error())
}
Expand Down Expand Up @@ -80,9 +85,12 @@ func TestAddHandlerBadFunc(t *testing.T) {
}()

b := bus.New()
b.AddHandler(func(m *msg, s string) error {
err := b.AddHandler(func(m *msg, s string) error {
return nil
})
if err != nil {
t.Fatal(err)
}
}

func TestAddListenerBadFunc(t *testing.T) {
Expand All @@ -103,13 +111,13 @@ func TestAddListenerBadFunc(t *testing.T) {

func BenchmarkHandlerRun(b *testing.B) {
for n := 0; n < b.N; n++ {
bus := bus.New()
bs := bus.New()

bus.AddHandler(func(m *msg) error {
bs.AddHandler(func(m *msg) error {
return nil
})

if err := bus.Dispatch(new(msg)); err != nil {
if err := bs.Dispatch(new(msg)); err != nil {
b.Fatal(err)
}
}
Expand Down
15 changes: 10 additions & 5 deletions bus/doc_test.go
Expand Up @@ -6,7 +6,7 @@ import (
)

// Creates a bus and adds a listener to a message afterward it publishes a new message
func ExampleBusListener() {
func ExampleInProcBus_AddEventListener() {

type msg struct {
Id int64
Expand All @@ -21,14 +21,14 @@ func ExampleBusListener() {
})

if err := b.Publish(new(msg)); err != nil {
fmt.Println(fmt.Sprintf("bus: %v", err))
fmt.Printf("error: (%v) \n", err)
}

// Output: db insert listener
}

// Creates a bus and adds a handler for a message afterward it dispatch a new message
func ExampleBusHandler() {
func ExampleInProcBus_AddHandler() {

type msg struct {
Id int64
Expand All @@ -37,13 +37,18 @@ func ExampleBusHandler() {

b := bus.New()

b.AddHandler(func(m *msg) error {
err := b.AddHandler(func(m *msg) error {
fmt.Println("db insert listener")
return nil
})

if err != nil {
fmt.Printf("error: (%v) \n", err)
return
}

if err := b.Dispatch(new(msg)); err != nil {
fmt.Println(fmt.Sprintf("bus: %v", err))
fmt.Printf("error: (%v) \n", err)
}

// Output: db insert listener
Expand Down
2 changes: 1 addition & 1 deletion concurrent/doc_test.go
Expand Up @@ -23,7 +23,7 @@ func ExampleRun() {

if len(errs) > 0 {
for _, err := range errs {
fmt.Println(fmt.Sprintf("error: %v", err))
fmt.Printf("error: %v \n", err)
}
}

Expand Down
10 changes: 9 additions & 1 deletion concurrent/runner.go
Expand Up @@ -2,9 +2,17 @@ package concurrent

import (
"fmt"
"runtime/debug"
"sync"
)

type RecoverError struct {
Err interface{}
Stack []byte
}

func (e *RecoverError) Error() string { return fmt.Sprintf("Do panicked: %v", e.Err) }

// Run executes the provided functions in concurrent and collects any errors they return.
// Be careful about your resource consumption
func Run(fns ...func() error) []error {
Expand All @@ -16,7 +24,7 @@ func Run(fns ...func() error) []error {
defer func() {

if v := recover(); v != nil {
errc <- fmt.Errorf("do is panicked (%v)", v)
errc <- &RecoverError{Err: v, Stack: debug.Stack()}
}

wg.Done()
Expand Down
5 changes: 3 additions & 2 deletions debugutil/http_dump_test.go
Expand Up @@ -3,6 +3,7 @@ package debugutil_test
import (
"bufio"
"bytes"
"context"
"github.com/donutloop/toolkit/debugutil"
"net/http"
"testing"
Expand Down Expand Up @@ -30,7 +31,7 @@ X-Xss-Protection: 1; mode=block
{"data": {"partner": {"verified_data": {"people": [{"identity_document_checks": [{"status": "passed", "file_links": [{"file_type": "photo", "link": "https://static.iwoca.com/assets/iwoca.4c17fef7de62.png"}], "check_id": "REFERENCE_0001", "datetime": "2017-06-12T14:05:51.666Z", "identity_document_type": "passport", "document_issuing_country": "gb", "provider_name": "test"}], "uid": "6cf7319e-f9ec-4038-ba4f-3561a6097484"}]}}, "state_key": "8e4db383-2ead-4a47-87df-220432714c47", "schema_version": "v1", "application": {"company": {"last_12_months_turnover": {"amount": 700000, "datetime": "2016-10-12T14:05:51.666Z"}, "type": "gmbh", "company_number": "01111112", "bank_details": {"iban": "DE89370400440532013000"}}, "requested_products": {"credit_facility": {"approval": {"amount": 15000}}}, "people": [{"residential_addresses": [{"town": "Ely", "uid": "cf9aa203-4e0c-4d7f-b42b-90c7b3d193d3", "house_number": "286", "date_from": "2014-02-03", "street_line_1": "Idverifier St", "postcode": "CB62AG"}], "last_name": "Norton", "uid": "6cf7319e-f9ec-4038-ba4f-3561a6097484", "roles": ["applicant", "shareholder", "guarantor", "director"], "title": "herr", "first_name": "Ervin", "privacy_policy": {"agreed": true, "datetime": "2016-10-12T14:05:51.666Z"}, "date_of_birth": "1980-01-01"}]}}}
`)
reader := bufio.NewReader(bytes.NewReader(r))
req, err := http.NewRequest(http.MethodGet, "/api/resource", nil)
req, err := http.NewRequestWithContext(context.Background(), http.MethodGet, "/api/resource", nil)
if err != nil {
t.Fatal(err)
}
Expand All @@ -52,7 +53,7 @@ func TestPrettyDumpRequest(t *testing.T) {

b := []byte(`{"data": {"partner": {"verified_data": {"people": [{"identity_document_checks": [{"status": "passed", "file_links": [{"file_type": "photo", "link": "https://static.iwoca.com/assets/iwoca.4c17fef7de62.png"}], "check_id": "REFERENCE_0001", "datetime": "2017-06-12T14:05:51.666Z", "identity_document_type": "passport", "document_issuing_country": "gb", "provider_name": "test"}], "uid": "6cf7319e-f9ec-4038-ba4f-3561a6097484"}]}}, "state_key": "8e4db383-2ead-4a47-87df-220432714c47", "schema_version": "v1", "application": {"company": {"last_12_months_turnover": {"amount": 700000, "datetime": "2016-10-12T14:05:51.666Z"}, "type": "gmbh", "company_number": "01111112", "bank_details": {"iban": "DE89370400440532013000"}}, "requested_products": {"credit_facility": {"approval": {"amount": 15000}}}, "people": [{"residential_addresses": [{"town": "Ely", "uid": "cf9aa203-4e0c-4d7f-b42b-90c7b3d193d3", "house_number": "286", "date_from": "2014-02-03", "street_line_1": "Idverifier St", "postcode": "CB62AG"}], "last_name": "Norton", "uid": "6cf7319e-f9ec-4038-ba4f-3561a6097484", "roles": ["applicant", "shareholder", "guarantor", "director"], "title": "herr", "first_name": "Ervin", "privacy_policy": {"agreed": true, "datetime": "2016-10-12T14:05:51.666Z"}, "date_of_birth": "1980-01-01"}]}}}`)

req, err := http.NewRequest(http.MethodGet, "/api/resource", bytes.NewReader(b))
req, err := http.NewRequestWithContext(context.Background(), http.MethodGet, "/api/resource", bytes.NewReader(b))
if err != nil {
t.Fatal(err)
}
Expand Down
8 changes: 7 additions & 1 deletion debugutil/http_log_round_tripper_test.go
@@ -1,6 +1,7 @@
package debugutil_test

import (
"context"
"fmt"
"github.com/donutloop/toolkit/debugutil"
"log"
Expand Down Expand Up @@ -31,7 +32,12 @@ func TestLogRoundTripper_RoundTrip(t *testing.T) {
httpClient := new(http.Client)
httpClient.Transport = debugutil.NewLogRoundTripper(http.DefaultTransport, logger{}, true)

response, err := httpClient.Get(server.URL)
req, err := http.NewRequestWithContext(context.Background(), http.MethodGet, server.URL, nil)
if err != nil {
t.Fatal(err)
}

response, err := httpClient.Do(req)
if err != nil {
t.Fatalf("could not create request: %v", err)
}
Expand Down
1 change: 1 addition & 0 deletions debugutil/prettysprint_test.go
Expand Up @@ -55,6 +55,7 @@ func Test(t *testing.T) {
},
}
for _, test := range tests {
test := test
t.Run(test.name, func(t *testing.T) {
output := debugutil.PrettySprint(test.input)
if output != test.output {
Expand Down
2 changes: 1 addition & 1 deletion event/doc_test.go
Expand Up @@ -13,7 +13,7 @@ func ExampleHooks() {
errs := hooks.Fire()
if len(errs) > 0 {
for _, err := range errs {
fmt.Println(fmt.Sprintf("error: %v", err))
fmt.Printf("error: %v \n", err)
}
}

Expand Down
2 changes: 1 addition & 1 deletion multierror/doc_test.go
Expand Up @@ -8,7 +8,7 @@ import (
"github.com/donutloop/toolkit/multierror"
)

func ExampleMultiError() {
func Example() {
errs := []error{
errors.New("error connect to db failed"),
errors.New("error marschaling json"),
Expand Down
11 changes: 7 additions & 4 deletions multierror/muliterror_test.go
Expand Up @@ -12,15 +12,18 @@ import (
"github.com/donutloop/toolkit/multierror"
)

var marshalError error = errors.New("error marshal json")
var connectionError error = errors.New("error connect to db failed")

func TestMultiError_Error(t *testing.T) {
errs := []error{
nil,
errors.New("error connect to db failed"),
errors.New("error marschaling json"),
connectionError,
marshalError,
}
expectedValue := "multiple errors: error connect to db failed; error marschaling json"
expectedValue := "multiple errors: error connect to db failed; error marshal json"
err := multierror.New(errs...)
if err.Error() != expectedValue {
t.Errorf(`unexpected error message (actual:"%s", expected: "%s")`, err.Error(), expectedValue)
t.Errorf(`unexpected error message (actual:"%v", expected: "%s")`, err, expectedValue)
}
}
2 changes: 1 addition & 1 deletion promise/doc_test.go
Expand Up @@ -16,7 +16,7 @@ func ExamplePromise() {
select {
case <-done:
case err := <-errc:
fmt.Println(fmt.Sprintf("error: %v", err))
fmt.Printf("error: %v \n", err)
}

// Output: do things
Expand Down
6 changes: 4 additions & 2 deletions promise/promise_test.go
Expand Up @@ -6,13 +6,15 @@ package promise_test

import (
"context"
"fmt"
"errors"
"github.com/donutloop/toolkit/promise"
"strings"
"testing"
"time"
)

var stubError error = errors.New("stub")

func TestDoPanic(t *testing.T) {

done, errc := promise.Do(context.Background(), func(ctx context.Context) error {
Expand All @@ -35,7 +37,7 @@ func TestDoPanic(t *testing.T) {
func TestDoFail(t *testing.T) {

done, errc := promise.Do(context.Background(), func(ctx context.Context) error {
return fmt.Errorf("stub")
return stubError
})

select {
Expand Down

0 comments on commit 204d6c8

Please sign in to comment.