Skip to content

Commit 6758a65

Browse files
committed
golangci-lint migrate
1 parent e791b92 commit 6758a65

File tree

13 files changed

+200
-135
lines changed

13 files changed

+200
-135
lines changed

backend/.golangci.yml

Lines changed: 57 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,37 +1,83 @@
1+
version: "2"
12
run:
23
tests: false
3-
timeout: 5m
44
linters:
5+
default: none
56
enable:
67
- bodyclose
78
- copyloopvar
89
- dogsled
910
- dupl
1011
- errcheck
1112
- gochecknoinits
13+
- gocognit
1214
- goconst
1315
- gocritic
1416
- gocyclo
15-
- gofmt
16-
- goimports
1717
- goprintffuncname
1818
- gosec
19-
- gosimple
2019
- govet
2120
- ineffassign
2221
- misspell
2322
- nakedret
23+
- nolintlint
24+
- prealloc
2425
- revive
2526
- rowserrcheck
2627
- staticcheck
27-
- stylecheck
28-
- typecheck
28+
- testifylint
2929
- unconvert
3030
- unparam
3131
- unused
3232
- whitespace
33-
disable-all: true
34-
35-
issues:
36-
exclude-dirs:
37-
- vendor
33+
settings:
34+
goconst:
35+
min-len: 2
36+
min-occurrences: 2
37+
revive:
38+
enable-all-rules: true
39+
rules:
40+
- name: unused-receiver
41+
disabled: true
42+
- name: line-length-limit
43+
disabled: true
44+
- name: add-constant
45+
disabled: true
46+
- name: cognitive-complexity
47+
disabled: true
48+
- name: function-length
49+
disabled: true
50+
- name: cyclomatic
51+
disabled: true
52+
- name: nested-structs
53+
disabled: true
54+
gocritic:
55+
disabled-checks:
56+
- hugeParam
57+
enabled-tags:
58+
- performance
59+
- style
60+
- experimental
61+
govet:
62+
enable:
63+
- shadow
64+
lll:
65+
line-length: 140
66+
misspell:
67+
locale: US
68+
exclusions:
69+
generated: lax
70+
paths:
71+
- third_party$
72+
- builtin$
73+
- examples$
74+
formatters:
75+
enable:
76+
- gofmt
77+
- goimports
78+
exclusions:
79+
generated: lax
80+
paths:
81+
- third_party$
82+
- builtin$
83+
- examples$

backend/datastore/mongo_test.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -24,9 +24,9 @@ func TestMongoCreation(t *testing.T) {
2424

2525
func TestWrongConnectionString(t *testing.T) {
2626
server, err := New("wrong", "test_ureadability", time.Millisecond*100)
27-
assert.Error(t, err)
27+
require.Error(t, err)
2828
assert.Nil(t, server)
2929
server, err = New("", "", time.Millisecond*100)
30-
assert.Error(t, err)
30+
require.Error(t, err)
3131
assert.Nil(t, server)
3232
}

backend/datastore/rules.go

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,7 @@ func (r RulesDAO) Get(ctx context.Context, rURL string) (Rule, bool) {
4242
var rules []Rule
4343
q := bson.M{"domain": u.Host, "enabled": true}
4444
log.Printf("[DEBUG] query %v", q)
45-
cursor, err := r.Collection.Find(ctx, q)
45+
cursor, err := r.Find(ctx, q)
4646
if err != nil {
4747
log.Printf("[DEBUG] error looking for rules for %s", rURL)
4848
return Rule{}, false
@@ -65,13 +65,15 @@ func (r RulesDAO) GetByID(ctx context.Context, id primitive.ObjectID) (Rule, boo
6565

6666
// Save upsert rule
6767
func (r RulesDAO) Save(ctx context.Context, rule Rule) (Rule, error) {
68-
ch, err := r.Collection.UpdateOne(ctx, bson.M{"domain": rule.Domain}, bson.M{"$set": rule}, options.Update().SetUpsert(true))
68+
ch, err := r.UpdateOne(ctx, bson.M{"domain": rule.Domain}, bson.M{"$set": rule}, options.Update().SetUpsert(true))
6969
if err != nil {
7070
log.Printf("[WARN] failed to save, error=%v, article=%v", err, rule)
7171
return rule, err
7272
}
7373
if ch.UpsertedID != nil {
74-
rule.ID = ch.UpsertedID.(primitive.ObjectID)
74+
if oid, ok := ch.UpsertedID.(primitive.ObjectID); ok {
75+
rule.ID = oid
76+
}
7577
}
7678
// if rule was updated, we have no id, so try to find it by domain
7779
if rule.ID == primitive.NilObjectID {
@@ -86,13 +88,13 @@ func (r RulesDAO) Save(ctx context.Context, rule Rule) (Rule, error) {
8688

8789
// Disable marks enabled=false, by id
8890
func (r RulesDAO) Disable(ctx context.Context, id primitive.ObjectID) error {
89-
_, err := r.Collection.UpdateOne(ctx, bson.M{"_id": id}, bson.M{"$set": bson.M{"enabled": false}})
91+
_, err := r.UpdateOne(ctx, bson.M{"_id": id}, bson.M{"$set": bson.M{"enabled": false}})
9092
return err
9193
}
9294

9395
// All returns list of all rules, both enabled and disabled
9496
func (r RulesDAO) All(ctx context.Context) []Rule {
95-
cursor, err := r.Collection.Find(ctx, bson.M{})
97+
cursor, err := r.Find(ctx, bson.M{})
9698
if err != nil {
9799
log.Printf("[WARN] failed to retrieve all rules, error=%v", err)
98100
return []Rule{}

backend/datastore/rules_test.go

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@ func TestRules(t *testing.T) {
2828

2929
// save a rule
3030
srule, err := rules.Save(context.Background(), rule)
31-
assert.NoError(t, err)
31+
require.NoError(t, err)
3232
assert.Equal(t, rule.Domain, srule.Domain)
3333
ruleID := srule.ID
3434

@@ -46,7 +46,7 @@ func TestRules(t *testing.T) {
4646

4747
// disable the rule
4848
err = rules.Disable(context.Background(), grule.ID)
49-
assert.NoError(t, err)
49+
require.NoError(t, err)
5050
assert.NotContains(t, rules.All(context.Background()), grule)
5151

5252
// get the rule by ID, should be marked as disabled
@@ -64,7 +64,7 @@ func TestRules(t *testing.T) {
6464

6565
// save a rule once more, should result in the same ID
6666
updatedRule, err := rules.Save(context.Background(), rule)
67-
assert.NoError(t, err)
67+
require.NoError(t, err)
6868
assert.Equal(t, rule.Domain, updatedRule.Domain)
6969
assert.Equal(t, ruleID, updatedRule.ID)
7070
}
@@ -84,7 +84,7 @@ func TestRulesCanceledContext(t *testing.T) {
8484
rule := Rule{Domain: "example.com", Enabled: true}
8585
srule, err := rules.Save(ctx, rule)
8686
assert.Equal(t, rule, srule)
87-
assert.Error(t, err)
87+
require.Error(t, err)
8888

8989
// retrieve a rule, wrong rule
9090
grule, found := rules.Get(context.Background(), "http://user^:passwo^[email protected]/")
@@ -95,7 +95,7 @@ func TestRulesCanceledContext(t *testing.T) {
9595
assert.Empty(t, grule, "canceled context")
9696
assert.False(t, found, "canceled context")
9797
assert.Empty(t, rules.All(ctx))
98-
assert.Error(t, rules.Disable(ctx, rule.ID))
98+
require.Error(t, rules.Disable(ctx, rule.ID))
9999
// get a rule by ID with canceled context
100100
grule, found = rules.GetByID(ctx, rule.ID)
101101
assert.Empty(t, grule)

backend/extractor/pics.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -60,7 +60,7 @@ func (f *UReadability) extractPics(iselect *goquery.Selection, url string) (main
6060
// getImageSize loads image to get size
6161
func (f *UReadability) getImageSize(url string) (size int) {
6262
httpClient := &http.Client{Timeout: 30 * time.Second}
63-
req, err := http.NewRequest("GET", url, nil)
63+
req, err := http.NewRequest("GET", url, http.NoBody)
6464
if err != nil {
6565
log.Printf("[WARN] can't create request to get pic from %s", url)
6666
return 0

backend/extractor/pics_test.go

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -20,10 +20,10 @@ func TestExtractPics(t *testing.T) {
2020
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
2121
fh, err := os.Open("testdata/poiezdka-s-apple-maps.html")
2222
testHTML, err := io.ReadAll(fh)
23-
require.NoError(t, err)
24-
require.NoError(t, fh.Close())
23+
assert.NoError(t, err)
24+
assert.NoError(t, fh.Close())
2525
_, err = w.Write(testHTML)
26-
require.NoError(t, err)
26+
assert.NoError(t, err)
2727
}))
2828
defer ts.Close()
2929

@@ -51,7 +51,7 @@ func TestExtractPicsDirectly(t *testing.T) {
5151
sel := d.Find("img")
5252
im, allImages, ok := lr.extractPics(sel, "url")
5353
assert.True(t, ok)
54-
assert.Equal(t, 1, len(allImages))
54+
assert.Len(t, allImages, 1)
5555
assert.Equal(t, "https://cdn1.tnwcdn.com/wp-content/blogs.dir/1/files/2016/01/page-source.jpg", im)
5656
})
5757

@@ -73,7 +73,7 @@ func TestExtractPicsDirectly(t *testing.T) {
7373
sel := d.Find("img")
7474
im, allImages, ok := lr.extractPics(sel, "url")
7575
assert.True(t, ok)
76-
assert.Equal(t, 1, len(allImages))
76+
assert.Len(t, allImages, 1)
7777
assert.Equal(t, "http://bad_url", im)
7878
})
7979

@@ -82,13 +82,13 @@ func TestExtractPicsDirectly(t *testing.T) {
8282
w.Header().Set("Content-Length", "1") // error on reading body
8383
}))
8484
defer ts.Close()
85-
data := fmt.Sprintf(`<body><img src="%s"></body>`, ts.URL)
85+
data := fmt.Sprintf(`<body><img src=%q></body>`, ts.URL)
8686
d, err := goquery.NewDocumentFromReader(strings.NewReader(data))
8787
require.NoError(t, err)
8888
sel := d.Find("img")
8989
im, allImages, ok := lr.extractPics(sel, "url")
9090
assert.True(t, ok)
91-
assert.Equal(t, 1, len(allImages))
91+
assert.Len(t, allImages, 1)
9292
assert.Equal(t, ts.URL, im)
9393
})
9494
}

backend/extractor/readability.go

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -74,7 +74,7 @@ func (f *UReadability) extractWithRules(ctx context.Context, reqURL string, rule
7474
rb := &Response{}
7575

7676
httpClient := &http.Client{Timeout: f.TimeOut}
77-
req, err := http.NewRequestWithContext(ctx, "GET", reqURL, nil)
77+
req, err := http.NewRequestWithContext(ctx, "GET", reqURL, http.NoBody)
7878
if err != nil {
7979
log.Printf("[WARN] failed to create request for %s, error=%v", reqURL, err)
8080
return nil, err
@@ -180,7 +180,7 @@ func (f *UReadability) getContent(ctx context.Context, body, reqURL string, rule
180180
r := f.Rules
181181
if rule, found := r.Get(ctx, reqURL); found {
182182
if content, rich, err = customParser(body, reqURL, rule); err == nil {
183-
return content, rich, err
183+
return content, rich, nil
184184
}
185185
log.Printf("[WARN] custom extractor failed for %s, error=%v", reqURL, err) // back to general parser
186186
}
@@ -208,8 +208,8 @@ func (f *UReadability) normalizeLinks(data string, reqContext *http.Request) (re
208208
dstLink := srcLink
209209
if absLink, changed := absoluteLink(srcLink); changed {
210210
dstLink = absLink
211-
srcLink = fmt.Sprintf(`"%s"`, srcLink)
212-
absLink = fmt.Sprintf(`"%s"`, absLink)
211+
srcLink = fmt.Sprintf("%q", srcLink)
212+
absLink = fmt.Sprintf("%q", absLink)
213213
result = strings.ReplaceAll(result, srcLink, absLink)
214214
log.Printf("[DEBUG] normalized %s -> %s", srcLink, dstLink)
215215
normalizedCount++

backend/extractor/readability_test.go

Lines changed: 15 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ import (
1212
"time"
1313

1414
"github.com/stretchr/testify/assert"
15+
"github.com/stretchr/testify/require"
1516
"go.mongodb.org/mongo-driver/bson/primitive"
1617

1718
"github.com/ukeeper/ukeeper-redabilty/backend/datastore"
@@ -83,15 +84,15 @@ func TestExtractURL(t *testing.T) {
8384
rb, err := lr.Extract(context.Background(), tt.url)
8485

8586
if tt.wantErr {
86-
assert.Error(t, err)
87+
require.Error(t, err)
8788
assert.Nil(t, rb)
8889
return
8990
}
9091

91-
assert.NoError(t, err)
92+
require.NoError(t, err)
9293
assert.Equal(t, tt.wantURL, rb.URL)
9394
assert.Equal(t, tt.wantTitle, rb.Title)
94-
assert.Equal(t, tt.wantContentLen, len(rb.Content))
95+
assert.Len(t, rb.Content, tt.wantContentLen)
9596
})
9697
}
9798
}
@@ -125,20 +126,20 @@ func TestExtractGeneral(t *testing.T) {
125126

126127
lr := UReadability{TimeOut: 30 * time.Second, SnippetSize: 200}
127128
a, err := lr.Extract(context.Background(), ts.URL+"/2015/11/26/vsiem-mirom-dlia-obshchiei-polzy/")
128-
assert.NoError(t, err)
129+
require.NoError(t, err)
129130
assert.Equal(t, "Всем миром для общей пользы • Umputun тут был", a.Title)
130131
assert.Equal(t, ts.URL+"/2015/11/26/vsiem-mirom-dlia-obshchiei-polzy/", a.URL)
131132
assert.Equal(t, "Не первый раз я практикую идею “а давайте, ребята, сделаем для общего блага …”, и вот опять. В нашем подкасте радио-т есть незаменимый инструмент, позволяющий собирать новости, готовить их к выпуску, ...", a.Excerpt)
132133
assert.Contains(t, ts.URL, a.Domain)
133134

134135
a, err = lr.Extract(context.Background(), ts.URL+"/v48b6Q")
135-
assert.NoError(t, err)
136+
require.NoError(t, err)
136137
assert.Equal(t, "UWP - Выпуск 369", a.Title)
137138
assert.Equal(t, ts.URL+"/p/2015/11/22/podcast-369/", a.URL)
138139
assert.Equal(t, "2015-11-22 Нагло ходил в гости. Табличка на двери сработала на 50%Никогда нас школа не хвалила. Девочка осваивает новый прибор. Мое неприятие их логики. И разошлись по будкам …Отбиваюсь от опасных ...", a.Excerpt)
139140
assert.Equal(t, "https://podcast.umputun.com/images/uwp/uwp369.jpg", a.Image)
140141
assert.Contains(t, ts.URL, a.Domain)
141-
assert.Equal(t, 13, len(a.AllLinks))
142+
assert.Len(t, a.AllLinks, 13)
142143
assert.Contains(t, a.AllLinks, "https://podcast.umputun.com/media/ump_podcast369.mp3")
143144
assert.Contains(t, a.AllLinks, "https://podcast.umputun.com/images/uwp/uwp369.jpg")
144145
log.Printf("links=%v", a.AllLinks)
@@ -150,20 +151,19 @@ func TestNormalizeLinks(t *testing.T) {
150151
u, _ := url.Parse("http://ukeeper.com/blah")
151152
out, links := lr.normalizeLinks(inp, &http.Request{URL: u})
152153
assert.Equal(t, `blah <img src="http://ukeeper.com/aaa.png"/> sdfasd <a href="http://ukeeper.com/blah2/aa.link">something</a> blah33 <img src="http://aaa.com/xyz.jpg">xx</img>`, out)
153-
assert.Equal(t, 3, len(links))
154+
assert.Len(t, links, 3)
154155

155156
inp = `<body>
156157
<img class="alignright size-full wp-image-944214 lazyloadableImage lazyLoad-fadeIn" alt="View Page Source" width="308" height="508" data-original="http://cdn1.tnwcdn.com/wp-content/blogs.dir/1/files/2016/01/page-source.jpg" src="http://cdn1.tnwcdn.com/wp-content/blogs.dir/1/files/2016/01/page-source.jpg"></body>`
157158
_, links = lr.normalizeLinks(inp, &http.Request{URL: u})
158-
assert.Equal(t, 1, len(links))
159+
assert.Len(t, links, 1)
159160
assert.Equal(t, "http://cdn1.tnwcdn.com/wp-content/blogs.dir/1/files/2016/01/page-source.jpg", links[0])
160-
161161
}
162162

163163
func TestNormalizeLinksIssue(t *testing.T) {
164164
lr := UReadability{TimeOut: 30 * time.Second, SnippetSize: 200}
165165
_, err := lr.Extract(context.Background(), "https://git-scm.com/book/en/v2/Git-Tools-Submodules")
166-
assert.NoError(t, err)
166+
require.NoError(t, err)
167167
}
168168

169169
type RulesMock struct{}
@@ -196,14 +196,14 @@ func TestGetContentCustom(t *testing.T) {
196196
}))
197197
defer ts.Close()
198198
resp, err := httpClient.Get(ts.URL + "/2015/09/25/poiezdka-s-apple-maps/")
199-
assert.NoError(t, err)
199+
require.NoError(t, err)
200200
defer resp.Body.Close()
201201
dataBytes, err := io.ReadAll(resp.Body)
202-
assert.NoError(t, err)
202+
require.NoError(t, err)
203203
body := string(dataBytes)
204204

205205
content, rich, err := lr.getContent(context.Background(), body, ts.URL+"/2015/09/25/poiezdka-s-apple-maps/", nil)
206-
assert.NoError(t, err)
207-
assert.Equal(t, 6988, len(content))
208-
assert.Equal(t, 7169, len(rich))
206+
require.NoError(t, err)
207+
assert.Len(t, content, 6988)
208+
assert.Len(t, rich, 7169)
209209
}

0 commit comments

Comments
 (0)