1
0
mirror of https://github.com/ipfs/kubo.git synced 2025-07-03 21:08:17 +08:00

ci: add stylecheck to golangci-lint (#9334)

This commit is contained in:
Gus Eggert
2022-10-06 10:18:40 -04:00
committed by GitHub
parent bffc012c6b
commit e550d9e476
51 changed files with 171 additions and 173 deletions

3
.golangci.yml Normal file
View File

@ -0,0 +1,3 @@
linters:
enable:
- stylecheck

View File

@ -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
}

View File

@ -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")

View File

@ -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{

View File

@ -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{

View File

@ -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) {

View File

@ -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
}

View File

@ -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

View File

@ -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)

View File

@ -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)

View File

@ -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) {

View File

@ -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
}

View File

@ -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
}

View File

@ -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)
}

View File

@ -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 {

View File

@ -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{

View File

@ -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
}

View File

@ -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]

View File

@ -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,
}

View File

@ -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
}

View File

@ -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)

View File

@ -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

View File

@ -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")

View File

@ -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)

View File

@ -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())

View File

@ -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

View File

@ -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 {

View File

@ -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
}

View File

@ -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

View File

@ -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)
}

View File

@ -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",

View File

@ -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) {

View File

@ -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)

View File

@ -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))

View File

@ -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)
}

View File

@ -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
}

View File

@ -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)
}

View File

@ -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...)

View File

@ -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)
}

View File

@ -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)

View File

@ -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)

View File

@ -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
}

View File

@ -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,

View File

@ -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

View File

@ -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
}
}

View File

@ -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.

View File

@ -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
}

View File

@ -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
}

View File

@ -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
}

View File

@ -158,7 +158,7 @@ test_expect_success 'pubsub cmd fails because it was disabled via cli flag' '
'
test_expect_success "pubsub cmd produces error" '
echo "Error: experimental pubsub feature not enabled. Run daemon with --enable-pubsub-experiment to use." > expected &&
echo "Error: experimental pubsub feature not enabled, run daemon with --enable-pubsub-experiment to use" > expected &&
test_cmp expected pubsub_cmd_out
'

View File

@ -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.
//