kubo/repo/common/common.go
Marcin Rataj 6a008fc74c
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)
2026-02-11 01:01:32 +01:00

94 lines
2.0 KiB
Go

package common
import (
"fmt"
"maps"
"strings"
)
func MapGetKV(v map[string]any, key string) (any, error) {
var ok bool
var mcursor map[string]any
var cursor any = v
parts := strings.Split(key, ".")
for i, part := range parts {
sofar := strings.Join(parts[:i], ".")
mcursor, ok = cursor.(map[string]any)
if !ok {
return nil, fmt.Errorf("%s key is not a map", sofar)
}
cursor, ok = mcursor[part]
if !ok {
// Construct the current path traversed to print a nice error message
var path string
if len(sofar) > 0 {
path += sofar + "."
}
path += part
return nil, fmt.Errorf("%s not found", path)
}
}
return cursor, nil
}
func MapSetKV(v map[string]any, key string, value any) error {
var ok bool
var mcursor map[string]any
var cursor any = v
parts := strings.Split(key, ".")
for i, part := range parts {
mcursor, ok = cursor.(map[string]any)
if !ok {
sofar := strings.Join(parts[:i], ".")
return fmt.Errorf("%s key is not a map", sofar)
}
// last part? set here
if i == (len(parts) - 1) {
mcursor[part] = value
break
}
cursor, ok = mcursor[part]
if !ok || cursor == nil { // create map if this is empty or is null
mcursor[part] = map[string]any{}
cursor = mcursor[part]
}
}
return nil
}
// MapMergeDeep merges the right map into the left map, recursively traversing
// child maps until a non-map value is found.
func MapMergeDeep(left, right map[string]any) map[string]any {
// We want to alter a copy of the map, not the original
result := maps.Clone(left)
if result == nil {
result = make(map[string]any)
}
for key, rightVal := range right {
// If right value is a map
if rightMap, ok := rightVal.(map[string]any); ok {
// If key is in left
if leftVal, found := result[key]; found {
// If left value is also a map
if leftMap, ok := leftVal.(map[string]any); ok {
// Merge nested map
result[key] = MapMergeDeep(leftMap, rightMap)
continue
}
}
}
// Otherwise set new value to result
result[key] = rightVal
}
return result
}