Skip to content

Commit

Permalink
chore: use typed error and fix missing wraps
Browse files Browse the repository at this point in the history
  • Loading branch information
crazy-max committed Sep 16, 2023
1 parent 20681d6 commit 24bc054
Show file tree
Hide file tree
Showing 24 changed files with 109 additions and 94 deletions.
3 changes: 3 additions & 0 deletions .golangci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,9 @@ linters-settings:
# The io/ioutil package has been deprecated.
# https://go.dev/doc/go1.16#ioutil
- io/ioutil
forbidigo:
forbid:
- '^fmt\.Errorf(# use errors\.Errorf instead)?$'
importas:
no-unaliased: true

Expand Down
2 changes: 1 addition & 1 deletion internal/app/diun.go
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ func New(meta model.Meta, cfg *config.Config, grpcAuthority string) (*Diun, erro
if len(cfg.Watch.Healthchecks.BaseURL) > 0 {
hcBaseURL, err = url.Parse(cfg.Watch.Healthchecks.BaseURL)
if err != nil {
return nil, errors.Wrap(err, "Cannot parse Healthchecks base URL")
return nil, errors.Wrap(err, "cannot parse Healthchecks base URL")
}
}
diun.hc = gohealthchecks.NewClient(&gohealthchecks.ClientOptions{
Expand Down
10 changes: 5 additions & 5 deletions internal/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ func Load(config string) (*Config, error) {
},
})
if found, err := fileLoader.Load(&cfg); err != nil {
return nil, errors.Wrap(err, "Failed to decode configuration from file")
return nil, errors.Wrap(err, "failed to decode configuration from file")
} else if !found {
log.Debug().Msg("No configuration file found")
} else {
Expand All @@ -47,7 +47,7 @@ func Load(config string) (*Config, error) {
Prefix: "DIUN_",
})
if found, err := envLoader.Load(&cfg); err != nil {
return nil, errors.Wrap(err, "Failed to decode configuration from environment variables")
return nil, errors.Wrap(err, "failed to decode configuration from environment variables")
} else if !found {
log.Debug().Msg("No DIUN_* environment variables defined")
} else {
Expand All @@ -64,16 +64,16 @@ func Load(config string) (*Config, error) {
func (cfg *Config) validate() error {
if len(cfg.Db.Path) > 0 {
if err := os.MkdirAll(path.Dir(cfg.Db.Path), os.ModePerm); err != nil {
return errors.Wrap(err, "Cannot create database destination folder")
return errors.Wrap(err, "cannot create database destination folder")
}
}

if cfg.Watch.Healthchecks != nil && len(cfg.Watch.Healthchecks.UUID) == 0 {
return errors.New("Healthchecks UUID is required")
return errors.New("healthchecks UUID is required")
}

if cfg.Providers == nil {
return errors.New("At least one provider is required")
return errors.New("at least one provider is required")
}

return validator.New().Struct(cfg)
Expand Down
2 changes: 1 addition & 1 deletion internal/db/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ func New(cfg model.Db) (*Client, error) {
log.Debug().Msgf("%d entries found in manifest bucket", stats.KeyN)
return nil
}); err != nil {
return nil, errors.Wrap(err, "Cannot count entries in manifest bucket")
return nil, errors.Wrap(err, "cannot count entries in manifest bucket")
}

c := &Client{
Expand Down
5 changes: 2 additions & 3 deletions internal/db/migrate.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ package db

import (
"encoding/json"
"fmt"
"time"

"github.com/opencontainers/go-digest"
Expand All @@ -24,12 +23,12 @@ func (c *Client) Migrate() error {
for version := c.metadata.Version + 1; version <= dbVersion; version++ {
migration, found := migrations[version]
if !found {
return fmt.Errorf("database migration v%d not found", version)
return errors.Errorf("database migration v%d not found", version)
}

log.Info().Msgf("Database migration v%d...", version)
if err := migration(c); err != nil {
return errors.Wrapf(err, "Database migration v%d failed", version)
return errors.Wrapf(err, "database migration v%d failed", version)
}
}

Expand Down
2 changes: 1 addition & 1 deletion internal/grpc/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ func (c *Client) Start() error {

lis, err := net.Listen("tcp", c.authority)
if err != nil {
return errors.Wrap(err, "Cannot create gRPC listener")
return errors.Wrap(err, "cannot create gRPC listener")
}

return c.server.Serve(lis)
Expand Down
3 changes: 2 additions & 1 deletion internal/grpc/image.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (

"github.com/containers/image/v5/docker/reference"
"github.com/crazy-max/diun/v4/pb"
"github.com/pkg/errors"
"google.golang.org/protobuf/types/known/timestamppb"
)

Expand Down Expand Up @@ -55,7 +56,7 @@ func (c *Client) ImageInspect(ctx context.Context, request *pb.ImageInspectReque
}

if _, ok := images[ref.Name()]; !ok {
return nil, fmt.Errorf("%s not found in database", ref.Name())
return nil, errors.Errorf("%s not found in database", ref.Name())
}

iir := &pb.ImageInspectResponse_Image{
Expand Down
4 changes: 2 additions & 2 deletions internal/model/regopts.go
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
package model

import (
"fmt"
"strings"
"time"

"github.com/crazy-max/diun/v4/pkg/registry"
"github.com/crazy-max/diun/v4/pkg/utl"
"github.com/pkg/errors"
)

// RegOpts holds slice of registry options
Expand Down Expand Up @@ -60,5 +60,5 @@ func (s *RegOpts) Select(name string, image registry.Image) (*RegOpt, error) {
if len(name) == 0 {
return nil, nil
}
return nil, fmt.Errorf("%s not found", name)
return nil, errors.Errorf("%s not found", name)
}
8 changes: 4 additions & 4 deletions internal/msg/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ func (c *Client) RenderMarkdown() (title []byte, body []byte, _ error) {
var titleBuf bytes.Buffer
titleTpl, err := template.New("title").Funcs(c.opts.TemplateFuncs).Parse(strings.TrimSuffix(strings.TrimSpace(c.opts.TemplateTitle), "\n"))
if err != nil {
return title, body, errors.Wrap(err, "Cannot parse title template")
return title, body, errors.Wrap(err, "cannot parse title template")
}
if err = titleTpl.Execute(&titleBuf, struct {
Meta model.Meta
Expand All @@ -50,14 +50,14 @@ func (c *Client) RenderMarkdown() (title []byte, body []byte, _ error) {
Meta: c.opts.Meta,
Entry: c.opts.Entry,
}); err != nil {
return title, body, errors.Wrap(err, "Cannot render notif title")
return title, body, errors.Wrap(err, "cannot render notif title")
}
title = titleBuf.Bytes()

var bodyBuf bytes.Buffer
bodyTpl, err := template.New("body").Funcs(c.opts.TemplateFuncs).Parse(strings.TrimSuffix(strings.TrimSpace(c.opts.TemplateBody), "\n"))
if err != nil {
return title, body, errors.Wrap(err, "Cannot parse body template")
return title, body, errors.Wrap(err, "cannot parse body template")
}
if err = bodyTpl.Execute(&bodyBuf, struct {
Meta model.Meta
Expand All @@ -66,7 +66,7 @@ func (c *Client) RenderMarkdown() (title []byte, body []byte, _ error) {
Meta: c.opts.Meta,
Entry: c.opts.Entry,
}); err != nil {
return title, body, errors.Wrap(err, "Cannot render notif body")
return title, body, errors.Wrap(err, "cannot render notif body")
}
body = bodyBuf.Bytes()

Expand Down
3 changes: 2 additions & 1 deletion internal/notif/discord/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import (
"github.com/crazy-max/diun/v4/internal/model"
"github.com/crazy-max/diun/v4/internal/msg"
"github.com/crazy-max/diun/v4/internal/notif/notifier"
"github.com/pkg/errors"
)

// Client represents an active discord notification object
Expand Down Expand Up @@ -138,7 +139,7 @@ func (c *Client) Send(entry model.NotifEntry) error {
}

if resp.StatusCode != http.StatusNoContent {
return fmt.Errorf("unexpected HTTP status %d: %s", resp.StatusCode, resp.Body)
return errors.Errorf("unexpected HTTP status %d: %s", resp.StatusCode, resp.Body)
}

return nil
Expand Down
5 changes: 2 additions & 3 deletions internal/notif/gotify/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ package gotify
import (
"bytes"
"encoding/json"
"fmt"
"net/http"
"net/url"
"path"
Expand Down Expand Up @@ -42,7 +41,7 @@ func (c *Client) Name() string {
func (c *Client) Send(entry model.NotifEntry) error {
token, err := utl.GetSecret(c.cfg.Token, c.cfg.TokenFile)
if err != nil {
return errors.New("Cannot retrieve token secret for Gotify notifier")
return errors.Wrap(err, "cannot retrieve token secret for Gotify notifier")
}

hc := http.Client{
Expand Down Expand Up @@ -117,7 +116,7 @@ func (c *Client) Send(entry model.NotifEntry) error {
if err != nil {
return err
}
return fmt.Errorf("%d %s: %s", errBody.ErrorCode, errBody.Error, errBody.ErrorDescription)
return errors.Errorf("%d %s: %s", errBody.ErrorCode, errBody.Error, errBody.ErrorDescription)
}

return nil
Expand Down
5 changes: 3 additions & 2 deletions internal/notif/mail/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import (
"github.com/crazy-max/diun/v4/pkg/utl"
"github.com/go-gomail/gomail"
"github.com/matcornic/hermes/v2"
"github.com/pkg/errors"
"github.com/rs/zerolog/log"
)

Expand Down Expand Up @@ -89,13 +90,13 @@ func (c *Client) Send(entry model.NotifEntry) error {
// Generate an HTML email with the provided contents (for modern clients)
htmlpart, err := h.GenerateHTML(email)
if err != nil {
return fmt.Errorf("hermes: %v", err)
return errors.Wrap(err, "cannot generate HTML email")
}

// Generate the plaintext version of the e-mail (for clients that do not support xHTML)
textpart, err := h.GeneratePlainText(email)
if err != nil {
return fmt.Errorf("hermes: %v", err)
return errors.Wrap(err, "cannot generate plaintext email")
}

mailMessage := gomail.NewMessage()
Expand Down
4 changes: 2 additions & 2 deletions internal/notif/matrix/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -48,11 +48,11 @@ func (c *Client) Send(entry model.NotifEntry) error {

user, err := utl.GetSecret(c.cfg.User, c.cfg.UserFile)
if err != nil {
return errors.New("Cannot retrieve username secret for Matrix notifier")
return errors.Wrap(err, "cannot retrieve username secret for Matrix notifier")
}
password, err := utl.GetSecret(c.cfg.Password, c.cfg.PasswordFile)
if err != nil {
return errors.New("Cannot retrieve password secret for Matrix notifier")
return errors.Wrap(err, "cannot retrieve password secret for Matrix notifier")
}

r, err := m.Login(&gomatrix.ReqLogin{
Expand Down
3 changes: 2 additions & 1 deletion internal/notif/ntfy/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import (
"github.com/crazy-max/diun/v4/internal/msg"
"github.com/crazy-max/diun/v4/internal/notif/notifier"
"github.com/crazy-max/diun/v4/pkg/utl"
"github.com/pkg/errors"
)

// Client represents an active ntfy notification object
Expand Down Expand Up @@ -107,7 +108,7 @@ func (c *Client) Send(entry model.NotifEntry) error {
if err != nil {
return err
}
return fmt.Errorf("%d %s: %s", errBody.ErrorCode, errBody.Error, errBody.ErrorDescription)
return errors.Errorf("%d %s: %s", errBody.ErrorCode, errBody.Error, errBody.ErrorDescription)
}

return nil
Expand Down
4 changes: 2 additions & 2 deletions internal/notif/pushover/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,12 +37,12 @@ func (c *Client) Name() string {
func (c *Client) Send(entry model.NotifEntry) error {
token, err := utl.GetSecret(c.cfg.Token, c.cfg.TokenFile)
if err != nil {
return errors.New("Cannot retrieve token secret for Pushover notifier")
return errors.Wrap(err, "cannot retrieve token secret for Pushover notifier")
}

recipient, err := utl.GetSecret(c.cfg.Recipient, c.cfg.RecipientFile)
if err != nil {
return errors.New("Cannot retrieve recipient secret for Pushover notifier")
return errors.Wrap(err, "cannot retrieve recipient secret for Pushover notifier")
}

message, err := msg.New(msg.Options{
Expand Down
5 changes: 2 additions & 3 deletions internal/notif/rocketchat/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ package rocketchat
import (
"bytes"
"encoding/json"
"fmt"
"net/http"
"net/url"
"path"
Expand Down Expand Up @@ -44,7 +43,7 @@ func (c *Client) Name() string {
func (c *Client) Send(entry model.NotifEntry) error {
token, err := utl.GetSecret(c.cfg.Token, c.cfg.TokenFile)
if err != nil {
return errors.New("Cannot retrieve token secret for RocketChat notifier")
return errors.Wrap(err, "cannot retrieve token secret for RocketChat notifier")
}

hc := http.Client{
Expand Down Expand Up @@ -152,7 +151,7 @@ func (c *Client) Send(entry model.NotifEntry) error {
}

if resp.StatusCode != http.StatusOK {
return fmt.Errorf("HTTP error %d: %s", resp.StatusCode, respBody.ErrorType)
return errors.Errorf("unexpected HTTP error %d: %s", resp.StatusCode, respBody.ErrorType)
}

return nil
Expand Down
6 changes: 3 additions & 3 deletions internal/notif/telegram/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,17 +39,17 @@ func (c *Client) Name() string {
func (c *Client) Send(entry model.NotifEntry) error {
token, err := utl.GetSecret(c.cfg.Token, c.cfg.TokenFile)
if err != nil {
return errors.New("Cannot retrieve token secret for Telegram notifier")
return errors.Wrap(err, "cannot retrieve token secret for Telegram notifier")
}

chatIDs := c.cfg.ChatIDs
chatIDsRaw, err := utl.GetSecret("", c.cfg.ChatIDsFile)
if err != nil {
return errors.New("Cannot retrieve chat IDs secret for Telegram notifier")
return errors.Wrap(err, "cannot retrieve chat IDs secret for Telegram notifier")
}
if len(chatIDsRaw) > 0 {
if err = json.Unmarshal([]byte(chatIDsRaw), &chatIDs); err != nil {
return errors.New("Cannot unmarshal chat IDs secret for Telegram notifier")
return errors.Wrap(err, "cannot unmarshal chat IDs secret for Telegram notifier")
}
}

Expand Down
Loading

0 comments on commit 24bc054

Please sign in to comment.