diff --git a/.golangci.yml b/.golangci.yml new file mode 100644 index 000000000..4f8a023cf --- /dev/null +++ b/.golangci.yml @@ -0,0 +1,27 @@ +version: "2" +linters: + default: standard + enable: + - unparam + +formatters: + enable: + - gofmt + - goimports + settings: + gofmt: + rewrite-rules: + - pattern: 'interface{}' + replacement: 'any' + +issues: + max-same-issues: 100 + + exclude-files: + - generated.*\\.go + + exclude-dirs: + - vendor + +run: + timeout: 10m diff --git a/Makefile b/Makefile index 1aa5cd994..0d1f72430 100644 --- a/Makefile +++ b/Makefile @@ -242,8 +242,6 @@ test: $(BUILD_DIRS) ./hack/test.sh $(SRC_PKGS) \ " -ADDTL_LINTERS := gofmt,goimports,unparam - .PHONY: lint lint: $(BUILD_DIRS) @echo "running linter" @@ -261,7 +259,7 @@ lint: $(BUILD_DIRS) --env GO111MODULE=on \ --env GOFLAGS="-mod=vendor" \ $(BUILD_IMAGE) \ - golangci-lint run --enable $(ADDTL_LINTERS) --timeout=10m --exclude-files="generated.*\.go$\" --exclude-dirs-use-default + golangci-lint run $(BUILD_DIRS): @mkdir -p $@ diff --git a/admissionregistration/lib.go b/admissionregistration/lib.go index 98f3109f5..bee451d6f 100644 --- a/admissionregistration/lib.go +++ b/admissionregistration/lib.go @@ -36,7 +36,7 @@ func init() { var ( ErrMissingKind = errors.New("test object missing kind") ErrMissingVersion = errors.New("test object missing version") - ErrWebhookNotActivated = errors.New("Admission webhooks are not activated. Enable it by configuring --enable-admission-plugins flag of kube-apiserver. For details, visit: https://appsco.de/kube-apiserver-webhooks") + ErrWebhookNotActivated = errors.New("admission webhooks are not activated. Enable it by configuring --enable-admission-plugins flag of kube-apiserver. For details, visit: https://appsco.de/kube-apiserver-webhooks") ) func BypassValidatingWebhookXray() bool { diff --git a/admissionregistration/v1/xray.go b/admissionregistration/v1/xray.go index 3a43af148..d647b64de 100644 --- a/admissionregistration/v1/xray.go +++ b/admissionregistration/v1/xray.go @@ -256,7 +256,8 @@ func (d ValidatingWebhookXray) check(ctx context.Context) (bool, error) { return false, err } - if d.op == v1.Create { + switch d.op { + case v1.Create: _, err := ri.Create(ctx, &u, metav1.CreateOptions{}) if kutil.AdmissionWebhookDeniedRequest(err) { klog.V(10).Infof("failed to create invalid test object as expected with error: %s", err) @@ -267,7 +268,7 @@ func (d ValidatingWebhookXray) check(ctx context.Context) (bool, error) { _ = dynamic_util.WaitUntilDeleted(ri, d.stopCh, accessor.GetName()) return false, admreg.ErrWebhookNotActivated - } else if d.op == v1.Update { + case v1.Update: _, err := ri.Create(ctx, &u, metav1.CreateOptions{}) if err != nil { return false, err @@ -296,7 +297,7 @@ func (d ValidatingWebhookXray) check(ctx context.Context) (bool, error) { } return false, admreg.ErrWebhookNotActivated - } else if d.op == v1.Delete { + case v1.Delete: _, err := ri.Create(ctx, &u, metav1.CreateOptions{}) if err != nil { return false, err diff --git a/admissionregistration/v1beta1/xray.go b/admissionregistration/v1beta1/xray.go index 092edafca..9f001191b 100644 --- a/admissionregistration/v1beta1/xray.go +++ b/admissionregistration/v1beta1/xray.go @@ -256,7 +256,8 @@ func (d ValidatingWebhookXray) check(ctx context.Context) (bool, error) { return false, err } - if d.op == v1beta1.Create { + switch d.op { + case v1beta1.Create: _, err := ri.Create(ctx, &u, metav1.CreateOptions{}) if kutil.AdmissionWebhookDeniedRequest(err) { klog.V(10).Infof("failed to create invalid test object as expected with error: %s", err) @@ -267,7 +268,7 @@ func (d ValidatingWebhookXray) check(ctx context.Context) (bool, error) { _ = dynamic_util.WaitUntilDeleted(ri, d.stopCh, accessor.GetName()) return false, admreg.ErrWebhookNotActivated - } else if d.op == v1beta1.Update { + case v1beta1.Update: _, err := ri.Create(ctx, &u, metav1.CreateOptions{}) if err != nil { return false, err @@ -296,7 +297,7 @@ func (d ValidatingWebhookXray) check(ctx context.Context) (bool, error) { } return false, admreg.ErrWebhookNotActivated - } else if d.op == v1beta1.Delete { + case v1beta1.Delete: _, err := ri.Create(ctx, &u, metav1.CreateOptions{}) if err != nil { return false, err diff --git a/api/v1/object.go b/api/v1/object.go index 92035935a..90e50df87 100644 --- a/api/v1/object.go +++ b/api/v1/object.go @@ -158,8 +158,8 @@ func MustParseObjectID(key OID) *ObjectID { return oid } -func ObjectIDMap(key OID) (map[string]interface{}, error) { - id := map[string]interface{}{ +func ObjectIDMap(key OID) (map[string]any, error) { + id := map[string]any{ "group": "", "kind": "", "namespace": "", diff --git a/api/v1/timeofday.go b/api/v1/timeofday.go index 88ea1a8ba..5d6310a44 100644 --- a/api/v1/timeofday.go +++ b/api/v1/timeofday.go @@ -164,7 +164,7 @@ func (t TimeOfDay) MarshalJSON() ([]byte, error) { } // ToUnstructured implements the value.UnstructuredConverter interface. -func (t TimeOfDay) ToUnstructured() interface{} { +func (t TimeOfDay) ToUnstructured() any { if t.IsZero() { return nil } @@ -177,11 +177,11 @@ func (t TimeOfDay) ToUnstructured() interface{} { // the OpenAPI spec of this type. // // See: https://github.com/kubernetes/kube-openapi/tree/master/pkg/generators -func (_ TimeOfDay) OpenAPISchemaType() []string { return []string{"string"} } +func (TimeOfDay) OpenAPISchemaType() []string { return []string{"string"} } // OpenAPISchemaFormat is used by the kube-openapi generator when constructing // the OpenAPI spec of this type. -func (_ TimeOfDay) OpenAPISchemaFormat() string { return "time" } +func (TimeOfDay) OpenAPISchemaFormat() string { return "time" } // MarshalQueryParameter converts to a URL query parameter value func (t TimeOfDay) MarshalQueryParameter() (string, error) { @@ -201,7 +201,7 @@ func (t *TimeOfDay) Fuzz(c fuzz.Continue) { // Allow for about 1000 years of randomness. Leave off nanoseconds // because JSON doesn't represent them so they can't round-trip // properly. - t.Time = time.Unix(c.Rand.Int63n(1000*365*24*60*60), 0) + t.Time = time.Unix(c.Int63n(1000*365*24*60*60), 0) } // ensure Time implements fuzz.Interface diff --git a/cluster/host_detector.go b/cluster/host_detector.go index f10bbbd9f..4f974ec25 100644 --- a/cluster/host_detector.go +++ b/cluster/host_detector.go @@ -50,12 +50,12 @@ func TestGKE() (string, error) { if err != nil { return "", err } - defer resp.Body.Close() + defer resp.Body.Close() // nolint:errcheck body, err := io.ReadAll(resp.Body) if err != nil { return "", err } - content := make(map[string]interface{}) + content := make(map[string]any) err = yaml.Unmarshal(body, &content) if err != nil { return "", err diff --git a/conditions/getter_test.go b/conditions/getter_test.go index 130350077..318c6d551 100644 --- a/conditions/getter_test.go +++ b/conditions/getter_test.go @@ -37,9 +37,9 @@ var ( func newConditioned(name string) *conditioned { // nolint: errcheck return &conditioned{ Unstructured: &unstructured.Unstructured{ - Object: map[string]interface{}{ + Object: map[string]any{ "kind": "Foo", - "metadata": map[string]interface{}{ + "metadata": map[string]any{ "name": name, }, }, diff --git a/conditions/matcher.go b/conditions/matcher.go index f79d2b413..43a161512 100644 --- a/conditions/matcher.go +++ b/conditions/matcher.go @@ -36,8 +36,8 @@ type matchConditions struct { expected kmapi.Conditions } -func (m matchConditions) Match(actual interface{}) (success bool, err error) { - elems := []interface{}{} +func (m matchConditions) Match(actual any) (success bool, err error) { + elems := []any{} for _, condition := range m.expected { elems = append(elems, MatchCondition(condition)) } @@ -45,11 +45,11 @@ func (m matchConditions) Match(actual interface{}) (success bool, err error) { return gomega.ConsistOf(elems).Match(actual) } -func (m matchConditions) FailureMessage(actual interface{}) (message string) { +func (m matchConditions) FailureMessage(actual any) (message string) { return fmt.Sprintf("expected\n\t%#v\nto match\n\t%#v\n", actual, m.expected) } -func (m matchConditions) NegatedFailureMessage(actual interface{}) (message string) { +func (m matchConditions) NegatedFailureMessage(actual any) (message string) { return fmt.Sprintf("expected\n\t%#v\nto not match\n\t%#v\n", actual, m.expected) } @@ -64,7 +64,7 @@ type matchCondition struct { expected kmapi.Condition } -func (m matchCondition) Match(actual interface{}) (success bool, err error) { +func (m matchCondition) Match(actual any) (success bool, err error) { actualCondition, ok := actual.(kmapi.Condition) if !ok { return false, fmt.Errorf("actual should be of type Condition") @@ -94,10 +94,10 @@ func (m matchCondition) Match(actual interface{}) (success bool, err error) { return ok, err } -func (m matchCondition) FailureMessage(actual interface{}) (message string) { +func (m matchCondition) FailureMessage(actual any) (message string) { return fmt.Sprintf("expected\n\t%#v\nto match\n\t%#v\n", actual, m.expected) } -func (m matchCondition) NegatedFailureMessage(actual interface{}) (message string) { +func (m matchCondition) NegatedFailureMessage(actual any) (message string) { return fmt.Sprintf("expected\n\t%#v\nto not match\n\t%#v\n", actual, m.expected) } diff --git a/conditions/matcher_test.go b/conditions/matcher_test.go index 1e7f94ef0..71b11908a 100644 --- a/conditions/matcher_test.go +++ b/conditions/matcher_test.go @@ -28,7 +28,7 @@ import ( func TestMatchConditions(t *testing.T) { testCases := []struct { name string - actual interface{} + actual any expected kmapi.Conditions expectMatch bool }{ @@ -151,7 +151,7 @@ func TestMatchConditions(t *testing.T) { func TestMatchCondition(t *testing.T) { testCases := []struct { name string - actual interface{} + actual any expected kmapi.Condition expectMatch bool }{ diff --git a/conditions/matchers.go b/conditions/matchers.go index 508932205..f35e606d0 100644 --- a/conditions/matchers.go +++ b/conditions/matchers.go @@ -36,7 +36,7 @@ type conditionMatcher struct { Expected *kmapi.Condition } -func (matcher *conditionMatcher) Match(actual interface{}) (success bool, err error) { +func (matcher *conditionMatcher) Match(actual any) (success bool, err error) { actualCondition, ok := actual.(*kmapi.Condition) if !ok { return false, errors.New("value should be a condition") @@ -45,10 +45,10 @@ func (matcher *conditionMatcher) Match(actual interface{}) (success bool, err er return hasSameState(actualCondition, matcher.Expected), nil } -func (matcher *conditionMatcher) FailureMessage(actual interface{}) (message string) { +func (matcher *conditionMatcher) FailureMessage(actual any) (message string) { return format.Message(actual, "to have the same state of", matcher.Expected) } -func (matcher *conditionMatcher) NegatedFailureMessage(actual interface{}) (message string) { +func (matcher *conditionMatcher) NegatedFailureMessage(actual any) (message string) { return format.Message(actual, "not to have the same state of", matcher.Expected) } diff --git a/conditions/merge_strategies_test.go b/conditions/merge_strategies_test.go index b56f27ca2..c6fa4306d 100644 --- a/conditions/merge_strategies_test.go +++ b/conditions/merge_strategies_test.go @@ -48,9 +48,9 @@ func TestLocalizeReason(t *testing.T) { getter := &conditioned{ Unstructured: &unstructured.Unstructured{ - Object: map[string]interface{}{ + Object: map[string]any{ "kind": "Foo", - "metadata": map[string]interface{}{ + "metadata": map[string]any{ "name": "test-cluster", }, }, @@ -74,9 +74,9 @@ func TestGetFirstReasonAndMessage(t *testing.T) { getter := &conditioned{ Unstructured: &unstructured.Unstructured{ - Object: map[string]interface{}{ + Object: map[string]any{ "kind": "Foo", - "metadata": map[string]interface{}{ + "metadata": map[string]any{ "name": "test-cluster", }, }, diff --git a/conditions/patch_test.go b/conditions/patch_test.go index c4c481444..2d15a4019 100644 --- a/conditions/patch_test.go +++ b/conditions/patch_test.go @@ -262,8 +262,8 @@ func TestApplyDoesNotAlterLastTransitionTime(t *testing.T) { before := newConditioned("test") after := &conditioned{ Unstructured: &unstructured.Unstructured{ - Object: map[string]interface{}{ - "status": map[string]interface{}{ + Object: map[string]any{ + "status": map[string]any{ "conditions": kmapi.Conditions{ kmapi.Condition{ Type: "foo", diff --git a/conditions/setter.go b/conditions/setter.go index eb9bf49f7..0e6b95de5 100644 --- a/conditions/setter.go +++ b/conditions/setter.go @@ -88,7 +88,7 @@ func TrueCondition(t kmapi.ConditionType) *kmapi.Condition { } // FalseCondition returns a condition with Status=False and the given type. -func FalseCondition(t kmapi.ConditionType, reason string, severity kmapi.ConditionSeverity, messageFormat string, messageArgs ...interface{}) *kmapi.Condition { +func FalseCondition(t kmapi.ConditionType, reason string, severity kmapi.ConditionSeverity, messageFormat string, messageArgs ...any) *kmapi.Condition { return &kmapi.Condition{ Type: t, Status: metav1.ConditionFalse, @@ -99,7 +99,7 @@ func FalseCondition(t kmapi.ConditionType, reason string, severity kmapi.Conditi } // UnknownCondition returns a condition with Status=Unknown and the given type. -func UnknownCondition(t kmapi.ConditionType, reason string, messageFormat string, messageArgs ...interface{}) *kmapi.Condition { +func UnknownCondition(t kmapi.ConditionType, reason string, messageFormat string, messageArgs ...any) *kmapi.Condition { return &kmapi.Condition{ Type: t, Status: metav1.ConditionUnknown, @@ -114,12 +114,12 @@ func MarkTrue(to Setter, t kmapi.ConditionType) { } // MarkUnknown sets Status=Unknown for the condition with the given type. -func MarkUnknown(to Setter, t kmapi.ConditionType, reason, messageFormat string, messageArgs ...interface{}) { +func MarkUnknown(to Setter, t kmapi.ConditionType, reason, messageFormat string, messageArgs ...any) { Set(to, UnknownCondition(t, reason, messageFormat, messageArgs...)) } // MarkFalse sets Status=False for the condition with the given type. -func MarkFalse(to Setter, t kmapi.ConditionType, reason string, severity kmapi.ConditionSeverity, messageFormat string, messageArgs ...interface{}) { +func MarkFalse(to Setter, t kmapi.ConditionType, reason string, severity kmapi.ConditionSeverity, messageFormat string, messageArgs ...any) { Set(to, FalseCondition(t, reason, severity, messageFormat, messageArgs...)) } diff --git a/conditions/setter_test.go b/conditions/setter_test.go index dc30125f0..e7a1ad9f8 100644 --- a/conditions/setter_test.go +++ b/conditions/setter_test.go @@ -270,7 +270,7 @@ type ConditionsMatcher struct { Expected kmapi.Conditions } -func (matcher *ConditionsMatcher) Match(actual interface{}) (success bool, err error) { +func (matcher *ConditionsMatcher) Match(actual any) (success bool, err error) { actualConditions, ok := actual.(kmapi.Conditions) if !ok { return false, errors.New("value should be a conditions list") @@ -288,10 +288,10 @@ func (matcher *ConditionsMatcher) Match(actual interface{}) (success bool, err e return true, nil } -func (matcher *ConditionsMatcher) FailureMessage(actual interface{}) (message string) { +func (matcher *ConditionsMatcher) FailureMessage(actual any) (message string) { return format.Message(actual, "to have the same conditions of", matcher.Expected) } -func (matcher *ConditionsMatcher) NegatedFailureMessage(actual interface{}) (message string) { +func (matcher *ConditionsMatcher) NegatedFailureMessage(actual any) (message string) { return format.Message(actual, "not to have the same conditions of", matcher.Expected) } diff --git a/core/v1/kubernetes.go b/core/v1/kubernetes.go index 1b7ed9e41..9a5c5ef10 100644 --- a/core/v1/kubernetes.go +++ b/core/v1/kubernetes.go @@ -260,7 +260,7 @@ func GetVolumeMountByName(volumeMounts []core.VolumeMount, name string) *core.Vo func UpsertVolumeMount(mounts []core.VolumeMount, nv ...core.VolumeMount) []core.VolumeMount { upsert := func(m core.VolumeMount) { for i, vol := range mounts { - if vol.Name == m.Name { + if vol.MountPath == m.MountPath { mounts[i] = m return } diff --git a/dynamic/conditions/conditions.go b/dynamic/conditions/conditions.go index 1055b57bb..6c6925015 100644 --- a/dynamic/conditions/conditions.go +++ b/dynamic/conditions/conditions.go @@ -64,7 +64,7 @@ func (do *DynamicOptions) SetCondition(newCond kmapi.Condition) error { } conds = conditions.SetCondition(conds, newCond) - unstrConds := make([]interface{}, len(conds)) + unstrConds := make([]any, len(conds)) for i := range conds { cond, err := runtime.DefaultUnstructuredConverter.ToUnstructured(&conds[i]) if err != nil { @@ -87,7 +87,7 @@ func (do *DynamicOptions) RemoveCondition(condType string) error { } conds = conditions.RemoveCondition(conds, condType) - unstrConds := make([]interface{}, len(conds)) + unstrConds := make([]any, len(conds)) for i := range conds { cond, err := runtime.DefaultUnstructuredConverter.ToUnstructured(&conds[i]) if err != nil { @@ -147,7 +147,7 @@ func (do *DynamicOptions) UpdateConditions(conditions []kmapi.Condition) error { return err } - unstrConds := make([]interface{}, len(conditions)) + unstrConds := make([]any, len(conditions)) for i := range conditions { cond, err := runtime.DefaultUnstructuredConverter.ToUnstructured(&conditions[i]) if err != nil { @@ -170,8 +170,8 @@ func stringToTimeHookFunc(layout string) mapstructure.DecodeHookFunc { return func( f reflect.Type, t reflect.Type, - data interface{}, - ) (interface{}, error) { + data any, + ) (any, error) { if f.Kind() != reflect.String { return data, nil } diff --git a/dynamic/conditions/conditions_test.go b/dynamic/conditions/conditions_test.go index fda527036..cd23d45d1 100644 --- a/dynamic/conditions/conditions_test.go +++ b/dynamic/conditions/conditions_test.go @@ -59,7 +59,7 @@ var conds = []kmapi.Condition{ } func newFoo() (*unstructured.Unstructured, error) { - unstrConds := make([]interface{}, len(conds)) + unstrConds := make([]any, len(conds)) for i := range conds { cond, err := runtime.DefaultUnstructuredConverter.ToUnstructured(&conds[i]) if err != nil { @@ -68,17 +68,17 @@ func newFoo() (*unstructured.Unstructured, error) { unstrConds[i] = cond } return &unstructured.Unstructured{ - Object: map[string]interface{}{ + Object: map[string]any{ "apiVersion": "foo/v1", "kind": "Foo", - "metadata": map[string]interface{}{ + "metadata": map[string]any{ "name": "foo-test", "namespace": "bar", }, - "spec": map[string]interface{}{ + "spec": map[string]any{ "foo": "bar", }, - "status": map[string]interface{}{ + "status": map[string]any{ "conditions": unstrConds, }, }, diff --git a/meta/annotations.go b/meta/annotations.go index 4ffdd4e50..0718696c5 100644 --- a/meta/annotations.go +++ b/meta/annotations.go @@ -23,7 +23,7 @@ import ( kutil "kmodules.xyz/client-go" ) -type ParserFunc func(map[string]string, string) (interface{}, error) +type ParserFunc func(map[string]string, string) (any, error) var ( _ ParserFunc = GetBool @@ -35,7 +35,7 @@ var ( _ ParserFunc = GetDuration ) -func GetBool(m map[string]string, key string) (interface{}, error) { +func GetBool(m map[string]string, key string) (any, error) { if m == nil { return false, kutil.ErrNotFound } @@ -51,7 +51,7 @@ func GetBoolValue(m map[string]string, key string) (bool, error) { return v.(bool), err } -func GetInt(m map[string]string, key string) (interface{}, error) { +func GetInt(m map[string]string, key string) (any, error) { if m == nil { return 0, kutil.ErrNotFound } @@ -67,7 +67,7 @@ func GetIntValue(m map[string]string, key string) (int, error) { return v.(int), err } -func GetString(m map[string]string, key string) (interface{}, error) { +func GetString(m map[string]string, key string) (any, error) { if m == nil { return "", kutil.ErrNotFound } @@ -99,7 +99,7 @@ func RemoveKey(m map[string]string, key string) map[string]string { return m } -func GetList(m map[string]string, key string) (interface{}, error) { +func GetList(m map[string]string, key string) (any, error) { if m == nil { return []string{}, kutil.ErrNotFound } @@ -117,7 +117,7 @@ func GetListValue(m map[string]string, key string) ([]string, error) { return v.([]string), err } -func GetMap(m map[string]string, key string) (interface{}, error) { +func GetMap(m map[string]string, key string) (any, error) { if m == nil { return map[string]string{}, kutil.ErrNotFound } @@ -135,7 +135,7 @@ func GetMapValue(m map[string]string, key string) (map[string]string, error) { return v.(map[string]string), err } -func GetFloat(m map[string]string, key string) (interface{}, error) { +func GetFloat(m map[string]string, key string) (any, error) { if m == nil { return 0.0, kutil.ErrNotFound } @@ -152,7 +152,7 @@ func GetFloatValue(m map[string]string, key string) (float64, error) { return v.(float64), err } -func GetDuration(m map[string]string, key string) (interface{}, error) { +func GetDuration(m map[string]string, key string) (any, error) { if m == nil { return time.Duration(0), kutil.ErrNotFound } @@ -169,10 +169,10 @@ func GetDurationValue(m map[string]string, key string) (time.Duration, error) { return v.(time.Duration), err } -type GetFunc func(map[string]string) (interface{}, error) +type GetFunc func(map[string]string) (any, error) func ParseFor(key string, fn ParserFunc) GetFunc { - return func(m map[string]string) (interface{}, error) { + return func(m map[string]string) (any, error) { return fn(m, key) } } diff --git a/meta/cmp.go b/meta/cmp.go index 101583a6d..5258b3d92 100644 --- a/meta/cmp.go +++ b/meta/cmp.go @@ -40,11 +40,11 @@ var cmpOptions = []cmp.Option{ }), } -func Diff(x, y interface{}) string { +func Diff(x, y any) string { return cmp.Diff(x, y, cmpOptions...) } -func Equal(x, y interface{}) bool { +func Equal(x, y any) bool { return cmp.Equal(x, y, cmpOptions...) } @@ -75,7 +75,7 @@ func EqualAnnotation(x, y map[string]string) bool { return true } -func JsonDiff(old, new interface{}) (string, error) { +func JsonDiff(old, new any) (string, error) { json := jsoniter.ConfigFastest oldBytes, err := json.Marshal(old) if err != nil { @@ -94,7 +94,7 @@ func JsonDiff(old, new interface{}) (string, error) { return "", err } - var aJson map[string]interface{} + var aJson map[string]any if err := json.Unmarshal(oldBytes, &aJson); err != nil { return "", err } diff --git a/meta/dataformat.go b/meta/dataformat.go index 6fd675ca6..bc3ad53f7 100644 --- a/meta/dataformat.go +++ b/meta/dataformat.go @@ -23,7 +23,7 @@ import ( "sigs.k8s.io/yaml" ) -func DecodeObject(in interface{}, out interface{}) error { +func DecodeObject(in any, out any) error { config := &mapstructure.DecoderConfig{ Metadata: nil, TagName: "json", @@ -56,10 +56,11 @@ func NewDataFormat(format string, def DataFormat) DataFormat { } } -func Marshal(v interface{}, format DataFormat) ([]byte, error) { - if format == JsonFormat { +func Marshal(v any, format DataFormat) ([]byte, error) { + switch format { + case JsonFormat: return json.Marshal(v) - } else if format == YAMLFormat { + case YAMLFormat: return yaml.Marshal(v) } return nil, fmt.Errorf("unknonw format: %v", format) diff --git a/meta/encoding.go b/meta/encoding.go index abaa4f0ed..1ba1b120f 100644 --- a/meta/encoding.go +++ b/meta/encoding.go @@ -149,7 +149,7 @@ func UnmarshalFromJSON(data []byte, gv schema.GroupVersion) (runtime.Object, err // // WARNING: `json` tags are not respected when struct converted to map[string]interface{} // WARNING: Embedded structs are not decoded properly: https://github.com/mitchellh/mapstructure/pull/80 -func Decode(input interface{}, output interface{}) error { +func Decode(input any, output any) error { config := &mapstructure.DecoderConfig{ DecodeHook: StringToQuantityHookFunc(), Metadata: nil, @@ -169,8 +169,8 @@ func StringToQuantityHookFunc() mapstructure.DecodeHookFunc { return func( f reflect.Type, t reflect.Type, - data interface{}, - ) (interface{}, error) { + data any, + ) (any, error) { if f.Kind() != reflect.String { return data, nil } diff --git a/meta/hash.go b/meta/hash.go index 0e7778f4f..b8f2ec165 100644 --- a/meta/hash.go +++ b/meta/hash.go @@ -44,7 +44,7 @@ func ResourceHash(obj metav1.Object) string { // ObjectHash includes all top label fields (like data, spec) except TypeMeta, ObjectMeta and Status // also includes Generation, Annotation and Labels form ObjectMeta func ObjectHash(in metav1.Object) string { - obj := make(map[string]interface{}) + obj := make(map[string]any) obj["generation"] = in.GetGeneration() if len(in.GetLabels()) > 0 { @@ -84,7 +84,7 @@ func ObjectHash(in metav1.Object) string { } func GenerationHash(in metav1.Object) string { - obj := make(map[string]interface{}, 3) + obj := make(map[string]any, 3) obj["generation"] = in.GetGeneration() if len(in.GetLabels()) > 0 { obj["labels"] = in.GetLabels() @@ -106,7 +106,7 @@ func GenerationHash(in metav1.Object) string { // DeepHashObject writes specified object to hash using the spew library // which follows pointers and prints actual values of the nested objects // ensuring the hash does not change when a pointer changes. -func DeepHashObject(hasher hash.Hash, objectToWrite interface{}) { +func DeepHashObject(hasher hash.Hash, objectToWrite any) { hasher.Reset() printer := spew.ConfigState{ Indent: " ", @@ -114,10 +114,10 @@ func DeepHashObject(hasher hash.Hash, objectToWrite interface{}) { DisableMethods: true, SpewKeys: true, } - printer.Fprintf(hasher, "%#v", objectToWrite) + _, _ = printer.Fprintf(hasher, "%#v", objectToWrite) } -func MustAlreadyReconciled(o interface{}) bool { +func MustAlreadyReconciled(o any) bool { reconciled, err := AlreadyReconciled(o) if err != nil { panic("failed to extract status.observedGeneration field due to err:" + err.Error()) @@ -125,7 +125,7 @@ func MustAlreadyReconciled(o interface{}) bool { return reconciled } -func AlreadyReconciled(o interface{}) (bool, error) { +func AlreadyReconciled(o any) (bool, error) { var generation, observedGeneration int64 var err error diff --git a/meta/lib.go b/meta/lib.go index 455950a51..0e6f761e2 100644 --- a/meta/lib.go +++ b/meta/lib.go @@ -68,7 +68,7 @@ func DeleteInForeground() metav1.DeleteOptions { return metav1.DeleteOptions{PropagationPolicy: &policy} } -func GetKind(v interface{}) string { +func GetKind(v any) string { return reflect.Indirect(reflect.ValueOf(v)).Type().Name() } diff --git a/meta/patch.go b/meta/patch.go index 10d5e8a69..db8c227a8 100644 --- a/meta/patch.go +++ b/meta/patch.go @@ -29,14 +29,14 @@ import ( var json = jsoniter.ConfigFastest -func toJson(v interface{}) ([]byte, error) { +func toJson(v any) ([]byte, error) { if u, ok := v.([]byte); ok { return u, nil } return json.Marshal(v) } -func CreateStrategicPatch(cur interface{}, mod interface{}, fns ...mergepatch.PreconditionFunc) ([]byte, error) { +func CreateStrategicPatch(cur any, mod any, fns ...mergepatch.PreconditionFunc) ([]byte, error) { curJson, err := toJson(cur) if err != nil { return nil, err @@ -50,7 +50,7 @@ func CreateStrategicPatch(cur interface{}, mod interface{}, fns ...mergepatch.Pr return strategicpatch.CreateTwoWayMergePatch(curJson, modJson, mod, fns...) } -func CreateJSONMergePatch(cur interface{}, mod interface{}, fns ...mergepatch.PreconditionFunc) ([]byte, error) { +func CreateJSONMergePatch(cur any, mod any, fns ...mergepatch.PreconditionFunc) ([]byte, error) { curJson, err := toJson(cur) if err != nil { return nil, err @@ -72,7 +72,7 @@ func CreateJSONMergePatch(cur interface{}, mod interface{}, fns ...mergepatch.Pr return patch, nil } -func CreateJSONPatch(cur interface{}, mod interface{}) ([]byte, error) { +func CreateJSONPatch(cur any, mod any) ([]byte, error) { curJson, err := toJson(cur) if err != nil { return nil, err @@ -93,7 +93,7 @@ func CreateJSONPatch(cur interface{}, mod interface{}) ([]byte, error) { // Apply the preconditions to the patch, and return an error if any of them fail. // ref: https://github.com/kubernetes/apimachinery/blob/master/pkg/util/jsonmergepatch/patch.go#L74 func meetPreconditions(patch []byte, fns ...mergepatch.PreconditionFunc) error { - var patchMap map[string]interface{} + var patchMap map[string]any if err := json.Unmarshal(patch, &patchMap); err != nil { return fmt.Errorf("failed to unmarshal patch for precondition check: %s", patch) } @@ -115,8 +115,8 @@ func meetPreconditions(patch []byte, fns ...mergepatch.PreconditionFunc) error { // ref: https://github.com/kubernetes/apimachinery/blob/master/pkg/util/mergepatch/util.go#L30 func RequireChainKeyUnchanged(key string) mergepatch.PreconditionFunc { - return func(patch interface{}) bool { - patchMap, ok := patch.(map[string]interface{}) + return func(patch any) bool { + patchMap, ok := patch.(map[string]any) if !ok { fmt.Println("Invalid data") return true @@ -125,7 +125,7 @@ func RequireChainKeyUnchanged(key string) mergepatch.PreconditionFunc { } } -func checkChainKeyUnchanged(key string, mapData map[string]interface{}) bool { +func checkChainKeyUnchanged(key string, mapData map[string]any) bool { keys := strings.Split(key, ".") newKey := strings.Join(keys[1:], ".") @@ -134,7 +134,7 @@ func checkChainKeyUnchanged(key string, mapData map[string]interface{}) bool { return true } for _, val := range mapData { - if !checkChainKeyUnchanged(newKey, val.(map[string]interface{})) { + if !checkChainKeyUnchanged(newKey, val.(map[string]any)) { return false } } @@ -143,13 +143,13 @@ func checkChainKeyUnchanged(key string, mapData map[string]interface{}) bool { if !ok || len(keys) == 1 { return !ok } - if x, ok := values.([]interface{}); ok { + if x, ok := values.([]any); ok { // x is of type []Interface for _, val := range x { - return checkChainKeyUnchanged(newKey, val.(map[string]interface{})) + return checkChainKeyUnchanged(newKey, val.(map[string]any)) } } - return checkChainKeyUnchanged(newKey, values.(map[string]interface{})) + return checkChainKeyUnchanged(newKey, values.(map[string]any)) } return true } diff --git a/meta/patch_test.go b/meta/patch_test.go index 0bb8c5c09..ce11f6b86 100644 --- a/meta/patch_test.go +++ b/meta/patch_test.go @@ -90,11 +90,12 @@ func TestCreateStrategicPatch_Conditions(t *testing.T) { for _, c := range cases { t.Run(c.name, func(t *testing.T) { _, err := CreateStrategicPatch(&c.x, &c.y, c.cond...) - if c.result == true { + switch c.result { + case true: if err != nil { t.Errorf("Modifications should be passed. error: %v", err) } - } else if c.result == false { + case false: if err == nil || !mergepatch.IsPreconditionFailed(err) { t.Errorf("Modifications should be failed. error: %v", err) } @@ -127,11 +128,12 @@ func TestCreateJSONMergePatch_Conditions(t *testing.T) { for _, c := range cases { t.Run(c.name, func(t *testing.T) { _, err := CreateJSONMergePatch(&c.x, &c.y, c.cond...) - if c.result == true { + switch c.result { + case true: if err != nil { t.Errorf("Modifications should be passed. error: %v", err) } - } else if c.result == false { + case false: if err == nil || !mergepatch.IsPreconditionFailed(err) { t.Errorf("Modifications should be failed. error: %v", err) } diff --git a/meta/status.go b/meta/status.go index efa436837..893fe26b0 100644 --- a/meta/status.go +++ b/meta/status.go @@ -33,7 +33,7 @@ type Condition struct { ObservedGeneration int64 `json:"observedGeneration,omitempty"` } -func StatusEqual(old, new interface{}) bool { +func StatusEqual(old, new any) bool { oldStatus, oldExists := extractStatusFromObject(old) newStatus, newExists := extractStatusFromObject(new) if oldExists && newExists { @@ -48,7 +48,7 @@ func StatusEqual(old, new interface{}) bool { return !oldExists && !newExists } -func StatusConditionAwareEqual(old, new interface{}) bool { +func StatusConditionAwareEqual(old, new any) bool { oldStatus, oldExists := extractStatusFromObject(old) newStatus, newExists := extractStatusFromObject(new) if oldExists && newExists { @@ -61,7 +61,7 @@ func StatusConditionAwareEqual(old, new interface{}) bool { var result bool if oldKind == reflect.Map { - result = statusMapEqual(oldStatus.(map[string]interface{}), newStatus.(map[string]interface{})) + result = statusMapEqual(oldStatus.(map[string]any), newStatus.(map[string]any)) } else { oldStruct := structs.New(oldStatus) oldStruct.TagName = "json" @@ -81,7 +81,7 @@ func StatusConditionAwareEqual(old, new interface{}) bool { return !oldExists && !newExists } -func extractStatusFromObject(o interface{}) (interface{}, bool) { +func extractStatusFromObject(o any) (any, bool) { switch obj := o.(type) { case *unstructured.Unstructured: v, ok, _ := unstructured.NestedFieldNoCopy(obj.Object, "status") @@ -114,7 +114,7 @@ func conditionsEqual(old, nu []Condition) bool { return true } -func statusMapEqual(old, nu map[string]interface{}) bool { +func statusMapEqual(old, nu map[string]any) bool { // optimization if len(old) != len(nu) { return false diff --git a/meta/status_test.go b/meta/status_test.go index ed7b5d285..28de97a92 100644 --- a/meta/status_test.go +++ b/meta/status_test.go @@ -273,8 +273,8 @@ var ( func TestStatusConditionAwareEqual(t *testing.T) { type args struct { - old interface{} - new interface{} + old any + new any } tests := []struct { name string @@ -429,10 +429,10 @@ func TestStatusConditionAwareEqual(t *testing.T) { name: "Unstructured: old.status=missing, new.status=missing", args: args{ old: &unstructured.Unstructured{ - Object: map[string]interface{}{}, + Object: map[string]any{}, }, new: &unstructured.Unstructured{ - Object: map[string]interface{}{}, + Object: map[string]any{}, }, }, want: true, @@ -441,12 +441,12 @@ func TestStatusConditionAwareEqual(t *testing.T) { name: "Unstructured: old.status=nil, new.status=nil", args: args{ old: &unstructured.Unstructured{ - Object: map[string]interface{}{ + Object: map[string]any{ "status": nil, }, }, new: &unstructured.Unstructured{ - Object: map[string]interface{}{ + Object: map[string]any{ "status": nil, }, }, @@ -457,13 +457,13 @@ func TestStatusConditionAwareEqual(t *testing.T) { name: "Unstructured: old.status=empty, new.status=empty", args: args{ old: &unstructured.Unstructured{ - Object: map[string]interface{}{ - "status": map[string]interface{}{}, + Object: map[string]any{ + "status": map[string]any{}, }, }, new: &unstructured.Unstructured{ - Object: map[string]interface{}{ - "status": map[string]interface{}{}, + Object: map[string]any{ + "status": map[string]any{}, }, }, }, @@ -473,15 +473,15 @@ func TestStatusConditionAwareEqual(t *testing.T) { name: "Unstructured: old.status=full, new.status=full", args: args{ old: &unstructured.Unstructured{ - Object: map[string]interface{}{ - "status": map[string]interface{}{ + Object: map[string]any{ + "status": map[string]any{ "observedGeneration": 1, }, }, }, new: &unstructured.Unstructured{ - Object: map[string]interface{}{ - "status": map[string]interface{}{ + Object: map[string]any{ + "status": map[string]any{ "observedGeneration": 1, }, }, @@ -493,13 +493,13 @@ func TestStatusConditionAwareEqual(t *testing.T) { name: "Unstructured: old.status=empty, new.status=full", args: args{ old: &unstructured.Unstructured{ - Object: map[string]interface{}{ - "status": map[string]interface{}{}, + Object: map[string]any{ + "status": map[string]any{}, }, }, new: &unstructured.Unstructured{ - Object: map[string]interface{}{ - "status": map[string]interface{}{ + Object: map[string]any{ + "status": map[string]any{ "observedGeneration": 1, }, }, @@ -511,15 +511,15 @@ func TestStatusConditionAwareEqual(t *testing.T) { name: "Unstructured: old.status=full, new.status=empty", args: args{ old: &unstructured.Unstructured{ - Object: map[string]interface{}{ - "status": map[string]interface{}{ + Object: map[string]any{ + "status": map[string]any{ "observedGeneration": 1, }, }, }, new: &unstructured.Unstructured{ - Object: map[string]interface{}{ - "status": map[string]interface{}{}, + Object: map[string]any{ + "status": map[string]any{}, }, }, }, @@ -549,8 +549,8 @@ func toUnstructured(s string) runtime.Object { func TestStatusEqual(t *testing.T) { type args struct { - old interface{} - new interface{} + old any + new any } tests := []struct { name string @@ -705,10 +705,10 @@ func TestStatusEqual(t *testing.T) { name: "Unstructured: old.status=missing, new.status=missing", args: args{ old: &unstructured.Unstructured{ - Object: map[string]interface{}{}, + Object: map[string]any{}, }, new: &unstructured.Unstructured{ - Object: map[string]interface{}{}, + Object: map[string]any{}, }, }, want: true, @@ -717,12 +717,12 @@ func TestStatusEqual(t *testing.T) { name: "Unstructured: old.status=nil, new.status=nil", args: args{ old: &unstructured.Unstructured{ - Object: map[string]interface{}{ + Object: map[string]any{ "status": nil, }, }, new: &unstructured.Unstructured{ - Object: map[string]interface{}{ + Object: map[string]any{ "status": nil, }, }, @@ -733,13 +733,13 @@ func TestStatusEqual(t *testing.T) { name: "Unstructured: old.status=empty, new.status=empty", args: args{ old: &unstructured.Unstructured{ - Object: map[string]interface{}{ - "status": map[string]interface{}{}, + Object: map[string]any{ + "status": map[string]any{}, }, }, new: &unstructured.Unstructured{ - Object: map[string]interface{}{ - "status": map[string]interface{}{}, + Object: map[string]any{ + "status": map[string]any{}, }, }, }, @@ -749,15 +749,15 @@ func TestStatusEqual(t *testing.T) { name: "Unstructured: old.status=full, new.status=full", args: args{ old: &unstructured.Unstructured{ - Object: map[string]interface{}{ - "status": map[string]interface{}{ + Object: map[string]any{ + "status": map[string]any{ "observedGeneration": 1, }, }, }, new: &unstructured.Unstructured{ - Object: map[string]interface{}{ - "status": map[string]interface{}{ + Object: map[string]any{ + "status": map[string]any{ "observedGeneration": 1, }, }, @@ -769,13 +769,13 @@ func TestStatusEqual(t *testing.T) { name: "Unstructured: old.status=empty, new.status=full", args: args{ old: &unstructured.Unstructured{ - Object: map[string]interface{}{ - "status": map[string]interface{}{}, + Object: map[string]any{ + "status": map[string]any{}, }, }, new: &unstructured.Unstructured{ - Object: map[string]interface{}{ - "status": map[string]interface{}{ + Object: map[string]any{ + "status": map[string]any{ "observedGeneration": 1, }, }, @@ -787,15 +787,15 @@ func TestStatusEqual(t *testing.T) { name: "Unstructured: old.status=full, new.status=empty", args: args{ old: &unstructured.Unstructured{ - Object: map[string]interface{}{ - "status": map[string]interface{}{ + Object: map[string]any{ + "status": map[string]any{ "observedGeneration": 1, }, }, }, new: &unstructured.Unstructured{ - Object: map[string]interface{}{ - "status": map[string]interface{}{}, + Object: map[string]any{ + "status": map[string]any{}, }, }, }, diff --git a/tools/backup/manager.go b/tools/backup/manager.go index 77fa336f4..3331404db 100644 --- a/tools/backup/manager.go +++ b/tools/backup/manager.go @@ -48,7 +48,7 @@ const ( ) type ItemList struct { - Items []map[string]interface{} `json:"items,omitempty"` + Items []map[string]any `json:"items,omitempty"` } type BackupManager struct { @@ -112,12 +112,12 @@ func (mgr BackupManager) BackupToTar(backupDir string) (string, error) { if err != nil { return "", err } - defer file.Close() + defer file.Close() // nolint:errcheck // set up the gzip writer gw := gzip.NewWriter(file) - defer gw.Close() + defer gw.Close() // nolint:errcheck tw := tar.NewWriter(gw) - defer tw.Close() + defer tw.Close() // nolint:errcheck p := func(relPath string, data []byte) error { // now lets create the header as needed for this file within the tarball @@ -214,7 +214,7 @@ func (mgr BackupManager) Backup(process processorFunc) error { } } if mgr.sanitize { - if spec, ok := item["spec"].(map[string]interface{}); ok { + if spec, ok := item["spec"].(map[string]any); ok { switch r.Kind { case "Pod": item["spec"], err = cleanUpPodSpec(spec) @@ -222,9 +222,9 @@ func (mgr BackupManager) Backup(process processorFunc) error { return err } case "StatefulSet", "Deployment", "ReplicaSet", "DaemonSet", "ReplicationController", "Job": - template, ok := spec["template"].(map[string]interface{}) + template, ok := spec["template"].(map[string]any) if ok { - podSpec, ok := template["spec"].(map[string]interface{}) + podSpec, ok := template["spec"].(map[string]any) if ok { template["spec"], err = cleanUpPodSpec(podSpec) if err != nil { @@ -250,8 +250,8 @@ func (mgr BackupManager) Backup(process processorFunc) error { return nil } -func cleanUpObjectMeta(md interface{}) { - meta, ok := md.(map[string]interface{}) +func cleanUpObjectMeta(md any) { + meta, ok := md.(map[string]any) if !ok { return } @@ -281,7 +281,7 @@ func cleanUpDecorators(m map[string]string) { delete(m, "pv.kubernetes.io/bound-by-controller") } -func cleanUpPodSpec(in map[string]interface{}) (map[string]interface{}, error) { +func cleanUpPodSpec(in map[string]any) (map[string]any, error) { b, err := yaml.Marshal(in) if err != nil { return nil, err @@ -309,12 +309,12 @@ func cleanUpPodSpec(in map[string]interface{}) (map[string]interface{}, error) { if err != nil { return nil, err } - var out map[string]interface{} + var out map[string]any err = yaml.Unmarshal(b, &out) return out, err } -func getPathFromSelfLink(mapper meta.RESTMapper, obj map[string]interface{}) string { +func getPathFromSelfLink(mapper meta.RESTMapper, obj map[string]any) string { u := unstructured.Unstructured{Object: obj} gvk := u.GetObjectKind().GroupVersionKind() mapping, err := mapper.RESTMapping(gvk.GroupKind(), gvk.Version) diff --git a/tools/converter/lib.go b/tools/converter/lib.go index a5997eeaf..45514043e 100644 --- a/tools/converter/lib.go +++ b/tools/converter/lib.go @@ -30,13 +30,14 @@ import ( ) func Convert(name string, data []byte, format meta.DataFormat) ([]byte, string, error) { - if format == meta.JsonFormat { + switch format { + case meta.JsonFormat: out, err := ylib.ToJSON(data) if err != nil { return nil, "", err } return out, "application/json", nil - } else if format == meta.YAMLFormat { + case meta.YAMLFormat: if hasJSONPrefix(data) { out, err := yaml.JSONToYAML(data) if err != nil { diff --git a/tools/doctor/types.go b/tools/doctor/types.go index 245646127..b38ccdb56 100644 --- a/tools/doctor/types.go +++ b/tools/doctor/types.go @@ -130,7 +130,7 @@ func (c ClusterInfo) Validate() error { { if c.ClientConfig.Insecure { - errs = append(errs, errors.New("Admission webhooks can't be used when kube apiserver is accesible without verifying its TLS certificate (insecure-skip-tls-verify : true).")) + errs = append(errs, errors.New("admission webhooks can't be used when kube apiserver is accesible without verifying its TLS certificate (insecure-skip-tls-verify : true).")) } else { if c.ExtensionServerConfig.ClientCAData == "" { errs = append(errs, errors.Errorf(`"%s/%s" configmap is missing "client-ca-file" key.`, authenticationConfigMapNamespace, authenticationConfigMapName)) diff --git a/tools/exec/lib.go b/tools/exec/lib.go index 497f55e26..49f8d052c 100644 --- a/tools/exec/lib.go +++ b/tools/exec/lib.go @@ -33,7 +33,7 @@ import ( "k8s.io/client-go/tools/remotecommand" ) -var NotRunning = errors.New("container not running") +var ErrNotRunning = errors.New("container not running") type Options struct { core.PodExecOptions @@ -68,7 +68,7 @@ func Input(in string) func(*Options) { func TTY(enable bool) func(*Options) { return func(opts *Options) { - opts.PodExecOptions.TTY = enable + opts.TTY = enable } } @@ -121,16 +121,16 @@ func execIntoPod(ctx context.Context, config *rest.Config, kc kubernetes.Interfa if opts.CheckForRunningContainer { for _, status := range pod.Status.ContainerStatuses { - if status.Name == opts.PodExecOptions.Container { + if status.Name == opts.Container { if status.State.Running == nil { - return "", NotRunning + return "", ErrNotRunning } } } for _, status := range pod.Status.InitContainerStatuses { - if status.Name == opts.PodExecOptions.Container { + if status.Name == opts.Container { if status.State.Running == nil { - return "", NotRunning + return "", ErrNotRunning } } } diff --git a/tools/fsnotify/lib.go b/tools/fsnotify/lib.go index 73dfaa08a..fd481b273 100644 --- a/tools/fsnotify/lib.go +++ b/tools/fsnotify/lib.go @@ -44,7 +44,7 @@ func (w *Watcher) Run(stopCh <-chan struct{}) error { } go func() { <-stopCh - defer watcher.Close() + defer watcher.Close() // nolint:errcheck }() go func() { diff --git a/tools/portforward/tunnel.go b/tools/portforward/tunnel.go index 897a94559..13411722b 100644 --- a/tools/portforward/tunnel.go +++ b/tools/portforward/tunnel.go @@ -136,7 +136,7 @@ func getAvailablePort(preferredPort int) (int, error) { if err != nil { return 0, err } - defer l.Close() + defer l.Close() // nolint:errcheck _, p, err := net.SplitHostPort(l.Addr().String()) if err != nil { diff --git a/tools/queue/handler.go b/tools/queue/handler.go index e917b1c28..d69b34568 100644 --- a/tools/queue/handler.go +++ b/tools/queue/handler.go @@ -66,8 +66,8 @@ func logLevel(apiGroup string) klog.Level { // QueueingEventHandler queues the key for the object on add and update events type QueueingEventHandler struct { queue workqueue.TypedRateLimitingInterface[any] - enqueueAdd func(obj interface{}) bool - enqueueUpdate func(oldObj, newObj interface{}) bool + enqueueAdd func(obj any) bool + enqueueUpdate func(oldObj, newObj any) bool enqueueDelete bool restrictToNamespace string } @@ -84,7 +84,7 @@ func DefaultEventHandler(queue workqueue.TypedRateLimitingInterface[any], restri } } -func NewEventHandler(queue workqueue.TypedRateLimitingInterface[any], enqueueUpdate func(oldObj, newObj interface{}) bool, restrictToNamespace string) cache.ResourceEventHandler { +func NewEventHandler(queue workqueue.TypedRateLimitingInterface[any], enqueueUpdate func(oldObj, newObj any) bool, restrictToNamespace string) cache.ResourceEventHandler { return &QueueingEventHandler{ queue: queue, enqueueAdd: nil, @@ -107,8 +107,8 @@ func NewUpsertHandler(queue workqueue.TypedRateLimitingInterface[any], restrictT func NewDeleteHandler(queue workqueue.TypedRateLimitingInterface[any], restrictToNamespace string) cache.ResourceEventHandler { return &QueueingEventHandler{ queue: queue, - enqueueAdd: func(_ interface{}) bool { return false }, - enqueueUpdate: func(_, _ interface{}) bool { return false }, + enqueueAdd: func(_ any) bool { return false }, + enqueueUpdate: func(_, _ any) bool { return false }, enqueueDelete: true, restrictToNamespace: restrictToNamespace, } @@ -117,10 +117,10 @@ func NewDeleteHandler(queue workqueue.TypedRateLimitingInterface[any], restrictT func NewReconcilableHandler(queue workqueue.TypedRateLimitingInterface[any], restrictToNamespace string) cache.ResourceEventHandler { return &QueueingEventHandler{ queue: queue, - enqueueAdd: func(o interface{}) bool { + enqueueAdd: func(o any) bool { return !meta_util.MustAlreadyReconciled(o) }, - enqueueUpdate: func(old, nu interface{}) bool { + enqueueUpdate: func(old, nu any) bool { return (nu.(metav1.Object)).GetDeletionTimestamp() != nil || !meta_util.MustAlreadyReconciled(nu) }, enqueueDelete: true, @@ -132,7 +132,7 @@ func NewChangeHandler(queue workqueue.TypedRateLimitingInterface[any], restrictT return &QueueingEventHandler{ queue: queue, enqueueAdd: nil, - enqueueUpdate: func(old, nu interface{}) bool { + enqueueUpdate: func(old, nu any) bool { oldObj := old.(metav1.Object) nuObj := nu.(metav1.Object) return nuObj.GetDeletionTimestamp() != nil || @@ -150,7 +150,7 @@ func NewSpecStatusChangeHandler(queue workqueue.TypedRateLimitingInterface[any], return &QueueingEventHandler{ queue: queue, enqueueAdd: nil, - enqueueUpdate: func(old, nu interface{}) bool { + enqueueUpdate: func(old, nu any) bool { nuObj := nu.(metav1.Object) return nuObj.GetDeletionTimestamp() != nil || !meta_util.MustAlreadyReconciled(nu) || @@ -161,7 +161,7 @@ func NewSpecStatusChangeHandler(queue workqueue.TypedRateLimitingInterface[any], } } -func Enqueue(queue workqueue.TypedRateLimitingInterface[any], obj interface{}) { +func Enqueue(queue workqueue.TypedRateLimitingInterface[any], obj any) { key, err := cache.DeletionHandlingMetaNamespaceKeyFunc(obj) if err != nil { klog.Errorf("Couldn't get key for object %+v: %v", obj, err) @@ -170,7 +170,7 @@ func Enqueue(queue workqueue.TypedRateLimitingInterface[any], obj interface{}) { queue.Add(key) } -func EnqueueAfter(queue workqueue.TypedRateLimitingInterface[any], obj interface{}, duration time.Duration) { +func EnqueueAfter(queue workqueue.TypedRateLimitingInterface[any], obj any, duration time.Duration) { key, err := cache.DeletionHandlingMetaNamespaceKeyFunc(obj) if err != nil { klog.Errorf("Couldn't get key for object %+v: %v", obj, err) @@ -179,7 +179,7 @@ func EnqueueAfter(queue workqueue.TypedRateLimitingInterface[any], obj interface queue.AddAfter(key, duration) } -func (h *QueueingEventHandler) OnAdd(obj interface{}, isInInitialList bool) { +func (h *QueueingEventHandler) OnAdd(obj any, isInInitialList bool) { klog.V(6).Infof("Add event for %+v\n", obj) if h.enqueueAdd == nil || h.enqueueAdd(obj) { if h.restrictToNamespace != core.NamespaceAll { @@ -202,7 +202,7 @@ func (h *QueueingEventHandler) OnAdd(obj interface{}, isInInitialList bool) { } } -func (h *QueueingEventHandler) OnUpdate(oldObj, newObj interface{}) { +func (h *QueueingEventHandler) OnUpdate(oldObj, newObj any) { klog.V(6).Infof("Update event for %+v\n", newObj) if h.enqueueUpdate == nil || h.enqueueUpdate(oldObj, newObj) { if h.restrictToNamespace != core.NamespaceAll { @@ -225,7 +225,7 @@ func (h *QueueingEventHandler) OnUpdate(oldObj, newObj interface{}) { } } -func (h *QueueingEventHandler) OnDelete(obj interface{}) { +func (h *QueueingEventHandler) OnDelete(obj any) { klog.V(6).Infof("Delete event for %+v\n", obj) if h.enqueueDelete { if h.restrictToNamespace != core.NamespaceAll { @@ -270,7 +270,7 @@ type versionedEventHandler struct { gvk schema.GroupVersionKind } -func (w versionedEventHandler) setGroupVersionKind(obj interface{}) interface{} { +func (w versionedEventHandler) setGroupVersionKind(obj any) any { if r, ok := obj.(runtime.Object); ok { r = r.DeepCopyObject() r.GetObjectKind().SetGroupVersionKind(w.gvk) @@ -279,15 +279,15 @@ func (w versionedEventHandler) setGroupVersionKind(obj interface{}) interface{} return obj } -func (w versionedEventHandler) OnAdd(obj interface{}, isInInitialList bool) { +func (w versionedEventHandler) OnAdd(obj any, isInInitialList bool) { w.inner.OnAdd(w.setGroupVersionKind(obj), isInInitialList) } -func (w versionedEventHandler) OnUpdate(oldObj, newObj interface{}) { +func (w versionedEventHandler) OnUpdate(oldObj, newObj any) { w.inner.OnUpdate(w.setGroupVersionKind(oldObj), w.setGroupVersionKind(newObj)) } -func (w versionedEventHandler) OnDelete(obj interface{}) { +func (w versionedEventHandler) OnDelete(obj any) { w.inner.OnDelete(w.setGroupVersionKind(obj)) } @@ -302,24 +302,24 @@ type filteredEventHandler struct { sel labels.Selector } -func (w filteredEventHandler) matches(obj interface{}) bool { +func (w filteredEventHandler) matches(obj any) bool { accessor, err := meta.Accessor(obj) return err == nil && w.sel.Matches(labels.Set(accessor.GetLabels())) } -func (w filteredEventHandler) OnAdd(obj interface{}, isInInitialList bool) { +func (w filteredEventHandler) OnAdd(obj any, isInInitialList bool) { if w.matches(obj) { w.inner.OnAdd(obj, isInInitialList) } } -func (w filteredEventHandler) OnUpdate(oldObj, newObj interface{}) { +func (w filteredEventHandler) OnUpdate(oldObj, newObj any) { if w.matches(oldObj) && w.matches(newObj) { w.inner.OnUpdate(oldObj, newObj) } } -func (w filteredEventHandler) OnDelete(obj interface{}) { +func (w filteredEventHandler) OnDelete(obj any) { if w.matches(obj) { w.inner.OnDelete(obj) } diff --git a/tools/wait/wait.go b/tools/wait/wait.go index 01d7691c6..c5a843a4e 100644 --- a/tools/wait/wait.go +++ b/tools/wait/wait.go @@ -222,7 +222,7 @@ func (w Wait) IsDeleted(event watch.Event) (bool, error) { // keep waiting in the event we see an error - we expect the watch to be closed by // the server if the error is unrecoverable. err := apierrors.FromObject(event.Object) - fmt.Fprintf(w.errOut, "error: An error occurred while waiting for the object to be deleted: %v", err) + _, _ = fmt.Fprintf(w.errOut, "error: An error occurred while waiting for the object to be deleted: %v", err) return false, nil case watch.Deleted: return true, nil @@ -314,7 +314,7 @@ func (w ConditionalWait) checkCondition(obj *unstructured.Unstructured) (bool, e return false, nil } for _, conditionUncast := range conditions { - condition := conditionUncast.(map[string]interface{}) + condition := conditionUncast.(map[string]any) name, found, err := unstructured.NestedString(condition, "type") if !found || err != nil || !strings.EqualFold(name, w.conditionName) { continue @@ -334,7 +334,7 @@ func (w ConditionalWait) isConditionMet(event watch.Event) (bool, error) { // keep waiting in the event we see an error - we expect the watch to be closed by // the server err := apierrors.FromObject(event.Object) - fmt.Fprintf(w.errOut, "error: An error occurred while waiting for the condition to be satisfied: %v", err) + _, _ = fmt.Fprintf(w.errOut, "error: An error occurred while waiting for the condition to be satisfied: %v", err) return false, nil } if event.Type == watch.Deleted { diff --git a/tools/wait/wait_test.go b/tools/wait/wait_test.go index 162d0724c..fb7f247c9 100644 --- a/tools/wait/wait_test.go +++ b/tools/wait/wait_test.go @@ -49,10 +49,10 @@ func newUnstructuredList(items ...*unstructured.Unstructured) *unstructured.Unst func newUnstructured(apiVersion, kind, namespace, name string) *unstructured.Unstructured { return &unstructured.Unstructured{ - Object: map[string]interface{}{ + Object: map[string]any{ "apiVersion": apiVersion, "kind": kind, - "metadata": map[string]interface{}{ + "metadata": map[string]any{ "namespace": namespace, "name": name, "uid": "some-UID-value", @@ -73,7 +73,7 @@ func newUnstructuredStatus(status *metav1.Status) runtime.Unstructured { func addCondition(in *unstructured.Unstructured, name, status string) *unstructured.Unstructured { conditions, _, _ := unstructured.NestedSlice(in.Object, "status", "conditions") - conditions = append(conditions, map[string]interface{}{ + conditions = append(conditions, map[string]any{ "type": name, "status": status, })