Skip to content

Commit 45ba3e8

Browse files
authored
errors.Wrapf -> fmt.Errorf, remove dependency on github.com/pkg/errors (#4198)
1 parent 5bbdffb commit 45ba3e8

File tree

11 files changed

+72
-83
lines changed

11 files changed

+72
-83
lines changed

.golangci.yml

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -112,8 +112,6 @@ linters:
112112
depguard:
113113
rules:
114114
wrap:
115-
files:
116-
- '!**/pkg/database/*.go'
117115
deny:
118116
- pkg: github.com/pkg/errors
119117
desc: errors.Wrap() is deprecated in favor of fmt.Errorf()

go.mod

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -66,7 +66,6 @@ require (
6666
github.com/nxadm/tail v1.4.11
6767
github.com/oschwald/geoip2-golang v1.9.0
6868
github.com/oschwald/maxminddb-golang v1.12.0
69-
github.com/pkg/errors v0.9.1
7069
github.com/prometheus/client_golang v1.23.2
7170
github.com/prometheus/client_model v0.6.2
7271
github.com/prometheus/common v0.66.1

pkg/apiserver/alerts_test.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -240,7 +240,7 @@ func TestAlertListFilters(t *testing.T) {
240240

241241
w := lapi.RecordResponse(t, ctx, "GET", "/v1/alerts?test=test", alertContent, "password")
242242
assert.Equal(t, http.StatusInternalServerError, w.Code)
243-
assert.JSONEq(t, `{"message":"Filter parameter 'test' is unknown (=test): invalid filter"}`, w.Body.String())
243+
assert.JSONEq(t, `{"message":"filter parameter 'test' is unknown (=test): invalid filter"}`, w.Body.String())
244244

245245
// get without filters
246246

@@ -418,7 +418,7 @@ func TestListAlert(t *testing.T) {
418418

419419
w := lapi.RecordResponse(t, ctx, "GET", "/v1/alerts?test=test", emptyBody, "password")
420420
assert.Equal(t, http.StatusInternalServerError, w.Code)
421-
assert.JSONEq(t, `{"message":"Filter parameter 'test' is unknown (=test): invalid filter"}`, w.Body.String())
421+
assert.JSONEq(t, `{"message":"filter parameter 'test' is unknown (=test): invalid filter"}`, w.Body.String())
422422

423423
// List Alert
424424

pkg/database/alertfilter.go

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,6 @@ import (
66
"strings"
77
"time"
88

9-
"github.com/pkg/errors"
109
log "github.com/sirupsen/logrus"
1110

1211
"github.com/crowdsecurity/go-cs-lib/cstime"
@@ -148,7 +147,7 @@ func handleAlertIPPredicates(rng csnet.Range, contains bool, predicates *[]predi
148147
case 0:
149148
return nil
150149
default:
151-
return errors.Wrapf(InvalidFilter, "Unknown ip size %d", rng.Size())
150+
return fmt.Errorf("unknown ip size %d: %w", rng.Size(), InvalidFilter)
152151
}
153152
}
154153

@@ -200,7 +199,7 @@ func alertPredicatesFromFilter(filter map[string][]string) ([]predicate.Alert, e
200199
case "contains":
201200
contains, err = strconv.ParseBool(value[0])
202201
if err != nil {
203-
return nil, errors.Wrapf(InvalidFilter, "invalid contains value : %s", err)
202+
return nil, fmt.Errorf("invalid contains value: %w: %w", err, InvalidFilter)
204203
}
205204
case "scope":
206205
handleScopeFilter(value[0], &predicates)
@@ -230,7 +229,7 @@ func alertPredicatesFromFilter(filter map[string][]string) ([]predicate.Alert, e
230229
}
231230
case "has_active_decision":
232231
if hasActiveDecision, err = strconv.ParseBool(value[0]); err != nil {
233-
return nil, errors.Wrapf(ParseType, "'%s' is not a boolean: %s", value[0], err)
232+
return nil, fmt.Errorf("'%s' is not a boolean: %w: %w", value[0], err, ParseType)
234233
}
235234

236235
if hasActiveDecision {
@@ -247,7 +246,7 @@ func alertPredicatesFromFilter(filter map[string][]string) ([]predicate.Alert, e
247246
case "with_decisions":
248247
continue
249248
default:
250-
return nil, errors.Wrapf(InvalidFilter, "Filter parameter '%s' is unknown (=%s)", param, value[0])
249+
return nil, fmt.Errorf("filter parameter '%s' is unknown (=%s): %w", param, value[0], InvalidFilter)
251250
}
252251
}
253252

pkg/database/alerts.go

Lines changed: 19 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -3,13 +3,13 @@ package database
33
import (
44
"context"
55
"encoding/json"
6+
"errors"
67
"fmt"
78
"sort"
89
"strconv"
910
"strings"
1011
"time"
1112

12-
"github.com/pkg/errors"
1313
log "github.com/sirupsen/logrus"
1414

1515
"github.com/crowdsecurity/go-cs-lib/cstime"
@@ -201,7 +201,7 @@ func (c *Client) UpdateCommunityBlocklist(ctx context.Context, alertItem *models
201201

202202
startAtTime, err := time.Parse(time.RFC3339, *alertItem.StartAt)
203203
if err != nil {
204-
return 0, 0, 0, errors.Wrapf(ParseTimeFail, "start_at field time '%s': %s", *alertItem.StartAt, err)
204+
return 0, 0, 0, fmt.Errorf("start_at field time '%s': %w: %w", *alertItem.StartAt, err, ParseTimeFail)
205205
}
206206

207207
if alertItem.StopAt == nil {
@@ -210,7 +210,7 @@ func (c *Client) UpdateCommunityBlocklist(ctx context.Context, alertItem *models
210210

211211
stopAtTime, err := time.Parse(time.RFC3339, *alertItem.StopAt)
212212
if err != nil {
213-
return 0, 0, 0, errors.Wrapf(ParseTimeFail, "stop_at field time '%s': %s", *alertItem.StopAt, err)
213+
return 0, 0, 0, fmt.Errorf("stop_at field time '%s': %w: %w", *alertItem.StopAt, err, ParseTimeFail)
214214
}
215215

216216
ts, err := time.Parse(time.RFC3339, *alertItem.StopAt)
@@ -245,7 +245,7 @@ func (c *Client) UpdateCommunityBlocklist(ctx context.Context, alertItem *models
245245

246246
alertRef, err := alertB.Save(ctx)
247247
if err != nil {
248-
return 0, 0, 0, errors.Wrapf(BulkError, "error creating alert : %s", err)
248+
return 0, 0, 0, fmt.Errorf("error creating alert: %w: %w", err, BulkError)
249249
}
250250

251251
if len(alertItem.Decisions) == 0 {
@@ -254,7 +254,7 @@ func (c *Client) UpdateCommunityBlocklist(ctx context.Context, alertItem *models
254254

255255
txClient, err := c.Ent.Tx(ctx)
256256
if err != nil {
257-
return 0, 0, 0, errors.Wrapf(BulkError, "error creating transaction : %s", err)
257+
return 0, 0, 0, fmt.Errorf("error creating transaction: %w: %w", err, BulkError)
258258
}
259259

260260
decOrigin := CapiMachineID
@@ -373,7 +373,7 @@ func (c *Client) createDecisionBatch(ctx context.Context, simulated bool, stopAt
373373

374374
duration, err := cstime.ParseDurationWithDays(*decisionItem.Duration)
375375
if err != nil {
376-
return nil, errors.Wrapf(ParseDurationFail, "decision duration '%+v' : %s", *decisionItem.Duration, err)
376+
return nil, fmt.Errorf("decision duration '%+v': %w: %w", *decisionItem.Duration, err, ParseDurationFail)
377377
}
378378

379379
// if the scope is IP or Range, convert the value to integers
@@ -456,7 +456,7 @@ func buildEventCreates(ctx context.Context, logger log.FieldLogger, client *ent.
456456

457457
marshallMetas, err := json.Marshal(eventItem.Meta)
458458
if err != nil {
459-
return nil, errors.Wrapf(MarshalFail, "event meta '%v' : %s", eventItem.Meta, err)
459+
return nil, fmt.Errorf("event meta '%v': %w: %w", eventItem.Meta, err, MarshalFail)
460460
}
461461

462462
// the serialized field is too big, let's try to progressively strip it
@@ -475,7 +475,7 @@ func buildEventCreates(ctx context.Context, logger log.FieldLogger, client *ent.
475475

476476
marshallMetas, err = json.Marshal(eventItem.Meta)
477477
if err != nil {
478-
return nil, errors.Wrapf(MarshalFail, "event meta '%v' : %s", eventItem.Meta, err)
478+
return nil, fmt.Errorf("event meta '%v': %w: %w", eventItem.Meta, err, MarshalFail)
479479
}
480480

481481
if event.SerializedValidator(string(marshallMetas)) == nil {
@@ -599,7 +599,7 @@ func saveAlerts(ctx context.Context, c *Client, batch []alertCreatePlan) ([]stri
599599

600600
alertsCreateBulk, err := c.Ent.Alert.CreateBulk(builders...).Save(ctx)
601601
if err != nil {
602-
return nil, errors.Wrapf(BulkError, "bulk creating alert : %s", err)
602+
return nil, fmt.Errorf("bulk creating alert: %w: %w", err, BulkError)
603603
}
604604

605605
ret := make([]string, len(alertsCreateBulk))
@@ -798,7 +798,7 @@ func (c *Client) QueryAlertWithFilter(ctx context.Context, filter map[string][]s
798798
if val, ok := filter["limit"]; ok {
799799
limitConv, err := strconv.Atoi(val[0])
800800
if err != nil {
801-
return nil, errors.Wrapf(QueryFail, "bad limit in parameters: %s", val)
801+
return nil, fmt.Errorf("bad limit in parameters: %s: %w", val, QueryFail)
802802
}
803803

804804
limit = limitConv
@@ -843,7 +843,7 @@ func (c *Client) QueryAlertWithFilter(ctx context.Context, filter map[string][]s
843843

844844
result, err := alerts.Limit(paginationSize).Offset(offset).All(ctx)
845845
if err != nil {
846-
return nil, errors.Wrapf(QueryFail, "pagination size: %d, offset: %d: %s", paginationSize, offset, err)
846+
return nil, fmt.Errorf("pagination size: %d, offset: %d: %w: %w", paginationSize, offset, err, QueryFail)
847847
}
848848

849849
if len(result) == 0 { // no results, no need to try to paginate further
@@ -888,28 +888,28 @@ func (c *Client) DeleteAlertGraphBatch(ctx context.Context, alertItems []*ent.Al
888888
Where(event.HasOwnerWith(alert.IDIn(idList...))).Exec(ctx)
889889
if err != nil {
890890
c.Log.Warningf("DeleteAlertGraphBatch : %s", err)
891-
return 0, errors.Wrapf(DeleteFail, "alert graph delete batch events")
891+
return 0, fmt.Errorf("alert graph delete batch events: %w", DeleteFail)
892892
}
893893

894894
_, err = c.Ent.Meta.Delete().
895895
Where(meta.HasOwnerWith(alert.IDIn(idList...))).Exec(ctx)
896896
if err != nil {
897897
c.Log.Warningf("DeleteAlertGraphBatch : %s", err)
898-
return 0, errors.Wrapf(DeleteFail, "alert graph delete batch meta")
898+
return 0, fmt.Errorf("alert graph delete batch meta: %w", DeleteFail)
899899
}
900900

901901
_, err = c.Ent.Decision.Delete().
902902
Where(decision.HasOwnerWith(alert.IDIn(idList...))).Exec(ctx)
903903
if err != nil {
904904
c.Log.Warningf("DeleteAlertGraphBatch : %s", err)
905-
return 0, errors.Wrapf(DeleteFail, "alert graph delete batch decisions")
905+
return 0, fmt.Errorf("alert graph delete batch decisions: %w", DeleteFail)
906906
}
907907

908908
deleted, err := c.Ent.Alert.Delete().
909909
Where(alert.IDIn(idList...)).Exec(ctx)
910910
if err != nil {
911911
c.Log.Warningf("DeleteAlertGraphBatch : %s", err)
912-
return deleted, errors.Wrapf(DeleteFail, "alert graph delete batch")
912+
return deleted, fmt.Errorf("alert graph delete batch: %w", DeleteFail)
913913
}
914914

915915
c.Log.Debug("Done batch delete alerts")
@@ -923,30 +923,30 @@ func (c *Client) DeleteAlertGraph(ctx context.Context, alertItem *ent.Alert) err
923923
Where(event.HasOwnerWith(alert.IDEQ(alertItem.ID))).Exec(ctx)
924924
if err != nil {
925925
c.Log.Warningf("DeleteAlertGraph : %s", err)
926-
return errors.Wrapf(DeleteFail, "event with alert ID '%d'", alertItem.ID)
926+
return fmt.Errorf("event with alert ID '%d': %w", alertItem.ID, DeleteFail)
927927
}
928928

929929
// delete the associated meta
930930
_, err = c.Ent.Meta.Delete().
931931
Where(meta.HasOwnerWith(alert.IDEQ(alertItem.ID))).Exec(ctx)
932932
if err != nil {
933933
c.Log.Warningf("DeleteAlertGraph : %s", err)
934-
return errors.Wrapf(DeleteFail, "meta with alert ID '%d'", alertItem.ID)
934+
return fmt.Errorf("meta with alert ID '%d': %w", alertItem.ID, DeleteFail)
935935
}
936936

937937
// delete the associated decisions
938938
_, err = c.Ent.Decision.Delete().
939939
Where(decision.HasOwnerWith(alert.IDEQ(alertItem.ID))).Exec(ctx)
940940
if err != nil {
941941
c.Log.Warningf("DeleteAlertGraph : %s", err)
942-
return errors.Wrapf(DeleteFail, "decision with alert ID '%d'", alertItem.ID)
942+
return fmt.Errorf("decision with alert ID '%d': %w", alertItem.ID, DeleteFail)
943943
}
944944

945945
// delete the alert
946946
err = c.Ent.Alert.DeleteOne(alertItem).Exec(ctx)
947947
if err != nil {
948948
c.Log.Warningf("DeleteAlertGraph : %s", err)
949-
return errors.Wrapf(DeleteFail, "alert with ID '%d'", alertItem.ID)
949+
return fmt.Errorf("alert with ID '%d': %w", alertItem.ID, DeleteFail)
950950
}
951951

952952
return nil

pkg/database/bouncers.go

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -6,8 +6,6 @@ import (
66
"strings"
77
"time"
88

9-
"github.com/pkg/errors"
10-
119
"github.com/crowdsecurity/crowdsec/pkg/database/ent"
1210
"github.com/crowdsecurity/crowdsec/pkg/database/ent/bouncer"
1311
"github.com/crowdsecurity/crowdsec/pkg/models"
@@ -43,8 +41,8 @@ func (c *Client) BouncerUpdateBaseMetrics(ctx context.Context, bouncerName strin
4341
}
4442

4543
func (c *Client) SelectBouncers(ctx context.Context, apiKeyHash string, authType string) ([]*ent.Bouncer, error) {
46-
//Order by ID so manually created bouncer will be first in the list to use as the base name
47-
//when automatically creating a new entry if API keys are shared
44+
// Order by ID so manually created bouncer will be first in the list to use as the base name
45+
// when automatically creating a new entry if API keys are shared
4846
result, err := c.Ent.Bouncer.Query().Where(bouncer.APIKeyEQ(apiKeyHash), bouncer.AuthTypeEQ(authType)).Order(ent.Asc(bouncer.FieldID)).All(ctx)
4947
if err != nil {
5048
return nil, err
@@ -74,7 +72,7 @@ func (c *Client) SelectBouncerByName(ctx context.Context, bouncerName string) (*
7472
func (c *Client) ListBouncers(ctx context.Context) ([]*ent.Bouncer, error) {
7573
result, err := c.Ent.Bouncer.Query().All(ctx)
7674
if err != nil {
77-
return nil, errors.Wrapf(QueryFail, "listing bouncers: %s", err)
75+
return nil, fmt.Errorf("listing bouncers: %w: %w", err, QueryFail)
7876
}
7977

8078
return result, nil

pkg/database/config.go

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,6 @@ import (
44
"context"
55
"fmt"
66

7-
"github.com/pkg/errors"
8-
97
"github.com/crowdsecurity/crowdsec/pkg/database/ent"
108
"github.com/crowdsecurity/crowdsec/pkg/database/ent/configitem"
119
)
@@ -17,7 +15,7 @@ func (c *Client) GetConfigItem(ctx context.Context, key string) (string, error)
1715
case ent.IsNotFound(err):
1816
return "", nil
1917
case err != nil:
20-
return "", errors.Wrapf(QueryFail, "select config item: %s", err)
18+
return "", fmt.Errorf("select config item: %w: %w", err, QueryFail)
2119
default:
2220
return result.Value, nil
2321
}

pkg/database/decisionfilter.go

Lines changed: 10 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -5,8 +5,6 @@ import (
55
"strconv"
66
"strings"
77

8-
"github.com/pkg/errors"
9-
108
"github.com/crowdsecurity/crowdsec/pkg/csnet"
119
"github.com/crowdsecurity/crowdsec/pkg/database/ent"
1210
"github.com/crowdsecurity/crowdsec/pkg/database/ent/decision"
@@ -40,7 +38,7 @@ func applyDecisionFilter(query *ent.DecisionQuery, filter map[string][]string) (
4038
case "contains":
4139
contains, err = strconv.ParseBool(value[0])
4240
if err != nil {
43-
return nil, errors.Wrapf(InvalidFilter, "invalid contains value : %s", err)
41+
return nil, fmt.Errorf("invalid contains value: %w: %w", err, InvalidFilter)
4442
}
4543
case "scopes", "scope": // Swagger mentions both of them, let's just support both to make sure we don't break anything
4644
scopes := strings.Split(value[0], ",")
@@ -79,26 +77,26 @@ func applyDecisionFilter(query *ent.DecisionQuery, filter map[string][]string) (
7977
case "ip", "range":
8078
rng, err = csnet.NewRange(value[0])
8179
if err != nil {
82-
return nil, errors.Wrapf(InvalidIPOrRange, "unable to convert '%s' to int: %s", value[0], err)
80+
return nil, fmt.Errorf("unable to convert '%s' to int: %w: %w", value[0], err, InvalidIPOrRange)
8381
}
8482
case "limit":
8583
limit, err := strconv.Atoi(value[0])
8684
if err != nil {
87-
return nil, errors.Wrapf(InvalidFilter, "invalid limit value : %s", err)
85+
return nil, fmt.Errorf("invalid limit value: %w: %w", err, InvalidFilter)
8886
}
8987

9088
query = query.Limit(limit)
9189
case "offset":
9290
offset, err := strconv.Atoi(value[0])
9391
if err != nil {
94-
return nil, errors.Wrapf(InvalidFilter, "invalid offset value : %s", err)
92+
return nil, fmt.Errorf("invalid offset value: %w: %w", err, InvalidFilter)
9593
}
9694

9795
query = query.Offset(offset)
9896
case "id_gt":
9997
id, err := strconv.Atoi(value[0])
10098
if err != nil {
101-
return nil, errors.Wrapf(InvalidFilter, "invalid id_gt value : %s", err)
99+
return nil, fmt.Errorf("invalid id_gt value: %w: %w", err, InvalidFilter)
102100
}
103101

104102
query = query.Where(decision.IDGT(id))
@@ -115,22 +113,22 @@ func applyDecisionFilter(query *ent.DecisionQuery, filter map[string][]string) (
115113

116114
func decisionIPv4Filter(decisions *ent.DecisionQuery, contains bool, rng csnet.Range) (*ent.DecisionQuery, error) {
117115
if contains {
118-
/*Decision contains {start_ip,end_ip}*/
116+
// Decision contains {start_ip,end_ip}
119117
return decisions.Where(decision.And(
120118
decision.StartIPLTE(rng.Start.Addr),
121119
decision.EndIPGTE(rng.End.Addr),
122120
decision.IPSizeEQ(int64(rng.Size())))), nil
123121
}
124122

125-
/*Decision is contained within {start_ip,end_ip}*/
123+
// Decision is contained within {start_ip,end_ip}
126124
return decisions.Where(decision.And(
127125
decision.StartIPGTE(rng.Start.Addr),
128126
decision.EndIPLTE(rng.End.Addr),
129127
decision.IPSizeEQ(int64(rng.Size())))), nil
130128
}
131129

132130
func decisionIPv6Filter(decisions *ent.DecisionQuery, contains bool, rng csnet.Range) (*ent.DecisionQuery, error) {
133-
/*decision contains {start_ip,end_ip}*/
131+
// decision contains {start_ip,end_ip}
134132
if contains {
135133
return decisions.Where(decision.And(
136134
// matching addr size
@@ -157,7 +155,7 @@ func decisionIPv6Filter(decisions *ent.DecisionQuery, contains bool, rng csnet.R
157155
)), nil
158156
}
159157

160-
/*decision is contained within {start_ip,end_ip}*/
158+
// decision is contained within {start_ip,end_ip}
161159
return decisions.Where(decision.And(
162160
// matching addr size
163161
decision.IPSizeEQ(int64(rng.Size())),
@@ -192,7 +190,7 @@ func decisionIPFilter(decisions *ent.DecisionQuery, contains bool, rng csnet.Ran
192190
case 0:
193191
return decisions, nil
194192
default:
195-
return nil, errors.Wrapf(InvalidFilter, "unknown ip size %d", rng.Size())
193+
return nil, fmt.Errorf("unknown ip size %d: %w", rng.Size(), InvalidFilter)
196194
}
197195
}
198196

0 commit comments

Comments
 (0)