Skip to content

Commit 94885b4

Browse files
committed
Fix lint issues, remove unused code, and update to newer APIs
Add golangci-lint v2 config. Replace dot imports of generics with named imports. Use keyed struct literals throughout. Replace deprecated reflect.SliceHeader with unsafe.Slice, ioutil with os, and Magnet with MagnetV2. Replace MakeMapIfNilAndSet with MakeMapIfNil+MapInsert. Fix missing error checks in tracker HTTP client and webtorrent transport. Fix sync.Pool type assertion for pointer types. Remove unused functions, types, and struct fields across the codebase.
1 parent bd1371e commit 94885b4

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

54 files changed

+163
-305
lines changed

.golangci.yml

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
version: "2"
2+
3+
linters:
4+
disable:
5+
- errcheck
6+
settings:
7+
govet:
8+
disable:
9+
- composites
10+
staticcheck:
11+
checks:
12+
- "all"
13+
- "-ST1000"
14+
- "-ST1003"
15+
- "-ST1016"
16+
- "-ST1020"
17+
- "-ST1021"
18+
- "-ST1022"
19+
- "-ST1023"
20+
- "-QF1008"

analysis/peer-upload-order.go

Lines changed: 2 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -53,19 +53,10 @@ func (me *PeerUploadOrder) Install(cbs *torrent.Callbacks) {
5353
cbs.DeletedRequest = append(cbs.DeletedRequest, me.deletedRequest)
5454
}
5555

56-
func (me *PeerUploadOrder) report(desc string, req torrent.Request, peer *torrent.Peer) {
57-
peerConn, ok := peer.TryAsPeerConn()
58-
var peerId *torrent.PeerID
59-
if ok {
60-
peerId = &peerConn.PeerID
61-
}
62-
log.Printf("%s: %v, %v", desc, req, peerId)
63-
}
64-
6556
func (me *PeerUploadOrder) onReceivedRequested(event torrent.PeerMessageEvent) {
6657
req := torrent.Request{
67-
event.Message.Index,
68-
torrent.ChunkSpec{
58+
Index: event.Message.Index,
59+
ChunkSpec: torrent.ChunkSpec{
6960
Begin: event.Message.Begin,
7061
Length: pp.Integer(len(event.Message.Piece)),
7162
},

bencode/decode.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -458,7 +458,7 @@ func (d *Decoder) parseDict(v reflect.Value) error {
458458
ok, err = d.parseValue(setValue)
459459
if err != nil {
460460
var target *UnmarshalTypeError
461-
if !(errors.As(err, &target) && df.Tags.IgnoreUnmarshalTypeError()) {
461+
if !errors.As(err, &target) || !df.Tags.IgnoreUnmarshalTypeError() {
462462
return fmt.Errorf("parsing value for key %q: %w", keyValue, err)
463463
}
464464
}

client-stats.go

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,8 @@ import (
77
)
88

99
func setAdd[K comparable](m *map[K]struct{}, elem K) {
10-
g.MakeMapIfNilAndSet(m, elem, struct{}{})
10+
g.MakeMapIfNil(m)
11+
g.MapInsert(*m, elem, struct{}{})
1112
}
1213

1314
type clientHolepunchAddrSets struct {

client.go

Lines changed: 5 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,6 @@ import (
2626
"github.com/anacrolix/chansync/events"
2727
"github.com/anacrolix/dht/v2"
2828
"github.com/anacrolix/dht/v2/krpc"
29-
. "github.com/anacrolix/generics"
3029
g "github.com/anacrolix/generics"
3130
"github.com/anacrolix/generics/heap"
3231
"github.com/anacrolix/log"
@@ -46,7 +45,6 @@ import (
4645

4746
"github.com/anacrolix/torrent/bencode"
4847
"github.com/anacrolix/torrent/internal/check"
49-
"github.com/anacrolix/torrent/internal/limiter"
5048
"github.com/anacrolix/torrent/iplist"
5149
"github.com/anacrolix/torrent/metainfo"
5250
"github.com/anacrolix/torrent/mse"
@@ -110,7 +108,6 @@ type Client struct {
110108

111109
numWebSeedRequests map[webseedHostKeyHandle]int
112110

113-
activeAnnounceLimiter limiter.Instance
114111
// TODO: Move this onto ClientConfig.
115112
httpClient *http.Client
116113

@@ -564,11 +561,6 @@ func (cl *Client) ipBlockRange(ip net.IP) (r iplist.Range, blocked bool) {
564561
return cl.ipBlockList.Lookup(ip)
565562
}
566563

567-
func (cl *Client) ipIsBlocked(ip net.IP) bool {
568-
_, blocked := cl.ipBlockRange(ip)
569-
return blocked
570-
}
571-
572564
func (cl *Client) wantConns() bool {
573565
if cl.config.AlwaysWantConns {
574566
return true
@@ -868,7 +860,8 @@ func (cl *Client) dialAndCompleteHandshake(opts outgoingConnOpts) (c *PeerConn,
868860
if holepunchAddrErr == nil {
869861
cl.lock()
870862
if !opts.receivedHolepunchConnect {
871-
g.MakeMapIfNilAndSet(&cl.undialableWithoutHolepunch, holepunchAddr, struct{}{})
863+
g.MakeMapIfNil(&cl.undialableWithoutHolepunch)
864+
g.MapInsert(cl.undialableWithoutHolepunch, holepunchAddr, struct{}{})
872865
}
873866
if !opts.skipHolepunchRendezvous {
874867
opts.t.trySendHolepunchRendezvous(holepunchAddr)
@@ -881,7 +874,8 @@ func (cl *Client) dialAndCompleteHandshake(opts outgoingConnOpts) (c *PeerConn,
881874
if opts.receivedHolepunchConnect && holepunchAddrErr == nil {
882875
cl.lock()
883876
if g.MapContains(cl.undialableWithoutHolepunch, holepunchAddr) {
884-
g.MakeMapIfNilAndSet(&cl.dialableOnlyAfterHolepunch, holepunchAddr, struct{}{})
877+
g.MakeMapIfNil(&cl.dialableOnlyAfterHolepunch)
878+
g.MapInsert(cl.dialableOnlyAfterHolepunch, holepunchAddr, struct{}{})
885879
}
886880
g.MakeMapIfNil(&cl.dialedSuccessfullyAfterHolepunchConnect)
887881
g.MapInsert(cl.dialedSuccessfullyAfterHolepunchConnect, holepunchAddr, struct{}{})
@@ -1763,7 +1757,7 @@ func (cl *Client) newConnection(nc net.Conn, opts newConnectionOpts) (c *PeerCon
17631757
if opts.remoteAddr != nil {
17641758
netipAddrPort, err := netip.ParseAddrPort(opts.remoteAddr.String())
17651759
if err == nil {
1766-
c.bannableAddr = Some(netipAddrPort.Addr())
1760+
c.bannableAddr = g.Some(netipAddrPort.Addr())
17671761
}
17681762
}
17691763
c.legacyPeerImpl = c

client_test.go

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -708,7 +708,9 @@ func makeMagnet(t *testing.T, cl *Client, dir, name string) string {
708708
require.NoError(t, err)
709709
mi.InfoBytes, err = bencode.Marshal(info)
710710
require.NoError(t, err)
711-
magnet := mi.Magnet(nil, &info).String()
711+
m, err := mi.MagnetV2()
712+
require.NoError(t, err)
713+
magnet := m.String()
712714
tr, err := cl.AddTorrent(&mi)
713715
require.NoError(t, err)
714716
require.True(t, tr.Seeding())
@@ -923,7 +925,7 @@ func TestDroppedTorrentsNotReturned(t *testing.T) {
923925
qt.Check(t, qt.Equals(tt1, tt))
924926
qt.Check(t, qt.SliceContains(cl.Torrents(), tt))
925927
tt.Drop()
926-
tt1, ok = cl.Torrent(tt.InfoHash())
928+
_, ok = cl.Torrent(tt.InfoHash())
927929
qt.Check(t, qt.IsFalse(ok))
928930
qt.Check(t, qt.HasLen(cl.Torrents(), 0))
929931
}

cmd/torrent/announce.go

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,13 +8,14 @@ import (
88
"github.com/anacrolix/torrent"
99
"github.com/anacrolix/torrent/tracker"
1010
"github.com/anacrolix/torrent/tracker/udp"
11+
"github.com/anacrolix/torrent/types/infohash"
1112
)
1213

1314
type AnnounceCmd struct {
1415
Event udp.AnnounceEvent
1516
Port *uint16
16-
Tracker string `arg:"positional"`
17-
InfoHash torrent.InfoHash `arg:"positional"`
17+
Tracker string `arg:"positional"`
18+
InfoHash infohash.T `arg:"positional"`
1819
}
1920

2021
func announceErr(flags AnnounceCmd) error {

cmd/torrent/download.go

Lines changed: 2 additions & 51 deletions
Original file line numberDiff line numberDiff line change
@@ -82,55 +82,6 @@ func clientStatusWriter(ctx context.Context, cl *torrent.Client) {
8282
}
8383
}
8484

85-
// Keeping this for now for reference in case I do per-torrent deltas in client status updates.
86-
func torrentBar(t *torrent.Torrent, pieceStates bool) {
87-
go func() {
88-
start := time.Now()
89-
if t.Info() == nil {
90-
fmt.Printf("%v: getting torrent info for %q\n", time.Since(start), t.Name())
91-
<-t.GotInfo()
92-
}
93-
lastStats := t.Stats()
94-
var lastLine string
95-
interval := 3 * time.Second
96-
for range time.Tick(interval) {
97-
var completedPieces, partialPieces int
98-
psrs := t.PieceStateRuns()
99-
for _, r := range psrs {
100-
if r.Complete {
101-
completedPieces += r.Length
102-
}
103-
if r.Partial {
104-
partialPieces += r.Length
105-
}
106-
}
107-
stats := t.Stats()
108-
byteRate := int64(time.Second)
109-
byteRate *= stats.BytesReadUsefulData.Int64() - lastStats.BytesReadUsefulData.Int64()
110-
byteRate /= int64(interval)
111-
line := fmt.Sprintf(
112-
"%v: downloading %q: %s/%s, %d/%d pieces completed (%d partial): %v/s\n",
113-
time.Since(start),
114-
t.Name(),
115-
humanize.Bytes(uint64(t.BytesCompleted())),
116-
humanize.Bytes(uint64(t.Length())),
117-
completedPieces,
118-
t.NumPieces(),
119-
partialPieces,
120-
humanize.Bytes(uint64(byteRate)),
121-
)
122-
if line != lastLine {
123-
lastLine = line
124-
os.Stdout.WriteString(line)
125-
}
126-
if pieceStates {
127-
fmt.Println(psrs)
128-
}
129-
lastStats = stats
130-
}
131-
}()
132-
}
133-
13485
type stringAddr string
13586

13687
func (stringAddr) Network() string { return "" }
@@ -173,7 +124,7 @@ func addTorrents(
173124
metaInfo, err := metainfo.Load(response.Body)
174125
defer response.Body.Close()
175126
if err != nil {
176-
return nil, fmt.Errorf("error loading torrent file %q: %s\n", arg, err)
127+
return nil, fmt.Errorf("error loading torrent file %q: %s", arg, err)
177128
}
178129
t, err := client.AddTorrent(metaInfo)
179130
if err != nil {
@@ -186,7 +137,7 @@ func addTorrents(
186137
} else {
187138
metaInfo, err := metainfo.LoadFromFile(arg)
188139
if err != nil {
189-
return nil, fmt.Errorf("error loading torrent file %q: %s\n", arg, err)
140+
return nil, fmt.Errorf("error loading torrent file %q: %s", arg, err)
190141
}
191142
t, err := client.AddTorrent(metaInfo)
192143
if err != nil {

cmd/torrent/main.go

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ import (
1515
"github.com/anacrolix/envpprof"
1616
app "github.com/anacrolix/gostdapp"
1717
"github.com/anacrolix/log"
18-
xprometheus "github.com/anacrolix/missinggo/v2/prometheus"
18+
expvar_prometheus "github.com/anacrolix/missinggo/v2/expvar-prometheus"
1919

2020
"github.com/davecgh/go-spew/spew"
2121
"github.com/prometheus/client_golang/prometheus"
@@ -27,10 +27,10 @@ import (
2727

2828
func init() {
2929
stdLog.SetFlags(stdLog.Flags() | stdLog.Lshortfile)
30-
prometheus.MustRegister(xprometheus.NewExpvarCollector())
30+
prometheus.MustRegister(expvar_prometheus.NewCollector())
3131
http.Handle("/metrics", promhttp.Handler())
3232
log.Default = log.NewLogger().WithDefaultLevel(log.Info)
33-
log.Default.SetHandlers(log.SlogHandlerAsHandler{slog.Default().Handler()})
33+
log.Default.SetHandlers(log.SlogHandlerAsHandler{SlogHandler: slog.Default().Handler()})
3434
}
3535

3636
func main() {

cmd/torrent/scrape.go

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6,13 +6,13 @@ import (
66

77
"github.com/davecgh/go-spew/spew"
88

9-
"github.com/anacrolix/torrent"
109
"github.com/anacrolix/torrent/tracker"
10+
"github.com/anacrolix/torrent/types/infohash"
1111
)
1212

1313
type scrapeCfg struct {
14-
Tracker string `arg:"positional"`
15-
InfoHashes []torrent.InfoHash `arity:"+" arg:"positional"`
14+
Tracker string `arg:"positional"`
15+
InfoHashes []infohash.T `arity:"+" arg:"positional"`
1616
}
1717

1818
func scrape(flags scrapeCfg) error {

0 commit comments

Comments
 (0)