refactor: apply go fix modernizers from Go 1.26 (#11190)
* chore: apply go fix modernizers from Go 1.26 automated refactoring: interface{} to any, slices.Contains, and other idiomatic updates. * feat(ci): add `go fix` check to Go analysis workflow ensures Go 1.26 modernizers are applied, fails CI if `go fix ./...` produces any changes (similar to existing `go fmt` enforcement)
Marcin Rataj committed
Feb 11, 2026 at 01:01 UTC
6a008fc74c3c9cca4c634cc80110effd3cd3a5bc
127 files changed
+580
-618
.github/workflows/golang-analysis.yml
+9
@@ -47,6 +47,15 @@ jobs:
47
echo "$out"
48
exit 1
49
fi
50
+ - name: go fix
51
+ if: always() # run this step even if the previous one failed
52
+ run: |
53
+ go fix ./...
54
+ if [[ -n $(git diff --name-only) ]]; then
55
+ echo "go fix produced changes. Run 'go fix ./...' locally and commit the result."
56
+ git diff
57
+ exit 1
58
+ fi
59
- name: go vet
60
if: always() # run this step even if the previous one failed
61
uses: protocol/multiple-go-modules@v1.4
blocks/blockstoreutil/remove.go
+3
-3
@@ -34,10 +34,10 @@ type RmBlocksOpts struct {
34
// It returns a channel where objects of type RemovedBlock are placed, when
35
// not using the Quiet option. Block removal is asynchronous and will
36
// skip any pinned blocks.
37
-func RmBlocks(ctx context.Context, blocks bs.GCBlockstore, pins pin.Pinner, cids []cid.Cid, opts RmBlocksOpts) (<-chan interface{}, error) {
37
+func RmBlocks(ctx context.Context, blocks bs.GCBlockstore, pins pin.Pinner, cids []cid.Cid, opts RmBlocksOpts) (<-chan any, error) {
38
// make the channel large enough to hold any result to avoid
39
// blocking while holding the GCLock
40
- out := make(chan interface{}, len(cids))
40
+ out := make(chan any, len(cids))
41
go func() {
42
defer close(out)
43
@@ -75,7 +75,7 @@ func RmBlocks(ctx context.Context, blocks bs.GCBlockstore, pins pin.Pinner, cids
75
// out channel, with an error which indicates that the Cid is pinned.
76
// This function is used in RmBlocks to filter out any blocks which are not
77
// to be removed (because they are pinned).
78
-func FilterPinned(ctx context.Context, pins pin.Pinner, out chan<- interface{}, cids []cid.Cid) []cid.Cid {
78
+func FilterPinned(ctx context.Context, pins pin.Pinner, out chan<- any, cids []cid.Cid) []cid.Cid {
79
stillOkay := make([]cid.Cid, 0, len(cids))
80
res, err := pins.CheckIfPinned(ctx, cids...)
81
if err != nil {
client/rpc/requestbuilder.go
+4
-4
@@ -18,10 +18,10 @@ type RequestBuilder interface {
18
BodyBytes(body []byte) RequestBuilder
19
Body(body io.Reader) RequestBuilder
20
FileBody(body io.Reader) RequestBuilder
21
- Option(key string, value interface{}) RequestBuilder
21
+ Option(key string, value any) RequestBuilder
22
Header(name, value string) RequestBuilder
23
Send(ctx context.Context) (*Response, error)
24
- Exec(ctx context.Context, res interface{}) error
24
+ Exec(ctx context.Context, res any) error
25
}
26
27
// encodedAbsolutePathVersion is the version from which the absolute path header in
@@ -83,7 +83,7 @@ func (r *requestBuilder) FileBody(body io.Reader) RequestBuilder {
83
}
84
85
// Option sets the given option.
86
-func (r *requestBuilder) Option(key string, value interface{}) RequestBuilder {
86
+func (r *requestBuilder) Option(key string, value any) RequestBuilder {
87
var s string
88
switch v := value.(type) {
89
case bool:
@@ -128,7 +128,7 @@ func (r *requestBuilder) Send(ctx context.Context) (*Response, error) {
128
}
129
130
// Exec sends the request a request and decodes the response.
131
-func (r *requestBuilder) Exec(ctx context.Context, res interface{}) error {
131
+func (r *requestBuilder) Exec(ctx context.Context, res any) error {
132
httpRes, err := r.Send(ctx)
133
if err != nil {
134
return err
client/rpc/response.go
+1
-1
@@ -64,7 +64,7 @@ func (r *Response) Cancel() error {
64
}
65
66
// Decode reads request body and decodes it as json.
67
-func (r *Response) decode(dec interface{}) error {
67
+func (r *Response) decode(dec any) error {
68
if r.Error != nil {
69
return r.Error
70
}
cmd/ipfs/kubo/daemon.go
+1
-1
@@ -1287,7 +1287,7 @@ func merge(cs ...<-chan error) <-chan error {
1287
1288
func YesNoPrompt(prompt string) bool {
1289
var s string
1290
- for i := 0; i < 3; i++ {
1290
+ for range 3 {
1291
fmt.Printf("%s ", prompt)
1292
_, err := fmt.Scanf("%s", &s)
1293
if err != nil {
cmd/ipfs/kubo/dnsresolve_test.go
+1
-1
@@ -18,7 +18,7 @@ var (
18
19
func makeResolver(t *testing.T, n uint8) *madns.Resolver {
20
results := make([]net.IPAddr, n)
21
- for i := uint8(0); i < n; i++ {
21
+ for i := range n {
22
results[i] = net.IPAddr{IP: net.ParseIP(fmt.Sprintf("192.0.2.%d", i))}
23
}
24
cmd/ipfs/kubo/init.go
+1
-1
@@ -133,7 +133,7 @@ func applyProfiles(conf *config.Config, profiles string) error {
133
return nil
134
}
135
136
- for _, profile := range strings.Split(profiles, ",") {
136
+ for profile := range strings.SplitSeq(profiles, ",") {
137
transformer, ok := config.Profiles[profile]
138
if !ok {
139
return fmt.Errorf("invalid configuration profile: %s", profile)
cmd/ipfs/kubo/start.go
+1
-1
@@ -251,7 +251,7 @@ func apiAddrOption(req *cmds.Request) (ma.Multiaddr, error) {
251
// multipart requests is %-encoded. Before this version, its sent raw.
252
var encodedAbsolutePathVersion = semver.MustParse("0.23.0-dev")
253
254
-func makeExecutor(req *cmds.Request, env interface{}) (cmds.Executor, error) {
254
+func makeExecutor(req *cmds.Request, env any) (cmds.Executor, error) {
255
exe := tracingWrappedExecutor{cmds.NewExecutor(req.Root)}
256
cctx := env.(*oldcmds.Context)
257
cmd/ipfs/util/signal.go
+2
-4
@@ -37,9 +37,7 @@ func (ih *IntrHandler) Close() error {
37
func (ih *IntrHandler) Handle(handler func(count int, ih *IntrHandler), sigs ...os.Signal) {
38
notify := make(chan os.Signal, 1)
39
signal.Notify(notify, sigs...)
40
- ih.wg.Add(1)
41
- go func() {
42
- defer ih.wg.Done()
40
+ ih.wg.Go(func() {
41
defer signal.Stop(notify)
42
43
count := 0
@@ -52,7 +50,7 @@ func (ih *IntrHandler) Handle(handler func(count int, ih *IntrHandler), sigs ...
50
handler(count, ih)
51
}
52
}
55
- }()
53
+ })
54
}
55
56
func SetupInterruptHandler(ctx context.Context) (io.Closer, context.Context) {
commands/reqlog.go
+1
-1
@@ -11,7 +11,7 @@ type ReqLogEntry struct {
11
EndTime time.Time
12
Active bool
13
Command string
14
- Options map[string]interface{}
14
+ Options map[string]any
15
Args []string
16
ID int
17
config/autoconf_client.go
+10
-18
@@ -3,6 +3,7 @@ package config
3
import (
4
"fmt"
5
"path/filepath"
6
+ "slices"
7
"sync"
8
9
"github.com/ipfs/boxo/autoconf"
@@ -82,12 +83,9 @@ func validateAutoConfDisabled(cfg *Config) error {
83
var errors []string
84
85
// Check Bootstrap
85
- for _, peer := range cfg.Bootstrap {
86
- if peer == AutoPlaceholder {
87
- hasAutoValues = true
88
- errors = append(errors, "Bootstrap contains 'auto' but AutoConf.Enabled=false")
89
- break
90
- }
86
+ if slices.Contains(cfg.Bootstrap, AutoPlaceholder) {
87
+ hasAutoValues = true
88
+ errors = append(errors, "Bootstrap contains 'auto' but AutoConf.Enabled=false")
89
}
90
91
// Check DNS.Resolvers
@@ -102,21 +100,15 @@ func validateAutoConfDisabled(cfg *Config) error {
100
}
101
102
// Check Routing.DelegatedRouters
105
- for _, router := range cfg.Routing.DelegatedRouters {
106
- if router == AutoPlaceholder {
107
- hasAutoValues = true
108
- errors = append(errors, "Routing.DelegatedRouters contains 'auto' but AutoConf.Enabled=false")
109
- break
110
- }
103
+ if slices.Contains(cfg.Routing.DelegatedRouters, AutoPlaceholder) {
104
+ hasAutoValues = true
105
+ errors = append(errors, "Routing.DelegatedRouters contains 'auto' but AutoConf.Enabled=false")
106
}
107
108
// Check Ipns.DelegatedPublishers
114
- for _, publisher := range cfg.Ipns.DelegatedPublishers {
115
- if publisher == AutoPlaceholder {
116
- hasAutoValues = true
117
- errors = append(errors, "Ipns.DelegatedPublishers contains 'auto' but AutoConf.Enabled=false")
118
- break
119
- }
109
+ if slices.Contains(cfg.Ipns.DelegatedPublishers, AutoPlaceholder) {
110
+ hasAutoValues = true
111
+ errors = append(errors, "Ipns.DelegatedPublishers contains 'auto' but AutoConf.Enabled=false")
112
}
113
114
// Log all errors
config/autonat.go
+1
-1
@@ -84,5 +84,5 @@ type AutoNATThrottleConfig struct {
84
// global/peer dialback limits.
85
//
86
// When unset, this defaults to 1 minute.
87
- Interval OptionalDuration `json:",omitempty"`
87
+ Interval OptionalDuration
88
}
config/config.go
+13
-13
@@ -47,7 +47,7 @@ type Config struct {
47
48
Internal Internal // experimental/unstable options
49
50
- Bitswap Bitswap `json:",omitempty"`
50
+ Bitswap Bitswap
51
}
52
53
const (
@@ -106,7 +106,7 @@ func Filename(configroot, userConfigFile string) (string, error) {
106
}
107
108
// HumanOutput gets a config value ready for printing.
109
-func HumanOutput(value interface{}) ([]byte, error) {
109
+func HumanOutput(value any) ([]byte, error) {
110
s, ok := value.(string)
111
if ok {
112
return []byte(strings.Trim(s, "\n")), nil
@@ -115,12 +115,12 @@ func HumanOutput(value interface{}) ([]byte, error) {
115
}
116
117
// Marshal configuration with JSON.
118
-func Marshal(value interface{}) ([]byte, error) {
118
+func Marshal(value any) ([]byte, error) {
119
// need to prettyprint, hence MarshalIndent, instead of Encoder
120
return json.MarshalIndent(value, "", " ")
121
}
122
123
-func FromMap(v map[string]interface{}) (*Config, error) {
123
+func FromMap(v map[string]any) (*Config, error) {
124
buf := new(bytes.Buffer)
125
if err := json.NewEncoder(buf).Encode(v); err != nil {
126
return nil, err
@@ -132,12 +132,12 @@ func FromMap(v map[string]interface{}) (*Config, error) {
132
return &conf, nil
133
}
134
135
-func ToMap(conf *Config) (map[string]interface{}, error) {
135
+func ToMap(conf *Config) (map[string]any, error) {
136
buf := new(bytes.Buffer)
137
if err := json.NewEncoder(buf).Encode(conf); err != nil {
138
return nil, err
139
}
140
- var m map[string]interface{}
140
+ var m map[string]any
141
if err := json.NewDecoder(buf).Decode(&m); err != nil {
142
return nil, fmt.Errorf("failure to decode config: %w", err)
143
}
@@ -147,14 +147,14 @@ func ToMap(conf *Config) (map[string]interface{}, error) {
147
// Convert config to a map, without using encoding/json, since
148
// zero/empty/'omitempty' fields are excluded by encoding/json during
149
// marshaling.
150
-func ReflectToMap(conf interface{}) interface{} {
150
+func ReflectToMap(conf any) any {
151
v := reflect.ValueOf(conf)
152
if !v.IsValid() {
153
return nil
154
}
155
156
// Handle pointer type
157
- if v.Kind() == reflect.Ptr {
157
+ if v.Kind() == reflect.Pointer {
158
if v.IsNil() {
159
// Create a zero value of the pointer's element type
160
elemType := v.Type().Elem()
@@ -166,7 +166,7 @@ func ReflectToMap(conf interface{}) interface{} {
166
167
switch v.Kind() {
168
case reflect.Struct:
169
- result := make(map[string]interface{})
169
+ result := make(map[string]any)
170
t := v.Type()
171
for i := 0; i < v.NumField(); i++ {
172
field := v.Field(i)
@@ -178,7 +178,7 @@ func ReflectToMap(conf interface{}) interface{} {
178
return result
179
180
case reflect.Map:
181
- result := make(map[string]interface{})
181
+ result := make(map[string]any)
182
iter := v.MapRange()
183
for iter.Next() {
184
key := iter.Key()
@@ -194,7 +194,7 @@ func ReflectToMap(conf interface{}) interface{} {
194
return result
195
196
case reflect.Slice, reflect.Array:
197
- result := make([]interface{}, v.Len())
197
+ result := make([]any, v.Len())
198
for i := 0; i < v.Len(); i++ {
199
result[i] = ReflectToMap(v.Index(i).Interface())
200
}
@@ -234,11 +234,11 @@ func CheckKey(key string) error {
234
235
// Parse the key and verify it's presence in the map.
236
var ok bool
237
- var mapCursor map[string]interface{}
237
+ var mapCursor map[string]any
238
239
parts := strings.Split(key, ".")
240
for i, part := range parts {
241
- mapCursor, ok = cursor.(map[string]interface{})
241
+ mapCursor, ok = cursor.(map[string]any)
242
if !ok {
243
if cursor == nil {
244
return nil
config/config_test.go
+7
-7
@@ -32,7 +32,7 @@ func TestReflectToMap(t *testing.T) {
32
// Helper function to create a test config with various field types
33
reflectedConfig := ReflectToMap(new(Config))
34
35
- mapConfig, ok := reflectedConfig.(map[string]interface{})
35
+ mapConfig, ok := reflectedConfig.(map[string]any)
36
if !ok {
37
t.Fatal("Config didn't convert to map")
38
}
@@ -42,7 +42,7 @@ func TestReflectToMap(t *testing.T) {
42
t.Fatal("Identity field not found")
43
}
44
45
- mapIdentity, ok := reflectedIdentity.(map[string]interface{})
45
+ mapIdentity, ok := reflectedIdentity.(map[string]any)
46
if !ok {
47
t.Fatal("Identity field didn't convert to map")
48
}
@@ -70,7 +70,7 @@ func TestReflectToMap(t *testing.T) {
70
if !ok {
71
t.Fatal("Bootstrap field not found in config")
72
}
73
- bootstrap, ok := reflectedBootstrap.([]interface{})
73
+ bootstrap, ok := reflectedBootstrap.([]any)
74
if !ok {
75
t.Fatal("Bootstrap field didn't convert to []string")
76
}
@@ -82,7 +82,7 @@ func TestReflectToMap(t *testing.T) {
82
if !ok {
83
t.Fatal("Datastore field not found in config")
84
}
85
- datastore, ok := reflectedDatastore.(map[string]interface{})
85
+ datastore, ok := reflectedDatastore.(map[string]any)
86
if !ok {
87
t.Fatal("Datastore field didn't convert to map")
88
}
@@ -107,7 +107,7 @@ func TestReflectToMap(t *testing.T) {
107
if !ok {
108
t.Fatal("DNS field not found in config")
109
}
110
- DNS, ok := reflectedDNS.(map[string]interface{})
110
+ DNS, ok := reflectedDNS.(map[string]any)
111
if !ok {
112
t.Fatal("DNS field didn't convert to map")
113
}
@@ -116,12 +116,12 @@ func TestReflectToMap(t *testing.T) {
116
t.Fatal("Resolvers field not found in DNS")
117
}
118
// Test map field
119
- if _, ok := reflectedResolvers.(map[string]interface{}); !ok {
119
+ if _, ok := reflectedResolvers.(map[string]any); !ok {
120
t.Fatal("Resolvers field didn't convert to map")
121
}
122
123
// Test pointer field
124
- if _, ok := DNS["MaxCacheTTL"].(map[string]interface{}); !ok {
124
+ if _, ok := DNS["MaxCacheTTL"].(map[string]any); !ok {
125
// Since OptionalDuration only field is private, we cannot test it
126
t.Fatal("MaxCacheTTL field didn't convert to map")
127
}
config/datastore.go
+3
-3
@@ -32,12 +32,12 @@ type Datastore struct {
32
NoSync bool `json:",omitempty"`
33
Params *json.RawMessage `json:",omitempty"`
34
35
- Spec map[string]interface{}
35
+ Spec map[string]any
36
37
HashOnRead bool
38
BloomFilterSize int
39
- BlockKeyCacheSize OptionalInteger `json:",omitempty"`
40
- WriteThrough Flag `json:",omitempty"`
39
+ BlockKeyCacheSize OptionalInteger
40
+ WriteThrough Flag `json:",omitempty"`
41
}
42
43
// DataStorePath returns the default data store path given a configuration root
config/init.go
+22
-22
@@ -130,8 +130,8 @@ func DefaultDatastoreConfig() Datastore {
130
}
131
}
132
133
-func pebbleSpec() map[string]interface{} {
134
- return map[string]interface{}{
133
+func pebbleSpec() map[string]any {
134
+ return map[string]any{
135
"type": "pebbleds",
136
"prefix": "pebble.datastore",
137
"path": "pebbleds",
@@ -139,11 +139,11 @@ func pebbleSpec() map[string]interface{} {
139
}
140
}
141
142
-func pebbleSpecMeasure() map[string]interface{} {
143
- return map[string]interface{}{
142
+func pebbleSpecMeasure() map[string]any {
143
+ return map[string]any{
144
"type": "measure",
145
"prefix": "pebble.datastore",
146
- "child": map[string]interface{}{
146
+ "child": map[string]any{
147
"formatMajorVersion": int(pebble.FormatNewest),
148
"type": "pebbleds",
149
"path": "pebbleds",
@@ -151,8 +151,8 @@ func pebbleSpecMeasure() map[string]interface{} {
151
}
152
}
153
154
-func badgerSpec() map[string]interface{} {
155
- return map[string]interface{}{
154
+func badgerSpec() map[string]any {
155
+ return map[string]any{
156
"type": "badgerds",
157
"prefix": "badger.datastore",
158
"path": "badgerds",
@@ -161,11 +161,11 @@ func badgerSpec() map[string]interface{} {
161
}
162
}
163
164
-func badgerSpecMeasure() map[string]interface{} {
165
- return map[string]interface{}{
164
+func badgerSpecMeasure() map[string]any {
165
+ return map[string]any{
166
"type": "measure",
167
"prefix": "badger.datastore",
168
- "child": map[string]interface{}{
168
+ "child": map[string]any{
169
"type": "badgerds",
170
"path": "badgerds",
171
"syncWrites": false,
@@ -174,11 +174,11 @@ func badgerSpecMeasure() map[string]interface{} {
174
}
175
}
176
177
-func flatfsSpec() map[string]interface{} {
178
- return map[string]interface{}{
177
+func flatfsSpec() map[string]any {
178
+ return map[string]any{
179
"type": "mount",
180
- "mounts": []interface{}{
181
- map[string]interface{}{
180
+ "mounts": []any{
181
+ map[string]any{
182
"mountpoint": "/blocks",
183
"type": "flatfs",
184
"prefix": "flatfs.datastore",
@@ -186,7 +186,7 @@ func flatfsSpec() map[string]interface{} {
186
"sync": false,
187
"shardFunc": "/repo/flatfs/shard/v1/next-to-last/2",
188
},
189
- map[string]interface{}{
189
+ map[string]any{
190
"mountpoint": "/",
191
"type": "levelds",
192
"prefix": "leveldb.datastore",
@@ -197,26 +197,26 @@ func flatfsSpec() map[string]interface{} {
197
}
198
}
199
200
-func flatfsSpecMeasure() map[string]interface{} {
201
- return map[string]interface{}{
200
+func flatfsSpecMeasure() map[string]any {
201
+ return map[string]any{
202
"type": "mount",
203
- "mounts": []interface{}{
204
- map[string]interface{}{
203
+ "mounts": []any{
204
+ map[string]any{
205
"mountpoint": "/blocks",
206
"type": "measure",
207
"prefix": "flatfs.datastore",
208
- "child": map[string]interface{}{
208
+ "child": map[string]any{
209
"type": "flatfs",
210
"path": "blocks",
211
"sync": false,
212
"shardFunc": "/repo/flatfs/shard/v1/next-to-last/2",
213
},
214
},
215
- map[string]interface{}{
215
+ map[string]any{
216
"mountpoint": "/",
217
"type": "measure",
218
"prefix": "leveldb.datastore",
219
- "child": map[string]interface{}{
219
+ "child": map[string]any{
220
"type": "levelds",
221
"path": "datastore",
222
"compression": "none",
config/internal.go
+2
-2
@@ -41,7 +41,7 @@ type BitswapBroadcastControl struct {
41
// MaxPeers sets a hard limit on the number of peers to send broadcasts to.
42
// A value of 0 means no broadcasts are sent. A value of -1 means there is
43
// no limit. Default is [DefaultBroadcastControlMaxPeers].
44
- MaxPeers OptionalInteger `json:",omitempty"`
44
+ MaxPeers OptionalInteger
45
// LocalPeers enables or disables broadcast control for peers on the local
46
// network. If false, than always broadcast to peers on the local network.
47
// If true, apply broadcast control to local peers. Default is
@@ -58,7 +58,7 @@ type BitswapBroadcastControl struct {
58
// this number of random peers receives a broadcast. This may be helpful in
59
// cases where peers that are not receiving broadcasts my have wanted
60
// blocks. Default is [DefaultBroadcastControlMaxRandomPeers].
61
- MaxRandomPeers OptionalInteger `json:",omitempty"`
61
+ MaxRandomPeers OptionalInteger
62
// SendToPendingPeers enables or disables sending broadcasts to any peers
63
// to which there is a pending message to send. When enabled, this sends
64
// broadcasts to many more peers, but does so in a way that does not
config/plugins.go
+1
-1
@@ -7,5 +7,5 @@ type Plugins struct {
7
8
type Plugin struct {
9
Disabled bool
10
- Config interface{} `json:",omitempty"`
10
+ Config any `json:",omitempty"`
11
}
config/provide.go
+1
-1
@@ -102,7 +102,7 @@ type ProvideDHT struct {
102
103
func ParseProvideStrategy(s string) ProvideStrategy {
104
var strategy ProvideStrategy
105
- for _, part := range strings.Split(s, "+") {
105
+ for part := range strings.SplitSeq(s, "+") {
106
switch part {
107
case "all", "flat", "": // special case, does not mix with others ("flat" is deprecated, maps to "all")
108
return ProvideStrategyAll
config/routing.go
+4
-9
@@ -5,6 +5,7 @@ import (
5
"fmt"
6
"os"
7
"runtime"
8
+ "slices"
9
"strings"
10
)
11
@@ -59,7 +60,7 @@ type Router struct {
60
61
// Parameters are extra configuration that this router might need.
62
// A common one for HTTP router is "Endpoint".
62
- Parameters interface{}
63
+ Parameters any
64
}
65
66
type (
@@ -78,13 +79,7 @@ func (m Methods) Check() error {
79
80
// Check unsupported methods
81
for k := range m {
81
- seen := false
82
- for _, mn := range MethodNameList {
83
- if mn == k {
84
- seen = true
85
- break
86
- }
87
- }
82
+ seen := slices.Contains(MethodNameList, k)
83
84
if seen {
85
continue
@@ -108,7 +103,7 @@ func (r *RouterParser) UnmarshalJSON(b []byte) error {
103
}
104
raw := out.Parameters.(*json.RawMessage)
105
111
- var p interface{}
106
+ var p any
107
switch out.Type {
108
case RouterTypeHTTP:
109
p = &HTTPRouterParams{}
config/serialize/serialize.go
+3
-3
@@ -18,7 +18,7 @@ import (
18
var ErrNotInitialized = errors.New("ipfs not initialized, please run 'ipfs init'")
19
20
// ReadConfigFile reads the config from `filename` into `cfg`.
21
-func ReadConfigFile(filename string, cfg interface{}) error {
21
+func ReadConfigFile(filename string, cfg any) error {
22
f, err := os.Open(filename)
23
if err != nil {
24
if os.IsNotExist(err) {
@@ -34,7 +34,7 @@ func ReadConfigFile(filename string, cfg interface{}) error {
34
}
35
36
// WriteConfigFile writes the config from `cfg` into `filename`.
37
-func WriteConfigFile(filename string, cfg interface{}) error {
37
+func WriteConfigFile(filename string, cfg any) error {
38
err := os.MkdirAll(filepath.Dir(filename), 0o755)
39
if err != nil {
40
return err
@@ -50,7 +50,7 @@ func WriteConfigFile(filename string, cfg interface{}) error {
50
}
51
52
// encode configuration with JSON.
53
-func encode(w io.Writer, value interface{}) error {
53
+func encode(w io.Writer, value any) error {
54
// need to prettyprint, hence MarshalIndent, instead of Encoder
55
buf, err := config.Marshal(value)
56
if err != nil {
config/types.go
+2
-2
@@ -298,7 +298,7 @@ func (d Duration) MarshalJSON() ([]byte, error) {
298
}
299
300
func (d *Duration) UnmarshalJSON(b []byte) error {
301
- var v interface{}
301
+ var v any
302
if err := json.Unmarshal(b, &v); err != nil {
303
return err
304
}
@@ -485,7 +485,7 @@ func (p *OptionalBytes) UnmarshalJSON(input []byte) error {
485
case "null", "undefined":
486
*p = OptionalBytes{}
487
default:
488
- var value interface{}
488
+ var value any
489
err := json.Unmarshal(input, &value)
490
if err != nil {
491
return err
core/commands/cid.go
+1
-1
@@ -112,7 +112,7 @@ The optional format string is a printf style format string:
112
return emitCids(req, resp, opts)
113
},
114
PostRun: cmds.PostRunMap{
115
- cmds.CLI: streamResult(func(v interface{}, out io.Writer) nonFatalError {
115
+ cmds.CLI: streamResult(func(v any, out io.Writer) nonFatalError {
116
r := v.(*CidFormatRes)
117
if r.ErrorMsg != "" {
118
return nonFatalError(fmt.Sprintf("%s: %s", r.CidStr, r.ErrorMsg))
core/commands/cid_test.go
+2
-2
@@ -39,7 +39,7 @@ func TestCidFmtCmd(t *testing.T) {
39
40
// Mock request
41
req := &cmds.Request{
42
- Options: map[string]interface{}{
42
+ Options: map[string]any{
43
cidToVersionOptionName: "0",
44
cidMultibaseOptionName: e.MultibaseName,
45
cidFormatOptionName: "%s",
@@ -90,7 +90,7 @@ func TestCidFmtCmd(t *testing.T) {
90
for _, e := range testCases {
91
// Mock request
92
req := &cmds.Request{
93
- Options: map[string]interface{}{
93
+ Options: map[string]any{
94
cidToVersionOptionName: e.Ver,
95
cidMultibaseOptionName: e.MultibaseName,
96
cidFormatOptionName: "%s",
core/commands/cmdenv/env.go
+1
-1
@@ -21,7 +21,7 @@ import (
21
var log = logging.Logger("core/commands/cmdenv")
22
23
// GetNode extracts the node from the environment.
24
-func GetNode(env interface{}) (*core.IpfsNode, error) {
24
+func GetNode(env any) (*core.IpfsNode, error) {
25
ctx, ok := env.(*commands.Context)
26
if !ok {
27
return nil, fmt.Errorf("expected env to be of type %T, got %T", ctx, env)
core/commands/commands.go
+2
-2
@@ -20,7 +20,7 @@ type commandEncoder struct {
20
w io.Writer
21
}
22
23
-func (e *commandEncoder) Encode(v interface{}) error {
23
+func (e *commandEncoder) Encode(v any) error {
24
var (
25
cmd *Command
26
ok bool
@@ -232,7 +232,7 @@ type nonFatalError string
232
// streamResult is a helper function to stream results that possibly
233
// contain non-fatal errors. The helper function is allowed to panic
234
// on internal errors.
235
-func streamResult(procVal func(interface{}, io.Writer) nonFatalError) func(cmds.Response, cmds.ResponseEmitter) error {
235
+func streamResult(procVal func(any, io.Writer) nonFatalError) func(cmds.Response, cmds.ResponseEmitter) error {
236
return func(res cmds.Response, re cmds.ResponseEmitter) (rerr error) {
237
defer func() {
238
if r := recover(); r != nil {
core/commands/config.go
+18
-18
@@ -22,13 +22,13 @@ import (
22
23
// ConfigUpdateOutput is config profile apply command's output
24
type ConfigUpdateOutput struct {
25
- OldCfg map[string]interface{}
26
- NewCfg map[string]interface{}
25
+ OldCfg map[string]any
26
+ NewCfg map[string]any
27
}
28
29
type ConfigField struct {
30
Key string
31
- Value interface{}
31
+ Value any
32
}
33
34
const (
@@ -117,7 +117,7 @@ Set multiple values in the 'Addresses.AppendAnnounce' array:
117
value := args[1]
118
119
if parseJSON, _ := req.Options[configJSONOptionName].(bool); parseJSON {
120
- var jsonVal interface{}
120
+ var jsonVal any
121
if err := json.Unmarshal([]byte(value), &jsonVal); err != nil {
122
err = fmt.Errorf("failed to unmarshal json. %s", err)
123
return err
@@ -199,7 +199,7 @@ var configShowCmd = &cmds.Command{
199
NOTE: For security reasons, this command will omit your private key and remote services. If you would like to make a full backup of your config (private key included), you must copy the config file from your repo.
200
`,
201
},
202
- Type: make(map[string]interface{}),
202
+ Type: make(map[string]any),
203
Run: func(req *cmds.Request, res cmds.ResponseEmitter, env cmds.Environment) error {
204
cfgRoot, err := cmdenv.GetConfigRoot(env)
205
if err != nil {
@@ -217,7 +217,7 @@ NOTE: For security reasons, this command will omit your private key and remote s
217
return err
218
}
219
220
- var cfg map[string]interface{}
220
+ var cfg map[string]any
221
err = json.Unmarshal(data, &cfg)
222
if err != nil {
223
return err
@@ -262,7 +262,7 @@ NOTE: For security reasons, this command will omit your private key and remote s
262
},
263
}
264
265
-var HumanJSONEncoder = cmds.MakeTypedEncoder(func(req *cmds.Request, w io.Writer, out *map[string]interface{}) error {
265
+var HumanJSONEncoder = cmds.MakeTypedEncoder(func(req *cmds.Request, w io.Writer, out *map[string]any) error {
266
buf, err := config.HumanOutput(out)
267
if err != nil {
268
return err
@@ -273,35 +273,35 @@ var HumanJSONEncoder = cmds.MakeTypedEncoder(func(req *cmds.Request, w io.Writer
273
})
274
275
// Scrubs value and returns error if missing
276
-func scrubValue(m map[string]interface{}, key []string) (map[string]interface{}, error) {
276
+func scrubValue(m map[string]any, key []string) (map[string]any, error) {
277
return scrubMapInternal(m, key, false)
278
}
279
280
// Scrubs value and returns no error if missing
281
-func scrubOptionalValue(m map[string]interface{}, key []string) (map[string]interface{}, error) {
281
+func scrubOptionalValue(m map[string]any, key []string) (map[string]any, error) {
282
return scrubMapInternal(m, key, true)
283
}
284
285
-func scrubEither(u interface{}, key []string, okIfMissing bool) (interface{}, error) {
286
- m, ok := u.(map[string]interface{})
285
+func scrubEither(u any, key []string, okIfMissing bool) (any, error) {
286
+ m, ok := u.(map[string]any)
287
if ok {
288
return scrubMapInternal(m, key, okIfMissing)
289
}
290
return scrubValueInternal(m, key, okIfMissing)
291
}
292
293
-func scrubValueInternal(v interface{}, key []string, okIfMissing bool) (interface{}, error) {
293
+func scrubValueInternal(v any, key []string, okIfMissing bool) (any, error) {
294
if v == nil && !okIfMissing {
295
return nil, errors.New("failed to find specified key")
296
}
297
return nil, nil
298
}
299
300
-func scrubMapInternal(m map[string]interface{}, key []string, okIfMissing bool) (map[string]interface{}, error) {
300
+func scrubMapInternal(m map[string]any, key []string, okIfMissing bool) (map[string]any, error) {
301
if len(key) == 0 {
302
- return make(map[string]interface{}), nil // delete value
302
+ return make(map[string]any), nil // delete value
303
}
304
- n := map[string]interface{}{}
304
+ n := map[string]any{}
305
for k, v := range m {
306
if key[0] == "*" || strings.EqualFold(key[0], k) {
307
u, err := scrubEither(v, key[1:], okIfMissing)
@@ -463,7 +463,7 @@ func buildProfileHelp() string {
463
}
464
465
// scrubPrivKey scrubs private key for security reasons.
466
-func scrubPrivKey(cfg *config.Config) (map[string]interface{}, error) {
466
+func scrubPrivKey(cfg *config.Config) (map[string]any, error) {
467
cfgMap, err := config.ToMap(cfg)
468
if err != nil {
469
return nil, err
@@ -553,7 +553,7 @@ func getConfigWithAutoExpand(r repo.Repo, key string) (*ConfigField, error) {
553
}, nil
554
}
555
556
-func setConfig(r repo.Repo, key string, value interface{}) (*ConfigField, error) {
556
+func setConfig(r repo.Repo, key string, value any) (*ConfigField, error) {
557
err := r.SetConfigKey(key, value)
558
if err != nil {
559
return nil, fmt.Errorf("failed to set config value: %s (maybe use --json?)", err)
@@ -646,7 +646,7 @@ func getRemotePinningServices(r repo.Repo) (map[string]config.RemotePinningServi
646
if remoteServicesTag, err := getConfig(r, config.RemoteServicesPath); err == nil {
647
// seems that golang cannot type assert map[string]interface{} to map[string]config.RemotePinningService
648
// so we have to manually copy the data :-|
649
- if val, ok := remoteServicesTag.Value.(map[string]interface{}); ok {
649
+ if val, ok := remoteServicesTag.Value.(map[string]any); ok {
650
jsonString, err := json.Marshal(val)
651
if err != nil {
652
return nil, err
core/commands/dag/dag.go
+3
-3
@@ -294,9 +294,9 @@ CAR file follows the CARv1 format: https://ipld.io/specs/transport/car/carv1/
294
295
// DagStat is a dag stat command response
296
type DagStat struct {
297
- Cid cid.Cid `json:",omitempty"`
298
- Size uint64 `json:",omitempty"`
299
- NumBlocks int64 `json:",omitempty"`
297
+ Cid cid.Cid
298
+ Size uint64 `json:",omitempty"`
299
+ NumBlocks int64 `json:",omitempty"`
300
}
301
302
func (s *DagStat) String() string {
core/commands/e/error.go
+1
-1
@@ -6,7 +6,7 @@ import (
6
)
7
8
// TypeErr returns an error with a string that explains what error was expected and what was received.
9
-func TypeErr(expected, actual interface{}) error {
9
+func TypeErr(expected, actual any) error {
10
return fmt.Errorf("expected type %T, got %T", expected, actual)
11
}
12
core/commands/extra.go
+2
-2
@@ -56,8 +56,8 @@ func GetPreemptsAutoUpdate(e *cmds.Extra) (val bool, found bool) {
56
return getBoolFlag(e, preemptsAutoUpdate{})
57
}
58
59
-func getBoolFlag(e *cmds.Extra, key interface{}) (val bool, found bool) {
60
- var ival interface{}
59
+func getBoolFlag(e *cmds.Extra, key any) (val bool, found bool) {
60
+ var ival any
61
ival, found = e.GetValue(key)
62
if !found {
63
return false, false
core/commands/files_test.go
+1
-1
@@ -30,7 +30,7 @@ func TestFilesCp_DagCborNodeFails(t *testing.T) {
30
"/ipfs/" + protoNode.Cid().String(),
31
"/test-destination",
32
},
33
- Options: map[string]interface{}{
33
+ Options: map[string]any{
34
"force": false,
35
},
36
}
core/commands/filestore.go
+1
-1
@@ -85,7 +85,7 @@ The output is:
85
if err != nil {
86
return err
87
}
88
- return streamResult(func(v interface{}, out io.Writer) nonFatalError {
88
+ return streamResult(func(v any, out io.Writer) nonFatalError {
89
r := v.(*filestore.ListRes)
90
if r.ErrorMsg != "" {
91
return nonFatalError(r.ErrorMsg)
core/commands/get_test.go
+1
-1
@@ -15,7 +15,7 @@ func TestGetOutputPath(t *testing.T) {
15
}{
16
{
17
args: []string{"/ipns/multiformats.io/"},
18
- opts: map[string]interface{}{
18
+ opts: map[string]any{
19
"output": "takes-precedence",
20
},
21
outPath: "takes-precedence",
core/commands/id.go
+2
-2
@@ -146,7 +146,7 @@ EXAMPLE:
146
Type: IdOutput{},
147
}
148
149
-func printPeer(keyEnc ke.KeyEncoder, ps pstore.Peerstore, p peer.ID) (interface{}, error) {
149
+func printPeer(keyEnc ke.KeyEncoder, ps pstore.Peerstore, p peer.ID) (any, error) {
150
if p == "" {
151
return nil, errors.New("attempted to print nil peer")
152
}
@@ -189,7 +189,7 @@ func printPeer(keyEnc ke.KeyEncoder, ps pstore.Peerstore, p peer.ID) (interface{
189
}
190
191
// printing self is special cased as we get values differently.
192
-func printSelf(keyEnc ke.KeyEncoder, node *core.IpfsNode) (interface{}, error) {
192
+func printSelf(keyEnc ke.KeyEncoder, node *core.IpfsNode) (any, error) {
193
info := new(IdOutput)
194
info.ID = keyEnc.FormatID(node.Identity)
195
core/commands/ping.go
+1
-1
@@ -112,7 +112,7 @@ trip latency information.
112
ticker := time.NewTicker(time.Second)
113
defer ticker.Stop()
114
115
- for i := 0; i < numPings; i++ {
115
+ for range numPings {
116
r, ok := <-pings
117
if !ok {
118
break
core/commands/swarm.go
+1
-1
@@ -435,7 +435,7 @@ type connInfo struct {
435
Muxer string `json:",omitempty"`
436
Direction inet.Direction `json:",omitempty"`
437
Streams []streamInfo `json:",omitempty"`
438
- Identify IdOutput `json:",omitempty"`
438
+ Identify IdOutput
439
}
440
441
func (ci *connInfo) Sort() {
core/commands/sysdiag.go
+12
-12
@@ -34,8 +34,8 @@ Prints out information about your computer to aid in easier debugging.
34
},
35
}
36
37
-func getInfo(nd *core.IpfsNode) (map[string]interface{}, error) {
38
- info := make(map[string]interface{})
37
+func getInfo(nd *core.IpfsNode) (map[string]any, error) {
38
+ info := make(map[string]any)
39
err := runtimeInfo(info)
40
if err != nil {
41
return nil, err
@@ -66,8 +66,8 @@ func getInfo(nd *core.IpfsNode) (map[string]interface{}, error) {
66
return info, nil
67
}
68
69
-func runtimeInfo(out map[string]interface{}) error {
70
- rt := make(map[string]interface{})
69
+func runtimeInfo(out map[string]any) error {
70
+ rt := make(map[string]any)
71
rt["os"] = runtime.GOOS
72
rt["arch"] = runtime.GOARCH
73
rt["compiler"] = runtime.Compiler
@@ -80,8 +80,8 @@ func runtimeInfo(out map[string]interface{}) error {
80
return nil
81
}
82
83
-func envVarInfo(out map[string]interface{}) error {
84
- ev := make(map[string]interface{})
83
+func envVarInfo(out map[string]any) error {
84
+ ev := make(map[string]any)
85
ev["GOPATH"] = os.Getenv("GOPATH")
86
ev[config.EnvDir] = os.Getenv(config.EnvDir)
87
@@ -89,7 +89,7 @@ func envVarInfo(out map[string]interface{}) error {
89
return nil
90
}
91
92
-func diskSpaceInfo(out map[string]interface{}) error {
92
+func diskSpaceInfo(out map[string]any) error {
93
pathRoot, err := config.PathRoot()
94
if err != nil {
95
return err
@@ -99,7 +99,7 @@ func diskSpaceInfo(out map[string]interface{}) error {
99
return err
100
}
101
102
- out["diskinfo"] = map[string]interface{}{
102
+ out["diskinfo"] = map[string]any{
103
"fstype": dinfo.FsType,
104
"total_space": dinfo.Total,
105
"free_space": dinfo.Free,
@@ -108,8 +108,8 @@ func diskSpaceInfo(out map[string]interface{}) error {
108
return nil
109
}
110
111
-func memInfo(out map[string]interface{}) error {
112
- m := make(map[string]interface{})
111
+func memInfo(out map[string]any) error {
112
+ m := make(map[string]any)
113
114
meminf, err := sysi.MemoryInfo()
115
if err != nil {
@@ -122,8 +122,8 @@ func memInfo(out map[string]interface{}) error {
122
return nil
123
}
124
125
-func netInfo(online bool, out map[string]interface{}) error {
126
- n := make(map[string]interface{})
125
+func netInfo(online bool, out map[string]any) error {
126
+ n := make(map[string]any)
127
addrs, err := manet.InterfaceMultiaddrs()
128
if err != nil {
129
return err
core/coreapi/test/api_test.go
+1
-1
@@ -37,7 +37,7 @@ func (NodeProvider) MakeAPISwarm(t *testing.T, ctx context.Context, fullIdentity
37
nodes := make([]*core.IpfsNode, n)
38
apis := make([]coreiface.CoreAPI, n)
39
40
- for i := 0; i < n; i++ {
40
+ for i := range n {
41
var ident config.Identity
42
if fullIdentity {
43
sk, pk, err := crypto.GenerateKeyPair(crypto.RSA, 2048)
core/corehttp/gateway.go
+2
-3
@@ -5,6 +5,7 @@ import (
5
"errors"
6
"fmt"
7
"io"
8
+ "maps"
9
"net"
10
"net/http"
11
"time"
@@ -281,9 +282,7 @@ func getGatewayConfig(n *core.IpfsNode) (gateway.Config, map[string][]string, er
282
}
283
284
// Add default implicit known gateways, such as subdomain gateway on localhost.
284
- for hostname, gw := range defaultKnownGateways {
285
- gwCfg.PublicGateways[hostname] = gw
286
- }
285
+ maps.Copy(gwCfg.PublicGateways, defaultKnownGateways)
286
287
// Apply values from cfg.Gateway.PublicGateways if they exist.
288
for hostname, gw := range cfg.Gateway.PublicGateways {
core/corehttp/metrics_test.go
+1
-1
@@ -19,7 +19,7 @@ func TestPeersTotal(t *testing.T) {
19
ctx := context.Background()
20
21
hosts := make([]*bhost.BasicHost, 4)
22
- for i := 0; i < 4; i++ {
22
+ for i := range 4 {
23
var err error
24
hosts[i], err = bhost.NewHost(swarmt.GenSwarm(t), nil)
25
if err != nil {
core/coreiface/options/unixfs.go
+2
-2
@@ -46,7 +46,7 @@ type UnixfsAddSettings struct {
46
FsCache bool
47
NoCopy bool
48
49
- Events chan<- interface{}
49
+ Events chan<- any
50
Silent bool
51
Progress bool
52
@@ -320,7 +320,7 @@ func (unixfsOpts) HashOnly(hashOnly bool) UnixfsAddOption {
320
// Add operation.
321
//
322
// Note that if this channel blocks it may slowdown the adder
323
-func (unixfsOpts) Events(sink chan<- interface{}) UnixfsAddOption {
323
+func (unixfsOpts) Events(sink chan<- any) UnixfsAddOption {
324
return func(settings *UnixfsAddSettings) error {
325
settings.Events = sink
326
return nil
core/coreiface/tests/unixfs.go
+4
-6
@@ -377,14 +377,12 @@ func (tp *TestSuite) TestAdd(t *testing.T) {
377
// handle events if relevant to test case
378
379
opts := testCase.opts
380
- eventOut := make(chan interface{})
380
+ eventOut := make(chan any)
381
var evtWg sync.WaitGroup
382
if len(testCase.events) > 0 {
383
opts = append(opts, options.Unixfs.Events(eventOut))
384
- evtWg.Add(1)
384
386
- go func() {
387
- defer evtWg.Done()
385
+ evtWg.Go(func() {
386
expected := testCase.events
387
388
for evt := range eventOut {
@@ -424,7 +422,7 @@ func (tp *TestSuite) TestAdd(t *testing.T) {
422
if len(expected) > 0 {
423
t.Errorf("%d event(s) didn't arrive", len(expected))
424
}
427
- }()
425
+ })
426
}
427
428
tapi, err := api.WithOptions(testCase.apiOpts...)
@@ -800,7 +798,7 @@ func (tp *TestSuite) TestLsNonUnixfs(t *testing.T) {
798
t.Fatal(err)
799
}
800
803
- nd, err := cbor.WrapObject(map[string]interface{}{"foo": "bar"}, math.MaxUint64, -1)
801
+ nd, err := cbor.WrapObject(map[string]any{"foo": "bar"}, math.MaxUint64, -1)
802
if err != nil {
803
t.Fatal(err)
804
}
core/coreiface/unixfs.go
+6
-6
@@ -14,12 +14,12 @@ import (
14
15
type AddEvent struct {
16
Name string
17
- Path path.ImmutablePath `json:",omitempty"`
18
- Bytes int64 `json:",omitempty"`
19
- Size string `json:",omitempty"`
20
- Mode os.FileMode `json:",omitempty"`
21
- Mtime int64 `json:",omitempty"`
22
- MtimeNsecs int `json:",omitempty"`
17
+ Path path.ImmutablePath
18
+ Bytes int64 `json:",omitempty"`
19
+ Size string `json:",omitempty"`
20
+ Mode os.FileMode `json:",omitempty"`
21
+ Mtime int64 `json:",omitempty"`
22
+ MtimeNsecs int `json:",omitempty"`
23
}
24
25
// FileType is an enum of possible UnixFS file types.
core/corerepo/gc.go
+1
-4
@@ -60,10 +60,7 @@ func NewGC(n *core.IpfsNode) (*GC, error) {
60
61
// calculate the slack space between StorageMax and StorageGCWatermark
62
// used to limit GC duration
63
- slackGB := (storageMax - storageGC) / 10e9
64
- if slackGB < 1 {
65
- slackGB = 1
66
- }
63
+ slackGB := max((storageMax-storageGC)/10e9, 1)
64
65
return &GC{
66
Node: n,
core/coreunix/add.go
+3
-3
@@ -75,7 +75,7 @@ type Adder struct {
75
gcLocker bstore.GCLocker
76
dagService ipld.DAGService
77
bufferedDS *ipld.BufferedDAG
78
- Out chan<- interface{}
78
+ Out chan<- any
79
Progress bool
80
Pin bool
81
PinName string
@@ -576,7 +576,7 @@ func (adder *Adder) maybePauseForGC(ctx context.Context) error {
576
}
577
578
// outputDagnode sends dagnode info over the output channel
579
-func outputDagnode(out chan<- interface{}, name string, dn ipld.Node) error {
579
+func outputDagnode(out chan<- any, name string, dn ipld.Node) error {
580
if out == nil {
581
return nil
582
}
@@ -614,7 +614,7 @@ func getOutput(dagnode ipld.Node) (*coreiface.AddEvent, error) {
614
type progressReader struct {
615
file io.Reader
616
path string
617
- out chan<- interface{}
617
+ out chan<- any
618
bytes int64
619
lastProgress int64
620
}
core/coreunix/add_test.go
+4
-4
@@ -44,7 +44,7 @@ func TestAddMultipleGCLive(t *testing.T) {
44
t.Fatal(err)
45
}
46
47
- out := make(chan interface{}, 10)
47
+ out := make(chan any, 10)
48
adder, err := NewAdder(ctx, node.Pinning, node.Blockstore, node.DAG)
49
if err != nil {
50
t.Fatal(err)
@@ -176,7 +176,7 @@ func TestAddGCLive(t *testing.T) {
176
t.Fatal(err)
177
}
178
179
- out := make(chan interface{})
179
+ out := make(chan any)
180
adder, err := NewAdder(ctx, node.Pinning, node.Blockstore, node.DAG)
181
if err != nil {
182
t.Fatal(err)
@@ -291,7 +291,7 @@ func testAddWPosInfo(t *testing.T, rawLeaves bool) {
291
if err != nil {
292
t.Fatal(err)
293
}
294
- out := make(chan interface{})
294
+ out := make(chan any)
295
adder.Out = out
296
adder.Progress = true
297
adder.RawLeaves = rawLeaves
@@ -382,4 +382,4 @@ func (fi *dummyFileInfo) Size() int64 { return fi.size }
382
func (fi *dummyFileInfo) Mode() os.FileMode { return 0 }
383
func (fi *dummyFileInfo) ModTime() time.Time { return fi.modTime }
384
func (fi *dummyFileInfo) IsDir() bool { return false }
385
-func (fi *dummyFileInfo) Sys() interface{} { return nil }
385
+func (fi *dummyFileInfo) Sys() any { return nil }
core/node/bitswap.go
+3
-3
@@ -47,7 +47,7 @@ type bitswapOptionsOut struct {
47
48
// BitswapOptions creates configuration options for Bitswap from the config file
49
// and whether to provide data.
50
-func BitswapOptions(cfg *config.Config) interface{} {
50
+func BitswapOptions(cfg *config.Config) any {
51
return func() bitswapOptionsOut {
52
var internalBsCfg config.InternalBitswap
53
if cfg.Internal.Bitswap != nil {
@@ -81,7 +81,7 @@ type bitswapIn struct {
81
// Bitswap creates the BitSwap server/client instance.
82
// If Bitswap.ServerEnabled is false, the node will act only as a client
83
// using an empty blockstore to prevent serving blocks to other peers.
84
-func Bitswap(serverEnabled, libp2pEnabled, httpEnabled bool) interface{} {
84
+func Bitswap(serverEnabled, libp2pEnabled, httpEnabled bool) any {
85
return func(in bitswapIn, lc fx.Lifecycle) (*bitswap.Bitswap, error) {
86
var bitswapNetworks, bitswapLibp2p network.BitSwapNetwork
87
var bitswapBlockstore blockstore.Blockstore = in.Bs
@@ -206,7 +206,7 @@ func Bitswap(serverEnabled, libp2pEnabled, httpEnabled bool) interface{} {
206
207
// OnlineExchange creates new LibP2P backed block exchange.
208
// Returns a no-op exchange if Bitswap is disabled.
209
-func OnlineExchange(isBitswapActive bool) interface{} {
209
+func OnlineExchange(isBitswapActive bool) any {
210
return func(in *bitswap.Bitswap, lc fx.Lifecycle) exchange.Interface {
211
if !isBitswapActive {
212
return &noopExchange{closer: in}
core/node/helpers.go
+2
-2
@@ -40,7 +40,7 @@ func (lcss *lcStartStop) Append(f func() func()) {
40
})
41
}
42
43
-func maybeProvide(opt interface{}, enable bool) fx.Option {
43
+func maybeProvide(opt any, enable bool) fx.Option {
44
if enable {
45
return fx.Provide(opt)
46
}
@@ -48,7 +48,7 @@ func maybeProvide(opt interface{}, enable bool) fx.Option {
48
}
49
50
// nolint unused
51
-func maybeInvoke(opt interface{}, enable bool) fx.Option {
51
+func maybeInvoke(opt any, enable bool) fx.Option {
52
if enable {
53
return fx.Invoke(opt)
54
}
core/node/libp2p/addrs.go
+3
-3
@@ -99,7 +99,7 @@ func makeAddrsFactory(announce []string, appendAnnounce []string, noAnnounce []s
99
}, nil
100
}
101
102
-func AddrsFactory(announce []string, appendAnnounce []string, noAnnounce []string) interface{} {
102
+func AddrsFactory(announce []string, appendAnnounce []string, noAnnounce []string) any {
103
return func(params struct {
104
fx.In
105
ForgeMgr *p2pforge.P2PForgeCertMgr `optional:"true"`
@@ -124,7 +124,7 @@ func AddrsFactory(announce []string, appendAnnounce []string, noAnnounce []strin
124
}
125
}
126
127
-func ListenOn(addresses []string) interface{} {
127
+func ListenOn(addresses []string) any {
128
return func() (opts Libp2pOpts) {
129
return Libp2pOpts{
130
Opts: []libp2p.Option{
@@ -134,7 +134,7 @@ func ListenOn(addresses []string) interface{} {
134
}
135
}
136
137
-func P2PForgeCertMgr(repoPath string, cfg config.AutoTLS, atlsLog *logging.ZapEventLogger) interface{} {
137
+func P2PForgeCertMgr(repoPath string, cfg config.AutoTLS, atlsLog *logging.ZapEventLogger) any {
138
return func() (*p2pforge.P2PForgeCertMgr, error) {
139
storagePath := filepath.Join(repoPath, "p2p-forge-certs")
140
rawLogger := atlsLog.Desugar()
core/node/libp2p/pubsub.go
+2
-2
@@ -25,7 +25,7 @@ type pubsubParams struct {
25
Discovery discovery.Discovery
26
}
27
28
-func FloodSub(pubsubOptions ...pubsub.Option) interface{} {
28
+func FloodSub(pubsubOptions ...pubsub.Option) any {
29
return func(mctx helpers.MetricsCtx, lc fx.Lifecycle, params pubsubParams) (service *pubsub.PubSub, err error) {
30
return pubsub.NewFloodSub(
31
helpers.LifecycleCtx(mctx, lc),
@@ -37,7 +37,7 @@ func FloodSub(pubsubOptions ...pubsub.Option) interface{} {
37
}
38
}
39
40
-func GossipSub(pubsubOptions ...pubsub.Option) interface{} {
40
+func GossipSub(pubsubOptions ...pubsub.Option) any {
41
return func(mctx helpers.MetricsCtx, lc fx.Lifecycle, params pubsubParams) (service *pubsub.PubSub, err error) {
42
return pubsub.NewGossipSub(
43
helpers.LifecycleCtx(mctx, lc),
core/node/libp2p/rcmgr.go
+3
-3
@@ -28,7 +28,7 @@ const NetLimitTraceFilename = "rcmgr.json.gz"
28
29
var ErrNoResourceMgr = errors.New("missing ResourceMgr: make sure the daemon is running with Swarm.ResourceMgr.Enabled")
30
31
-func ResourceManager(repoPath string, cfg config.SwarmConfig, userResourceOverrides rcmgr.PartialLimitConfig) interface{} {
31
+func ResourceManager(repoPath string, cfg config.SwarmConfig, userResourceOverrides rcmgr.PartialLimitConfig) any {
32
return func(mctx helpers.MetricsCtx, lc fx.Lifecycle, repo repo.Repo) (network.ResourceManager, Libp2pOpts, error) {
33
var manager network.ResourceManager
34
var opts Libp2pOpts
@@ -231,8 +231,8 @@ func (u ResourceLimitsAndUsage) ToResourceLimits() rcmgr.ResourceLimits {
231
type LimitsConfigAndUsage struct {
232
// This is duplicated from rcmgr.ResourceManagerStat but using ResourceLimitsAndUsage
233
// instead of network.ScopeStat.
234
- System ResourceLimitsAndUsage `json:",omitempty"`
235
- Transient ResourceLimitsAndUsage `json:",omitempty"`
234
+ System ResourceLimitsAndUsage
235
+ Transient ResourceLimitsAndUsage
236
Services map[string]ResourceLimitsAndUsage `json:",omitempty"`
237
Protocols map[protocol.ID]ResourceLimitsAndUsage `json:",omitempty"`
238
Peers map[peer.ID]ResourceLimitsAndUsage `json:",omitempty"`
core/node/libp2p/rcmgr_logging_test.go
+1
-1
@@ -36,7 +36,7 @@ func TestLoggingResourceManager(t *testing.T) {
36
}
37
38
// 2 of these should result in resource limit exceeded errors and subsequent log messages
39
- for i := 0; i < 3; i++ {
39
+ for range 3 {
40
_, _ = lrm.OpenConnection(network.DirInbound, false, ma.StringCast("/ip4/127.0.0.1/tcp/1234"))
41
}
42
core/node/libp2p/routing.go
+1
-1
@@ -63,7 +63,7 @@ type processInitialRoutingOut struct {
63
64
type AddrInfoChan chan peer.AddrInfo
65
66
-func BaseRouting(cfg *config.Config) interface{} {
66
+func BaseRouting(cfg *config.Config) any {
67
return func(lc fx.Lifecycle, in processInitialRoutingIn) (out processInitialRoutingOut, err error) {
68
var dualDHT *ddht.DHT
69
if dht, ok := in.Router.(*ddht.DHT); ok {
core/node/libp2p/sec.go
+1
-1
@@ -8,7 +8,7 @@ import (
8
tls "github.com/libp2p/go-libp2p/p2p/security/tls"
9
)
10
11
-func Security(enabled bool, tptConfig config.Transports) interface{} {
11
+func Security(enabled bool, tptConfig config.Transports) any {
12
if !enabled {
13
return func() (opts Libp2pOpts) {
14
log.Errorf(`Your IPFS node has been configured to run WITHOUT ENCRYPTED CONNECTIONS.
core/node/libp2p/topicdiscovery.go
+1
-1
@@ -12,7 +12,7 @@ import (
12
"github.com/libp2p/go-libp2p/core/routing"
13
)
14
15
-func TopicDiscovery() interface{} {
15
+func TopicDiscovery() any {
16
return func(host host.Host, cr routing.ContentRouting) (service discovery.Discovery, err error) {
17
baseDisc := disc.NewRoutingDiscovery(cr)
18
minBackoff, maxBackoff := time.Second*60, time.Hour
core/node/libp2p/transport.go
+1
-1
@@ -17,7 +17,7 @@ import (
17
"go.uber.org/fx"
18
)
19
20
-func Transports(tptConfig config.Transports) interface{} {
20
+func Transports(tptConfig config.Transports) any {
21
return func(params struct {
22
fx.In
23
Fprint PNetFingerprint `optional:"true"`
fuse/ipns/ipns_test.go
+5
-5
@@ -401,11 +401,11 @@ func TestFSThrash(t *testing.T) {
401
wg := sync.WaitGroup{}
402
403
// Spawn off workers to make directories
404
- for i := 0; i < ndirWorkers; i++ {
404
+ for i := range ndirWorkers {
405
wg.Add(1)
406
go func(worker int) {
407
defer wg.Done()
408
- for j := 0; j < ndirs; j++ {
408
+ for j := range ndirs {
409
dirlock.RLock()
410
n := mrand.Intn(len(dirs))
411
dir := dirs[n]
@@ -425,11 +425,11 @@ func TestFSThrash(t *testing.T) {
425
}
426
427
// Spawn off workers to make files
428
- for i := 0; i < nfileWorkers; i++ {
428
+ for i := range nfileWorkers {
429
wg.Add(1)
430
go func(worker int) {
431
defer wg.Done()
432
- for j := 0; j < nfiles; j++ {
432
+ for j := range nfiles {
433
dirlock.RLock()
434
n := mrand.Intn(len(dirs))
435
dir := dirs[n]
@@ -478,7 +478,7 @@ func TestMultiWrite(t *testing.T) {
478
}
479
480
data := randBytes(1001)
481
- for i := 0; i < len(data); i++ {
481
+ for i := range data {
482
n, err := fi.Write(data[i : i+1])
483
if err != nil {
484
t.Fatal(err)
fuse/ipns/ipns_unix.go
+1
-1
@@ -29,7 +29,7 @@ import (
29
30
func init() {
31
if os.Getenv("IPFS_FUSE_DEBUG") != "" {
32
- fuse.Debug = func(msg interface{}) {
32
+ fuse.Debug = func(msg any) {
33
fmt.Println(msg)
34
}
35
}
fuse/mfs/mfs_test.go
+3
-3
@@ -237,7 +237,7 @@ func TestConcurrentRW(t *testing.T) {
237
238
t.Run("write", func(t *testing.T) {
239
errs := make(chan (error), 1)
240
- for i := 0; i < files; i++ {
240
+ for i := range files {
241
go func() {
242
var err error
243
defer func() { errs <- err }()
@@ -254,7 +254,7 @@ func TestConcurrentRW(t *testing.T) {
254
}
255
}()
256
}
257
- for i := 0; i < files; i++ {
257
+ for range files {
258
err := <-errs
259
if err != nil {
260
t.Fatal(err)
@@ -285,7 +285,7 @@ func TestConcurrentRW(t *testing.T) {
285
}
286
}()
287
}
288
- for i := 0; i < files; i++ {
288
+ for range files {
289
err := <-errs
290
if err != nil {
291
t.Fatal(err)
fuse/mount/mount.go
+1
-1
@@ -77,7 +77,7 @@ func UnmountCmd(point string) (*exec.Cmd, error) {
77
// Attempts a given number of times.
78
func ForceUnmountManyTimes(m Mount, attempts int) error {
79
var err error
80
- for i := 0; i < attempts; i++ {
80
+ for range attempts {
81
err = ForceUnmount(m)
82
if err == nil {
83
return err
fuse/node/mount_unix.go
+6
-12
@@ -86,25 +86,19 @@ func doMount(node *core.IpfsNode, fsdir, nsdir, mfsdir string) error {
86
87
var wg sync.WaitGroup
88
89
- wg.Add(1)
90
- go func() {
91
- defer wg.Done()
89
+ wg.Go(func() {
90
fsmount, err1 = rofs.Mount(node, fsdir)
93
- }()
91
+ })
92
93
if node.IsOnline {
96
- wg.Add(1)
97
- go func() {
98
- defer wg.Done()
94
+ wg.Go(func() {
95
nsmount, err2 = ipns.Mount(node, nsdir, fsdir)
100
- }()
96
+ })
97
}
98
103
- wg.Add(1)
104
- go func() {
105
- defer wg.Done()
99
+ wg.Go(func() {
100
mfmount, err3 = mfs.Mount(node, mfsdir)
107
- }()
101
+ })
102
103
wg.Wait()
104
fuse/readonly/ipfs_test.go
+6
-8
@@ -141,14 +141,14 @@ func TestIpfsStressRead(t *testing.T) {
141
ndiriter := 50
142
143
// Make a bunch of objects
144
- for i := 0; i < nobj; i++ {
144
+ for range nobj {
145
fi, _ := randObj(t, nd, rand.Int63n(50000))
146
nodes = append(nodes, fi)
147
paths = append(paths, fi.Cid().String())
148
}
149
150
// Now make a bunch of dirs
151
- for i := 0; i < ndiriter; i++ {
151
+ for range ndiriter {
152
db, err := uio.NewDirectory(nd.DAG)
153
if err != nil {
154
t.Fatal(err)
@@ -180,12 +180,10 @@ func TestIpfsStressRead(t *testing.T) {
180
wg := sync.WaitGroup{}
181
errs := make(chan error)
182
183
- for s := 0; s < 4; s++ {
184
- wg.Add(1)
185
- go func() {
186
- defer wg.Done()
183
+ for range 4 {
184
+ wg.Go(func() {
185
188
- for i := 0; i < 2000; i++ {
186
+ for range 2000 {
187
item, err := path.NewPath("/ipfs/" + paths[rand.Intn(len(paths))])
188
if err != nil {
189
errs <- err
@@ -220,7 +218,7 @@ func TestIpfsStressRead(t *testing.T) {
218
errs <- errors.New("incorrect read")
219
}
220
}
223
- }()
221
+ })
222
}
223
224
go func() {
gc/gc_test.go
+3
-3
@@ -34,7 +34,7 @@ func TestGC(t *testing.T) {
34
var expectedDiscarded []multihash.Multihash
35
36
// add some pins
37
- for i := 0; i < 5; i++ {
37
+ for range 5 {
38
// direct
39
root, _, err := daggen.MakeDagNode(dserv.Add, 0, 1)
40
require.NoError(t, err)
@@ -54,7 +54,7 @@ func TestGC(t *testing.T) {
54
require.NoError(t, err)
55
56
// add more dags to be GCed
57
- for i := 0; i < 5; i++ {
57
+ for range 5 {
58
_, allCids, err := daggen.MakeDagNode(dserv.Add, 5, 2)
59
require.NoError(t, err)
60
expectedDiscarded = append(expectedDiscarded, toMHs(allCids)...)
@@ -62,7 +62,7 @@ func TestGC(t *testing.T) {
62
63
// and some other as "best effort roots"
64
var bestEffortRoots []cid.Cid
65
- for i := 0; i < 5; i++ {
65
+ for range 5 {
66
root, allCids, err := daggen.MakeDagNode(dserv.Add, 5, 2)
67
require.NoError(t, err)
68
bestEffortRoots = append(bestEffortRoots, root)
plugin/plugin.go
+1
-1
@@ -11,7 +11,7 @@ type Environment struct {
11
//
12
// This is an arbitrary JSON-like object unmarshaled into an interface{}
13
// according to https://golang.org/pkg/encoding/json/#Unmarshal.
14
- Config interface{}
14
+ Config any
15
}
16
17
// Plugin is the base interface for all kinds of go-ipfs plugins
plugin/plugins/badgerds/badgerds.go
+2
-2
@@ -52,7 +52,7 @@ type datastoreConfig struct {
52
// BadgerdsDatastoreConfig returns a configuration stub for a badger datastore
53
// from the given parameters.
54
func (*badgerdsPlugin) DatastoreConfigParser() fsrepo.ConfigFromMap {
55
- return func(params map[string]interface{}) (fsrepo.DatastoreConfig, error) {
55
+ return func(params map[string]any) (fsrepo.DatastoreConfig, error) {
56
var c datastoreConfig
57
var ok bool
58
@@ -104,7 +104,7 @@ func (*badgerdsPlugin) DatastoreConfigParser() fsrepo.ConfigFromMap {
104
}
105
106
func (c *datastoreConfig) DiskSpec() fsrepo.DiskSpec {
107
- return map[string]interface{}{
107
+ return map[string]any{
108
"type": "badgerds",
109
"path": c.path,
110
}
plugin/plugins/flatfs/flatfs.go
+2
-2
@@ -45,7 +45,7 @@ type datastoreConfig struct {
45
// DatastoreConfigParser returns a configuration stub for a flatfs datastore
46
// from the given parameters.
47
func (*flatfsPlugin) DatastoreConfigParser() fsrepo.ConfigFromMap {
48
- return func(params map[string]interface{}) (fsrepo.DatastoreConfig, error) {
48
+ return func(params map[string]any) (fsrepo.DatastoreConfig, error) {
49
var c datastoreConfig
50
var ok bool
51
var err error
@@ -73,7 +73,7 @@ func (*flatfsPlugin) DatastoreConfigParser() fsrepo.ConfigFromMap {
73
}
74
75
func (c *datastoreConfig) DiskSpec() fsrepo.DiskSpec {
76
- return map[string]interface{}{
76
+ return map[string]any{
77
"type": "flatfs",
78
"path": c.path,
79
"shardFunc": c.shardFun.String(),
plugin/plugins/levelds/levelds.go
+2
-2
@@ -45,7 +45,7 @@ type datastoreConfig struct {
45
// DatastoreConfigParser returns a configuration stub for a badger datastore
46
// from the given parameters.
47
func (*leveldsPlugin) DatastoreConfigParser() fsrepo.ConfigFromMap {
48
- return func(params map[string]interface{}) (fsrepo.DatastoreConfig, error) {
48
+ return func(params map[string]any) (fsrepo.DatastoreConfig, error) {
49
var c datastoreConfig
50
var ok bool
51
@@ -70,7 +70,7 @@ func (*leveldsPlugin) DatastoreConfigParser() fsrepo.ConfigFromMap {
70
}
71
72
func (c *datastoreConfig) DiskSpec() fsrepo.DiskSpec {
73
- return map[string]interface{}{
73
+ return map[string]any{
74
"type": "levelds",
75
"path": c.path,
76
}
plugin/plugins/pebbleds/pebbleds.go
+1
-1
@@ -175,7 +175,7 @@ func getConfigInt(name string, params map[string]any) (int, error) {
175
}
176
177
func (c *datastoreConfig) DiskSpec() fsrepo.DiskSpec {
178
- return map[string]interface{}{
178
+ return map[string]any{
179
"type": "pebbleds",
180
"path": c.path,
181
}
plugin/plugins/peerlog/peerlog.go
+3
-3
@@ -74,12 +74,12 @@ func (*peerLogPlugin) Version() string {
74
// since it is internal-only, unsupported functionality.
75
// For supported functionality, we should rework the plugin API to support this use case
76
// of including plugins that are disabled by default.
77
-func extractEnabled(config interface{}) bool {
77
+func extractEnabled(config any) bool {
78
// plugin is disabled by default, unless Enabled=true
79
if config == nil {
80
return false
81
}
82
- mapIface, ok := config.(map[string]interface{})
82
+ mapIface, ok := config.(map[string]any)
83
if !ok {
84
return false
85
}
@@ -123,7 +123,7 @@ func (pl *peerLogPlugin) collectEvents(node *core.IpfsNode) {
123
// don't immediately run into this situation
124
// again.
125
loop:
126
- for i := 0; i < busyDropAmount; i++ {
126
+ for range busyDropAmount {
127
select {
128
case <-pl.events:
129
dropped++
plugin/plugins/peerlog/peerlog_test.go
+5
-5
@@ -5,7 +5,7 @@ import "testing"
5
func TestExtractEnabled(t *testing.T) {
6
for _, c := range []struct {
7
name string
8
- config interface{}
8
+ config any
9
expected bool
10
}{
11
{
@@ -20,22 +20,22 @@ func TestExtractEnabled(t *testing.T) {
20
},
21
{
22
name: "returns false when config has no Enabled field",
23
- config: map[string]interface{}{},
23
+ config: map[string]any{},
24
expected: false,
25
},
26
{
27
name: "returns false when config has a null Enabled field",
28
- config: map[string]interface{}{"Enabled": nil},
28
+ config: map[string]any{"Enabled": nil},
29
expected: false,
30
},
31
{
32
name: "returns false when config has a non-boolean Enabled field",
33
- config: map[string]interface{}{"Enabled": 1},
33
+ config: map[string]any{"Enabled": 1},
34
expected: false,
35
},
36
{
37
name: "returns the value of the Enabled field",
38
- config: map[string]interface{}{"Enabled": true},
38
+ config: map[string]any{"Enabled": true},
39
expected: true,
40
},
41
} {
plugin/plugins/telemetry/telemetry.go
+2
-2
@@ -148,12 +148,12 @@ func (p *telemetryPlugin) Version() string {
148
return "0.0.1"
149
}
150
151
-func readFromConfig(cfg interface{}, key string) string {
151
+func readFromConfig(cfg any, key string) string {
152
if cfg == nil {
153
return ""
154
}
155
156
- pcfg, ok := cfg.(map[string]interface{})
156
+ pcfg, ok := cfg.(map[string]any)
157
if !ok {
158
return ""
159
}
plugin/plugins/telemetry/telemetry_test.go
+1
-1
@@ -95,7 +95,7 @@ func makeNode(t *testing.T) (node *core.IpfsNode, repopath string) {
95
t.Fatal(err)
96
}
97
98
- cfg.Datastore.Spec = map[string]interface{}{
98
+ cfg.Datastore.Spec = map[string]any{
99
"type": "pebbleds",
100
"prefix": "pebble.datastore",
101
"path": "pebbleds",
repo/common/common.go
+13
-13
@@ -6,16 +6,16 @@ import (
6
"strings"
7
)
8
9
-func MapGetKV(v map[string]interface{}, key string) (interface{}, error) {
9
+func MapGetKV(v map[string]any, key string) (any, error) {
10
var ok bool
11
- var mcursor map[string]interface{}
12
- var cursor interface{} = v
11
+ var mcursor map[string]any
12
+ var cursor any = v
13
14
parts := strings.Split(key, ".")
15
for i, part := range parts {
16
sofar := strings.Join(parts[:i], ".")
17
18
- mcursor, ok = cursor.(map[string]interface{})
18
+ mcursor, ok = cursor.(map[string]any)
19
if !ok {
20
return nil, fmt.Errorf("%s key is not a map", sofar)
21
}
@@ -34,14 +34,14 @@ func MapGetKV(v map[string]interface{}, key string) (interface{}, error) {
34
return cursor, nil
35
}
36
37
-func MapSetKV(v map[string]interface{}, key string, value interface{}) error {
37
+func MapSetKV(v map[string]any, key string, value any) error {
38
var ok bool
39
- var mcursor map[string]interface{}
40
- var cursor interface{} = v
39
+ var mcursor map[string]any
40
+ var cursor any = v
41
42
parts := strings.Split(key, ".")
43
for i, part := range parts {
44
- mcursor, ok = cursor.(map[string]interface{})
44
+ mcursor, ok = cursor.(map[string]any)
45
if !ok {
46
sofar := strings.Join(parts[:i], ".")
47
return fmt.Errorf("%s key is not a map", sofar)
@@ -55,7 +55,7 @@ func MapSetKV(v map[string]interface{}, key string, value interface{}) error {
55
56
cursor, ok = mcursor[part]
57
if !ok || cursor == nil { // create map if this is empty or is null
58
- mcursor[part] = map[string]interface{}{}
58
+ mcursor[part] = map[string]any{}
59
cursor = mcursor[part]
60
}
61
}
@@ -64,20 +64,20 @@ func MapSetKV(v map[string]interface{}, key string, value interface{}) error {
64
65
// MapMergeDeep merges the right map into the left map, recursively traversing
66
// child maps until a non-map value is found.
67
-func MapMergeDeep(left, right map[string]interface{}) map[string]interface{} {
67
+func MapMergeDeep(left, right map[string]any) map[string]any {
68
// We want to alter a copy of the map, not the original
69
result := maps.Clone(left)
70
if result == nil {
71
- result = make(map[string]interface{})
71
+ result = make(map[string]any)
72
}
73
74
for key, rightVal := range right {
75
// If right value is a map
76
- if rightMap, ok := rightVal.(map[string]interface{}); ok {
76
+ if rightMap, ok := rightVal.(map[string]any); ok {
77
// If key is in left
78
if leftVal, found := result[key]; found {
79
// If left value is also a map
80
- if leftMap, ok := leftVal.(map[string]interface{}); ok {
80
+ if leftMap, ok := leftVal.(map[string]any); ok {
81
// Merge nested map
82
result[key] = MapMergeDeep(leftMap, rightMap)
83
continue
repo/common/common_test.go
+12
-12
@@ -7,10 +7,10 @@ import (
7
)
8
9
func TestMapMergeDeepReturnsNew(t *testing.T) {
10
- leftMap := make(map[string]interface{})
10
+ leftMap := make(map[string]any)
11
leftMap["A"] = "Hello World"
12
13
- rightMap := make(map[string]interface{})
13
+ rightMap := make(map[string]any)
14
rightMap["A"] = "Foo"
15
16
MapMergeDeep(leftMap, rightMap)
@@ -19,7 +19,7 @@ func TestMapMergeDeepReturnsNew(t *testing.T) {
19
}
20
21
func TestMapMergeDeepNewKey(t *testing.T) {
22
- leftMap := make(map[string]interface{})
22
+ leftMap := make(map[string]any)
23
leftMap["A"] = "Hello World"
24
/*
25
leftMap
@@ -28,7 +28,7 @@ func TestMapMergeDeepNewKey(t *testing.T) {
28
}
29
*/
30
31
- rightMap := make(map[string]interface{})
31
+ rightMap := make(map[string]any)
32
rightMap["B"] = "Bar"
33
/*
34
rightMap
@@ -50,11 +50,11 @@ func TestMapMergeDeepNewKey(t *testing.T) {
50
}
51
52
func TestMapMergeDeepRecursesOnMaps(t *testing.T) {
53
- leftMapA := make(map[string]interface{})
53
+ leftMapA := make(map[string]any)
54
leftMapA["B"] = "A value!"
55
leftMapA["C"] = "Another value!"
56
57
- leftMap := make(map[string]interface{})
57
+ leftMap := make(map[string]any)
58
leftMap["A"] = leftMapA
59
/*
60
leftMap
@@ -66,10 +66,10 @@ func TestMapMergeDeepRecursesOnMaps(t *testing.T) {
66
}
67
*/
68
69
- rightMapA := make(map[string]interface{})
69
+ rightMapA := make(map[string]any)
70
rightMapA["C"] = "A different value!"
71
72
- rightMap := make(map[string]interface{})
72
+ rightMap := make(map[string]any)
73
rightMap["A"] = rightMapA
74
/*
75
rightMap
@@ -91,16 +91,16 @@ func TestMapMergeDeepRecursesOnMaps(t *testing.T) {
91
}
92
*/
93
94
- resultA := result["A"].(map[string]interface{})
94
+ resultA := result["A"].(map[string]any)
95
require.Equal(t, "A value!", resultA["B"], "Unaltered values should not change")
96
require.Equal(t, "A different value!", resultA["C"], "Nested values should be altered")
97
}
98
99
func TestMapMergeDeepRightNotAMap(t *testing.T) {
100
- leftMapA := make(map[string]interface{})
100
+ leftMapA := make(map[string]any)
101
leftMapA["B"] = "A value!"
102
103
- leftMap := make(map[string]interface{})
103
+ leftMap := make(map[string]any)
104
leftMap["A"] = leftMapA
105
/*
106
origMap
@@ -111,7 +111,7 @@ func TestMapMergeDeepRightNotAMap(t *testing.T) {
111
}
112
*/
113
114
- rightMap := make(map[string]interface{})
114
+ rightMap := make(map[string]any)
115
rightMap["A"] = "Not a map!"
116
/*
117
newMap
repo/fsrepo/config_test.go
+3
-3
@@ -123,7 +123,7 @@ func TestLevelDbConfig(t *testing.T) {
123
}
124
dir := t.TempDir()
125
126
- spec := make(map[string]interface{})
126
+ spec := make(map[string]any)
127
err = json.Unmarshal(leveldbConfig, &spec)
128
if err != nil {
129
t.Fatal(err)
@@ -157,7 +157,7 @@ func TestFlatfsConfig(t *testing.T) {
157
}
158
dir := t.TempDir()
159
160
- spec := make(map[string]interface{})
160
+ spec := make(map[string]any)
161
err = json.Unmarshal(flatfsConfig, &spec)
162
if err != nil {
163
t.Fatal(err)
@@ -191,7 +191,7 @@ func TestMeasureConfig(t *testing.T) {
191
}
192
dir := t.TempDir()
193
194
- spec := make(map[string]interface{})
194
+ spec := make(map[string]any)
195
err = json.Unmarshal(measureConfig, &spec)
196
if err != nil {
197
t.Fatal(err)
repo/fsrepo/datastores.go
+15
-15
@@ -15,7 +15,7 @@ import (
15
)
16
17
// ConfigFromMap creates a new datastore config from a map.
18
-type ConfigFromMap func(map[string]interface{}) (DatastoreConfig, error)
18
+type ConfigFromMap func(map[string]any) (DatastoreConfig, error)
19
20
// DatastoreConfig is an abstraction of a datastore config. A "spec" is first
21
// converted to a DatastoreConfig and then Create() is called to instantiate a
@@ -35,7 +35,7 @@ type DatastoreConfig interface {
35
// completely different datastores and a migration will be performed. Runtime
36
// values such as cache options or concurrency options should not be added
37
// here.
38
-type DiskSpec map[string]interface{}
38
+type DiskSpec map[string]any
39
40
// Bytes returns a minimal JSON encoding of the DiskSpec.
41
func (spec DiskSpec) Bytes() []byte {
@@ -75,7 +75,7 @@ func AddDatastoreConfigHandler(name string, dsc ConfigFromMap) error {
75
76
// AnyDatastoreConfig returns a DatastoreConfig from a spec based on
77
// the "type" parameter.
78
-func AnyDatastoreConfig(params map[string]interface{}) (DatastoreConfig, error) {
78
+func AnyDatastoreConfig(params map[string]any) (DatastoreConfig, error) {
79
which, ok := params["type"].(string)
80
if !ok {
81
return nil, fmt.Errorf("'type' field missing or not a string")
@@ -97,14 +97,14 @@ type premount struct {
97
}
98
99
// MountDatastoreConfig returns a mount DatastoreConfig from a spec.
100
-func MountDatastoreConfig(params map[string]interface{}) (DatastoreConfig, error) {
100
+func MountDatastoreConfig(params map[string]any) (DatastoreConfig, error) {
101
var res mountDatastoreConfig
102
- mounts, ok := params["mounts"].([]interface{})
102
+ mounts, ok := params["mounts"].([]any)
103
if !ok {
104
return nil, fmt.Errorf("'mounts' field is missing or not an array")
105
}
106
for _, iface := range mounts {
107
- cfg, ok := iface.(map[string]interface{})
107
+ cfg, ok := iface.(map[string]any)
108
if !ok {
109
return nil, fmt.Errorf("expected map for mountpoint")
110
}
@@ -133,12 +133,12 @@ func MountDatastoreConfig(params map[string]interface{}) (DatastoreConfig, error
133
}
134
135
func (c *mountDatastoreConfig) DiskSpec() DiskSpec {
136
- cfg := map[string]interface{}{"type": "mount"}
137
- mounts := make([]interface{}, len(c.mounts))
136
+ cfg := map[string]any{"type": "mount"}
137
+ mounts := make([]any, len(c.mounts))
138
for i, m := range c.mounts {
139
c := m.ds.DiskSpec()
140
if c == nil {
141
- c = make(map[string]interface{})
141
+ c = make(map[string]any)
142
}
143
c["mountpoint"] = m.prefix.String()
144
mounts[i] = c
@@ -161,11 +161,11 @@ func (c *mountDatastoreConfig) Create(path string) (repo.Datastore, error) {
161
}
162
163
type memDatastoreConfig struct {
164
- cfg map[string]interface{}
164
+ cfg map[string]any
165
}
166
167
// MemDatastoreConfig returns a memory DatastoreConfig from a spec.
168
-func MemDatastoreConfig(params map[string]interface{}) (DatastoreConfig, error) {
168
+func MemDatastoreConfig(params map[string]any) (DatastoreConfig, error) {
169
return &memDatastoreConfig{params}, nil
170
}
171
@@ -183,8 +183,8 @@ type logDatastoreConfig struct {
183
}
184
185
// LogDatastoreConfig returns a log DatastoreConfig from a spec.
186
-func LogDatastoreConfig(params map[string]interface{}) (DatastoreConfig, error) {
187
- childField, ok := params["child"].(map[string]interface{})
186
+func LogDatastoreConfig(params map[string]any) (DatastoreConfig, error) {
187
+ childField, ok := params["child"].(map[string]any)
188
if !ok {
189
return nil, fmt.Errorf("'child' field is missing or not a map")
190
}
@@ -217,8 +217,8 @@ type measureDatastoreConfig struct {
217
}
218
219
// MeasureDatastoreConfig returns a measure DatastoreConfig from a spec.
220
-func MeasureDatastoreConfig(params map[string]interface{}) (DatastoreConfig, error) {
221
- childField, ok := params["child"].(map[string]interface{})
220
+func MeasureDatastoreConfig(params map[string]any) (DatastoreConfig, error) {
221
+ childField, ok := params["child"].(map[string]any)
222
if !ok {
223
return nil, fmt.Errorf("'child' field is missing or not a map")
224
}
repo/fsrepo/fsrepo.go
+6
-6
@@ -279,7 +279,7 @@ func initConfig(path string, conf *config.Config) error {
279
return nil
280
}
281
282
-func initSpec(path string, conf map[string]interface{}) error {
282
+func initSpec(path string, conf map[string]any) error {
283
fn, err := config.Path(path, specFn)
284
if err != nil {
285
return err
@@ -651,7 +651,7 @@ func (r *FSRepo) SetConfig(updated *config.Config) error {
651
// to avoid clobbering user-provided keys, must read the config from disk
652
// as a map, write the updated struct values to the map and write the map
653
// to disk.
654
- var mapconf map[string]interface{}
654
+ var mapconf map[string]any
655
if err := serialize.ReadConfigFile(r.configFilePath, &mapconf); err != nil {
656
return err
657
}
@@ -670,7 +670,7 @@ func (r *FSRepo) SetConfig(updated *config.Config) error {
670
}
671
672
// GetConfigKey retrieves only the value of a particular key.
673
-func (r *FSRepo) GetConfigKey(key string) (interface{}, error) {
673
+func (r *FSRepo) GetConfigKey(key string) (any, error) {
674
packageLock.Lock()
675
defer packageLock.Unlock()
676
@@ -678,7 +678,7 @@ func (r *FSRepo) GetConfigKey(key string) (interface{}, error) {
678
return nil, errors.New("repo is closed")
679
}
680
681
- var cfg map[string]interface{}
681
+ var cfg map[string]any
682
if err := serialize.ReadConfigFile(r.configFilePath, &cfg); err != nil {
683
return nil, err
684
}
@@ -686,7 +686,7 @@ func (r *FSRepo) GetConfigKey(key string) (interface{}, error) {
686
}
687
688
// SetConfigKey writes the value of a particular key.
689
-func (r *FSRepo) SetConfigKey(key string, value interface{}) error {
689
+func (r *FSRepo) SetConfigKey(key string, value any) error {
690
packageLock.Lock()
691
defer packageLock.Unlock()
692
@@ -701,7 +701,7 @@ func (r *FSRepo) SetConfigKey(key string, value interface{}) error {
701
}
702
703
// Load into a map so we don't end up writing any additional defaults to the config file.
704
- var mapconf map[string]interface{}
704
+ var mapconf map[string]any
705
if err := serialize.ReadConfigFile(r.configFilePath, &mapconf); err != nil {
706
return err
707
}
repo/fsrepo/fsrepo_test.go
+1
-1
@@ -15,7 +15,7 @@ import (
15
func TestInitIdempotence(t *testing.T) {
16
t.Parallel()
17
path := t.TempDir()
18
- for i := 0; i < 10; i++ {
18
+ for range 10 {
19
require.NoError(t, Init(path, &config.Config{Datastore: config.DefaultDatastoreConfig()}), "multiple calls to init should succeed")
20
}
21
}
repo/fsrepo/migrations/atomicfile/atomicfile_test.go
+1
-1
@@ -187,7 +187,7 @@ func TestNoTempFilesAfterOperations(t *testing.T) {
187
dir := t.TempDir()
188
189
// Perform multiple operations
190
- for i := 0; i < testIterations; i++ {
190
+ for i := range testIterations {
191
path := filepath.Join(dir, fmt.Sprintf("test%d.txt", i))
192
193
af, err := New(path, 0644)
repo/fsrepo/migrations/common/config_helpers.go
+7
-7
@@ -207,7 +207,7 @@ func CopyField(config map[string]any, from, to string) error {
207
}
208
209
// ConvertInterfaceSlice converts []interface{} to []string
210
-func ConvertInterfaceSlice(slice []interface{}) []string {
210
+func ConvertInterfaceSlice(slice []any) []string {
211
result := make([]string, 0, len(slice))
212
for _, item := range slice {
213
if str, ok := item.(string); ok {
@@ -241,11 +241,11 @@ func SafeCastMap(value any) map[string]any {
241
}
242
243
// SafeCastSlice safely casts to []interface{} with fallback to empty slice
244
-func SafeCastSlice(value any) []interface{} {
245
- if s, ok := value.([]interface{}); ok {
244
+func SafeCastSlice(value any) []any {
245
+ if s, ok := value.([]any); ok {
246
return s
247
}
248
- return []interface{}{}
248
+ return []any{}
249
}
250
251
// ReplaceDefaultsWithAuto replaces default values with "auto" in a map
@@ -271,7 +271,7 @@ func EnsureSliceContains(config map[string]any, path string, value string) {
271
return
272
}
273
274
- if slice, ok := existing.([]interface{}); ok {
274
+ if slice, ok := existing.([]any); ok {
275
// Check if value already exists
276
for _, item := range slice {
277
if str, ok := item.(string); ok && str == value {
@@ -297,7 +297,7 @@ func ReplaceInSlice(config map[string]any, path string, oldValue, newValue strin
297
return
298
}
299
300
- if slice, ok := existing.([]interface{}); ok {
300
+ if slice, ok := existing.([]any); ok {
301
result := make([]string, 0, len(slice))
302
for _, item := range slice {
303
if str, ok := item.(string); ok {
@@ -343,7 +343,7 @@ func IsEmptySlice(value any) bool {
343
if value == nil {
344
return true
345
}
346
- if slice, ok := value.([]interface{}); ok {
346
+ if slice, ok := value.([]any); ok {
347
return len(slice) == 0
348
}
349
if slice, ok := value.([]string); ok {
repo/fsrepo/migrations/common/testing_helpers.go
+2
-2
@@ -78,7 +78,7 @@ func AssertConfigField(t *testing.T, config map[string]any, path string, expecte
78
// Handle different types of comparisons
79
switch exp := expected.(type) {
80
case []string:
81
- actualSlice, ok := actual.([]interface{})
81
+ actualSlice, ok := actual.([]any)
82
if !ok {
83
t.Errorf("field %s: expected []string, got %T", path, actual)
84
return
@@ -133,7 +133,7 @@ func CreateTestRepo(t *testing.T, version int, config map[string]any) string {
133
134
// Write version file
135
versionPath := filepath.Join(tempDir, "version")
136
- err := os.WriteFile(versionPath, []byte(fmt.Sprintf("%d", version)), 0644)
136
+ err := os.WriteFile(versionPath, fmt.Appendf(nil, "%d", version), 0644)
137
if err != nil {
138
t.Fatalf("failed to write version file: %v", err)
139
}
repo/fsrepo/migrations/fs-repo-16-to-17/migration/migration_test.go
+48
-49
@@ -3,6 +3,7 @@ package mg16
3
import (
4
"bytes"
5
"encoding/json"
6
+ "maps"
7
"os"
8
"path/filepath"
9
"testing"
@@ -13,13 +14,13 @@ import (
14
)
15
16
// Helper function to run migration on JSON input and return result
16
-func runMigrationOnJSON(t *testing.T, input string) map[string]interface{} {
17
+func runMigrationOnJSON(t *testing.T, input string) map[string]any {
18
t.Helper()
19
var output bytes.Buffer
20
err := convert(bytes.NewReader([]byte(input)), &output)
21
require.NoError(t, err)
22
22
- var result map[string]interface{}
23
+ var result map[string]any
24
err = json.Unmarshal(output.Bytes(), &result)
25
require.NoError(t, err)
26
@@ -27,33 +28,33 @@ func runMigrationOnJSON(t *testing.T, input string) map[string]interface{} {
28
}
29
30
// Helper function to assert nested map key has expected value
30
-func assertMapKeyEquals(t *testing.T, result map[string]interface{}, path []string, key string, expected interface{}) {
31
+func assertMapKeyEquals(t *testing.T, result map[string]any, path []string, key string, expected any) {
32
t.Helper()
33
current := result
34
for _, p := range path {
35
section, exists := current[p]
36
require.True(t, exists, "Section %s not found in path %v", p, path)
36
- current = section.(map[string]interface{})
37
+ current = section.(map[string]any)
38
}
39
40
assert.Equal(t, expected, current[key], "Expected %s to be %v", key, expected)
41
}
42
43
// Helper function to assert slice contains expected values
43
-func assertSliceEquals(t *testing.T, result map[string]interface{}, path []string, expected []string) {
44
+func assertSliceEquals(t *testing.T, result map[string]any, path []string, expected []string) {
45
t.Helper()
46
current := result
47
for i, p := range path[:len(path)-1] {
48
section, exists := current[p]
49
require.True(t, exists, "Section %s not found in path %v at index %d", p, path, i)
49
- current = section.(map[string]interface{})
50
+ current = section.(map[string]any)
51
}
52
53
sliceKey := path[len(path)-1]
54
slice, exists := current[sliceKey]
55
require.True(t, exists, "Slice %s not found", sliceKey)
56
56
- actualSlice := slice.([]interface{})
57
+ actualSlice := slice.([]any)
58
require.Equal(t, len(expected), len(actualSlice), "Expected slice length %d, got %d", len(expected), len(actualSlice))
59
60
for i, exp := range expected {
@@ -62,27 +63,25 @@ func assertSliceEquals(t *testing.T, result map[string]interface{}, path []strin
63
}
64
65
// Helper to build test config JSON with specified fields
65
-func buildTestConfig(fields map[string]interface{}) string {
66
- config := map[string]interface{}{
67
- "Identity": map[string]interface{}{"PeerID": "QmTest"},
68
- }
69
- for k, v := range fields {
70
- config[k] = v
66
+func buildTestConfig(fields map[string]any) string {
67
+ config := map[string]any{
68
+ "Identity": map[string]any{"PeerID": "QmTest"},
69
}
70
+ maps.Copy(config, fields)
71
data, _ := json.MarshalIndent(config, "", " ")
72
return string(data)
73
}
74
75
// Helper to run migration and get DNS resolvers
77
-func runMigrationAndGetDNSResolvers(t *testing.T, input string) map[string]interface{} {
76
+func runMigrationAndGetDNSResolvers(t *testing.T, input string) map[string]any {
77
t.Helper()
78
result := runMigrationOnJSON(t, input)
80
- dns := result["DNS"].(map[string]interface{})
81
- return dns["Resolvers"].(map[string]interface{})
79
+ dns := result["DNS"].(map[string]any)
80
+ return dns["Resolvers"].(map[string]any)
81
}
82
83
// Helper to assert multiple resolver values
85
-func assertResolvers(t *testing.T, resolvers map[string]interface{}, expected map[string]string) {
84
+func assertResolvers(t *testing.T, resolvers map[string]any, expected map[string]string) {
85
t.Helper()
86
for key, expectedValue := range expected {
87
assert.Equal(t, expectedValue, resolvers[key], "Expected %s resolver to be %v", key, expectedValue)
@@ -100,25 +99,25 @@ func TestMigration(t *testing.T) {
99
defer os.RemoveAll(tempDir)
100
101
// Create a test config with default bootstrap peers
103
- testConfig := map[string]interface{}{
102
+ testConfig := map[string]any{
103
"Bootstrap": []string{
104
"/dnsaddr/bootstrap.libp2p.io/p2p/QmNnooDu7bfjPFoTZYxMNLWUQJyrVwtbZg5gBMjTezGAJN",
105
"/dnsaddr/bootstrap.libp2p.io/p2p/QmQCU2EcMqAqQPR2i9bChDtGNJchTbq5TbXJJ16u19uLTa",
106
"/ip4/192.168.1.1/tcp/4001/p2p/QmCustomPeer", // Custom peer
107
},
109
- "DNS": map[string]interface{}{
108
+ "DNS": map[string]any{
109
"Resolvers": map[string]string{},
110
},
112
- "Routing": map[string]interface{}{
111
+ "Routing": map[string]any{
112
"DelegatedRouters": []string{},
113
},
115
- "Ipns": map[string]interface{}{
114
+ "Ipns": map[string]any{
115
"ResolveCacheSize": 128,
116
},
118
- "Identity": map[string]interface{}{
117
+ "Identity": map[string]any{
118
"PeerID": "QmTest",
119
},
121
- "Version": map[string]interface{}{
120
+ "Version": map[string]any{
121
"Current": "0.36.0",
122
},
123
}
@@ -153,38 +152,38 @@ func TestMigration(t *testing.T) {
152
configData, err = os.ReadFile(configPath)
153
require.NoError(t, err)
154
156
- var updatedConfig map[string]interface{}
155
+ var updatedConfig map[string]any
156
err = json.Unmarshal(configData, &updatedConfig)
157
require.NoError(t, err)
158
159
// Check AutoConf was added
160
autoConf, exists := updatedConfig["AutoConf"]
161
assert.True(t, exists, "AutoConf section not added")
163
- autoConfMap := autoConf.(map[string]interface{})
162
+ autoConfMap := autoConf.(map[string]any)
163
// URL is not set explicitly in migration (uses implicit default)
164
_, hasURL := autoConfMap["URL"]
165
assert.False(t, hasURL, "AutoConf URL should not be explicitly set in migration")
166
167
// Check Bootstrap was updated
169
- bootstrap := updatedConfig["Bootstrap"].([]interface{})
168
+ bootstrap := updatedConfig["Bootstrap"].([]any)
169
assert.Equal(t, 2, len(bootstrap), "Expected 2 bootstrap entries")
170
assert.Equal(t, "auto", bootstrap[0], "Expected first bootstrap entry to be 'auto'")
171
assert.Equal(t, "/ip4/192.168.1.1/tcp/4001/p2p/QmCustomPeer", bootstrap[1], "Expected custom peer to be preserved")
172
173
// Check DNS.Resolvers was updated
175
- dns := updatedConfig["DNS"].(map[string]interface{})
176
- resolvers := dns["Resolvers"].(map[string]interface{})
174
+ dns := updatedConfig["DNS"].(map[string]any)
175
+ resolvers := dns["Resolvers"].(map[string]any)
176
assert.Equal(t, "auto", resolvers["."], "Expected DNS resolver for '.' to be 'auto'")
177
178
// Check Routing.DelegatedRouters was updated
180
- routing := updatedConfig["Routing"].(map[string]interface{})
181
- delegatedRouters := routing["DelegatedRouters"].([]interface{})
179
+ routing := updatedConfig["Routing"].(map[string]any)
180
+ delegatedRouters := routing["DelegatedRouters"].([]any)
181
assert.Equal(t, 1, len(delegatedRouters))
182
assert.Equal(t, "auto", delegatedRouters[0], "Expected DelegatedRouters to be ['auto']")
183
184
// Check Ipns.DelegatedPublishers was updated
186
- ipns := updatedConfig["Ipns"].(map[string]interface{})
187
- delegatedPublishers := ipns["DelegatedPublishers"].([]interface{})
185
+ ipns := updatedConfig["Ipns"].(map[string]any)
186
+ delegatedPublishers := ipns["DelegatedPublishers"].([]any)
187
assert.Equal(t, 1, len(delegatedPublishers))
188
assert.Equal(t, "auto", delegatedPublishers[0], "Expected DelegatedPublishers to be ['auto']")
189
@@ -200,7 +199,7 @@ func TestMigration(t *testing.T) {
199
200
func TestConvert(t *testing.T) {
201
t.Parallel()
203
- input := buildTestConfig(map[string]interface{}{
202
+ input := buildTestConfig(map[string]any{
203
"Bootstrap": []string{
204
"/dnsaddr/bootstrap.libp2p.io/p2p/QmNnooDu7bfjPFoTZYxMNLWUQJyrVwtbZg5gBMjTezGAJN",
205
"/dnsaddr/bootstrap.libp2p.io/p2p/QmQCU2EcMqAqQPR2i9bChDtGNJchTbq5TbXJJ16u19uLTa",
@@ -212,7 +211,7 @@ func TestConvert(t *testing.T) {
211
// Check that AutoConf section was added but is empty (using implicit defaults)
212
autoConf, exists := result["AutoConf"]
213
require.True(t, exists, "AutoConf section should exist")
215
- autoConfMap, ok := autoConf.(map[string]interface{})
214
+ autoConfMap, ok := autoConf.(map[string]any)
215
require.True(t, ok, "AutoConf should be a map")
216
require.Empty(t, autoConfMap, "AutoConf should be empty (using implicit defaults)")
217
@@ -282,7 +281,7 @@ func TestBootstrapMigration(t *testing.T) {
281
282
t.Run("replaces all old default bootstrapper peers with auto entry", func(t *testing.T) {
283
t.Parallel()
285
- input := buildTestConfig(map[string]interface{}{
284
+ input := buildTestConfig(map[string]any{
285
"Bootstrap": []string{
286
"/dnsaddr/bootstrap.libp2p.io/p2p/QmNnooDu7bfjPFoTZYxMNLWUQJyrVwtbZg5gBMjTezGAJN",
287
"/dnsaddr/bootstrap.libp2p.io/p2p/QmQCU2EcMqAqQPR2i9bChDtGNJchTbq5TbXJJ16u19uLTa",
@@ -322,8 +321,8 @@ func TestDNSMigration(t *testing.T) {
321
322
t.Run("preserves all custom DNS resolvers unchanged", func(t *testing.T) {
323
t.Parallel()
325
- input := buildTestConfig(map[string]interface{}{
326
- "DNS": map[string]interface{}{
324
+ input := buildTestConfig(map[string]any{
325
+ "DNS": map[string]any{
326
"Resolvers": map[string]string{
327
".": "https://my-custom-resolver.com",
328
".eth": "https://eth.resolver",
@@ -340,8 +339,8 @@ func TestDNSMigration(t *testing.T) {
339
340
t.Run("preserves custom dot and eth resolvers unchanged", func(t *testing.T) {
341
t.Parallel()
343
- input := buildTestConfig(map[string]interface{}{
344
- "DNS": map[string]interface{}{
342
+ input := buildTestConfig(map[string]any{
343
+ "DNS": map[string]any{
344
"Resolvers": map[string]string{
345
".": "https://cloudflare-dns.com/dns-query",
346
".eth": "https://example.com/dns-query",
@@ -358,8 +357,8 @@ func TestDNSMigration(t *testing.T) {
357
358
t.Run("replaces old default eth resolver with auto", func(t *testing.T) {
359
t.Parallel()
361
- input := buildTestConfig(map[string]interface{}{
362
- "DNS": map[string]interface{}{
360
+ input := buildTestConfig(map[string]any{
361
+ "DNS": map[string]any{
362
"Resolvers": map[string]string{
363
".": "https://cloudflare-dns.com/dns-query",
364
".eth": "https://dns.eth.limo/dns-query", // should be replaced
@@ -395,8 +394,8 @@ func TestRoutingMigration(t *testing.T) {
394
395
t.Run("replaces cid.contact with auto while preserving custom routers added by user", func(t *testing.T) {
396
t.Parallel()
398
- input := buildTestConfig(map[string]interface{}{
399
- "Routing": map[string]interface{}{
397
+ input := buildTestConfig(map[string]any{
398
+ "Routing": map[string]any{
399
"DelegatedRouters": []string{
400
"https://cid.contact",
401
"https://my-custom-router.com",
@@ -425,8 +424,8 @@ func TestIpnsMigration(t *testing.T) {
424
425
t.Run("preserves existing custom DelegatedPublishers unchanged", func(t *testing.T) {
426
t.Parallel()
428
- input := buildTestConfig(map[string]interface{}{
429
- "Ipns": map[string]interface{}{
427
+ input := buildTestConfig(map[string]any{
428
+ "Ipns": map[string]any{
429
"DelegatedPublishers": []string{
430
"https://my-publisher.com",
431
"https://another-publisher.com",
@@ -440,8 +439,8 @@ func TestIpnsMigration(t *testing.T) {
439
440
t.Run("adds auto DelegatedPublishers to existing Ipns section", func(t *testing.T) {
441
t.Parallel()
443
- input := buildTestConfig(map[string]interface{}{
444
- "Ipns": map[string]interface{}{
442
+ input := buildTestConfig(map[string]any{
443
+ "Ipns": map[string]any{
444
"ResolveCacheSize": 128,
445
},
446
})
@@ -461,8 +460,8 @@ func TestAutoConfMigration(t *testing.T) {
460
461
t.Run("preserves existing AutoConf fields unchanged", func(t *testing.T) {
462
t.Parallel()
464
- input := buildTestConfig(map[string]interface{}{
465
- "AutoConf": map[string]interface{}{
463
+ input := buildTestConfig(map[string]any{
464
+ "AutoConf": map[string]any{
465
"URL": "https://custom.example.com/autoconf.json",
466
"Enabled": false,
467
"CustomField": "preserved",
repo/fsrepo/migrations/ipfsdir.go
+1
-1
@@ -70,7 +70,7 @@ func WriteRepoVersion(ipfsDir string, version int) error {
70
}
71
72
vFilePath := filepath.Join(ipfsDir, versionFile)
73
- return os.WriteFile(vFilePath, []byte(fmt.Sprintf("%d\n", version)), 0o644)
73
+ return os.WriteFile(vFilePath, fmt.Appendf(nil, "%d\n", version), 0o644)
74
}
75
76
func repoVersion(ipfsDir string) (int, error) {
repo/mock.go
+2
-2
@@ -44,11 +44,11 @@ func (m *Mock) BackupConfig(prefix string) (string, error) {
44
return "", errTODO
45
}
46
47
-func (m *Mock) SetConfigKey(key string, value interface{}) error {
47
+func (m *Mock) SetConfigKey(key string, value any) error {
48
return errTODO
49
}
50
51
-func (m *Mock) GetConfigKey(key string) (interface{}, error) {
51
+func (m *Mock) GetConfigKey(key string) (any, error) {
52
return nil, errTODO
53
}
54
repo/onlyone.go
+4
-4
@@ -8,7 +8,7 @@ import (
8
// open one.
9
type OnlyOne struct {
10
mu sync.Mutex
11
- active map[interface{}]*ref
11
+ active map[any]*ref
12
}
13
14
// Open a Repo identified by key. If Repo is not already open, the
@@ -23,11 +23,11 @@ type OnlyOne struct {
23
// r, err := o.Open(repoKey(path), open)
24
//
25
// Call Repo.Close when done.
26
-func (o *OnlyOne) Open(key interface{}, open func() (Repo, error)) (Repo, error) {
26
+func (o *OnlyOne) Open(key any, open func() (Repo, error)) (Repo, error) {
27
o.mu.Lock()
28
defer o.mu.Unlock()
29
if o.active == nil {
30
- o.active = make(map[interface{}]*ref)
30
+ o.active = make(map[any]*ref)
31
}
32
33
item, found := o.active[key]
@@ -49,7 +49,7 @@ func (o *OnlyOne) Open(key interface{}, open func() (Repo, error)) (Repo, error)
49
50
type ref struct {
51
parent *OnlyOne
52
- key interface{}
52
+ key any
53
refs uint32
54
Repo
55
}
repo/repo.go
+2
-2
@@ -38,10 +38,10 @@ type Repo interface {
38
SetConfig(*config.Config) error
39
40
// SetConfigKey sets the given key-value pair within the config and persists it to storage.
41
- SetConfigKey(key string, value interface{}) error
41
+ SetConfigKey(key string, value any) error
42
43
// GetConfigKey reads the value for the given key from the configuration in storage.
44
- GetConfigKey(key string) (interface{}, error)
44
+ GetConfigKey(key string) (any, error)
45
46
// Datastore returns a reference to the configured data storage backend.
47
Datastore() Datastore
test/cli/add_test.go
+1
-1
@@ -630,7 +630,7 @@ func createDeterministicFiles(dirPath string, numFiles, nameLen, lastNameLen int
630
return err
631
}
632
633
- for i := 0; i < numFiles; i++ {
633
+ for i := range numFiles {
634
// Use lastNameLen for the final file
635
currentNameLen := nameLen
636
if i == numFiles-1 {
test/cli/api_file_test.go
+2
-2
@@ -37,7 +37,7 @@ func TestAddressFileReady(t *testing.T) {
37
// Poll for api file to appear
38
apiFile := filepath.Join(node.Dir, "api")
39
var fileExists bool
40
- for i := 0; i < 100; i++ {
40
+ for range 100 {
41
if _, err := os.Stat(apiFile); err == nil {
42
fileExists = true
43
break
@@ -81,7 +81,7 @@ func TestAddressFileReady(t *testing.T) {
81
// Poll for gateway file to appear
82
gatewayFile := filepath.Join(node.Dir, "gateway")
83
var fileExists bool
84
- for i := 0; i < 100; i++ {
84
+ for range 100 {
85
if _, err := os.Stat(gatewayFile); err == nil {
86
fileExists = true
87
break
test/cli/autoconf/expand_comprehensive_test.go
+14
-14
@@ -85,37 +85,37 @@ func testAllAutoConfFieldsResolve(t *testing.T) {
85
// Create comprehensive autoconf response matching Schema 4 format
86
// Use server URLs to ensure they're reachable and valid
87
serverURL := fmt.Sprintf("http://%s", r.Host) // Get the server URL from the request
88
- autoConf := map[string]interface{}{
88
+ autoConf := map[string]any{
89
"AutoConfVersion": 2025072301,
90
"AutoConfSchema": 1,
91
"AutoConfTTL": 86400,
92
- "SystemRegistry": map[string]interface{}{
93
- "AminoDHT": map[string]interface{}{
92
+ "SystemRegistry": map[string]any{
93
+ "AminoDHT": map[string]any{
94
"URL": "https://github.com/ipfs/specs/pull/497",
95
"Description": "Test AminoDHT system",
96
- "NativeConfig": map[string]interface{}{
96
+ "NativeConfig": map[string]any{
97
"Bootstrap": []string{
98
"/dnsaddr/bootstrap.libp2p.io/p2p/QmNnooDu7bfjPFoTZYxMNLWUQJyrVwtbZg5gBMjTezGAJN",
99
"/dnsaddr/bootstrap.libp2p.io/p2p/QmQCU2EcMqAqQPR2i9bChDtGNJchTbq5TbXJJ16u19uLTa",
100
},
101
},
102
- "DelegatedConfig": map[string]interface{}{
102
+ "DelegatedConfig": map[string]any{
103
"Read": []string{"/routing/v1/providers", "/routing/v1/peers", "/routing/v1/ipns"},
104
"Write": []string{"/routing/v1/ipns"},
105
},
106
},
107
- "IPNI": map[string]interface{}{
107
+ "IPNI": map[string]any{
108
"URL": serverURL + "/ipni-system",
109
"Description": "Test IPNI system",
110
- "DelegatedConfig": map[string]interface{}{
110
+ "DelegatedConfig": map[string]any{
111
"Read": []string{"/routing/v1/providers"},
112
"Write": []string{},
113
},
114
},
115
- "CustomIPNS": map[string]interface{}{
115
+ "CustomIPNS": map[string]any{
116
"URL": serverURL + "/ipns-system",
117
"Description": "Test IPNS system",
118
- "DelegatedConfig": map[string]interface{}{
118
+ "DelegatedConfig": map[string]any{
119
"Read": []string{"/routing/v1/ipns"},
120
"Write": []string{"/routing/v1/ipns"},
121
},
@@ -125,8 +125,8 @@ func testAllAutoConfFieldsResolve(t *testing.T) {
125
".": {"https://cloudflare-dns.com/dns-query"},
126
"eth.": {"https://dns.google/dns-query"},
127
},
128
- "DelegatedEndpoints": map[string]interface{}{
129
- serverURL: map[string]interface{}{
128
+ "DelegatedEndpoints": map[string]any{
129
+ serverURL: map[string]any{
130
"Systems": []string{"IPNI", "CustomIPNS"}, // Use non-AminoDHT systems to avoid filtering
131
"Read": []string{"/routing/v1/providers", "/routing/v1/ipns"},
132
"Write": []string{"/routing/v1/ipns"},
@@ -155,7 +155,7 @@ func testAllAutoConfFieldsResolve(t *testing.T) {
155
// Clear any existing autoconf cache to prevent interference
156
result := node.RunIPFS("config", "show")
157
if result.ExitCode() == 0 {
158
- var cfg map[string]interface{}
158
+ var cfg map[string]any
159
if json.Unmarshal([]byte(result.Stdout.String()), &cfg) == nil {
160
if repoPath, exists := cfg["path"]; exists {
161
if pathStr, ok := repoPath.(string); ok {
@@ -436,12 +436,12 @@ func testConfigShowExpandAutoComplete(t *testing.T) {
436
assert.Contains(t, expandedConfig, "bootstrap.libp2p.io", "Should contain expanded bootstrap peers")
437
438
// Should be valid JSON
439
- var configMap map[string]interface{}
439
+ var configMap map[string]any
440
err := json.Unmarshal([]byte(expandedConfig), &configMap)
441
require.NoError(t, err, "Expanded config should be valid JSON")
442
443
// Verify specific fields were expanded
444
- if bootstrap, ok := configMap["Bootstrap"].([]interface{}); ok {
444
+ if bootstrap, ok := configMap["Bootstrap"].([]any); ok {
445
assert.Greater(t, len(bootstrap), 0, "Bootstrap should have expanded entries")
446
for _, peer := range bootstrap {
447
assert.NotEqual(t, "auto", peer, "Bootstrap entries should not be 'auto'")
test/cli/autoconf/expand_fallback_test.go
+3
-5
@@ -5,6 +5,7 @@ import (
5
"net/http"
6
"net/http/httptest"
7
"os"
8
+ "slices"
9
"testing"
10
"time"
11
@@ -240,11 +241,8 @@ func testDaemonWithMalformedAutoConf(t *testing.T) {
241
242
foundFallbackPeers := 0
243
for _, expectedPeer := range expectedBootstrapPeers {
243
- for _, actualPeer := range bootstrap {
244
- if actualPeer == expectedPeer {
245
- foundFallbackPeers++
246
- break
247
- }
244
+ if slices.Contains(bootstrap, expectedPeer) {
245
+ foundFallbackPeers++
246
}
247
}
248
assert.Greater(t, foundFallbackPeers, 0, "Should contain bootstrap peers from GetMainnetFallbackConfig() AminoDHT NativeConfig")
test/cli/autoconf/expand_test.go
+1
-1
@@ -286,7 +286,7 @@ func testConfigReplacePreservesAuto(t *testing.T) {
286
assert.Contains(t, originalConfig, `"foo.": "auto"`)
287
288
// Modify the config string to add a new field but preserve auto values
289
- var configMap map[string]interface{}
289
+ var configMap map[string]any
290
err := json.Unmarshal([]byte(originalConfig), &configMap)
291
require.NoError(t, err)
292
test/cli/autoconf/extensibility_test.go
+32
-34
@@ -4,6 +4,7 @@ import (
4
"encoding/json"
5
"net/http"
6
"net/http/httptest"
7
+ "slices"
8
"strings"
9
"testing"
10
"time"
@@ -35,56 +36,56 @@ func TestAutoConfExtensibility_NewSystem(t *testing.T) {
36
var mockServer *httptest.Server
37
mockServer = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
38
// Create autoconf.json with NewSystem
38
- autoconfData := map[string]interface{}{
39
+ autoconfData := map[string]any{
40
"AutoConfVersion": 2025072901,
41
"AutoConfSchema": 1,
42
"AutoConfTTL": 86400,
42
- "SystemRegistry": map[string]interface{}{
43
- "AminoDHT": map[string]interface{}{
43
+ "SystemRegistry": map[string]any{
44
+ "AminoDHT": map[string]any{
45
"URL": "https://github.com/ipfs/specs/pull/497",
46
"Description": "Public DHT swarm",
46
- "NativeConfig": map[string]interface{}{
47
+ "NativeConfig": map[string]any{
48
"Bootstrap": []string{
49
"/dnsaddr/bootstrap.libp2p.io/p2p/QmNnooDu7bfjPFoTZYxMNLWUQJyrVwtbZg5gBMjTezGAJN",
50
},
51
},
51
- "DelegatedConfig": map[string]interface{}{
52
+ "DelegatedConfig": map[string]any{
53
"Read": []string{"/routing/v1/providers", "/routing/v1/peers", "/routing/v1/ipns"},
54
"Write": []string{"/routing/v1/ipns"},
55
},
56
},
56
- "IPNI": map[string]interface{}{
57
+ "IPNI": map[string]any{
58
"URL": "https://ipni.example.com",
59
"Description": "Network Indexer",
59
- "DelegatedConfig": map[string]interface{}{
60
+ "DelegatedConfig": map[string]any{
61
"Read": []string{"/routing/v1/providers"},
62
"Write": []string{},
63
},
64
},
64
- "NewSystem": map[string]interface{}{
65
+ "NewSystem": map[string]any{
66
"URL": "https://example.com/newsystem",
67
"Description": "Test system for extensibility verification",
67
- "NativeConfig": map[string]interface{}{
68
+ "NativeConfig": map[string]any{
69
"Bootstrap": []string{
70
"/ip4/127.0.0.1/tcp/9999/p2p/12D3KooWPeQ4r3v6CmVmKXoFGtqEqcr3L8P6La9yH5oEWKtoLVVa",
71
},
72
},
72
- "DelegatedConfig": map[string]interface{}{
73
+ "DelegatedConfig": map[string]any{
74
"Read": []string{"/routing/v1/providers"},
75
"Write": []string{},
76
},
77
},
78
},
78
- "DNSResolvers": map[string]interface{}{
79
+ "DNSResolvers": map[string]any{
80
"eth.": []string{"https://dns.eth.limo/dns-query"},
81
},
81
- "DelegatedEndpoints": map[string]interface{}{
82
- "https://ipni.example.com": map[string]interface{}{
82
+ "DelegatedEndpoints": map[string]any{
83
+ "https://ipni.example.com": map[string]any{
84
"Systems": []string{"IPNI"},
85
"Read": []string{"/routing/v1/providers"},
86
"Write": []string{},
87
},
87
- mockServer.URL + "/newsystem": map[string]interface{}{
88
+ mockServer.URL + "/newsystem": map[string]any{
89
"Systems": []string{"NewSystem"},
90
"Read": []string{"/routing/v1/providers"},
91
"Write": []string{},
@@ -101,7 +102,7 @@ func TestAutoConfExtensibility_NewSystem(t *testing.T) {
102
// NewSystem mock server URL will be dynamically assigned
103
newSystemServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
104
// Simple mock server for NewSystem endpoint
104
- response := map[string]interface{}{"Providers": []interface{}{}}
105
+ response := map[string]any{"Providers": []any{}}
106
w.Header().Set("Content-Type", "application/json")
107
_ = json.NewEncoder(w).Encode(response)
108
}))
@@ -110,56 +111,56 @@ func TestAutoConfExtensibility_NewSystem(t *testing.T) {
111
// Update the autoconf to point to the correct NewSystem endpoint
112
mockServer.Close()
113
mockServer = httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
113
- autoconfData := map[string]interface{}{
114
+ autoconfData := map[string]any{
115
"AutoConfVersion": 2025072901,
116
"AutoConfSchema": 1,
117
"AutoConfTTL": 86400,
117
- "SystemRegistry": map[string]interface{}{
118
- "AminoDHT": map[string]interface{}{
118
+ "SystemRegistry": map[string]any{
119
+ "AminoDHT": map[string]any{
120
"URL": "https://github.com/ipfs/specs/pull/497",
121
"Description": "Public DHT swarm",
121
- "NativeConfig": map[string]interface{}{
122
+ "NativeConfig": map[string]any{
123
"Bootstrap": []string{
124
"/dnsaddr/bootstrap.libp2p.io/p2p/QmNnooDu7bfjPFoTZYxMNLWUQJyrVwtbZg5gBMjTezGAJN",
125
},
126
},
126
- "DelegatedConfig": map[string]interface{}{
127
+ "DelegatedConfig": map[string]any{
128
"Read": []string{"/routing/v1/providers", "/routing/v1/peers", "/routing/v1/ipns"},
129
"Write": []string{"/routing/v1/ipns"},
130
},
131
},
131
- "IPNI": map[string]interface{}{
132
+ "IPNI": map[string]any{
133
"URL": "https://ipni.example.com",
134
"Description": "Network Indexer",
134
- "DelegatedConfig": map[string]interface{}{
135
+ "DelegatedConfig": map[string]any{
136
"Read": []string{"/routing/v1/providers"},
137
"Write": []string{},
138
},
139
},
139
- "NewSystem": map[string]interface{}{
140
+ "NewSystem": map[string]any{
141
"URL": "https://example.com/newsystem",
142
"Description": "Test system for extensibility verification",
142
- "NativeConfig": map[string]interface{}{
143
+ "NativeConfig": map[string]any{
144
"Bootstrap": []string{
145
"/ip4/127.0.0.1/tcp/9999/p2p/12D3KooWPeQ4r3v6CmVmKXoFGtqEqcr3L8P6La9yH5oEWKtoLVVa",
146
},
147
},
147
- "DelegatedConfig": map[string]interface{}{
148
+ "DelegatedConfig": map[string]any{
149
"Read": []string{"/routing/v1/providers"},
150
"Write": []string{},
151
},
152
},
153
},
153
- "DNSResolvers": map[string]interface{}{
154
+ "DNSResolvers": map[string]any{
155
"eth.": []string{"https://dns.eth.limo/dns-query"},
156
},
156
- "DelegatedEndpoints": map[string]interface{}{
157
- "https://ipni.example.com": map[string]interface{}{
157
+ "DelegatedEndpoints": map[string]any{
158
+ "https://ipni.example.com": map[string]any{
159
"Systems": []string{"IPNI"},
160
"Read": []string{"/routing/v1/providers"},
161
"Write": []string{},
162
},
162
- newSystemServer.URL: map[string]interface{}{
163
+ newSystemServer.URL: map[string]any{
164
"Systems": []string{"NewSystem"},
165
"Read": []string{"/routing/v1/providers"},
166
"Write": []string{},
@@ -227,11 +228,8 @@ func TestAutoConfExtensibility_NewSystem(t *testing.T) {
228
// Should contain NewSystem endpoint (not native) - now with routing path
229
foundNewSystem := false
230
expectedNewSystemURL := newSystemServer.URL + "/routing/v1/providers" // Full URL with path, as returned by DelegatedRoutersWithAutoConf
230
- for _, url := range routerURLs {
231
- if url == expectedNewSystemURL {
232
- foundNewSystem = true
233
- break
234
- }
231
+ if slices.Contains(routerURLs, expectedNewSystemURL) {
232
+ foundNewSystem = true
233
}
234
require.True(t, foundNewSystem, "Should contain NewSystem endpoint (%s) for delegated routing, got: %v", expectedNewSystemURL, routerURLs)
235
test/cli/autoconf/fuzz_test.go
+47
-47
@@ -70,7 +70,7 @@ func TestAutoConfFuzz(t *testing.T) {
70
func testFuzzAutoConfVersion(t *testing.T) {
71
testCases := []struct {
72
name string
73
- version interface{}
73
+ version any
74
expectError bool
75
}{
76
{"valid version", 2025071801, false},
@@ -84,22 +84,22 @@ func testFuzzAutoConfVersion(t *testing.T) {
84
85
for _, tc := range testCases {
86
t.Run(tc.name, func(t *testing.T) {
87
- config := map[string]interface{}{
87
+ config := map[string]any{
88
"AutoConfVersion": tc.version,
89
"AutoConfSchema": 1,
90
"AutoConfTTL": 86400,
91
- "SystemRegistry": map[string]interface{}{
92
- "AminoDHT": map[string]interface{}{
91
+ "SystemRegistry": map[string]any{
92
+ "AminoDHT": map[string]any{
93
"Description": "Test AminoDHT system",
94
- "NativeConfig": map[string]interface{}{
94
+ "NativeConfig": map[string]any{
95
"Bootstrap": []string{
96
"/dnsaddr/bootstrap.libp2p.io/p2p/QmNnooDu7bfjPFoTZYxMNLWUQJyrVwtbZg5gBMjTezGAJN",
97
},
98
},
99
},
100
},
101
- "DNSResolvers": map[string]interface{}{},
102
- "DelegatedEndpoints": map[string]interface{}{},
101
+ "DNSResolvers": map[string]any{},
102
+ "DelegatedEndpoints": map[string]any{},
103
}
104
105
jsonData, err := json.Marshal(config)
@@ -120,7 +120,7 @@ func testFuzzAutoConfVersion(t *testing.T) {
120
func testFuzzBootstrapArrays(t *testing.T) {
121
type testCase struct {
122
name string
123
- bootstrap interface{}
123
+ bootstrap any
124
expectError bool
125
validate func(*testing.T, *autoconf.Response)
126
}
@@ -177,7 +177,7 @@ func testFuzzBootstrapArrays(t *testing.T) {
177
},
178
{
179
name: "mixed types in array",
180
- bootstrap: []interface{}{"/dnsaddr/test", 123, nil},
180
+ bootstrap: []any{"/dnsaddr/test", 123, nil},
181
expectError: true,
182
},
183
{
@@ -199,20 +199,20 @@ func testFuzzBootstrapArrays(t *testing.T) {
199
200
for _, tc := range testCases {
201
t.Run(tc.name, func(t *testing.T) {
202
- config := map[string]interface{}{
202
+ config := map[string]any{
203
"AutoConfVersion": 2025072301,
204
"AutoConfSchema": 1,
205
"AutoConfTTL": 86400,
206
- "SystemRegistry": map[string]interface{}{
207
- "AminoDHT": map[string]interface{}{
206
+ "SystemRegistry": map[string]any{
207
+ "AminoDHT": map[string]any{
208
"Description": "Test AminoDHT system",
209
- "NativeConfig": map[string]interface{}{
209
+ "NativeConfig": map[string]any{
210
"Bootstrap": tc.bootstrap,
211
},
212
},
213
},
214
- "DNSResolvers": map[string]interface{}{},
215
- "DelegatedEndpoints": map[string]interface{}{},
214
+ "DNSResolvers": map[string]any{},
215
+ "DelegatedEndpoints": map[string]any{},
216
}
217
218
jsonData, err := json.Marshal(config)
@@ -247,7 +247,7 @@ func testFuzzBootstrapArrays(t *testing.T) {
247
func testFuzzDNSResolvers(t *testing.T) {
248
type testCase struct {
249
name string
250
- resolvers interface{}
250
+ resolvers any
251
expectError bool
252
validate func(*testing.T, *autoconf.Response)
253
}
@@ -314,27 +314,27 @@ func testFuzzDNSResolvers(t *testing.T) {
314
},
315
{
316
name: "nested invalid structure",
317
- resolvers: map[string]interface{}{".": map[string]string{"invalid": "structure"}},
317
+ resolvers: map[string]any{".": map[string]string{"invalid": "structure"}},
318
expectError: true,
319
},
320
}
321
322
for _, tc := range testCases {
323
t.Run(tc.name, func(t *testing.T) {
324
- config := map[string]interface{}{
324
+ config := map[string]any{
325
"AutoConfVersion": 2025072301,
326
"AutoConfSchema": 1,
327
"AutoConfTTL": 86400,
328
- "SystemRegistry": map[string]interface{}{
329
- "AminoDHT": map[string]interface{}{
328
+ "SystemRegistry": map[string]any{
329
+ "AminoDHT": map[string]any{
330
"Description": "Test AminoDHT system",
331
- "NativeConfig": map[string]interface{}{
331
+ "NativeConfig": map[string]any{
332
"Bootstrap": []string{"/dnsaddr/test"},
333
},
334
},
335
},
336
"DNSResolvers": tc.resolvers,
337
- "DelegatedEndpoints": map[string]interface{}{},
337
+ "DelegatedEndpoints": map[string]any{},
338
}
339
340
jsonData, err := json.Marshal(config)
@@ -366,7 +366,7 @@ func testFuzzDelegatedRouters(t *testing.T) {
366
// Test various malformed delegated router configurations
367
type testCase struct {
368
name string
369
- routers interface{}
369
+ routers any
370
expectError bool
371
validate func(*testing.T, *autoconf.Response)
372
}
@@ -374,8 +374,8 @@ func testFuzzDelegatedRouters(t *testing.T) {
374
testCases := []testCase{
375
{
376
name: "valid endpoints",
377
- routers: map[string]interface{}{
378
- "https://ipni.example.com": map[string]interface{}{
377
+ routers: map[string]any{
378
+ "https://ipni.example.com": map[string]any{
379
"Systems": []string{"IPNI"},
380
"Read": []string{"/routing/v1/providers"},
381
"Write": []string{},
@@ -392,7 +392,7 @@ func testFuzzDelegatedRouters(t *testing.T) {
392
},
393
{
394
name: "empty routers",
395
- routers: map[string]interface{}{},
395
+ routers: map[string]any{},
396
validate: func(t *testing.T, resp *autoconf.Response) {
397
assert.Empty(t, resp.Config.DelegatedEndpoints, "Empty routers should result in empty endpoints")
398
},
@@ -411,8 +411,8 @@ func testFuzzDelegatedRouters(t *testing.T) {
411
},
412
{
413
name: "invalid endpoint URLs",
414
- routers: map[string]interface{}{
415
- "not-a-url": map[string]interface{}{
414
+ routers: map[string]any{
415
+ "not-a-url": map[string]any{
416
"Systems": []string{"IPNI"},
417
"Read": []string{"/routing/v1/providers"},
418
"Write": []string{},
@@ -424,19 +424,19 @@ func testFuzzDelegatedRouters(t *testing.T) {
424
425
for _, tc := range testCases {
426
t.Run(tc.name, func(t *testing.T) {
427
- config := map[string]interface{}{
427
+ config := map[string]any{
428
"AutoConfVersion": 2025072301,
429
"AutoConfSchema": 1,
430
"AutoConfTTL": 86400,
431
- "SystemRegistry": map[string]interface{}{
432
- "AminoDHT": map[string]interface{}{
431
+ "SystemRegistry": map[string]any{
432
+ "AminoDHT": map[string]any{
433
"Description": "Test AminoDHT system",
434
- "NativeConfig": map[string]interface{}{
434
+ "NativeConfig": map[string]any{
435
"Bootstrap": []string{"/dnsaddr/test"},
436
},
437
},
438
},
439
- "DNSResolvers": map[string]interface{}{},
439
+ "DNSResolvers": map[string]any{},
440
"DelegatedEndpoints": tc.routers,
441
}
442
@@ -510,26 +510,26 @@ func testFuzzDelegatedPublishers(t *testing.T) {
510
511
for _, tc := range testCases {
512
t.Run(tc.name, func(t *testing.T) {
513
- autoConfData := map[string]interface{}{
513
+ autoConfData := map[string]any{
514
"AutoConfVersion": 2025072301,
515
"AutoConfSchema": 1,
516
"AutoConfTTL": 86400,
517
- "SystemRegistry": map[string]interface{}{
518
- "TestSystem": map[string]interface{}{
517
+ "SystemRegistry": map[string]any{
518
+ "TestSystem": map[string]any{
519
"Description": "Test system for fuzz testing",
520
- "DelegatedConfig": map[string]interface{}{
520
+ "DelegatedConfig": map[string]any{
521
"Read": []string{"/routing/v1/ipns"},
522
"Write": []string{"/routing/v1/ipns"},
523
},
524
},
525
},
526
- "DNSResolvers": map[string]interface{}{},
527
- "DelegatedEndpoints": map[string]interface{}{},
526
+ "DNSResolvers": map[string]any{},
527
+ "DelegatedEndpoints": map[string]any{},
528
}
529
530
// Add test URLs as delegated endpoints
531
for _, url := range tc.urls {
532
- autoConfData["DelegatedEndpoints"].(map[string]interface{})[url] = map[string]interface{}{
532
+ autoConfData["DelegatedEndpoints"].(map[string]any)[url] = map[string]any{
533
"Systems": []string{"TestSystem"},
534
"Read": []string{"/routing/v1/ipns"},
535
"Write": []string{"/routing/v1/ipns"},
@@ -598,27 +598,27 @@ func testFuzzLargePayloads(t *testing.T) {
598
}
599
600
largeDNSResolvers := make(map[string][]string)
601
- for i := 0; i < 1000; i++ {
601
+ for i := range 1000 {
602
domain := fmt.Sprintf("domain%d.example.com", i)
603
largeDNSResolvers[domain] = []string{
604
fmt.Sprintf("https://resolver%d.example.com/dns-query", i),
605
}
606
}
607
608
- config := map[string]interface{}{
608
+ config := map[string]any{
609
"AutoConfVersion": 2025072301,
610
"AutoConfSchema": 1,
611
"AutoConfTTL": 86400,
612
- "SystemRegistry": map[string]interface{}{
613
- "AminoDHT": map[string]interface{}{
612
+ "SystemRegistry": map[string]any{
613
+ "AminoDHT": map[string]any{
614
"Description": "Test AminoDHT system",
615
- "NativeConfig": map[string]interface{}{
615
+ "NativeConfig": map[string]any{
616
"Bootstrap": largeBootstrap,
617
},
618
},
619
},
620
"DNSResolvers": largeDNSResolvers,
621
- "DelegatedEndpoints": map[string]interface{}{},
621
+ "DelegatedEndpoints": map[string]any{},
622
}
623
624
jsonData, err := json.Marshal(config)
@@ -644,7 +644,7 @@ func testFuzzLargePayloads(t *testing.T) {
644
// Helper function to generate many DNS resolvers for testing
645
func generateManyResolvers(count int) map[string][]string {
646
resolvers := make(map[string][]string)
647
- for i := 0; i < count; i++ {
647
+ for i := range count {
648
domain := fmt.Sprintf("domain%d.example.com", i)
649
resolvers[domain] = []string{
650
fmt.Sprintf("https://resolver%d.example.com/dns-query", i),
test/cli/autoconf/ipns_test.go
+2
-3
@@ -4,6 +4,7 @@ import (
4
"encoding/json"
5
"fmt"
6
"io"
7
+ "maps"
8
"net/http"
9
"net/http/httptest"
10
"strings"
@@ -330,9 +331,7 @@ func (m *mockIPNSPublisher) getPublishedKeys() map[string]string {
331
m.mu.Lock()
332
defer m.mu.Unlock()
333
result := make(map[string]string)
333
- for k, v := range m.publishedKeys {
334
- result[k] = v
335
- }
334
+ maps.Copy(result, m.publishedKeys)
335
return result
336
}
337
test/cli/autoconf/routing_test.go
+5
-5
@@ -34,7 +34,7 @@ type mockRoutingServer struct {
34
server *httptest.Server
35
mu sync.Mutex
36
requests []string
37
- providerFunc func(cid string) []map[string]interface{}
37
+ providerFunc func(cid string) []map[string]any
38
}
39
40
func newMockRoutingServer(t *testing.T) *mockRoutingServer {
@@ -44,8 +44,8 @@ func newMockRoutingServer(t *testing.T) *mockRoutingServer {
44
}
45
46
// Default provider function returns mock provider records
47
- m.providerFunc = func(cid string) []map[string]interface{} {
48
- return []map[string]interface{}{
47
+ m.providerFunc = func(cid string) []map[string]any {
48
+ return []map[string]any{
49
{
50
"Protocol": "transport-bitswap",
51
"Schema": "bitswap",
@@ -175,8 +175,8 @@ func testRoutingErrorHandling(t *testing.T) {
175
defer routingServer.close()
176
177
// Configure to return no providers (empty response)
178
- routingServer.providerFunc = func(cid string) []map[string]interface{} {
179
- return []map[string]interface{}{}
178
+ routingServer.providerFunc = func(cid string) []map[string]any {
179
+ return []map[string]any{}
180
}
181
182
// Create autoconf data
test/cli/basic_commands_test.go
+2
-3
@@ -65,8 +65,8 @@ func TestIPFSVersionDeps(t *testing.T) {
65
assert.True(t, strings.HasPrefix(lines[0], "github.com/ipfs/kubo@v"))
66
67
for _, depLine := range lines[1:] {
68
- split := strings.Split(depLine, " => ")
69
- for _, moduleVersion := range split {
68
+ split := strings.SplitSeq(depLine, " => ")
69
+ for moduleVersion := range split {
70
splitModVers := strings.Split(moduleVersion, "@")
71
modPath := splitModVers[0]
72
modVers := splitModVers[1]
@@ -92,7 +92,6 @@ func TestAllSubcommandsAcceptHelp(t *testing.T) {
92
t.Parallel()
93
node := harness.NewT(t).NewNode()
94
for _, cmd := range node.IPFSCommands() {
95
- cmd := cmd
95
t.Run(fmt.Sprintf("command %q accepts help", cmd), func(t *testing.T) {
96
t.Parallel()
97
splitCmd := strings.Split(cmd, " ")[1:]
test/cli/bitswap_config_test.go
+2
-2
@@ -141,10 +141,10 @@ func TestBitswapConfig(t *testing.T) {
141
142
// read libp2p identify from remote peer, and print protocols
143
res := requester.IPFS("id", "-f", "<protocols>", provider.PeerID().String())
144
- protocols := strings.Split(strings.TrimSpace(res.Stdout.String()), "\n")
144
+ protocols := strings.SplitSeq(strings.TrimSpace(res.Stdout.String()), "\n")
145
146
// No bitswap protocols should be present
147
- for _, proto := range protocols {
147
+ for proto := range protocols {
148
assert.NotContains(t, proto, bsnet.ProtocolBitswap, "bitswap protocol %s should not be advertised when server is disabled", proto)
149
assert.NotContains(t, proto, bsnet.ProtocolBitswapNoVers, "bitswap protocol %s should not be advertised when server is disabled", proto)
150
assert.NotContains(t, proto, bsnet.ProtocolBitswapOneOne, "bitswap protocol %s should not be advertised when server is disabled", proto)
test/cli/block_size_test.go
+1
-1
@@ -60,7 +60,7 @@ func allBlockCIDs(t *testing.T, node *harness.Node, root string) []string {
60
t.Helper()
61
cids := []string{root}
62
res := node.IPFS("refs", "-r", "--unique", root)
63
- for _, line := range strings.Split(strings.TrimSpace(res.Stdout.String()), "\n") {
63
+ for line := range strings.SplitSeq(strings.TrimSpace(res.Stdout.String()), "\n") {
64
if line != "" {
65
cids = append(cids, line)
66
}
test/cli/config_secrets_test.go
+2
-2
@@ -76,7 +76,7 @@ func TestConfigSecrets(t *testing.T) {
76
var origPrivKey string
77
assert.Contains(t, originalConfig, "PrivKey")
78
// Simple extraction - find the PrivKey line
79
- for _, line := range strings.Split(originalConfig, "\n") {
79
+ for line := range strings.SplitSeq(originalConfig, "\n") {
80
if strings.Contains(line, "\"PrivKey\":") {
81
origPrivKey = line
82
break
@@ -98,7 +98,7 @@ func TestConfigSecrets(t *testing.T) {
98
99
// Verify the PrivKey line is the same
100
var newPrivKey string
101
- for _, line := range strings.Split(newConfig, "\n") {
101
+ for line := range strings.SplitSeq(newConfig, "\n") {
102
if strings.Contains(line, "\"PrivKey\":") {
103
newPrivKey = line
104
break
test/cli/content_blocking_test.go
-1
@@ -202,7 +202,6 @@ func TestContentBlocking(t *testing.T) {
202
203
// Confirm that denylist is active for every command in 'cliCmds' x 'testCases'
204
for _, cmd := range cliCmds {
205
- cmd := cmd
205
cliTestName := fmt.Sprintf("CLI '%s' denies %s", strings.Join(cmd, " "), testCase.name)
206
t.Run(cliTestName, func(t *testing.T) {
207
t.Parallel()
test/cli/dht_autoclient_test.go
+1
-1
@@ -33,7 +33,7 @@ func TestDHTAutoclient(t *testing.T) {
33
randomBytes := random.Bytes(1000)
34
hash := nodes[0].IPFSAdd(bytes.NewReader(randomBytes))
35
36
- for i := 0; i < 10; i++ {
36
+ for i := range 10 {
37
res := nodes[i].IPFS("cat", hash)
38
assert.Equal(t, randomBytes, []byte(res.Stdout.Trimmed()))
39
}
test/cli/files_test.go
+3
-3
@@ -200,7 +200,7 @@ func TestFilesNoFlushLimit(t *testing.T) {
200
defer node.StopDaemon()
201
202
// Perform 256 operations with --flush=false (should succeed)
203
- for i := 0; i < 256; i++ {
203
+ for i := range 256 {
204
res := node.IPFS("files", "mkdir", "--flush=false", fmt.Sprintf("/dir%d", i))
205
assert.NoError(t, res.Err, "operation %d should succeed", i+1)
206
}
@@ -229,7 +229,7 @@ func TestFilesNoFlushLimit(t *testing.T) {
229
defer node.StopDaemon()
230
231
// Perform 5 operations (should succeed)
232
- for i := 0; i < 5; i++ {
232
+ for i := range 5 {
233
res := node.IPFS("files", "mkdir", "--flush=false", fmt.Sprintf("/dir%d", i))
234
assert.NoError(t, res.Err, "operation %d should succeed", i+1)
235
}
@@ -321,7 +321,7 @@ func TestFilesNoFlushLimit(t *testing.T) {
321
defer node.StopDaemon()
322
323
// Should be able to do many operations without error
324
- for i := 0; i < 300; i++ {
324
+ for i := range 300 {
325
res := node.IPFS("files", "mkdir", "--flush=false", fmt.Sprintf("/dir%d", i))
326
assert.NoError(t, res.Err, "operation %d should succeed with limit disabled", i+1)
327
}
test/cli/harness/harness.go
+1
-1
@@ -91,7 +91,7 @@ func (h *Harness) NewNode() *Node {
91
92
func (h *Harness) NewNodes(count int) Nodes {
93
var newNodes []*Node
94
- for i := 0; i < count; i++ {
94
+ for range count {
95
newNodes = append(newNodes, h.NewNode())
96
}
97
return newNodes
test/cli/harness/ipfs.go
+3
-3
@@ -26,7 +26,7 @@ func (n *Node) IPFSCommands() []string {
26
return cmds
27
}
28
29
-func (n *Node) SetIPFSConfig(key string, val interface{}, flags ...string) {
29
+func (n *Node) SetIPFSConfig(key string, val any, flags ...string) {
30
valBytes, err := json.Marshal(val)
31
if err != nil {
32
log.Panicf("marshling config for key '%s': %s", key, err)
@@ -57,13 +57,13 @@ func (n *Node) SetIPFSConfig(key string, val interface{}, flags ...string) {
57
}
58
}
59
60
-func (n *Node) GetIPFSConfig(key string, val interface{}) {
60
+func (n *Node) GetIPFSConfig(key string, val any) {
61
res := n.IPFS("config", key)
62
valStr := strings.TrimSpace(res.Stdout.String())
63
// only when the result is a string is the result not well-formed JSON,
64
// so check the value type and add quotes if it's expected to be a string
65
reflectVal := reflect.ValueOf(val)
66
- if reflectVal.Kind() == reflect.Ptr && reflectVal.Elem().Kind() == reflect.String {
66
+ if reflectVal.Kind() == reflect.Pointer && reflectVal.Elem().Kind() == reflect.String {
67
valStr = fmt.Sprintf(`"%s"`, valStr)
68
}
69
err := json.Unmarshal([]byte(valStr), val)
test/cli/harness/node.go
+2
-2
@@ -475,7 +475,7 @@ func (n *Node) PeerID() peer.ID {
475
476
func (n *Node) WaitOnAPI(authorization string) *Node {
477
log.Debugf("waiting on API for node %d", n.ID)
478
- for i := 0; i < 50; i++ {
478
+ for range 50 {
479
if n.checkAPI(authorization) {
480
log.Debugf("daemon API found, daemon stdout: %s", n.Daemon.Stdout.String())
481
return n
@@ -647,7 +647,7 @@ func (n *Node) Peers() []multiaddr.Multiaddr {
647
// Wait for daemon to be ready if it's supposed to be running
648
if n.Daemon != nil && n.Daemon.Cmd != nil && n.Daemon.Cmd.Process != nil {
649
// Give daemon a short time to become ready
650
- for i := 0; i < 10; i++ {
650
+ for range 10 {
651
if n.IsAlive() {
652
break
653
}
test/cli/harness/peering.go
+2
-2
@@ -24,7 +24,7 @@ func NewRandPort() int {
24
portMutex.Lock()
25
defer portMutex.Unlock()
26
27
- for i := 0; i < 100; i++ {
27
+ for range 100 {
28
l, err := net.Listen("tcp", "localhost:0")
29
if err != nil {
30
continue
@@ -39,7 +39,7 @@ func NewRandPort() int {
39
}
40
41
// Fallback to random port if we can't get a unique one from the OS
42
- for i := 0; i < 1000; i++ {
42
+ for range 1000 {
43
port := 30000 + rand.Intn(10000)
44
if _, used := allocatedPorts[port]; !used {
45
allocatedPorts[port] = struct{}{}
test/cli/ipfswatch_test.go
+4
-4
@@ -107,10 +107,10 @@ func TestIPFSWatch(t *testing.T) {
107
108
// Configure pebbleds as the datastore
109
node.UpdateConfig(func(cfg *config.Config) {
110
- cfg.Datastore.Spec = map[string]interface{}{
110
+ cfg.Datastore.Spec = map[string]any{
111
"type": "mount",
112
- "mounts": []interface{}{
113
- map[string]interface{}{
112
+ "mounts": []any{
113
+ map[string]any{
114
"mountpoint": "/blocks",
115
"path": "blocks",
116
"prefix": "flatfs.datastore",
@@ -118,7 +118,7 @@ func TestIPFSWatch(t *testing.T) {
118
"sync": true,
119
"type": "flatfs",
120
},
121
- map[string]interface{}{
121
+ map[string]any{
122
"mountpoint": "/",
123
"path": "datastore",
124
"prefix": "pebble.datastore",
test/cli/log_level_test.go
+13
-13
@@ -423,12 +423,12 @@ func TestLogLevel(t *testing.T) {
423
defer resp.Body.Close()
424
425
// Parse JSON response
426
- var result map[string]interface{}
426
+ var result map[string]any
427
err = json.NewDecoder(resp.Body).Decode(&result)
428
require.NoError(t, err)
429
430
// Check that we have the Levels field
431
- levels, ok := result["Levels"].(map[string]interface{})
431
+ levels, ok := result["Levels"].(map[string]any)
432
require.True(t, ok, "Response should have 'Levels' field")
433
434
// Should have exactly one entry for the default level
@@ -498,12 +498,12 @@ func TestLogLevel(t *testing.T) {
498
defer resp.Body.Close()
499
500
// Parse JSON response
501
- var result map[string]interface{}
501
+ var result map[string]any
502
err = json.NewDecoder(resp.Body).Decode(&result)
503
require.NoError(t, err)
504
505
// Check that we have the Levels field
506
- levels, ok := result["Levels"].(map[string]interface{})
506
+ levels, ok := result["Levels"].(map[string]any)
507
require.True(t, ok, "Response should have 'Levels' field")
508
509
// Should have exactly one entry
@@ -526,7 +526,7 @@ func TestLogLevel(t *testing.T) {
526
defer resp.Body.Close()
527
528
// Parse JSON response
529
- var result map[string]interface{}
529
+ var result map[string]any
530
err = json.NewDecoder(resp.Body).Decode(&result)
531
require.NoError(t, err)
532
@@ -549,7 +549,7 @@ func TestLogLevel(t *testing.T) {
549
defer resp.Body.Close()
550
551
// Parse JSON response
552
- var result map[string]interface{}
552
+ var result map[string]any
553
err = json.NewDecoder(resp.Body).Decode(&result)
554
require.NoError(t, err)
555
@@ -577,7 +577,7 @@ func TestLogLevel(t *testing.T) {
577
defer resp.Body.Close()
578
579
// Parse JSON response
580
- var result map[string]interface{}
580
+ var result map[string]any
581
err = json.NewDecoder(resp.Body).Decode(&result)
582
require.NoError(t, err)
583
@@ -594,11 +594,11 @@ func TestLogLevel(t *testing.T) {
594
require.NoError(t, err)
595
defer resp.Body.Close()
596
597
- var getResult map[string]interface{}
597
+ var getResult map[string]any
598
err = json.NewDecoder(resp.Body).Decode(&getResult)
599
require.NoError(t, err)
600
601
- levels, _ := getResult["Levels"].(map[string]interface{})
601
+ levels, _ := getResult["Levels"].(map[string]any)
602
coreLevel, _ := levels["core"].(string)
603
assert.Equal(t, "error", coreLevel, "Core level should be back to 'error' (default)")
604
})
@@ -790,18 +790,18 @@ func parseCLIOutput(t *testing.T, output string) map[string]string {
790
return actualSubsystems
791
}
792
793
-func parseHTTPResponse(t *testing.T, resp *http.Response) map[string]interface{} {
793
+func parseHTTPResponse(t *testing.T, resp *http.Response) map[string]any {
794
t.Helper()
795
- var result map[string]interface{}
795
+ var result map[string]any
796
err := json.NewDecoder(resp.Body).Decode(&result)
797
require.NoError(t, err)
798
- levels, ok := result["Levels"].(map[string]interface{})
798
+ levels, ok := result["Levels"].(map[string]any)
799
require.True(t, ok, "Response should have 'Levels' field")
800
assert.Greater(t, len(levels), 10, "Should have many subsystems")
801
return levels
802
}
803
804
-func validateAllSubsystemsPresent(t *testing.T, expectedSubsystems []string, actualLevels map[string]interface{}, context string) {
804
+func validateAllSubsystemsPresent(t *testing.T, expectedSubsystems []string, actualLevels map[string]any, context string) {
805
t.Helper()
806
for _, expectedSub := range expectedSubsystems {
807
expectedSub = strings.TrimSpace(expectedSub)
test/cli/migrations/migration_16_to_latest_test.go
+25
-25
@@ -127,16 +127,16 @@ func testDaemonMigrationWithoutAuto(t *testing.T) {
127
configPath := filepath.Join(node.Dir, "config")
128
129
// Read existing config from static fixture
130
- var v16Config map[string]interface{}
130
+ var v16Config map[string]any
131
configData, err := os.ReadFile(configPath)
132
require.NoError(t, err)
133
require.NoError(t, json.Unmarshal(configData, &v16Config))
134
135
// Add custom DNS resolver that should be preserved
136
if v16Config["DNS"] == nil {
137
- v16Config["DNS"] = map[string]interface{}{}
137
+ v16Config["DNS"] = map[string]any{}
138
}
139
- dnsSection := v16Config["DNS"].(map[string]interface{})
139
+ dnsSection := v16Config["DNS"].(map[string]any)
140
dnsSection["Resolvers"] = map[string]string{
141
".": "https://custom-dns.example.com/dns-query",
142
"eth.": "https://dns.eth.limo/dns-query", // This is a default that will be replaced with "auto"
@@ -177,17 +177,17 @@ func testDaemonMigrationWithoutAuto(t *testing.T) {
177
178
type ConfigField struct {
179
Path string
180
- Expected interface{}
180
+ Expected any
181
Message string
182
}
183
184
type MigrationTestHelper struct {
185
t *testing.T
186
- config map[string]interface{}
186
+ config map[string]any
187
}
188
189
func NewMigrationTestHelper(t *testing.T, configPath string) *MigrationTestHelper {
190
- var config map[string]interface{}
190
+ var config map[string]any
191
configData, err := os.ReadFile(configPath)
192
require.NoError(t, err)
193
require.NoError(t, json.Unmarshal(configData, &config))
@@ -201,32 +201,32 @@ func (h *MigrationTestHelper) RequireFieldExists(path string) *MigrationTestHelp
201
return h
202
}
203
204
-func (h *MigrationTestHelper) RequireFieldEquals(path string, expected interface{}) *MigrationTestHelper {
204
+func (h *MigrationTestHelper) RequireFieldEquals(path string, expected any) *MigrationTestHelper {
205
value := h.getNestedValue(path)
206
require.Equal(h.t, expected, value, "Field %s should equal %v", path, expected)
207
return h
208
}
209
210
-func (h *MigrationTestHelper) RequireArrayContains(path string, expected interface{}) *MigrationTestHelper {
210
+func (h *MigrationTestHelper) RequireArrayContains(path string, expected any) *MigrationTestHelper {
211
value := h.getNestedValue(path)
212
- require.IsType(h.t, []interface{}{}, value, "Field %s should be an array", path)
213
- array := value.([]interface{})
212
+ require.IsType(h.t, []any{}, value, "Field %s should be an array", path)
213
+ array := value.([]any)
214
require.Contains(h.t, array, expected, "Array %s should contain %v", path, expected)
215
return h
216
}
217
218
func (h *MigrationTestHelper) RequireArrayLength(path string, expectedLen int) *MigrationTestHelper {
219
value := h.getNestedValue(path)
220
- require.IsType(h.t, []interface{}{}, value, "Field %s should be an array", path)
221
- array := value.([]interface{})
220
+ require.IsType(h.t, []any{}, value, "Field %s should be an array", path)
221
+ array := value.([]any)
222
require.Len(h.t, array, expectedLen, "Array %s should have length %d", path, expectedLen)
223
return h
224
}
225
226
-func (h *MigrationTestHelper) RequireArrayDoesNotContain(path string, notExpected interface{}) *MigrationTestHelper {
226
+func (h *MigrationTestHelper) RequireArrayDoesNotContain(path string, notExpected any) *MigrationTestHelper {
227
value := h.getNestedValue(path)
228
- require.IsType(h.t, []interface{}{}, value, "Field %s should be an array", path)
229
- array := value.([]interface{})
228
+ require.IsType(h.t, []any{}, value, "Field %s should be an array", path)
229
+ array := value.([]any)
230
require.NotContains(h.t, array, notExpected, "Array %s should not contain %v", path, notExpected)
231
return h
232
}
@@ -277,32 +277,32 @@ func (h *MigrationTestHelper) RequireNoAutoValues() *MigrationTestHelper {
277
return h
278
}
279
280
-func (h *MigrationTestHelper) RequireMapDoesNotContainValue(path string, notExpected interface{}) *MigrationTestHelper {
280
+func (h *MigrationTestHelper) RequireMapDoesNotContainValue(path string, notExpected any) *MigrationTestHelper {
281
value := h.getNestedValue(path)
282
- require.IsType(h.t, map[string]interface{}{}, value, "Field %s should be a map", path)
283
- mapValue := value.(map[string]interface{})
282
+ require.IsType(h.t, map[string]any{}, value, "Field %s should be a map", path)
283
+ mapValue := value.(map[string]any)
284
for k, v := range mapValue {
285
require.NotEqual(h.t, notExpected, v, "Map %s[%s] should not equal %v", path, k, notExpected)
286
}
287
return h
288
}
289
290
-func (h *MigrationTestHelper) getNestedValue(path string) interface{} {
290
+func (h *MigrationTestHelper) getNestedValue(path string) any {
291
segments := h.parseKuboConfigPath(path)
292
- current := interface{}(h.config)
292
+ current := any(h.config)
293
294
for _, segment := range segments {
295
switch segment.Type {
296
case "field":
297
switch v := current.(type) {
298
- case map[string]interface{}:
298
+ case map[string]any:
299
current = v[segment.Key]
300
default:
301
return nil
302
}
303
case "mapKey":
304
switch v := current.(type) {
305
- case map[string]interface{}:
305
+ case map[string]any:
306
current = v[segment.Key]
307
default:
308
return nil
@@ -776,7 +776,7 @@ func runDaemonWithMultipleMigrationMonitoring(t *testing.T, node *harness.Node,
776
// =============================================================================
777
778
// Helper functions for test cleanup assertions
779
-func assertNoTempFiles(t *testing.T, dir string, msgAndArgs ...interface{}) {
779
+func assertNoTempFiles(t *testing.T, dir string, msgAndArgs ...any) {
780
t.Helper()
781
tmpFiles, err := filepath.Glob(filepath.Join(dir, ".tmp-*"))
782
require.NoError(t, err)
@@ -844,12 +844,12 @@ func testBackupFilesPersistAfterSuccessfulMigration(t *testing.T) {
844
// Verify backup files contain valid JSON
845
data16to17, err := os.ReadFile(backup16to17)
846
require.NoError(t, err)
847
- var config16to17 map[string]interface{}
847
+ var config16to17 map[string]any
848
require.NoError(t, json.Unmarshal(data16to17, &config16to17), "16-to-17 backup should be valid JSON")
849
850
data17to18, err := os.ReadFile(backup17to18)
851
require.NoError(t, err)
852
- var config17to18 map[string]interface{}
852
+ var config17to18 map[string]any
853
require.NoError(t, json.Unmarshal(data17to18, &config17to18), "17-to-18 backup should be valid JSON")
854
}
855
test/cli/migrations/migration_17_to_latest_test.go
+16
-16
@@ -243,11 +243,11 @@ func testRepoProviderReproviderMigration(t *testing.T) {
243
// setupV17RepoWithProviderConfig creates a v17 repo with Provider/Reprovider configuration
244
func setupV17RepoWithProviderConfig(t *testing.T) *harness.Node {
245
return setupV17RepoWithConfig(t,
246
- map[string]interface{}{
246
+ map[string]any{
247
"Enabled": true,
248
"WorkerCount": 8,
249
},
250
- map[string]interface{}{
250
+ map[string]any{
251
"Strategy": "roots",
252
"Interval": "24h",
253
})
@@ -256,17 +256,17 @@ func setupV17RepoWithProviderConfig(t *testing.T) *harness.Node {
256
// setupV17RepoWithFlatStrategy creates a v17 repo with "flat" strategy for testing conversion
257
func setupV17RepoWithFlatStrategy(t *testing.T) *harness.Node {
258
return setupV17RepoWithConfig(t,
259
- map[string]interface{}{
259
+ map[string]any{
260
"Enabled": false,
261
},
262
- map[string]interface{}{
262
+ map[string]any{
263
"Strategy": "flat", // This should be converted to "all"
264
"Interval": "12h",
265
})
266
}
267
268
// setupV17RepoWithConfig is a helper that creates a v17 repo with specified Provider/Reprovider config
269
-func setupV17RepoWithConfig(t *testing.T, providerConfig, reproviderConfig map[string]interface{}) *harness.Node {
269
+func setupV17RepoWithConfig(t *testing.T, providerConfig, reproviderConfig map[string]any) *harness.Node {
270
node := setupStaticV16Repo(t)
271
272
// First migrate to v17
@@ -275,7 +275,7 @@ func setupV17RepoWithConfig(t *testing.T, providerConfig, reproviderConfig map[s
275
276
// Update config with specified Provider and Reprovider settings
277
configPath := filepath.Join(node.Dir, "config")
278
- var config map[string]interface{}
278
+ var config map[string]any
279
configData, err := os.ReadFile(configPath)
280
require.NoError(t, err)
281
require.NoError(t, json.Unmarshal(configData, &config))
@@ -283,13 +283,13 @@ func setupV17RepoWithConfig(t *testing.T, providerConfig, reproviderConfig map[s
283
if providerConfig != nil {
284
config["Provider"] = providerConfig
285
} else {
286
- config["Provider"] = map[string]interface{}{}
286
+ config["Provider"] = map[string]any{}
287
}
288
289
if reproviderConfig != nil {
290
config["Reprovider"] = reproviderConfig
291
} else {
292
- config["Reprovider"] = map[string]interface{}{}
292
+ config["Reprovider"] = map[string]any{}
293
}
294
295
modifiedConfigData, err := json.MarshalIndent(config, "", " ")
@@ -302,25 +302,25 @@ func setupV17RepoWithConfig(t *testing.T, providerConfig, reproviderConfig map[s
302
// setupV17RepoWithEmptySections creates a v17 repo with empty Provider/Reprovider sections
303
func setupV17RepoWithEmptySections(t *testing.T) *harness.Node {
304
return setupV17RepoWithConfig(t,
305
- map[string]interface{}{},
306
- map[string]interface{}{})
305
+ map[string]any{},
306
+ map[string]any{})
307
}
308
309
// setupV17RepoWithProviderOnly creates a v17 repo with only Provider configuration
310
func setupV17RepoWithProviderOnly(t *testing.T) *harness.Node {
311
return setupV17RepoWithConfig(t,
312
- map[string]interface{}{
312
+ map[string]any{
313
"Enabled": false,
314
"WorkerCount": 32,
315
},
316
- map[string]interface{}{})
316
+ map[string]any{})
317
}
318
319
// setupV17RepoWithReproviderOnly creates a v17 repo with only Reprovider configuration
320
func setupV17RepoWithReproviderOnly(t *testing.T) *harness.Node {
321
return setupV17RepoWithConfig(t,
322
- map[string]interface{}{},
323
- map[string]interface{}{
322
+ map[string]any{},
323
+ map[string]any{
324
"Strategy": "pinned",
325
"Interval": "48h",
326
})
@@ -329,8 +329,8 @@ func setupV17RepoWithReproviderOnly(t *testing.T) *harness.Node {
329
// setupV17RepoWithInvalidStrategy creates a v17 repo with an invalid strategy value
330
func setupV17RepoWithInvalidStrategy(t *testing.T) *harness.Node {
331
return setupV17RepoWithConfig(t,
332
- map[string]interface{}{},
333
- map[string]interface{}{
332
+ map[string]any{},
333
+ map[string]any{
334
"Strategy": "invalid-strategy", // This is not a valid strategy
335
"Interval": "24h",
336
})
test/cli/migrations/migration_mixed_15_to_latest_test.go
+8
-8
@@ -74,7 +74,7 @@ func testDaemonMigration15ToLatest(t *testing.T) {
74
require.Equal(t, "15", strings.TrimSpace(string(versionData)), "Should start at version 15")
75
76
// Read original config to verify preservation of key fields
77
- var originalConfig map[string]interface{}
77
+ var originalConfig map[string]any
78
configData, err := os.ReadFile(configPath)
79
require.NoError(t, err)
80
require.NoError(t, json.Unmarshal(configData, &originalConfig))
@@ -102,7 +102,7 @@ func testDaemonMigration15ToLatest(t *testing.T) {
102
require.Equal(t, latestVersion, strings.TrimSpace(string(versionData)), "Version should be updated to latest")
103
104
// Verify config is still valid JSON and key fields preserved
105
- var finalConfig map[string]interface{}
105
+ var finalConfig map[string]any
106
configData, err = os.ReadFile(configPath)
107
require.NoError(t, err)
108
require.NoError(t, json.Unmarshal(configData, &finalConfig), "Config should remain valid JSON")
@@ -148,7 +148,7 @@ func testRepoMigration15ToLatest(t *testing.T) {
148
require.Equal(t, latestVersion, strings.TrimSpace(string(versionData)), "Version should be updated to latest")
149
150
// Verify config is valid JSON
151
- var finalConfig map[string]interface{}
151
+ var finalConfig map[string]any
152
configData, err := os.ReadFile(configPath)
153
require.NoError(t, err)
154
require.NoError(t, json.Unmarshal(configData, &finalConfig), "Config should remain valid JSON")
@@ -413,13 +413,13 @@ func verifyMigrationSteps(t *testing.T, output string, from, to int, forward boo
413
}
414
415
// getNestedValue retrieves a nested value from a config map using dot notation
416
-func getNestedValue(config map[string]interface{}, path string) interface{} {
416
+func getNestedValue(config map[string]any, path string) any {
417
parts := strings.Split(path, ".")
418
- current := interface{}(config)
418
+ current := any(config)
419
420
for _, part := range parts {
421
switch v := current.(type) {
422
- case map[string]interface{}:
422
+ case map[string]any:
423
current = v[part]
424
default:
425
return nil
@@ -466,7 +466,7 @@ func testRepoReverseHybridMigrationLatestTo15(t *testing.T) {
466
require.Equal(t, latestVersion, strings.TrimSpace(string(versionData)), "Should be at latest version after forward migration")
467
468
// Read config after forward migration to use as baseline for downgrade
469
- var latestConfig map[string]interface{}
469
+ var latestConfig map[string]any
470
configData, err := os.ReadFile(configPath)
471
require.NoError(t, err)
472
require.NoError(t, json.Unmarshal(configData, &latestConfig))
@@ -487,7 +487,7 @@ func testRepoReverseHybridMigrationLatestTo15(t *testing.T) {
487
require.Equal(t, "15", strings.TrimSpace(string(versionData)), "Version should be updated to 15")
488
489
// Verify config is still valid JSON and key fields preserved
490
- var finalConfig map[string]interface{}
490
+ var finalConfig map[string]any
491
configData, err = os.ReadFile(configPath)
492
require.NoError(t, err)
493
require.NoError(t, json.Unmarshal(configData, &finalConfig), "Config should remain valid JSON")
test/cli/peering_test.go
+2
-6
@@ -1,6 +1,7 @@
1
package cli
2
3
import (
4
+ "slices"
5
"testing"
6
"time"
7
@@ -14,12 +15,7 @@ func TestPeering(t *testing.T) {
15
t.Parallel()
16
17
containsPeerID := func(p peer.ID, peers []peer.ID) bool {
17
- for _, peerID := range peers {
18
- if p == peerID {
19
- return true
20
- }
21
- }
22
- return false
18
+ return slices.Contains(peers, p)
19
}
20
21
assertPeered := func(h *harness.Harness, from *harness.Node, to *harness.Node) {
test/cli/pin_ls_names_test.go
+5
-5
@@ -134,8 +134,8 @@ func TestPinLsWithNamesForSpecificCIDs(t *testing.T) {
134
assertCIDOnly(t, output, cidC)
135
136
// Pin C should appear but without a name (just type)
137
- lines := strings.Split(output, "\n")
138
- for _, line := range lines {
137
+ lines := strings.SplitSeq(output, "\n")
138
+ for line := range lines {
139
if strings.Contains(line, cidC) {
140
// Should have CID and type but no name
141
require.Contains(t, line, "recursive", "pin type 'recursive' not found for unnamed pin %s in line: %s", cidC, line)
@@ -362,7 +362,7 @@ func TestPinLsWithNamesForSpecificCIDs(t *testing.T) {
362
numPins := 10
363
done := make(chan struct{}, numPins)
364
365
- for i := 0; i < numPins; i++ {
365
+ for i := range numPins {
366
go func(idx int) {
367
defer func() { done <- struct{}{} }()
368
@@ -374,14 +374,14 @@ func TestPinLsWithNamesForSpecificCIDs(t *testing.T) {
374
}
375
376
// Wait for all goroutines
377
- for i := 0; i < numPins; i++ {
377
+ for range numPins {
378
<-done
379
}
380
381
// Verify all pins have correct names
382
res := node.IPFS("pin", "ls", "--names")
383
output := res.Stdout.String()
384
- for i := 0; i < numPins; i++ {
384
+ for i := range numPins {
385
pinName := fmt.Sprintf("concurrent-pin-%d", i)
386
require.Contains(t, output, pinName,
387
"concurrent pin name '%s' not found in output", pinName)
test/cli/pinning_remote_test.go
+1
-1
@@ -431,7 +431,7 @@ func TestRemotePinning(t *testing.T) {
431
defer pin.M.Unlock()
432
pin.Status = "pinned"
433
}
434
- for i := 0; i < 4; i++ {
434
+ for i := range 4 {
435
hash := node.IPFSAddStr(string(random.Bytes(1000)))
436
name := fmt.Sprintf("--name=%d", i)
437
node.IPFS("pin", "remote", "add", "--service=svc", "--name="+name, hash)
test/cli/provide_stats_test.go
+4
-4
@@ -396,8 +396,8 @@ func TestProvideStatOutputFormats(t *testing.T) {
396
397
// Parse JSON to verify structure
398
var result struct {
399
- Sweep map[string]interface{} `json:"Sweep"`
400
- Legacy map[string]interface{} `json:"Legacy"`
399
+ Sweep map[string]any `json:"Sweep"`
400
+ Legacy map[string]any `json:"Legacy"`
401
}
402
err := json.Unmarshal([]byte(res.Stdout.String()), &result)
403
require.NoError(t, err, "Output should be valid JSON")
@@ -420,8 +420,8 @@ func TestProvideStatOutputFormats(t *testing.T) {
420
421
// Parse JSON to verify structure
422
var result struct {
423
- Sweep map[string]interface{} `json:"Sweep"`
424
- Legacy map[string]interface{} `json:"Legacy"`
423
+ Sweep map[string]any `json:"Sweep"`
424
+ Legacy map[string]any `json:"Legacy"`
425
}
426
err := json.Unmarshal([]byte(res.Stdout.String()), &result)
427
require.NoError(t, err, "Output should be valid JSON")
test/cli/provider_test.go
+2
-3
@@ -647,7 +647,7 @@ func runResumeTests(t *testing.T, apply cfgApplier) {
647
node := setupNode(t, true)
648
defer node.StopDaemon()
649
650
- for i := 0; i < 10; i++ {
650
+ for i := range 10 {
651
node.IPFSAddStr(fmt.Sprintf("resume-test-%d-%d", i, time.Now().UnixNano()))
652
}
653
@@ -678,7 +678,7 @@ func runResumeTests(t *testing.T, apply cfgApplier) {
678
node := setupNode(t, false)
679
defer node.StopDaemon()
680
681
- for i := 0; i < 10; i++ {
681
+ for i := range 10 {
682
node.IPFSAddStr(fmt.Sprintf("no-resume-%d-%d", i, time.Now().UnixNano()))
683
}
684
@@ -753,7 +753,6 @@ func TestProvider(t *testing.T) {
753
}
754
755
for _, v := range variants {
756
- v := v // capture
756
t.Run(v.name, func(t *testing.T) {
757
// t.Parallel()
758
runProviderSuite(t, v.reprovide, v.apply)
test/cli/pubsub_test.go
+1
-1
@@ -35,7 +35,7 @@ func waitForMessagePropagation(t *testing.T) {
35
// a small delay between each to allow for ordered delivery.
36
func publishMessages(t *testing.T, publisher *harness.Node, topic string, n int) {
37
t.Helper()
38
- for i := 0; i < n; i++ {
38
+ for range n {
39
publisher.PipeStrToIPFS("msg", "pubsub", "pub", topic)
40
time.Sleep(50 * time.Millisecond)
41
}
test/cli/repo_verify_test.go
+4
-4
@@ -64,7 +64,7 @@ func corruptMultipleBlocks(t *testing.T, node *harness.Node, count int) []string
64
65
var corrupted []string
66
for i := 0; i < count && i < len(eligible); i++ {
67
- err := os.WriteFile(eligible[i], []byte(fmt.Sprintf("corrupted data %d", i)), 0644)
67
+ err := os.WriteFile(eligible[i], fmt.Appendf(nil, "corrupted data %d", i), 0644)
68
require.NoError(t, err)
69
corrupted = append(corrupted, eligible[i])
70
}
@@ -195,7 +195,7 @@ func TestRepoVerify(t *testing.T) {
195
node := harness.NewT(t).NewNode().Init()
196
197
// Create 20 blocks
198
- for i := 0; i < 20; i++ {
198
+ for i := range 20 {
199
node.IPFSAddStr(strings.Repeat("test content ", i+1))
200
}
201
@@ -319,7 +319,7 @@ func TestRepoVerify(t *testing.T) {
319
node := harness.NewT(t).NewNode().Init()
320
321
// Create 1000 small blocks
322
- for i := 0; i < 1000; i++ {
322
+ for i := range 1000 {
323
node.IPFSAddStr(fmt.Sprintf("content-%d", i))
324
}
325
@@ -346,7 +346,7 @@ func TestRepoVerify(t *testing.T) {
346
node := harness.NewT(t).NewNode().Init()
347
348
// Create several blocks
349
- for i := 0; i < 5; i++ {
349
+ for i := range 5 {
350
node.IPFSAddStr(fmt.Sprintf("content for removal test %d", i))
351
}
352
test/cli/routing_dht_test.go
-2
@@ -87,7 +87,6 @@ func testRoutingDHT(t *testing.T, enablePubsub bool) {
87
t.Parallel()
88
keys := []string{"foo", "/pk/foo", "/ipns/foo"}
89
for _, key := range keys {
90
- key := key
90
t.Run(key, func(t *testing.T) {
91
t.Parallel()
92
res := nodes[0].RunIPFS("routing", "put", key)
@@ -100,7 +99,6 @@ func testRoutingDHT(t *testing.T, enablePubsub bool) {
99
100
t.Run("get with bad keys (issue #4611)", func(t *testing.T) {
101
for _, key := range []string{"foo", "/pk/foo"} {
103
- key := key
102
t.Run(key, func(t *testing.T) {
103
t.Parallel()
104
res := nodes[0].RunIPFS("routing", "get", key)
test/cli/telemetry_test.go
+2
-2
@@ -229,7 +229,7 @@ func TestTelemetry(t *testing.T) {
229
}
230
231
// Channel to receive captured telemetry data
232
- telemetryChan := make(chan map[string]interface{}, 1)
232
+ telemetryChan := make(chan map[string]any, 1)
233
234
// Create a mock HTTP server to capture telemetry
235
mockServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
@@ -244,7 +244,7 @@ func TestTelemetry(t *testing.T) {
244
return
245
}
246
247
- var telemetryData map[string]interface{}
247
+ var telemetryData map[string]any
248
if err := json.Unmarshal(body, &telemetryData); err != nil {
249
http.Error(w, "Invalid JSON", http.StatusBadRequest)
250
return
test/cli/testutils/floats.go
+1
-1
@@ -2,7 +2,7 @@ package testutils
2
3
func FloatTruncate(value float64, decimalPlaces int) float64 {
4
pow := 1.0
5
- for i := 0; i < decimalPlaces; i++ {
5
+ for range decimalPlaces {
6
pow *= 10.0
7
}
8
return float64(int(value*pow)) / pow
test/cli/testutils/json.go
+1
-1
@@ -2,7 +2,7 @@ package testutils
2
3
import "encoding/json"
4
5
-type JSONObj map[string]interface{}
5
+type JSONObj map[string]any
6
7
func ToJSONStr(m JSONObj) string {
8
b, err := json.Marshal(m)
test/cli/testutils/pinningservice/pinning.go
+16
-16
@@ -61,10 +61,10 @@ type PinningService struct {
61
}
62
63
type Pin struct {
64
- CID string `json:"cid"`
65
- Name string `json:"name"`
66
- Origins []string `json:"origins"`
67
- Meta map[string]interface{} `json:"meta"`
64
+ CID string `json:"cid"`
65
+ Name string `json:"name"`
66
+ Origins []string `json:"origins"`
67
+ Meta map[string]any `json:"meta"`
68
}
69
70
type PinStatus struct {
@@ -74,17 +74,17 @@ type PinStatus struct {
74
Created time.Time
75
Pin Pin
76
Delegates []string
77
- Info map[string]interface{}
77
+ Info map[string]any
78
}
79
80
func (p *PinStatus) MarshalJSON() ([]byte, error) {
81
type pinStatusJSON struct {
82
- RequestID string `json:"requestid"`
83
- Status string `json:"status"`
84
- Created time.Time `json:"created"`
85
- Pin Pin `json:"pin"`
86
- Delegates []string `json:"delegates"`
87
- Info map[string]interface{} `json:"info"`
82
+ RequestID string `json:"requestid"`
83
+ Status string `json:"status"`
84
+ Created time.Time `json:"created"`
85
+ Pin Pin `json:"pin"`
86
+ Delegates []string `json:"delegates"`
87
+ Info map[string]any `json:"info"`
88
}
89
// lock the pin before marshaling it to protect against data races while marshaling
90
p.M.Lock()
@@ -155,10 +155,10 @@ func writeJSON(w http.ResponseWriter, val any, statusCode int) {
155
}
156
157
type AddPinRequest struct {
158
- CID string `json:"cid"`
159
- Name string `json:"name"`
160
- Origins []string `json:"origins"`
161
- Meta map[string]interface{} `json:"meta"`
158
+ CID string `json:"cid"`
159
+ Name string `json:"name"`
160
+ Origins []string `json:"origins"`
161
+ Meta map[string]any `json:"meta"`
162
}
163
164
func (p *PinningService) addPin(writer http.ResponseWriter, req *http.Request, params httprouter.Params) {
@@ -312,7 +312,7 @@ func (p *PinningService) listPins(writer http.ResponseWriter, req *http.Request,
312
313
// meta
314
if metaStr != "" {
315
- meta := map[string]interface{}{}
315
+ meta := map[string]any{}
316
err := json.Unmarshal([]byte(metaStr), &meta)
317
if err != nil {
318
errResp(writer, fmt.Sprintf("parsing meta: %s", err), "", http.StatusBadRequest)
test/cli/testutils/random_deterministic.go
+1
-4
@@ -17,10 +17,7 @@ func (r *randomReader) Read(p []byte) (int, error) {
17
if r.remaining <= 0 {
18
return 0, io.EOF
19
}
20
- n := int64(len(p))
21
- if n > r.remaining {
22
- n = r.remaining
23
- }
20
+ n := min(int64(len(p)), r.remaining)
21
// Generate random bytes directly into the provided buffer
22
r.cipher.XORKeyStream(p[:n], make([]byte, n))
23
r.remaining -= n
test/cli/testutils/strings.go
+1
-1
@@ -22,7 +22,7 @@ var (
22
// and concats them all together into one string slice.
23
// If an arg is not one of those types, this panics.
24
// If an arg is an empty string, it is dropped.
25
-func StrCat(args ...interface{}) []string {
25
+func StrCat(args ...any) []string {
26
res := make([]string, 0)
27
for _, a := range args {
28
if s, ok := a.(string); ok {
test/integration/bitswap_wo_routing_test.go
+1
-1
@@ -20,7 +20,7 @@ func TestBitswapWithoutRouting(t *testing.T) {
20
mn := mocknet.New()
21
22
var nodes []*core.IpfsNode
23
- for i := 0; i < numPeers; i++ {
23
+ for range numPeers {
24
n, err := core.NewNode(ctx, &core.BuildCfg{
25
Online: true,
26
Host: coremock.MockHostOption(mn),
test/integration/wan_lan_dht_test.go
+1
-1
@@ -93,7 +93,7 @@ func RunDHTConnectivity(conf testutil.LatencyConfig, numPeers int) error {
93
94
connectionContext, connCtxCancel := context.WithTimeout(ctx, 15*time.Second)
95
defer connCtxCancel()
96
- for i := 0; i < numPeers; i++ {
96
+ for i := range numPeers {
97
wanPeer, err := core.NewNode(ctx, &core.BuildCfg{
98
Online: true,
99
Routing: libp2p2.DHTServerOption,