chore: fix a bunch of issues caught by golangci-lint
Most of these are probably harmless but a few looked like they might actually be bugs. Most of them are just faulty tests. License: MIT Signed-off-by: Steven Allen <steven@stebalien.com>
Steven Allen committed
Mar 27, 2019 at 14:46 UTC
1f293eff1b3da26a0c1e4c7d1c45adb88f536dd8
49 files changed
+242
-193
cmd/ipfs/daemon.go
+2
-2
@@ -530,7 +530,7 @@ func printSwarmAddrs(node *core.IpfsNode) {
530
for _, addr := range ifaceAddrs {
531
lisAddrs = append(lisAddrs, addr.String())
532
}
533
- sort.Sort(sort.StringSlice(lisAddrs))
533
+ sort.Strings(lisAddrs)
534
for _, addr := range lisAddrs {
535
fmt.Printf("Swarm listening on %s\n", addr)
536
}
@@ -539,7 +539,7 @@ func printSwarmAddrs(node *core.IpfsNode) {
539
for _, addr := range node.PeerHost.Addrs() {
540
addrs = append(addrs, addr.String())
541
}
542
- sort.Sort(sort.StringSlice(addrs))
542
+ sort.Strings(addrs)
543
for _, addr := range addrs {
544
fmt.Printf("Swarm announcing %s\n", addr)
545
}
cmd/ipfs/main.go
+5
-3
@@ -37,8 +37,6 @@ import (
37
// log is the command logger
38
var log = logging.Logger("cmd/ipfs")
39
40
-var errRequestCanceled = errors.New("request canceled")
41
-
40
// declared as a var for testing purposes
41
var dnsResolver = madns.DefaultResolver
42
@@ -325,7 +323,11 @@ func startProfiling() (func(), error) {
323
if err != nil {
324
return nil, err
325
}
328
- pprof.StartCPUProfile(ofi)
326
+ err = pprof.StartCPUProfile(ofi)
327
+ if err != nil {
328
+ ofi.Close()
329
+ return nil, err
330
+ }
331
go func() {
332
for range time.NewTicker(time.Second * 30).C {
333
err := writeHeapProfileToFile()
cmd/ipfswatch/main.go
+8
-2
@@ -103,7 +103,7 @@ func run(ipfsPath, watchPath string) error {
103
})
104
}
105
106
- interrupts := make(chan os.Signal)
106
+ interrupts := make(chan os.Signal, 1)
107
signal.Notify(interrupts, os.Interrupt, syscall.SIGTERM)
108
109
for {
@@ -129,7 +129,9 @@ func run(ipfsPath, watchPath string) error {
129
switch e.Op {
130
case fsnotify.Create:
131
if isDir {
132
- addTree(watcher, e.Name)
132
+ if err := addTree(watcher, e.Name); err != nil {
133
+ return err
134
+ }
135
}
136
}
137
proc.Go(func(p process.Process) {
@@ -167,6 +169,10 @@ func run(ipfsPath, watchPath string) error {
169
170
func addTree(w *fsnotify.Watcher, root string) error {
171
err := filepath.Walk(root, func(path string, info os.FileInfo, err error) error {
172
+ if err != nil {
173
+ log.Println(err)
174
+ return nil
175
+ }
176
isDir, err := IsDirectory(path)
177
if err != nil {
178
log.Println(err)
cmd/seccat/seccat.go
+8
-2
@@ -129,8 +129,14 @@ func setupPeer(a args) (peer.ID, pstore.Peerstore, error) {
129
}
130
131
ps := pstoremem.NewPeerstore()
132
- ps.AddPrivKey(p, sk)
133
- ps.AddPubKey(p, pk)
132
+ err = ps.AddPrivKey(p, sk)
133
+ if err != nil {
134
+ return "", nil, err
135
+ }
136
+ err = ps.AddPubKey(p, pk)
137
+ if err != nil {
138
+ return "", nil, err
139
+ }
140
141
out("local peer id: %s", p)
142
return p, ps, nil
commands/reqlog.go
-2
@@ -44,8 +44,6 @@ func (rl *ReqLog) AddEntry(rle *ReqLogEntry) {
44
if rle == nil || !rle.Active {
45
rl.maybeCleanup()
46
}
47
-
48
- return
47
}
48
49
// ClearInactive removes stale entries
core/builder.go
+2
-2
@@ -78,10 +78,10 @@ func (cfg *BuildCfg) fillDefaults() error {
78
79
if cfg.Repo == nil {
80
var d ds.Datastore
81
- d = ds.NewMapDatastore()
82
-
81
if cfg.NilRepo {
82
d = ds.NewNullDatastore()
83
+ } else {
84
+ d = ds.NewMapDatastore()
85
}
86
r, err := defaultRepo(dsync.MutexWrap(d))
87
if err != nil {
core/commands/add.go
+5
-3
@@ -230,7 +230,7 @@ You can now check what blocks have been created by:
230
opts = append(opts, options.Unixfs.Layout(options.TrickleLayout))
231
}
232
233
- errCh := make(chan error)
233
+ errCh := make(chan error, 1)
234
go func() {
235
var err error
236
defer func() { errCh <- err }()
@@ -255,12 +255,14 @@ You can now check what blocks have been created by:
255
output.Name = path.Join(name, output.Name)
256
}
257
258
- res.Emit(&AddEvent{
258
+ if err := res.Emit(&AddEvent{
259
Name: output.Name,
260
Hash: h,
261
Bytes: output.Bytes,
262
Size: output.Size,
263
- })
263
+ }); err != nil {
264
+ return err
265
+ }
266
}
267
268
return <-errCh
core/commands/cid.go
+3
-6
@@ -239,8 +239,7 @@ var basesCmd = &cmds.Command{
239
for code, name := range mbase.EncodingToStr {
240
res = append(res, CodeAndName{int(code), name})
241
}
242
- cmds.EmitOnce(resp, res)
243
- return nil
242
+ return cmds.EmitOnce(resp, res)
243
},
244
Encoders: cmds.EncoderMap{
245
cmds.Text: cmds.MakeTypedEncoder(func(req *cmds.Request, w io.Writer, val []CodeAndName) error {
@@ -287,8 +286,7 @@ var codecsCmd = &cmds.Command{
286
for code, name := range cid.CodecToStr {
287
res = append(res, CodeAndName{int(code), name})
288
}
290
- cmds.EmitOnce(resp, res)
291
- return nil
289
+ return cmds.EmitOnce(resp, res)
290
},
291
Encoders: cmds.EncoderMap{
292
cmds.Text: cmds.MakeTypedEncoder(func(req *cmds.Request, w io.Writer, val []CodeAndName) error {
@@ -321,8 +319,7 @@ var hashesCmd = &cmds.Command{
319
}
320
res = append(res, CodeAndName{int(code), name})
321
}
324
- cmds.EmitOnce(resp, res)
325
- return nil
322
+ return cmds.EmitOnce(resp, res)
323
},
324
Encoders: codecsCmd.Encoders,
325
Type: codecsCmd.Type,
core/commands/commands.go
+1
-21
@@ -12,8 +12,6 @@ import (
12
"sort"
13
"strings"
14
15
- e "github.com/ipfs/go-ipfs/core/commands/e"
16
-
15
"github.com/ipfs/go-ipfs-cmdkit"
16
cmds "github.com/ipfs/go-ipfs-cmds"
17
)
@@ -129,28 +127,10 @@ func cmdPathStrings(cmd *Command, showOptions bool) []string {
127
}
128
129
recurse("", cmd)
132
- sort.Sort(sort.StringSlice(cmds))
130
+ sort.Strings(cmds)
131
return cmds
132
}
133
136
-// changes here will also need to be applied at
137
-// - ./dag/dag.go
138
-// - ./object/object.go
139
-// - ./files/files.go
140
-// - ./unixfs/unixfs.go
141
-func unwrapOutput(i interface{}) (interface{}, error) {
142
- var (
143
- ch <-chan interface{}
144
- ok bool
145
- )
146
-
147
- if ch, ok = i.(<-chan interface{}); !ok {
148
- return nil, e.TypeErr(ch, i)
149
- }
150
-
151
- return <-ch, nil
152
-}
153
-
134
type nonFatalError string
135
136
// streamResult is a helper function to stream results that possibly
core/commands/config.go
+6
-8
@@ -134,8 +134,8 @@ Set the value of the 'Datastore.Path' key:
134
}
135
buf = append(buf, byte('\n'))
136
137
- w.Write(buf)
138
- return nil
137
+ _, err = w.Write(buf)
138
+ return err
139
}),
140
},
141
Type: ConfigField{},
@@ -185,9 +185,8 @@ NOTE: For security reasons, this command will omit your private key. If you woul
185
return err
186
}
187
buf = append(buf, byte('\n'))
188
- w.Write(buf)
189
-
190
- return nil
188
+ _, err = w.Write(buf)
189
+ return err
190
}),
191
},
192
}
@@ -352,9 +351,8 @@ var configProfileApplyCmd = &cmds.Command{
351
diff := jsondiff.Compare(out.OldCfg, out.NewCfg)
352
buf := jsondiff.Format(diff)
353
355
- w.Write(buf)
356
-
357
- return nil
354
+ _, err := w.Write(buf)
355
+ return err
356
}),
357
},
358
Type: ConfigUpdateOutput{},
core/commands/files.go
+3
@@ -168,6 +168,9 @@ var filesStatCmd = &cmds.Command{
168
}
169
170
local, sizeLocal, err := walkBlock(req.Context, dagserv, nd)
171
+ if err != nil {
172
+ return err
173
+ }
174
175
o.WithLocality = true
176
o.Local = local
core/commands/get.go
+1
-1
@@ -274,7 +274,7 @@ func fileArchive(f files.Node, name string, archive bool, compression int) (io.R
274
piper, pipew := io.Pipe()
275
checkErrAndClosePipe := func(err error) bool {
276
if err != nil {
277
- pipew.CloseWithError(err)
277
+ _ = pipew.CloseWithError(err)
278
return true
279
}
280
return false
core/commands/p2p.go
+4
-1
@@ -149,8 +149,11 @@ func parseIpfsAddr(addr string) ([]ipfsaddr.IPFSAddr, error) {
149
}
150
// resolve mutiladdr whose protocol is not ma.P_IPFS
151
ctx, cancel := context.WithTimeout(context.Background(), resolveTimeout)
152
+ defer cancel()
153
addrs, err := madns.Resolve(ctx, mutiladdr)
153
- cancel()
154
+ if err != nil {
155
+ return nil, err
156
+ }
157
if len(addrs) == 0 {
158
return nil, errors.New("fail to resolve the multiaddr:" + mutiladdr.String())
159
}
core/commands/repo.go
+7
-5
@@ -98,7 +98,10 @@ order to reclaim hard disk space.
98
}
99
} else {
100
err := corerepo.CollectResult(req.Context, gcOutChan, func(k cid.Cid) {
101
- re.Emit(&GcResult{Key: k})
101
+ // Nothing to do with this error, really. This
102
+ // most likely means that the client is gone but
103
+ // we still need to let the GC finish.
104
+ _ = re.Emit(&GcResult{Key: k})
105
})
106
if err != nil {
107
return err
@@ -163,10 +166,9 @@ Version string The repo version.
166
if err != nil {
167
return err
168
}
166
- cmds.EmitOnce(res, &corerepo.Stat{
169
+ return cmds.EmitOnce(res, &corerepo.Stat{
170
SizeStat: sizeStat,
171
})
169
- return nil
172
}
173
174
stat, err := corerepo.RepoStat(req.Context, n)
@@ -396,9 +398,9 @@ var repoVersionCmd = &cmds.Command{
398
quiet, _ := req.Options[repoQuietOptionName].(bool)
399
400
if quiet {
399
- fmt.Fprintf(w, fmt.Sprintf("fs-repo@%s\n", out.Version))
401
+ fmt.Fprintf(w, "fs-repo@%s\n", out.Version)
402
} else {
401
- fmt.Fprintf(w, fmt.Sprintf("ipfs repo version fs-repo@%s\n", out.Version))
403
+ fmt.Fprintf(w, "ipfs repo version fs-repo@%s\n", out.Version)
404
}
405
return nil
406
}),
core/commands/swarm.go
+3
-3
@@ -256,7 +256,7 @@ var swarmAddrsCmd = &cmds.Command{
256
for p := range am.Addrs {
257
ids = append(ids, p)
258
}
259
- sort.Sort(sort.StringSlice(ids))
259
+ sort.Strings(ids)
260
261
for _, p := range ids {
262
paddrs := am.Addrs[p]
@@ -307,7 +307,7 @@ var swarmAddrsLocalCmd = &cmds.Command{
307
}
308
addrs = append(addrs, saddr)
309
}
310
- sort.Sort(sort.StringSlice(addrs))
310
+ sort.Strings(addrs)
311
return cmds.EmitOnce(res, &stringList{addrs})
312
},
313
Type: stringList{},
@@ -338,7 +338,7 @@ var swarmAddrsListenCmd = &cmds.Command{
338
for _, addr := range maddrs {
339
addrs = append(addrs, addr.String())
340
}
341
- sort.Sort(sort.StringSlice(addrs))
341
+ sort.Strings(addrs)
342
343
return cmds.EmitOnce(res, &stringList{addrs})
344
},
core/core.go
+7
-3
@@ -399,7 +399,7 @@ func makeAddrsFactory(cfg config.Addresses) (p2pbhost.AddrsFactory, error) {
399
var out []ma.Multiaddr
400
for _, maddr := range addrs {
401
// check for exact matches
402
- ok, _ := noAnnAddrs[maddr.String()]
402
+ ok := noAnnAddrs[maddr.String()]
403
// check for /ipcidr matches
404
if !ok && !filters.AddrBlocked(maddr) {
405
out = append(out, maddr)
@@ -815,8 +815,12 @@ func (n *IpfsNode) loadPrivateKey() error {
815
}
816
817
n.PrivateKey = sk
818
- n.Peerstore.AddPrivKey(n.Identity, n.PrivateKey)
819
- n.Peerstore.AddPubKey(n.Identity, sk.GetPublic())
818
+ if err := n.Peerstore.AddPrivKey(n.Identity, n.PrivateKey); err != nil {
819
+ return err
820
+ }
821
+ if err := n.Peerstore.AddPubKey(n.Identity, sk.GetPublic()); err != nil {
822
+ return err
823
+ }
824
return nil
825
}
826
core/coreapi/pubsub.go
+4
-8
@@ -48,14 +48,7 @@ func (api *PubSubAPI) Peers(ctx context.Context, opts ...caopts.PubSubPeersOptio
48
return nil, err
49
}
50
51
- peers := api.pubSub.ListPeers(settings.Topic)
52
- out := make([]peer.ID, len(peers))
53
-
54
- for i, peer := range peers {
55
- out[i] = peer
56
- }
57
-
58
- return out, nil
51
+ return api.pubSub.ListPeers(settings.Topic), nil
52
}
53
54
func (api *PubSubAPI) Publish(ctx context.Context, topic string, data []byte) error {
@@ -69,6 +62,9 @@ func (api *PubSubAPI) Publish(ctx context.Context, topic string, data []byte) er
62
63
func (api *PubSubAPI) Subscribe(ctx context.Context, topic string, opts ...caopts.PubSubSubscribeOption) (coreiface.PubSubSubscription, error) {
64
options, err := caopts.PubSubSubscribeOptions(opts...)
65
+ if err != nil {
66
+ return nil, err
67
+ }
68
69
r, err := api.checkNode()
70
if err != nil {
core/coreapi/swarm.go
+3
-6
@@ -23,9 +23,8 @@ type connInfo struct {
23
conn net.Conn
24
dir net.Direction
25
26
- addr ma.Multiaddr
27
- peer peer.ID
28
- muxer string
26
+ addr ma.Multiaddr
27
+ peer peer.ID
28
}
29
30
func (api *SwarmAPI) Connect(ctx context.Context, pi pstore.PeerInfo) error {
@@ -83,9 +82,7 @@ func (api *SwarmAPI) KnownAddrs(context.Context) (map[peer.ID][]ma.Multiaddr, er
82
addrs := make(map[peer.ID][]ma.Multiaddr)
83
ps := api.peerHost.Network().Peerstore()
84
for _, p := range ps.Peers() {
86
- for _, a := range ps.Addrs(p) {
87
- addrs[p] = append(addrs[p], a)
88
- }
85
+ addrs[p] = append(addrs[p], ps.Addrs(p)...)
86
sort.Slice(addrs[p], func(i, j int) bool {
87
return addrs[p][i].String() < addrs[p][j].String()
88
})
core/corehttp/gateway_test.go
+1
-7
@@ -43,7 +43,7 @@ func (m mockNamesys) Resolve(ctx context.Context, name string, opts ...nsopts.Re
43
depth = ^uint(0)
44
}
45
for strings.HasPrefix(name, "/ipns/") {
46
- if depth <= 0 {
46
+ if depth == 0 {
47
return value, namesys.ErrResolveRecursion
48
}
49
depth--
@@ -235,9 +235,6 @@ func TestGatewayGet(t *testing.T) {
235
}
236
237
func TestIPNSHostnameRedirect(t *testing.T) {
238
- ctx, cancel := context.WithCancel(context.Background())
239
- defer cancel()
240
-
238
ns := mockNamesys{}
239
ts, api, ctx := newTestServerAndNode(t, ns)
240
t.Logf("test server url: %s", ts.URL)
@@ -326,9 +323,6 @@ func TestIPNSHostnameRedirect(t *testing.T) {
323
}
324
325
func TestIPNSHostnameBacklinks(t *testing.T) {
329
- ctx, cancel := context.WithCancel(context.Background())
330
- defer cancel()
331
-
326
ns := mockNamesys{}
327
ts, api, ctx := newTestServerAndNode(t, ns)
328
t.Logf("test server url: %s", ts.URL)
core/corehttp/mutex_profile.go
+2
-2
@@ -20,7 +20,7 @@ func MutexFractionOption(path string) ServeOption {
20
}
21
if err := r.ParseForm(); err != nil {
22
w.WriteHeader(http.StatusBadRequest)
23
- w.Write([]byte(err.Error()))
23
+ _, _ = w.Write([]byte(err.Error()))
24
return
25
}
26
@@ -33,7 +33,7 @@ func MutexFractionOption(path string) ServeOption {
33
fr, err := strconv.Atoi(asfr)
34
if err != nil {
35
w.WriteHeader(http.StatusBadRequest)
36
- w.Write([]byte(err.Error()))
36
+ _, _ = w.Write([]byte(err.Error()))
37
return
38
}
39
log.Infof("Setting MutexProfileFraction to %d", fr)
core/corehttp/option_test.go
+3
-1
@@ -52,7 +52,9 @@ func TestCheckVersionOption(t *testing.T) {
52
if !tc.shouldHandle {
53
t.Error("handler was called even though version didn't match")
54
} else {
55
- io.WriteString(w, "check!")
55
+ if _, err := io.WriteString(w, "check!"); err != nil {
56
+ t.Error(err)
57
+ }
58
}
59
})
60
core/corerepo/gc.go
+6
-2
@@ -40,11 +40,15 @@ func NewGC(n *core.IpfsNode) (*GC, error) {
40
// TODO: there should be a general check for all of the cfg fields
41
// maybe distinguish between user config file and default struct?
42
if cfg.Datastore.StorageMax == "" {
43
- r.SetConfigKey("Datastore.StorageMax", "10GB")
43
+ if err := r.SetConfigKey("Datastore.StorageMax", "10GB"); err != nil {
44
+ return nil, err
45
+ }
46
cfg.Datastore.StorageMax = "10GB"
47
}
48
if cfg.Datastore.StorageGCWatermark == 0 {
47
- r.SetConfigKey("Datastore.StorageGCWatermark", 90)
49
+ if err := r.SetConfigKey("Datastore.StorageGCWatermark", 90); err != nil {
50
+ return nil, err
51
+ }
52
cfg.Datastore.StorageGCWatermark = 90
53
}
54
core/coreunix/add_test.go
+6
-5
@@ -72,7 +72,7 @@ func TestAddGCLive(t *testing.T) {
72
_, err := adder.AddAllAndPin(slf)
73
74
if err != nil {
75
- t.Fatal(err)
75
+ t.Error(err)
76
}
77
78
}()
@@ -93,7 +93,9 @@ func TestAddGCLive(t *testing.T) {
93
}()
94
95
// gc shouldnt start until we let the add finish its current file.
96
- pipew.Write([]byte("some data for file b"))
96
+ if _, err := pipew.Write([]byte("some data for file b")); err != nil {
97
+ t.Fatal(err)
98
+ }
99
100
select {
101
case <-gcstarted:
@@ -178,7 +180,7 @@ func testAddWPosInfo(t *testing.T, rawLeaves bool) {
180
defer close(adder.Out)
181
_, err = adder.AddAllAndPin(file)
182
if err != nil {
181
- t.Fatal(err)
183
+ t.Error(err)
184
}
185
}()
186
for range out {
@@ -227,7 +229,7 @@ func (bs *testBlockstore) PutMany(blocks []blocks.Block) error {
229
return bs.GCBlockstore.PutMany(blocks)
230
}
231
230
-func (bs *testBlockstore) CheckForPosInfo(block blocks.Block) error {
232
+func (bs *testBlockstore) CheckForPosInfo(block blocks.Block) {
233
fsn, ok := block.(*pi.FilestoreNode)
234
if ok {
235
posInfo := fsn.PosInfo
@@ -240,7 +242,6 @@ func (bs *testBlockstore) CheckForPosInfo(block blocks.Block) error {
242
bs.countAtOffsetNonZero += 1
243
}
244
}
243
- return nil
245
}
246
247
type dummyFileInfo struct {
core/coreunix/metadata_test.go
+5
-1
@@ -3,6 +3,7 @@ package coreunix
3
import (
4
"bytes"
5
"context"
6
+ "io"
7
"io/ioutil"
8
"testing"
9
@@ -35,7 +36,10 @@ func TestMetadata(t *testing.T) {
36
// Make some random node
37
ds := getDagserv(t)
38
data := make([]byte, 1000)
38
- u.NewTimeSeededRand().Read(data)
39
+ _, err := io.ReadFull(u.NewTimeSeededRand(), data)
40
+ if err != nil {
41
+ t.Fatal(err)
42
+ }
43
r := bytes.NewReader(data)
44
nd, err := importer.BuildDagFromReader(ds, chunker.DefaultSplitter(r))
45
if err != nil {
dagutils/diff.go
+2
-2
@@ -139,8 +139,8 @@ func Diff(ctx context.Context, ds ipld.DAGService, a, b ipld.Node) ([]*Change, e
139
out = append(out, subc)
140
}
141
}
142
- cleanA.RemoveNodeLink(l.Name)
143
- cleanB.RemoveNodeLink(l.Name)
142
+ _ = cleanA.RemoveNodeLink(l.Name)
143
+ _ = cleanB.RemoveNodeLink(l.Name)
144
}
145
}
146
dagutils/utils.go
+1
-1
@@ -183,7 +183,7 @@ func (e *Editor) rmLink(ctx context.Context, root *dag.ProtoNode, path []string)
183
return nil, err
184
}
185
186
- e.tmp.Remove(ctx, root.Cid())
186
+ _ = e.tmp.Remove(ctx, root.Cid())
187
188
_ = root.RemoveNodeLink(path[0])
189
err = root.AddNodeLink(path[0], nnode)
exchange/reprovide/reprovide_test.go
+5
-2
@@ -30,11 +30,14 @@ func TestReprovide(t *testing.T) {
30
bstore := blockstore.NewBlockstore(dssync.MutexWrap(ds.NewMapDatastore()))
31
32
blk := blocks.NewBlock([]byte("this is a test"))
33
- bstore.Put(blk)
33
+ err := bstore.Put(blk)
34
+ if err != nil {
35
+ t.Fatal(err)
36
+ }
37
38
keyProvider := NewBlockstoreProvider(bstore)
39
reprov := NewReprovider(ctx, clA, keyProvider)
37
- err := reprov.Reprovide()
40
+ err = reprov.Reprovide()
41
if err != nil {
42
t.Fatal(err)
43
}
fuse/ipns/ipns_test.go
+37
-33
@@ -6,6 +6,7 @@ import (
6
"bytes"
7
"context"
8
"fmt"
9
+ "io"
10
"io/ioutil"
11
mrand "math/rand"
12
"os"
@@ -30,7 +31,10 @@ func maybeSkipFuseTests(t *testing.T) {
31
32
func randBytes(size int) []byte {
33
b := make([]byte, size)
33
- u.NewTimeSeededRand().Read(b)
34
+ _, err := io.ReadFull(u.NewTimeSeededRand(), b)
35
+ if err != nil {
36
+ panic(err)
37
+ }
38
return b
39
}
40
@@ -41,33 +45,20 @@ func mkdir(t *testing.T, path string) {
45
}
46
}
47
44
-func writeFile(t *testing.T, size int, path string) []byte {
45
- return writeFileData(t, randBytes(size), path)
46
-}
47
-
48
-func writeFileData(t *testing.T, data []byte, path string) []byte {
49
- fi, err := os.Create(path)
50
- if err != nil {
51
- t.Fatal(err)
52
- }
53
-
54
- n, err := fi.Write(data)
55
- if err != nil {
56
- t.Fatal(err)
57
- }
58
-
59
- if n != len(data) {
60
- t.Fatal("Didnt write proper amount!")
61
- }
62
-
63
- err = fi.Close()
48
+func writeFileOrFail(t *testing.T, size int, path string) []byte {
49
+ data, err := writeFile(size, path)
50
if err != nil {
51
t.Fatal(err)
52
}
67
-
53
return data
54
}
55
56
+func writeFile(size int, path string) ([]byte, error) {
57
+ data := randBytes(size)
58
+ err := ioutil.WriteFile(path, data, 0666)
59
+ return data, err
60
+}
61
+
62
func verifyFile(t *testing.T, path string, wantData []byte) {
63
isData, err := ioutil.ReadFile(path)
64
if err != nil {
@@ -168,7 +159,7 @@ func TestIpnsBasicIO(t *testing.T) {
159
defer closeMount(mnt)
160
161
fname := mnt.Dir + "/local/testfile"
171
- data := writeFile(t, 10, fname)
162
+ data := writeFileOrFail(t, 10, fname)
163
164
rbuf, err := ioutil.ReadFile(fname)
165
if err != nil {
@@ -198,7 +189,7 @@ func TestFilePersistence(t *testing.T) {
189
node, mnt := setupIpnsTest(t, nil)
190
191
fname := "/local/atestfile"
201
- data := writeFile(t, 127, mnt.Dir+fname)
192
+ data := writeFileOrFail(t, 127, mnt.Dir+fname)
193
194
mnt.Close()
195
@@ -226,7 +217,7 @@ func TestMultipleDirs(t *testing.T) {
217
checkExists(t, mnt.Dir+dir1)
218
219
t.Log("write a file in it")
229
- data1 := writeFile(t, 4000, mnt.Dir+dir1+"/file1")
220
+ data1 := writeFileOrFail(t, 4000, mnt.Dir+dir1+"/file1")
221
222
verifyFile(t, mnt.Dir+dir1+"/file1", data1)
223
@@ -236,7 +227,7 @@ func TestMultipleDirs(t *testing.T) {
227
checkExists(t, mnt.Dir+dir1+"/dir2")
228
229
t.Log("file in that subdirectory")
239
- data2 := writeFile(t, 5000, mnt.Dir+dir1+"/dir2/file2")
230
+ data2 := writeFileOrFail(t, 5000, mnt.Dir+dir1+"/dir2/file2")
231
232
verifyFile(t, mnt.Dir+dir1+"/dir2/file2", data2)
233
@@ -262,7 +253,7 @@ func TestFileSizeReporting(t *testing.T) {
253
defer mnt.Close()
254
255
fname := mnt.Dir + "/local/sizecheck"
265
- data := writeFile(t, 5555, fname)
256
+ data := writeFileOrFail(t, 5555, fname)
257
258
finfo, err := os.Stat(fname)
259
if err != nil {
@@ -302,7 +293,7 @@ func TestAppendFile(t *testing.T) {
293
defer mnt.Close()
294
295
fname := mnt.Dir + "/local/file"
305
- data := writeFile(t, 1300, fname)
296
+ data := writeFileOrFail(t, 1300, fname)
297
298
fi, err := os.OpenFile(fname, os.O_RDWR|os.O_APPEND, 0666)
299
if err != nil {
@@ -360,7 +351,11 @@ func TestConcurrentWrites(t *testing.T) {
351
go func(n int) {
352
defer wg.Done()
353
for j := 0; j < filesPerActor; j++ {
363
- out := writeFile(t, fileSize, mnt.Dir+fmt.Sprintf("/local/%dFILE%d", n, j))
354
+ out, err := writeFile(fileSize, mnt.Dir+fmt.Sprintf("/local/%dFILE%d", n, j))
355
+ if err != nil {
356
+ t.Error(err)
357
+ continue
358
+ }
359
data[n][j] = out
360
}
361
}(i)
@@ -369,6 +364,10 @@ func TestConcurrentWrites(t *testing.T) {
364
365
for i := 0; i < nactors; i++ {
366
for j := 0; j < filesPerActor; j++ {
367
+ if data[i][j] == nil {
368
+ // Error already reported.
369
+ continue
370
+ }
371
verifyFile(t, mnt.Dir+fmt.Sprintf("/local/%dFILE%d", i, j), data[i][j])
372
}
373
}
@@ -410,7 +409,8 @@ func TestFSThrash(t *testing.T) {
409
newDir := fmt.Sprintf("%s/dir%d-%d", dir, worker, j)
410
err := os.Mkdir(newDir, os.ModeDir)
411
if err != nil {
413
- t.Fatal(err)
412
+ t.Error(err)
413
+ continue
414
}
415
dirlock.Lock()
416
dirs = append(dirs, newDir)
@@ -432,7 +432,11 @@ func TestFSThrash(t *testing.T) {
432
433
newFileName := fmt.Sprintf("%s/file%d-%d", dir, worker, j)
434
435
- data := writeFile(t, 2000+mrand.Intn(5000), newFileName)
435
+ data, err := writeFile(2000+mrand.Intn(5000), newFileName)
436
+ if err != nil {
437
+ t.Error(err)
438
+ continue
439
+ }
440
filelock.Lock()
441
files[newFileName] = data
442
filelock.Unlock()
@@ -444,11 +448,11 @@ func TestFSThrash(t *testing.T) {
448
for name, data := range files {
449
out, err := ioutil.ReadFile(name)
450
if err != nil {
447
- t.Fatal(err)
451
+ t.Error(err)
452
}
453
454
if !bytes.Equal(data, out) {
451
- t.Fatal("Data didnt match")
455
+ t.Errorf("Data didnt match in %s: expected %v, got %v", name, data, out)
456
}
457
}
458
}
fuse/mount/fuse.go
+1
-1
@@ -56,7 +56,7 @@ func NewMount(p goprocess.Process, fsys fs.FS, mountpoint string, allow_other bo
56
57
// launch the mounting process.
58
if err := m.mount(); err != nil {
59
- m.Unmount() // just in case.
59
+ _ = m.Unmount() // just in case.
60
return nil, err
61
}
62
fuse/node/mount_unix.go
+6
-4
@@ -35,10 +35,12 @@ func Mount(node *core.IpfsNode, fsdir, nsdir string) error {
35
// if the user said "Mount", then there must be something wrong.
36
// so, close them and try again.
37
if node.Mounts.Ipfs != nil && node.Mounts.Ipfs.IsActive() {
38
- node.Mounts.Ipfs.Unmount()
38
+ // best effort
39
+ _ = node.Mounts.Ipfs.Unmount()
40
}
41
if node.Mounts.Ipns != nil && node.Mounts.Ipns.IsActive() {
41
- node.Mounts.Ipns.Unmount()
42
+ // best effort
43
+ _ = node.Mounts.Ipns.Unmount()
44
}
45
46
if err := platformFuseChecks(node); err != nil {
@@ -95,10 +97,10 @@ func doMount(node *core.IpfsNode, fsdir, nsdir string) error {
97
98
if err1 != nil || err2 != nil {
99
if fsmount != nil {
98
- fsmount.Unmount()
100
+ _ = fsmount.Unmount()
101
}
102
if nsmount != nil {
101
- nsmount.Unmount()
103
+ _ = nsmount.Unmount()
104
}
105
106
if err1 != nil {
fuse/readonly/ipfs_test.go
+5
-1
@@ -7,6 +7,7 @@ import (
7
"context"
8
"errors"
9
"fmt"
10
+ "io"
11
"io/ioutil"
12
"math/rand"
13
"os"
@@ -41,7 +42,10 @@ func maybeSkipFuseTests(t *testing.T) {
42
43
func randObj(t *testing.T, nd *core.IpfsNode, size int64) (ipld.Node, []byte) {
44
buf := make([]byte, size)
44
- u.NewTimeSeededRand().Read(buf)
45
+ _, err := io.ReadFull(u.NewTimeSeededRand(), buf)
46
+ if err != nil {
47
+ t.Fatal(err)
48
+ }
49
read := bytes.NewReader(buf)
50
obj, err := importer.BuildTrickleDagFromReader(nd.DAG, chunker.DefaultSplitter(read))
51
if err != nil {
keystore/keystore_test.go
+1
-1
@@ -198,7 +198,7 @@ func TestInvalidKeyFiles(t *testing.T) {
198
t.Fatal(err)
199
}
200
201
- if exist, err = ks.Has(".invalid"); err == nil {
201
+ if _, err = ks.Has(".invalid"); err == nil {
202
t.Fatal("shouldnt be able to put a key with a 'hidden' name")
203
}
204
}
namesys/namesys.go
+1
-1
@@ -183,7 +183,7 @@ func (ns *mpns) PublishWithEOL(ctx context.Context, name ci.PrivKey, value path.
183
return err
184
}
185
ttl := DefaultResolverCacheTTL
186
- if ttEol := eol.Sub(time.Now()); ttEol < ttl {
186
+ if ttEol := time.Until(eol); ttEol < ttl {
187
ttl = ttEol
188
}
189
ns.cacheSet(peer.IDB58Encode(id), value, ttl)
namesys/namesys_test.go
+4
-1
@@ -104,5 +104,8 @@ func TestPublishWithCache0(t *testing.T) {
104
if err != nil {
105
t.Fatal(err)
106
}
107
- nsys.Publish(context.Background(), priv, p)
107
+ err = nsys.Publish(context.Background(), priv, p)
108
+ if err != nil {
109
+ t.Fatal(err)
110
+ }
111
}
namesys/republisher/repub_test.go
+3
-1
@@ -41,7 +41,9 @@ func TestRepublish(t *testing.T) {
41
nodes = append(nodes, nd)
42
}
43
44
- mn.LinkAll()
44
+ if err := mn.LinkAll(); err != nil {
45
+ t.Fatal(err)
46
+ }
47
48
bsinf := core.BootstrapConfigWithPeers(
49
[]pstore.PeerInfo{
namesys/routing.go
+1
-1
@@ -137,7 +137,7 @@ func (r *IpnsResolver) resolveOnceAsync(ctx context.Context, name string, option
137
case ipns.ErrUnrecognizedValidity:
138
// No EOL.
139
case nil:
140
- ttEol := eol.Sub(time.Now())
140
+ ttEol := time.Until(eol)
141
if ttEol < 0 {
142
// It *was* valid when we first resolved it.
143
ttl = 0
p2p/remote.go
+3
-3
@@ -48,7 +48,7 @@ func (p2p *P2P) ForwardRemote(ctx context.Context, proto protocol.ID, addr ma.Mu
48
func (l *remoteListener) handleStream(remote net.Stream) {
49
local, err := manet.Dial(l.addr)
50
if err != nil {
51
- remote.Reset()
51
+ _ = remote.Reset()
52
return
53
}
54
@@ -56,14 +56,14 @@ func (l *remoteListener) handleStream(remote net.Stream) {
56
57
if l.reportRemote {
58
if _, err := fmt.Fprintf(local, "%s\n", peer.Pretty()); err != nil {
59
- remote.Reset()
59
+ _ = remote.Reset()
60
return
61
}
62
}
63
64
peerMa, err := ma.NewMultiaddr(maPrefix + peer.Pretty())
65
if err != nil {
66
- remote.Reset()
66
+ _ = remote.Reset()
67
return
68
}
69
p2p/stream.go
+8
-12
@@ -31,15 +31,13 @@ type Stream struct {
31
}
32
33
// close stream endpoints and deregister it
34
-func (s *Stream) close() error {
34
+func (s *Stream) close() {
35
s.Registry.Close(s)
36
- return nil
36
}
37
38
// reset closes stream endpoints and deregisters it
40
-func (s *Stream) reset() error {
39
+func (s *Stream) reset() {
40
s.Registry.Reset(s)
42
- return nil
41
}
42
43
func (s *Stream) startStreaming() {
@@ -108,17 +106,15 @@ func (r *StreamRegistry) Deregister(streamID uint64) {
106
}
107
108
// Close stream endpoints and deregister it
111
-func (r *StreamRegistry) Close(s *Stream) error {
112
- s.Local.Close()
113
- s.Remote.Close()
109
+func (r *StreamRegistry) Close(s *Stream) {
110
+ _ = s.Local.Close()
111
+ _ = s.Remote.Close()
112
s.Registry.Deregister(s.id)
115
- return nil
113
}
114
115
// Reset closes stream endpoints and deregisters it
119
-func (r *StreamRegistry) Reset(s *Stream) error {
120
- s.Local.Close()
121
- s.Remote.Reset()
116
+func (r *StreamRegistry) Reset(s *Stream) {
117
+ _ = s.Local.Close()
118
+ _ = s.Remote.Reset()
119
s.Registry.Deregister(s.id)
123
- return nil
120
}
pin/pin_test.go
+14
-6
@@ -2,6 +2,7 @@ package pin
2
3
import (
4
"context"
5
+ "io"
6
"testing"
7
"time"
8
@@ -21,7 +22,10 @@ var rand = util.NewTimeSeededRand()
22
func randNode() (*mdag.ProtoNode, cid.Cid) {
23
nd := new(mdag.ProtoNode)
24
nd.SetData(make([]byte, 32))
24
- rand.Read(nd.Data())
25
+ _, err := io.ReadFull(rand, nd.Data())
26
+ if err != nil {
27
+ panic(err)
28
+ }
29
k := nd.Cid()
30
return nd, k
31
}
@@ -111,11 +115,11 @@ func TestPinnerBasic(t *testing.T) {
115
assertPinned(t, p, bk, "Recursively pinned node not found..")
116
117
d, _ := randNode()
114
- d.AddNodeLink("a", a)
115
- d.AddNodeLink("c", c)
118
+ _ = d.AddNodeLink("a", a)
119
+ _ = d.AddNodeLink("c", c)
120
121
e, _ := randNode()
118
- d.AddNodeLink("e", e)
122
+ _ = d.AddNodeLink("e", e)
123
124
// Must be in dagserv for unpin to work
125
err = dserv.Add(ctx, e)
@@ -385,8 +389,12 @@ func TestPinUpdate(t *testing.T) {
389
n1, c1 := randNode()
390
n2, c2 := randNode()
391
388
- dserv.Add(ctx, n1)
389
- dserv.Add(ctx, n2)
392
+ if err := dserv.Add(ctx, n1); err != nil {
393
+ t.Fatal(err)
394
+ }
395
+ if err := dserv.Add(ctx, n2); err != nil {
396
+ t.Fatal(err)
397
+ }
398
399
if err := p.Pin(ctx, n1, true); err != nil {
400
t.Fatal(err)
plugin/loader/loader.go
+1
-1
@@ -115,7 +115,7 @@ func (loader *PluginLoader) Start(iface coreiface.CoreAPI) error {
115
if pl, ok := pl.(plugin.PluginDaemon); ok {
116
err := pl.Start(iface)
117
if err != nil {
118
- closePlugins(loader.plugins[i:])
118
+ _ = closePlugins(loader.plugins[i:])
119
return err
120
}
121
}
provider/queue.go
+3
-5
@@ -62,11 +62,6 @@ func (q *Queue) Dequeue() <-chan cid.Cid {
62
return q.dequeue
63
}
64
65
-type entry struct {
66
- cid cid.Cid
67
- key datastore.Key
68
-}
69
-
65
// Look for next Cid in the queue and return it. Skip over gaps and mangled data
66
func (q *Queue) nextEntry() (datastore.Key, cid.Cid) {
67
for {
@@ -91,6 +86,9 @@ func (q *Queue) nextEntry() (datastore.Key, cid.Cid) {
86
log.Warningf("Error marshalling Cid from queue: ", err)
87
q.head++
88
err = q.ds.Delete(key)
89
+ if err != nil {
90
+ log.Warningf("Provider queue failed to delete: %s", key)
91
+ }
92
continue
93
}
94
provider/queue_test.go
+3
@@ -99,6 +99,9 @@ func TestMangledData(t *testing.T) {
99
100
// remove entries in the middle
101
err = queue.ds.Put(queue.queueKey(5), []byte("borked"))
102
+ if err != nil {
103
+ t.Fatal(err)
104
+ }
105
106
expected := append(cids[:5], cids[6:]...)
107
assertOrdered(expected, queue, t)
test/bench/bench_cli_ipfs_add/main.go
+8
-3
@@ -80,7 +80,10 @@ func benchmarkAdd(amount int64) (*testing.BenchmarkResult, error) {
80
}
81
defer os.Remove(f.Name())
82
83
- random.WritePseudoRandomBytes(amount, f, seed)
83
+ if err := random.WritePseudoRandomBytes(amount, f, seed); err != nil {
84
+ benchmarkError = err
85
+ b.Fatal(err)
86
+ }
87
if err := f.Close(); err != nil {
88
benchmarkError = err
89
b.Fatal(err)
@@ -95,8 +98,10 @@ func benchmarkAdd(amount int64) (*testing.BenchmarkResult, error) {
98
benchmarkError = err
99
b.Fatal(err)
100
}
98
- defer daemonCmd.Wait()
99
- defer daemonCmd.Process.Signal(os.Interrupt)
101
+ defer func() {
102
+ _ = daemonCmd.Process.Signal(os.Interrupt)
103
+ _ = daemonCmd.Wait()
104
+ }()
105
}
106
107
b.StartTimer()
test/bench/offline_add/main.go
+4
-1
@@ -62,7 +62,10 @@ func benchmarkAdd(amount int64) (*testing.BenchmarkResult, error) {
62
}
63
defer os.Remove(f.Name())
64
65
- random.WritePseudoRandomBytes(amount, f, seed)
65
+ err = random.WritePseudoRandomBytes(amount, f, seed)
66
+ if err != nil {
67
+ b.Fatal(err)
68
+ }
69
if err := f.Close(); err != nil {
70
b.Fatal(err)
71
}
test/dependencies/ma-pipe-unidir/main.go
+5
-2
@@ -81,12 +81,15 @@ func app() int {
81
defer conn.Close()
82
switch mode {
83
case "recv":
84
- io.Copy(os.Stdout, conn)
84
+ _, err = io.Copy(os.Stdout, conn)
85
case "send":
86
- io.Copy(conn, os.Stdin)
86
+ _, err = io.Copy(conn, os.Stdin)
87
default:
88
return 1
89
}
90
+ if err != nil {
91
+ return 1
92
+ }
93
return 0
94
}
95
test/integration/addcat_test.go
+11
-6
@@ -84,8 +84,11 @@ func AddCatPowers(conf testutil.LatencyConfig, megabytesMax int64) error {
84
}
85
86
func RandomBytes(n int64) []byte {
87
- data := new(bytes.Buffer)
88
- random.WritePseudoRandomBytes(n, data, kSeed)
87
+ var data bytes.Buffer
88
+ err := random.WritePseudoRandomBytes(n, &data, kSeed)
89
+ if err != nil {
90
+ panic(err)
91
+ }
92
return data.Bytes()
93
}
94
@@ -155,13 +158,15 @@ func DirectAddCat(data []byte, conf testutil.LatencyConfig) error {
158
}
159
160
// verify
158
- bufout := new(bytes.Buffer)
159
- io.Copy(bufout, readerCatted.(io.Reader))
160
- if 0 != bytes.Compare(bufout.Bytes(), data) {
161
+ var bufout bytes.Buffer
162
+ _, err = io.Copy(&bufout, readerCatted.(io.Reader))
163
+ if err != nil {
164
+ return err
165
+ }
166
+ if !bytes.Equal(bufout.Bytes(), data) {
167
return errors.New("catted data does not match added data")
168
}
169
164
- cancel()
170
return nil
171
}
172
test/integration/bench_cat_test.go
+6
-3
@@ -102,9 +102,12 @@ func benchCat(b *testing.B, data []byte, conf testutil.LatencyConfig) error {
102
}
103
104
// verify
105
- bufout := new(bytes.Buffer)
106
- io.Copy(bufout, readerCatted.(io.Reader))
107
- if 0 != bytes.Compare(bufout.Bytes(), data) {
105
+ var bufout bytes.Buffer
106
+ _, err = io.Copy(&bufout, readerCatted.(io.Reader))
107
+ if err != nil {
108
+ return err
109
+ }
110
+ if !bytes.Equal(bufout.Bytes(), data) {
111
return errors.New("catted data does not match added data")
112
}
113
return nil
test/integration/bitswap_wo_routing_test.go
+4
-1
@@ -35,7 +35,10 @@ func TestBitswapWithoutRouting(t *testing.T) {
35
nodes = append(nodes, n)
36
}
37
38
- mn.LinkAll()
38
+ err := mn.LinkAll()
39
+ if err != nil {
40
+ t.Fatal(err)
41
+ }
42
43
// connect them
44
for _, n1 := range nodes {
test/integration/three_legged_cat_test.go
+10
-5
@@ -112,7 +112,10 @@ func RunThreeLeggedCat(data []byte, conf testutil.LatencyConfig) error {
112
return err
113
}
114
115
- mn.LinkAll()
115
+ err = mn.LinkAll()
116
+ if err != nil {
117
+ return err
118
+ }
119
120
bis := bootstrap.Peerstore.PeerInfo(bootstrap.PeerHost.ID())
121
bcfg := core.BootstrapConfigWithPeers([]pstore.PeerInfo{bis})
@@ -134,11 +137,13 @@ func RunThreeLeggedCat(data []byte, conf testutil.LatencyConfig) error {
137
}
138
139
// verify
137
- bufout := new(bytes.Buffer)
138
- io.Copy(bufout, readerCatted.(io.Reader))
139
- if 0 != bytes.Compare(bufout.Bytes(), data) {
140
+ var bufout bytes.Buffer
141
+ _, err = io.Copy(&bufout, readerCatted.(io.Reader))
142
+ if err != nil {
143
+ return err
144
+ }
145
+ if !bytes.Equal(bufout.Bytes(), data) {
146
return errors.New("catted data does not match added data")
147
}
142
- cancel()
148
return nil
149
}