@cryptotaxi247 / kubo / commits / f12b372af

style: gofumpt and godot [skip changelog] (#10081)

Kay committed Aug 17, 2023 at 15:32 UTC f12b372af9cc32975ff48397708fac3ec1f9966f
148 files changed +449 -433
assets/assets.go
+2 -2
@@ -17,7 +17,7 @@ import (
17 //go:embed init-doc
18 var Asset embed.FS
19
20 -// initDocPaths lists the paths for the docs we want to seed during --init
20 +// initDocPaths lists the paths for the docs we want to seed during --init.
21 var initDocPaths = []string{
22 gopath.Join("init-doc", "about"),
23 gopath.Join("init-doc", "readme"),
@@ -28,7 +28,7 @@ var initDocPaths = []string{
28 gopath.Join("init-doc", "ping"),
29 }
30
31 -// SeedInitDocs adds the list of embedded init documentation to the passed node, pins it and returns the root key
31 +// SeedInitDocs adds the list of embedded init documentation to the passed node, pins it and returns the root key.
32 func SeedInitDocs(nd *core.IpfsNode) (cid.Cid, error) {
33 return addAssetList(nd, initDocPaths)
34 }
client/rpc/api.go
+5 -5
@@ -48,7 +48,7 @@ type HttpApi struct {
48 // IPFS daemon
49 //
50 // Daemon api address is pulled from the $IPFS_PATH/api file.
51 -// If $IPFS_PATH env var is not present, it defaults to ~/.ipfs
51 +// If $IPFS_PATH env var is not present, it defaults to ~/.ipfs.
52 func NewLocalApi() (*HttpApi, error) {
53 baseDir := os.Getenv(EnvDir)
54 if baseDir == "" {
@@ -59,7 +59,7 @@ func NewLocalApi() (*HttpApi, error) {
59 }
60
61 // NewPathApi constructs new HttpApi by pulling api address from specified
62 -// ipfspath. Api file should be located at $ipfspath/api
62 +// ipfspath. Api file should be located at $ipfspath/api.
63 func NewPathApi(ipfspath string) (*HttpApi, error) {
64 a, err := ApiAddr(ipfspath)
65 if err != nil {
@@ -71,7 +71,7 @@ func NewPathApi(ipfspath string) (*HttpApi, error) {
71 return NewApi(a)
72 }
73
74 -// ApiAddr reads api file in specified ipfs path
74 +// ApiAddr reads api file in specified ipfs path.
75 func ApiAddr(ipfspath string) (ma.Multiaddr, error) {
76 baseDir, err := homedir.Expand(ipfspath)
77 if err != nil {
@@ -88,7 +88,7 @@ func ApiAddr(ipfspath string) (ma.Multiaddr, error) {
88 return ma.NewMultiaddr(strings.TrimSpace(string(api)))
89 }
90
91 -// NewApi constructs HttpApi with specified endpoint
91 +// NewApi constructs HttpApi with specified endpoint.
92 func NewApi(a ma.Multiaddr) (*HttpApi, error) {
93 c := &http.Client{
94 Transport: &http.Transport{
@@ -100,7 +100,7 @@ func NewApi(a ma.Multiaddr) (*HttpApi, error) {
100 return NewApiWithClient(a, c)
101 }
102
103 -// NewApiWithClient constructs HttpApi with specified endpoint and custom http client
103 +// NewApiWithClient constructs HttpApi with specified endpoint and custom http client.
104 func NewApiWithClient(a ma.Multiaddr, c *http.Client) (*HttpApi, error) {
105 _, url, err := manet.DialArgs(a)
106 if err != nil {
client/rpc/apifile.go
+7 -6
@@ -12,7 +12,7 @@ import (
12 "github.com/ipfs/go-cid"
13 )
14
15 -const forwardSeekLimit = 1 << 14 //16k
15 +const forwardSeekLimit = 1 << 14 // 16k
16
17 func (api *UnixfsAPI) Get(ctx context.Context, p path.Path) (files.Node, error) {
18 if p.Mutable() { // use resolved path in case we are dealing with IPNS / MFS
@@ -107,11 +107,11 @@ func (f *apiFile) Seek(offset int64, whence int) (int64, error) {
107 case io.SeekCurrent:
108 offset = f.at + offset
109 }
110 - if f.at == offset { //noop
110 + if f.at == offset { // noop
111 return offset, nil
112 }
113
114 - if f.at < offset && offset-f.at < forwardSeekLimit { //forward skip
114 + if f.at < offset && offset-f.at < forwardSeekLimit { // forward skip
115 r, err := io.CopyN(io.Discard, f.r.Output, offset-f.at)
116
117 f.at += r
@@ -246,7 +246,6 @@ func (api *UnixfsAPI) getDir(ctx context.Context, p path.Path, size int64) (file
246 resp, err := api.core().Request("ls", p.String()).
247 Option("resolve-size", true).
248 Option("stream", true).Send(ctx)
249 -
249 if err != nil {
250 return nil, err
251 }
@@ -266,5 +265,7 @@ func (api *UnixfsAPI) getDir(ctx context.Context, p path.Path, size int64) (file
265 return d, nil
266 }
267
269 -var _ files.File = &apiFile{}
270 -var _ files.Directory = &apiDir{}
268 +var (
269 + _ files.File = &apiFile{}
270 + _ files.Directory = &apiDir{}
271 +)
client/rpc/block.go
+1 -1
@@ -83,7 +83,7 @@ func (api *BlockAPI) Get(ctx context.Context, p path.Path) (io.Reader, error) {
83 return nil, parseErrNotFoundWithFallbackToError(resp.Error)
84 }
85
86 - //TODO: make get return ReadCloser to avoid copying
86 + // TODO: make get return ReadCloser to avoid copying
87 defer resp.Close()
88 b := new(bytes.Buffer)
89 if _, err := io.Copy(b, resp.Output); err != nil {
client/rpc/dag.go
+6 -4
@@ -14,9 +14,11 @@ import (
14 multicodec "github.com/multiformats/go-multicodec"
15 )
16
17 -type httpNodeAdder HttpApi
18 -type HttpDagServ httpNodeAdder
19 -type pinningHttpNodeAdder httpNodeAdder
17 +type (
18 + httpNodeAdder HttpApi
19 + HttpDagServ httpNodeAdder
20 + pinningHttpNodeAdder httpNodeAdder
21 +)
22
23 func (api *HttpDagServ) Get(ctx context.Context, c cid.Cid) (format.Node, error) {
24 r, err := api.core().Block().Get(ctx, path.IpldPath(c))
@@ -114,7 +116,7 @@ func (api *HttpDagServ) Pinning() format.NodeAdder {
116 }
117
118 func (api *HttpDagServ) Remove(ctx context.Context, c cid.Cid) error {
117 - return api.core().Block().Rm(ctx, path.IpldPath(c)) //TODO: should we force rm?
119 + return api.core().Block().Rm(ctx, path.IpldPath(c)) // TODO: should we force rm?
120 }
121
122 func (api *HttpDagServ) RemoveMany(ctx context.Context, cids []cid.Cid) error {
client/rpc/errors.go
+2 -2
@@ -68,7 +68,7 @@ func parseErrNotFound(msg string) (error, bool) {
68 // Assume CIDs break on:
69 // - Whitespaces: " \t\n\r\v\f"
70 // - Semicolon: ";" this is to parse ipld.ErrNotFound wrapped in multierr
71 -// - Double Quotes: "\"" this is for parsing %q and %#v formating
71 +// - Double Quotes: "\"" this is for parsing %q and %#v formating.
72 const cidBreakSet = " \t\n\r\v\f;\""
73
74 func parseIPLDErrNotFound(msg string) (error, bool) {
@@ -139,7 +139,7 @@ func parseIPLDErrNotFound(msg string) (error, bool) {
139 // This is a simple error type that just return msg as Error().
140 // But that also match ipld.ErrNotFound when called with Is(err).
141 // That is needed to keep compatiblity with code that use string.Contains(err.Error(), "blockstore: block not found")
142 -// and code using ipld.ErrNotFound
142 +// and code using ipld.ErrNotFound.
143 type blockstoreNotFoundMatchingIPLDErrNotFound struct {
144 msg string
145 }
client/rpc/object.go
+1 -1
@@ -87,7 +87,7 @@ func (api *ObjectAPI) Data(ctx context.Context, p path.Path) (io.Reader, error)
87 return nil, resp.Error
88 }
89
90 - //TODO: make Data return ReadCloser to avoid copying
90 + // TODO: make Data return ReadCloser to avoid copying
91 defer resp.Close()
92 b := new(bytes.Buffer)
93 if _, err := io.Copy(b, resp.Output); err != nil {
client/rpc/path.go
+1 -1
@@ -15,7 +15,7 @@ func (api *HttpApi) ResolvePath(ctx context.Context, p path.Path) (path.Resolved
15 RemPath string
16 }
17
18 - //TODO: this is hacky, fixing https://github.com/ipfs/go-ipfs/issues/5703 would help
18 + // TODO: this is hacky, fixing https://github.com/ipfs/go-ipfs/issues/5703 would help
19
20 var err error
21 if p.Namespace() == "ipns" {
client/rpc/pin.go
+1 -1
@@ -112,7 +112,7 @@ func (api *PinAPI) Ls(ctx context.Context, opts ...caopts.PinLsOption) (<-chan i
112 }
113
114 // IsPinned returns whether or not the given cid is pinned
115 -// and an explanation of why its pinned
115 +// and an explanation of why its pinned.
116 func (api *PinAPI) IsPinned(ctx context.Context, p path.Path, opts ...caopts.PinIsPinnedOption) (string, bool, error) {
117 options, err := caopts.PinIsPinnedOptions(opts...)
118 if err != nil {
client/rpc/pubsub.go
+1 -2
@@ -152,7 +152,6 @@ func (api *PubsubAPI) Subscribe(ctx context.Context, topic string, opts ...caopt
152 }
153 */
154 resp, err := api.core().Request("pubsub/sub", toMultibase([]byte(topic))).Send(ctx)
155 -
155 if err != nil {
156 return nil, err
157 }
@@ -207,7 +206,7 @@ func (api *PubsubAPI) core() *HttpApi {
206 return (*HttpApi)(api)
207 }
208
210 -// Encodes bytes into URL-safe multibase that can be sent over HTTP RPC (URL or body)
209 +// Encodes bytes into URL-safe multibase that can be sent over HTTP RPC (URL or body).
210 func toMultibase(data []byte) string {
211 mb, _ := mbase.Encode(mbase.Base64url, data)
212 return mb
client/rpc/response.go
+2 -3
@@ -54,7 +54,7 @@ func (r *Response) Close() error {
54 return nil
55 }
56
57 -// Cancel aborts running request (without draining request body)
57 +// Cancel aborts running request (without draining request body).
58 func (r *Response) Cancel() error {
59 if r.Output != nil {
60 return r.Output.Close()
@@ -63,7 +63,7 @@ func (r *Response) Cancel() error {
63 return nil
64 }
65
66 -// Decode reads request body and decodes it as json
66 +// Decode reads request body and decodes it as json.
67 func (r *Response) decode(dec interface{}) error {
68 if r.Error != nil {
69 return r.Error
@@ -157,7 +157,6 @@ func (r *Request) Send(c *http.Client) (*Response, error) {
157 }
158
159 func (r *Request) getURL() string {
160 -
160 values := make(url.Values)
161 for _, arg := range r.Args {
162 values.Add("arg", arg)
client/rpc/routing.go
-1
@@ -49,7 +49,6 @@ func (api *RoutingAPI) Put(ctx context.Context, key string, value []byte, opts .
49 Option("allow-offline", cfg.AllowOffline).
50 FileBody(bytes.NewReader(value)).
51 Send(ctx)
52 -
52 if err != nil {
53 return err
54 }
cmd/ipfs/add_migrations.go
+2 -2
@@ -19,7 +19,7 @@ import (
19 "github.com/libp2p/go-libp2p/core/peer"
20 )
21
22 -// addMigrations adds any migration downloaded by the fetcher to the IPFS node
22 +// addMigrations adds any migration downloaded by the fetcher to the IPFS node.
23 func addMigrations(ctx context.Context, node *core.IpfsNode, fetcher migrations.Fetcher, pin bool) error {
24 var fetchers []migrations.Fetcher
25 if mf, ok := fetcher.(*migrations.MultiFetcher); ok {
@@ -63,7 +63,7 @@ func addMigrations(ctx context.Context, node *core.IpfsNode, fetcher migrations.
63 return nil
64 }
65
66 -// addMigrationFiles adds the files at paths to IPFS, optionally pinning them
66 +// addMigrationFiles adds the files at paths to IPFS, optionally pinning them.
67 func addMigrationFiles(ctx context.Context, node *core.IpfsNode, paths []string, pin bool) error {
68 if len(paths) == 0 {
69 return nil
cmd/ipfs/daemon.go
+9 -11
@@ -73,7 +73,7 @@ const (
73 enableMultiplexKwd = "enable-mplex-experiment"
74 agentVersionSuffix = "agent-version-suffix"
75 // apiAddrKwd = "address-api"
76 - // swarmAddrKwd = "address-swarm"
76 + // swarmAddrKwd = "address-swarm".
77 )
78
79 var daemonCmd = &cmds.Command{
@@ -389,7 +389,7 @@ func daemonFunc(req *cmds.Request, re cmds.ResponseEmitter, env cmds.Environment
389 "pubsub": pubsub,
390 "ipnsps": ipnsps,
391 },
392 - //TODO(Kubuxu): refactor Online vs Offline by adding Permanent vs Ephemeral
392 + // TODO(Kubuxu): refactor Online vs Offline by adding Permanent vs Ephemeral
393 }
394
395 routingOption, _ := req.Options[routingOptionKwd].(string)
@@ -552,7 +552,7 @@ take effect.
552 }
553
554 // Add ipfs version info to prometheus metrics
555 - var ipfsInfoMetric = promauto.NewGaugeVec(prometheus.GaugeOpts{
555 + ipfsInfoMetric := promauto.NewGaugeVec(prometheus.GaugeOpts{
556 Name: "ipfs_info",
557 Help: "IPFS version information.",
558 }, []string{"version", "commit"})
@@ -607,7 +607,6 @@ take effect.
607 log.Error("failed to bootstrap (no peers found): consider updating Bootstrap or Peering section of your config")
608 }
609 })
610 -
610 }
611
612 // Hard deprecation notice if someone still uses IPFS_REUSEPORT
@@ -627,7 +626,7 @@ take effect.
626 return errs
627 }
628
630 -// serveHTTPApi collects options, creates listener, prints status message and starts serving requests
629 +// serveHTTPApi collects options, creates listener, prints status message and starts serving requests.
630 func serveHTTPApi(req *cmds.Request, cctx *oldcmds.Context) (<-chan error, error) {
631 cfg, err := cctx.GetConfig()
632 if err != nil {
@@ -690,7 +689,7 @@ func serveHTTPApi(req *cmds.Request, cctx *oldcmds.Context) (<-chan error, error
689 gatewayOpt = corehttp.GatewayOption("/ipfs", "/ipns")
690 }
691
693 - var opts = []corehttp.ServeOption{
692 + opts := []corehttp.ServeOption{
693 corehttp.MetricsCollectionOption("api"),
694 corehttp.MetricsOpenCensusCollectionOption(),
695 corehttp.MetricsOpenCensusDefaultPrometheusRegistry(),
@@ -752,7 +751,7 @@ func rewriteMaddrToUseLocalhostIfItsAny(maddr ma.Multiaddr) ma.Multiaddr {
751 }
752 }
753
755 -// printSwarmAddrs prints the addresses of the host
754 +// printSwarmAddrs prints the addresses of the host.
755 func printSwarmAddrs(node *core.IpfsNode) {
756 if !node.IsOnline {
757 fmt.Println("Swarm not listening, running in offline mode.")
@@ -781,10 +780,9 @@ func printSwarmAddrs(node *core.IpfsNode) {
780 for _, addr := range addrs {
781 fmt.Printf("Swarm announcing %s\n", addr)
782 }
784 -
783 }
784
787 -// serveHTTPGateway collects options, creates listener, prints status message and starts serving requests
785 +// serveHTTPGateway collects options, creates listener, prints status message and starts serving requests.
786 func serveHTTPGateway(req *cmds.Request, cctx *oldcmds.Context) (<-chan error, error) {
787 cfg, err := cctx.GetConfig()
788 if err != nil {
@@ -837,7 +835,7 @@ func serveHTTPGateway(req *cmds.Request, cctx *oldcmds.Context) (<-chan error, e
835 cmdctx := *cctx
836 cmdctx.Gateway = true
837
840 - var opts = []corehttp.ServeOption{
838 + opts := []corehttp.ServeOption{
839 corehttp.MetricsCollectionOption("gateway"),
840 corehttp.HostnameOption(),
841 corehttp.GatewayOption("/ipfs", "/ipns"),
@@ -891,7 +889,7 @@ func serveHTTPGateway(req *cmds.Request, cctx *oldcmds.Context) (<-chan error, e
889 return errc, nil
890 }
891
894 -// collects options and opens the fuse mountpoint
892 +// collects options and opens the fuse mountpoint.
893 func mountFuse(req *cmds.Request, cctx *oldcmds.Context) error {
894 cfg, err := cctx.GetConfig()
895 if err != nil {
cmd/ipfs/dnsresolve_test.go
+2 -1
@@ -25,7 +25,8 @@ func makeResolver(t *testing.T, n uint8) *madns.Resolver {
25 backend := &madns.MockResolver{
26 IP: map[string][]net.IPAddr{
27 "example.com": results,
28 - }}
28 + },
29 + }
30
31 resolver, err := madns.NewResolver(madns.WithDefaultResolver(backend))
32 if err != nil {
cmd/ipfs/init.go
+1 -1
@@ -194,7 +194,7 @@ func checkWritable(dir string) error {
194
195 if os.IsNotExist(err) {
196 // dir doesn't exist, check that we can create it
197 - return os.Mkdir(dir, 0775)
197 + return os.Mkdir(dir, 0o775)
198 }
199
200 if os.IsPermission(err) {
cmd/ipfs/ipfs.go
+1 -1
@@ -14,7 +14,7 @@ var Root = &cmds.Command{
14 Helptext: commands.Root.Helptext,
15 }
16
17 -// commandsClientCmd is the "ipfs commands" command for local cli
17 +// commandsClientCmd is the "ipfs commands" command for local cli.
18 var commandsClientCmd = commands.CommandsCmd(Root)
19
20 // Commands in localCommands should always be run locally (even if daemon is running).
cmd/ipfs/main.go
+7 -5
@@ -39,11 +39,13 @@ import (
39 "go.opentelemetry.io/otel/trace"
40 )
41
42 -// log is the command logger
43 -var log = logging.Logger("cmd/ipfs")
44 -var tracer trace.Tracer
42 +// log is the command logger.
43 +var (
44 + log = logging.Logger("cmd/ipfs")
45 + tracer trace.Tracer
46 +)
47
46 -// declared as a var for testing purposes
48 +// declared as a var for testing purposes.
49 var dnsResolver = madns.DefaultResolver
50
51 const (
@@ -73,7 +75,7 @@ func loadPlugins(repoPath string) (*loader.PluginLoader, error) {
75 // - if user requests help, print it and exit.
76 // - run the command invocation
77 // - output the response
76 -// - if anything fails, print error, maybe with help
78 +// - if anything fails, print error, maybe with help.
79 func main() {
80 os.Exit(mainRet())
81 }
cmd/ipfs/pinmfs.go
+1 -1
@@ -18,7 +18,7 @@ import (
18 "github.com/ipfs/kubo/core"
19 )
20
21 -// mfslog is the logger for remote mfs pinning
21 +// mfslog is the logger for remote mfs pinning.
22 var mfslog = logging.Logger("remotepinning/mfs")
23
24 type lastPin struct {
cmd/ipfs/runmain_test.go
+2 -2
@@ -12,7 +12,7 @@ import (
12
13 // this abuses go so much that I felt dirty writing this code
14 // but it is the only way to do it without writing custom compiler that would
15 -// be a clone of go-build with go-test
15 +// be a clone of go-build with go-test.
16 func TestRunMain(t *testing.T) {
17 args := flag.Args()
18 os.Args = append([]string{os.Args[0]}, args...)
@@ -20,7 +20,7 @@ func TestRunMain(t *testing.T) {
20
21 p := os.Getenv("IPFS_COVER_RET_FILE")
22 if len(p) != 0 {
23 - os.WriteFile(p, []byte(fmt.Sprintf("%d\n", ret)), 0777)
23 + os.WriteFile(p, []byte(fmt.Sprintf("%d\n", ret)), 0o777)
24 }
25
26 // close outputs so go testing doesn't print anything
cmd/ipfs/util/ulimit.go
+5 -5
@@ -14,19 +14,19 @@ var log = logging.Logger("ulimit")
14 var (
15 supportsFDManagement = false
16
17 - // getlimit returns the soft and hard limits of file descriptors counts
17 + // getlimit returns the soft and hard limits of file descriptors counts.
18 getLimit func() (uint64, uint64, error)
19 - // set limit sets the soft and hard limits of file descriptors counts
19 + // set limit sets the soft and hard limits of file descriptors counts.
20 setLimit func(uint64, uint64) error
21 )
22
23 -// minimum file descriptor limit before we complain
23 +// minimum file descriptor limit before we complain.
24 const minFds = 2048
25
26 // default max file descriptor limit.
27 const maxFds = 8192
28
29 -// userMaxFDs returns the value of IPFS_FD_MAX
29 +// userMaxFDs returns the value of IPFS_FD_MAX.
30 func userMaxFDs() uint64 {
31 // check if the IPFS_FD_MAX is set up and if it does
32 // not have a valid fds number notify the user
@@ -42,7 +42,7 @@ func userMaxFDs() uint64 {
42 }
43
44 // ManageFdLimit raise the current max file descriptor count
45 -// of the process based on the IPFS_FD_MAX value
45 +// of the process based on the IPFS_FD_MAX value.
46 func ManageFdLimit() (changed bool, newLimit uint64, err error) {
47 if !supportsFDManagement {
48 return false, 0, nil
cmd/ipfswatch/main.go
+6 -5
@@ -24,9 +24,11 @@ import (
24 homedir "github.com/mitchellh/go-homedir"
25 )
26
27 -var http = flag.Bool("http", false, "expose IPFS HTTP API")
28 -var repoPath = flag.String("repo", os.Getenv("IPFS_PATH"), "IPFS_PATH to use")
29 -var watchPath = flag.String("path", ".", "the path to watch")
27 +var (
28 + http = flag.Bool("http", false, "expose IPFS HTTP API")
29 + repoPath = flag.String("repo", os.Getenv("IPFS_PATH"), "IPFS_PATH to use")
30 + watchPath = flag.String("path", ".", "the path to watch")
31 +)
32
33 func main() {
34 flag.Parse()
@@ -52,7 +54,6 @@ func main() {
54 }
55
56 func run(ipfsPath, watchPath string) error {
55 -
57 proc := process.WithParent(process.Background())
58 log.Printf("running IPFSWatch on '%s' using repo at '%s'...", watchPath, ipfsPath)
59
@@ -93,7 +94,7 @@ func run(ipfsPath, watchPath string) error {
94
95 if *http {
96 addr := "/ip4/127.0.0.1/tcp/5001"
96 - var opts = []corehttp.ServeOption{
97 + opts := []corehttp.ServeOption{
98 corehttp.GatewayOption("/ipfs", "/ipns"),
99 corehttp.WebUIOption,
100 corehttp.CommandsOption(cmdCtx(node, ipfsPath)),
commands/context.go
+2 -2
@@ -19,7 +19,7 @@ import (
19
20 var log = logging.Logger("command")
21
22 -// Context represents request context
22 +// Context represents request context.
23 type Context struct {
24 ConfigRoot string
25 ReqLog *ReqLog
@@ -54,7 +54,7 @@ func (c *Context) GetNode() (*core.IpfsNode, error) {
54 }
55
56 // GetAPI returns CoreAPI instance backed by ipfs node.
57 -// It may construct the node with the provided function
57 +// It may construct the node with the provided function.
58 func (c *Context) GetAPI() (coreiface.CoreAPI, error) {
59 if c.api == nil {
60 n, err := c.GetNode()
commands/reqlog.go
+8 -8
@@ -5,7 +5,7 @@ import (
5 "time"
6 )
7
8 -// ReqLogEntry is an entry in the request log
8 +// ReqLogEntry is an entry in the request log.
9 type ReqLogEntry struct {
10 StartTime time.Time
11 EndTime time.Time
@@ -18,14 +18,14 @@ type ReqLogEntry struct {
18 log *ReqLog
19 }
20
21 -// Copy returns a copy of the ReqLogEntry
21 +// Copy returns a copy of the ReqLogEntry.
22 func (r *ReqLogEntry) Copy() *ReqLogEntry {
23 out := *r
24 out.log = nil
25 return &out
26 }
27
28 -// ReqLog is a log of requests
28 +// ReqLog is a log of requests.
29 type ReqLog struct {
30 Requests []*ReqLogEntry
31 nextID int
@@ -33,7 +33,7 @@ type ReqLog struct {
33 keep time.Duration
34 }
35
36 -// AddEntry adds an entry to the log
36 +// AddEntry adds an entry to the log.
37 func (rl *ReqLog) AddEntry(rle *ReqLogEntry) {
38 rl.lock.Lock()
39 defer rl.lock.Unlock()
@@ -47,7 +47,7 @@ func (rl *ReqLog) AddEntry(rle *ReqLogEntry) {
47 }
48 }
49
50 -// ClearInactive removes stale entries
50 +// ClearInactive removes stale entries.
51 func (rl *ReqLog) ClearInactive() {
52 rl.lock.Lock()
53 defer rl.lock.Unlock()
@@ -79,14 +79,14 @@ func (rl *ReqLog) cleanup() {
79 rl.Requests = rl.Requests[:i]
80 }
81
82 -// SetKeepTime sets a duration after which an entry will be considered inactive
82 +// SetKeepTime sets a duration after which an entry will be considered inactive.
83 func (rl *ReqLog) SetKeepTime(t time.Duration) {
84 rl.lock.Lock()
85 defer rl.lock.Unlock()
86 rl.keep = t
87 }
88
89 -// Report generates a copy of all the entries in the requestlog
89 +// Report generates a copy of all the entries in the requestlog.
90 func (rl *ReqLog) Report() []*ReqLogEntry {
91 rl.lock.Lock()
92 defer rl.lock.Unlock()
@@ -99,7 +99,7 @@ func (rl *ReqLog) Report() []*ReqLogEntry {
99 return out
100 }
101
102 -// Finish marks an entry in the log as finished
102 +// Finish marks an entry in the log as finished.
103 func (rl *ReqLog) Finish(rle *ReqLogEntry) {
104 rl.lock.Lock()
105 defer rl.lock.Unlock()
config/autonat.go
+1 -1
@@ -64,7 +64,7 @@ type AutoNATConfig struct {
64 Throttle *AutoNATThrottleConfig `json:",omitempty"`
65 }
66
67 -// AutoNATThrottleConfig configures the throttle limites
67 +// AutoNATThrottleConfig configures the throttle limites.
68 type AutoNATThrottleConfig struct {
69 // GlobalLimit and PeerLimit sets the global and per-peer dialback
70 // limits. The AutoNAT service will only perform the specified number of
config/config.go
+5 -5
@@ -41,17 +41,17 @@ type Config struct {
41 }
42
43 const (
44 - // DefaultPathName is the default config dir name
44 + // DefaultPathName is the default config dir name.
45 DefaultPathName = ".ipfs"
46 // DefaultPathRoot is the path to the default config dir location.
47 DefaultPathRoot = "~/" + DefaultPathName
48 - // DefaultConfigFile is the filename of the configuration file
48 + // DefaultConfigFile is the filename of the configuration file.
49 DefaultConfigFile = "config"
50 // EnvDir is the environment variable used to change the path root.
51 EnvDir = "IPFS_PATH"
52 )
53
54 -// PathRoot returns the default configuration root directory
54 +// PathRoot returns the default configuration root directory.
55 func PathRoot() (string, error) {
56 dir := os.Getenv(EnvDir)
57 var err error
@@ -95,7 +95,7 @@ func Filename(configroot, userConfigFile string) (string, error) {
95 return userConfigFile, nil
96 }
97
98 -// HumanOutput gets a config value ready for printing
98 +// HumanOutput gets a config value ready for printing.
99 func HumanOutput(value interface{}) ([]byte, error) {
100 s, ok := value.(string)
101 if ok {
@@ -104,7 +104,7 @@ func HumanOutput(value interface{}) ([]byte, error) {
104 return Marshal(value)
105 }
106
107 -// Marshal configuration with JSON
107 +// Marshal configuration with JSON.
108 func Marshal(value interface{}) ([]byte, error) {
109 // need to prettyprint, hence MarshalIndent, instead of Encoder
110 return json.MarshalIndent(value, "", " ")
config/datastore.go
+1 -1
@@ -26,7 +26,7 @@ type Datastore struct {
26 }
27
28 // DataStorePath returns the default data store path given a configuration root
29 -// (set an empty string to have the default configuration root)
29 +// (set an empty string to have the default configuration root).
30 func DataStorePath(configroot string) (string, error) {
31 return Path(configroot, DefaultDataStoreDirectory)
32 }
config/dns.go
+1 -1
@@ -1,6 +1,6 @@
1 package config
2
3 -// DNS specifies DNS resolution rules using custom resolvers
3 +// DNS specifies DNS resolution rules using custom resolvers.
4 type DNS struct {
5 // Resolvers is a map of FQDNs to URLs for custom DNS resolution.
6 // URLs starting with `https://` indicate DoH endpoints.
config/gateway.go
-1
@@ -37,7 +37,6 @@ type GatewaySpec struct {
37
38 // Gateway contains options for the HTTP gateway server.
39 type Gateway struct {
40 -
40 // HTTPHeaders configures the headers that should be returned by this
41 // gateway.
42 HTTPHeaders map[string][]string // HTTP headers to return with the gateway
config/identity.go
+6 -4
@@ -6,9 +6,11 @@ import (
6 ic "github.com/libp2p/go-libp2p/core/crypto"
7 )
8
9 -const IdentityTag = "Identity"
10 -const PrivKeyTag = "PrivKey"
11 -const PrivKeySelector = IdentityTag + "." + PrivKeyTag
9 +const (
10 + IdentityTag = "Identity"
11 + PrivKeyTag = "PrivKey"
12 + PrivKeySelector = IdentityTag + "." + PrivKeyTag
13 +)
14
15 // Identity tracks the configuration of the local node's identity.
16 type Identity struct {
@@ -16,7 +18,7 @@ type Identity struct {
18 PrivKey string `json:",omitempty"`
19 }
20
19 -// DecodePrivateKey is a helper to decode the users PrivateKey
21 +// DecodePrivateKey is a helper to decode the users PrivateKey.
22 func (i *Identity) DecodePrivateKey(passphrase string) (ic.PrivKey, error) {
23 pkb, err := base64.StdEncoding.DecodeString(i.PrivKey)
24 if err != nil {
config/init.go
+3 -3
@@ -90,15 +90,15 @@ func InitWithIdentity(identity Identity) (*Config, error) {
90 }
91
92 // DefaultConnMgrHighWater is the default value for the connection managers
93 -// 'high water' mark
93 +// 'high water' mark.
94 const DefaultConnMgrHighWater = 96
95
96 // DefaultConnMgrLowWater is the default value for the connection managers 'low
97 -// water' mark
97 +// water' mark.
98 const DefaultConnMgrLowWater = 32
99
100 // DefaultConnMgrGracePeriod is the default value for the connection managers
101 -// grace period
101 +// grace period.
102 const DefaultConnMgrGracePeriod = time.Second * 20
103
104 // DefaultConnMgrType is the default value for the connection managers
config/migration.go
+1 -1
@@ -5,7 +5,7 @@ const DefaultMigrationKeep = "cache"
5 var DefaultMigrationDownloadSources = []string{"HTTPS", "IPFS"}
6
7 // Migration configures how migrations are downloaded and if the downloads are
8 -// added to IPFS locally
8 +// added to IPFS locally.
9 type Migration struct {
10 // Sources in order of preference, where "IPFS" means use IPFS and "HTTPS"
11 // means use default gateways. Any other values are interpreted as
config/mounts.go
+1 -1
@@ -1,6 +1,6 @@
1 package config
2
3 -// Mounts stores the (string) mount points
3 +// Mounts stores the (string) mount points.
4 type Mounts struct {
5 IPFS string
6 IPNS string
config/profile.go
+3 -3
@@ -6,10 +6,10 @@ import (
6 "time"
7 )
8
9 -// Transformer is a function which takes configuration and applies some filter to it
9 +// Transformer is a function which takes configuration and applies some filter to it.
10 type Transformer func(c *Config) error
11
12 -// Profile contains the profile transformer the description of the profile
12 +// Profile contains the profile transformer the description of the profile.
13 type Profile struct {
14 // Description briefly describes the functionality of the profile.
15 Description string
@@ -43,7 +43,7 @@ var defaultServerFilters = []string{
43 "/ip6/fe80::/ipcidr/10",
44 }
45
46 -// Profiles is a map holding configuration transformers. Docs are in docs/config.md
46 +// Profiles is a map holding configuration transformers. Docs are in docs/config.md.
47 var Profiles = map[string]Profile{
48 "server": {
49 Description: `Disables local host discovery, recommended when
config/reprovider.go
+4 -2
@@ -2,8 +2,10 @@ package config
2
3 import "time"
4
5 -const DefaultReproviderInterval = time.Hour * 22 // https://github.com/ipfs/kubo/pull/9326
6 -const DefaultReproviderStrategy = "all"
5 +const (
6 + DefaultReproviderInterval = time.Hour * 22 // https://github.com/ipfs/kubo/pull/9326
7 + DefaultReproviderStrategy = "all"
8 +)
9
10 type Reprovider struct {
11 Interval *OptionalDuration `json:",omitempty"` // Time period to reprovide locally stored objects to the network
config/routing.go
+5 -5
@@ -6,7 +6,7 @@ import (
6 "runtime"
7 )
8
9 -// Routing defines configuration options for libp2p routing
9 +// Routing defines configuration options for libp2p routing.
10 type Routing struct {
11 // Type sets default daemon routing mode.
12 //
@@ -23,7 +23,6 @@ type Routing struct {
23 }
24
25 type Router struct {
26 -
26 // Router type ID. See RouterType for more info.
27 Type RouterType
28
@@ -32,11 +31,12 @@ type Router struct {
31 Parameters interface{}
32 }
33
35 -type Routers map[string]RouterParser
36 -type Methods map[MethodName]Method
34 +type (
35 + Routers map[string]RouterParser
36 + Methods map[MethodName]Method
37 +)
38
39 func (m Methods) Check() error {
39 -
40 // Check supported methods
41 for _, mn := range MethodNameList {
42 _, ok := m[mn]
config/routing_test.go
+35 -31
@@ -23,42 +23,46 @@ func TestRouterParameters(t *testing.T) {
23 PublicIPNetwork: false,
24 },
25 }},
26 - "router-parallel": {Router{
27 - Type: RouterTypeParallel,
28 - Parameters: ComposableRouterParams{
29 - Routers: []ConfigRouter{
30 - {
31 - RouterName: "router-dht",
32 - Timeout: Duration{10 * time.Second},
33 - IgnoreErrors: true,
34 - },
35 - {
36 - RouterName: "router-dht",
37 - Timeout: Duration{10 * time.Second},
38 - IgnoreErrors: false,
39 - ExecuteAfter: &OptionalDuration{&sec},
26 + "router-parallel": {
27 + Router{
28 + Type: RouterTypeParallel,
29 + Parameters: ComposableRouterParams{
30 + Routers: []ConfigRouter{
31 + {
32 + RouterName: "router-dht",
33 + Timeout: Duration{10 * time.Second},
34 + IgnoreErrors: true,
35 + },
36 + {
37 + RouterName: "router-dht",
38 + Timeout: Duration{10 * time.Second},
39 + IgnoreErrors: false,
40 + ExecuteAfter: &OptionalDuration{&sec},
41 + },
42 },
43 + Timeout: &OptionalDuration{&min},
44 },
42 - Timeout: &OptionalDuration{&min},
43 - }},
45 + },
46 },
45 - "router-sequential": {Router{
46 - Type: RouterTypeSequential,
47 - Parameters: ComposableRouterParams{
48 - Routers: []ConfigRouter{
49 - {
50 - RouterName: "router-dht",
51 - Timeout: Duration{10 * time.Second},
52 - IgnoreErrors: true,
53 - },
54 - {
55 - RouterName: "router-dht",
56 - Timeout: Duration{10 * time.Second},
57 - IgnoreErrors: false,
47 + "router-sequential": {
48 + Router{
49 + Type: RouterTypeSequential,
50 + Parameters: ComposableRouterParams{
51 + Routers: []ConfigRouter{
52 + {
53 + RouterName: "router-dht",
54 + Timeout: Duration{10 * time.Second},
55 + IgnoreErrors: true,
56 + },
57 + {
58 + RouterName: "router-dht",
59 + Timeout: Duration{10 * time.Second},
60 + IgnoreErrors: false,
61 + },
62 },
63 + Timeout: &OptionalDuration{&min},
64 },
60 - Timeout: &OptionalDuration{&min},
61 - }},
65 + },
66 },
67 },
68 Methods: Methods{
config/serialize/serialize.go
+3 -3
@@ -35,12 +35,12 @@ func ReadConfigFile(filename string, cfg interface{}) error {
35
36 // WriteConfigFile writes the config from `cfg` into `filename`.
37 func WriteConfigFile(filename string, cfg interface{}) error {
38 - err := os.MkdirAll(filepath.Dir(filename), 0755)
38 + err := os.MkdirAll(filepath.Dir(filename), 0o755)
39 if err != nil {
40 return err
41 }
42
43 - f, err := atomicfile.New(filename, 0600)
43 + f, err := atomicfile.New(filename, 0o600)
44 if err != nil {
45 return err
46 }
@@ -49,7 +49,7 @@ func WriteConfigFile(filename string, cfg interface{}) error {
49 return encode(f, cfg)
50 }
51
52 -// encode configuration with JSON
52 +// encode configuration with JSON.
53 func encode(w io.Writer, value interface{}) error {
54 // need to prettyprint, hence MarshalIndent, instead of Encoder
55 buf, err := config.Marshal(value)
config/serialize/serialize_test.go
+1 -1
@@ -30,7 +30,7 @@ func TestConfig(t *testing.T) {
30 }
31
32 if runtime.GOOS != "windows" { // see https://golang.org/src/os/types_windows.go
33 - if g := st.Mode().Perm(); g&0117 != 0 {
33 + if g := st.Mode().Perm(); g&0o117 != 0 {
34 t.Fatalf("config file should not be executable or accessible to world: %v", g)
35 }
36 }
config/swarm.go
+1 -1
@@ -127,7 +127,7 @@ type Transports struct {
127 }
128 }
129
130 -// ConnMgr defines configuration options for the libp2p connection manager
130 +// ConnMgr defines configuration options for the libp2p connection manager.
131 type ConnMgr struct {
132 Type *OptionalString `json:",omitempty"`
133 LowWater *OptionalInteger `json:",omitempty"`
config/types.go
+36 -22
@@ -42,8 +42,10 @@ func (o Strings) MarshalJSON() ([]byte, error) {
42 }
43 }
44
45 -var _ json.Unmarshaler = (*Strings)(nil)
46 -var _ json.Marshaler = (*Strings)(nil)
45 +var (
46 + _ json.Unmarshaler = (*Strings)(nil)
47 + _ json.Marshaler = (*Strings)(nil)
48 +)
49
50 // Flag represents a ternary value: false (-1), default (0), or true (+1).
51 //
@@ -113,8 +115,10 @@ func (f Flag) String() string {
115 }
116 }
117
116 -var _ json.Unmarshaler = (*Flag)(nil)
117 -var _ json.Marshaler = (*Flag)(nil)
118 +var (
119 + _ json.Unmarshaler = (*Flag)(nil)
120 + _ json.Marshaler = (*Flag)(nil)
121 +)
122
123 // Priority represents a value with a priority where 0 means "default" and -1
124 // means "disabled".
@@ -210,17 +214,19 @@ func (p Priority) String() string {
214 }
215 }
216
213 -var _ json.Unmarshaler = (*Priority)(nil)
214 -var _ json.Marshaler = (*Priority)(nil)
217 +var (
218 + _ json.Unmarshaler = (*Priority)(nil)
219 + _ json.Marshaler = (*Priority)(nil)
220 +)
221
222 // OptionalDuration wraps time.Duration to provide json serialization and deserialization.
223 //
218 -// NOTE: the zero value encodes to JSON nill
224 +// NOTE: the zero value encodes to JSON nill.
225 type OptionalDuration struct {
226 value *time.Duration
227 }
228
223 -// NewOptionalDuration returns an OptionalDuration from a string
229 +// NewOptionalDuration returns an OptionalDuration from a string.
230 func NewOptionalDuration(d time.Duration) *OptionalDuration {
231 return &OptionalDuration{value: &d}
232 }
@@ -266,8 +272,10 @@ func (d OptionalDuration) String() string {
272 return d.value.String()
273 }
274
269 -var _ json.Unmarshaler = (*OptionalDuration)(nil)
270 -var _ json.Marshaler = (*OptionalDuration)(nil)
275 +var (
276 + _ json.Unmarshaler = (*OptionalDuration)(nil)
277 + _ json.Marshaler = (*OptionalDuration)(nil)
278 +)
279
280 type Duration struct {
281 time.Duration
@@ -298,17 +306,19 @@ func (d *Duration) UnmarshalJSON(b []byte) error {
306 }
307 }
308
301 -var _ json.Unmarshaler = (*Duration)(nil)
302 -var _ json.Marshaler = (*Duration)(nil)
309 +var (
310 + _ json.Unmarshaler = (*Duration)(nil)
311 + _ json.Marshaler = (*Duration)(nil)
312 +)
313
314 // OptionalInteger represents an integer that has a default value
315 //
306 -// When encoded in json, Default is encoded as "null"
316 +// When encoded in json, Default is encoded as "null".
317 type OptionalInteger struct {
318 value *int64
319 }
320
311 -// NewOptionalInteger returns an OptionalInteger from a int64
321 +// NewOptionalInteger returns an OptionalInteger from a int64.
322 func NewOptionalInteger(v int64) *OptionalInteger {
323 return &OptionalInteger{value: &v}
324 }
@@ -321,7 +331,7 @@ func (p *OptionalInteger) WithDefault(defaultValue int64) (value int64) {
331 return *p.value
332 }
333
324 -// IsDefault returns if this is a default optional integer
334 +// IsDefault returns if this is a default optional integer.
335 func (p *OptionalInteger) IsDefault() bool {
336 return p == nil || p.value == nil
337 }
@@ -355,17 +365,19 @@ func (p OptionalInteger) String() string {
365 return fmt.Sprintf("%d", *p.value)
366 }
367
358 -var _ json.Unmarshaler = (*OptionalInteger)(nil)
359 -var _ json.Marshaler = (*OptionalInteger)(nil)
368 +var (
369 + _ json.Unmarshaler = (*OptionalInteger)(nil)
370 + _ json.Marshaler = (*OptionalInteger)(nil)
371 +)
372
373 // OptionalString represents a string that has a default value
374 //
363 -// When encoded in json, Default is encoded as "null"
375 +// When encoded in json, Default is encoded as "null".
376 type OptionalString struct {
377 value *string
378 }
379
368 -// NewOptionalString returns an OptionalString from a string
380 +// NewOptionalString returns an OptionalString from a string.
381 func NewOptionalString(s string) *OptionalString {
382 return &OptionalString{value: &s}
383 }
@@ -378,7 +390,7 @@ func (p *OptionalString) WithDefault(defaultValue string) (value string) {
390 return *p.value
391 }
392
381 -// IsDefault returns if this is a default optional integer
393 +// IsDefault returns if this is a default optional integer.
394 func (p *OptionalString) IsDefault() bool {
395 return p == nil || p.value == nil
396 }
@@ -412,8 +424,10 @@ func (p OptionalString) String() string {
424 return *p.value
425 }
426
415 -var _ json.Unmarshaler = (*OptionalInteger)(nil)
416 -var _ json.Marshaler = (*OptionalInteger)(nil)
427 +var (
428 + _ json.Unmarshaler = (*OptionalInteger)(nil)
429 + _ json.Marshaler = (*OptionalInteger)(nil)
430 +)
431
432 type swarmLimits doNotUse
433
config/types_test.go
-3
@@ -129,7 +129,6 @@ func TestOneStrings(t *testing.T) {
129 out, err := json.Marshal(Strings{"one"})
130 if err != nil {
131 t.Fatal(err)
132 -
132 }
133 expected := "\"one\""
134 if string(out) != expected {
@@ -141,7 +140,6 @@ func TestNoStrings(t *testing.T) {
140 out, err := json.Marshal(Strings{})
141 if err != nil {
142 t.Fatal(err)
144 -
143 }
144 expected := "null"
145 if string(out) != expected {
@@ -153,7 +151,6 @@ func TestManyStrings(t *testing.T) {
151 out, err := json.Marshal(Strings{"one", "two"})
152 if err != nil {
153 t.Fatal(err)
156 -
154 }
155 expected := "[\"one\",\"two\"]"
156 if string(out) != expected {
core/bootstrap/bootstrap.go
-2
@@ -85,7 +85,6 @@ func BootstrapConfigWithPeers(pis []peer.AddrInfo) BootstrapConfig {
85 // connections to well-known bootstrap peers. It also kicks off subsystem
86 // bootstrapping (i.e. routing).
87 func Bootstrap(id peer.ID, host host.Host, rt routing.Routing, cfg BootstrapConfig) (io.Closer, error) {
88 -
88 // make a signal to wait for one bootstrap round to complete.
89 doneWithRound := make(chan struct{})
90
@@ -219,7 +218,6 @@ func saveConnectedPeersAsTemporaryBootstrap(ctx context.Context, host host.Host,
218 // Peers can be original bootstrap or temporary ones (drawn from a list of
219 // persisted previously connected peers).
220 func bootstrapRound(ctx context.Context, host host.Host, cfg BootstrapConfig) error {
222 -
221 ctx, cancel := context.WithTimeout(ctx, cfg.ConnectionTimeout)
222 defer cancel()
223 id := host.ID()
core/commands/bootstrap.go
+1 -3
@@ -374,9 +374,7 @@ func bootstrapRemove(r repo.Repo, cfg *config.Config, toRemove []string) ([]stri
374 removed = append(removed, p)
375 continue
376 }
377 - var (
378 - keptAddrs, removedAddrs []ma.Multiaddr
379 - )
377 + var keptAddrs, removedAddrs []ma.Multiaddr
378 // remove specific addresses
379 filter:
380 for _, addr := range p.Addrs {
core/commands/cmdenv/cidbase.go
+4 -2
@@ -10,8 +10,10 @@ import (
10 mbase "github.com/multiformats/go-multibase"
11 )
12
13 -var OptionCidBase = cmds.StringOption("cid-base", "Multibase encoding used for version 1 CIDs in output.")
14 -var OptionUpgradeCidV0InOutput = cmds.BoolOption("upgrade-cidv0-in-output", "Upgrade version 0 to version 1 CIDs in output.")
13 +var (
14 + OptionCidBase = cmds.StringOption("cid-base", "Multibase encoding used for version 1 CIDs in output.")
15 + OptionUpgradeCidV0InOutput = cmds.BoolOption("upgrade-cidv0-in-output", "Upgrade version 0 to version 1 CIDs in output.")
16 +)
17
18 // GetCidEncoder processes the `cid-base` and `output-cidv1` options and
19 // returns a encoder to use based on those parameters.
core/commands/cmdutils/utils.go
-1
@@ -47,5 +47,4 @@ func CheckBlockSize(req *cmds.Request, size uint64) error {
47 return fmt.Errorf("produced block is over 1MiB: big blocks can't be exchanged with other peers. consider using UnixFS for automatic chunking of bigger files, or pass --allow-big-block to override")
48 }
49 return nil
50 -
50 }
core/commands/commands_test.go
+1
@@ -71,6 +71,7 @@ func TestROCommands(t *testing.T) {
71 }
72 }
73 }
74 +
75 func TestCommands(t *testing.T) {
76 list := []string{
77 "/add",
core/commands/completion.go
-1
@@ -208,7 +208,6 @@ complete -c ipfs --keep-order --no-files
208
209 {{ template "command" . }}
210 `))
211 -
211 }
212
213 // writeBashCompletions generates a bash completion script for the given command tree.
core/commands/config.go
-1
@@ -581,5 +581,4 @@ func getRemotePinningServices(r repo.Repo) (map[string]config.RemotePinningServi
581 }
582 }
583 return oldServices, nil
584 -
584 }
core/commands/config_test.go
-1
@@ -12,6 +12,5 @@ func TestScrubMapInternalDelete(t *testing.T) {
12 }
13 if len(m) != 0 {
14 t.Errorf("expecting an empty map, got a non-empty map")
15 -
15 }
16 }
core/commands/dag/dag.go
+5 -4
@@ -13,9 +13,9 @@ import (
13 cid "github.com/ipfs/go-cid"
14 cidenc "github.com/ipfs/go-cidutil/cidenc"
15 cmds "github.com/ipfs/go-ipfs-cmds"
16 - //gipfree "github.com/ipld/go-ipld-prime/impl/free"
17 - //gipselector "github.com/ipld/go-ipld-prime/traversal/selector"
18 - //gipselectorbuilder "github.com/ipld/go-ipld-prime/traversal/selector/builder"
16 + // gipfree "github.com/ipld/go-ipld-prime/impl/free"
17 + // gipselector "github.com/ipld/go-ipld-prime/traversal/selector"
18 + // gipselectorbuilder "github.com/ipld/go-ipld-prime/traversal/selector/builder"
19 )
20
21 const (
@@ -209,7 +209,6 @@ Specification of CAR formats: https://ipld.io/specs/transport/car/
209 Run: dagImport,
210 Encoders: cmds.EncoderMap{
211 cmds.Text: cmds.MakeTypedEncoder(func(req *cmds.Request, w io.Writer, event *CarImportOutput) error {
212 -
212 silent, _ := req.Options[silentOptionName].(bool)
213 if silent {
214 return nil
@@ -343,9 +342,11 @@ func (s *DagStatSummary) String() string {
342 func (s *DagStatSummary) incrementTotalSize(size uint64) {
343 s.TotalSize += size
344 }
345 +
346 func (s *DagStatSummary) incrementRedundantSize(size uint64) {
347 s.redundantSize += size
348 }
349 +
350 func (s *DagStatSummary) appendStats(stats *DagStat) {
351 s.DagStatsArray = append(s.DagStatsArray, stats)
352 }
core/commands/dag/export.go
-1
@@ -79,7 +79,6 @@ func dagExport(req *cmds.Request, res cmds.ResponseEmitter, env cmds.Environment
79 }
80
81 func finishCLIExport(res cmds.Response, re cmds.ResponseEmitter) error {
82 -
82 var showProgress bool
83 val, specified := res.Request().Options[progressOptionName]
84 if !specified {
core/commands/external.go
+1 -1
@@ -41,7 +41,7 @@ func ExternalBinary(instructions string) *cmds.Command {
41 cmd := exec.Command(binname, req.Arguments...)
42
43 // TODO: make commands lib be able to pass stdin through daemon
44 - //cmd.Stdin = req.Stdin()
44 + // cmd.Stdin = req.Stdin()
45 cmd.Stdin = io.LimitReader(nil, 0)
46 cmd.Stdout = w
47 cmd.Stderr = w
core/commands/files.go
+4 -5
@@ -88,8 +88,10 @@ const (
88 filesHashOptionName = "hash"
89 )
90
91 -var cidVersionOption = cmds.IntOption(filesCidVersionOptionName, "cid-ver", "Cid version to use. (experimental)")
92 -var hashOption = cmds.StringOption(filesHashOptionName, "Hash function to use. Will set Cid version to 1 if used. (experimental)")
91 +var (
92 + cidVersionOption = cmds.IntOption(filesCidVersionOptionName, "cid-ver", "Cid version to use. (experimental)")
93 + hashOption = cmds.StringOption(filesHashOptionName, "Hash function to use. Will set Cid version to 1 if used. (experimental)")
94 +)
95
96 var errFormat = errors.New("format was set by multiple options. Only one format option is allowed")
97
@@ -131,7 +133,6 @@ var filesStatCmd = &cmds.Command{
133 cmds.BoolOption(filesWithLocalOptionName, "Compute the amount of the dag that is local, and if possible the total size"),
134 },
135 Run: func(req *cmds.Request, res cmds.ResponseEmitter, env cmds.Environment) error {
134 -
136 _, err := statGetFormatOptions(req)
137 if err != nil {
138 return cmds.Errorf(cmds.ErrClient, err.Error())
@@ -225,7 +226,6 @@ func moreThanOne(a, b, c bool) bool {
226 }
227
228 func statGetFormatOptions(req *cmds.Request) (string, error) {
228 -
229 hash, _ := req.Options[filesHashOptionName].(bool)
230 size, _ := req.Options[filesSizeOptionName].(bool)
231 format, _ := req.Options[filesFormatOptionName].(string)
@@ -307,7 +307,6 @@ func walkBlock(ctx context.Context, dagserv ipld.DAGService, nd ipld.Node) (bool
307 }
308
309 childLocal, childLocalSize, err := walkBlock(ctx, dagserv, child)
310 -
310 if err != nil {
311 return local, sizeLocal, err
312 }
core/commands/keystore.go
-3
@@ -118,7 +118,6 @@ var keyGenCmd = &cmds.Command{
118 }
119
120 key, err := api.Key().Generate(req.Context, name, opts...)
121 -
121 if err != nil {
122 return err
123 }
@@ -211,7 +210,6 @@ elsewhere. For example, using openssl to get a PEM with public key:
210 stdKey, err := crypto.PrivKeyToStdKey(sk)
211 if err != nil {
212 return fmt.Errorf("converting libp2p private key to std Go key: %w", err)
214 -
213 }
214 // For some reason the ed25519.PrivateKey does not use pointer
215 // receivers, so we need to convert it for MarshalPKCS8PrivateKey.
@@ -375,7 +373,6 @@ The PEM format allows for key generation outside of the IPFS node:
373 sk, _, err = crypto.KeyPairFromStdKey(stdKey)
374 if err != nil {
375 return fmt.Errorf("converting std Go key to libp2p key: %w", err)
378 -
376 }
377 case keyFormatLibp2pCleartextOption:
378 sk, err = crypto.UnmarshalPrivateKey(data)
core/commands/name/publish.go
+1 -3
@@ -15,9 +15,7 @@ import (
15 ke "github.com/ipfs/kubo/core/commands/keyencode"
16 )
17
18 -var (
19 - errAllowOffline = errors.New("can't publish while offline: pass `--allow-offline` to override")
20 -)
18 +var errAllowOffline = errors.New("can't publish while offline: pass `--allow-offline` to override")
19
20 const (
21 ipfsPathOptionName = "ipfs-path"
core/commands/p2p.go
+1 -3
@@ -370,9 +370,7 @@ var p2pCloseCmd = &cmds.Command{
370
371 proto := protocol.ID(protoOpt)
372
373 - var (
374 - target, listen ma.Multiaddr
375 - )
373 + var target, listen ma.Multiaddr
374
375 if l {
376 listen, err = ma.NewMultiaddr(listenOpt)
core/commands/pin/remotepin.go
+12 -10
@@ -54,16 +54,18 @@ var remotePinServiceCmd = &cmds.Command{
54 },
55 }
56
57 -const pinNameOptionName = "name"
58 -const pinCIDsOptionName = "cid"
59 -const pinStatusOptionName = "status"
60 -const pinServiceNameOptionName = "service"
61 -const pinServiceNameArgName = pinServiceNameOptionName
62 -const pinServiceEndpointArgName = "endpoint"
63 -const pinServiceKeyArgName = "key"
64 -const pinServiceStatOptionName = "stat"
65 -const pinBackgroundOptionName = "background"
66 -const pinForceOptionName = "force"
57 +const (
58 + pinNameOptionName = "name"
59 + pinCIDsOptionName = "cid"
60 + pinStatusOptionName = "status"
61 + pinServiceNameOptionName = "service"
62 + pinServiceNameArgName = pinServiceNameOptionName
63 + pinServiceEndpointArgName = "endpoint"
64 + pinServiceKeyArgName = "key"
65 + pinServiceStatOptionName = "stat"
66 + pinBackgroundOptionName = "background"
67 + pinForceOptionName = "force"
68 +)
69
70 type RemotePinOutput struct {
71 Status string
core/commands/pin/remotepin_test.go
-1
@@ -63,5 +63,4 @@ func TestNormalizeEndpoint(t *testing.T) {
63 continue
64 }
65 }
66 -
66 }
core/commands/root.go
+4 -2
@@ -16,8 +16,10 @@ import (
16
17 var log = logging.Logger("core/commands")
18
19 -var ErrNotOnline = errors.New("this command must be run in online mode. Try running 'ipfs daemon' first")
20 -var ErrSelfUnsupported = errors.New("finding your own node in the DHT is currently not supported")
19 +var (
20 + ErrNotOnline = errors.New("this command must be run in online mode. Try running 'ipfs daemon' first")
21 + ErrSelfUnsupported = errors.New("finding your own node in the DHT is currently not supported")
22 +)
23
24 const (
25 RepoDirOption = "repo-dir"
core/commands/routing.go
+5 -6
@@ -21,9 +21,7 @@ import (
21 routing "github.com/libp2p/go-libp2p/core/routing"
22 )
23
24 -var (
25 - errAllowOffline = errors.New("can't put while offline: pass `--allow-offline` to override")
26 -)
24 +var errAllowOffline = errors.New("can't put while offline: pass `--allow-offline` to override")
25
26 const (
27 dhtVerboseOptionName = "verbose"
@@ -75,7 +73,6 @@ var findProvidersRoutingCmd = &cmds.Command{
73 }
74
75 c, err := cid.Parse(req.Arguments[0])
78 -
76 if err != nil {
77 return err
78 }
@@ -495,8 +492,10 @@ identified by QmFoo.
492 Type: routing.QueryEvent{},
493 }
494
498 -type printFunc func(obj *routing.QueryEvent, out io.Writer, verbose bool) error
499 -type pfuncMap map[routing.QueryEventType]printFunc
495 +type (
496 + printFunc func(obj *routing.QueryEvent, out io.Writer, verbose bool) error
497 + pfuncMap map[routing.QueryEventType]printFunc
498 +)
499
500 func printEvent(obj *routing.QueryEvent, out io.Writer, verbose bool, override pfuncMap) error {
501 if verbose {
core/commands/swarm.go
+2 -1
@@ -345,7 +345,8 @@ var swarmResourcesCmd = &cmds.Command{
345 Get a summary of all resources accounted for by the libp2p Resource Manager.
346 This includes the limits and the usage against those limits.
347 This can output a human readable table and JSON encoding.
348 -`},
348 +`,
349 + },
350 Run: func(req *cmds.Request, res cmds.ResponseEmitter, env cmds.Environment) error {
351 node, err := cmdenv.GetNode(env)
352 if err != nil {
core/core.go
-1
@@ -64,7 +64,6 @@ var log = logging.Logger("core")
64
65 // IpfsNode is IPFS Core module. It represents an IPFS instance.
66 type IpfsNode struct {
67 -
67 // Self
68 Identity peer.ID // the local node's identity
69
core/coreapi/swarm.go
+4 -2
@@ -29,8 +29,10 @@ type connInfo struct {
29 }
30
31 // tag used in the connection manager when explicitly connecting to a peer.
32 -const connectionManagerTag = "user-connect"
33 -const connectionManagerWeight = 100
32 +const (
33 + connectionManagerTag = "user-connect"
34 + connectionManagerWeight = 100
35 +)
36
37 func (api *SwarmAPI) Connect(ctx context.Context, pi peer.AddrInfo) error {
38 ctx, span := tracing.Span(ctx, "CoreAPI.SwarmAPI", "Connect", trace.WithAttributes(attribute.String("peerid", pi.ID.String())))
core/coreapi/unixfs.go
+7 -6
@@ -32,8 +32,10 @@ import (
32
33 type UnixfsAPI CoreAPI
34
35 -var nilNode *core.IpfsNode
36 -var once sync.Once
35 +var (
36 + nilNode *core.IpfsNode
37 + once sync.Once
38 +)
39
40 func getOrCreateNilNode() (*core.IpfsNode, error) {
41 once.Do(func() {
@@ -41,7 +43,7 @@ func getOrCreateNilNode() (*core.IpfsNode, error) {
43 return
44 }
45 node, err := core.NewNode(context.Background(), &core.BuildCfg{
44 - //TODO: need this to be true or all files
46 + // TODO: need this to be true or all files
47 // hashed will be stored in memory!
48 NilRepo: true,
49 })
@@ -253,7 +255,6 @@ func (api *UnixfsAPI) processLink(ctx context.Context, linkres ft.LinkResult, se
255 defer span.End()
256 if linkres.Link != nil {
257 span.SetAttributes(attribute.String("linkname", linkres.Link.Name), attribute.String("cid", linkres.Link.Cid.String()))
256 -
258 }
259
260 if linkres.Err != nil {
@@ -314,7 +315,7 @@ func (api *UnixfsAPI) lsFromLinksAsync(ctx context.Context, dir uio.Directory, s
315 defer close(out)
316 for l := range dir.EnumLinksAsync(ctx) {
317 select {
317 - case out <- api.processLink(ctx, l, settings): //TODO: perf: processing can be done in background and in parallel
318 + case out <- api.processLink(ctx, l, settings): // TODO: perf: processing can be done in background and in parallel
319 case <-ctx.Done():
320 return
321 }
@@ -329,7 +330,7 @@ func (api *UnixfsAPI) lsFromLinks(ctx context.Context, ndlinks []*ipld.Link, set
330 for _, l := range ndlinks {
331 lr := ft.LinkResult{Link: &ipld.Link{Name: l.Name, Size: l.Size, Cid: l.Cid}}
332
332 - links <- api.processLink(ctx, lr, settings) //TODO: can be parallel if settings.Async
333 + links <- api.processLink(ctx, lr, settings) // TODO: can be parallel if settings.Async
334 }
335 close(links)
336 return links, nil
core/corehttp/commands.go
+5 -7
@@ -20,12 +20,11 @@ import (
20 "go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp"
21 )
22
23 -var (
24 - errAPIVersionMismatch = errors.New("api version mismatch")
25 -)
23 +var errAPIVersionMismatch = errors.New("api version mismatch")
24
27 -const originEnvKey = "API_ORIGIN"
28 -const originEnvKeyDeprecate = `You are using the ` + originEnvKey + `ENV Variable.
25 +const (
26 + originEnvKey = "API_ORIGIN"
27 + originEnvKeyDeprecate = `You are using the ` + originEnvKey + `ENV Variable.
28 This functionality is deprecated, and will be removed in future versions.
29 Instead, try either adding headers to the config, or passing them via
30 cli arguments:
@@ -33,6 +32,7 @@ cli arguments:
32 ipfs config API.HTTPHeaders --json '{"Access-Control-Allow-Origin": ["*"]}'
33 ipfs daemon
34 `
35 +)
36
37 // APIPath is the path at which the API is mounted.
38 const APIPath = "/api/v0"
@@ -100,7 +100,6 @@ func addCORSDefaults(c *cmdsHttp.ServerConfig) {
100 }
101
102 func patchCORSVars(c *cmdsHttp.ServerConfig, addr net.Addr) {
103 -
103 // we have to grab the port from an addr, which may be an ip6 addr.
104 // TODO: this should take multiaddrs and derive port from there.
105 port := ""
@@ -125,7 +124,6 @@ func patchCORSVars(c *cmdsHttp.ServerConfig, addr net.Addr) {
124
125 func commandsOption(cctx oldcmds.Context, command *cmds.Command, allowGet bool) ServeOption {
126 return func(n *core.IpfsNode, l net.Listener, mux *http.ServeMux) (*http.ServeMux, error) {
128 -
127 cfg := cmdsHttp.NewServerConfig()
128 cfg.AllowGet = allowGet
129 corsAllowedMethods := []string{http.MethodPost}
core/corehttp/metrics.go
+5 -7
@@ -151,13 +151,11 @@ func MetricsCollectionOption(handlerName string) ServeOption {
151 }
152 }
153
154 -var (
155 - peersTotalMetric = prometheus.NewDesc(
156 - prometheus.BuildFQName("ipfs", "p2p", "peers_total"),
157 - "Number of connected peers",
158 - []string{"transport"},
159 - nil,
160 - )
154 +var peersTotalMetric = prometheus.NewDesc(
155 + prometheus.BuildFQName("ipfs", "p2p", "peers_total"),
156 + "Number of connected peers",
157 + []string{"transport"},
158 + nil,
159 )
160
161 type IpfsNodeCollector struct {
core/coreunix/add_test.go
-2
@@ -179,11 +179,9 @@ func TestAddGCLive(t *testing.T) {
179 defer close(addDone)
180 defer close(out)
181 _, err := adder.AddAllAndPin(context.Background(), slf)
182 -
182 if err != nil {
183 t.Error(err)
184 }
186 -
185 }()
186
187 addedHashes := make(map[string]struct{})
core/node/groups.go
-1
@@ -248,7 +248,6 @@ var IPNS = fx.Options(
248
249 // Online groups online-only units
250 func Online(bcfg *BuildCfg, cfg *config.Config, userResourceOverrides rcmgr.PartialLimitConfig) fx.Option {
251 -
251 // Namesys params
252
253 ipnsCacheSize := cfg.Ipns.ResolveCacheSize
core/node/helpers/helpers.go
+1
@@ -2,6 +2,7 @@ package helpers
2
3 import (
4 "context"
5 +
6 "go.uber.org/fx"
7 )
8
core/node/libp2p/rcmgr.go
+2 -1
@@ -118,7 +118,8 @@ filled in with autocomputed defaults.`)
118 lc.Append(fx.Hook{
119 OnStop: func(_ context.Context) error {
120 return manager.Close()
121 - }})
121 + },
122 + })
123
124 return manager, opts, nil
125 }
core/node/libp2p/rcmgr_logging.go
+28 -2
@@ -31,8 +31,10 @@ type loggingScope struct {
31 countErrs func(error)
32 }
33
34 -var _ network.ResourceManager = (*loggingResourceManager)(nil)
35 -var _ rcmgr.ResourceManagerState = (*loggingResourceManager)(nil)
34 +var (
35 + _ network.ResourceManager = (*loggingResourceManager)(nil)
36 + _ rcmgr.ResourceManagerState = (*loggingResourceManager)(nil)
37 +)
38
39 func (n *loggingResourceManager) start(ctx context.Context) {
40 logInterval := n.logInterval
@@ -85,36 +87,43 @@ func (n *loggingResourceManager) countErrs(err error) {
87 func (n *loggingResourceManager) ViewSystem(f func(network.ResourceScope) error) error {
88 return n.delegate.ViewSystem(f)
89 }
90 +
91 func (n *loggingResourceManager) ViewTransient(f func(network.ResourceScope) error) error {
92 return n.delegate.ViewTransient(func(s network.ResourceScope) error {
93 return f(&loggingScope{logger: n.logger, delegate: s, countErrs: n.countErrs})
94 })
95 }
96 +
97 func (n *loggingResourceManager) ViewService(svc string, f func(network.ServiceScope) error) error {
98 return n.delegate.ViewService(svc, func(s network.ServiceScope) error {
99 return f(&loggingScope{logger: n.logger, delegate: s, countErrs: n.countErrs})
100 })
101 }
102 +
103 func (n *loggingResourceManager) ViewProtocol(p protocol.ID, f func(network.ProtocolScope) error) error {
104 return n.delegate.ViewProtocol(p, func(s network.ProtocolScope) error {
105 return f(&loggingScope{logger: n.logger, delegate: s, countErrs: n.countErrs})
106 })
107 }
108 +
109 func (n *loggingResourceManager) ViewPeer(p peer.ID, f func(network.PeerScope) error) error {
110 return n.delegate.ViewPeer(p, func(s network.PeerScope) error {
111 return f(&loggingScope{logger: n.logger, delegate: s, countErrs: n.countErrs})
112 })
113 }
114 +
115 func (n *loggingResourceManager) OpenConnection(dir network.Direction, usefd bool, remote ma.Multiaddr) (network.ConnManagementScope, error) {
116 connMgmtScope, err := n.delegate.OpenConnection(dir, usefd, remote)
117 n.countErrs(err)
118 return connMgmtScope, err
119 }
120 +
121 func (n *loggingResourceManager) OpenStream(p peer.ID, dir network.Direction) (network.StreamManagementScope, error) {
122 connMgmtScope, err := n.delegate.OpenStream(p, dir)
123 n.countErrs(err)
124 return connMgmtScope, err
125 }
126 +
127 func (n *loggingResourceManager) Close() error {
128 return n.delegate.Close()
129 }
@@ -127,6 +136,7 @@ func (n *loggingResourceManager) ListServices() []string {
136
137 return rapi.ListServices()
138 }
139 +
140 func (n *loggingResourceManager) ListProtocols() []protocol.ID {
141 rapi, ok := n.delegate.(rcmgr.ResourceManagerState)
142 if !ok {
@@ -135,6 +145,7 @@ func (n *loggingResourceManager) ListProtocols() []protocol.ID {
145
146 return rapi.ListProtocols()
147 }
148 +
149 func (n *loggingResourceManager) ListPeers() []peer.ID {
150 rapi, ok := n.delegate.(rcmgr.ResourceManagerState)
151 if !ok {
@@ -158,54 +169,69 @@ func (s *loggingScope) ReserveMemory(size int, prio uint8) error {
169 s.countErrs(err)
170 return err
171 }
172 +
173 func (s *loggingScope) ReleaseMemory(size int) {
174 s.delegate.ReleaseMemory(size)
175 }
176 +
177 func (s *loggingScope) Stat() network.ScopeStat {
178 return s.delegate.Stat()
179 }
180 +
181 func (s *loggingScope) BeginSpan() (network.ResourceScopeSpan, error) {
182 return s.delegate.BeginSpan()
183 }
184 +
185 func (s *loggingScope) Done() {
186 s.delegate.(network.ResourceScopeSpan).Done()
187 }
188 +
189 func (s *loggingScope) Name() string {
190 return s.delegate.(network.ServiceScope).Name()
191 }
192 +
193 func (s *loggingScope) Protocol() protocol.ID {
194 return s.delegate.(network.ProtocolScope).Protocol()
195 }
196 +
197 func (s *loggingScope) Peer() peer.ID {
198 return s.delegate.(network.PeerScope).Peer()
199 }
200 +
201 func (s *loggingScope) PeerScope() network.PeerScope {
202 return s.delegate.(network.PeerScope)
203 }
204 +
205 func (s *loggingScope) SetPeer(p peer.ID) error {
206 err := s.delegate.(network.ConnManagementScope).SetPeer(p)
207 s.countErrs(err)
208 return err
209 }
210 +
211 func (s *loggingScope) ProtocolScope() network.ProtocolScope {
212 return s.delegate.(network.ProtocolScope)
213 }
214 +
215 func (s *loggingScope) SetProtocol(proto protocol.ID) error {
216 err := s.delegate.(network.StreamManagementScope).SetProtocol(proto)
217 s.countErrs(err)
218 return err
219 }
220 +
221 func (s *loggingScope) ServiceScope() network.ServiceScope {
222 return s.delegate.(network.ServiceScope)
223 }
224 +
225 func (s *loggingScope) SetService(srv string) error {
226 err := s.delegate.(network.StreamManagementScope).SetService(srv)
227 s.countErrs(err)
228 return err
229 }
230 +
231 func (s *loggingScope) Limit() rcmgr.Limit {
232 return s.delegate.(rcmgr.ResourceScopeLimiter).Limit()
233 }
234 +
235 func (s *loggingScope) SetLimit(limit rcmgr.Limit) {
236 s.delegate.(rcmgr.ResourceScopeLimiter).SetLimit(limit)
237 }
core/node/libp2p/routing.go
-1
@@ -232,7 +232,6 @@ func PubsubRouter(mctx helpers.MetricsCtx, lc fx.Lifecycle, in p2pPSRoutingIn) (
232 in.Validator,
233 namesys.WithRebroadcastInterval(time.Minute),
234 )
235 -
235 if err != nil {
236 return p2pRouterOut{}, nil, err
237 }
core/node/libp2p/topicdiscovery.go
-1
@@ -21,7 +21,6 @@ func TopicDiscovery() interface{} {
21 baseDisc,
22 backoff.NewExponentialBackoff(minBackoff, maxBackoff, backoff.FullJitter, time.Second, 5.0, 0, rng),
23 )
24 -
24 if err != nil {
25 return nil, err
26 }
core/node/libp2p/transport.go
+2 -1
@@ -18,7 +18,8 @@ func Transports(tptConfig config.Transports) interface{} {
18 return func(pnet struct {
19 fx.In
20 Fprint PNetFingerprint `optional:"true"`
21 - }) (opts Libp2pOpts, err error) {
21 + },
22 + ) (opts Libp2pOpts, err error) {
23 privateNetworkEnabled := pnet.Fprint != nil
24
25 if tptConfig.Network.TCP.WithDefault(true) {
docs/examples/kubo-as-a-library/main.go
+2 -2
@@ -85,7 +85,7 @@ func createTempRepo() (string, error) {
85
86 /// ------ Spawning the node
87
88 -// Creates an IPFS node and returns its coreAPI
88 +// Creates an IPFS node and returns its coreAPI.
89 func createNode(ctx context.Context, repoPath string) (*core.IpfsNode, error) {
90 // Open the repo
91 repo, err := fsrepo.Open(repoPath)
@@ -107,7 +107,7 @@ func createNode(ctx context.Context, repoPath string) (*core.IpfsNode, error) {
107
108 var loadPluginsOnce sync.Once
109
110 -// Spawns a node to be used just for this run (i.e. creates a tmp repo)
110 +// Spawns a node to be used just for this run (i.e. creates a tmp repo).
111 func spawnEphemeral(ctx context.Context) (icore.CoreAPI, *core.IpfsNode, error) {
112 var onceErr error
113 loadPluginsOnce.Do(func() {
fuse/ipns/ipns_test.go
+9 -10
@@ -56,7 +56,7 @@ func writeFileOrFail(t *testing.T, size int, path string) []byte {
56
57 func writeFile(size int, path string) ([]byte, error) {
58 data := randBytes(size)
59 - err := os.WriteFile(path, data, 0666)
59 + err := os.WriteFile(path, data, 0o666)
60 return data, err
61 }
62
@@ -156,7 +156,7 @@ func TestIpnsLocalLink(t *testing.T) {
156 }
157 }
158
159 -// Test writing a file and reading it back
159 +// Test writing a file and reading it back.
160 func TestIpnsBasicIO(t *testing.T) {
161 if testing.Short() {
162 t.SkipNow()
@@ -187,7 +187,7 @@ func TestIpnsBasicIO(t *testing.T) {
187 }
188 }
189
190 -// Test to make sure file changes persist over mounts of ipns
190 +// Test to make sure file changes persist over mounts of ipns.
191 func TestFilePersistence(t *testing.T) {
192 if testing.Short() {
193 t.SkipNow()
@@ -250,7 +250,7 @@ func TestMultipleDirs(t *testing.T) {
250 mnt.Close()
251 }
252
253 -// Test to make sure the filesystem reports file sizes correctly
253 +// Test to make sure the filesystem reports file sizes correctly.
254 func TestFileSizeReporting(t *testing.T) {
255 if testing.Short() {
256 t.SkipNow()
@@ -271,7 +271,7 @@ func TestFileSizeReporting(t *testing.T) {
271 }
272 }
273
274 -// Test to make sure you can't create multiple entries with the same name
274 +// Test to make sure you can't create multiple entries with the same name.
275 func TestDoubleEntryFailure(t *testing.T) {
276 if testing.Short() {
277 t.SkipNow()
@@ -280,12 +280,12 @@ func TestDoubleEntryFailure(t *testing.T) {
280 defer mnt.Close()
281
282 dname := mnt.Dir + "/local/thisisadir"
283 - err := os.Mkdir(dname, 0777)
283 + err := os.Mkdir(dname, 0o777)
284 if err != nil {
285 t.Fatal(err)
286 }
287
288 - err = os.Mkdir(dname, 0777)
288 + err = os.Mkdir(dname, 0o777)
289 if err == nil {
290 t.Fatal("Should have gotten error one creating new directory.")
291 }
@@ -301,7 +301,7 @@ func TestAppendFile(t *testing.T) {
301 fname := mnt.Dir + "/local/file"
302 data := writeFileOrFail(t, 1300, fname)
303
304 - fi, err := os.OpenFile(fname, os.O_RDWR|os.O_APPEND, 0666)
304 + fi, err := os.OpenFile(fname, os.O_RDWR|os.O_APPEND, 0o666)
305 if err != nil {
306 t.Fatal(err)
307 }
@@ -463,9 +463,8 @@ func TestFSThrash(t *testing.T) {
463 }
464 }
465
466 -// Test writing a medium sized file one byte at a time
466 +// Test writing a medium sized file one byte at a time.
467 func TestMultiWrite(t *testing.T) {
468 -
468 if testing.Short() {
469 t.SkipNow()
470 }
fuse/ipns/ipns_unix.go
+13 -11
@@ -149,7 +149,7 @@ func CreateRoot(ctx context.Context, ipfs iface.CoreAPI, keys map[string]iface.K
149 // Attr returns file attributes.
150 func (r *Root) Attr(ctx context.Context, a *fuse.Attr) error {
151 log.Debug("Root Attr")
152 - a.Mode = os.ModeDir | 0111 // -rw+x
152 + a.Mode = os.ModeDir | 0o111 // -rw+x
153 return nil
154 }
155
@@ -212,7 +212,7 @@ func (r *Root) Forget() {
212 }
213
214 // ReadDirAll reads a particular directory. Will show locally available keys
215 -// as well as a symlink to the peerID key
215 +// as well as a symlink to the peerID key.
216 func (r *Root) ReadDirAll(ctx context.Context) ([]fuse.Dirent, error) {
217 log.Debug("Root ReadDirAll")
218
@@ -231,7 +231,7 @@ func (r *Root) ReadDirAll(ctx context.Context) ([]fuse.Dirent, error) {
231 return listing, nil
232 }
233
234 -// Directory is wrapper over an mfs directory to satisfy the fuse fs interface
234 +// Directory is wrapper over an mfs directory to satisfy the fuse fs interface.
235 type Directory struct {
236 dir *mfs.Directory
237 }
@@ -240,7 +240,7 @@ type FileNode struct {
240 fi *mfs.File
241 }
242
243 -// File is wrapper over an mfs file to satisfy the fuse fs interface
243 +// File is wrapper over an mfs file to satisfy the fuse fs interface.
244 type File struct {
245 fi mfs.FileDescriptor
246 }
@@ -248,7 +248,7 @@ type File struct {
248 // Attr returns the attributes of a given node.
249 func (d *Directory) Attr(ctx context.Context, a *fuse.Attr) error {
250 log.Debug("Directory Attr")
251 - a.Mode = os.ModeDir | 0555
251 + a.Mode = os.ModeDir | 0o555
252 a.Uid = uint32(os.Getuid())
253 a.Gid = uint32(os.Getgid())
254 return nil
@@ -262,7 +262,7 @@ func (fi *FileNode) Attr(ctx context.Context, a *fuse.Attr) error {
262 // In this case, the dag node in question may not be unixfs
263 return fmt.Errorf("fuse/ipns: failed to get file.Size(): %s", err)
264 }
265 - a.Mode = os.FileMode(0666)
265 + a.Mode = os.FileMode(0o666)
266 a.Size = uint64(size)
267 a.Uid = uint32(os.Getuid())
268 a.Gid = uint32(os.Getgid())
@@ -289,7 +289,7 @@ func (d *Directory) Lookup(ctx context.Context, name string) (fs.Node, error) {
289 }
290 }
291
292 -// ReadDirAll reads the link structure as directory entries
292 +// ReadDirAll reads the link structure as directory entries.
293 func (d *Directory) ReadDirAll(ctx context.Context) ([]fuse.Dirent, error) {
294 listing, err := d.dir.List(ctx)
295 if err != nil {
@@ -491,7 +491,7 @@ func (d *Directory) Remove(ctx context.Context, req *fuse.RemoveRequest) error {
491 return nil
492 }
493
494 -// Rename implements NodeRenamer
494 +// Rename implements NodeRenamer.
495 func (d *Directory) Rename(ctx context.Context, req *fuse.RenameRequest, newDir fs.Node) error {
496 cur, err := d.dir.Child(req.OldName)
497 if err != nil {
@@ -531,7 +531,7 @@ func min(a, b int) int {
531 return b
532 }
533
534 -// to check that out Node implements all the interfaces we want
534 +// to check that out Node implements all the interfaces we want.
535 type ipnsRoot interface {
536 fs.Node
537 fs.HandleReadDirAller
@@ -565,5 +565,7 @@ type ipnsFileNode interface {
565 fs.NodeOpener
566 }
567
568 -var _ ipnsFileNode = (*FileNode)(nil)
569 -var _ ipnsFile = (*File)(nil)
568 +var (
569 + _ ipnsFileNode = (*FileNode)(nil)
570 + _ ipnsFile = (*File)(nil)
571 +)
fuse/ipns/link_unix.go
+1 -1
@@ -17,7 +17,7 @@ type Link struct {
17
18 func (l *Link) Attr(ctx context.Context, a *fuse.Attr) error {
19 log.Debug("Link attr.")
20 - a.Mode = os.ModeSymlink | 0555
20 + a.Mode = os.ModeSymlink | 0o555
21 return nil
22 }
23
fuse/mount/fuse.go
+2 -2
@@ -16,7 +16,7 @@ import (
16
17 var ErrNotMounted = errors.New("not mounted")
18
19 -// mount implements go-ipfs/fuse/mount
19 +// mount implements go-ipfs/fuse/mount.
20 type mount struct {
21 mpoint string
22 filesys fs.FS
@@ -34,7 +34,7 @@ func NewMount(p goprocess.Process, fsys fs.FS, mountpoint string, allowOther boo
34 var conn *fuse.Conn
35 var err error
36
37 - var mountOpts = []fuse.MountOption{
37 + mountOpts := []fuse.MountOption{
38 fuse.MaxReadahead(64 * 1024 * 1024),
39 fuse.AsyncRead(),
40 }
fuse/mount/mount.go
+2 -2
@@ -16,7 +16,7 @@ var log = logging.Logger("mount")
16
17 var MountTimeout = time.Second * 5
18
19 -// Mount represents a filesystem mount
19 +// Mount represents a filesystem mount.
20 type Mount interface {
21 // MountPoint is the path at which this mount is mounted
22 MountPoint() string
@@ -65,7 +65,7 @@ func ForceUnmount(m Mount) error {
65 }
66
67 // UnmountCmd creates an exec.Cmd that is GOOS-specific
68 -// for unmount a FUSE mount
68 +// for unmount a FUSE mount.
69 func UnmountCmd(point string) (*exec.Cmd, error) {
70 switch runtime.GOOS {
71 case "darwin":
fuse/node/mount_darwin.go
+1 -1
@@ -25,7 +25,7 @@ func init() {
25 // skip fuse checks.
26 const dontCheckOSXFUSEConfigKey = "DontCheckOSXFUSE"
27
28 -// fuseVersionPkg is the go pkg url for fuse-version
28 +// fuseVersionPkg is the go pkg url for fuse-version.
29 const fuseVersionPkg = "github.com/jbenet/go-fuse-version/fuse-version"
30
31 // errStrFuseRequired is returned when we're sure the user does not have fuse.
fuse/node/mount_test.go
+1 -1
@@ -32,7 +32,7 @@ func mkdir(t *testing.T, path string) {
32 }
33 }
34
35 -// Test externally unmounting, then trying to unmount in code
35 +// Test externally unmounting, then trying to unmount in code.
36 func TestExternalUnmount(t *testing.T) {
37 if testing.Short() {
38 t.SkipNow()
fuse/node/mount_unix.go
+3 -3
@@ -19,14 +19,14 @@ import (
19
20 var log = logging.Logger("node")
21
22 -// fuseNoDirectory used to check the returning fuse error
22 +// fuseNoDirectory used to check the returning fuse error.
23 const fuseNoDirectory = "fusermount: failed to access mountpoint"
24
25 -// fuseExitStatus1 used to check the returning fuse error
25 +// fuseExitStatus1 used to check the returning fuse error.
26 const fuseExitStatus1 = "fusermount: exit status 1"
27
28 // platformFuseChecks can get overridden by arch-specific files
29 -// to run fuse checks (like checking the OSXFUSE version)
29 +// to run fuse checks (like checking the OSXFUSE version).
30 var platformFuseChecks = func(*core.IpfsNode) error {
31 return nil
32 }
fuse/readonly/ipfs_test.go
+6 -6
@@ -79,7 +79,7 @@ func setupIpfsTest(t *testing.T, node *core.IpfsNode) (*core.IpfsNode, *fstest.M
79 return node, mnt
80 }
81
82 -// Test writing an object and reading it back through fuse
82 +// Test writing an object and reading it back through fuse.
83 func TestIpfsBasicRead(t *testing.T) {
84 if testing.Short() {
85 t.SkipNow()
@@ -122,7 +122,7 @@ func getPaths(t *testing.T, ipfs *core.IpfsNode, name string, n *dag.ProtoNode)
122 return out
123 }
124
125 -// Perform a large number of concurrent reads to stress the system
125 +// Perform a large number of concurrent reads to stress the system.
126 func TestIpfsStressRead(t *testing.T) {
127 if testing.Short() {
128 t.SkipNow()
@@ -194,8 +194,8 @@ func TestIpfsStressRead(t *testing.T) {
194 errs <- err
195 }
196
197 - //nd.Context() is never closed which leads to
198 - //hitting 8128 goroutine limit in go test -race mode
197 + // nd.Context() is never closed which leads to
198 + // hitting 8128 goroutine limit in go test -race mode
199 ctx, cancelFunc := context.WithCancel(context.Background())
200
201 read, err := api.Unixfs().Get(ctx, item)
@@ -229,7 +229,7 @@ func TestIpfsStressRead(t *testing.T) {
229 }
230 }
231
232 -// Test writing a file and reading it back
232 +// Test writing a file and reading it back.
233 func TestIpfsBasicDirRead(t *testing.T) {
234 if testing.Short() {
235 t.SkipNow()
@@ -280,7 +280,7 @@ func TestIpfsBasicDirRead(t *testing.T) {
280 }
281 }
282
283 -// Test to make sure the filesystem reports file sizes correctly
283 +// Test to make sure the filesystem reports file sizes correctly.
284 func TestFileSizeReporting(t *testing.T) {
285 if testing.Short() {
286 t.SkipNow()
fuse/readonly/readonly_unix.go
+8 -8
@@ -49,7 +49,7 @@ type Root struct {
49
50 // Attr returns file attributes.
51 func (*Root) Attr(ctx context.Context, a *fuse.Attr) error {
52 - a.Mode = os.ModeDir | 0111 // -rw+x
52 + a.Mode = os.ModeDir | 0o111 // -rw+x
53 return nil
54 }
55
@@ -139,7 +139,7 @@ func (s *Node) loadData() error {
139 func (s *Node) Attr(ctx context.Context, a *fuse.Attr) error {
140 log.Debug("Node attr")
141 if rawnd, ok := s.Nd.(*mdag.RawNode); ok {
142 - a.Mode = 0444
142 + a.Mode = 0o444
143 a.Size = uint64(len(rawnd.RawData()))
144 a.Blocks = 1
145 return nil
@@ -152,18 +152,18 @@ func (s *Node) Attr(ctx context.Context, a *fuse.Attr) error {
152 }
153 switch s.cached.Type() {
154 case ft.TDirectory, ft.THAMTShard:
155 - a.Mode = os.ModeDir | 0555
155 + a.Mode = os.ModeDir | 0o555
156 case ft.TFile:
157 size := s.cached.FileSize()
158 - a.Mode = 0444
158 + a.Mode = 0o444
159 a.Size = uint64(size)
160 a.Blocks = uint64(len(s.Nd.Links()))
161 case ft.TRaw:
162 - a.Mode = 0444
162 + a.Mode = 0o444
163 a.Size = uint64(len(s.cached.Data()))
164 a.Blocks = uint64(len(s.Nd.Links()))
165 case ft.TSymlink:
166 - a.Mode = 0777 | os.ModeSymlink
166 + a.Mode = 0o777 | os.ModeSymlink
167 a.Size = uint64(len(s.cached.Data()))
168 default:
169 return fmt.Errorf("invalid data type - %s", s.cached.Type())
@@ -195,7 +195,7 @@ func (s *Node) Lookup(ctx context.Context, name string) (fs.Node, error) {
195 return &Node{Ipfs: s.Ipfs, Nd: nd}, nil
196 }
197
198 -// ReadDirAll reads the link structure as directory entries
198 +// ReadDirAll reads the link structure as directory entries.
199 func (s *Node) ReadDirAll(ctx context.Context) ([]fuse.Dirent, error) {
200 log.Debug("Node ReadDir")
201 dir, err := uio.NewDirectoryFromNode(s.Ipfs.DAG, s.Nd)
@@ -284,7 +284,7 @@ func (s *Node) Read(ctx context.Context, req *fuse.ReadRequest, resp *fuse.ReadR
284 return nil // may be non-nil / not succeeded
285 }
286
287 -// to check that out Node implements all the interfaces we want
287 +// to check that out Node implements all the interfaces we want.
288 type roRoot interface {
289 fs.Node
290 fs.HandleReadDirAller
gc/gc.go
-1
@@ -191,7 +191,6 @@ func Descendants(ctx context.Context, getLinks dag.GetLinks, set *cid.Set, roots
191 err := dag.Walk(ctx, verifyGetLinks, wrapper.C, func(k cid.Cid) bool {
192 return set.Visit(toCidV1(k))
193 }, dag.Concurrent())
194 -
194 if err != nil {
195 err = verboseCidError(err)
196 return err
p2p/listener.go
+3 -3
@@ -10,7 +10,7 @@ import (
10 ma "github.com/multiformats/go-multiaddr"
11 )
12
13 -// Listener listens for connections and proxies them to a target
13 +// Listener listens for connections and proxies them to a target.
14 type Listener interface {
15 Protocol() protocol.ID
16 ListenAddress() ma.Multiaddr
@@ -23,7 +23,7 @@ type Listener interface {
23 }
24
25 // Listeners manages a group of Listener implementations,
26 -// checking for conflicts and optionally dispatching connections
26 +// checking for conflicts and optionally dispatching connections.
27 type Listeners struct {
28 sync.RWMutex
29
@@ -60,7 +60,7 @@ func newListenersP2P(host p2phost.Host) *Listeners {
60 return reg
61 }
62
63 -// Register registers listenerInfo into this registry and starts it
63 +// Register registers listenerInfo into this registry and starts it.
64 func (r *Listeners) Register(l Listener) error {
65 r.Lock()
66 defer r.Unlock()
p2p/local.go
+2 -2
@@ -12,7 +12,7 @@ import (
12 manet "github.com/multiformats/go-multiaddr/net"
13 )
14
15 -// localListener manet streams and proxies them to libp2p services
15 +// localListener manet streams and proxies them to libp2p services.
16 type localListener struct {
17 ctx context.Context
18
@@ -25,7 +25,7 @@ type localListener struct {
25 listener manet.Listener
26 }
27
28 -// ForwardLocal creates new P2P stream to a remote listener
28 +// ForwardLocal creates new P2P stream to a remote listener.
29 func (p2p *P2P) ForwardLocal(ctx context.Context, peer peer.ID, proto protocol.ID, bindAddr ma.Multiaddr) (Listener, error) {
30 listener := &localListener{
31 ctx: ctx,
p2p/p2p.go
+3 -3
@@ -10,7 +10,7 @@ import (
10
11 var log = logging.Logger("p2p-mount")
12
13 -// P2P structure holds information on currently running streams/Listeners
13 +// P2P structure holds information on currently running streams/Listeners.
14 type P2P struct {
15 ListenersLocal *Listeners
16 ListenersP2P *Listeners
@@ -21,7 +21,7 @@ type P2P struct {
21 peerstore pstore.Peerstore
22 }
23
24 -// New creates new P2P struct
24 +// New creates new P2P struct.
25 func New(identity peer.ID, peerHost p2phost.Host, peerstore pstore.Peerstore) *P2P {
26 return &P2P{
27 identity: identity,
@@ -40,7 +40,7 @@ func New(identity peer.ID, peerHost p2phost.Host, peerstore pstore.Peerstore) *P
40 }
41
42 // CheckProtoExists checks whether a proto handler is registered to
43 -// mux handler
43 +// mux handler.
44 func (p2p *P2P) CheckProtoExists(proto protocol.ID) bool {
45 protos := p2p.peerHost.Mux().Protocols()
46
p2p/remote.go
+2 -2
@@ -12,7 +12,7 @@ import (
12
13 var maPrefix = "/" + ma.ProtocolWithCode(ma.P_IPFS).Name + "/"
14
15 -// remoteListener accepts libp2p streams and proxies them to a manet host
15 +// remoteListener accepts libp2p streams and proxies them to a manet host.
16 type remoteListener struct {
17 p2p *P2P
18
@@ -27,7 +27,7 @@ type remoteListener struct {
27 reportRemote bool
28 }
29
30 -// ForwardRemote creates new p2p listener
30 +// ForwardRemote creates new p2p listener.
31 func (p2p *P2P) ForwardRemote(ctx context.Context, proto protocol.ID, addr ma.Multiaddr, reportRemote bool) (Listener, error) {
32 listener := &remoteListener{
33 p2p: p2p,
p2p/stream.go
+6 -6
@@ -30,12 +30,12 @@ type Stream struct {
30 Registry *StreamRegistry
31 }
32
33 -// close stream endpoints and deregister it
33 +// close stream endpoints and deregister it.
34 func (s *Stream) close() {
35 s.Registry.Close(s)
36 }
37
38 -// reset closes stream endpoints and deregisters it
38 +// reset closes stream endpoints and deregisters it.
39 func (s *Stream) reset() {
40 s.Registry.Reset(s)
41 }
@@ -71,7 +71,7 @@ type StreamRegistry struct {
71 ifconnmgr.ConnManager
72 }
73
74 -// Register registers a stream to the registry
74 +// Register registers a stream to the registry.
75 func (r *StreamRegistry) Register(streamInfo *Stream) {
76 r.Lock()
77 defer r.Unlock()
@@ -86,7 +86,7 @@ func (r *StreamRegistry) Register(streamInfo *Stream) {
86 streamInfo.startStreaming()
87 }
88
89 -// Deregister deregisters stream from the registry
89 +// Deregister deregisters stream from the registry.
90 func (r *StreamRegistry) Deregister(streamID uint64) {
91 r.Lock()
92 defer r.Unlock()
@@ -105,14 +105,14 @@ func (r *StreamRegistry) Deregister(streamID uint64) {
105 delete(r.Streams, streamID)
106 }
107
108 -// Close stream endpoints and deregister it
108 +// Close stream endpoints and deregister it.
109 func (r *StreamRegistry) Close(s *Stream) {
110 _ = s.Local.Close()
111 _ = s.Remote.Close()
112 s.Registry.Deregister(s.id)
113 }
114
115 -// Reset closes stream endpoints and deregisters it
115 +// Reset closes stream endpoints and deregisters it.
116 func (r *StreamRegistry) Reset(s *Stream) {
117 _ = s.Local.Close()
118 _ = s.Remote.Reset()
peering/peering.go
+2 -1
@@ -201,7 +201,7 @@ func (ps *PeeringService) Start() error {
201 return nil
202 }
203
204 -// GetState get the State of the PeeringService
204 +// GetState get the State of the PeeringService.
205 func (ps *PeeringService) GetState() State {
206 ps.mu.RLock()
207 defer ps.mu.RUnlock()
@@ -306,6 +306,7 @@ func (nn *netNotifee) Connected(_ network.Network, c network.Conn) {
306 go handler.stopIfConnected()
307 }
308 }
309 +
310 func (nn *netNotifee) Disconnected(_ network.Network, c network.Conn) {
311 ps := (*PeeringService)(nn)
312
plugin/datastore.go
+1 -1
@@ -5,7 +5,7 @@ import (
5 )
6
7 // PluginDatastore is an interface that can be implemented to add handlers for
8 -// for different datastores
8 +// for different datastores.
9 type PluginDatastore interface {
10 Plugin
11
plugin/ipld.go
+1 -1
@@ -5,7 +5,7 @@ import (
5 )
6
7 // PluginIPLD is an interface that can be implemented to add handlers for
8 -// for different IPLD codecs
8 +// for different IPLD codecs.
9 type PluginIPLD interface {
10 Plugin
11
plugin/loader/loader.go
+3 -3
@@ -93,7 +93,7 @@ type PluginLoader struct {
93 repo string
94 }
95
96 -// NewPluginLoader creates new plugin loader
96 +// NewPluginLoader creates new plugin loader.
97 func NewPluginLoader(repo string) (*PluginLoader, error) {
98 loader := &PluginLoader{plugins: make([]plugin.Plugin, 0, len(preloadPlugins)), repo: repo}
99 if repo != "" {
@@ -226,7 +226,7 @@ func loadDynamicPlugins(pluginDir string) ([]plugin.Plugin, error) {
226 return nil
227 }
228
229 - if info.Mode().Perm()&0111 == 0 {
229 + if info.Mode().Perm()&0o111 == 0 {
230 // file is not executable let's not load it
231 // this is to prevent loading plugins from for example non-executable
232 // mounts, some /tmp mounts are marked as such for security
@@ -245,7 +245,7 @@ func loadDynamicPlugins(pluginDir string) ([]plugin.Plugin, error) {
245 return plugins, err
246 }
247
248 -// Initialize initializes all loaded plugins
248 +// Initialize initializes all loaded plugins.
249 func (loader *PluginLoader) Initialize() error {
250 if err := loader.transition(loaderLoading, loaderInitializing); err != nil {
251 return err
plugin/plugins/badgerds/badgerds.go
+3 -3
@@ -13,7 +13,7 @@ import (
13 badgerds "github.com/ipfs/go-ds-badger"
14 )
15
16 -// Plugins is exported list of plugins that will be loaded
16 +// Plugins is exported list of plugins that will be loaded.
17 var Plugins = []plugin.Plugin{
18 &badgerdsPlugin{},
19 }
@@ -47,7 +47,7 @@ type datastoreConfig struct {
47 }
48
49 // BadgerdsDatastoreConfig returns a configuration stub for a badger datastore
50 -// from the given parameters
50 +// from the given parameters.
51 func (*badgerdsPlugin) DatastoreConfigParser() fsrepo.ConfigFromMap {
52 return func(params map[string]interface{}) (fsrepo.DatastoreConfig, error) {
53 var c datastoreConfig
@@ -113,7 +113,7 @@ func (c *datastoreConfig) Create(path string) (repo.Datastore, error) {
113 p = filepath.Join(path, p)
114 }
115
116 - err := os.MkdirAll(p, 0755)
116 + err := os.MkdirAll(p, 0o755)
117 if err != nil {
118 return nil, err
119 }
plugin/plugins/dagjose/dagjose.go
+1 -1
@@ -8,7 +8,7 @@ import (
8 mc "github.com/multiformats/go-multicodec"
9 )
10
11 -// Plugins is exported list of plugins that will be loaded
11 +// Plugins is exported list of plugins that will be loaded.
12 var Plugins = []plugin.Plugin{
13 &dagjosePlugin{},
14 }
plugin/plugins/flatfs/flatfs.go
+2 -2
@@ -11,7 +11,7 @@ import (
11 flatfs "github.com/ipfs/go-ds-flatfs"
12 )
13
14 -// Plugins is exported list of plugins that will be loaded
14 +// Plugins is exported list of plugins that will be loaded.
15 var Plugins = []plugin.Plugin{
16 &flatfsPlugin{},
17 }
@@ -43,7 +43,7 @@ type datastoreConfig struct {
43 }
44
45 // BadgerdsDatastoreConfig returns a configuration stub for a badger datastore
46 -// from the given parameters
46 +// from the given parameters.
47 func (*flatfsPlugin) DatastoreConfigParser() fsrepo.ConfigFromMap {
48 return func(params map[string]interface{}) (fsrepo.DatastoreConfig, error) {
49 var c datastoreConfig
plugin/plugins/git/git.go
+1 -1
@@ -13,7 +13,7 @@ import (
13 mc "github.com/multiformats/go-multicodec"
14 )
15
16 -// Plugins is exported list of plugins that will be loaded
16 +// Plugins is exported list of plugins that will be loaded.
17 var Plugins = []plugin.Plugin{
18 &gitPlugin{},
19 }
plugin/plugins/levelds/levelds.go
+2 -2
@@ -12,7 +12,7 @@ import (
12 ldbopts "github.com/syndtr/goleveldb/leveldb/opt"
13 )
14
15 -// Plugins is exported list of plugins that will be loaded
15 +// Plugins is exported list of plugins that will be loaded.
16 var Plugins = []plugin.Plugin{
17 &leveldsPlugin{},
18 }
@@ -43,7 +43,7 @@ type datastoreConfig struct {
43 }
44
45 // BadgerdsDatastoreConfig returns a configuration stub for a badger datastore
46 -// from the given parameters
46 +// from the given parameters.
47 func (*leveldsPlugin) DatastoreConfigParser() fsrepo.ConfigFromMap {
48 return func(params map[string]interface{}) (fsrepo.DatastoreConfig, error) {
49 var c datastoreConfig
plugin/plugins/peerlog/peerlog.go
+3 -3
@@ -20,7 +20,7 @@ var log = logging.Logger("plugin/peerlog")
20 type eventType int
21
22 var (
23 - // size of the event queue buffer
23 + // size of the event queue buffer.
24 eventQueueSize = 64 * 1024
25 // number of events to drop when busy.
26 busyDropAmount = eventQueueSize / 8
@@ -54,7 +54,7 @@ type peerLogPlugin struct {
54
55 var _ plugin.PluginDaemonInternal = (*peerLogPlugin)(nil)
56
57 -// Plugins is exported list of plugins that will be loaded
57 +// Plugins is exported list of plugins that will be loaded.
58 var Plugins = []plugin.Plugin{
59 &peerLogPlugin{},
60 }
@@ -94,7 +94,7 @@ func extractEnabled(config interface{}) bool {
94 return enabled
95 }
96
97 -// Init initializes plugin
97 +// Init initializes plugin.
98 func (pl *peerLogPlugin) Init(env *plugin.Environment) error {
99 pl.events = make(chan plEvent, eventQueueSize)
100 pl.enabled = extractEnabled(env.Config)
plugin/tracer.go
+1 -1
@@ -4,7 +4,7 @@ import (
4 "github.com/opentracing/opentracing-go"
5 )
6
7 -// PluginTracer is an interface that can be implemented to add a tracer
7 +// PluginTracer is an interface that can be implemented to add a tracer.
8 type PluginTracer interface {
9 Plugin
10
repo/common/common.go
+1 -1
@@ -62,7 +62,7 @@ func MapSetKV(v map[string]interface{}, key string, value interface{}) error {
62 }
63
64 // Merges the right map into the left map, recursively traversing child maps
65 -// until a non-map value is found
65 +// until a non-map value is found.
66 func MapMergeDeep(left, right map[string]interface{}) map[string]interface{} {
67 // We want to alter a copy of the map, not the original
68 result := make(map[string]interface{})
repo/fsrepo/config_test.go
+1 -1
@@ -12,7 +12,7 @@ import (
12 )
13
14 // note: to test sorting of the mountpoints in the disk spec they are
15 -// specified out of order in the test config
15 +// specified out of order in the test config.
16 var defaultConfig = []byte(`{
17 "StorageMax": "10GB",
18 "StorageGCWatermark": 90,
repo/fsrepo/datastores.go
+9 -10
@@ -14,12 +14,12 @@ import (
14 "github.com/ipfs/go-ds-measure"
15 )
16
17 -// ConfigFromMap creates a new datastore config from a map
17 +// ConfigFromMap creates a new datastore config from a map.
18 type ConfigFromMap func(map[string]interface{}) (DatastoreConfig, error)
19
20 // DatastoreConfig is an abstraction of a datastore config. A "spec"
21 // is first converted to a DatastoreConfig and then Create() is called
22 -// to instantiate a new datastore
22 +// to instantiate a new datastore.
23 type DatastoreConfig interface {
24 // DiskSpec returns a minimal configuration of the datastore
25 // represting what is stored on disk. Run time values are
@@ -38,7 +38,7 @@ type DatastoreConfig interface {
38 // here.
39 type DiskSpec map[string]interface{}
40
41 -// Bytes returns a minimal JSON encoding of the DiskSpec
41 +// Bytes returns a minimal JSON encoding of the DiskSpec.
42 func (spec DiskSpec) Bytes() []byte {
43 b, err := json.Marshal(spec)
44 if err != nil {
@@ -48,7 +48,7 @@ func (spec DiskSpec) Bytes() []byte {
48 return bytes.TrimSpace(b)
49 }
50
51 -// String returns a minimal JSON encoding of the DiskSpec
51 +// String returns a minimal JSON encoding of the DiskSpec.
52 func (spec DiskSpec) String() string {
53 return string(spec.Bytes())
54 }
@@ -75,7 +75,7 @@ func AddDatastoreConfigHandler(name string, dsc ConfigFromMap) error {
75 }
76
77 // AnyDatastoreConfig returns a DatastoreConfig from a spec based on
78 -// the "type" parameter
78 +// the "type" parameter.
79 func AnyDatastoreConfig(params map[string]interface{}) (DatastoreConfig, error) {
80 which, ok := params["type"].(string)
81 if !ok {
@@ -97,7 +97,7 @@ type premount struct {
97 prefix ds.Key
98 }
99
100 -// MountDatastoreConfig returns a mount DatastoreConfig from a spec
100 +// MountDatastoreConfig returns a mount DatastoreConfig from a spec.
101 func MountDatastoreConfig(params map[string]interface{}) (DatastoreConfig, error) {
102 var res mountDatastoreConfig
103 mounts, ok := params["mounts"].([]interface{})
@@ -165,7 +165,7 @@ type memDatastoreConfig struct {
165 cfg map[string]interface{}
166 }
167
168 -// MemDatastoreConfig returns a memory DatastoreConfig from a spec
168 +// MemDatastoreConfig returns a memory DatastoreConfig from a spec.
169 func MemDatastoreConfig(params map[string]interface{}) (DatastoreConfig, error) {
170 return &memDatastoreConfig{params}, nil
171 }
@@ -183,7 +183,7 @@ type logDatastoreConfig struct {
183 name string
184 }
185
186 -// LogDatastoreConfig returns a log DatastoreConfig from a spec
186 +// LogDatastoreConfig returns a log DatastoreConfig from a spec.
187 func LogDatastoreConfig(params map[string]interface{}) (DatastoreConfig, error) {
188 childField, ok := params["child"].(map[string]interface{})
189 if !ok {
@@ -198,7 +198,6 @@ func LogDatastoreConfig(params map[string]interface{}) (DatastoreConfig, error)
198 return nil, fmt.Errorf("'name' field was missing or not a string")
199 }
200 return &logDatastoreConfig{child, name}, nil
201 -
201 }
202
203 func (c *logDatastoreConfig) Create(path string) (repo.Datastore, error) {
@@ -218,7 +217,7 @@ type measureDatastoreConfig struct {
217 prefix string
218 }
219
221 -// MeasureDatastoreConfig returns a measure DatastoreConfig from a spec
220 +// MeasureDatastoreConfig returns a measure DatastoreConfig from a spec.
221 func MeasureDatastoreConfig(params map[string]interface{}) (DatastoreConfig, error) {
222 childField, ok := params["child"].(map[string]interface{})
223 if !ok {
repo/fsrepo/fsrepo.go
+14 -12
@@ -31,12 +31,12 @@ import (
31 )
32
33 // LockFile is the filename of the repo lock, relative to config dir
34 -// TODO rename repo lock and hide name
34 +// TODO rename repo lock and hide name.
35 const LockFile = "repo.lock"
36
37 var log = logging.Logger("fsrepo")
38
39 -// RepoVersion is the version number that we are currently expecting to see
39 +// RepoVersion is the version number that we are currently expecting to see.
40 var RepoVersion = 14
41
42 var migrationInstructions = `See https://github.com/ipfs/fs-repo-migrations/blob/master/run.md
@@ -64,9 +64,11 @@ func (err NoRepoError) Error() string {
64 return fmt.Sprintf("no IPFS repo found in %s.\nplease run: 'ipfs init'", err.Path)
65 }
66
67 -const apiFile = "api"
68 -const gatewayFile = "gateway"
69 -const swarmKeyFile = "swarm.key"
67 +const (
68 + apiFile = "api"
69 + gatewayFile = "gateway"
70 + swarmKeyFile = "swarm.key"
71 +)
72
73 const specFn = "datastore_spec"
74
@@ -277,13 +279,12 @@ func initSpec(path string, conf map[string]interface{}) error {
279 }
280 bytes := dsc.DiskSpec().Bytes()
281
280 - return os.WriteFile(fn, bytes, 0600)
282 + return os.WriteFile(fn, bytes, 0o600)
283 }
284
285 // Init initializes a new FSRepo at the given path with the provided config.
286 // TODO add support for custom datastores.
287 func Init(repoPath string, conf *config.Config) error {
286 -
288 // packageLock must be held to ensure that the repo is not initialized more
289 // than once.
290 packageLock.Lock()
@@ -597,7 +598,7 @@ func (r *FSRepo) BackupConfig(prefix string) (string, error) {
598 }
599 defer temp.Close()
600
600 - orig, err := os.OpenFile(r.configFilePath, os.O_RDONLY, 0600)
601 + orig, err := os.OpenFile(r.configFilePath, os.O_RDONLY, 0o600)
602 if err != nil {
603 return "", err
604 }
@@ -626,7 +627,6 @@ func (r *FSRepo) BackupConfig(prefix string) (string, error) {
627 // We need to comb SetConfig calls and replace them when possible with a
628 // JSON map variant.
629 func (r *FSRepo) SetConfig(updated *config.Config) error {
629 -
630 // packageLock is held to provide thread-safety.
631 packageLock.Lock()
632 defer packageLock.Unlock()
@@ -725,7 +725,7 @@ func (r *FSRepo) Datastore() repo.Datastore {
725 return d
726 }
727
728 -// GetStorageUsage computes the storage space taken by the repo in bytes
728 +// GetStorageUsage computes the storage space taken by the repo in bytes.
729 func (r *FSRepo) GetStorageUsage(ctx context.Context) (uint64, error) {
730 return ds.DiskUsage(ctx, r.Datastore())
731 }
@@ -746,8 +746,10 @@ func (r *FSRepo) SwarmKey() ([]byte, error) {
746 return io.ReadAll(f)
747 }
748
749 -var _ io.Closer = &FSRepo{}
750 -var _ repo.Repo = &FSRepo{}
749 +var (
750 + _ io.Closer = &FSRepo{}
751 + _ repo.Repo = &FSRepo{}
752 +)
753
754 // IsInitialized returns true if the repo is initialized at provided |path|.
755 func IsInitialized(path string) bool {
repo/fsrepo/migrations/fetch.go
+2 -2
@@ -130,7 +130,7 @@ func FetchBinary(ctx context.Context, fetcher Fetcher, dist, ver, binName, out s
130 }
131
132 // Set mode of binary to executable
133 - err = os.Chmod(out, 0755)
133 + err = os.Chmod(out, 0o755)
134 if err != nil {
135 return "", err
136 }
@@ -184,7 +184,7 @@ func osWithVariant() (string, error) {
184 // "go-ipfs_v0.8.0-rc2_linux-amd64.tar.gz"
185 //
186 // This would form the path:
187 -// go-ipfs/v0.8.0/go-ipfs_v0.8.0_linux-amd64.tar.gz
187 +// go-ipfs/v0.8.0/go-ipfs_v0.8.0_linux-amd64.tar.gz.
188 func makeArchivePath(dist, name, ver, atype string) (string, string) {
189 arcName := fmt.Sprintf("%s_%s_%s-%s.%s", name, ver, runtime.GOOS, runtime.GOARCH, atype)
190 return fmt.Sprintf("%s/%s/%s", dist, ver, arcName), arcName
repo/fsrepo/migrations/fetch_test.go
+2 -2
@@ -184,7 +184,7 @@ func TestFetchBinary(t *testing.T) {
184 // Windows doesn't have read-only directories https://github.com/golang/go/issues/35042 this would need to be
185 // tested another way
186 if runtime.GOOS != "windows" {
187 - err = os.Chmod(tmpDir, 0555)
187 + err = os.Chmod(tmpDir, 0o555)
188 if err != nil {
189 panic(err)
190 }
@@ -200,7 +200,7 @@ func TestFetchBinary(t *testing.T) {
200 if err != nil {
201 panic(err)
202 }
203 - err = os.Chmod(tmpDir, 0755)
203 + err = os.Chmod(tmpDir, 0o755)
204 if err != nil {
205 panic(err)
206 }
repo/fsrepo/migrations/fetcher.go
+3 -4
@@ -10,12 +10,12 @@ import (
10 )
11
12 const (
13 - // Current distribution to fetch migrations from
13 + // Current distribution to fetch migrations from.
14 CurrentIpfsDist = "/ipfs/QmYerugGRCZWA8yQMKDsd9daEVXUR3C5nuw3VXuX1mggHa" // fs-repo-13-to-14 v1.0.0
15 // Latest distribution path. Default for fetchers.
16 LatestIpfsDist = "/ipns/dist.ipfs.tech"
17
18 - // Distribution environ variable
18 + // Distribution environ variable.
19 envIpfsDistPath = "IPFS_DIST_PATH"
20 )
21
@@ -40,7 +40,6 @@ type limitReadCloser struct {
40 // NewMultiFetcher creates a MultiFetcher with the given Fetchers. The
41 // Fetchers are tried in order, then passed to this function.
42 func NewMultiFetcher(f ...Fetcher) *MultiFetcher {
43 -
43 mf := &MultiFetcher{
44 fetchers: make([]Fetcher, len(f)),
45 }
@@ -95,7 +94,7 @@ func NewLimitReadCloser(rc io.ReadCloser, limit int64) io.ReadCloser {
94 // then returns the IPNS path.
95 //
96 // To get the IPFS path of the latest distribution, if not overriddin by the
98 -// environ variable: GetDistPathEnv(CurrentIpfsDist)
97 +// environ variable: GetDistPathEnv(CurrentIpfsDist).
98 func GetDistPathEnv(distPath string) string {
99 if dist := os.Getenv(envIpfsDistPath); dist != "" {
100 return dist
repo/fsrepo/migrations/httpfetcher.go
+2 -2
@@ -11,11 +11,11 @@ import (
11
12 const (
13 defaultGatewayURL = "https://ipfs.io"
14 - // Default maximum download size
14 + // Default maximum download size.
15 defaultFetchLimit = 1024 * 1024 * 512
16 )
17
18 -// HttpFetcher fetches files over HTTP
18 +// HttpFetcher fetches files over HTTP.
19 type HttpFetcher struct { //nolint
20 distPath string
21 gateway string
repo/fsrepo/migrations/ipfsdir.go
+1 -1
@@ -84,7 +84,7 @@ func WriteRepoVersion(ipfsDir string, version int) error {
84 }
85
86 vFilePath := filepath.Join(ipfsDir, versionFile)
87 - return os.WriteFile(vFilePath, []byte(fmt.Sprintf("%d\n", version)), 0644)
87 + return os.WriteFile(vFilePath, []byte(fmt.Sprintf("%d\n", version)), 0o644)
88 }
89
90 func repoVersion(ipfsDir string) (int, error) {
repo/fsrepo/migrations/ipfsdir_test.go
+1 -1
@@ -138,7 +138,7 @@ func testRepoVersion(t *testing.T) {
138 t.Fatal(err)
139 }
140 vFilePath := filepath.Join(ipfsDir, versionFile)
141 - err = os.WriteFile(vFilePath, []byte("bad-version-data\n"), 0644)
141 + err = os.WriteFile(vFilePath, []byte("bad-version-data\n"), 0o644)
142 if err != nil {
143 panic(err)
144 }
repo/fsrepo/migrations/ipfsfetcher/ipfsfetcher.go
+2 -2
@@ -25,7 +25,7 @@ import (
25 )
26
27 const (
28 - // Default maximum download size
28 + // Default maximum download size.
29 defaultFetchLimit = 1024 * 1024 * 512
30
31 tempNodeTCPAddr = "/ip4/127.0.0.1/tcp/0"
@@ -155,7 +155,7 @@ func (f *IpfsFetcher) AddrInfo() peer.AddrInfo {
155 return f.addrInfo
156 }
157
158 -// FetchedPaths returns the IPFS paths of all items fetched by this fetcher
158 +// FetchedPaths returns the IPFS paths of all items fetched by this fetcher.
159 func (f *IpfsFetcher) FetchedPaths() []ipath.Path {
160 f.mutex.Lock()
161 defer f.mutex.Unlock()
repo/fsrepo/migrations/ipfsfetcher/ipfsfetcher_test.go
+1 -2
@@ -55,7 +55,6 @@ func TestIpfsFetcher(t *testing.T) {
55 if _, err = fetcher.Fetch(ctx, "/no_such_file"); err == nil {
56 t.Fatal("expected error 404")
57 }
58 -
58 }
59
60 func TestInitIpfsFetcher(t *testing.T) {
@@ -110,7 +109,7 @@ func TestInitIpfsFetcher(t *testing.T) {
109 }
110
111 func TestReadIpfsConfig(t *testing.T) {
113 - var testConfig = `
112 + testConfig := `
113 {
114 "Bootstrap": [
115 "/dnsaddr/bootstrap.libp2p.io/p2p/QmcZf59bWwK5XFi76CZX8cbJ4BhTzzA3gU1ZjYZcYW3dwt",
repo/fsrepo/migrations/migrations.go
+1 -1
@@ -151,7 +151,7 @@ func ReadMigrationConfig(repoRoot string, userConfigFile string) (*config.Migrat
151 }
152
153 // GetMigrationFetcher creates one or more fetchers according to
154 -// downloadSources,
154 +// downloadSources,.
155 func GetMigrationFetcher(downloadSources []string, distPath string, newIpfsFetcher func(string) Fetcher) (Fetcher, error) {
156 const httpUserAgent = "go-ipfs"
157 const numTriesPerHTTP = 3
repo/fsrepo/migrations/migrations_test.go
+1 -1
@@ -191,7 +191,7 @@ func createFakeBin(from, to int, tmpDir string) {
191 panic(err)
192 }
193 emptyFile.Close()
194 - err = os.Chmod(migPath, 0755)
194 + err = os.Chmod(migPath, 0o755)
195 if err != nil {
196 panic(err)
197 }
repo/fsrepo/migrations/unpack_test.go
+3 -4
@@ -35,7 +35,7 @@ func TestUnpackTgz(t *testing.T) {
35 tmpDir := t.TempDir()
36
37 badTarGzip := filepath.Join(tmpDir, "bad.tar.gz")
38 - err := os.WriteFile(badTarGzip, []byte("bad-data\n"), 0644)
38 + err := os.WriteFile(badTarGzip, []byte("bad-data\n"), 0o644)
39 if err != nil {
40 panic(err)
41 }
@@ -72,14 +72,13 @@ func TestUnpackTgz(t *testing.T) {
72 if fi.Size() != int64(len(testData)) {
73 t.Fatal("unpacked file size is", fi.Size(), "expected", len(testData))
74 }
75 -
75 }
76
77 func TestUnpackZip(t *testing.T) {
78 tmpDir := t.TempDir()
79
80 badZip := filepath.Join(tmpDir, "bad.zip")
82 - err := os.WriteFile(badZip, []byte("bad-data\n"), 0644)
81 + err := os.WriteFile(badZip, []byte("bad-data\n"), 0o644)
82 if err != nil {
83 panic(err)
84 }
@@ -153,7 +152,7 @@ func writeTarGzip(root, fileName, data string, w io.Writer) error {
152 if fileName != "" {
153 hdr := &tar.Header{
154 Name: path.Join(root, fileName),
156 - Mode: 0600,
155 + Mode: 0o600,
156 Size: int64(len(data)),
157 }
158 // Write header
repo/mock.go
+1 -1
@@ -15,7 +15,7 @@ import (
15
16 var errTODO = errors.New("TODO: mock repo")
17
18 -// Mock is not thread-safe
18 +// Mock is not thread-safe.
19 type Mock struct {
20 C config.Config
21 D Datastore
repo/repo.go
+1 -3
@@ -15,9 +15,7 @@ import (
15 ma "github.com/multiformats/go-multiaddr"
16 )
17
18 -var (
19 - ErrApiNotRunning = errors.New("api not running") //nolint
20 -)
18 +var ErrApiNotRunning = errors.New("api not running") //nolint
19
20 // Repo represents all persistent data of a given ipfs node.
21 type Repo interface {
routing/composer.go
+4 -3
@@ -11,8 +11,10 @@ import (
11 "github.com/multiformats/go-multihash"
12 )
13
14 -var _ routinghelpers.ProvideManyRouter = &Composer{}
15 -var _ routing.Routing = &Composer{}
14 +var (
15 + _ routinghelpers.ProvideManyRouter = &Composer{}
16 + _ routing.Routing = &Composer{}
17 +)
18
19 type Composer struct {
20 GetValueRouter routing.Routing
@@ -27,7 +29,6 @@ func (c *Composer) Provide(ctx context.Context, cid cid.Cid, provide bool) error
29 err := c.ProvideRouter.Provide(ctx, cid, provide)
30 if err != nil {
31 log.Debug("composer: calling provide: ", cid, " error: ", err)
30 -
32 }
33
34 return err
routing/delegated_test.go
-1
@@ -154,7 +154,6 @@ func TestParserRecursive(t *testing.T) {
154
155 _, ok := router.(*Composer)
156 require.True(ok)
157 -
157 }
158
159 func TestParserRecursiveLoop(t *testing.T) {
routing/wrapper.go
+4 -2
@@ -13,8 +13,10 @@ type ProvideManyRouter interface {
13 routing.Routing
14 }
15
16 -var _ routing.Routing = &httpRoutingWrapper{}
17 -var _ routinghelpers.ProvideManyRouter = &httpRoutingWrapper{}
16 +var (
17 + _ routing.Routing = &httpRoutingWrapper{}
18 + _ routinghelpers.ProvideManyRouter = &httpRoutingWrapper{}
19 +)
20
21 // httpRoutingWrapper is a wrapper needed to construct the routing.Routing interface from
22 // http delegated routing.
tar/format.go
+5 -3
@@ -21,8 +21,10 @@ import (
21
22 var log = logging.Logger("tarfmt")
23
24 -var blockSize = 512
25 -var zeroBlock = make([]byte, blockSize)
24 +var (
25 + blockSize = 512
26 + zeroBlock = make([]byte, blockSize)
27 +)
28
29 func marshalHeader(h *tar.Header) ([]byte, error) {
30 buf := new(bytes.Buffer)
@@ -91,7 +93,7 @@ func ImportTar(ctx context.Context, r io.Reader, ds ipld.DAGService) (*dag.Proto
93 }
94
95 // adds a '-' to the beginning of each path element so we can use 'data' as a
94 -// special link in the structure without having to worry about
96 +// special link in the structure without having to worry about.
97 func escapePath(pth string) string {
98 elems := path.SplitList(strings.Trim(pth, "/"))
99 for i, e := range elems {
test/cli/basic_commands_test.go
-2
@@ -210,7 +210,6 @@ func TestCommandDocsWidth(t *testing.T) {
210 for _, line := range SplitLines(res) {
211 assert.LessOrEqualf(t, len(line), 80, "expected width %d < 80 for %q", len(line), cmd)
212 }
213 -
213 })
214 }
215 }
@@ -226,7 +225,6 @@ func TestAllCommandsFailWhenPassedBadFlag(t *testing.T) {
225 assert.Equal(t, 1, res.Cmd.ProcessState.ExitCode())
226 })
227 }
229 -
228 }
229
230 func TestCommandsFlags(t *testing.T) {
test/cli/content_routing_http_test.go
+1
@@ -37,6 +37,7 @@ func (r *fakeHTTPContentRouter) ProvideBitswap(ctx context.Context, req *server.
37 r.provideCalls++
38 return 0, nil
39 }
40 +
41 func (r *fakeHTTPContentRouter) Provide(ctx context.Context, req *server.WriteProvideRequest) (types.ProviderResponse, error) {
42 r.m.Lock()
43 defer r.m.Unlock()
test/cli/dag_test.go
-1
@@ -101,5 +101,4 @@ func TestDag(t *testing.T) {
101 stat := node.RunIPFS("dag", "stat", "--progress=false", node1Cid, node2Cid)
102 assert.Equal(t, content, stat.Stdout.Bytes())
103 })
104 -
104 }
test/cli/delegated_routing_http_test.go
-1
@@ -155,5 +155,4 @@ func TestHTTPDelegatedRouting(t *testing.T) {
155 resp := node.APIClient().Get("/debug/metrics/prometheus")
156 assert.Contains(t, resp.Body, "routing_http_client_length_count")
157 })
158 -
158 }
test/cli/dht_legacy_test.go
-1
@@ -107,7 +107,6 @@ func TestLegacyDHT(t *testing.T) {
107 sort.IntSlice(counts).Sort()
108 assert.Equal(t, []int{1, 4}, counts)
109 })
110 -
110 })
111
112 t.Run("dht commands fail when offline", func(t *testing.T) {
test/cli/gateway_test.go
-3
@@ -196,9 +196,7 @@ func TestGateway(t *testing.T) {
196 resp.Body,
197 fmt.Sprintf(`<link rel="canonical" href="/ipns/%s?query=to-remember" />`, peerID),
198 )
199 -
199 })
201 -
200 })
201
202 t.Run("GET invalid IPFS path errors", func(t *testing.T) {
@@ -583,7 +581,6 @@ func TestGateway(t *testing.T) {
581
582 assert.Equal(t, test.deserializedGatewayStaticCode, client.Get(deserializedPath, setHost).StatusCode)
583 assert.Equal(t, test.deserializedGatewayStaticCode, client.Get(deserializedPath, withHostAndAccept("application/json")).StatusCode)
586 -
584 }
585 }
586
test/cli/harness/harness.go
+3 -3
@@ -127,11 +127,11 @@ func (h *Harness) WriteFile(filename, contents string) {
127 log.Panicf("%s must be a relative path", filename)
128 }
129 absPath := filepath.Join(h.Runner.Dir, filename)
130 - err := os.MkdirAll(filepath.Dir(absPath), 0777)
130 + err := os.MkdirAll(filepath.Dir(absPath), 0o777)
131 if err != nil {
132 log.Panicf("creating intermediate dirs for %q: %s", filename, err.Error())
133 }
134 - err = os.WriteFile(absPath, []byte(contents), 0644)
134 + err = os.WriteFile(absPath, []byte(contents), 0o644)
135 if err != nil {
136 log.Panicf("writing %q (%q): %s", filename, absPath, err.Error())
137 }
@@ -166,7 +166,7 @@ func (h *Harness) Mkdirs(paths ...string) {
166 log.Panicf("%s must be a relative path when making dirs", path)
167 }
168 absPath := filepath.Join(h.Runner.Dir, path)
169 - err := os.MkdirAll(absPath, 0777)
169 + err := os.MkdirAll(absPath, 0o777)
170 if err != nil {
171 log.Panicf("recursively making dirs under %s: %s", absPath, err)
172 }
test/cli/harness/node.go
+1 -1
@@ -46,7 +46,7 @@ type Node struct {
46
47 func BuildNode(ipfsBin, baseDir string, id int) *Node {
48 dir := filepath.Join(baseDir, strconv.Itoa(id))
49 - if err := os.MkdirAll(dir, 0755); err != nil {
49 + if err := os.MkdirAll(dir, 0o755); err != nil {
50 panic(err)
51 }
52
test/cli/harness/peering.go
-1
@@ -26,7 +26,6 @@ func CreatePeerNodes(t *testing.T, n int, peerings []Peering) (*Harness, Nodes)
26 cfg.Routing.Type = config.NewOptionalString("none")
27 cfg.Addresses.Swarm = []string{fmt.Sprintf("/ip4/127.0.0.1/tcp/%d", NewRandPort())}
28 })
29 -
29 })
30
31 for _, peering := range peerings {
test/cli/harness/run.go
+4 -4
@@ -14,8 +14,10 @@ type Runner struct {
14 Verbose bool
15 }
16
17 -type CmdOpt func(*exec.Cmd)
18 -type RunFunc func(*exec.Cmd) error
17 +type (
18 + CmdOpt func(*exec.Cmd)
19 + RunFunc func(*exec.Cmd) error
20 +)
21
22 var RunFuncStart = (*exec.Cmd).Start
23
@@ -100,11 +102,9 @@ func (r *Runner) AssertNoError(result *RunResult) {
102 if result.ExitErr != nil {
103 log.Panicf("'%s' returned error, code: %d, err: %s\nstdout:%s\nstderr:%s\n",
104 result.Cmd.Args, result.ExitErr.ExitCode(), result.ExitErr.Error(), result.Stdout.String(), result.Stderr.String())
103 -
105 }
106 if result.Err != nil {
107 log.Panicf("unable to run %s: %s", result.Cmd.Path, result.Err)
107 -
108 }
109 }
110
test/cli/init_test.go
+1 -3
@@ -88,13 +88,12 @@ func TestInit(t *testing.T) {
88 t.Parallel()
89 node := harness.NewT(t).NewNode()
90 badDir := fp.Join(node.Dir, ".badipfs")
91 - err := os.Mkdir(badDir, 0000)
91 + err := os.Mkdir(badDir, 0o000)
92 require.NoError(t, err)
93
94 res := node.RunIPFS("init", "--repo-dir", badDir)
95 assert.NotEqual(t, 0, res.Cmd.ProcessState.ExitCode())
96 assert.Contains(t, res.Stderr.String(), "permission denied")
97 -
97 })
98
99 t.Run("init with ed25519", func(t *testing.T) {
@@ -160,5 +159,4 @@ func TestInit(t *testing.T) {
159 assert.NotEqual(t, 0, res.ExitErr.ExitCode())
160 assert.Contains(t, res.Stderr.String(), "Error: ipfs daemon is running. please stop it to run this command")
161 })
163 -
162 }
test/cli/pins_test.go
-2
@@ -76,7 +76,6 @@ func testPins(t *testing.T, args testPinsArgs) {
76 for _, cid := range cids {
77 assert.Contains(t, verboseVerifyOut, fmt.Sprintf("%s ok", cid))
78 }
79 -
79 })
80 t.Run("ls output should contain the cids", func(t *testing.T) {
81 lsOut := ipfsPinLS()
@@ -195,7 +194,6 @@ func TestPins(t *testing.T) {
194 testPins(t, testPinsArgs{pinArg: "--progress", lsArg: "--stream"})
195 testPins(t, testPinsArgs{baseArg: "--cid-base=base32"})
196 testPins(t, testPinsArgs{lsArg: "--stream", baseArg: "--cid-base=base32"})
198 -
197 })
198
199 t.Run("test pinning with daemon running without network", func(t *testing.T) {
test/cli/swarm_test.go
-3
@@ -36,7 +36,6 @@ func TestSwarm(t *testing.T) {
36 err := json.Unmarshal(res.Stdout.Bytes(), &output)
37 assert.NoError(t, err)
38 assert.Equal(t, 0, len(output.Peers))
39 -
39 })
40 t.Run("ipfs swarm peers with flag identify outputs expected identify information about connected peers", func(t *testing.T) {
41 t.Parallel()
@@ -63,7 +62,6 @@ func TestSwarm(t *testing.T) {
62 assert.Len(t, actualAdresses, 1)
63 assert.Equal(t, expectedAddresses[0], actualAdresses[0])
64 assert.Greater(t, len(actualProtocols), 0)
66 -
65 })
66
67 t.Run("ipfs swarm peers with flag identify outputs Identify field with data that matches calling ipfs id on a peer", func(t *testing.T) {
@@ -88,6 +86,5 @@ func TestSwarm(t *testing.T) {
86 assert.Equal(t, outputIdentify.AgentVersion, otherNodeIDOutput.AgentVersion)
87 assert.ElementsMatch(t, outputIdentify.Addresses, otherNodeIDOutput.Addresses)
88 assert.ElementsMatch(t, outputIdentify.Protocols, otherNodeIDOutput.Protocols)
91 -
89 })
90 }
test/cli/testutils/random_files.go
+5 -3
@@ -9,8 +9,10 @@ import (
9 "time"
10 )
11
12 -var AlphabetEasy = []rune("abcdefghijklmnopqrstuvwxyz01234567890-_")
13 -var AlphabetHard = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ01234567890!@#$%^&*()-_+= ;.,<>'\"[]{}() ")
12 +var (
13 + AlphabetEasy = []rune("abcdefghijklmnopqrstuvwxyz01234567890-_")
14 + AlphabetHard = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ01234567890!@#$%^&*()-_+= ;.,<>'\"[]{}() ")
15 +)
16
17 type RandFiles struct {
18 Rand *rand.Rand
@@ -104,7 +106,7 @@ func (r *RandFiles) WriteRandomDir(root string, depth int) error {
106 n := rand.Intn(r.FilenameSize-4) + 4
107 name := r.RandomFilename(n)
108 root = path.Join(root, name)
107 - if err := os.MkdirAll(root, 0755); err != nil {
109 + if err := os.MkdirAll(root, 0o755); err != nil {
110 return fmt.Errorf("creating random dir: %w", err)
111 }
112
test/cli/tracing_test.go
+1 -1
@@ -45,7 +45,7 @@ func TestTracing(t *testing.T) {
45
46 // touch traces.json and give it 777 perms in case Docker runs as a different user
47 node.WriteBytes("traces.json", nil)
48 - err := os.Chmod(filepath.Join(node.Dir, "traces.json"), 0777)
48 + err := os.Chmod(filepath.Join(node.Dir, "traces.json"), 0o777)
49 require.NoError(t, err)
50
51 dockerBin, err := exec.LookPath("docker")
test/cli/transports_test.go
+1 -2
@@ -32,7 +32,7 @@ func TestTransports(t *testing.T) {
32 }
33 checkRandomDir := func(nodes harness.Nodes) {
34 randDir := filepath.Join(nodes[0].Dir, "foobar")
35 - require.NoError(t, os.Mkdir(randDir, 0777))
35 + require.NoError(t, os.Mkdir(randDir, 0o777))
36 rf := testutils.NewRandFiles()
37 rf.FanoutDirs = 3
38 rf.FanoutFiles = 6
@@ -148,5 +148,4 @@ func TestTransports(t *testing.T) {
148 nodes.StartDaemons().Connect()
149 runTests(nodes)
150 })
151 -
151 }
test/dependencies/iptb/iptb.go
-1
@@ -19,7 +19,6 @@ func init() {
19 PluginName: plugin.PluginName,
20 BuiltIn: true,
21 }, false)
22 -
22 if err != nil {
23 panic(err)
24 }
test/dependencies/ma-pipe-unidir/main.go
+2 -2
@@ -57,7 +57,7 @@ func app() int {
57
58 if len(opts.PidFile) > 0 {
59 data := []byte(strconv.Itoa(os.Getpid()))
60 - err := os.WriteFile(opts.PidFile, data, 0644)
60 + err := os.WriteFile(opts.PidFile, data, 0o644)
61 if err != nil {
62 return 1
63 }
@@ -78,7 +78,7 @@ func app() int {
78
79 if len(opts.PidFile) > 0 {
80 data := []byte(strconv.Itoa(os.Getpid()))
81 - err := os.WriteFile(opts.PidFile, data, 0644)
81 + err := os.WriteFile(opts.PidFile, data, 0o644)
82 if err != nil {
83 return 1
84 }
test/integration/bench_test.go
-1
@@ -8,7 +8,6 @@ import (
8 )
9
10 func benchmarkAddCat(numBytes int64, conf testutil.LatencyConfig, b *testing.B) {
11 -
11 b.StopTimer()
12 b.SetBytes(numBytes)
13 data := RandomBytes(numBytes) // we don't want to measure the time it takes to generate this data
test/integration/wan_lan_dht_test.go
+4 -2
@@ -51,8 +51,10 @@ func TestDHTConnectivitySlowRouting(t *testing.T) {
51 }
52
53 // wan prefix must have a real corresponding ASN for the peer diversity filter to work.
54 -var wanPrefix = net.ParseIP("2001:218:3004::")
55 -var lanPrefix = net.ParseIP("fe80::")
54 +var (
55 + wanPrefix = net.ParseIP("2001:218:3004::")
56 + lanPrefix = net.ParseIP("fe80::")
57 +)
58
59 func makeAddr(n uint32, wan bool) ma.Multiaddr {
60 var ip net.IP
thirdparty/dir/dir.go
+1 -1
@@ -8,7 +8,7 @@ import (
8 "path/filepath"
9 )
10
11 -// Writable ensures the directory exists and is writable
11 +// Writable ensures the directory exists and is writable.
12 func Writable(path string) error {
13 // Construct the path if missing
14 if err := os.MkdirAll(path, os.ModePerm); err != nil {
thirdparty/notifier/notifier_test.go
+1 -3
@@ -7,7 +7,7 @@ import (
7 "time"
8 )
9
10 -// test data structures
10 +// test data structures.
11 type Router struct {
12 queue chan Packet
13 notifier Notifier
@@ -36,7 +36,6 @@ func (r *Router) notifyAll(notify func(n RouterNotifiee)) {
36 }
37
38 func (r *Router) Receive(p Packet) {
39 -
39 select {
40 case r.queue <- p: // enqueued
41 r.notifyAll(func(n RouterNotifiee) {
@@ -100,7 +99,6 @@ func (m *Metrics) String() string {
99 }
100
101 func TestNotifies(t *testing.T) {
103 -
102 m := Metrics{received: make(chan struct{})}
103 r := Router{queue: make(chan Packet, 10)}
104 r.Notify(&m)
thirdparty/unit/unit.go
+1 -2
@@ -15,11 +15,10 @@ const (
15 )
16
17 func (i Information) String() string {
18 -
18 tmp := int64(i)
19
20 // default
22 - var d = tmp
21 + d := tmp
22 symbol := "B"
23
24 switch {
version.go
+3 -3
@@ -7,10 +7,10 @@ import (
7 "github.com/ipfs/kubo/repo/fsrepo"
8 )
9
10 -// CurrentCommit is the current git commit, this is set as a ldflag in the Makefile
10 +// CurrentCommit is the current git commit, this is set as a ldflag in the Makefile.
11 var CurrentCommit string
12
13 -// CurrentVersionNumber is the current application's version literal
13 +// CurrentVersionNumber is the current application's version literal.
14 const CurrentVersionNumber = "0.23.0-dev"
15
16 const ApiVersion = "/kubo/" + CurrentVersionNumber + "/" //nolint
@@ -48,7 +48,7 @@ func GetVersionInfo() *VersionInfo {
48 Version: CurrentVersionNumber,
49 Commit: CurrentCommit,
50 Repo: fmt.Sprint(fsrepo.RepoVersion),
51 - System: runtime.GOARCH + "/" + runtime.GOOS, //TODO: Precise version here
51 + System: runtime.GOARCH + "/" + runtime.GOOS, // TODO: Precise version here
52 Golang: runtime.Version(),
53 }
54 }