From f12b372af9cc32975ff48397708fac3ec1f9966f Mon Sep 17 00:00:00 2001 From: Kay Date: Thu, 17 Aug 2023 15:32:08 +0330 Subject: [PATCH] style: gofumpt and godot [skip changelog] (#10081) --- assets/assets.go | 4 +- client/rpc/api.go | 10 +-- client/rpc/apifile.go | 13 ++-- client/rpc/block.go | 2 +- client/rpc/dag.go | 10 +-- client/rpc/errors.go | 4 +- client/rpc/object.go | 2 +- client/rpc/path.go | 2 +- client/rpc/pin.go | 2 +- client/rpc/pubsub.go | 3 +- client/rpc/response.go | 5 +- client/rpc/routing.go | 1 - cmd/ipfs/add_migrations.go | 4 +- cmd/ipfs/daemon.go | 20 +++--- cmd/ipfs/dnsresolve_test.go | 3 +- cmd/ipfs/init.go | 2 +- cmd/ipfs/ipfs.go | 2 +- cmd/ipfs/main.go | 12 ++-- cmd/ipfs/pinmfs.go | 2 +- cmd/ipfs/runmain_test.go | 4 +- cmd/ipfs/util/ulimit.go | 10 +-- cmd/ipfswatch/main.go | 11 ++-- commands/context.go | 4 +- commands/reqlog.go | 16 ++--- config/autonat.go | 2 +- config/config.go | 10 +-- config/datastore.go | 2 +- config/dns.go | 2 +- config/gateway.go | 1 - config/identity.go | 10 +-- config/init.go | 6 +- config/migration.go | 2 +- config/mounts.go | 2 +- config/profile.go | 6 +- config/reprovider.go | 6 +- config/routing.go | 10 +-- config/routing_test.go | 66 ++++++++++--------- config/serialize/serialize.go | 6 +- config/serialize/serialize_test.go | 2 +- config/swarm.go | 2 +- config/types.go | 58 +++++++++------- config/types_test.go | 3 - core/bootstrap/bootstrap.go | 2 - core/commands/bootstrap.go | 4 +- core/commands/cmdenv/cidbase.go | 6 +- core/commands/cmdutils/utils.go | 1 - core/commands/commands_test.go | 1 + core/commands/completion.go | 1 - core/commands/config.go | 1 - core/commands/config_test.go | 1 - core/commands/dag/dag.go | 9 +-- core/commands/dag/export.go | 1 - core/commands/external.go | 2 +- core/commands/files.go | 9 ++- core/commands/keystore.go | 3 - core/commands/name/publish.go | 4 +- core/commands/p2p.go | 4 +- core/commands/pin/remotepin.go | 22 ++++--- core/commands/pin/remotepin_test.go | 1 - core/commands/root.go | 6 +- core/commands/routing.go | 11 ++-- core/commands/swarm.go | 3 +- core/core.go | 1 - core/coreapi/swarm.go | 6 +- core/coreapi/unixfs.go | 13 ++-- core/corehttp/commands.go | 12 ++-- core/corehttp/metrics.go | 12 ++-- core/coreunix/add_test.go | 2 - core/node/groups.go | 1 - core/node/helpers/helpers.go | 1 + core/node/libp2p/rcmgr.go | 3 +- core/node/libp2p/rcmgr_logging.go | 30 ++++++++- core/node/libp2p/routing.go | 1 - core/node/libp2p/topicdiscovery.go | 1 - core/node/libp2p/transport.go | 3 +- docs/examples/kubo-as-a-library/main.go | 4 +- fuse/ipns/ipns_test.go | 19 +++--- fuse/ipns/ipns_unix.go | 24 +++---- fuse/ipns/link_unix.go | 2 +- fuse/mount/fuse.go | 4 +- fuse/mount/mount.go | 4 +- fuse/node/mount_darwin.go | 2 +- fuse/node/mount_test.go | 2 +- fuse/node/mount_unix.go | 6 +- fuse/readonly/ipfs_test.go | 12 ++-- fuse/readonly/readonly_unix.go | 16 ++--- gc/gc.go | 1 - p2p/listener.go | 6 +- p2p/local.go | 4 +- p2p/p2p.go | 6 +- p2p/remote.go | 4 +- p2p/stream.go | 12 ++-- peering/peering.go | 3 +- plugin/datastore.go | 2 +- plugin/ipld.go | 2 +- plugin/loader/loader.go | 6 +- plugin/plugins/badgerds/badgerds.go | 6 +- plugin/plugins/dagjose/dagjose.go | 2 +- plugin/plugins/flatfs/flatfs.go | 4 +- plugin/plugins/git/git.go | 2 +- plugin/plugins/levelds/levelds.go | 4 +- plugin/plugins/peerlog/peerlog.go | 6 +- plugin/tracer.go | 2 +- repo/common/common.go | 2 +- repo/fsrepo/config_test.go | 2 +- repo/fsrepo/datastores.go | 19 +++--- repo/fsrepo/fsrepo.go | 26 ++++---- repo/fsrepo/migrations/fetch.go | 4 +- repo/fsrepo/migrations/fetch_test.go | 4 +- repo/fsrepo/migrations/fetcher.go | 7 +- repo/fsrepo/migrations/httpfetcher.go | 4 +- repo/fsrepo/migrations/ipfsdir.go | 2 +- repo/fsrepo/migrations/ipfsdir_test.go | 2 +- .../migrations/ipfsfetcher/ipfsfetcher.go | 4 +- .../ipfsfetcher/ipfsfetcher_test.go | 3 +- repo/fsrepo/migrations/migrations.go | 2 +- repo/fsrepo/migrations/migrations_test.go | 2 +- repo/fsrepo/migrations/unpack_test.go | 7 +- repo/mock.go | 2 +- repo/repo.go | 4 +- routing/composer.go | 7 +- routing/delegated_test.go | 1 - routing/wrapper.go | 6 +- tar/format.go | 8 ++- test/cli/basic_commands_test.go | 2 - test/cli/content_routing_http_test.go | 1 + test/cli/dag_test.go | 1 - test/cli/delegated_routing_http_test.go | 1 - test/cli/dht_legacy_test.go | 1 - test/cli/gateway_test.go | 3 - test/cli/harness/harness.go | 6 +- test/cli/harness/node.go | 2 +- test/cli/harness/peering.go | 1 - test/cli/harness/run.go | 8 +-- test/cli/init_test.go | 4 +- test/cli/pins_test.go | 2 - test/cli/swarm_test.go | 3 - test/cli/testutils/random_files.go | 8 ++- test/cli/tracing_test.go | 2 +- test/cli/transports_test.go | 3 +- test/dependencies/iptb/iptb.go | 1 - test/dependencies/ma-pipe-unidir/main.go | 4 +- test/integration/bench_test.go | 1 - test/integration/wan_lan_dht_test.go | 6 +- thirdparty/dir/dir.go | 2 +- thirdparty/notifier/notifier_test.go | 4 +- thirdparty/unit/unit.go | 3 +- version.go | 6 +- 148 files changed, 449 insertions(+), 433 deletions(-) diff --git a/assets/assets.go b/assets/assets.go index 945e8e10a22..9dff80e074e 100644 --- a/assets/assets.go +++ b/assets/assets.go @@ -17,7 +17,7 @@ import ( //go:embed init-doc var Asset embed.FS -// initDocPaths lists the paths for the docs we want to seed during --init +// initDocPaths lists the paths for the docs we want to seed during --init. var initDocPaths = []string{ gopath.Join("init-doc", "about"), gopath.Join("init-doc", "readme"), @@ -28,7 +28,7 @@ var initDocPaths = []string{ gopath.Join("init-doc", "ping"), } -// SeedInitDocs adds the list of embedded init documentation to the passed node, pins it and returns the root key +// SeedInitDocs adds the list of embedded init documentation to the passed node, pins it and returns the root key. func SeedInitDocs(nd *core.IpfsNode) (cid.Cid, error) { return addAssetList(nd, initDocPaths) } diff --git a/client/rpc/api.go b/client/rpc/api.go index 404f4b312c8..cb791e7ee2f 100644 --- a/client/rpc/api.go +++ b/client/rpc/api.go @@ -48,7 +48,7 @@ type HttpApi struct { // IPFS daemon // // Daemon api address is pulled from the $IPFS_PATH/api file. -// If $IPFS_PATH env var is not present, it defaults to ~/.ipfs +// If $IPFS_PATH env var is not present, it defaults to ~/.ipfs. func NewLocalApi() (*HttpApi, error) { baseDir := os.Getenv(EnvDir) if baseDir == "" { @@ -59,7 +59,7 @@ func NewLocalApi() (*HttpApi, error) { } // NewPathApi constructs new HttpApi by pulling api address from specified -// ipfspath. Api file should be located at $ipfspath/api +// ipfspath. Api file should be located at $ipfspath/api. func NewPathApi(ipfspath string) (*HttpApi, error) { a, err := ApiAddr(ipfspath) if err != nil { @@ -71,7 +71,7 @@ func NewPathApi(ipfspath string) (*HttpApi, error) { return NewApi(a) } -// ApiAddr reads api file in specified ipfs path +// ApiAddr reads api file in specified ipfs path. func ApiAddr(ipfspath string) (ma.Multiaddr, error) { baseDir, err := homedir.Expand(ipfspath) if err != nil { @@ -88,7 +88,7 @@ func ApiAddr(ipfspath string) (ma.Multiaddr, error) { return ma.NewMultiaddr(strings.TrimSpace(string(api))) } -// NewApi constructs HttpApi with specified endpoint +// NewApi constructs HttpApi with specified endpoint. func NewApi(a ma.Multiaddr) (*HttpApi, error) { c := &http.Client{ Transport: &http.Transport{ @@ -100,7 +100,7 @@ func NewApi(a ma.Multiaddr) (*HttpApi, error) { return NewApiWithClient(a, c) } -// NewApiWithClient constructs HttpApi with specified endpoint and custom http client +// NewApiWithClient constructs HttpApi with specified endpoint and custom http client. func NewApiWithClient(a ma.Multiaddr, c *http.Client) (*HttpApi, error) { _, url, err := manet.DialArgs(a) if err != nil { diff --git a/client/rpc/apifile.go b/client/rpc/apifile.go index 24e93a8347f..873a67b7be0 100644 --- a/client/rpc/apifile.go +++ b/client/rpc/apifile.go @@ -12,7 +12,7 @@ import ( "github.com/ipfs/go-cid" ) -const forwardSeekLimit = 1 << 14 //16k +const forwardSeekLimit = 1 << 14 // 16k func (api *UnixfsAPI) Get(ctx context.Context, p path.Path) (files.Node, error) { 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) { case io.SeekCurrent: offset = f.at + offset } - if f.at == offset { //noop + if f.at == offset { // noop return offset, nil } - if f.at < offset && offset-f.at < forwardSeekLimit { //forward skip + if f.at < offset && offset-f.at < forwardSeekLimit { // forward skip r, err := io.CopyN(io.Discard, f.r.Output, offset-f.at) f.at += r @@ -246,7 +246,6 @@ func (api *UnixfsAPI) getDir(ctx context.Context, p path.Path, size int64) (file resp, err := api.core().Request("ls", p.String()). Option("resolve-size", true). Option("stream", true).Send(ctx) - if err != nil { return nil, err } @@ -266,5 +265,7 @@ func (api *UnixfsAPI) getDir(ctx context.Context, p path.Path, size int64) (file return d, nil } -var _ files.File = &apiFile{} -var _ files.Directory = &apiDir{} +var ( + _ files.File = &apiFile{} + _ files.Directory = &apiDir{} +) diff --git a/client/rpc/block.go b/client/rpc/block.go index a11e5e6550a..2b0048380be 100644 --- a/client/rpc/block.go +++ b/client/rpc/block.go @@ -83,7 +83,7 @@ func (api *BlockAPI) Get(ctx context.Context, p path.Path) (io.Reader, error) { return nil, parseErrNotFoundWithFallbackToError(resp.Error) } - //TODO: make get return ReadCloser to avoid copying + // TODO: make get return ReadCloser to avoid copying defer resp.Close() b := new(bytes.Buffer) if _, err := io.Copy(b, resp.Output); err != nil { diff --git a/client/rpc/dag.go b/client/rpc/dag.go index 69f83abfed8..f4c9be351f2 100644 --- a/client/rpc/dag.go +++ b/client/rpc/dag.go @@ -14,9 +14,11 @@ import ( multicodec "github.com/multiformats/go-multicodec" ) -type httpNodeAdder HttpApi -type HttpDagServ httpNodeAdder -type pinningHttpNodeAdder httpNodeAdder +type ( + httpNodeAdder HttpApi + HttpDagServ httpNodeAdder + pinningHttpNodeAdder httpNodeAdder +) func (api *HttpDagServ) Get(ctx context.Context, c cid.Cid) (format.Node, error) { r, err := api.core().Block().Get(ctx, path.IpldPath(c)) @@ -114,7 +116,7 @@ func (api *HttpDagServ) Pinning() format.NodeAdder { } func (api *HttpDagServ) Remove(ctx context.Context, c cid.Cid) error { - return api.core().Block().Rm(ctx, path.IpldPath(c)) //TODO: should we force rm? + return api.core().Block().Rm(ctx, path.IpldPath(c)) // TODO: should we force rm? } func (api *HttpDagServ) RemoveMany(ctx context.Context, cids []cid.Cid) error { diff --git a/client/rpc/errors.go b/client/rpc/errors.go index dc5946be327..84340b550e2 100644 --- a/client/rpc/errors.go +++ b/client/rpc/errors.go @@ -68,7 +68,7 @@ func parseErrNotFound(msg string) (error, bool) { // Assume CIDs break on: // - Whitespaces: " \t\n\r\v\f" // - Semicolon: ";" this is to parse ipld.ErrNotFound wrapped in multierr -// - Double Quotes: "\"" this is for parsing %q and %#v formating +// - Double Quotes: "\"" this is for parsing %q and %#v formating. const cidBreakSet = " \t\n\r\v\f;\"" func parseIPLDErrNotFound(msg string) (error, bool) { @@ -139,7 +139,7 @@ func parseIPLDErrNotFound(msg string) (error, bool) { // This is a simple error type that just return msg as Error(). // But that also match ipld.ErrNotFound when called with Is(err). // That is needed to keep compatiblity with code that use string.Contains(err.Error(), "blockstore: block not found") -// and code using ipld.ErrNotFound +// and code using ipld.ErrNotFound. type blockstoreNotFoundMatchingIPLDErrNotFound struct { msg string } diff --git a/client/rpc/object.go b/client/rpc/object.go index 5860c7661a1..7464cea1a72 100644 --- a/client/rpc/object.go +++ b/client/rpc/object.go @@ -87,7 +87,7 @@ func (api *ObjectAPI) Data(ctx context.Context, p path.Path) (io.Reader, error) return nil, resp.Error } - //TODO: make Data return ReadCloser to avoid copying + // TODO: make Data return ReadCloser to avoid copying defer resp.Close() b := new(bytes.Buffer) if _, err := io.Copy(b, resp.Output); err != nil { diff --git a/client/rpc/path.go b/client/rpc/path.go index 6edf0e797c2..1b88eb07d26 100644 --- a/client/rpc/path.go +++ b/client/rpc/path.go @@ -15,7 +15,7 @@ func (api *HttpApi) ResolvePath(ctx context.Context, p path.Path) (path.Resolved RemPath string } - //TODO: this is hacky, fixing https://github.com/ipfs/go-ipfs/issues/5703 would help + // TODO: this is hacky, fixing https://github.com/ipfs/go-ipfs/issues/5703 would help var err error if p.Namespace() == "ipns" { diff --git a/client/rpc/pin.go b/client/rpc/pin.go index dc85b9f3080..e8aecf11cf6 100644 --- a/client/rpc/pin.go +++ b/client/rpc/pin.go @@ -112,7 +112,7 @@ func (api *PinAPI) Ls(ctx context.Context, opts ...caopts.PinLsOption) (<-chan i } // IsPinned returns whether or not the given cid is pinned -// and an explanation of why its pinned +// and an explanation of why its pinned. func (api *PinAPI) IsPinned(ctx context.Context, p path.Path, opts ...caopts.PinIsPinnedOption) (string, bool, error) { options, err := caopts.PinIsPinnedOptions(opts...) if err != nil { diff --git a/client/rpc/pubsub.go b/client/rpc/pubsub.go index a386c80a1d2..f255da5addf 100644 --- a/client/rpc/pubsub.go +++ b/client/rpc/pubsub.go @@ -152,7 +152,6 @@ func (api *PubsubAPI) Subscribe(ctx context.Context, topic string, opts ...caopt } */ resp, err := api.core().Request("pubsub/sub", toMultibase([]byte(topic))).Send(ctx) - if err != nil { return nil, err } @@ -207,7 +206,7 @@ func (api *PubsubAPI) core() *HttpApi { return (*HttpApi)(api) } -// Encodes bytes into URL-safe multibase that can be sent over HTTP RPC (URL or body) +// Encodes bytes into URL-safe multibase that can be sent over HTTP RPC (URL or body). func toMultibase(data []byte) string { mb, _ := mbase.Encode(mbase.Base64url, data) return mb diff --git a/client/rpc/response.go b/client/rpc/response.go index bad27477767..c47da4a685c 100644 --- a/client/rpc/response.go +++ b/client/rpc/response.go @@ -54,7 +54,7 @@ func (r *Response) Close() error { return nil } -// Cancel aborts running request (without draining request body) +// Cancel aborts running request (without draining request body). func (r *Response) Cancel() error { if r.Output != nil { return r.Output.Close() @@ -63,7 +63,7 @@ func (r *Response) Cancel() error { return nil } -// Decode reads request body and decodes it as json +// Decode reads request body and decodes it as json. func (r *Response) decode(dec interface{}) error { if r.Error != nil { return r.Error @@ -157,7 +157,6 @@ func (r *Request) Send(c *http.Client) (*Response, error) { } func (r *Request) getURL() string { - values := make(url.Values) for _, arg := range r.Args { values.Add("arg", arg) diff --git a/client/rpc/routing.go b/client/rpc/routing.go index a6c4f5c0865..babed15fb2a 100644 --- a/client/rpc/routing.go +++ b/client/rpc/routing.go @@ -49,7 +49,6 @@ func (api *RoutingAPI) Put(ctx context.Context, key string, value []byte, opts . Option("allow-offline", cfg.AllowOffline). FileBody(bytes.NewReader(value)). Send(ctx) - if err != nil { return err } diff --git a/cmd/ipfs/add_migrations.go b/cmd/ipfs/add_migrations.go index e0a5d710181..e0138112112 100644 --- a/cmd/ipfs/add_migrations.go +++ b/cmd/ipfs/add_migrations.go @@ -19,7 +19,7 @@ import ( "github.com/libp2p/go-libp2p/core/peer" ) -// addMigrations adds any migration downloaded by the fetcher to the IPFS node +// addMigrations adds any migration downloaded by the fetcher to the IPFS node. func addMigrations(ctx context.Context, node *core.IpfsNode, fetcher migrations.Fetcher, pin bool) error { var fetchers []migrations.Fetcher if mf, ok := fetcher.(*migrations.MultiFetcher); ok { @@ -63,7 +63,7 @@ func addMigrations(ctx context.Context, node *core.IpfsNode, fetcher migrations. return nil } -// addMigrationFiles adds the files at paths to IPFS, optionally pinning them +// addMigrationFiles adds the files at paths to IPFS, optionally pinning them. func addMigrationFiles(ctx context.Context, node *core.IpfsNode, paths []string, pin bool) error { if len(paths) == 0 { return nil diff --git a/cmd/ipfs/daemon.go b/cmd/ipfs/daemon.go index 5788bf3ce45..7be97e23ba1 100644 --- a/cmd/ipfs/daemon.go +++ b/cmd/ipfs/daemon.go @@ -73,7 +73,7 @@ const ( enableMultiplexKwd = "enable-mplex-experiment" agentVersionSuffix = "agent-version-suffix" // apiAddrKwd = "address-api" - // swarmAddrKwd = "address-swarm" + // swarmAddrKwd = "address-swarm". ) var daemonCmd = &cmds.Command{ @@ -389,7 +389,7 @@ func daemonFunc(req *cmds.Request, re cmds.ResponseEmitter, env cmds.Environment "pubsub": pubsub, "ipnsps": ipnsps, }, - //TODO(Kubuxu): refactor Online vs Offline by adding Permanent vs Ephemeral + // TODO(Kubuxu): refactor Online vs Offline by adding Permanent vs Ephemeral } routingOption, _ := req.Options[routingOptionKwd].(string) @@ -552,7 +552,7 @@ take effect. } // Add ipfs version info to prometheus metrics - var ipfsInfoMetric = promauto.NewGaugeVec(prometheus.GaugeOpts{ + ipfsInfoMetric := promauto.NewGaugeVec(prometheus.GaugeOpts{ Name: "ipfs_info", Help: "IPFS version information.", }, []string{"version", "commit"}) @@ -607,7 +607,6 @@ take effect. log.Error("failed to bootstrap (no peers found): consider updating Bootstrap or Peering section of your config") } }) - } // Hard deprecation notice if someone still uses IPFS_REUSEPORT @@ -627,7 +626,7 @@ take effect. return errs } -// serveHTTPApi collects options, creates listener, prints status message and starts serving requests +// serveHTTPApi collects options, creates listener, prints status message and starts serving requests. func serveHTTPApi(req *cmds.Request, cctx *oldcmds.Context) (<-chan error, error) { cfg, err := cctx.GetConfig() if err != nil { @@ -690,7 +689,7 @@ func serveHTTPApi(req *cmds.Request, cctx *oldcmds.Context) (<-chan error, error gatewayOpt = corehttp.GatewayOption("/ipfs", "/ipns") } - var opts = []corehttp.ServeOption{ + opts := []corehttp.ServeOption{ corehttp.MetricsCollectionOption("api"), corehttp.MetricsOpenCensusCollectionOption(), corehttp.MetricsOpenCensusDefaultPrometheusRegistry(), @@ -752,7 +751,7 @@ func rewriteMaddrToUseLocalhostIfItsAny(maddr ma.Multiaddr) ma.Multiaddr { } } -// printSwarmAddrs prints the addresses of the host +// printSwarmAddrs prints the addresses of the host. func printSwarmAddrs(node *core.IpfsNode) { if !node.IsOnline { fmt.Println("Swarm not listening, running in offline mode.") @@ -781,10 +780,9 @@ func printSwarmAddrs(node *core.IpfsNode) { for _, addr := range addrs { fmt.Printf("Swarm announcing %s\n", addr) } - } -// serveHTTPGateway collects options, creates listener, prints status message and starts serving requests +// serveHTTPGateway collects options, creates listener, prints status message and starts serving requests. func serveHTTPGateway(req *cmds.Request, cctx *oldcmds.Context) (<-chan error, error) { cfg, err := cctx.GetConfig() if err != nil { @@ -837,7 +835,7 @@ func serveHTTPGateway(req *cmds.Request, cctx *oldcmds.Context) (<-chan error, e cmdctx := *cctx cmdctx.Gateway = true - var opts = []corehttp.ServeOption{ + opts := []corehttp.ServeOption{ corehttp.MetricsCollectionOption("gateway"), corehttp.HostnameOption(), corehttp.GatewayOption("/ipfs", "/ipns"), @@ -891,7 +889,7 @@ func serveHTTPGateway(req *cmds.Request, cctx *oldcmds.Context) (<-chan error, e return errc, nil } -// collects options and opens the fuse mountpoint +// collects options and opens the fuse mountpoint. func mountFuse(req *cmds.Request, cctx *oldcmds.Context) error { cfg, err := cctx.GetConfig() if err != nil { diff --git a/cmd/ipfs/dnsresolve_test.go b/cmd/ipfs/dnsresolve_test.go index fcba5d69702..8ffa0ebdeb3 100644 --- a/cmd/ipfs/dnsresolve_test.go +++ b/cmd/ipfs/dnsresolve_test.go @@ -25,7 +25,8 @@ func makeResolver(t *testing.T, n uint8) *madns.Resolver { backend := &madns.MockResolver{ IP: map[string][]net.IPAddr{ "example.com": results, - }} + }, + } resolver, err := madns.NewResolver(madns.WithDefaultResolver(backend)) if err != nil { diff --git a/cmd/ipfs/init.go b/cmd/ipfs/init.go index 28845faa568..0c5223d7fce 100644 --- a/cmd/ipfs/init.go +++ b/cmd/ipfs/init.go @@ -194,7 +194,7 @@ func checkWritable(dir string) error { if os.IsNotExist(err) { // dir doesn't exist, check that we can create it - return os.Mkdir(dir, 0775) + return os.Mkdir(dir, 0o775) } if os.IsPermission(err) { diff --git a/cmd/ipfs/ipfs.go b/cmd/ipfs/ipfs.go index 24aea66c786..3b953c40c88 100644 --- a/cmd/ipfs/ipfs.go +++ b/cmd/ipfs/ipfs.go @@ -14,7 +14,7 @@ var Root = &cmds.Command{ Helptext: commands.Root.Helptext, } -// commandsClientCmd is the "ipfs commands" command for local cli +// commandsClientCmd is the "ipfs commands" command for local cli. var commandsClientCmd = commands.CommandsCmd(Root) // Commands in localCommands should always be run locally (even if daemon is running). diff --git a/cmd/ipfs/main.go b/cmd/ipfs/main.go index c1e5299322f..22fdca91b9d 100644 --- a/cmd/ipfs/main.go +++ b/cmd/ipfs/main.go @@ -39,11 +39,13 @@ import ( "go.opentelemetry.io/otel/trace" ) -// log is the command logger -var log = logging.Logger("cmd/ipfs") -var tracer trace.Tracer +// log is the command logger. +var ( + log = logging.Logger("cmd/ipfs") + tracer trace.Tracer +) -// declared as a var for testing purposes +// declared as a var for testing purposes. var dnsResolver = madns.DefaultResolver const ( @@ -73,7 +75,7 @@ func loadPlugins(repoPath string) (*loader.PluginLoader, error) { // - if user requests help, print it and exit. // - run the command invocation // - output the response -// - if anything fails, print error, maybe with help +// - if anything fails, print error, maybe with help. func main() { os.Exit(mainRet()) } diff --git a/cmd/ipfs/pinmfs.go b/cmd/ipfs/pinmfs.go index c2c0cb8b7f7..977d96ba0c4 100644 --- a/cmd/ipfs/pinmfs.go +++ b/cmd/ipfs/pinmfs.go @@ -18,7 +18,7 @@ import ( "github.com/ipfs/kubo/core" ) -// mfslog is the logger for remote mfs pinning +// mfslog is the logger for remote mfs pinning. var mfslog = logging.Logger("remotepinning/mfs") type lastPin struct { diff --git a/cmd/ipfs/runmain_test.go b/cmd/ipfs/runmain_test.go index d9187911207..4d73cfd4366 100644 --- a/cmd/ipfs/runmain_test.go +++ b/cmd/ipfs/runmain_test.go @@ -12,7 +12,7 @@ import ( // this abuses go so much that I felt dirty writing this code // but it is the only way to do it without writing custom compiler that would -// be a clone of go-build with go-test +// be a clone of go-build with go-test. func TestRunMain(t *testing.T) { args := flag.Args() os.Args = append([]string{os.Args[0]}, args...) @@ -20,7 +20,7 @@ func TestRunMain(t *testing.T) { p := os.Getenv("IPFS_COVER_RET_FILE") if len(p) != 0 { - os.WriteFile(p, []byte(fmt.Sprintf("%d\n", ret)), 0777) + os.WriteFile(p, []byte(fmt.Sprintf("%d\n", ret)), 0o777) } // close outputs so go testing doesn't print anything diff --git a/cmd/ipfs/util/ulimit.go b/cmd/ipfs/util/ulimit.go index e024ced8439..a00e810761d 100644 --- a/cmd/ipfs/util/ulimit.go +++ b/cmd/ipfs/util/ulimit.go @@ -14,19 +14,19 @@ var log = logging.Logger("ulimit") var ( supportsFDManagement = false - // getlimit returns the soft and hard limits of file descriptors counts + // getlimit returns the soft and hard limits of file descriptors counts. getLimit func() (uint64, uint64, error) - // set limit sets the soft and hard limits of file descriptors counts + // set limit sets the soft and hard limits of file descriptors counts. setLimit func(uint64, uint64) error ) -// minimum file descriptor limit before we complain +// minimum file descriptor limit before we complain. const minFds = 2048 // default max file descriptor limit. const maxFds = 8192 -// userMaxFDs returns the value of IPFS_FD_MAX +// userMaxFDs returns the value of IPFS_FD_MAX. func userMaxFDs() uint64 { // check if the IPFS_FD_MAX is set up and if it does // not have a valid fds number notify the user @@ -42,7 +42,7 @@ func userMaxFDs() uint64 { } // ManageFdLimit raise the current max file descriptor count -// of the process based on the IPFS_FD_MAX value +// of the process based on the IPFS_FD_MAX value. func ManageFdLimit() (changed bool, newLimit uint64, err error) { if !supportsFDManagement { return false, 0, nil diff --git a/cmd/ipfswatch/main.go b/cmd/ipfswatch/main.go index 9f2558e25ea..0f0283fb87c 100644 --- a/cmd/ipfswatch/main.go +++ b/cmd/ipfswatch/main.go @@ -24,9 +24,11 @@ import ( homedir "github.com/mitchellh/go-homedir" ) -var http = flag.Bool("http", false, "expose IPFS HTTP API") -var repoPath = flag.String("repo", os.Getenv("IPFS_PATH"), "IPFS_PATH to use") -var watchPath = flag.String("path", ".", "the path to watch") +var ( + http = flag.Bool("http", false, "expose IPFS HTTP API") + repoPath = flag.String("repo", os.Getenv("IPFS_PATH"), "IPFS_PATH to use") + watchPath = flag.String("path", ".", "the path to watch") +) func main() { flag.Parse() @@ -52,7 +54,6 @@ func main() { } func run(ipfsPath, watchPath string) error { - proc := process.WithParent(process.Background()) log.Printf("running IPFSWatch on '%s' using repo at '%s'...", watchPath, ipfsPath) @@ -93,7 +94,7 @@ func run(ipfsPath, watchPath string) error { if *http { addr := "/ip4/127.0.0.1/tcp/5001" - var opts = []corehttp.ServeOption{ + opts := []corehttp.ServeOption{ corehttp.GatewayOption("/ipfs", "/ipns"), corehttp.WebUIOption, corehttp.CommandsOption(cmdCtx(node, ipfsPath)), diff --git a/commands/context.go b/commands/context.go index fa10228190d..855db1afe53 100644 --- a/commands/context.go +++ b/commands/context.go @@ -19,7 +19,7 @@ import ( var log = logging.Logger("command") -// Context represents request context +// Context represents request context. type Context struct { ConfigRoot string ReqLog *ReqLog @@ -54,7 +54,7 @@ func (c *Context) GetNode() (*core.IpfsNode, error) { } // GetAPI returns CoreAPI instance backed by ipfs node. -// It may construct the node with the provided function +// It may construct the node with the provided function. func (c *Context) GetAPI() (coreiface.CoreAPI, error) { if c.api == nil { n, err := c.GetNode() diff --git a/commands/reqlog.go b/commands/reqlog.go index 14c10a7c0f8..444bbcd3e21 100644 --- a/commands/reqlog.go +++ b/commands/reqlog.go @@ -5,7 +5,7 @@ import ( "time" ) -// ReqLogEntry is an entry in the request log +// ReqLogEntry is an entry in the request log. type ReqLogEntry struct { StartTime time.Time EndTime time.Time @@ -18,14 +18,14 @@ type ReqLogEntry struct { log *ReqLog } -// Copy returns a copy of the ReqLogEntry +// Copy returns a copy of the ReqLogEntry. func (r *ReqLogEntry) Copy() *ReqLogEntry { out := *r out.log = nil return &out } -// ReqLog is a log of requests +// ReqLog is a log of requests. type ReqLog struct { Requests []*ReqLogEntry nextID int @@ -33,7 +33,7 @@ type ReqLog struct { keep time.Duration } -// AddEntry adds an entry to the log +// AddEntry adds an entry to the log. func (rl *ReqLog) AddEntry(rle *ReqLogEntry) { rl.lock.Lock() defer rl.lock.Unlock() @@ -47,7 +47,7 @@ func (rl *ReqLog) AddEntry(rle *ReqLogEntry) { } } -// ClearInactive removes stale entries +// ClearInactive removes stale entries. func (rl *ReqLog) ClearInactive() { rl.lock.Lock() defer rl.lock.Unlock() @@ -79,14 +79,14 @@ func (rl *ReqLog) cleanup() { rl.Requests = rl.Requests[:i] } -// SetKeepTime sets a duration after which an entry will be considered inactive +// SetKeepTime sets a duration after which an entry will be considered inactive. func (rl *ReqLog) SetKeepTime(t time.Duration) { rl.lock.Lock() defer rl.lock.Unlock() rl.keep = t } -// Report generates a copy of all the entries in the requestlog +// Report generates a copy of all the entries in the requestlog. func (rl *ReqLog) Report() []*ReqLogEntry { rl.lock.Lock() defer rl.lock.Unlock() @@ -99,7 +99,7 @@ func (rl *ReqLog) Report() []*ReqLogEntry { return out } -// Finish marks an entry in the log as finished +// Finish marks an entry in the log as finished. func (rl *ReqLog) Finish(rle *ReqLogEntry) { rl.lock.Lock() defer rl.lock.Unlock() diff --git a/config/autonat.go b/config/autonat.go index 64856faa680..eb87b48e6f4 100644 --- a/config/autonat.go +++ b/config/autonat.go @@ -64,7 +64,7 @@ type AutoNATConfig struct { Throttle *AutoNATThrottleConfig `json:",omitempty"` } -// AutoNATThrottleConfig configures the throttle limites +// AutoNATThrottleConfig configures the throttle limites. type AutoNATThrottleConfig struct { // GlobalLimit and PeerLimit sets the global and per-peer dialback // limits. The AutoNAT service will only perform the specified number of diff --git a/config/config.go b/config/config.go index bc8ea371f17..035fbe2966c 100644 --- a/config/config.go +++ b/config/config.go @@ -41,17 +41,17 @@ type Config struct { } const ( - // DefaultPathName is the default config dir name + // DefaultPathName is the default config dir name. DefaultPathName = ".ipfs" // DefaultPathRoot is the path to the default config dir location. DefaultPathRoot = "~/" + DefaultPathName - // DefaultConfigFile is the filename of the configuration file + // DefaultConfigFile is the filename of the configuration file. DefaultConfigFile = "config" // EnvDir is the environment variable used to change the path root. EnvDir = "IPFS_PATH" ) -// PathRoot returns the default configuration root directory +// PathRoot returns the default configuration root directory. func PathRoot() (string, error) { dir := os.Getenv(EnvDir) var err error @@ -95,7 +95,7 @@ func Filename(configroot, userConfigFile string) (string, error) { return userConfigFile, nil } -// HumanOutput gets a config value ready for printing +// HumanOutput gets a config value ready for printing. func HumanOutput(value interface{}) ([]byte, error) { s, ok := value.(string) if ok { @@ -104,7 +104,7 @@ func HumanOutput(value interface{}) ([]byte, error) { return Marshal(value) } -// Marshal configuration with JSON +// Marshal configuration with JSON. func Marshal(value interface{}) ([]byte, error) { // need to prettyprint, hence MarshalIndent, instead of Encoder return json.MarshalIndent(value, "", " ") diff --git a/config/datastore.go b/config/datastore.go index 2b2bcb51828..1a5994a1750 100644 --- a/config/datastore.go +++ b/config/datastore.go @@ -26,7 +26,7 @@ type Datastore struct { } // DataStorePath returns the default data store path given a configuration root -// (set an empty string to have the default configuration root) +// (set an empty string to have the default configuration root). func DataStorePath(configroot string) (string, error) { return Path(configroot, DefaultDataStoreDirectory) } diff --git a/config/dns.go b/config/dns.go index 444d9908897..8e1fc85a5d8 100644 --- a/config/dns.go +++ b/config/dns.go @@ -1,6 +1,6 @@ package config -// DNS specifies DNS resolution rules using custom resolvers +// DNS specifies DNS resolution rules using custom resolvers. type DNS struct { // Resolvers is a map of FQDNs to URLs for custom DNS resolution. // URLs starting with `https://` indicate DoH endpoints. diff --git a/config/gateway.go b/config/gateway.go index 816b1f48d23..a655828496e 100644 --- a/config/gateway.go +++ b/config/gateway.go @@ -37,7 +37,6 @@ type GatewaySpec struct { // Gateway contains options for the HTTP gateway server. type Gateway struct { - // HTTPHeaders configures the headers that should be returned by this // gateway. HTTPHeaders map[string][]string // HTTP headers to return with the gateway diff --git a/config/identity.go b/config/identity.go index 6117365c914..5b661dfb454 100644 --- a/config/identity.go +++ b/config/identity.go @@ -6,9 +6,11 @@ import ( ic "github.com/libp2p/go-libp2p/core/crypto" ) -const IdentityTag = "Identity" -const PrivKeyTag = "PrivKey" -const PrivKeySelector = IdentityTag + "." + PrivKeyTag +const ( + IdentityTag = "Identity" + PrivKeyTag = "PrivKey" + PrivKeySelector = IdentityTag + "." + PrivKeyTag +) // Identity tracks the configuration of the local node's identity. type Identity struct { @@ -16,7 +18,7 @@ type Identity struct { PrivKey string `json:",omitempty"` } -// DecodePrivateKey is a helper to decode the users PrivateKey +// DecodePrivateKey is a helper to decode the users PrivateKey. func (i *Identity) DecodePrivateKey(passphrase string) (ic.PrivKey, error) { pkb, err := base64.StdEncoding.DecodeString(i.PrivKey) if err != nil { diff --git a/config/init.go b/config/init.go index a6e3c46cc7a..9b0bf9dbf47 100644 --- a/config/init.go +++ b/config/init.go @@ -90,15 +90,15 @@ func InitWithIdentity(identity Identity) (*Config, error) { } // DefaultConnMgrHighWater is the default value for the connection managers -// 'high water' mark +// 'high water' mark. const DefaultConnMgrHighWater = 96 // DefaultConnMgrLowWater is the default value for the connection managers 'low -// water' mark +// water' mark. const DefaultConnMgrLowWater = 32 // DefaultConnMgrGracePeriod is the default value for the connection managers -// grace period +// grace period. const DefaultConnMgrGracePeriod = time.Second * 20 // DefaultConnMgrType is the default value for the connection managers diff --git a/config/migration.go b/config/migration.go index 27d4b3c7025..e172988a9c6 100644 --- a/config/migration.go +++ b/config/migration.go @@ -5,7 +5,7 @@ const DefaultMigrationKeep = "cache" var DefaultMigrationDownloadSources = []string{"HTTPS", "IPFS"} // Migration configures how migrations are downloaded and if the downloads are -// added to IPFS locally +// added to IPFS locally. type Migration struct { // Sources in order of preference, where "IPFS" means use IPFS and "HTTPS" // means use default gateways. Any other values are interpreted as diff --git a/config/mounts.go b/config/mounts.go index b23d30b2ef3..dfdd1e5bf6c 100644 --- a/config/mounts.go +++ b/config/mounts.go @@ -1,6 +1,6 @@ package config -// Mounts stores the (string) mount points +// Mounts stores the (string) mount points. type Mounts struct { IPFS string IPNS string diff --git a/config/profile.go b/config/profile.go index 1a401391846..83d53359dae 100644 --- a/config/profile.go +++ b/config/profile.go @@ -6,10 +6,10 @@ import ( "time" ) -// Transformer is a function which takes configuration and applies some filter to it +// Transformer is a function which takes configuration and applies some filter to it. type Transformer func(c *Config) error -// Profile contains the profile transformer the description of the profile +// Profile contains the profile transformer the description of the profile. type Profile struct { // Description briefly describes the functionality of the profile. Description string @@ -43,7 +43,7 @@ var defaultServerFilters = []string{ "/ip6/fe80::/ipcidr/10", } -// Profiles is a map holding configuration transformers. Docs are in docs/config.md +// Profiles is a map holding configuration transformers. Docs are in docs/config.md. var Profiles = map[string]Profile{ "server": { Description: `Disables local host discovery, recommended when diff --git a/config/reprovider.go b/config/reprovider.go index 19ee1c58d9c..dae9ae6dee9 100644 --- a/config/reprovider.go +++ b/config/reprovider.go @@ -2,8 +2,10 @@ package config import "time" -const DefaultReproviderInterval = time.Hour * 22 // https://github.com/ipfs/kubo/pull/9326 -const DefaultReproviderStrategy = "all" +const ( + DefaultReproviderInterval = time.Hour * 22 // https://github.com/ipfs/kubo/pull/9326 + DefaultReproviderStrategy = "all" +) type Reprovider struct { Interval *OptionalDuration `json:",omitempty"` // Time period to reprovide locally stored objects to the network diff --git a/config/routing.go b/config/routing.go index ede8f0f9ea9..60faa605cce 100644 --- a/config/routing.go +++ b/config/routing.go @@ -6,7 +6,7 @@ import ( "runtime" ) -// Routing defines configuration options for libp2p routing +// Routing defines configuration options for libp2p routing. type Routing struct { // Type sets default daemon routing mode. // @@ -23,7 +23,6 @@ type Routing struct { } type Router struct { - // Router type ID. See RouterType for more info. Type RouterType @@ -32,11 +31,12 @@ type Router struct { Parameters interface{} } -type Routers map[string]RouterParser -type Methods map[MethodName]Method +type ( + Routers map[string]RouterParser + Methods map[MethodName]Method +) func (m Methods) Check() error { - // Check supported methods for _, mn := range MethodNameList { _, ok := m[mn] diff --git a/config/routing_test.go b/config/routing_test.go index 4dfc54ccbd2..87a4f8cce1b 100644 --- a/config/routing_test.go +++ b/config/routing_test.go @@ -23,42 +23,46 @@ func TestRouterParameters(t *testing.T) { PublicIPNetwork: false, }, }}, - "router-parallel": {Router{ - Type: RouterTypeParallel, - Parameters: ComposableRouterParams{ - Routers: []ConfigRouter{ - { - RouterName: "router-dht", - Timeout: Duration{10 * time.Second}, - IgnoreErrors: true, - }, - { - RouterName: "router-dht", - Timeout: Duration{10 * time.Second}, - IgnoreErrors: false, - ExecuteAfter: &OptionalDuration{&sec}, + "router-parallel": { + Router{ + Type: RouterTypeParallel, + Parameters: ComposableRouterParams{ + Routers: []ConfigRouter{ + { + RouterName: "router-dht", + Timeout: Duration{10 * time.Second}, + IgnoreErrors: true, + }, + { + RouterName: "router-dht", + Timeout: Duration{10 * time.Second}, + IgnoreErrors: false, + ExecuteAfter: &OptionalDuration{&sec}, + }, }, + Timeout: &OptionalDuration{&min}, }, - Timeout: &OptionalDuration{&min}, - }}, + }, }, - "router-sequential": {Router{ - Type: RouterTypeSequential, - Parameters: ComposableRouterParams{ - Routers: []ConfigRouter{ - { - RouterName: "router-dht", - Timeout: Duration{10 * time.Second}, - IgnoreErrors: true, - }, - { - RouterName: "router-dht", - Timeout: Duration{10 * time.Second}, - IgnoreErrors: false, + "router-sequential": { + Router{ + Type: RouterTypeSequential, + Parameters: ComposableRouterParams{ + Routers: []ConfigRouter{ + { + RouterName: "router-dht", + Timeout: Duration{10 * time.Second}, + IgnoreErrors: true, + }, + { + RouterName: "router-dht", + Timeout: Duration{10 * time.Second}, + IgnoreErrors: false, + }, }, + Timeout: &OptionalDuration{&min}, }, - Timeout: &OptionalDuration{&min}, - }}, + }, }, }, Methods: Methods{ diff --git a/config/serialize/serialize.go b/config/serialize/serialize.go index d20e48118f5..616e529cbd0 100644 --- a/config/serialize/serialize.go +++ b/config/serialize/serialize.go @@ -35,12 +35,12 @@ func ReadConfigFile(filename string, cfg interface{}) error { // WriteConfigFile writes the config from `cfg` into `filename`. func WriteConfigFile(filename string, cfg interface{}) error { - err := os.MkdirAll(filepath.Dir(filename), 0755) + err := os.MkdirAll(filepath.Dir(filename), 0o755) if err != nil { return err } - f, err := atomicfile.New(filename, 0600) + f, err := atomicfile.New(filename, 0o600) if err != nil { return err } @@ -49,7 +49,7 @@ func WriteConfigFile(filename string, cfg interface{}) error { return encode(f, cfg) } -// encode configuration with JSON +// encode configuration with JSON. func encode(w io.Writer, value interface{}) error { // need to prettyprint, hence MarshalIndent, instead of Encoder buf, err := config.Marshal(value) diff --git a/config/serialize/serialize_test.go b/config/serialize/serialize_test.go index cc161c80dbd..bf4b8b16f70 100644 --- a/config/serialize/serialize_test.go +++ b/config/serialize/serialize_test.go @@ -30,7 +30,7 @@ func TestConfig(t *testing.T) { } if runtime.GOOS != "windows" { // see https://golang.org/src/os/types_windows.go - if g := st.Mode().Perm(); g&0117 != 0 { + if g := st.Mode().Perm(); g&0o117 != 0 { t.Fatalf("config file should not be executable or accessible to world: %v", g) } } diff --git a/config/swarm.go b/config/swarm.go index cbd46e5e1fd..45b8a9a5205 100644 --- a/config/swarm.go +++ b/config/swarm.go @@ -127,7 +127,7 @@ type Transports struct { } } -// ConnMgr defines configuration options for the libp2p connection manager +// ConnMgr defines configuration options for the libp2p connection manager. type ConnMgr struct { Type *OptionalString `json:",omitempty"` LowWater *OptionalInteger `json:",omitempty"` diff --git a/config/types.go b/config/types.go index 2171a53f5bd..131324efe2d 100644 --- a/config/types.go +++ b/config/types.go @@ -42,8 +42,10 @@ func (o Strings) MarshalJSON() ([]byte, error) { } } -var _ json.Unmarshaler = (*Strings)(nil) -var _ json.Marshaler = (*Strings)(nil) +var ( + _ json.Unmarshaler = (*Strings)(nil) + _ json.Marshaler = (*Strings)(nil) +) // Flag represents a ternary value: false (-1), default (0), or true (+1). // @@ -113,8 +115,10 @@ func (f Flag) String() string { } } -var _ json.Unmarshaler = (*Flag)(nil) -var _ json.Marshaler = (*Flag)(nil) +var ( + _ json.Unmarshaler = (*Flag)(nil) + _ json.Marshaler = (*Flag)(nil) +) // Priority represents a value with a priority where 0 means "default" and -1 // means "disabled". @@ -210,17 +214,19 @@ func (p Priority) String() string { } } -var _ json.Unmarshaler = (*Priority)(nil) -var _ json.Marshaler = (*Priority)(nil) +var ( + _ json.Unmarshaler = (*Priority)(nil) + _ json.Marshaler = (*Priority)(nil) +) // OptionalDuration wraps time.Duration to provide json serialization and deserialization. // -// NOTE: the zero value encodes to JSON nill +// NOTE: the zero value encodes to JSON nill. type OptionalDuration struct { value *time.Duration } -// NewOptionalDuration returns an OptionalDuration from a string +// NewOptionalDuration returns an OptionalDuration from a string. func NewOptionalDuration(d time.Duration) *OptionalDuration { return &OptionalDuration{value: &d} } @@ -266,8 +272,10 @@ func (d OptionalDuration) String() string { return d.value.String() } -var _ json.Unmarshaler = (*OptionalDuration)(nil) -var _ json.Marshaler = (*OptionalDuration)(nil) +var ( + _ json.Unmarshaler = (*OptionalDuration)(nil) + _ json.Marshaler = (*OptionalDuration)(nil) +) type Duration struct { time.Duration @@ -298,17 +306,19 @@ func (d *Duration) UnmarshalJSON(b []byte) error { } } -var _ json.Unmarshaler = (*Duration)(nil) -var _ json.Marshaler = (*Duration)(nil) +var ( + _ json.Unmarshaler = (*Duration)(nil) + _ json.Marshaler = (*Duration)(nil) +) // OptionalInteger represents an integer that has a default value // -// When encoded in json, Default is encoded as "null" +// When encoded in json, Default is encoded as "null". type OptionalInteger struct { value *int64 } -// NewOptionalInteger returns an OptionalInteger from a int64 +// NewOptionalInteger returns an OptionalInteger from a int64. func NewOptionalInteger(v int64) *OptionalInteger { return &OptionalInteger{value: &v} } @@ -321,7 +331,7 @@ func (p *OptionalInteger) WithDefault(defaultValue int64) (value int64) { return *p.value } -// IsDefault returns if this is a default optional integer +// IsDefault returns if this is a default optional integer. func (p *OptionalInteger) IsDefault() bool { return p == nil || p.value == nil } @@ -355,17 +365,19 @@ func (p OptionalInteger) String() string { return fmt.Sprintf("%d", *p.value) } -var _ json.Unmarshaler = (*OptionalInteger)(nil) -var _ json.Marshaler = (*OptionalInteger)(nil) +var ( + _ json.Unmarshaler = (*OptionalInteger)(nil) + _ json.Marshaler = (*OptionalInteger)(nil) +) // OptionalString represents a string that has a default value // -// When encoded in json, Default is encoded as "null" +// When encoded in json, Default is encoded as "null". type OptionalString struct { value *string } -// NewOptionalString returns an OptionalString from a string +// NewOptionalString returns an OptionalString from a string. func NewOptionalString(s string) *OptionalString { return &OptionalString{value: &s} } @@ -378,7 +390,7 @@ func (p *OptionalString) WithDefault(defaultValue string) (value string) { return *p.value } -// IsDefault returns if this is a default optional integer +// IsDefault returns if this is a default optional integer. func (p *OptionalString) IsDefault() bool { return p == nil || p.value == nil } @@ -412,8 +424,10 @@ func (p OptionalString) String() string { return *p.value } -var _ json.Unmarshaler = (*OptionalInteger)(nil) -var _ json.Marshaler = (*OptionalInteger)(nil) +var ( + _ json.Unmarshaler = (*OptionalInteger)(nil) + _ json.Marshaler = (*OptionalInteger)(nil) +) type swarmLimits doNotUse diff --git a/config/types_test.go b/config/types_test.go index caef2b112c0..7ea7506f147 100644 --- a/config/types_test.go +++ b/config/types_test.go @@ -129,7 +129,6 @@ func TestOneStrings(t *testing.T) { out, err := json.Marshal(Strings{"one"}) if err != nil { t.Fatal(err) - } expected := "\"one\"" if string(out) != expected { @@ -141,7 +140,6 @@ func TestNoStrings(t *testing.T) { out, err := json.Marshal(Strings{}) if err != nil { t.Fatal(err) - } expected := "null" if string(out) != expected { @@ -153,7 +151,6 @@ func TestManyStrings(t *testing.T) { out, err := json.Marshal(Strings{"one", "two"}) if err != nil { t.Fatal(err) - } expected := "[\"one\",\"two\"]" if string(out) != expected { diff --git a/core/bootstrap/bootstrap.go b/core/bootstrap/bootstrap.go index b566e0e978e..ed95d74e18b 100644 --- a/core/bootstrap/bootstrap.go +++ b/core/bootstrap/bootstrap.go @@ -85,7 +85,6 @@ func BootstrapConfigWithPeers(pis []peer.AddrInfo) BootstrapConfig { // connections to well-known bootstrap peers. It also kicks off subsystem // bootstrapping (i.e. routing). func Bootstrap(id peer.ID, host host.Host, rt routing.Routing, cfg BootstrapConfig) (io.Closer, error) { - // make a signal to wait for one bootstrap round to complete. doneWithRound := make(chan struct{}) @@ -219,7 +218,6 @@ func saveConnectedPeersAsTemporaryBootstrap(ctx context.Context, host host.Host, // Peers can be original bootstrap or temporary ones (drawn from a list of // persisted previously connected peers). func bootstrapRound(ctx context.Context, host host.Host, cfg BootstrapConfig) error { - ctx, cancel := context.WithTimeout(ctx, cfg.ConnectionTimeout) defer cancel() id := host.ID() diff --git a/core/commands/bootstrap.go b/core/commands/bootstrap.go index 07cdcbe7967..decf2b27167 100644 --- a/core/commands/bootstrap.go +++ b/core/commands/bootstrap.go @@ -374,9 +374,7 @@ func bootstrapRemove(r repo.Repo, cfg *config.Config, toRemove []string) ([]stri removed = append(removed, p) continue } - var ( - keptAddrs, removedAddrs []ma.Multiaddr - ) + var keptAddrs, removedAddrs []ma.Multiaddr // remove specific addresses filter: for _, addr := range p.Addrs { diff --git a/core/commands/cmdenv/cidbase.go b/core/commands/cmdenv/cidbase.go index 32f2c2157de..55815f52427 100644 --- a/core/commands/cmdenv/cidbase.go +++ b/core/commands/cmdenv/cidbase.go @@ -10,8 +10,10 @@ import ( mbase "github.com/multiformats/go-multibase" ) -var OptionCidBase = cmds.StringOption("cid-base", "Multibase encoding used for version 1 CIDs in output.") -var OptionUpgradeCidV0InOutput = cmds.BoolOption("upgrade-cidv0-in-output", "Upgrade version 0 to version 1 CIDs in output.") +var ( + OptionCidBase = cmds.StringOption("cid-base", "Multibase encoding used for version 1 CIDs in output.") + OptionUpgradeCidV0InOutput = cmds.BoolOption("upgrade-cidv0-in-output", "Upgrade version 0 to version 1 CIDs in output.") +) // GetCidEncoder processes the `cid-base` and `output-cidv1` options and // returns a encoder to use based on those parameters. diff --git a/core/commands/cmdutils/utils.go b/core/commands/cmdutils/utils.go index 9b498933b6a..954f476b6bf 100644 --- a/core/commands/cmdutils/utils.go +++ b/core/commands/cmdutils/utils.go @@ -47,5 +47,4 @@ func CheckBlockSize(req *cmds.Request, size uint64) error { 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") } return nil - } diff --git a/core/commands/commands_test.go b/core/commands/commands_test.go index bf1b7645085..0f2b0721b3c 100644 --- a/core/commands/commands_test.go +++ b/core/commands/commands_test.go @@ -71,6 +71,7 @@ func TestROCommands(t *testing.T) { } } } + func TestCommands(t *testing.T) { list := []string{ "/add", diff --git a/core/commands/completion.go b/core/commands/completion.go index c4fb1ba4142..8babaac36e3 100644 --- a/core/commands/completion.go +++ b/core/commands/completion.go @@ -208,7 +208,6 @@ complete -c ipfs --keep-order --no-files {{ template "command" . }} `)) - } // writeBashCompletions generates a bash completion script for the given command tree. diff --git a/core/commands/config.go b/core/commands/config.go index 4d2ea4f0d95..b2455102747 100644 --- a/core/commands/config.go +++ b/core/commands/config.go @@ -581,5 +581,4 @@ func getRemotePinningServices(r repo.Repo) (map[string]config.RemotePinningServi } } return oldServices, nil - } diff --git a/core/commands/config_test.go b/core/commands/config_test.go index 9e244f54ff1..5eb79c15349 100644 --- a/core/commands/config_test.go +++ b/core/commands/config_test.go @@ -12,6 +12,5 @@ func TestScrubMapInternalDelete(t *testing.T) { } if len(m) != 0 { t.Errorf("expecting an empty map, got a non-empty map") - } } diff --git a/core/commands/dag/dag.go b/core/commands/dag/dag.go index 41fde70e506..ac6f25d7d62 100644 --- a/core/commands/dag/dag.go +++ b/core/commands/dag/dag.go @@ -13,9 +13,9 @@ import ( cid "github.com/ipfs/go-cid" cidenc "github.com/ipfs/go-cidutil/cidenc" cmds "github.com/ipfs/go-ipfs-cmds" - //gipfree "github.com/ipld/go-ipld-prime/impl/free" - //gipselector "github.com/ipld/go-ipld-prime/traversal/selector" - //gipselectorbuilder "github.com/ipld/go-ipld-prime/traversal/selector/builder" + // gipfree "github.com/ipld/go-ipld-prime/impl/free" + // gipselector "github.com/ipld/go-ipld-prime/traversal/selector" + // gipselectorbuilder "github.com/ipld/go-ipld-prime/traversal/selector/builder" ) const ( @@ -209,7 +209,6 @@ Specification of CAR formats: https://ipld.io/specs/transport/car/ Run: dagImport, Encoders: cmds.EncoderMap{ cmds.Text: cmds.MakeTypedEncoder(func(req *cmds.Request, w io.Writer, event *CarImportOutput) error { - silent, _ := req.Options[silentOptionName].(bool) if silent { return nil @@ -343,9 +342,11 @@ func (s *DagStatSummary) String() string { func (s *DagStatSummary) incrementTotalSize(size uint64) { s.TotalSize += size } + func (s *DagStatSummary) incrementRedundantSize(size uint64) { s.redundantSize += size } + func (s *DagStatSummary) appendStats(stats *DagStat) { s.DagStatsArray = append(s.DagStatsArray, stats) } diff --git a/core/commands/dag/export.go b/core/commands/dag/export.go index 337d8ce8fb7..d46fa6e21bf 100644 --- a/core/commands/dag/export.go +++ b/core/commands/dag/export.go @@ -79,7 +79,6 @@ func dagExport(req *cmds.Request, res cmds.ResponseEmitter, env cmds.Environment } func finishCLIExport(res cmds.Response, re cmds.ResponseEmitter) error { - var showProgress bool val, specified := res.Request().Options[progressOptionName] if !specified { diff --git a/core/commands/external.go b/core/commands/external.go index 0eb4de03641..65ddcea4d9f 100644 --- a/core/commands/external.go +++ b/core/commands/external.go @@ -41,7 +41,7 @@ func ExternalBinary(instructions string) *cmds.Command { cmd := exec.Command(binname, req.Arguments...) // TODO: make commands lib be able to pass stdin through daemon - //cmd.Stdin = req.Stdin() + // cmd.Stdin = req.Stdin() cmd.Stdin = io.LimitReader(nil, 0) cmd.Stdout = w cmd.Stderr = w diff --git a/core/commands/files.go b/core/commands/files.go index 9c0c6e5a968..ce1cf1cfc81 100644 --- a/core/commands/files.go +++ b/core/commands/files.go @@ -88,8 +88,10 @@ const ( filesHashOptionName = "hash" ) -var cidVersionOption = cmds.IntOption(filesCidVersionOptionName, "cid-ver", "Cid version to use. (experimental)") -var hashOption = cmds.StringOption(filesHashOptionName, "Hash function to use. Will set Cid version to 1 if used. (experimental)") +var ( + cidVersionOption = cmds.IntOption(filesCidVersionOptionName, "cid-ver", "Cid version to use. (experimental)") + hashOption = cmds.StringOption(filesHashOptionName, "Hash function to use. Will set Cid version to 1 if used. (experimental)") +) var errFormat = errors.New("format was set by multiple options. Only one format option is allowed") @@ -131,7 +133,6 @@ var filesStatCmd = &cmds.Command{ cmds.BoolOption(filesWithLocalOptionName, "Compute the amount of the dag that is local, and if possible the total size"), }, Run: func(req *cmds.Request, res cmds.ResponseEmitter, env cmds.Environment) error { - _, err := statGetFormatOptions(req) if err != nil { return cmds.Errorf(cmds.ErrClient, err.Error()) @@ -225,7 +226,6 @@ func moreThanOne(a, b, c bool) bool { } func statGetFormatOptions(req *cmds.Request) (string, error) { - hash, _ := req.Options[filesHashOptionName].(bool) size, _ := req.Options[filesSizeOptionName].(bool) format, _ := req.Options[filesFormatOptionName].(string) @@ -307,7 +307,6 @@ func walkBlock(ctx context.Context, dagserv ipld.DAGService, nd ipld.Node) (bool } childLocal, childLocalSize, err := walkBlock(ctx, dagserv, child) - if err != nil { return local, sizeLocal, err } diff --git a/core/commands/keystore.go b/core/commands/keystore.go index ed0d5d4e9c5..d68801cad46 100644 --- a/core/commands/keystore.go +++ b/core/commands/keystore.go @@ -118,7 +118,6 @@ var keyGenCmd = &cmds.Command{ } key, err := api.Key().Generate(req.Context, name, opts...) - if err != nil { return err } @@ -211,7 +210,6 @@ elsewhere. For example, using openssl to get a PEM with public key: stdKey, err := crypto.PrivKeyToStdKey(sk) if err != nil { return fmt.Errorf("converting libp2p private key to std Go key: %w", err) - } // For some reason the ed25519.PrivateKey does not use pointer // 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: sk, _, err = crypto.KeyPairFromStdKey(stdKey) if err != nil { return fmt.Errorf("converting std Go key to libp2p key: %w", err) - } case keyFormatLibp2pCleartextOption: sk, err = crypto.UnmarshalPrivateKey(data) diff --git a/core/commands/name/publish.go b/core/commands/name/publish.go index bb4a4b70887..6cc51df14bd 100644 --- a/core/commands/name/publish.go +++ b/core/commands/name/publish.go @@ -15,9 +15,7 @@ import ( ke "github.com/ipfs/kubo/core/commands/keyencode" ) -var ( - errAllowOffline = errors.New("can't publish while offline: pass `--allow-offline` to override") -) +var errAllowOffline = errors.New("can't publish while offline: pass `--allow-offline` to override") const ( ipfsPathOptionName = "ipfs-path" diff --git a/core/commands/p2p.go b/core/commands/p2p.go index 7aaa7fee2a9..7b8b416e59c 100644 --- a/core/commands/p2p.go +++ b/core/commands/p2p.go @@ -370,9 +370,7 @@ var p2pCloseCmd = &cmds.Command{ proto := protocol.ID(protoOpt) - var ( - target, listen ma.Multiaddr - ) + var target, listen ma.Multiaddr if l { listen, err = ma.NewMultiaddr(listenOpt) diff --git a/core/commands/pin/remotepin.go b/core/commands/pin/remotepin.go index bbec1a73d46..2fe615c147b 100644 --- a/core/commands/pin/remotepin.go +++ b/core/commands/pin/remotepin.go @@ -54,16 +54,18 @@ var remotePinServiceCmd = &cmds.Command{ }, } -const pinNameOptionName = "name" -const pinCIDsOptionName = "cid" -const pinStatusOptionName = "status" -const pinServiceNameOptionName = "service" -const pinServiceNameArgName = pinServiceNameOptionName -const pinServiceEndpointArgName = "endpoint" -const pinServiceKeyArgName = "key" -const pinServiceStatOptionName = "stat" -const pinBackgroundOptionName = "background" -const pinForceOptionName = "force" +const ( + pinNameOptionName = "name" + pinCIDsOptionName = "cid" + pinStatusOptionName = "status" + pinServiceNameOptionName = "service" + pinServiceNameArgName = pinServiceNameOptionName + pinServiceEndpointArgName = "endpoint" + pinServiceKeyArgName = "key" + pinServiceStatOptionName = "stat" + pinBackgroundOptionName = "background" + pinForceOptionName = "force" +) type RemotePinOutput struct { Status string diff --git a/core/commands/pin/remotepin_test.go b/core/commands/pin/remotepin_test.go index d1dfa8fd5e4..98bb707a804 100644 --- a/core/commands/pin/remotepin_test.go +++ b/core/commands/pin/remotepin_test.go @@ -63,5 +63,4 @@ func TestNormalizeEndpoint(t *testing.T) { continue } } - } diff --git a/core/commands/root.go b/core/commands/root.go index 76e110e2b9b..0e274f0872f 100644 --- a/core/commands/root.go +++ b/core/commands/root.go @@ -16,8 +16,10 @@ import ( var log = logging.Logger("core/commands") -var ErrNotOnline = errors.New("this command must be run in online mode. Try running 'ipfs daemon' first") -var ErrSelfUnsupported = errors.New("finding your own node in the DHT is currently not supported") +var ( + ErrNotOnline = errors.New("this command must be run in online mode. Try running 'ipfs daemon' first") + ErrSelfUnsupported = errors.New("finding your own node in the DHT is currently not supported") +) const ( RepoDirOption = "repo-dir" diff --git a/core/commands/routing.go b/core/commands/routing.go index 44ca2e29f1d..e2071fd40a8 100644 --- a/core/commands/routing.go +++ b/core/commands/routing.go @@ -21,9 +21,7 @@ import ( routing "github.com/libp2p/go-libp2p/core/routing" ) -var ( - errAllowOffline = errors.New("can't put while offline: pass `--allow-offline` to override") -) +var errAllowOffline = errors.New("can't put while offline: pass `--allow-offline` to override") const ( dhtVerboseOptionName = "verbose" @@ -75,7 +73,6 @@ var findProvidersRoutingCmd = &cmds.Command{ } c, err := cid.Parse(req.Arguments[0]) - if err != nil { return err } @@ -495,8 +492,10 @@ identified by QmFoo. Type: routing.QueryEvent{}, } -type printFunc func(obj *routing.QueryEvent, out io.Writer, verbose bool) error -type pfuncMap map[routing.QueryEventType]printFunc +type ( + printFunc func(obj *routing.QueryEvent, out io.Writer, verbose bool) error + pfuncMap map[routing.QueryEventType]printFunc +) func printEvent(obj *routing.QueryEvent, out io.Writer, verbose bool, override pfuncMap) error { if verbose { diff --git a/core/commands/swarm.go b/core/commands/swarm.go index 0e28c71754c..fc4d8f7d29d 100644 --- a/core/commands/swarm.go +++ b/core/commands/swarm.go @@ -345,7 +345,8 @@ var swarmResourcesCmd = &cmds.Command{ Get a summary of all resources accounted for by the libp2p Resource Manager. This includes the limits and the usage against those limits. This can output a human readable table and JSON encoding. -`}, +`, + }, Run: func(req *cmds.Request, res cmds.ResponseEmitter, env cmds.Environment) error { node, err := cmdenv.GetNode(env) if err != nil { diff --git a/core/core.go b/core/core.go index 5c0a7ef2cba..a0e06324f84 100644 --- a/core/core.go +++ b/core/core.go @@ -64,7 +64,6 @@ var log = logging.Logger("core") // IpfsNode is IPFS Core module. It represents an IPFS instance. type IpfsNode struct { - // Self Identity peer.ID // the local node's identity diff --git a/core/coreapi/swarm.go b/core/coreapi/swarm.go index 778a46e725f..d3b6a0e432e 100644 --- a/core/coreapi/swarm.go +++ b/core/coreapi/swarm.go @@ -29,8 +29,10 @@ type connInfo struct { } // tag used in the connection manager when explicitly connecting to a peer. -const connectionManagerTag = "user-connect" -const connectionManagerWeight = 100 +const ( + connectionManagerTag = "user-connect" + connectionManagerWeight = 100 +) func (api *SwarmAPI) Connect(ctx context.Context, pi peer.AddrInfo) error { ctx, span := tracing.Span(ctx, "CoreAPI.SwarmAPI", "Connect", trace.WithAttributes(attribute.String("peerid", pi.ID.String()))) diff --git a/core/coreapi/unixfs.go b/core/coreapi/unixfs.go index dd6db41fbd7..e1a607d7397 100644 --- a/core/coreapi/unixfs.go +++ b/core/coreapi/unixfs.go @@ -32,8 +32,10 @@ import ( type UnixfsAPI CoreAPI -var nilNode *core.IpfsNode -var once sync.Once +var ( + nilNode *core.IpfsNode + once sync.Once +) func getOrCreateNilNode() (*core.IpfsNode, error) { once.Do(func() { @@ -41,7 +43,7 @@ func getOrCreateNilNode() (*core.IpfsNode, error) { return } node, err := core.NewNode(context.Background(), &core.BuildCfg{ - //TODO: need this to be true or all files + // TODO: need this to be true or all files // hashed will be stored in memory! NilRepo: true, }) @@ -253,7 +255,6 @@ func (api *UnixfsAPI) processLink(ctx context.Context, linkres ft.LinkResult, se defer span.End() if linkres.Link != nil { span.SetAttributes(attribute.String("linkname", linkres.Link.Name), attribute.String("cid", linkres.Link.Cid.String())) - } if linkres.Err != nil { @@ -314,7 +315,7 @@ func (api *UnixfsAPI) lsFromLinksAsync(ctx context.Context, dir uio.Directory, s defer close(out) for l := range dir.EnumLinksAsync(ctx) { select { - case out <- api.processLink(ctx, l, settings): //TODO: perf: processing can be done in background and in parallel + case out <- api.processLink(ctx, l, settings): // TODO: perf: processing can be done in background and in parallel case <-ctx.Done(): return } @@ -329,7 +330,7 @@ func (api *UnixfsAPI) lsFromLinks(ctx context.Context, ndlinks []*ipld.Link, set for _, l := range ndlinks { lr := ft.LinkResult{Link: &ipld.Link{Name: l.Name, Size: l.Size, Cid: l.Cid}} - links <- api.processLink(ctx, lr, settings) //TODO: can be parallel if settings.Async + links <- api.processLink(ctx, lr, settings) // TODO: can be parallel if settings.Async } close(links) return links, nil diff --git a/core/corehttp/commands.go b/core/corehttp/commands.go index e7ac1428944..63abc5922fc 100644 --- a/core/corehttp/commands.go +++ b/core/corehttp/commands.go @@ -20,12 +20,11 @@ import ( "go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp" ) -var ( - errAPIVersionMismatch = errors.New("api version mismatch") -) +var errAPIVersionMismatch = errors.New("api version mismatch") -const originEnvKey = "API_ORIGIN" -const originEnvKeyDeprecate = `You are using the ` + originEnvKey + `ENV Variable. +const ( + originEnvKey = "API_ORIGIN" + originEnvKeyDeprecate = `You are using the ` + originEnvKey + `ENV Variable. This functionality is deprecated, and will be removed in future versions. Instead, try either adding headers to the config, or passing them via cli arguments: @@ -33,6 +32,7 @@ cli arguments: ipfs config API.HTTPHeaders --json '{"Access-Control-Allow-Origin": ["*"]}' ipfs daemon ` +) // APIPath is the path at which the API is mounted. const APIPath = "/api/v0" @@ -100,7 +100,6 @@ func addCORSDefaults(c *cmdsHttp.ServerConfig) { } func patchCORSVars(c *cmdsHttp.ServerConfig, addr net.Addr) { - // we have to grab the port from an addr, which may be an ip6 addr. // TODO: this should take multiaddrs and derive port from there. port := "" @@ -125,7 +124,6 @@ func patchCORSVars(c *cmdsHttp.ServerConfig, addr net.Addr) { func commandsOption(cctx oldcmds.Context, command *cmds.Command, allowGet bool) ServeOption { return func(n *core.IpfsNode, l net.Listener, mux *http.ServeMux) (*http.ServeMux, error) { - cfg := cmdsHttp.NewServerConfig() cfg.AllowGet = allowGet corsAllowedMethods := []string{http.MethodPost} diff --git a/core/corehttp/metrics.go b/core/corehttp/metrics.go index e26be1ca9f3..f43362ff755 100644 --- a/core/corehttp/metrics.go +++ b/core/corehttp/metrics.go @@ -151,13 +151,11 @@ func MetricsCollectionOption(handlerName string) ServeOption { } } -var ( - peersTotalMetric = prometheus.NewDesc( - prometheus.BuildFQName("ipfs", "p2p", "peers_total"), - "Number of connected peers", - []string{"transport"}, - nil, - ) +var peersTotalMetric = prometheus.NewDesc( + prometheus.BuildFQName("ipfs", "p2p", "peers_total"), + "Number of connected peers", + []string{"transport"}, + nil, ) type IpfsNodeCollector struct { diff --git a/core/coreunix/add_test.go b/core/coreunix/add_test.go index 4560d9964d8..be6f98ed7db 100644 --- a/core/coreunix/add_test.go +++ b/core/coreunix/add_test.go @@ -179,11 +179,9 @@ func TestAddGCLive(t *testing.T) { defer close(addDone) defer close(out) _, err := adder.AddAllAndPin(context.Background(), slf) - if err != nil { t.Error(err) } - }() addedHashes := make(map[string]struct{}) diff --git a/core/node/groups.go b/core/node/groups.go index a626a5cae77..e101bb3ed93 100644 --- a/core/node/groups.go +++ b/core/node/groups.go @@ -248,7 +248,6 @@ var IPNS = fx.Options( // Online groups online-only units func Online(bcfg *BuildCfg, cfg *config.Config, userResourceOverrides rcmgr.PartialLimitConfig) fx.Option { - // Namesys params ipnsCacheSize := cfg.Ipns.ResolveCacheSize diff --git a/core/node/helpers/helpers.go b/core/node/helpers/helpers.go index 546c8e97762..4c3a0488116 100644 --- a/core/node/helpers/helpers.go +++ b/core/node/helpers/helpers.go @@ -2,6 +2,7 @@ package helpers import ( "context" + "go.uber.org/fx" ) diff --git a/core/node/libp2p/rcmgr.go b/core/node/libp2p/rcmgr.go index c11c7262c7d..47a823d5d09 100644 --- a/core/node/libp2p/rcmgr.go +++ b/core/node/libp2p/rcmgr.go @@ -118,7 +118,8 @@ filled in with autocomputed defaults.`) lc.Append(fx.Hook{ OnStop: func(_ context.Context) error { return manager.Close() - }}) + }, + }) return manager, opts, nil } diff --git a/core/node/libp2p/rcmgr_logging.go b/core/node/libp2p/rcmgr_logging.go index 978222bfe3e..56e017b82ea 100644 --- a/core/node/libp2p/rcmgr_logging.go +++ b/core/node/libp2p/rcmgr_logging.go @@ -31,8 +31,10 @@ type loggingScope struct { countErrs func(error) } -var _ network.ResourceManager = (*loggingResourceManager)(nil) -var _ rcmgr.ResourceManagerState = (*loggingResourceManager)(nil) +var ( + _ network.ResourceManager = (*loggingResourceManager)(nil) + _ rcmgr.ResourceManagerState = (*loggingResourceManager)(nil) +) func (n *loggingResourceManager) start(ctx context.Context) { logInterval := n.logInterval @@ -85,36 +87,43 @@ func (n *loggingResourceManager) countErrs(err error) { func (n *loggingResourceManager) ViewSystem(f func(network.ResourceScope) error) error { return n.delegate.ViewSystem(f) } + func (n *loggingResourceManager) ViewTransient(f func(network.ResourceScope) error) error { return n.delegate.ViewTransient(func(s network.ResourceScope) error { return f(&loggingScope{logger: n.logger, delegate: s, countErrs: n.countErrs}) }) } + func (n *loggingResourceManager) ViewService(svc string, f func(network.ServiceScope) error) error { return n.delegate.ViewService(svc, func(s network.ServiceScope) error { return f(&loggingScope{logger: n.logger, delegate: s, countErrs: n.countErrs}) }) } + func (n *loggingResourceManager) ViewProtocol(p protocol.ID, f func(network.ProtocolScope) error) error { return n.delegate.ViewProtocol(p, func(s network.ProtocolScope) error { return f(&loggingScope{logger: n.logger, delegate: s, countErrs: n.countErrs}) }) } + func (n *loggingResourceManager) ViewPeer(p peer.ID, f func(network.PeerScope) error) error { return n.delegate.ViewPeer(p, func(s network.PeerScope) error { return f(&loggingScope{logger: n.logger, delegate: s, countErrs: n.countErrs}) }) } + func (n *loggingResourceManager) OpenConnection(dir network.Direction, usefd bool, remote ma.Multiaddr) (network.ConnManagementScope, error) { connMgmtScope, err := n.delegate.OpenConnection(dir, usefd, remote) n.countErrs(err) return connMgmtScope, err } + func (n *loggingResourceManager) OpenStream(p peer.ID, dir network.Direction) (network.StreamManagementScope, error) { connMgmtScope, err := n.delegate.OpenStream(p, dir) n.countErrs(err) return connMgmtScope, err } + func (n *loggingResourceManager) Close() error { return n.delegate.Close() } @@ -127,6 +136,7 @@ func (n *loggingResourceManager) ListServices() []string { return rapi.ListServices() } + func (n *loggingResourceManager) ListProtocols() []protocol.ID { rapi, ok := n.delegate.(rcmgr.ResourceManagerState) if !ok { @@ -135,6 +145,7 @@ func (n *loggingResourceManager) ListProtocols() []protocol.ID { return rapi.ListProtocols() } + func (n *loggingResourceManager) ListPeers() []peer.ID { rapi, ok := n.delegate.(rcmgr.ResourceManagerState) if !ok { @@ -158,54 +169,69 @@ func (s *loggingScope) ReserveMemory(size int, prio uint8) error { s.countErrs(err) return err } + func (s *loggingScope) ReleaseMemory(size int) { s.delegate.ReleaseMemory(size) } + func (s *loggingScope) Stat() network.ScopeStat { return s.delegate.Stat() } + func (s *loggingScope) BeginSpan() (network.ResourceScopeSpan, error) { return s.delegate.BeginSpan() } + func (s *loggingScope) Done() { s.delegate.(network.ResourceScopeSpan).Done() } + func (s *loggingScope) Name() string { return s.delegate.(network.ServiceScope).Name() } + func (s *loggingScope) Protocol() protocol.ID { return s.delegate.(network.ProtocolScope).Protocol() } + func (s *loggingScope) Peer() peer.ID { return s.delegate.(network.PeerScope).Peer() } + func (s *loggingScope) PeerScope() network.PeerScope { return s.delegate.(network.PeerScope) } + func (s *loggingScope) SetPeer(p peer.ID) error { err := s.delegate.(network.ConnManagementScope).SetPeer(p) s.countErrs(err) return err } + func (s *loggingScope) ProtocolScope() network.ProtocolScope { return s.delegate.(network.ProtocolScope) } + func (s *loggingScope) SetProtocol(proto protocol.ID) error { err := s.delegate.(network.StreamManagementScope).SetProtocol(proto) s.countErrs(err) return err } + func (s *loggingScope) ServiceScope() network.ServiceScope { return s.delegate.(network.ServiceScope) } + func (s *loggingScope) SetService(srv string) error { err := s.delegate.(network.StreamManagementScope).SetService(srv) s.countErrs(err) return err } + func (s *loggingScope) Limit() rcmgr.Limit { return s.delegate.(rcmgr.ResourceScopeLimiter).Limit() } + func (s *loggingScope) SetLimit(limit rcmgr.Limit) { s.delegate.(rcmgr.ResourceScopeLimiter).SetLimit(limit) } diff --git a/core/node/libp2p/routing.go b/core/node/libp2p/routing.go index 007ff33978b..98234f5ceda 100644 --- a/core/node/libp2p/routing.go +++ b/core/node/libp2p/routing.go @@ -232,7 +232,6 @@ func PubsubRouter(mctx helpers.MetricsCtx, lc fx.Lifecycle, in p2pPSRoutingIn) ( in.Validator, namesys.WithRebroadcastInterval(time.Minute), ) - if err != nil { return p2pRouterOut{}, nil, err } diff --git a/core/node/libp2p/topicdiscovery.go b/core/node/libp2p/topicdiscovery.go index 81bec285fe3..8d0254383e8 100644 --- a/core/node/libp2p/topicdiscovery.go +++ b/core/node/libp2p/topicdiscovery.go @@ -21,7 +21,6 @@ func TopicDiscovery() interface{} { baseDisc, backoff.NewExponentialBackoff(minBackoff, maxBackoff, backoff.FullJitter, time.Second, 5.0, 0, rng), ) - if err != nil { return nil, err } diff --git a/core/node/libp2p/transport.go b/core/node/libp2p/transport.go index f737c608643..8e04a63ffc8 100644 --- a/core/node/libp2p/transport.go +++ b/core/node/libp2p/transport.go @@ -18,7 +18,8 @@ func Transports(tptConfig config.Transports) interface{} { return func(pnet struct { fx.In Fprint PNetFingerprint `optional:"true"` - }) (opts Libp2pOpts, err error) { + }, + ) (opts Libp2pOpts, err error) { privateNetworkEnabled := pnet.Fprint != nil if tptConfig.Network.TCP.WithDefault(true) { diff --git a/docs/examples/kubo-as-a-library/main.go b/docs/examples/kubo-as-a-library/main.go index ce19a5a64e9..785973c5baa 100644 --- a/docs/examples/kubo-as-a-library/main.go +++ b/docs/examples/kubo-as-a-library/main.go @@ -85,7 +85,7 @@ func createTempRepo() (string, error) { /// ------ Spawning the node -// Creates an IPFS node and returns its coreAPI +// Creates an IPFS node and returns its coreAPI. func createNode(ctx context.Context, repoPath string) (*core.IpfsNode, error) { // Open the repo repo, err := fsrepo.Open(repoPath) @@ -107,7 +107,7 @@ func createNode(ctx context.Context, repoPath string) (*core.IpfsNode, error) { var loadPluginsOnce sync.Once -// Spawns a node to be used just for this run (i.e. creates a tmp repo) +// Spawns a node to be used just for this run (i.e. creates a tmp repo). func spawnEphemeral(ctx context.Context) (icore.CoreAPI, *core.IpfsNode, error) { var onceErr error loadPluginsOnce.Do(func() { diff --git a/fuse/ipns/ipns_test.go b/fuse/ipns/ipns_test.go index 05a4e467ef5..ca2ec4c1abc 100644 --- a/fuse/ipns/ipns_test.go +++ b/fuse/ipns/ipns_test.go @@ -56,7 +56,7 @@ func writeFileOrFail(t *testing.T, size int, path string) []byte { func writeFile(size int, path string) ([]byte, error) { data := randBytes(size) - err := os.WriteFile(path, data, 0666) + err := os.WriteFile(path, data, 0o666) return data, err } @@ -156,7 +156,7 @@ func TestIpnsLocalLink(t *testing.T) { } } -// Test writing a file and reading it back +// Test writing a file and reading it back. func TestIpnsBasicIO(t *testing.T) { if testing.Short() { t.SkipNow() @@ -187,7 +187,7 @@ func TestIpnsBasicIO(t *testing.T) { } } -// Test to make sure file changes persist over mounts of ipns +// Test to make sure file changes persist over mounts of ipns. func TestFilePersistence(t *testing.T) { if testing.Short() { t.SkipNow() @@ -250,7 +250,7 @@ func TestMultipleDirs(t *testing.T) { mnt.Close() } -// Test to make sure the filesystem reports file sizes correctly +// Test to make sure the filesystem reports file sizes correctly. func TestFileSizeReporting(t *testing.T) { if testing.Short() { t.SkipNow() @@ -271,7 +271,7 @@ func TestFileSizeReporting(t *testing.T) { } } -// Test to make sure you can't create multiple entries with the same name +// Test to make sure you can't create multiple entries with the same name. func TestDoubleEntryFailure(t *testing.T) { if testing.Short() { t.SkipNow() @@ -280,12 +280,12 @@ func TestDoubleEntryFailure(t *testing.T) { defer mnt.Close() dname := mnt.Dir + "/local/thisisadir" - err := os.Mkdir(dname, 0777) + err := os.Mkdir(dname, 0o777) if err != nil { t.Fatal(err) } - err = os.Mkdir(dname, 0777) + err = os.Mkdir(dname, 0o777) if err == nil { t.Fatal("Should have gotten error one creating new directory.") } @@ -301,7 +301,7 @@ func TestAppendFile(t *testing.T) { fname := mnt.Dir + "/local/file" data := writeFileOrFail(t, 1300, fname) - fi, err := os.OpenFile(fname, os.O_RDWR|os.O_APPEND, 0666) + fi, err := os.OpenFile(fname, os.O_RDWR|os.O_APPEND, 0o666) if err != nil { t.Fatal(err) } @@ -463,9 +463,8 @@ func TestFSThrash(t *testing.T) { } } -// Test writing a medium sized file one byte at a time +// Test writing a medium sized file one byte at a time. func TestMultiWrite(t *testing.T) { - if testing.Short() { t.SkipNow() } diff --git a/fuse/ipns/ipns_unix.go b/fuse/ipns/ipns_unix.go index 9db0d61f951..e4f49cf123b 100644 --- a/fuse/ipns/ipns_unix.go +++ b/fuse/ipns/ipns_unix.go @@ -149,7 +149,7 @@ func CreateRoot(ctx context.Context, ipfs iface.CoreAPI, keys map[string]iface.K // Attr returns file attributes. func (r *Root) Attr(ctx context.Context, a *fuse.Attr) error { log.Debug("Root Attr") - a.Mode = os.ModeDir | 0111 // -rw+x + a.Mode = os.ModeDir | 0o111 // -rw+x return nil } @@ -212,7 +212,7 @@ func (r *Root) Forget() { } // ReadDirAll reads a particular directory. Will show locally available keys -// as well as a symlink to the peerID key +// as well as a symlink to the peerID key. func (r *Root) ReadDirAll(ctx context.Context) ([]fuse.Dirent, error) { log.Debug("Root ReadDirAll") @@ -231,7 +231,7 @@ func (r *Root) ReadDirAll(ctx context.Context) ([]fuse.Dirent, error) { return listing, nil } -// Directory is wrapper over an mfs directory to satisfy the fuse fs interface +// Directory is wrapper over an mfs directory to satisfy the fuse fs interface. type Directory struct { dir *mfs.Directory } @@ -240,7 +240,7 @@ type FileNode struct { fi *mfs.File } -// File is wrapper over an mfs file to satisfy the fuse fs interface +// File is wrapper over an mfs file to satisfy the fuse fs interface. type File struct { fi mfs.FileDescriptor } @@ -248,7 +248,7 @@ type File struct { // Attr returns the attributes of a given node. func (d *Directory) Attr(ctx context.Context, a *fuse.Attr) error { log.Debug("Directory Attr") - a.Mode = os.ModeDir | 0555 + a.Mode = os.ModeDir | 0o555 a.Uid = uint32(os.Getuid()) a.Gid = uint32(os.Getgid()) return nil @@ -262,7 +262,7 @@ func (fi *FileNode) Attr(ctx context.Context, a *fuse.Attr) error { // In this case, the dag node in question may not be unixfs return fmt.Errorf("fuse/ipns: failed to get file.Size(): %s", err) } - a.Mode = os.FileMode(0666) + a.Mode = os.FileMode(0o666) a.Size = uint64(size) a.Uid = uint32(os.Getuid()) a.Gid = uint32(os.Getgid()) @@ -289,7 +289,7 @@ func (d *Directory) Lookup(ctx context.Context, name string) (fs.Node, error) { } } -// ReadDirAll reads the link structure as directory entries +// ReadDirAll reads the link structure as directory entries. func (d *Directory) ReadDirAll(ctx context.Context) ([]fuse.Dirent, error) { listing, err := d.dir.List(ctx) if err != nil { @@ -491,7 +491,7 @@ func (d *Directory) Remove(ctx context.Context, req *fuse.RemoveRequest) error { return nil } -// Rename implements NodeRenamer +// Rename implements NodeRenamer. func (d *Directory) Rename(ctx context.Context, req *fuse.RenameRequest, newDir fs.Node) error { cur, err := d.dir.Child(req.OldName) if err != nil { @@ -531,7 +531,7 @@ func min(a, b int) int { return b } -// to check that out Node implements all the interfaces we want +// to check that out Node implements all the interfaces we want. type ipnsRoot interface { fs.Node fs.HandleReadDirAller @@ -565,5 +565,7 @@ type ipnsFileNode interface { fs.NodeOpener } -var _ ipnsFileNode = (*FileNode)(nil) -var _ ipnsFile = (*File)(nil) +var ( + _ ipnsFileNode = (*FileNode)(nil) + _ ipnsFile = (*File)(nil) +) diff --git a/fuse/ipns/link_unix.go b/fuse/ipns/link_unix.go index 355787b3c5e..da810c8f947 100644 --- a/fuse/ipns/link_unix.go +++ b/fuse/ipns/link_unix.go @@ -17,7 +17,7 @@ type Link struct { func (l *Link) Attr(ctx context.Context, a *fuse.Attr) error { log.Debug("Link attr.") - a.Mode = os.ModeSymlink | 0555 + a.Mode = os.ModeSymlink | 0o555 return nil } diff --git a/fuse/mount/fuse.go b/fuse/mount/fuse.go index b1060e6fd70..2dcb8ccae4f 100644 --- a/fuse/mount/fuse.go +++ b/fuse/mount/fuse.go @@ -16,7 +16,7 @@ import ( var ErrNotMounted = errors.New("not mounted") -// mount implements go-ipfs/fuse/mount +// mount implements go-ipfs/fuse/mount. type mount struct { mpoint string filesys fs.FS @@ -34,7 +34,7 @@ func NewMount(p goprocess.Process, fsys fs.FS, mountpoint string, allowOther boo var conn *fuse.Conn var err error - var mountOpts = []fuse.MountOption{ + mountOpts := []fuse.MountOption{ fuse.MaxReadahead(64 * 1024 * 1024), fuse.AsyncRead(), } diff --git a/fuse/mount/mount.go b/fuse/mount/mount.go index 52784a16d27..a52374dd819 100644 --- a/fuse/mount/mount.go +++ b/fuse/mount/mount.go @@ -16,7 +16,7 @@ var log = logging.Logger("mount") var MountTimeout = time.Second * 5 -// Mount represents a filesystem mount +// Mount represents a filesystem mount. type Mount interface { // MountPoint is the path at which this mount is mounted MountPoint() string @@ -65,7 +65,7 @@ func ForceUnmount(m Mount) error { } // UnmountCmd creates an exec.Cmd that is GOOS-specific -// for unmount a FUSE mount +// for unmount a FUSE mount. func UnmountCmd(point string) (*exec.Cmd, error) { switch runtime.GOOS { case "darwin": diff --git a/fuse/node/mount_darwin.go b/fuse/node/mount_darwin.go index 73fa86772e4..bd0bbb3ae3d 100644 --- a/fuse/node/mount_darwin.go +++ b/fuse/node/mount_darwin.go @@ -25,7 +25,7 @@ func init() { // skip fuse checks. const dontCheckOSXFUSEConfigKey = "DontCheckOSXFUSE" -// fuseVersionPkg is the go pkg url for fuse-version +// fuseVersionPkg is the go pkg url for fuse-version. const fuseVersionPkg = "github.com/jbenet/go-fuse-version/fuse-version" // errStrFuseRequired is returned when we're sure the user does not have fuse. diff --git a/fuse/node/mount_test.go b/fuse/node/mount_test.go index 1691cfa5ba2..178fddcf665 100644 --- a/fuse/node/mount_test.go +++ b/fuse/node/mount_test.go @@ -32,7 +32,7 @@ func mkdir(t *testing.T, path string) { } } -// Test externally unmounting, then trying to unmount in code +// Test externally unmounting, then trying to unmount in code. func TestExternalUnmount(t *testing.T) { if testing.Short() { t.SkipNow() diff --git a/fuse/node/mount_unix.go b/fuse/node/mount_unix.go index 84795b13d34..1e509a2435c 100644 --- a/fuse/node/mount_unix.go +++ b/fuse/node/mount_unix.go @@ -19,14 +19,14 @@ import ( var log = logging.Logger("node") -// fuseNoDirectory used to check the returning fuse error +// fuseNoDirectory used to check the returning fuse error. const fuseNoDirectory = "fusermount: failed to access mountpoint" -// fuseExitStatus1 used to check the returning fuse error +// fuseExitStatus1 used to check the returning fuse error. const fuseExitStatus1 = "fusermount: exit status 1" // platformFuseChecks can get overridden by arch-specific files -// to run fuse checks (like checking the OSXFUSE version) +// to run fuse checks (like checking the OSXFUSE version). var platformFuseChecks = func(*core.IpfsNode) error { return nil } diff --git a/fuse/readonly/ipfs_test.go b/fuse/readonly/ipfs_test.go index ffe86509d5a..bc6204abb6a 100644 --- a/fuse/readonly/ipfs_test.go +++ b/fuse/readonly/ipfs_test.go @@ -79,7 +79,7 @@ func setupIpfsTest(t *testing.T, node *core.IpfsNode) (*core.IpfsNode, *fstest.M return node, mnt } -// Test writing an object and reading it back through fuse +// Test writing an object and reading it back through fuse. func TestIpfsBasicRead(t *testing.T) { if testing.Short() { t.SkipNow() @@ -122,7 +122,7 @@ func getPaths(t *testing.T, ipfs *core.IpfsNode, name string, n *dag.ProtoNode) return out } -// Perform a large number of concurrent reads to stress the system +// Perform a large number of concurrent reads to stress the system. func TestIpfsStressRead(t *testing.T) { if testing.Short() { t.SkipNow() @@ -194,8 +194,8 @@ func TestIpfsStressRead(t *testing.T) { errs <- err } - //nd.Context() is never closed which leads to - //hitting 8128 goroutine limit in go test -race mode + // nd.Context() is never closed which leads to + // hitting 8128 goroutine limit in go test -race mode ctx, cancelFunc := context.WithCancel(context.Background()) read, err := api.Unixfs().Get(ctx, item) @@ -229,7 +229,7 @@ func TestIpfsStressRead(t *testing.T) { } } -// Test writing a file and reading it back +// Test writing a file and reading it back. func TestIpfsBasicDirRead(t *testing.T) { if testing.Short() { t.SkipNow() @@ -280,7 +280,7 @@ func TestIpfsBasicDirRead(t *testing.T) { } } -// Test to make sure the filesystem reports file sizes correctly +// Test to make sure the filesystem reports file sizes correctly. func TestFileSizeReporting(t *testing.T) { if testing.Short() { t.SkipNow() diff --git a/fuse/readonly/readonly_unix.go b/fuse/readonly/readonly_unix.go index d925ec8c291..c75a35fbd17 100644 --- a/fuse/readonly/readonly_unix.go +++ b/fuse/readonly/readonly_unix.go @@ -49,7 +49,7 @@ type Root struct { // Attr returns file attributes. func (*Root) Attr(ctx context.Context, a *fuse.Attr) error { - a.Mode = os.ModeDir | 0111 // -rw+x + a.Mode = os.ModeDir | 0o111 // -rw+x return nil } @@ -139,7 +139,7 @@ func (s *Node) loadData() error { func (s *Node) Attr(ctx context.Context, a *fuse.Attr) error { log.Debug("Node attr") if rawnd, ok := s.Nd.(*mdag.RawNode); ok { - a.Mode = 0444 + a.Mode = 0o444 a.Size = uint64(len(rawnd.RawData())) a.Blocks = 1 return nil @@ -152,18 +152,18 @@ func (s *Node) Attr(ctx context.Context, a *fuse.Attr) error { } switch s.cached.Type() { case ft.TDirectory, ft.THAMTShard: - a.Mode = os.ModeDir | 0555 + a.Mode = os.ModeDir | 0o555 case ft.TFile: size := s.cached.FileSize() - a.Mode = 0444 + a.Mode = 0o444 a.Size = uint64(size) a.Blocks = uint64(len(s.Nd.Links())) case ft.TRaw: - a.Mode = 0444 + a.Mode = 0o444 a.Size = uint64(len(s.cached.Data())) a.Blocks = uint64(len(s.Nd.Links())) case ft.TSymlink: - a.Mode = 0777 | os.ModeSymlink + a.Mode = 0o777 | os.ModeSymlink a.Size = uint64(len(s.cached.Data())) default: 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) { return &Node{Ipfs: s.Ipfs, Nd: nd}, nil } -// ReadDirAll reads the link structure as directory entries +// ReadDirAll reads the link structure as directory entries. func (s *Node) ReadDirAll(ctx context.Context) ([]fuse.Dirent, error) { log.Debug("Node ReadDir") 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 return nil // may be non-nil / not succeeded } -// to check that out Node implements all the interfaces we want +// to check that out Node implements all the interfaces we want. type roRoot interface { fs.Node fs.HandleReadDirAller diff --git a/gc/gc.go b/gc/gc.go index 031ba16dc42..c85f9d6bf24 100644 --- a/gc/gc.go +++ b/gc/gc.go @@ -191,7 +191,6 @@ func Descendants(ctx context.Context, getLinks dag.GetLinks, set *cid.Set, roots err := dag.Walk(ctx, verifyGetLinks, wrapper.C, func(k cid.Cid) bool { return set.Visit(toCidV1(k)) }, dag.Concurrent()) - if err != nil { err = verboseCidError(err) return err diff --git a/p2p/listener.go b/p2p/listener.go index 906137ea1f3..f5942ffa0a3 100644 --- a/p2p/listener.go +++ b/p2p/listener.go @@ -10,7 +10,7 @@ import ( ma "github.com/multiformats/go-multiaddr" ) -// Listener listens for connections and proxies them to a target +// Listener listens for connections and proxies them to a target. type Listener interface { Protocol() protocol.ID ListenAddress() ma.Multiaddr @@ -23,7 +23,7 @@ type Listener interface { } // Listeners manages a group of Listener implementations, -// checking for conflicts and optionally dispatching connections +// checking for conflicts and optionally dispatching connections. type Listeners struct { sync.RWMutex @@ -60,7 +60,7 @@ func newListenersP2P(host p2phost.Host) *Listeners { return reg } -// Register registers listenerInfo into this registry and starts it +// Register registers listenerInfo into this registry and starts it. func (r *Listeners) Register(l Listener) error { r.Lock() defer r.Unlock() diff --git a/p2p/local.go b/p2p/local.go index 85baf948b4c..6ef110c3931 100644 --- a/p2p/local.go +++ b/p2p/local.go @@ -12,7 +12,7 @@ import ( manet "github.com/multiformats/go-multiaddr/net" ) -// localListener manet streams and proxies them to libp2p services +// localListener manet streams and proxies them to libp2p services. type localListener struct { ctx context.Context @@ -25,7 +25,7 @@ type localListener struct { listener manet.Listener } -// ForwardLocal creates new P2P stream to a remote listener +// ForwardLocal creates new P2P stream to a remote listener. func (p2p *P2P) ForwardLocal(ctx context.Context, peer peer.ID, proto protocol.ID, bindAddr ma.Multiaddr) (Listener, error) { listener := &localListener{ ctx: ctx, diff --git a/p2p/p2p.go b/p2p/p2p.go index e18488c2d6a..1d098942145 100644 --- a/p2p/p2p.go +++ b/p2p/p2p.go @@ -10,7 +10,7 @@ import ( var log = logging.Logger("p2p-mount") -// P2P structure holds information on currently running streams/Listeners +// P2P structure holds information on currently running streams/Listeners. type P2P struct { ListenersLocal *Listeners ListenersP2P *Listeners @@ -21,7 +21,7 @@ type P2P struct { peerstore pstore.Peerstore } -// New creates new P2P struct +// New creates new P2P struct. func New(identity peer.ID, peerHost p2phost.Host, peerstore pstore.Peerstore) *P2P { return &P2P{ identity: identity, @@ -40,7 +40,7 @@ func New(identity peer.ID, peerHost p2phost.Host, peerstore pstore.Peerstore) *P } // CheckProtoExists checks whether a proto handler is registered to -// mux handler +// mux handler. func (p2p *P2P) CheckProtoExists(proto protocol.ID) bool { protos := p2p.peerHost.Mux().Protocols() diff --git a/p2p/remote.go b/p2p/remote.go index ac540e9a551..a90155a210a 100644 --- a/p2p/remote.go +++ b/p2p/remote.go @@ -12,7 +12,7 @@ import ( var maPrefix = "/" + ma.ProtocolWithCode(ma.P_IPFS).Name + "/" -// remoteListener accepts libp2p streams and proxies them to a manet host +// remoteListener accepts libp2p streams and proxies them to a manet host. type remoteListener struct { p2p *P2P @@ -27,7 +27,7 @@ type remoteListener struct { reportRemote bool } -// ForwardRemote creates new p2p listener +// ForwardRemote creates new p2p listener. func (p2p *P2P) ForwardRemote(ctx context.Context, proto protocol.ID, addr ma.Multiaddr, reportRemote bool) (Listener, error) { listener := &remoteListener{ p2p: p2p, diff --git a/p2p/stream.go b/p2p/stream.go index ec8bac508b2..5d05cba7989 100644 --- a/p2p/stream.go +++ b/p2p/stream.go @@ -30,12 +30,12 @@ type Stream struct { Registry *StreamRegistry } -// close stream endpoints and deregister it +// close stream endpoints and deregister it. func (s *Stream) close() { s.Registry.Close(s) } -// reset closes stream endpoints and deregisters it +// reset closes stream endpoints and deregisters it. func (s *Stream) reset() { s.Registry.Reset(s) } @@ -71,7 +71,7 @@ type StreamRegistry struct { ifconnmgr.ConnManager } -// Register registers a stream to the registry +// Register registers a stream to the registry. func (r *StreamRegistry) Register(streamInfo *Stream) { r.Lock() defer r.Unlock() @@ -86,7 +86,7 @@ func (r *StreamRegistry) Register(streamInfo *Stream) { streamInfo.startStreaming() } -// Deregister deregisters stream from the registry +// Deregister deregisters stream from the registry. func (r *StreamRegistry) Deregister(streamID uint64) { r.Lock() defer r.Unlock() @@ -105,14 +105,14 @@ func (r *StreamRegistry) Deregister(streamID uint64) { delete(r.Streams, streamID) } -// Close stream endpoints and deregister it +// Close stream endpoints and deregister it. func (r *StreamRegistry) Close(s *Stream) { _ = s.Local.Close() _ = s.Remote.Close() s.Registry.Deregister(s.id) } -// Reset closes stream endpoints and deregisters it +// Reset closes stream endpoints and deregisters it. func (r *StreamRegistry) Reset(s *Stream) { _ = s.Local.Close() _ = s.Remote.Reset() diff --git a/peering/peering.go b/peering/peering.go index 00801626f13..291d9491c7a 100644 --- a/peering/peering.go +++ b/peering/peering.go @@ -201,7 +201,7 @@ func (ps *PeeringService) Start() error { return nil } -// GetState get the State of the PeeringService +// GetState get the State of the PeeringService. func (ps *PeeringService) GetState() State { ps.mu.RLock() defer ps.mu.RUnlock() @@ -306,6 +306,7 @@ func (nn *netNotifee) Connected(_ network.Network, c network.Conn) { go handler.stopIfConnected() } } + func (nn *netNotifee) Disconnected(_ network.Network, c network.Conn) { ps := (*PeeringService)(nn) diff --git a/plugin/datastore.go b/plugin/datastore.go index 15d93f3e6c8..e31a144d4aa 100644 --- a/plugin/datastore.go +++ b/plugin/datastore.go @@ -5,7 +5,7 @@ import ( ) // PluginDatastore is an interface that can be implemented to add handlers for -// for different datastores +// for different datastores. type PluginDatastore interface { Plugin diff --git a/plugin/ipld.go b/plugin/ipld.go index 2f783a61238..d366b92cc91 100644 --- a/plugin/ipld.go +++ b/plugin/ipld.go @@ -5,7 +5,7 @@ import ( ) // PluginIPLD is an interface that can be implemented to add handlers for -// for different IPLD codecs +// for different IPLD codecs. type PluginIPLD interface { Plugin diff --git a/plugin/loader/loader.go b/plugin/loader/loader.go index 84ebdc0fc40..80cc9a1b635 100644 --- a/plugin/loader/loader.go +++ b/plugin/loader/loader.go @@ -93,7 +93,7 @@ type PluginLoader struct { repo string } -// NewPluginLoader creates new plugin loader +// NewPluginLoader creates new plugin loader. func NewPluginLoader(repo string) (*PluginLoader, error) { loader := &PluginLoader{plugins: make([]plugin.Plugin, 0, len(preloadPlugins)), repo: repo} if repo != "" { @@ -226,7 +226,7 @@ func loadDynamicPlugins(pluginDir string) ([]plugin.Plugin, error) { return nil } - if info.Mode().Perm()&0111 == 0 { + if info.Mode().Perm()&0o111 == 0 { // file is not executable let's not load it // this is to prevent loading plugins from for example non-executable // mounts, some /tmp mounts are marked as such for security @@ -245,7 +245,7 @@ func loadDynamicPlugins(pluginDir string) ([]plugin.Plugin, error) { return plugins, err } -// Initialize initializes all loaded plugins +// Initialize initializes all loaded plugins. func (loader *PluginLoader) Initialize() error { if err := loader.transition(loaderLoading, loaderInitializing); err != nil { return err diff --git a/plugin/plugins/badgerds/badgerds.go b/plugin/plugins/badgerds/badgerds.go index 3d3f69061ab..5f5781f8fc3 100644 --- a/plugin/plugins/badgerds/badgerds.go +++ b/plugin/plugins/badgerds/badgerds.go @@ -13,7 +13,7 @@ import ( badgerds "github.com/ipfs/go-ds-badger" ) -// Plugins is exported list of plugins that will be loaded +// Plugins is exported list of plugins that will be loaded. var Plugins = []plugin.Plugin{ &badgerdsPlugin{}, } @@ -47,7 +47,7 @@ type datastoreConfig struct { } // BadgerdsDatastoreConfig returns a configuration stub for a badger datastore -// from the given parameters +// from the given parameters. func (*badgerdsPlugin) DatastoreConfigParser() fsrepo.ConfigFromMap { return func(params map[string]interface{}) (fsrepo.DatastoreConfig, error) { var c datastoreConfig @@ -113,7 +113,7 @@ func (c *datastoreConfig) Create(path string) (repo.Datastore, error) { p = filepath.Join(path, p) } - err := os.MkdirAll(p, 0755) + err := os.MkdirAll(p, 0o755) if err != nil { return nil, err } diff --git a/plugin/plugins/dagjose/dagjose.go b/plugin/plugins/dagjose/dagjose.go index 94321462993..4545e2e9663 100644 --- a/plugin/plugins/dagjose/dagjose.go +++ b/plugin/plugins/dagjose/dagjose.go @@ -8,7 +8,7 @@ import ( mc "github.com/multiformats/go-multicodec" ) -// Plugins is exported list of plugins that will be loaded +// Plugins is exported list of plugins that will be loaded. var Plugins = []plugin.Plugin{ &dagjosePlugin{}, } diff --git a/plugin/plugins/flatfs/flatfs.go b/plugin/plugins/flatfs/flatfs.go index 40b8b37d06c..1a23dfcca9d 100644 --- a/plugin/plugins/flatfs/flatfs.go +++ b/plugin/plugins/flatfs/flatfs.go @@ -11,7 +11,7 @@ import ( flatfs "github.com/ipfs/go-ds-flatfs" ) -// Plugins is exported list of plugins that will be loaded +// Plugins is exported list of plugins that will be loaded. var Plugins = []plugin.Plugin{ &flatfsPlugin{}, } @@ -43,7 +43,7 @@ type datastoreConfig struct { } // BadgerdsDatastoreConfig returns a configuration stub for a badger datastore -// from the given parameters +// from the given parameters. func (*flatfsPlugin) DatastoreConfigParser() fsrepo.ConfigFromMap { return func(params map[string]interface{}) (fsrepo.DatastoreConfig, error) { var c datastoreConfig diff --git a/plugin/plugins/git/git.go b/plugin/plugins/git/git.go index 2c56d83392c..baaea6c3541 100644 --- a/plugin/plugins/git/git.go +++ b/plugin/plugins/git/git.go @@ -13,7 +13,7 @@ import ( mc "github.com/multiformats/go-multicodec" ) -// Plugins is exported list of plugins that will be loaded +// Plugins is exported list of plugins that will be loaded. var Plugins = []plugin.Plugin{ &gitPlugin{}, } diff --git a/plugin/plugins/levelds/levelds.go b/plugin/plugins/levelds/levelds.go index ccb7c08f8cf..b08872de63d 100644 --- a/plugin/plugins/levelds/levelds.go +++ b/plugin/plugins/levelds/levelds.go @@ -12,7 +12,7 @@ import ( ldbopts "github.com/syndtr/goleveldb/leveldb/opt" ) -// Plugins is exported list of plugins that will be loaded +// Plugins is exported list of plugins that will be loaded. var Plugins = []plugin.Plugin{ &leveldsPlugin{}, } @@ -43,7 +43,7 @@ type datastoreConfig struct { } // BadgerdsDatastoreConfig returns a configuration stub for a badger datastore -// from the given parameters +// from the given parameters. func (*leveldsPlugin) DatastoreConfigParser() fsrepo.ConfigFromMap { return func(params map[string]interface{}) (fsrepo.DatastoreConfig, error) { var c datastoreConfig diff --git a/plugin/plugins/peerlog/peerlog.go b/plugin/plugins/peerlog/peerlog.go index 1b71cb1ae4c..f41a8b654ee 100644 --- a/plugin/plugins/peerlog/peerlog.go +++ b/plugin/plugins/peerlog/peerlog.go @@ -20,7 +20,7 @@ var log = logging.Logger("plugin/peerlog") type eventType int var ( - // size of the event queue buffer + // size of the event queue buffer. eventQueueSize = 64 * 1024 // number of events to drop when busy. busyDropAmount = eventQueueSize / 8 @@ -54,7 +54,7 @@ type peerLogPlugin struct { var _ plugin.PluginDaemonInternal = (*peerLogPlugin)(nil) -// Plugins is exported list of plugins that will be loaded +// Plugins is exported list of plugins that will be loaded. var Plugins = []plugin.Plugin{ &peerLogPlugin{}, } @@ -94,7 +94,7 @@ func extractEnabled(config interface{}) bool { return enabled } -// Init initializes plugin +// Init initializes plugin. func (pl *peerLogPlugin) Init(env *plugin.Environment) error { pl.events = make(chan plEvent, eventQueueSize) pl.enabled = extractEnabled(env.Config) diff --git a/plugin/tracer.go b/plugin/tracer.go index b6b56939d44..97aa8484645 100644 --- a/plugin/tracer.go +++ b/plugin/tracer.go @@ -4,7 +4,7 @@ import ( "github.com/opentracing/opentracing-go" ) -// PluginTracer is an interface that can be implemented to add a tracer +// PluginTracer is an interface that can be implemented to add a tracer. type PluginTracer interface { Plugin diff --git a/repo/common/common.go b/repo/common/common.go index e9c56e65ee3..ab74ffca853 100644 --- a/repo/common/common.go +++ b/repo/common/common.go @@ -62,7 +62,7 @@ func MapSetKV(v map[string]interface{}, key string, value interface{}) error { } // Merges the right map into the left map, recursively traversing child maps -// until a non-map value is found +// until a non-map value is found. func MapMergeDeep(left, right map[string]interface{}) map[string]interface{} { // We want to alter a copy of the map, not the original result := make(map[string]interface{}) diff --git a/repo/fsrepo/config_test.go b/repo/fsrepo/config_test.go index 060d0222ada..3c914ff8202 100644 --- a/repo/fsrepo/config_test.go +++ b/repo/fsrepo/config_test.go @@ -12,7 +12,7 @@ import ( ) // note: to test sorting of the mountpoints in the disk spec they are -// specified out of order in the test config +// specified out of order in the test config. var defaultConfig = []byte(`{ "StorageMax": "10GB", "StorageGCWatermark": 90, diff --git a/repo/fsrepo/datastores.go b/repo/fsrepo/datastores.go index 0f60056aa4e..86ed0a86308 100644 --- a/repo/fsrepo/datastores.go +++ b/repo/fsrepo/datastores.go @@ -14,12 +14,12 @@ import ( "github.com/ipfs/go-ds-measure" ) -// ConfigFromMap creates a new datastore config from a map +// ConfigFromMap creates a new datastore config from a map. type ConfigFromMap func(map[string]interface{}) (DatastoreConfig, error) // DatastoreConfig is an abstraction of a datastore config. A "spec" // is first converted to a DatastoreConfig and then Create() is called -// to instantiate a new datastore +// to instantiate a new datastore. type DatastoreConfig interface { // DiskSpec returns a minimal configuration of the datastore // represting what is stored on disk. Run time values are @@ -38,7 +38,7 @@ type DatastoreConfig interface { // here. type DiskSpec map[string]interface{} -// Bytes returns a minimal JSON encoding of the DiskSpec +// Bytes returns a minimal JSON encoding of the DiskSpec. func (spec DiskSpec) Bytes() []byte { b, err := json.Marshal(spec) if err != nil { @@ -48,7 +48,7 @@ func (spec DiskSpec) Bytes() []byte { return bytes.TrimSpace(b) } -// String returns a minimal JSON encoding of the DiskSpec +// String returns a minimal JSON encoding of the DiskSpec. func (spec DiskSpec) String() string { return string(spec.Bytes()) } @@ -75,7 +75,7 @@ func AddDatastoreConfigHandler(name string, dsc ConfigFromMap) error { } // AnyDatastoreConfig returns a DatastoreConfig from a spec based on -// the "type" parameter +// the "type" parameter. func AnyDatastoreConfig(params map[string]interface{}) (DatastoreConfig, error) { which, ok := params["type"].(string) if !ok { @@ -97,7 +97,7 @@ type premount struct { prefix ds.Key } -// MountDatastoreConfig returns a mount DatastoreConfig from a spec +// MountDatastoreConfig returns a mount DatastoreConfig from a spec. func MountDatastoreConfig(params map[string]interface{}) (DatastoreConfig, error) { var res mountDatastoreConfig mounts, ok := params["mounts"].([]interface{}) @@ -165,7 +165,7 @@ type memDatastoreConfig struct { cfg map[string]interface{} } -// MemDatastoreConfig returns a memory DatastoreConfig from a spec +// MemDatastoreConfig returns a memory DatastoreConfig from a spec. func MemDatastoreConfig(params map[string]interface{}) (DatastoreConfig, error) { return &memDatastoreConfig{params}, nil } @@ -183,7 +183,7 @@ type logDatastoreConfig struct { name string } -// LogDatastoreConfig returns a log DatastoreConfig from a spec +// LogDatastoreConfig returns a log DatastoreConfig from a spec. func LogDatastoreConfig(params map[string]interface{}) (DatastoreConfig, error) { childField, ok := params["child"].(map[string]interface{}) if !ok { @@ -198,7 +198,6 @@ func LogDatastoreConfig(params map[string]interface{}) (DatastoreConfig, error) return nil, fmt.Errorf("'name' field was missing or not a string") } return &logDatastoreConfig{child, name}, nil - } func (c *logDatastoreConfig) Create(path string) (repo.Datastore, error) { @@ -218,7 +217,7 @@ type measureDatastoreConfig struct { prefix string } -// MeasureDatastoreConfig returns a measure DatastoreConfig from a spec +// MeasureDatastoreConfig returns a measure DatastoreConfig from a spec. func MeasureDatastoreConfig(params map[string]interface{}) (DatastoreConfig, error) { childField, ok := params["child"].(map[string]interface{}) if !ok { diff --git a/repo/fsrepo/fsrepo.go b/repo/fsrepo/fsrepo.go index 3c4a709c195..c2f7ca72aef 100644 --- a/repo/fsrepo/fsrepo.go +++ b/repo/fsrepo/fsrepo.go @@ -31,12 +31,12 @@ import ( ) // LockFile is the filename of the repo lock, relative to config dir -// TODO rename repo lock and hide name +// TODO rename repo lock and hide name. const LockFile = "repo.lock" var log = logging.Logger("fsrepo") -// RepoVersion is the version number that we are currently expecting to see +// RepoVersion is the version number that we are currently expecting to see. var RepoVersion = 14 var migrationInstructions = `See https://github.com/ipfs/fs-repo-migrations/blob/master/run.md @@ -64,9 +64,11 @@ func (err NoRepoError) Error() string { return fmt.Sprintf("no IPFS repo found in %s.\nplease run: 'ipfs init'", err.Path) } -const apiFile = "api" -const gatewayFile = "gateway" -const swarmKeyFile = "swarm.key" +const ( + apiFile = "api" + gatewayFile = "gateway" + swarmKeyFile = "swarm.key" +) const specFn = "datastore_spec" @@ -277,13 +279,12 @@ func initSpec(path string, conf map[string]interface{}) error { } bytes := dsc.DiskSpec().Bytes() - return os.WriteFile(fn, bytes, 0600) + return os.WriteFile(fn, bytes, 0o600) } // Init initializes a new FSRepo at the given path with the provided config. // TODO add support for custom datastores. func Init(repoPath string, conf *config.Config) error { - // packageLock must be held to ensure that the repo is not initialized more // than once. packageLock.Lock() @@ -597,7 +598,7 @@ func (r *FSRepo) BackupConfig(prefix string) (string, error) { } defer temp.Close() - orig, err := os.OpenFile(r.configFilePath, os.O_RDONLY, 0600) + orig, err := os.OpenFile(r.configFilePath, os.O_RDONLY, 0o600) if err != nil { return "", err } @@ -626,7 +627,6 @@ func (r *FSRepo) BackupConfig(prefix string) (string, error) { // We need to comb SetConfig calls and replace them when possible with a // JSON map variant. func (r *FSRepo) SetConfig(updated *config.Config) error { - // packageLock is held to provide thread-safety. packageLock.Lock() defer packageLock.Unlock() @@ -725,7 +725,7 @@ func (r *FSRepo) Datastore() repo.Datastore { return d } -// GetStorageUsage computes the storage space taken by the repo in bytes +// GetStorageUsage computes the storage space taken by the repo in bytes. func (r *FSRepo) GetStorageUsage(ctx context.Context) (uint64, error) { return ds.DiskUsage(ctx, r.Datastore()) } @@ -746,8 +746,10 @@ func (r *FSRepo) SwarmKey() ([]byte, error) { return io.ReadAll(f) } -var _ io.Closer = &FSRepo{} -var _ repo.Repo = &FSRepo{} +var ( + _ io.Closer = &FSRepo{} + _ repo.Repo = &FSRepo{} +) // IsInitialized returns true if the repo is initialized at provided |path|. func IsInitialized(path string) bool { diff --git a/repo/fsrepo/migrations/fetch.go b/repo/fsrepo/migrations/fetch.go index 7feeac6e9b0..60081210f6b 100644 --- a/repo/fsrepo/migrations/fetch.go +++ b/repo/fsrepo/migrations/fetch.go @@ -130,7 +130,7 @@ func FetchBinary(ctx context.Context, fetcher Fetcher, dist, ver, binName, out s } // Set mode of binary to executable - err = os.Chmod(out, 0755) + err = os.Chmod(out, 0o755) if err != nil { return "", err } @@ -184,7 +184,7 @@ func osWithVariant() (string, error) { // "go-ipfs_v0.8.0-rc2_linux-amd64.tar.gz" // // This would form the path: -// go-ipfs/v0.8.0/go-ipfs_v0.8.0_linux-amd64.tar.gz +// go-ipfs/v0.8.0/go-ipfs_v0.8.0_linux-amd64.tar.gz. func makeArchivePath(dist, name, ver, atype string) (string, string) { arcName := fmt.Sprintf("%s_%s_%s-%s.%s", name, ver, runtime.GOOS, runtime.GOARCH, atype) return fmt.Sprintf("%s/%s/%s", dist, ver, arcName), arcName diff --git a/repo/fsrepo/migrations/fetch_test.go b/repo/fsrepo/migrations/fetch_test.go index 2273cb5e9e0..27452d386af 100644 --- a/repo/fsrepo/migrations/fetch_test.go +++ b/repo/fsrepo/migrations/fetch_test.go @@ -184,7 +184,7 @@ func TestFetchBinary(t *testing.T) { // Windows doesn't have read-only directories https://github.com/golang/go/issues/35042 this would need to be // tested another way if runtime.GOOS != "windows" { - err = os.Chmod(tmpDir, 0555) + err = os.Chmod(tmpDir, 0o555) if err != nil { panic(err) } @@ -200,7 +200,7 @@ func TestFetchBinary(t *testing.T) { if err != nil { panic(err) } - err = os.Chmod(tmpDir, 0755) + err = os.Chmod(tmpDir, 0o755) if err != nil { panic(err) } diff --git a/repo/fsrepo/migrations/fetcher.go b/repo/fsrepo/migrations/fetcher.go index 1dc4d0345c7..dc6d3c64249 100644 --- a/repo/fsrepo/migrations/fetcher.go +++ b/repo/fsrepo/migrations/fetcher.go @@ -10,12 +10,12 @@ import ( ) const ( - // Current distribution to fetch migrations from + // Current distribution to fetch migrations from. CurrentIpfsDist = "/ipfs/QmYerugGRCZWA8yQMKDsd9daEVXUR3C5nuw3VXuX1mggHa" // fs-repo-13-to-14 v1.0.0 // Latest distribution path. Default for fetchers. LatestIpfsDist = "/ipns/dist.ipfs.tech" - // Distribution environ variable + // Distribution environ variable. envIpfsDistPath = "IPFS_DIST_PATH" ) @@ -40,7 +40,6 @@ type limitReadCloser struct { // NewMultiFetcher creates a MultiFetcher with the given Fetchers. The // Fetchers are tried in order, then passed to this function. func NewMultiFetcher(f ...Fetcher) *MultiFetcher { - mf := &MultiFetcher{ fetchers: make([]Fetcher, len(f)), } @@ -95,7 +94,7 @@ func NewLimitReadCloser(rc io.ReadCloser, limit int64) io.ReadCloser { // then returns the IPNS path. // // To get the IPFS path of the latest distribution, if not overriddin by the -// environ variable: GetDistPathEnv(CurrentIpfsDist) +// environ variable: GetDistPathEnv(CurrentIpfsDist). func GetDistPathEnv(distPath string) string { if dist := os.Getenv(envIpfsDistPath); dist != "" { return dist diff --git a/repo/fsrepo/migrations/httpfetcher.go b/repo/fsrepo/migrations/httpfetcher.go index 81e0e406d22..588a01eadfd 100644 --- a/repo/fsrepo/migrations/httpfetcher.go +++ b/repo/fsrepo/migrations/httpfetcher.go @@ -11,11 +11,11 @@ import ( const ( defaultGatewayURL = "https://ipfs.io" - // Default maximum download size + // Default maximum download size. defaultFetchLimit = 1024 * 1024 * 512 ) -// HttpFetcher fetches files over HTTP +// HttpFetcher fetches files over HTTP. type HttpFetcher struct { //nolint distPath string gateway string diff --git a/repo/fsrepo/migrations/ipfsdir.go b/repo/fsrepo/migrations/ipfsdir.go index 1f1c320bfc4..464118d1c12 100644 --- a/repo/fsrepo/migrations/ipfsdir.go +++ b/repo/fsrepo/migrations/ipfsdir.go @@ -84,7 +84,7 @@ func WriteRepoVersion(ipfsDir string, version int) error { } vFilePath := filepath.Join(ipfsDir, versionFile) - return os.WriteFile(vFilePath, []byte(fmt.Sprintf("%d\n", version)), 0644) + return os.WriteFile(vFilePath, []byte(fmt.Sprintf("%d\n", version)), 0o644) } func repoVersion(ipfsDir string) (int, error) { diff --git a/repo/fsrepo/migrations/ipfsdir_test.go b/repo/fsrepo/migrations/ipfsdir_test.go index a92a6a6d0a6..e4e6267943b 100644 --- a/repo/fsrepo/migrations/ipfsdir_test.go +++ b/repo/fsrepo/migrations/ipfsdir_test.go @@ -138,7 +138,7 @@ func testRepoVersion(t *testing.T) { t.Fatal(err) } vFilePath := filepath.Join(ipfsDir, versionFile) - err = os.WriteFile(vFilePath, []byte("bad-version-data\n"), 0644) + err = os.WriteFile(vFilePath, []byte("bad-version-data\n"), 0o644) if err != nil { panic(err) } diff --git a/repo/fsrepo/migrations/ipfsfetcher/ipfsfetcher.go b/repo/fsrepo/migrations/ipfsfetcher/ipfsfetcher.go index 977b3165690..b35cab683d8 100644 --- a/repo/fsrepo/migrations/ipfsfetcher/ipfsfetcher.go +++ b/repo/fsrepo/migrations/ipfsfetcher/ipfsfetcher.go @@ -25,7 +25,7 @@ import ( ) const ( - // Default maximum download size + // Default maximum download size. defaultFetchLimit = 1024 * 1024 * 512 tempNodeTCPAddr = "/ip4/127.0.0.1/tcp/0" @@ -155,7 +155,7 @@ func (f *IpfsFetcher) AddrInfo() peer.AddrInfo { return f.addrInfo } -// FetchedPaths returns the IPFS paths of all items fetched by this fetcher +// FetchedPaths returns the IPFS paths of all items fetched by this fetcher. func (f *IpfsFetcher) FetchedPaths() []ipath.Path { f.mutex.Lock() defer f.mutex.Unlock() diff --git a/repo/fsrepo/migrations/ipfsfetcher/ipfsfetcher_test.go b/repo/fsrepo/migrations/ipfsfetcher/ipfsfetcher_test.go index f3a2a9313da..7323d017248 100644 --- a/repo/fsrepo/migrations/ipfsfetcher/ipfsfetcher_test.go +++ b/repo/fsrepo/migrations/ipfsfetcher/ipfsfetcher_test.go @@ -55,7 +55,6 @@ func TestIpfsFetcher(t *testing.T) { if _, err = fetcher.Fetch(ctx, "/no_such_file"); err == nil { t.Fatal("expected error 404") } - } func TestInitIpfsFetcher(t *testing.T) { @@ -110,7 +109,7 @@ func TestInitIpfsFetcher(t *testing.T) { } func TestReadIpfsConfig(t *testing.T) { - var testConfig = ` + testConfig := ` { "Bootstrap": [ "/dnsaddr/bootstrap.libp2p.io/p2p/QmcZf59bWwK5XFi76CZX8cbJ4BhTzzA3gU1ZjYZcYW3dwt", diff --git a/repo/fsrepo/migrations/migrations.go b/repo/fsrepo/migrations/migrations.go index 7e764b7312d..14cc6c2de89 100644 --- a/repo/fsrepo/migrations/migrations.go +++ b/repo/fsrepo/migrations/migrations.go @@ -151,7 +151,7 @@ func ReadMigrationConfig(repoRoot string, userConfigFile string) (*config.Migrat } // GetMigrationFetcher creates one or more fetchers according to -// downloadSources, +// downloadSources,. func GetMigrationFetcher(downloadSources []string, distPath string, newIpfsFetcher func(string) Fetcher) (Fetcher, error) { const httpUserAgent = "go-ipfs" const numTriesPerHTTP = 3 diff --git a/repo/fsrepo/migrations/migrations_test.go b/repo/fsrepo/migrations/migrations_test.go index 5f029e6a130..2fd75b7e9de 100644 --- a/repo/fsrepo/migrations/migrations_test.go +++ b/repo/fsrepo/migrations/migrations_test.go @@ -191,7 +191,7 @@ func createFakeBin(from, to int, tmpDir string) { panic(err) } emptyFile.Close() - err = os.Chmod(migPath, 0755) + err = os.Chmod(migPath, 0o755) if err != nil { panic(err) } diff --git a/repo/fsrepo/migrations/unpack_test.go b/repo/fsrepo/migrations/unpack_test.go index be5bb4f3924..e1152e2cae0 100644 --- a/repo/fsrepo/migrations/unpack_test.go +++ b/repo/fsrepo/migrations/unpack_test.go @@ -35,7 +35,7 @@ func TestUnpackTgz(t *testing.T) { tmpDir := t.TempDir() badTarGzip := filepath.Join(tmpDir, "bad.tar.gz") - err := os.WriteFile(badTarGzip, []byte("bad-data\n"), 0644) + err := os.WriteFile(badTarGzip, []byte("bad-data\n"), 0o644) if err != nil { panic(err) } @@ -72,14 +72,13 @@ func TestUnpackTgz(t *testing.T) { if fi.Size() != int64(len(testData)) { t.Fatal("unpacked file size is", fi.Size(), "expected", len(testData)) } - } func TestUnpackZip(t *testing.T) { tmpDir := t.TempDir() badZip := filepath.Join(tmpDir, "bad.zip") - err := os.WriteFile(badZip, []byte("bad-data\n"), 0644) + err := os.WriteFile(badZip, []byte("bad-data\n"), 0o644) if err != nil { panic(err) } @@ -153,7 +152,7 @@ func writeTarGzip(root, fileName, data string, w io.Writer) error { if fileName != "" { hdr := &tar.Header{ Name: path.Join(root, fileName), - Mode: 0600, + Mode: 0o600, Size: int64(len(data)), } // Write header diff --git a/repo/mock.go b/repo/mock.go index ae4d98d3b3a..46bb0cb4210 100644 --- a/repo/mock.go +++ b/repo/mock.go @@ -15,7 +15,7 @@ import ( var errTODO = errors.New("TODO: mock repo") -// Mock is not thread-safe +// Mock is not thread-safe. type Mock struct { C config.Config D Datastore diff --git a/repo/repo.go b/repo/repo.go index 05e938825a5..9abdf867e47 100644 --- a/repo/repo.go +++ b/repo/repo.go @@ -15,9 +15,7 @@ import ( ma "github.com/multiformats/go-multiaddr" ) -var ( - ErrApiNotRunning = errors.New("api not running") //nolint -) +var ErrApiNotRunning = errors.New("api not running") //nolint // Repo represents all persistent data of a given ipfs node. type Repo interface { diff --git a/routing/composer.go b/routing/composer.go index 24af9b356be..92c351fc53c 100644 --- a/routing/composer.go +++ b/routing/composer.go @@ -11,8 +11,10 @@ import ( "github.com/multiformats/go-multihash" ) -var _ routinghelpers.ProvideManyRouter = &Composer{} -var _ routing.Routing = &Composer{} +var ( + _ routinghelpers.ProvideManyRouter = &Composer{} + _ routing.Routing = &Composer{} +) type Composer struct { GetValueRouter routing.Routing @@ -27,7 +29,6 @@ func (c *Composer) Provide(ctx context.Context, cid cid.Cid, provide bool) error err := c.ProvideRouter.Provide(ctx, cid, provide) if err != nil { log.Debug("composer: calling provide: ", cid, " error: ", err) - } return err diff --git a/routing/delegated_test.go b/routing/delegated_test.go index da0210f5ebb..028f3b465f6 100644 --- a/routing/delegated_test.go +++ b/routing/delegated_test.go @@ -154,7 +154,6 @@ func TestParserRecursive(t *testing.T) { _, ok := router.(*Composer) require.True(ok) - } func TestParserRecursiveLoop(t *testing.T) { diff --git a/routing/wrapper.go b/routing/wrapper.go index f6a753843cd..10df177e017 100644 --- a/routing/wrapper.go +++ b/routing/wrapper.go @@ -13,8 +13,10 @@ type ProvideManyRouter interface { routing.Routing } -var _ routing.Routing = &httpRoutingWrapper{} -var _ routinghelpers.ProvideManyRouter = &httpRoutingWrapper{} +var ( + _ routing.Routing = &httpRoutingWrapper{} + _ routinghelpers.ProvideManyRouter = &httpRoutingWrapper{} +) // httpRoutingWrapper is a wrapper needed to construct the routing.Routing interface from // http delegated routing. diff --git a/tar/format.go b/tar/format.go index f3a2d3fb53c..626e0982b51 100644 --- a/tar/format.go +++ b/tar/format.go @@ -21,8 +21,10 @@ import ( var log = logging.Logger("tarfmt") -var blockSize = 512 -var zeroBlock = make([]byte, blockSize) +var ( + blockSize = 512 + zeroBlock = make([]byte, blockSize) +) func marshalHeader(h *tar.Header) ([]byte, error) { buf := new(bytes.Buffer) @@ -91,7 +93,7 @@ func ImportTar(ctx context.Context, r io.Reader, ds ipld.DAGService) (*dag.Proto } // adds a '-' to the beginning of each path element so we can use 'data' as a -// special link in the structure without having to worry about +// special link in the structure without having to worry about. func escapePath(pth string) string { elems := path.SplitList(strings.Trim(pth, "/")) for i, e := range elems { diff --git a/test/cli/basic_commands_test.go b/test/cli/basic_commands_test.go index 220ef285452..59444332aa6 100644 --- a/test/cli/basic_commands_test.go +++ b/test/cli/basic_commands_test.go @@ -210,7 +210,6 @@ func TestCommandDocsWidth(t *testing.T) { for _, line := range SplitLines(res) { assert.LessOrEqualf(t, len(line), 80, "expected width %d < 80 for %q", len(line), cmd) } - }) } } @@ -226,7 +225,6 @@ func TestAllCommandsFailWhenPassedBadFlag(t *testing.T) { assert.Equal(t, 1, res.Cmd.ProcessState.ExitCode()) }) } - } func TestCommandsFlags(t *testing.T) { diff --git a/test/cli/content_routing_http_test.go b/test/cli/content_routing_http_test.go index c1ea64d3fb5..2734e26003d 100644 --- a/test/cli/content_routing_http_test.go +++ b/test/cli/content_routing_http_test.go @@ -37,6 +37,7 @@ func (r *fakeHTTPContentRouter) ProvideBitswap(ctx context.Context, req *server. r.provideCalls++ return 0, nil } + func (r *fakeHTTPContentRouter) Provide(ctx context.Context, req *server.WriteProvideRequest) (types.ProviderResponse, error) { r.m.Lock() defer r.m.Unlock() diff --git a/test/cli/dag_test.go b/test/cli/dag_test.go index edcacffaefa..d17b71cfb12 100644 --- a/test/cli/dag_test.go +++ b/test/cli/dag_test.go @@ -101,5 +101,4 @@ func TestDag(t *testing.T) { stat := node.RunIPFS("dag", "stat", "--progress=false", node1Cid, node2Cid) assert.Equal(t, content, stat.Stdout.Bytes()) }) - } diff --git a/test/cli/delegated_routing_http_test.go b/test/cli/delegated_routing_http_test.go index b1ebacd1478..c02264f9482 100644 --- a/test/cli/delegated_routing_http_test.go +++ b/test/cli/delegated_routing_http_test.go @@ -155,5 +155,4 @@ func TestHTTPDelegatedRouting(t *testing.T) { resp := node.APIClient().Get("/debug/metrics/prometheus") assert.Contains(t, resp.Body, "routing_http_client_length_count") }) - } diff --git a/test/cli/dht_legacy_test.go b/test/cli/dht_legacy_test.go index 5a84b89631b..2b90d164cb2 100644 --- a/test/cli/dht_legacy_test.go +++ b/test/cli/dht_legacy_test.go @@ -107,7 +107,6 @@ func TestLegacyDHT(t *testing.T) { sort.IntSlice(counts).Sort() assert.Equal(t, []int{1, 4}, counts) }) - }) t.Run("dht commands fail when offline", func(t *testing.T) { diff --git a/test/cli/gateway_test.go b/test/cli/gateway_test.go index eb955b593b3..b2729da3c44 100644 --- a/test/cli/gateway_test.go +++ b/test/cli/gateway_test.go @@ -196,9 +196,7 @@ func TestGateway(t *testing.T) { resp.Body, fmt.Sprintf(``, peerID), ) - }) - }) t.Run("GET invalid IPFS path errors", func(t *testing.T) { @@ -583,7 +581,6 @@ func TestGateway(t *testing.T) { assert.Equal(t, test.deserializedGatewayStaticCode, client.Get(deserializedPath, setHost).StatusCode) assert.Equal(t, test.deserializedGatewayStaticCode, client.Get(deserializedPath, withHostAndAccept("application/json")).StatusCode) - } } diff --git a/test/cli/harness/harness.go b/test/cli/harness/harness.go index e68116b5efc..067608cdc38 100644 --- a/test/cli/harness/harness.go +++ b/test/cli/harness/harness.go @@ -127,11 +127,11 @@ func (h *Harness) WriteFile(filename, contents string) { log.Panicf("%s must be a relative path", filename) } absPath := filepath.Join(h.Runner.Dir, filename) - err := os.MkdirAll(filepath.Dir(absPath), 0777) + err := os.MkdirAll(filepath.Dir(absPath), 0o777) if err != nil { log.Panicf("creating intermediate dirs for %q: %s", filename, err.Error()) } - err = os.WriteFile(absPath, []byte(contents), 0644) + err = os.WriteFile(absPath, []byte(contents), 0o644) if err != nil { log.Panicf("writing %q (%q): %s", filename, absPath, err.Error()) } @@ -166,7 +166,7 @@ func (h *Harness) Mkdirs(paths ...string) { log.Panicf("%s must be a relative path when making dirs", path) } absPath := filepath.Join(h.Runner.Dir, path) - err := os.MkdirAll(absPath, 0777) + err := os.MkdirAll(absPath, 0o777) if err != nil { log.Panicf("recursively making dirs under %s: %s", absPath, err) } diff --git a/test/cli/harness/node.go b/test/cli/harness/node.go index 0516c2b452d..9fc01f4d7ca 100644 --- a/test/cli/harness/node.go +++ b/test/cli/harness/node.go @@ -46,7 +46,7 @@ type Node struct { func BuildNode(ipfsBin, baseDir string, id int) *Node { dir := filepath.Join(baseDir, strconv.Itoa(id)) - if err := os.MkdirAll(dir, 0755); err != nil { + if err := os.MkdirAll(dir, 0o755); err != nil { panic(err) } diff --git a/test/cli/harness/peering.go b/test/cli/harness/peering.go index 13c3430f065..7680eaf575f 100644 --- a/test/cli/harness/peering.go +++ b/test/cli/harness/peering.go @@ -26,7 +26,6 @@ func CreatePeerNodes(t *testing.T, n int, peerings []Peering) (*Harness, Nodes) cfg.Routing.Type = config.NewOptionalString("none") cfg.Addresses.Swarm = []string{fmt.Sprintf("/ip4/127.0.0.1/tcp/%d", NewRandPort())} }) - }) for _, peering := range peerings { diff --git a/test/cli/harness/run.go b/test/cli/harness/run.go index 75c07bcc2cf..bec05fbce68 100644 --- a/test/cli/harness/run.go +++ b/test/cli/harness/run.go @@ -14,8 +14,10 @@ type Runner struct { Verbose bool } -type CmdOpt func(*exec.Cmd) -type RunFunc func(*exec.Cmd) error +type ( + CmdOpt func(*exec.Cmd) + RunFunc func(*exec.Cmd) error +) var RunFuncStart = (*exec.Cmd).Start @@ -100,11 +102,9 @@ func (r *Runner) AssertNoError(result *RunResult) { if result.ExitErr != nil { log.Panicf("'%s' returned error, code: %d, err: %s\nstdout:%s\nstderr:%s\n", result.Cmd.Args, result.ExitErr.ExitCode(), result.ExitErr.Error(), result.Stdout.String(), result.Stderr.String()) - } if result.Err != nil { log.Panicf("unable to run %s: %s", result.Cmd.Path, result.Err) - } } diff --git a/test/cli/init_test.go b/test/cli/init_test.go index a45ef05d5b3..217ec64c3dc 100644 --- a/test/cli/init_test.go +++ b/test/cli/init_test.go @@ -88,13 +88,12 @@ func TestInit(t *testing.T) { t.Parallel() node := harness.NewT(t).NewNode() badDir := fp.Join(node.Dir, ".badipfs") - err := os.Mkdir(badDir, 0000) + err := os.Mkdir(badDir, 0o000) require.NoError(t, err) res := node.RunIPFS("init", "--repo-dir", badDir) assert.NotEqual(t, 0, res.Cmd.ProcessState.ExitCode()) assert.Contains(t, res.Stderr.String(), "permission denied") - }) t.Run("init with ed25519", func(t *testing.T) { @@ -160,5 +159,4 @@ func TestInit(t *testing.T) { assert.NotEqual(t, 0, res.ExitErr.ExitCode()) assert.Contains(t, res.Stderr.String(), "Error: ipfs daemon is running. please stop it to run this command") }) - } diff --git a/test/cli/pins_test.go b/test/cli/pins_test.go index 14a3dc2385c..8a36d469523 100644 --- a/test/cli/pins_test.go +++ b/test/cli/pins_test.go @@ -76,7 +76,6 @@ func testPins(t *testing.T, args testPinsArgs) { for _, cid := range cids { assert.Contains(t, verboseVerifyOut, fmt.Sprintf("%s ok", cid)) } - }) t.Run("ls output should contain the cids", func(t *testing.T) { lsOut := ipfsPinLS() @@ -195,7 +194,6 @@ func TestPins(t *testing.T) { testPins(t, testPinsArgs{pinArg: "--progress", lsArg: "--stream"}) testPins(t, testPinsArgs{baseArg: "--cid-base=base32"}) testPins(t, testPinsArgs{lsArg: "--stream", baseArg: "--cid-base=base32"}) - }) t.Run("test pinning with daemon running without network", func(t *testing.T) { diff --git a/test/cli/swarm_test.go b/test/cli/swarm_test.go index 920d310baa2..ecb66836269 100644 --- a/test/cli/swarm_test.go +++ b/test/cli/swarm_test.go @@ -36,7 +36,6 @@ func TestSwarm(t *testing.T) { err := json.Unmarshal(res.Stdout.Bytes(), &output) assert.NoError(t, err) assert.Equal(t, 0, len(output.Peers)) - }) t.Run("ipfs swarm peers with flag identify outputs expected identify information about connected peers", func(t *testing.T) { t.Parallel() @@ -63,7 +62,6 @@ func TestSwarm(t *testing.T) { assert.Len(t, actualAdresses, 1) assert.Equal(t, expectedAddresses[0], actualAdresses[0]) assert.Greater(t, len(actualProtocols), 0) - }) 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) { assert.Equal(t, outputIdentify.AgentVersion, otherNodeIDOutput.AgentVersion) assert.ElementsMatch(t, outputIdentify.Addresses, otherNodeIDOutput.Addresses) assert.ElementsMatch(t, outputIdentify.Protocols, otherNodeIDOutput.Protocols) - }) } diff --git a/test/cli/testutils/random_files.go b/test/cli/testutils/random_files.go index 0e550a125e3..c7dca10d6de 100644 --- a/test/cli/testutils/random_files.go +++ b/test/cli/testutils/random_files.go @@ -9,8 +9,10 @@ import ( "time" ) -var AlphabetEasy = []rune("abcdefghijklmnopqrstuvwxyz01234567890-_") -var AlphabetHard = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ01234567890!@#$%^&*()-_+= ;.,<>'\"[]{}() ") +var ( + AlphabetEasy = []rune("abcdefghijklmnopqrstuvwxyz01234567890-_") + AlphabetHard = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ01234567890!@#$%^&*()-_+= ;.,<>'\"[]{}() ") +) type RandFiles struct { Rand *rand.Rand @@ -104,7 +106,7 @@ func (r *RandFiles) WriteRandomDir(root string, depth int) error { n := rand.Intn(r.FilenameSize-4) + 4 name := r.RandomFilename(n) root = path.Join(root, name) - if err := os.MkdirAll(root, 0755); err != nil { + if err := os.MkdirAll(root, 0o755); err != nil { return fmt.Errorf("creating random dir: %w", err) } diff --git a/test/cli/tracing_test.go b/test/cli/tracing_test.go index ef717716eaa..6f19759beec 100644 --- a/test/cli/tracing_test.go +++ b/test/cli/tracing_test.go @@ -45,7 +45,7 @@ func TestTracing(t *testing.T) { // touch traces.json and give it 777 perms in case Docker runs as a different user node.WriteBytes("traces.json", nil) - err := os.Chmod(filepath.Join(node.Dir, "traces.json"), 0777) + err := os.Chmod(filepath.Join(node.Dir, "traces.json"), 0o777) require.NoError(t, err) dockerBin, err := exec.LookPath("docker") diff --git a/test/cli/transports_test.go b/test/cli/transports_test.go index 73f08c2e5fd..d37c78aad1a 100644 --- a/test/cli/transports_test.go +++ b/test/cli/transports_test.go @@ -32,7 +32,7 @@ func TestTransports(t *testing.T) { } checkRandomDir := func(nodes harness.Nodes) { randDir := filepath.Join(nodes[0].Dir, "foobar") - require.NoError(t, os.Mkdir(randDir, 0777)) + require.NoError(t, os.Mkdir(randDir, 0o777)) rf := testutils.NewRandFiles() rf.FanoutDirs = 3 rf.FanoutFiles = 6 @@ -148,5 +148,4 @@ func TestTransports(t *testing.T) { nodes.StartDaemons().Connect() runTests(nodes) }) - } diff --git a/test/dependencies/iptb/iptb.go b/test/dependencies/iptb/iptb.go index e3668c0a134..3344c656bda 100644 --- a/test/dependencies/iptb/iptb.go +++ b/test/dependencies/iptb/iptb.go @@ -19,7 +19,6 @@ func init() { PluginName: plugin.PluginName, BuiltIn: true, }, false) - if err != nil { panic(err) } diff --git a/test/dependencies/ma-pipe-unidir/main.go b/test/dependencies/ma-pipe-unidir/main.go index 5fdd3e09e3b..f8a2e32dc09 100644 --- a/test/dependencies/ma-pipe-unidir/main.go +++ b/test/dependencies/ma-pipe-unidir/main.go @@ -57,7 +57,7 @@ func app() int { if len(opts.PidFile) > 0 { data := []byte(strconv.Itoa(os.Getpid())) - err := os.WriteFile(opts.PidFile, data, 0644) + err := os.WriteFile(opts.PidFile, data, 0o644) if err != nil { return 1 } @@ -78,7 +78,7 @@ func app() int { if len(opts.PidFile) > 0 { data := []byte(strconv.Itoa(os.Getpid())) - err := os.WriteFile(opts.PidFile, data, 0644) + err := os.WriteFile(opts.PidFile, data, 0o644) if err != nil { return 1 } diff --git a/test/integration/bench_test.go b/test/integration/bench_test.go index b702bae032d..c269eddad38 100644 --- a/test/integration/bench_test.go +++ b/test/integration/bench_test.go @@ -8,7 +8,6 @@ import ( ) func benchmarkAddCat(numBytes int64, conf testutil.LatencyConfig, b *testing.B) { - b.StopTimer() b.SetBytes(numBytes) data := RandomBytes(numBytes) // we don't want to measure the time it takes to generate this data diff --git a/test/integration/wan_lan_dht_test.go b/test/integration/wan_lan_dht_test.go index 58558de3310..7c70aa98f49 100644 --- a/test/integration/wan_lan_dht_test.go +++ b/test/integration/wan_lan_dht_test.go @@ -51,8 +51,10 @@ func TestDHTConnectivitySlowRouting(t *testing.T) { } // wan prefix must have a real corresponding ASN for the peer diversity filter to work. -var wanPrefix = net.ParseIP("2001:218:3004::") -var lanPrefix = net.ParseIP("fe80::") +var ( + wanPrefix = net.ParseIP("2001:218:3004::") + lanPrefix = net.ParseIP("fe80::") +) func makeAddr(n uint32, wan bool) ma.Multiaddr { var ip net.IP diff --git a/thirdparty/dir/dir.go b/thirdparty/dir/dir.go index 1549cc80b60..5aa93c329bd 100644 --- a/thirdparty/dir/dir.go +++ b/thirdparty/dir/dir.go @@ -8,7 +8,7 @@ import ( "path/filepath" ) -// Writable ensures the directory exists and is writable +// Writable ensures the directory exists and is writable. func Writable(path string) error { // Construct the path if missing if err := os.MkdirAll(path, os.ModePerm); err != nil { diff --git a/thirdparty/notifier/notifier_test.go b/thirdparty/notifier/notifier_test.go index 9b9692ef13e..401b3b02ae7 100644 --- a/thirdparty/notifier/notifier_test.go +++ b/thirdparty/notifier/notifier_test.go @@ -7,7 +7,7 @@ import ( "time" ) -// test data structures +// test data structures. type Router struct { queue chan Packet notifier Notifier @@ -36,7 +36,6 @@ func (r *Router) notifyAll(notify func(n RouterNotifiee)) { } func (r *Router) Receive(p Packet) { - select { case r.queue <- p: // enqueued r.notifyAll(func(n RouterNotifiee) { @@ -100,7 +99,6 @@ func (m *Metrics) String() string { } func TestNotifies(t *testing.T) { - m := Metrics{received: make(chan struct{})} r := Router{queue: make(chan Packet, 10)} r.Notify(&m) diff --git a/thirdparty/unit/unit.go b/thirdparty/unit/unit.go index feeaa42bb2f..3b10db44cb8 100644 --- a/thirdparty/unit/unit.go +++ b/thirdparty/unit/unit.go @@ -15,11 +15,10 @@ const ( ) func (i Information) String() string { - tmp := int64(i) // default - var d = tmp + d := tmp symbol := "B" switch { diff --git a/version.go b/version.go index 265ec937e83..5eb0e2981c0 100644 --- a/version.go +++ b/version.go @@ -7,10 +7,10 @@ import ( "github.com/ipfs/kubo/repo/fsrepo" ) -// CurrentCommit is the current git commit, this is set as a ldflag in the Makefile +// CurrentCommit is the current git commit, this is set as a ldflag in the Makefile. var CurrentCommit string -// CurrentVersionNumber is the current application's version literal +// CurrentVersionNumber is the current application's version literal. const CurrentVersionNumber = "0.23.0-dev" const ApiVersion = "/kubo/" + CurrentVersionNumber + "/" //nolint @@ -48,7 +48,7 @@ func GetVersionInfo() *VersionInfo { Version: CurrentVersionNumber, Commit: CurrentCommit, Repo: fmt.Sprint(fsrepo.RepoVersion), - System: runtime.GOARCH + "/" + runtime.GOOS, //TODO: Precise version here + System: runtime.GOARCH + "/" + runtime.GOOS, // TODO: Precise version here Golang: runtime.Version(), } }