Skip to content

Commit

Permalink
[chore] Update Go and linter (#60)
Browse files Browse the repository at this point in the history
  • Loading branch information
kinbiko authored Jul 6, 2023
1 parent 76a8f75 commit cbd877e
Show file tree
Hide file tree
Showing 19 changed files with 195 additions and 151 deletions.
52 changes: 25 additions & 27 deletions .github/workflows/go.yml
Original file line number Diff line number Diff line change
@@ -1,42 +1,40 @@
name: Go
on: [push]
jobs:

build:
name: Build
runs-on: ubuntu-latest
steps:
- name: Set up Go
uses: actions/setup-go@v1
with:
go-version: 1.20
id: go

- name: Set up Go 1.16
uses: actions/setup-go@v1
with:
go-version: 1.16
id: go

- name: Check out code into the Go module directory
uses: actions/checkout@v1
- name: Check out code into the Go module directory
uses: actions/checkout@v1

- name: Get dependencies
run: go get -v -t -d ./...
- name: Get dependencies
run: go get -v -t -d ./...

- name: Build
run: go build -v .
- name: Build
run: go build -v .

# Running tests with and without the race checker, as certain tests are
# only run when the race checker is not enabled
- name: Test
run: go test -v -coverprofile=profile.cov ./...
# Running tests with and without the race checker, as certain tests are
# only run when the race checker is not enabled
- name: Test
run: go test -v -coverprofile=profile.cov ./...

- name: Coverage
uses: shogo82148/actions-goveralls@v1
with:
path-to-profile: profile.cov
- name: Coverage
uses: shogo82148/actions-goveralls@v1
with:
path-to-profile: profile.cov

- name: Test (race)
run: go test -race -v ./...
- name: Test (race)
run: go test -race -v ./...

- name: Install Linter
run: curl -sSfL https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh | sh -s v1.45.2
- name: Install Linter
run: curl -sSfL https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh | sh -s v1.53.2

- name: Lint
run: ./bin/golangci-lint run .
- name: Lint
run: ./bin/golangci-lint run .
34 changes: 16 additions & 18 deletions .golangci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,6 @@ run:
# the dependency descriptions in go.mod.
modules-download-mode: readonly


# output configuration options
output:
# colored-line-number|line-number|json|tab|checkstyle|code-climate, default is "colored-line-number"
Expand All @@ -57,7 +56,6 @@ output:
# print linter name in the end of issue text, default is true
print-linter-name: true


# all available settings of specific linters
linters-settings:
errcheck:
Expand All @@ -78,10 +76,6 @@ linters-settings:
# see https://github.com/kisielk/errcheck#excluding-functions for details
# exclude: /path/to/file.txt

funlen:
lines: 35
statements: 20

govet:
# report about shadowed variables
check-shadowing: true
Expand Down Expand Up @@ -114,6 +108,9 @@ linters-settings:
# where nested if/for is weighted more, and only one point regardless of
# cases in a switch.
min-complexity: 11
gomnd:
ignored-numbers:
- "2"
dupl:
# tokens count to trigger issue, 150 by default
threshold: 100
Expand All @@ -123,14 +120,15 @@ linters-settings:
# minimal occurrences count to trigger, 3 by default
min-occurrences: 3
depguard:
list-type: blacklist
include-go-root: false
packages:
- github.com/satori/go.uuid

# packages-with-error-messages:
# specify an error message to output when a blacklisted package is used
# github.com/sirupsen/logrus: "logging is allowed only by logutils.Log"
rules:
all:
files:
- "$all"
- "$test"
allow:
- "$gostd"
- "github.com/kinbiko/bugsnag"
- "github.com/kinbiko/jsonassert"
misspell:
# Correct spellings using locale preferences for US or UK.
# Default is to use a neutral variety of English.
Expand Down Expand Up @@ -203,7 +201,7 @@ linters-settings:
max-blank-identifiers: 2

whitespace:
multi-if: false # Enforces newlines (or comments) after every multi-line if statement
multi-if: false # Enforces newlines (or comments) after every multi-line if statement
multi-func: false # Enforces newlines (or comments) after every multi-line function signature
wsl:
# If true append is only allowed to be cuddled if appending value is
Expand Down Expand Up @@ -253,14 +251,13 @@ linters:
- unused
fast: false


issues:
# List of regexps of issue texts to exclude, empty list by default.
# But independently from this option we use default exclude patterns,
# it can be disabled by `exclude-use-default: false`. To list all
# excluded by default patterns execute `golangci-lint run --help`
# exclude:
# - abcdef
# - abcdef

# Excluding configuration per-path, per-linter, per-text and per-source
exclude-rules:
Expand All @@ -272,19 +269,20 @@ issues:
- dupl
- errcheck
- errchkjson
- exhaustivestruct
- funlen
- gocognit
- gocyclo
- gomnd
- lll
- paralleltest
- staticcheck
- stylecheck
- testpackage
- varnamelen
- path: \.go
linters:
- goerr113
- exhaustruct

# Independently from option `exclude` we use default exclude patterns,
# it can be disabled by this option. To list all
Expand Down
24 changes: 17 additions & 7 deletions builds/http.go
Original file line number Diff line number Diff line change
@@ -1,13 +1,19 @@
// Package builds is a package for sending build requests to the Bugsnag Build API, as defined here:
// https://bugsnagbuildapi.docs.apiary.io/
package builds

import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"time"
)

const timeout = 10 * time.Second

// DefaultPublisher returns a publisher for requests against the Bugsnag SaaS
// endpoint. If you need to target your own on-premise installation, please use
// NewPublisher.
Expand All @@ -23,7 +29,7 @@ func NewPublisher(endpoint string) *Publisher {
}

// Publisher is a type for sending build requests to the Bugsnag Build API, as defined here:
//https://bugsnagbuildapi.docs.apiary.io/
// https://bugsnagbuildapi.docs.apiary.io/
type Publisher struct {
endpoint string
}
Expand All @@ -34,26 +40,30 @@ func (p *Publisher) Publish(req *JSONBuildRequest) error {
return fmt.Errorf("publisher created incorrectly; please use NewPublisher or DefaultPublisher to construct your builds.Publisher")
}

b, err := json.Marshal(req)
jsonBody, err := json.Marshal(req)
if err != nil {
return fmt.Errorf("unable to marshal JSON: %w", err)
}

httpReq, err := http.NewRequest("POST", p.endpoint, bytes.NewBuffer(b))

ctx, cancel := context.WithTimeout(context.Background(), timeout)
defer cancel()
httpReq, err := http.NewRequestWithContext(ctx, http.MethodPost, p.endpoint, bytes.NewBuffer(jsonBody))
if err != nil {
return fmt.Errorf("error when POST-ing request to '%s': %w", p.endpoint, err)
}
httpReq.Header.Add("Content-Type", "application/json")

httpRes, err := http.DefaultClient.Do(httpReq)
if err != nil {
return err
return fmt.Errorf("unable to make HTTP call: %w", err)
}
defer func() {
_ = httpRes.Body.Close()
}()

got, err := io.ReadAll(httpRes.Body)
if err != nil {
return err
return fmt.Errorf("unable to read response body: %w", err)
}

type response struct {
Expand All @@ -63,7 +73,7 @@ func (p *Publisher) Publish(req *JSONBuildRequest) error {
}
var res response
if err := json.Unmarshal(got, &res); err != nil {
return err
return fmt.Errorf("unable to read response body as JSON: %w", err)
}
if res.Status == "error" {
return fmt.Errorf("error when sending message: %s", res.Errors[0])
Expand Down
10 changes: 5 additions & 5 deletions builds/http_test.go
Original file line number Diff line number Diff line change
@@ -1,14 +1,15 @@
package builds_test

import (
"io/ioutil"
"io"
"net/http"
"net/http/httptest"
"testing"
"time"

"github.com/kinbiko/bugsnag/builds"
"github.com/kinbiko/jsonassert"

"github.com/kinbiko/bugsnag/builds"
)

func TestNonConstructedPublisher(t *testing.T) {
Expand All @@ -21,9 +22,9 @@ func TestPublishingBuilds(t *testing.T) {
testServer := func() (*httptest.Server, chan string) {
reqs := make(chan string, 10)
return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
body, _ := ioutil.ReadAll(r.Body)
body, _ := io.ReadAll(r.Body)
reqs <- string(body)
w.Write([]byte(`{"status": "ok"}`))
_, _ = w.Write([]byte(`{"status": "ok"}`))
})), reqs
}

Expand Down Expand Up @@ -82,5 +83,4 @@ func TestPublishingBuilds(t *testing.T) {
"appVersion": "1.5.2"
}`)
})

}
17 changes: 9 additions & 8 deletions builds/payload.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,12 @@ type JSONBuildRequest struct {
// the build relates to.
AppVersion string `json:"appVersion"` // E.g. "1.5.2"

//The release stage (eg, production, staging) that is being released (if
//applicable). Normally the fact that a build has been released to a
//release stage is detected automatically when an error event or session is
//received for the build. However if you would like to manually notify
//Bugsnag of the build being released you can specify the stage that the
//build was released to.
// The release stage (eg, production, staging) that is being released (if
// applicable). Normally the fact that a build has been released to a
// release stage is detected automatically when an error event or session is
// received for the build. However if you would like to manually notify
// Bugsnag of the build being released you can specify the stage that the
// build was released to.
ReleaseStage string `json:"releaseStage,omitempty"` // E.g. "staging"

// The name of the entity that triggered the build. Could be a user,
Expand Down Expand Up @@ -54,8 +54,9 @@ type JSONBuildRequest struct {
AutoAssignRelease bool `json:"autoAssignRelease,omitempty"`
}

// Information about the source control of the code. This can be used to
// link errors to the source code (for supported source control tools)
// JSONSourceControl is information about the source control of the code.
// This can be used to link errors to the source code (for supported source
// control tools)
type JSONSourceControl struct {
// If the provider can be inferred from the repository then it is not
// required. Must be one of: "github", "github-enterprise", "bitbucket",
Expand Down
43 changes: 27 additions & 16 deletions builds/validation.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ import (
"strings"
)

// Validate checks that the given JSONBuildRequest is valid.
// If it is not valid, an error is returned.
func (r *JSONBuildRequest) Validate() error {
if re := regexp.MustCompile("^[0-9a-f]{32}$"); !re.MatchString(r.APIKey) {
return fmt.Errorf(`APIKey must be 32 hex characters, but got "%s"`, r.APIKey)
Expand All @@ -15,23 +17,32 @@ func (r *JSONBuildRequest) Validate() error {
return fmt.Errorf(`AppVersion must be present`)
}

if r.SourceControl != nil {
if r.SourceControl.Repository == "" {
return fmt.Errorf(`SourceControl.Repository must be present when SourceControl is set`)
}
if r.SourceControl.Revision == "" {
return fmt.Errorf(`SourceControl.Revision must be present when SourceControl is set`)
}
if r.SourceControl.Provider != "" {
validProviders := []string{"github", "github-enterprise", "bitbucket", "bitbucket-server", "gitlab", "gitlab-onpremise"}
found := false
for _, p := range validProviders {
found = found || p == r.SourceControl.Provider
}
if !found {
return fmt.Errorf(`SourceControl.Provider must be unset (for automatic inference) or one of %v`, validProviders)
}
if r.SourceControl == nil {
return nil
}

if r.SourceControl.Repository == "" {
return fmt.Errorf(`SourceControl.Repository must be present when SourceControl is set`)
}
if r.SourceControl.Revision == "" {
return fmt.Errorf(`SourceControl.Revision must be present when SourceControl is set`)
}
if provider := r.SourceControl.Provider; provider != "" {
if err := validateSourceControlProvider(provider); err != nil {
return err
}
}
return nil
}

func validateSourceControlProvider(provider string) error {
validProviders := []string{"github", "github-enterprise", "bitbucket", "bitbucket-server", "gitlab", "gitlab-onpremise"}
found := false
for _, p := range validProviders {
found = found || p == provider
}
if !found {
return fmt.Errorf(`SourceControl.Provider must be unset (for automatic inference) or one of %v`, validProviders)
}
return nil
}
1 change: 0 additions & 1 deletion builds/validation_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,6 @@ func TestValidate(t *testing.T) {
if err := makeBigValidReq().Validate(); err != nil {
t.Errorf("unexpected error: %v", err)
}

})
t.Run("only bare-minimum populated", func(t *testing.T) {
if err := makeSmallValidReq().Validate(); err != nil {
Expand Down
Loading

0 comments on commit cbd877e

Please sign in to comment.