diff --git a/.golangci.yml b/.golangci.yml new file mode 100644 index 000000000000..de174afc44c1 --- /dev/null +++ b/.golangci.yml @@ -0,0 +1,3 @@ +linters: + enable: + - stylecheck diff --git a/cmd/ipfs/add_migrations.go b/cmd/ipfs/add_migrations.go index 95e0d10dab13..6d62b4d6bae6 100644 --- a/cmd/ipfs/add_migrations.go +++ b/cmd/ipfs/add_migrations.go @@ -56,7 +56,7 @@ func addMigrations(ctx context.Context, node *core.IpfsNode, fetcher migrations. } } default: - return errors.New("Cannot get migrations from unknown fetcher type") + return errors.New("cannot get migrations from unknown fetcher type") } } @@ -118,9 +118,9 @@ func addMigrationPaths(ctx context.Context, node *core.IpfsNode, peerInfo peer.A fmt.Printf("connected to migration peer %q\n", peerInfo) if pin { - pinApi := ipfs.Pin() + pinAPI := ipfs.Pin() for _, ipfsPath := range paths { - err := pinApi.Add(ctx, ipfsPath) + err := pinAPI.Add(ctx, ipfsPath) if err != nil { return err } diff --git a/cmd/ipfs/daemon.go b/cmd/ipfs/daemon.go index 34762e74798e..1bfb9d6f1137 100644 --- a/cmd/ipfs/daemon.go +++ b/cmd/ipfs/daemon.go @@ -62,7 +62,7 @@ const ( routingOptionCustomKwd = "custom" routingOptionDefaultKwd = "default" unencryptTransportKwd = "disable-transport-encryption" - unrestrictedApiAccessKwd = "unrestricted-api" + unrestrictedAPIAccessKwd = "unrestricted-api" writableKwd = "writable" enablePubSubKwd = "enable-pubsub-experiment" enableIPNSPubSubKwd = "enable-namesys-pubsub" @@ -174,7 +174,7 @@ Headers. cmds.BoolOption(writableKwd, "Enable writing objects (with POST, PUT and DELETE)"), cmds.StringOption(ipfsMountKwd, "Path to the mountpoint for IPFS (if using --mount). Defaults to config setting."), cmds.StringOption(ipnsMountKwd, "Path to the mountpoint for IPNS (if using --mount). Defaults to config setting."), - cmds.BoolOption(unrestrictedApiAccessKwd, "Allow API access to unlisted hashes"), + cmds.BoolOption(unrestrictedAPIAccessKwd, "Allow API access to unlisted hashes"), cmds.BoolOption(unencryptTransportKwd, "Disable transport encryption (for debugging protocols)"), cmds.BoolOption(enableGCKwd, "Enable automatic periodic repo garbage collection"), cmds.BoolOption(adjustFDLimitKwd, "Check and raise file descriptor limits if needed").WithDefault(true), @@ -654,7 +654,7 @@ func serveHTTPApi(req *cmds.Request, cctx *oldcmds.Context) (<-chan error, error // because this would open up the api to scripting vulnerabilities. // only the webui objects are allowed. // if you know what you're doing, go ahead and pass --unrestricted-api. - unrestricted, _ := req.Options[unrestrictedApiAccessKwd].(bool) + unrestricted, _ := req.Options[unrestrictedAPIAccessKwd].(bool) gatewayOpt := corehttp.GatewayOption(false, corehttp.WebUIPaths...) if unrestricted { gatewayOpt = corehttp.GatewayOption(true, "/ipfs", "/ipns") diff --git a/cmd/ipfs/init.go b/cmd/ipfs/init.go index b312fcb49112..745ceb3e23df 100644 --- a/cmd/ipfs/init.go +++ b/cmd/ipfs/init.go @@ -32,8 +32,9 @@ const ( profileOptionName = "profile" ) +// nolint var errRepoExists = errors.New(`ipfs configuration file already exists! -Reinitializing would overwrite your keys. +Reinitializing would overwrite your keys `) var initCmd = &cmds.Command{ diff --git a/cmd/ipfs/ipfs.go b/cmd/ipfs/ipfs.go index 6b30a0fc8aae..24aea66c7860 100644 --- a/cmd/ipfs/ipfs.go +++ b/cmd/ipfs/ipfs.go @@ -6,7 +6,7 @@ import ( cmds "github.com/ipfs/go-ipfs-cmds" ) -// This is the CLI root, used for executing commands accessible to CLI clients. +// Root is the CLI root, used for executing commands accessible to CLI clients. // Some subcommands (like 'ipfs daemon' or 'ipfs init') are only accessible here, // and can't be called through the HTTP API. var Root = &cmds.Command{ diff --git a/cmd/ipfs/pinmfs_test.go b/cmd/ipfs/pinmfs_test.go index 1f0c3636ac97..78c7a863bd79 100644 --- a/cmd/ipfs/pinmfs_test.go +++ b/cmd/ipfs/pinmfs_test.go @@ -98,7 +98,7 @@ func TestPinMFSRootNodeError(t *testing.T) { } func TestPinMFSService(t *testing.T) { - cfg_invalid_interval := &config.Config{ + cfgInvalidInterval := &config.Config{ Pinning: config.Pinning{ RemoteServices: map[string]config.RemotePinningService{ "disabled": { @@ -119,7 +119,7 @@ func TestPinMFSService(t *testing.T) { }, }, } - cfg_valid_unnamed := &config.Config{ + cfgValidUnnamed := &config.Config{ Pinning: config.Pinning{ RemoteServices: map[string]config.RemotePinningService{ "valid_unnamed": { @@ -134,7 +134,7 @@ func TestPinMFSService(t *testing.T) { }, }, } - cfg_valid_named := &config.Config{ + cfgValidNamed := &config.Config{ Pinning: config.Pinning{ RemoteServices: map[string]config.RemotePinningService{ "valid_named": { @@ -149,9 +149,9 @@ func TestPinMFSService(t *testing.T) { }, }, } - testPinMFSServiceWithError(t, cfg_invalid_interval, "remote pinning service \"invalid_interval\" has invalid MFS.RepinInterval") - testPinMFSServiceWithError(t, cfg_valid_unnamed, "error while listing remote pins: empty response from remote pinning service") - testPinMFSServiceWithError(t, cfg_valid_named, "error while listing remote pins: empty response from remote pinning service") + testPinMFSServiceWithError(t, cfgInvalidInterval, "remote pinning service \"invalid_interval\" has invalid MFS.RepinInterval") + testPinMFSServiceWithError(t, cfgValidUnnamed, "error while listing remote pins: empty response from remote pinning service") + testPinMFSServiceWithError(t, cfgValidNamed, "error while listing remote pins: empty response from remote pinning service") } func testPinMFSServiceWithError(t *testing.T, cfg *config.Config, expectedErrorPrefix string) { diff --git a/config/experiments.go b/config/experiments.go index a576a5b618a8..7ad87c85303b 100644 --- a/config/experiments.go +++ b/config/experiments.go @@ -6,7 +6,7 @@ type Experiments struct { ShardingEnabled bool `json:",omitempty"` // deprecated by autosharding: https://github.com/ipfs/kubo/pull/8527 GraphsyncEnabled bool Libp2pStreamMounting bool - P2pHttpProxy bool + P2pHttpProxy bool //nolint StrategicProviding bool AcceleratedDHTClient bool } diff --git a/core/commands/cid.go b/core/commands/cid.go index 0cf0e9dc05da..a6406a3e0f53 100644 --- a/core/commands/cid.go +++ b/core/commands/cid.go @@ -13,7 +13,6 @@ import ( verifcid "github.com/ipfs/go-verifcid" ipldmulticodec "github.com/ipld/go-ipld-prime/multicodec" mbase "github.com/multiformats/go-multibase" - "github.com/multiformats/go-multicodec" mc "github.com/multiformats/go-multicodec" mhash "github.com/multiformats/go-multihash" ) @@ -71,7 +70,7 @@ The optional format string is a printf style format string: opts.fmtStr = fmtStr if codecStr != "" { - var codec multicodec.Code + var codec mc.Code err := codec.Set(codecStr) if err != nil { return err diff --git a/core/commands/cmdenv/env.go b/core/commands/cmdenv/env.go index 48cbf2b034b5..2c58458907dc 100644 --- a/core/commands/cmdenv/env.go +++ b/core/commands/cmdenv/env.go @@ -27,7 +27,7 @@ func GetNode(env interface{}) (*core.IpfsNode, error) { } // GetApi extracts CoreAPI instance from the environment. -func GetApi(env cmds.Environment, req *cmds.Request) (coreiface.CoreAPI, error) { +func GetApi(env cmds.Environment, req *cmds.Request) (coreiface.CoreAPI, error) { //nolint ctx, ok := env.(*commands.Context) if !ok { return nil, fmt.Errorf("expected env to be of type %T, got %T", ctx, env) diff --git a/core/commands/dag/dag.go b/core/commands/dag/dag.go index 77c9ee4b590e..df7762c0062f 100644 --- a/core/commands/dag/dag.go +++ b/core/commands/dag/dag.go @@ -223,7 +223,7 @@ Specification of CAR formats: https://ipld.io/specs/transport/car/ // event should have only one of `Root` or `Stats` set, not both if event.Root == nil { if event.Stats == nil { - return fmt.Errorf("Unexpected message from DAG import") + return fmt.Errorf("unexpected message from DAG import") } stats, _ := req.Options[statsOptionName].(bool) if stats { @@ -233,7 +233,7 @@ Specification of CAR formats: https://ipld.io/specs/transport/car/ } if event.Stats != nil { - return fmt.Errorf("Unexpected message from DAG import") + return fmt.Errorf("unexpected message from DAG import") } enc, err := cmdenv.GetLowLevelCidEncoder(req) diff --git a/core/commands/dag/export.go b/core/commands/dag/export.go index 14e982bcc03b..e9d120e8794f 100644 --- a/core/commands/dag/export.go +++ b/core/commands/dag/export.go @@ -85,7 +85,7 @@ func finishCLIExport(res cmds.Response, re cmds.ResponseEmitter) error { if !specified { // default based on TTY availability errStat, _ := os.Stderr.Stat() - if 0 != (errStat.Mode() & os.ModeCharDevice) { + if (errStat.Mode() & os.ModeCharDevice) != 0 { showProgress = true } } else if val.(bool) { diff --git a/core/commands/id.go b/core/commands/id.go index b3fc076fb4a8..887f93efe311 100644 --- a/core/commands/id.go +++ b/core/commands/id.go @@ -23,9 +23,9 @@ import ( identify "github.com/libp2p/go-libp2p/p2p/protocol/identify" ) -const offlineIdErrorMessage = "'ipfs id' cannot query information on remote peers without a running daemon; if you only want to convert --peerid-base, pass --offline option." +const offlineIDErrorMessage = "'ipfs id' cannot query information on remote peers without a running daemon; if you only want to convert --peerid-base, pass --offline option" -type IdOutput struct { +type IdOutput struct { //nolint ID string PublicKey string Addresses []string @@ -98,7 +98,7 @@ EXAMPLE: offline, _ := req.Options[OfflineOption].(bool) if !offline && !n.IsOnline { - return errors.New(offlineIdErrorMessage) + return errors.New(offlineIDErrorMessage) } if !offline { @@ -107,7 +107,7 @@ EXAMPLE: switch err { case nil: case kb.ErrLookupFailure: - return errors.New(offlineIdErrorMessage) + return errors.New(offlineIDErrorMessage) default: return err } diff --git a/core/commands/keystore.go b/core/commands/keystore.go index e931c38ea2a4..f530d5eda93b 100644 --- a/core/commands/keystore.go +++ b/core/commands/keystore.go @@ -56,7 +56,7 @@ publish'. type KeyOutput struct { Name string - Id string + Id string //nolint } type KeyOutputList struct { @@ -67,7 +67,7 @@ type KeyOutputList struct { type KeyRenameOutput struct { Was string Now string - Id string + Id string //nolint Overwrite bool } diff --git a/core/commands/multibase.go b/core/commands/multibase.go index be8d613f29cb..d985aebf0c23 100644 --- a/core/commands/multibase.go +++ b/core/commands/multibase.go @@ -105,11 +105,11 @@ This command expects multibase inside of a file or via stdin: if err != nil { return fmt.Errorf("failed to access file: %w", err) } - encoded_data, err := io.ReadAll(file) + encodedData, err := io.ReadAll(file) if err != nil { return fmt.Errorf("failed to read file contents: %w", err) } - _, data, err := mbase.Decode(string(encoded_data)) + _, data, err := mbase.Decode(string(encodedData)) if err != nil { return fmt.Errorf("failed to decode multibase: %w", err) } @@ -156,11 +156,11 @@ but one can customize used base with -b: if err != nil { return fmt.Errorf("failed to access file: %w", err) } - encoded_data, err := io.ReadAll(file) + encodedData, err := io.ReadAll(file) if err != nil { return fmt.Errorf("failed to read file contents: %w", err) } - _, data, err := mbase.Decode(string(encoded_data)) + _, data, err := mbase.Decode(string(encodedData)) if err != nil { return fmt.Errorf("failed to decode multibase: %w", err) } diff --git a/core/commands/pin/remotepin.go b/core/commands/pin/remotepin.go index 49db55147cc3..ae04be6075c5 100644 --- a/core/commands/pin/remotepin.go +++ b/core/commands/pin/remotepin.go @@ -214,27 +214,27 @@ NOTE: a comma-separated notation is supported in CLI for convenience: // Block unless --background=true is passed if !req.Options[pinBackgroundOptionName].(bool) { - requestId := ps.GetRequestId() + requestID := ps.GetRequestId() for { - ps, err = c.GetStatusByID(ctx, requestId) + ps, err = c.GetStatusByID(ctx, requestID) if err != nil { - return fmt.Errorf("failed to check pin status for requestid=%q due to error: %v", requestId, err) + return fmt.Errorf("failed to check pin status for requestid=%q due to error: %v", requestID, err) } - if ps.GetRequestId() != requestId { - return fmt.Errorf("failed to check pin status for requestid=%q, remote service sent unexpected requestid=%q", requestId, ps.GetRequestId()) + if ps.GetRequestId() != requestID { + return fmt.Errorf("failed to check pin status for requestid=%q, remote service sent unexpected requestid=%q", requestID, ps.GetRequestId()) } s := ps.GetStatus() if s == pinclient.StatusPinned { break } if s == pinclient.StatusFailed { - return fmt.Errorf("remote service failed to pin requestid=%q", requestId) + return fmt.Errorf("remote service failed to pin requestid=%q", requestID) } tmr := time.NewTimer(time.Second / 2) select { case <-tmr.C: case <-ctx.Done(): - return fmt.Errorf("waiting for pin interrupted, requestid=%q remains on remote service", requestId) + return fmt.Errorf("waiting for pin interrupted, requestid=%q remains on remote service", requestID) } } } @@ -665,8 +665,8 @@ TIP: pass '--enc=json' for more useful JSON output. type ServiceDetails struct { Service string - ApiEndpoint string - Stat *Stat `json:",omitempty"` // present only when --stat not passed + ApiEndpoint string //nolint + Stat *Stat `json:",omitempty"` // present only when --stat not passed } type Stat struct { diff --git a/core/commands/root.go b/core/commands/root.go index 8a14b1c1a3a9..cfa2708e6421 100644 --- a/core/commands/root.go +++ b/core/commands/root.go @@ -25,7 +25,7 @@ const ( DebugOption = "debug" LocalOption = "local" // DEPRECATED: use OfflineOption OfflineOption = "offline" - ApiOption = "api" + ApiOption = "api" //nolint ) var Root = &cmds.Command{ @@ -118,7 +118,6 @@ The CLI will exit with one of the following values: }, } -// commandsDaemonCmd is the "ipfs commands" command for daemon var CommandsDaemonCmd = CommandsCmd(Root) var rootSubcommands = map[string]*cmds.Command{ diff --git a/core/commands/stat.go b/core/commands/stat.go index 0c4331fd4ece..a09c70ea1c10 100644 --- a/core/commands/stat.go +++ b/core/commands/stat.go @@ -132,8 +132,8 @@ Example: return err } } else if tfound { - protoId := protocol.ID(tstr) - stats := nd.Reporter.GetBandwidthForProtocol(protoId) + protoID := protocol.ID(tstr) + stats := nd.Reporter.GetBandwidthForProtocol(protoID) if err := res.Emit(&stats); err != nil { return err } diff --git a/core/commands/swarm.go b/core/commands/swarm.go index a070291d0c88..eb648a3c2ad1 100644 --- a/core/commands/swarm.go +++ b/core/commands/swarm.go @@ -336,7 +336,7 @@ The output of this command is JSON. } if node.ResourceManager == nil { - return libp2p.NoResourceMgrError + return libp2p.ErrNoResourceMgr } if len(req.Arguments) != 1 { @@ -394,7 +394,7 @@ Changes made via command line are persisted in the Swarm.ResourceMgr.Limits fiel } if node.ResourceManager == nil { - return libp2p.NoResourceMgrError + return libp2p.ErrNoResourceMgr } scope := req.Arguments[0] diff --git a/core/core_test.go b/core/core_test.go index 9a9075ae7266..488eb8421ec1 100644 --- a/core/core_test.go +++ b/core/core_test.go @@ -85,18 +85,18 @@ var errNotSupported = errors.New("method not supported") func TestDelegatedRoutingSingle(t *testing.T) { require := require.New(t) - pId1, priv1, err := GeneratePeerID() + pID1, priv1, err := GeneratePeerID() require.NoError(err) - pId2, _, err := GeneratePeerID() + pID2, _, err := GeneratePeerID() require.NoError(err) - theID := path.Join("/ipns", string(pId1)) - theErrorID := path.Join("/ipns", string(pId2)) + theID := path.Join("/ipns", string(pID1)) + theErrorID := path.Join("/ipns", string(pID2)) d := &delegatedRoutingService{ - goodPeerID: pId1, - badPeerID: pId2, + goodPeerID: pID1, + badPeerID: pID2, pk1: priv1, } @@ -122,18 +122,18 @@ func TestDelegatedRoutingSingle(t *testing.T) { func TestDelegatedRoutingMulti(t *testing.T) { require := require.New(t) - pId1, priv1, err := GeneratePeerID() + pID1, priv1, err := GeneratePeerID() require.NoError(err) - pId2, priv2, err := GeneratePeerID() + pID2, priv2, err := GeneratePeerID() require.NoError(err) - theID1 := path.Join("/ipns", string(pId1)) - theID2 := path.Join("/ipns", string(pId2)) + theID1 := path.Join("/ipns", string(pID1)) + theID2 := path.Join("/ipns", string(pID2)) d1 := &delegatedRoutingService{ - goodPeerID: pId1, - badPeerID: pId2, + goodPeerID: pID1, + badPeerID: pID2, pk1: priv1, serviceID: 1, } @@ -141,8 +141,8 @@ func TestDelegatedRoutingMulti(t *testing.T) { url1 := StartRoutingServer(t, d1) d2 := &delegatedRoutingService{ - goodPeerID: pId2, - badPeerID: pId1, + goodPeerID: pID2, + badPeerID: pID1, pk1: priv2, serviceID: 2, } diff --git a/core/coreapi/coreapi.go b/core/coreapi/coreapi.go index 515da6930fa6..fb549171a6ce 100644 --- a/core/coreapi/coreapi.go +++ b/core/coreapi/coreapi.go @@ -158,7 +158,7 @@ func (api *CoreAPI) WithOptions(opts ...options.ApiOption) (coreiface.CoreAPI, e n := api.nd - subApi := &CoreAPI{ + subAPI := &CoreAPI{ nctx: n.Context(), identity: n.Identity, @@ -190,14 +190,14 @@ func (api *CoreAPI) WithOptions(opts ...options.ApiOption) (coreiface.CoreAPI, e parentOpts: settings, } - subApi.checkOnline = func(allowOffline bool) error { + subAPI.checkOnline = func(allowOffline bool) error { if !n.IsOnline && !allowOffline { return coreiface.ErrOffline } return nil } - subApi.checkPublishAllowed = func() error { + subAPI.checkPublishAllowed = func() error { if n.Mounts.Ipns != nil && n.Mounts.Ipns.IsActive() { return errors.New("cannot manually publish while IPNS is mounted") } @@ -218,39 +218,39 @@ func (api *CoreAPI) WithOptions(opts ...options.ApiOption) (coreiface.CoreAPI, e return nil, fmt.Errorf("cannot specify negative resolve cache size") } - subApi.routing = offlineroute.NewOfflineRouter(subApi.repo.Datastore(), subApi.recordValidator) + subAPI.routing = offlineroute.NewOfflineRouter(subAPI.repo.Datastore(), subAPI.recordValidator) - subApi.namesys, err = namesys.NewNameSystem(subApi.routing, - namesys.WithDatastore(subApi.repo.Datastore()), - namesys.WithDNSResolver(subApi.dnsResolver), + subAPI.namesys, err = namesys.NewNameSystem(subAPI.routing, + namesys.WithDatastore(subAPI.repo.Datastore()), + namesys.WithDNSResolver(subAPI.dnsResolver), namesys.WithCache(cs)) if err != nil { return nil, fmt.Errorf("error constructing namesys: %w", err) } - subApi.provider = provider.NewOfflineProvider() + subAPI.provider = provider.NewOfflineProvider() - subApi.peerstore = nil - subApi.peerHost = nil - subApi.recordValidator = nil + subAPI.peerstore = nil + subAPI.peerHost = nil + subAPI.recordValidator = nil } if settings.Offline || !settings.FetchBlocks { - subApi.exchange = offlinexch.Exchange(subApi.blockstore) - subApi.blocks = bserv.New(subApi.blockstore, subApi.exchange) - subApi.dag = dag.NewDAGService(subApi.blocks) + subAPI.exchange = offlinexch.Exchange(subAPI.blockstore) + subAPI.blocks = bserv.New(subAPI.blockstore, subAPI.exchange) + subAPI.dag = dag.NewDAGService(subAPI.blocks) } - return subApi, nil + return subAPI, nil } // getSession returns new api backed by the same node with a read-only session DAG func (api *CoreAPI) getSession(ctx context.Context) *CoreAPI { - sesApi := *api + sesAPI := *api // TODO: We could also apply this to api.blocks, and compose into writable api, // but this requires some changes in blockservice/merkledag - sesApi.dag = dag.NewReadOnlyDagService(dag.NewSession(ctx, api.dag)) + sesAPI.dag = dag.NewReadOnlyDagService(dag.NewSession(ctx, api.dag)) - return &sesApi + return &sesAPI } diff --git a/core/coreapi/pubsub.go b/core/coreapi/pubsub.go index a1c9a07f0393..af29afecc847 100644 --- a/core/coreapi/pubsub.go +++ b/core/coreapi/pubsub.go @@ -97,7 +97,7 @@ func (api *PubSubAPI) Subscribe(ctx context.Context, topic string, opts ...caopt func (api *PubSubAPI) checkNode() (routing.Routing, error) { if api.pubSub == nil { - return nil, errors.New("experimental pubsub feature not enabled. Run daemon with --enable-pubsub-experiment to use.") + return nil, errors.New("experimental pubsub feature not enabled, run daemon with --enable-pubsub-experiment to use") } err := api.checkOnline(false) diff --git a/core/coreapi/unixfs.go b/core/coreapi/unixfs.go index e0fe0eb137d3..d43bfe3132bf 100644 --- a/core/coreapi/unixfs.go +++ b/core/coreapi/unixfs.go @@ -19,7 +19,6 @@ import ( bstore "github.com/ipfs/go-ipfs-blockstore" files "github.com/ipfs/go-ipfs-files" ipld "github.com/ipfs/go-ipld-format" - dag "github.com/ipfs/go-merkledag" merkledag "github.com/ipfs/go-merkledag" dagtest "github.com/ipfs/go-merkledag/test" mfs "github.com/ipfs/go-mfs" @@ -117,7 +116,7 @@ func (api *UnixfsAPI) Add(ctx context.Context, files files.Node, opts ...options } bserv := blockservice.New(addblockstore, exch) // hash security 001 - dserv := dag.NewDAGService(bserv) + dserv := merkledag.NewDAGService(bserv) // add a sync call to the DagService // this ensures that data written to the DagService is persisted to the underlying datastore diff --git a/core/corehttp/gateway.go b/core/corehttp/gateway.go index b9fff49b571b..0d0a234d946f 100644 --- a/core/corehttp/gateway.go +++ b/core/corehttp/gateway.go @@ -77,7 +77,7 @@ func GatewayOption(writable bool, paths ...string) ServeOption { AddAccessControlHeaders(headers) - offlineApi, err := api.WithOptions(options.Api.Offline(true)) + offlineAPI, err := api.WithOptions(options.Api.Offline(true)) if err != nil { return nil, err } @@ -86,7 +86,7 @@ func GatewayOption(writable bool, paths ...string) ServeOption { Headers: headers, Writable: writable, FastDirIndexThreshold: int(cfg.Gateway.FastDirIndexThreshold.WithDefault(100)), - }, api, offlineApi) + }, api, offlineAPI) gateway = otelhttp.NewHandler(gateway, "Gateway.Request") diff --git a/core/corehttp/gateway_handler.go b/core/corehttp/gateway_handler.go index 585ca89cb170..a96799f5875a 100644 --- a/core/corehttp/gateway_handler.go +++ b/core/corehttp/gateway_handler.go @@ -39,7 +39,7 @@ const ( ) var ( - onlyAscii = regexp.MustCompile("[[:^ascii:]]") + onlyASCII = regexp.MustCompile("[[:^ascii:]]") noModtime = time.Unix(0, 0) // disables Last-Modified header if passed as modtime ) @@ -68,7 +68,7 @@ type redirectTemplateData struct { type gatewayHandler struct { config GatewayConfig api NodeAPI - offlineApi NodeAPI + offlineAPI NodeAPI // generic metrics firstContentBlockGetMetric *prometheus.HistogramVec @@ -214,15 +214,15 @@ func newGatewayHistogramMetric(name string, help string) *prometheus.HistogramVe // NewGatewayHandler returns an http.Handler that can act as a gateway to IPFS content // offlineApi is a version of the API that should not make network requests for missing data -func NewGatewayHandler(c GatewayConfig, api NodeAPI, offlineApi NodeAPI) http.Handler { - return newGatewayHandler(c, api, offlineApi) +func NewGatewayHandler(c GatewayConfig, api NodeAPI, offlineAPI NodeAPI) http.Handler { + return newGatewayHandler(c, api, offlineAPI) } -func newGatewayHandler(c GatewayConfig, api NodeAPI, offlineApi NodeAPI) *gatewayHandler { +func newGatewayHandler(c GatewayConfig, api NodeAPI, offlineAPI NodeAPI) *gatewayHandler { i := &gatewayHandler{ config: c, api: api, - offlineApi: offlineApi, + offlineAPI: offlineAPI, // Improved Metrics // ---------------------------- // Time till the first content block (bar in /ipfs/cid/foo/bar) @@ -683,7 +683,7 @@ func addContentDispositionHeader(w http.ResponseWriter, r *http.Request, content // Set Content-Disposition to arbitrary filename and disposition func setContentDispositionHeader(w http.ResponseWriter, filename string, disposition string) { utf8Name := url.PathEscape(filename) - asciiName := url.PathEscape(onlyAscii.ReplaceAllLiteralString(filename, "_")) + asciiName := url.PathEscape(onlyASCII.ReplaceAllLiteralString(filename, "_")) w.Header().Set("Content-Disposition", fmt.Sprintf("%s; filename=\"%s\"; filename*=UTF-8''%s", disposition, asciiName, utf8Name)) } @@ -933,7 +933,7 @@ func (i *gatewayHandler) handlePathResolution(w http.ResponseWriter, r *http.Req // https://github.com/ipfs/specs/blob/main/http-gateways/PATH_GATEWAY.md#cache-control-request-header func (i *gatewayHandler) handleOnlyIfCached(w http.ResponseWriter, r *http.Request, contentPath ipath.Path, logger *zap.SugaredLogger) (requestHandled bool) { if r.Header.Get("Cache-Control") == "only-if-cached" { - _, err := i.offlineApi.Block().Stat(r.Context(), contentPath) + _, err := i.offlineAPI.Block().Stat(r.Context(), contentPath) if err != nil { if r.Method == http.MethodHead { w.WriteHeader(http.StatusPreconditionFailed) diff --git a/core/corehttp/gateway_handler_unixfs_dir.go b/core/corehttp/gateway_handler_unixfs_dir.go index 511066f43582..1c803b13b346 100644 --- a/core/corehttp/gateway_handler_unixfs_dir.go +++ b/core/corehttp/gateway_handler_unixfs_dir.go @@ -39,10 +39,10 @@ func (i *gatewayHandler) serveDirectory(ctx context.Context, w http.ResponseWrit webError(w, "failed to parse request path", err, http.StatusInternalServerError) return } - originalUrlPath := requestURI.Path + originalURLPath := requestURI.Path // Ensure directory paths end with '/' - if originalUrlPath[len(originalUrlPath)-1] != '/' { + if originalURLPath[len(originalURLPath)-1] != '/' { // don't redirect to trailing slash if it's go get // https://github.com/ipfs/kubo/pull/3963 goget := r.URL.Query().Get("go-get") == "1" @@ -53,7 +53,7 @@ func (i *gatewayHandler) serveDirectory(ctx context.Context, w http.ResponseWrit suffix = suffix + "?" + r.URL.RawQuery } // /ipfs/cid/foo?bar must be redirected to /ipfs/cid/foo/?bar - redirectURL := originalUrlPath + suffix + redirectURL := originalURLPath + suffix logger.Debugw("directory location moved permanently", "status", http.StatusMovedPermanently) http.Redirect(w, r, redirectURL, http.StatusMovedPermanently) return @@ -125,7 +125,7 @@ func (i *gatewayHandler) serveDirectory(ctx context.Context, w http.ResponseWrit di := directoryItem{ Size: "", // no size because we did not fetch child nodes Name: link.Name, - Path: gopath.Join(originalUrlPath, link.Name), + Path: gopath.Join(originalURLPath, link.Name), Hash: hash, ShortHash: shortHash(hash), } @@ -149,7 +149,7 @@ func (i *gatewayHandler) serveDirectory(ctx context.Context, w http.ResponseWrit // construct the correct back link // https://github.com/ipfs/kubo/issues/1365 - var backLink string = originalUrlPath + backLink := originalURLPath // don't go further up than /ipfs/$hash/ pathSplit := path.SplitList(contentPath.String()) diff --git a/core/corehttp/gateway_indexPage.go b/core/corehttp/gateway_indexPage.go index 1168d65560cf..19e444da3f05 100644 --- a/core/corehttp/gateway_indexPage.go +++ b/core/corehttp/gateway_indexPage.go @@ -117,8 +117,8 @@ func init() { // custom template-escaping function to escape a full path, including '#' and '?' urlEscape := func(rawUrl string) string { - pathUrl := url.URL{Path: rawUrl} - return pathUrl.String() + pathURL := url.URL{Path: rawUrl} + return pathURL.String() } // Directory listing template diff --git a/core/corehttp/lazyseek_test.go b/core/corehttp/lazyseek_test.go index 2733acafb386..49aca0a0e2a1 100644 --- a/core/corehttp/lazyseek_test.go +++ b/core/corehttp/lazyseek_test.go @@ -11,14 +11,14 @@ type badSeeker struct { io.ReadSeeker } -var badSeekErr = fmt.Errorf("I'm a bad seeker") +var errBadSeek = fmt.Errorf("bad seeker") func (bs badSeeker) Seek(offset int64, whence int) (int64, error) { off, err := bs.ReadSeeker.Seek(0, io.SeekCurrent) if err != nil { panic(err) } - return off, badSeekErr + return off, errBadSeek } func TestLazySeekerError(t *testing.T) { @@ -73,7 +73,7 @@ func TestLazySeekerError(t *testing.T) { if err == nil { t.Fatalf("expected an error, got output %s", string(b)) } - if err != badSeekErr { + if err != errBadSeek { t.Fatalf("expected a bad seek error, got %s", err) } if len(b) != 0 { diff --git a/core/corehttp/metrics.go b/core/corehttp/metrics.go index da2d576a21b1..e26be1ca9f37 100644 --- a/core/corehttp/metrics.go +++ b/core/corehttp/metrics.go @@ -164,7 +164,7 @@ type IpfsNodeCollector struct { Node *core.IpfsNode } -func (_ IpfsNodeCollector) Describe(ch chan<- *prometheus.Desc) { +func (IpfsNodeCollector) Describe(ch chan<- *prometheus.Desc) { ch <- peersTotalMetric } diff --git a/core/corehttp/p2p_proxy.go b/core/corehttp/p2p_proxy.go index 44c20c2ad5c7..e239f47cd047 100644 --- a/core/corehttp/p2p_proxy.go +++ b/core/corehttp/p2p_proxy.go @@ -58,11 +58,11 @@ func parseRequest(request *http.Request) (*proxyRequest, error) { split := strings.SplitN(path, "/", 5) if len(split) < 5 { - return nil, fmt.Errorf("Invalid request path '%s'", path) + return nil, fmt.Errorf("invalid request path '%s'", path) } if _, err := peer.Decode(split[2]); err != nil { - return nil, fmt.Errorf("Invalid request path '%s'", path) + return nil, fmt.Errorf("invalid request path '%s'", path) } if split[3] == "http" { @@ -71,7 +71,7 @@ func parseRequest(request *http.Request) (*proxyRequest, error) { split = strings.SplitN(path, "/", 7) if len(split) < 7 || split[3] != "x" || split[5] != "http" { - return nil, fmt.Errorf("Invalid request path '%s'", path) + return nil, fmt.Errorf("invalid request path '%s'", path) } return &proxyRequest{split[2], protocol.ID("/x/" + split[4] + "/http"), split[6]}, nil diff --git a/core/corehttp/redirect.go b/core/corehttp/redirect.go index 5af596bd6f37..bcd536d235ba 100644 --- a/core/corehttp/redirect.go +++ b/core/corehttp/redirect.go @@ -24,5 +24,5 @@ type redirectHandler struct { } func (i *redirectHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { - http.Redirect(w, r, i.path, 302) + http.Redirect(w, r, i.path, http.StatusFound) } diff --git a/core/corehttp/webui.go b/core/corehttp/webui.go index 4952dc16fa5e..98e69cd5c382 100644 --- a/core/corehttp/webui.go +++ b/core/corehttp/webui.go @@ -3,7 +3,7 @@ package corehttp // TODO: move to IPNS const WebUIPath = "/ipfs/bafybeiageaoxg6d7npaof6eyzqbwvbubyler7bq44hayik2hvqcggg7d2y" // v2.18.1 -// this is a list of all past webUI paths. +// WebUIPaths is a list of all past webUI paths. var WebUIPaths = []string{ WebUIPath, "/ipfs/bafybeidb5eryh72zajiokdggzo7yct2d6hhcflncji5im2y5w26uuygdsm", diff --git a/core/node/libp2p/libp2p.go b/core/node/libp2p/libp2p.go index c041139d1714..b36197152215 100644 --- a/core/node/libp2p/libp2p.go +++ b/core/node/libp2p/libp2p.go @@ -25,7 +25,6 @@ type Libp2pOpts struct { Opts []libp2p.Option `group:"libp2p"` } -// Misc options var UserAgent = simpleOpt(libp2p.UserAgent(version.GetUserAgentVersion())) func ConnectionManager(low, high int, grace time.Duration) func() (opts Libp2pOpts, err error) { diff --git a/core/node/libp2p/rcmgr.go b/core/node/libp2p/rcmgr.go index 2764f67af8a4..c24d03108178 100644 --- a/core/node/libp2p/rcmgr.go +++ b/core/node/libp2p/rcmgr.go @@ -28,7 +28,7 @@ import ( const NetLimitDefaultFilename = "limit.json" const NetLimitTraceFilename = "rcmgr.json.gz" -var NoResourceMgrError = fmt.Errorf("missing ResourceMgr: make sure the daemon is running with Swarm.ResourceMgr.Enabled") +var ErrNoResourceMgr = fmt.Errorf("missing ResourceMgr: make sure the daemon is running with Swarm.ResourceMgr.Enabled") func ResourceManager(cfg config.SwarmConfig) interface{} { return func(mctx helpers.MetricsCtx, lc fx.Lifecycle, repo repo.Repo) (network.ResourceManager, Libp2pOpts, error) { @@ -136,7 +136,7 @@ func NetStat(mgr network.ResourceManager, scope string) (NetStatOut, error) { case scope == "all": rapi, ok := mgr.(rcmgr.ResourceManagerState) if !ok { // NullResourceManager - return result, NoResourceMgrError + return result, ErrNoResourceMgr } stat := rapi.Stat() @@ -223,7 +223,7 @@ func NetLimit(mgr network.ResourceManager, scope string) (rcmgr.BaseLimit, error getLimit := func(s network.ResourceScope) error { limiter, ok := s.(rcmgr.ResourceScopeLimiter) if !ok { // NullResourceManager - return NoResourceMgrError + return ErrNoResourceMgr } limit := limiter.Limit() switch l := limit.(type) { @@ -271,7 +271,7 @@ func NetSetLimit(mgr network.ResourceManager, repo repo.Repo, scope string, limi setLimit := func(s network.ResourceScope) error { limiter, ok := s.(rcmgr.ResourceScopeLimiter) if !ok { // NullResourceManager - return NoResourceMgrError + return ErrNoResourceMgr } limiter.SetLimit(&limit) diff --git a/core/node/libp2p/transport.go b/core/node/libp2p/transport.go index e59770772a5c..d96891df2269 100644 --- a/core/node/libp2p/transport.go +++ b/core/node/libp2p/transport.go @@ -33,8 +33,7 @@ func Transports(tptConfig config.Transports) interface{} { if tptConfig.Network.QUIC.WithDefault(!privateNetworkEnabled) { if privateNetworkEnabled { return opts, fmt.Errorf( - "The QUIC transport does not support private networks. " + - "Please disable Swarm.Transports.Network.QUIC.", + "QUIC transport does not support private networks, please disable Swarm.Transports.Network.QUIC", ) } // TODO(9290): Make WithMetrics configurable @@ -45,8 +44,7 @@ func Transports(tptConfig config.Transports) interface{} { if tptConfig.Network.WebTransport.WithDefault(false && !privateNetworkEnabled) { if privateNetworkEnabled { return opts, fmt.Errorf( - "The WebTransport transport does not support private networks. " + - "Please disable Swarm.Transports.Network.WebTransport.", + "WebTransport transport does not support private networks, please disable Swarm.Transports.Network.WebTransport", ) } opts.Opts = append(opts.Opts, libp2p.Transport(webtransport.New)) diff --git a/fuse/ipns/ipns_test.go b/fuse/ipns/ipns_test.go index 06bb0cdfe590..51ac9518cf45 100644 --- a/fuse/ipns/ipns_test.go +++ b/fuse/ipns/ipns_test.go @@ -116,12 +116,12 @@ func setupIpnsTest(t *testing.T, node *core.IpfsNode) (*core.IpfsNode, *mountWra } } - coreApi, err := coreapi.NewCoreAPI(node) + coreAPI, err := coreapi.NewCoreAPI(node) if err != nil { t.Fatal(err) } - fs, err := NewFileSystem(node.Context(), coreApi, "", "") + fs, err := NewFileSystem(node.Context(), coreAPI, "", "") if err != nil { t.Fatal(err) } diff --git a/fuse/ipns/ipns_unix.go b/fuse/ipns/ipns_unix.go index e1840d259644..c198989191b8 100644 --- a/fuse/ipns/ipns_unix.go +++ b/fuse/ipns/ipns_unix.go @@ -147,25 +147,25 @@ func CreateRoot(ctx context.Context, ipfs iface.CoreAPI, keys map[string]iface.K } // Attr returns file attributes. -func (*Root) Attr(ctx context.Context, a *fuse.Attr) error { +func (r *Root) Attr(ctx context.Context, a *fuse.Attr) error { log.Debug("Root Attr") a.Mode = os.ModeDir | 0111 // -rw+x return nil } // Lookup performs a lookup under this node. -func (s *Root) Lookup(ctx context.Context, name string) (fs.Node, error) { +func (r *Root) Lookup(ctx context.Context, name string) (fs.Node, error) { switch name { case "mach_kernel", ".hidden", "._.": // Just quiet some log noise on OS X. return nil, fuse.ENOENT } - if lnk, ok := s.LocalLinks[name]; ok { + if lnk, ok := r.LocalLinks[name]; ok { return lnk, nil } - nd, ok := s.LocalDirs[name] + nd, ok := r.LocalDirs[name] if ok { switch nd := nd.(type) { case *Directory: @@ -179,7 +179,7 @@ func (s *Root) Lookup(ctx context.Context, name string) (fs.Node, error) { // other links go through ipns resolution and are symlinked into the ipfs mountpoint ipnsName := "/ipns/" + name - resolved, err := s.Ipfs.Name().Resolve(ctx, ipnsName) + resolved, err := r.Ipfs.Name().Resolve(ctx, ipnsName) if err != nil { log.Warnf("ipns: namesys resolve error: %s", err) return nil, fuse.ENOENT @@ -189,7 +189,7 @@ func (s *Root) Lookup(ctx context.Context, name string) (fs.Node, error) { return nil, errors.New("invalid path from ipns record") } - return &Link{s.IpfsRoot + "/" + strings.TrimPrefix(resolved.String(), "/ipfs/")}, nil + return &Link{r.IpfsRoot + "/" + strings.TrimPrefix(resolved.String(), "/ipfs/")}, nil } func (r *Root) Close() error { @@ -270,8 +270,8 @@ func (fi *FileNode) Attr(ctx context.Context, a *fuse.Attr) error { } // Lookup performs a lookup under this node. -func (s *Directory) Lookup(ctx context.Context, name string) (fs.Node, error) { - child, err := s.dir.Child(name) +func (d *Directory) Lookup(ctx context.Context, name string) (fs.Node, error) { + child, err := d.dir.Child(name) if err != nil { // todo: make this error more versatile. return nil, fuse.ENOENT @@ -290,8 +290,8 @@ func (s *Directory) Lookup(ctx context.Context, name string) (fs.Node, error) { } // ReadDirAll reads the link structure as directory entries -func (dir *Directory) ReadDirAll(ctx context.Context) ([]fuse.Dirent, error) { - listing, err := dir.dir.List(ctx) +func (d *Directory) ReadDirAll(ctx context.Context) ([]fuse.Dirent, error) { + listing, err := d.dir.List(ctx) if err != nil { return nil, err } @@ -401,8 +401,8 @@ func (fi *File) Forget() { } } -func (dir *Directory) Mkdir(ctx context.Context, req *fuse.MkdirRequest) (fs.Node, error) { - child, err := dir.dir.Mkdir(req.Name) +func (d *Directory) Mkdir(ctx context.Context, req *fuse.MkdirRequest) (fs.Node, error) { + child, err := d.dir.Mkdir(req.Name) if err != nil { return nil, err } @@ -451,15 +451,15 @@ func (fi *File) Release(ctx context.Context, req *fuse.ReleaseRequest) error { return fi.fi.Close() } -func (dir *Directory) Create(ctx context.Context, req *fuse.CreateRequest, resp *fuse.CreateResponse) (fs.Node, fs.Handle, error) { +func (d *Directory) Create(ctx context.Context, req *fuse.CreateRequest, resp *fuse.CreateResponse) (fs.Node, fs.Handle, error) { // New 'empty' file nd := dag.NodeWithData(ft.FilePBData(nil, 0)) - err := dir.dir.AddChild(req.Name, nd) + err := d.dir.AddChild(req.Name, nd) if err != nil { return nil, nil, err } - child, err := dir.dir.Child(req.Name) + child, err := d.dir.Child(req.Name) if err != nil { return nil, nil, err } @@ -483,8 +483,8 @@ func (dir *Directory) Create(ctx context.Context, req *fuse.CreateRequest, resp return nodechild, &File{fi: fd}, nil } -func (dir *Directory) Remove(ctx context.Context, req *fuse.RemoveRequest) error { - err := dir.dir.Unlink(req.Name) +func (d *Directory) Remove(ctx context.Context, req *fuse.RemoveRequest) error { + err := d.dir.Unlink(req.Name) if err != nil { return fuse.ENOENT } @@ -492,13 +492,13 @@ func (dir *Directory) Remove(ctx context.Context, req *fuse.RemoveRequest) error } // Rename implements NodeRenamer -func (dir *Directory) Rename(ctx context.Context, req *fuse.RenameRequest, newDir fs.Node) error { - cur, err := dir.dir.Child(req.OldName) +func (d *Directory) Rename(ctx context.Context, req *fuse.RenameRequest, newDir fs.Node) error { + cur, err := d.dir.Child(req.OldName) if err != nil { return err } - err = dir.dir.Unlink(req.OldName) + err = d.dir.Unlink(req.OldName) if err != nil { return err } diff --git a/fuse/ipns/mount_unix.go b/fuse/ipns/mount_unix.go index c04cc45a461e..34a8eef5137d 100644 --- a/fuse/ipns/mount_unix.go +++ b/fuse/ipns/mount_unix.go @@ -12,7 +12,7 @@ import ( // Mount mounts ipns at a given location, and returns a mount.Mount instance. func Mount(ipfs *core.IpfsNode, ipnsmp, ipfsmp string) (mount.Mount, error) { - coreApi, err := coreapi.NewCoreAPI(ipfs) + coreAPI, err := coreapi.NewCoreAPI(ipfs) if err != nil { return nil, err } @@ -22,12 +22,12 @@ func Mount(ipfs *core.IpfsNode, ipnsmp, ipfsmp string) (mount.Mount, error) { return nil, err } - allow_other := cfg.Mounts.FuseAllowOther + allowOther := cfg.Mounts.FuseAllowOther - fsys, err := NewFileSystem(ipfs.Context(), coreApi, ipfsmp, ipnsmp) + fsys, err := NewFileSystem(ipfs.Context(), coreAPI, ipfsmp, ipnsmp) if err != nil { return nil, err } - return mount.NewMount(ipfs.Process, fsys, ipnsmp, allow_other) + return mount.NewMount(ipfs.Process, fsys, ipnsmp, allowOther) } diff --git a/fuse/mount/fuse.go b/fuse/mount/fuse.go index 99f374043d21..b1060e6fd705 100644 --- a/fuse/mount/fuse.go +++ b/fuse/mount/fuse.go @@ -30,7 +30,7 @@ type mount struct { // Mount mounts a fuse fs.FS at a given location, and returns a Mount instance. // parent is a ContextGroup to bind the mount's ContextGroup to. -func NewMount(p goprocess.Process, fsys fs.FS, mountpoint string, allow_other bool) (Mount, error) { +func NewMount(p goprocess.Process, fsys fs.FS, mountpoint string, allowOther bool) (Mount, error) { var conn *fuse.Conn var err error @@ -39,7 +39,7 @@ func NewMount(p goprocess.Process, fsys fs.FS, mountpoint string, allow_other bo fuse.AsyncRead(), } - if allow_other { + if allowOther { mountOpts = append(mountOpts, fuse.AllowOther()) } conn, err = fuse.Mount(mountpoint, mountOpts...) diff --git a/fuse/readonly/mount_unix.go b/fuse/readonly/mount_unix.go index 87e4b33a7c00..19be37abecb4 100644 --- a/fuse/readonly/mount_unix.go +++ b/fuse/readonly/mount_unix.go @@ -15,7 +15,7 @@ func Mount(ipfs *core.IpfsNode, mountpoint string) (mount.Mount, error) { if err != nil { return nil, err } - allow_other := cfg.Mounts.FuseAllowOther + allowOther := cfg.Mounts.FuseAllowOther fsys := NewFileSystem(ipfs) - return mount.NewMount(ipfs.Process, fsys, mountpoint, allow_other) + return mount.NewMount(ipfs.Process, fsys, mountpoint, allowOther) } diff --git a/fuse/readonly/readonly_unix.go b/fuse/readonly/readonly_unix.go index a4d6f251301d..39ca972e5959 100644 --- a/fuse/readonly/readonly_unix.go +++ b/fuse/readonly/readonly_unix.go @@ -180,11 +180,11 @@ func (s *Node) Lookup(ctx context.Context, name string) (fs.Node, error) { case os.ErrNotExist, mdag.ErrLinkNotFound: // todo: make this error more versatile. return nil, fuse.ENOENT + case nil: + // noop default: log.Errorf("fuse lookup %q: %s", name, err) return nil, fuse.EIO - case nil: - // noop } nd, err := s.Ipfs.DAG.Get(ctx, link.Cid) diff --git a/gc/gc.go b/gc/gc.go index e3b0fda68f90..851b42d3b32e 100644 --- a/gc/gc.go +++ b/gc/gc.go @@ -167,7 +167,7 @@ func Descendants(ctx context.Context, getLinks dag.GetLinks, set *cid.Set, roots verboseCidError := func(err error) error { if strings.Contains(err.Error(), verifcid.ErrBelowMinimumHashLength.Error()) || strings.Contains(err.Error(), verifcid.ErrPossiblyInsecureHashFunction.Error()) { - err = fmt.Errorf("\"%s\"\nPlease run 'ipfs pin verify'"+ + err = fmt.Errorf("\"%s\"\nPlease run 'ipfs pin verify'"+ //nolint " to list insecure hashes. If you want to read them,"+ " please downgrade your go-ipfs to 0.4.13\n", err) log.Error(err) diff --git a/repo/fsrepo/fsrepo.go b/repo/fsrepo/fsrepo.go index f3e9841e8b0b..219f136f71e6 100644 --- a/repo/fsrepo/fsrepo.go +++ b/repo/fsrepo/fsrepo.go @@ -35,7 +35,7 @@ const LockFile = "repo.lock" var log = logging.Logger("fsrepo") -// version number that we are currently expecting to see +// RepoVersion is the version number that we are currently expecting to see var RepoVersion = 12 var migrationInstructions = `See https://github.com/ipfs/fs-repo-migrations/blob/master/run.md @@ -383,7 +383,7 @@ func (r *FSRepo) SetAPIAddr(addr ma.Multiaddr) error { } // Remove the temp file when rename return error if err1 := os.Remove(filepath.Join(r.path, "."+apiFile+".tmp")); err1 != nil { - return fmt.Errorf("File Rename error: %s, File remove error: %s", err.Error(), + return fmt.Errorf("file Rename error: %s, file remove error: %s", err.Error(), err1.Error()) } return err @@ -422,7 +422,7 @@ func (r *FSRepo) SetGatewayAddr(addr net.Addr) error { } // Remove the temp file when rename return error if err1 := os.Remove(tmpPath); err1 != nil { - return fmt.Errorf("File Rename error: %w, File remove error: %s", err, err1.Error()) + return fmt.Errorf("file Rename error: %w, file remove error: %s", err, err1.Error()) } return err } diff --git a/repo/fsrepo/migrations/httpfetcher.go b/repo/fsrepo/migrations/httpfetcher.go index 9be7f9f0a104..81e0e406d22a 100644 --- a/repo/fsrepo/migrations/httpfetcher.go +++ b/repo/fsrepo/migrations/httpfetcher.go @@ -16,7 +16,7 @@ const ( ) // HttpFetcher fetches files over HTTP -type HttpFetcher struct { +type HttpFetcher struct { //nolint distPath string gateway string limit int64 @@ -30,7 +30,7 @@ var _ Fetcher = (*HttpFetcher)(nil) // Specifying "" for distPath sets the default IPNS path. // Specifying "" for gateway sets the default. // Specifying 0 for fetchLimit sets the default, -1 means no limit. -func NewHttpFetcher(distPath, gateway, userAgent string, fetchLimit int64) *HttpFetcher { +func NewHttpFetcher(distPath, gateway, userAgent string, fetchLimit int64) *HttpFetcher { //nolint f := &HttpFetcher{ distPath: LatestIpfsDist, gateway: defaultGatewayURL, diff --git a/repo/fsrepo/migrations/ipfsfetcher/ipfsfetcher.go b/repo/fsrepo/migrations/ipfsfetcher/ipfsfetcher.go index cc10de4eba58..ce7b490efd20 100644 --- a/repo/fsrepo/migrations/ipfsfetcher/ipfsfetcher.go +++ b/repo/fsrepo/migrations/ipfsfetcher/ipfsfetcher.go @@ -28,7 +28,7 @@ const ( // Default maximum download size defaultFetchLimit = 1024 * 1024 * 512 - tempNodeTcpAddr = "/ip4/127.0.0.1/tcp/0" + tempNodeTCPAddr = "/ip4/127.0.0.1/tcp/0" ) type IpfsFetcher struct { @@ -193,7 +193,7 @@ func initTempNode(ctx context.Context, bootstrap []string, peers []peer.AddrInfo // Disable listening for inbound connections cfg.Addresses.Gateway = []string{} cfg.Addresses.API = []string{} - cfg.Addresses.Swarm = []string{tempNodeTcpAddr} + cfg.Addresses.Swarm = []string{tempNodeTCPAddr} if len(bootstrap) != 0 { cfg.Bootstrap = bootstrap diff --git a/repo/fsrepo/migrations/migrations.go b/repo/fsrepo/migrations/migrations.go index 9c556fe9722c..7e764b7312df 100644 --- a/repo/fsrepo/migrations/migrations.go +++ b/repo/fsrepo/migrations/migrations.go @@ -166,6 +166,8 @@ func GetMigrationFetcher(downloadSources []string, distPath string, newIpfsFetch if newIpfsFetcher != nil { fetchers = append(fetchers, newIpfsFetcher(distPath)) } + case "": + // Ignore empty string default: u, err := url.Parse(src) if err != nil { @@ -179,8 +181,6 @@ func GetMigrationFetcher(downloadSources []string, distPath string, newIpfsFetch return nil, errors.New("bad gateway address: url scheme must be http or https") } fetchers = append(fetchers, &RetryFetcher{NewHttpFetcher(distPath, u.String(), httpUserAgent, 0), numTriesPerHTTP}) - case "": - // Ignore empty string } } diff --git a/repo/repo.go b/repo/repo.go index 3c61031774b3..bec02049d181 100644 --- a/repo/repo.go +++ b/repo/repo.go @@ -15,7 +15,7 @@ import ( ) var ( - ErrApiNotRunning = errors.New("api not running") + ErrApiNotRunning = errors.New("api not running") //nolint ) // Repo represents all persistent data of a given ipfs node. diff --git a/test/integration/addcat_test.go b/test/integration/addcat_test.go index 3564a20dd00e..45e8729aca63 100644 --- a/test/integration/addcat_test.go +++ b/test/integration/addcat_test.go @@ -122,12 +122,12 @@ func DirectAddCat(data []byte, conf testutil.LatencyConfig) error { } defer catter.Close() - adderApi, err := coreapi.NewCoreAPI(adder) + adderAPI, err := coreapi.NewCoreAPI(adder) if err != nil { return err } - catterApi, err := coreapi.NewCoreAPI(catter) + catterAPI, err := coreapi.NewCoreAPI(catter) if err != nil { return err } @@ -147,12 +147,12 @@ func DirectAddCat(data []byte, conf testutil.LatencyConfig) error { return err } - added, err := adderApi.Unixfs().Add(ctx, files.NewBytesFile(data)) + added, err := adderAPI.Unixfs().Add(ctx, files.NewBytesFile(data)) if err != nil { return err } - readerCatted, err := catterApi.Unixfs().Get(ctx, added) + readerCatted, err := catterAPI.Unixfs().Get(ctx, added) if err != nil { return err } diff --git a/test/integration/bench_cat_test.go b/test/integration/bench_cat_test.go index 952f8e48bb18..d7e37dbb9ae8 100644 --- a/test/integration/bench_cat_test.go +++ b/test/integration/bench_cat_test.go @@ -65,12 +65,12 @@ func benchCat(b *testing.B, data []byte, conf testutil.LatencyConfig) error { } defer catter.Close() - adderApi, err := coreapi.NewCoreAPI(adder) + adderAPI, err := coreapi.NewCoreAPI(adder) if err != nil { return err } - catterApi, err := coreapi.NewCoreAPI(catter) + catterAPI, err := coreapi.NewCoreAPI(catter) if err != nil { return err } @@ -90,13 +90,13 @@ func benchCat(b *testing.B, data []byte, conf testutil.LatencyConfig) error { return err } - added, err := adderApi.Unixfs().Add(ctx, files.NewBytesFile(data)) + added, err := adderAPI.Unixfs().Add(ctx, files.NewBytesFile(data)) if err != nil { return err } b.StartTimer() - readerCatted, err := catterApi.Unixfs().Get(ctx, added) + readerCatted, err := catterAPI.Unixfs().Get(ctx, added) if err != nil { return err } diff --git a/test/integration/three_legged_cat_test.go b/test/integration/three_legged_cat_test.go index f41c9a7ddea4..f0358272b092 100644 --- a/test/integration/three_legged_cat_test.go +++ b/test/integration/three_legged_cat_test.go @@ -93,12 +93,12 @@ func RunThreeLeggedCat(data []byte, conf testutil.LatencyConfig) error { } defer catter.Close() - adderApi, err := coreapi.NewCoreAPI(adder) + adderAPI, err := coreapi.NewCoreAPI(adder) if err != nil { return err } - catterApi, err := coreapi.NewCoreAPI(catter) + catterAPI, err := coreapi.NewCoreAPI(catter) if err != nil { return err } @@ -117,12 +117,12 @@ func RunThreeLeggedCat(data []byte, conf testutil.LatencyConfig) error { return err } - added, err := adderApi.Unixfs().Add(ctx, files.NewBytesFile(data)) + added, err := adderAPI.Unixfs().Add(ctx, files.NewBytesFile(data)) if err != nil { return err } - readerCatted, err := catterApi.Unixfs().Get(ctx, added) + readerCatted, err := catterAPI.Unixfs().Get(ctx, added) if err != nil { return err } diff --git a/version.go b/version.go index 6e11b8b57951..7639d27dae88 100644 --- a/version.go +++ b/version.go @@ -13,7 +13,7 @@ var CurrentCommit string // CurrentVersionNumber is the current application's version literal const CurrentVersionNumber = "0.17.0-dev" -const ApiVersion = "/kubo/" + CurrentVersionNumber + "/" +const ApiVersion = "/kubo/" + CurrentVersionNumber + "/" //nolint // GetUserAgentVersion is the libp2p user agent used by go-ipfs. //