diff --git a/bake/bake.go b/bake/bake.go index d49c7a338db5..5cb6c7564dfc 100644 --- a/bake/bake.go +++ b/bake/bake.go @@ -486,10 +486,8 @@ func (c Config) loadLinks(name string, t *Target, m map[string]*Target, o map[st if target == name { return errors.Errorf("target %s cannot link to itself", target) } - for _, v := range visited { - if v == target { - return errors.Errorf("infinite loop from %s to %s", name, target) - } + if slices.Contains(visited, target) { + return errors.Errorf("infinite loop from %s to %s", name, target) } t2, ok := m[target] if !ok { diff --git a/bake/compose.go b/bake/compose.go index fba1f3de2836..87cd5fa3c1e2 100644 --- a/bake/compose.go +++ b/bake/compose.go @@ -315,7 +315,7 @@ type ( stringArray []string ) -func (sa *stringArray) UnmarshalYAML(unmarshal func(interface{}) error) error { +func (sa *stringArray) UnmarshalYAML(unmarshal func(any) error) error { var multi []string err := unmarshal(&multi) if err != nil { @@ -332,7 +332,7 @@ func (sa *stringArray) UnmarshalYAML(unmarshal func(interface{}) error) error { // composeExtTarget converts Compose build extension x-bake to bake Target // https://github.com/compose-spec/compose-spec/blob/master/spec.md#extension -func (t *Target) composeExtTarget(exts map[string]interface{}) error { +func (t *Target) composeExtTarget(exts map[string]any) error { var xb xbake ext, ok := exts["x-bake"] diff --git a/bake/entitlements.go b/bake/entitlements.go index 389d0dd9772f..bd93a7f34069 100644 --- a/bake/entitlements.go +++ b/bake/entitlements.go @@ -306,7 +306,7 @@ func (c EntitlementConf) Prompt(ctx context.Context, isRemote bool, out io.Write fmt.Fprintf(out, "\nPass %q to grant requested privileges.\n", strings.Join(slices.Concat(flags, flagsFS), " ")) } - args := append([]string(nil), os.Args...) + args := slices.Clone(os.Args) if v, ok := os.LookupEnv("DOCKER_CLI_PLUGIN_ORIGINAL_CLI_COMMAND"); ok && v != "" { args[0] = v } diff --git a/bake/hcl_test.go b/bake/hcl_test.go index 7ee8a259669e..5f899544fe5d 100644 --- a/bake/hcl_test.go +++ b/bake/hcl_test.go @@ -1645,7 +1645,7 @@ func TestHCLIndexOfFunc(t *testing.T) { require.Empty(t, c.Targets[1].Tags[1]) } -func ptrstr(s interface{}) *string { +func ptrstr(s any) *string { var n *string if reflect.ValueOf(s).Kind() == reflect.String { ss := s.(string) diff --git a/bake/hclparser/gohcl/decode.go b/bake/hclparser/gohcl/decode.go index a8aa20e3ba22..9f73a59bc3ba 100644 --- a/bake/hclparser/gohcl/decode.go +++ b/bake/hclparser/gohcl/decode.go @@ -15,11 +15,11 @@ import ( // DecodeOptions allows customizing sections of the decoding process. type DecodeOptions struct { - ImpliedType func(gv interface{}) (cty.Type, error) + ImpliedType func(gv any) (cty.Type, error) Convert func(in cty.Value, want cty.Type) (cty.Value, error) } -func (o DecodeOptions) DecodeBody(body hcl.Body, ctx *hcl.EvalContext, val interface{}) hcl.Diagnostics { +func (o DecodeOptions) DecodeBody(body hcl.Body, ctx *hcl.EvalContext, val any) hcl.Diagnostics { o = o.withDefaults() rv := reflect.ValueOf(val) @@ -46,7 +46,7 @@ func (o DecodeOptions) DecodeBody(body hcl.Body, ctx *hcl.EvalContext, val inter // are returned then the given value may have been partially-populated but // may still be accessed by a careful caller for static analysis and editor // integration use-cases. -func DecodeBody(body hcl.Body, ctx *hcl.EvalContext, val interface{}) hcl.Diagnostics { +func DecodeBody(body hcl.Body, ctx *hcl.EvalContext, val any) hcl.Diagnostics { return DecodeOptions{}.DecodeBody(body, ctx, val) } @@ -282,7 +282,7 @@ func (o DecodeOptions) decodeBlockToValue(block *hcl.Block, ctx *hcl.EvalContext return diags } -func (o DecodeOptions) DecodeExpression(expr hcl.Expression, ctx *hcl.EvalContext, val interface{}) hcl.Diagnostics { +func (o DecodeOptions) DecodeExpression(expr hcl.Expression, ctx *hcl.EvalContext, val any) hcl.Diagnostics { o = o.withDefaults() srcVal, diags := expr.Value(ctx) @@ -332,7 +332,7 @@ func (o DecodeOptions) DecodeExpression(expr hcl.Expression, ctx *hcl.EvalContex // are returned then the given value may have been partially-populated but // may still be accessed by a careful caller for static analysis and editor // integration use-cases. -func DecodeExpression(expr hcl.Expression, ctx *hcl.EvalContext, val interface{}) hcl.Diagnostics { +func DecodeExpression(expr hcl.Expression, ctx *hcl.EvalContext, val any) hcl.Diagnostics { return DecodeOptions{}.DecodeExpression(expr, ctx, val) } diff --git a/bake/hclparser/gohcl/decode_test.go b/bake/hclparser/gohcl/decode_test.go index 7130a2c87b7a..a532c69a3887 100644 --- a/bake/hclparser/gohcl/decode_test.go +++ b/bake/hclparser/gohcl/decode_test.go @@ -16,8 +16,8 @@ import ( ) func TestDecodeBody(t *testing.T) { - deepEquals := func(other interface{}) func(v interface{}) bool { - return func(v interface{}) bool { + deepEquals := func(other any) func(v any) bool { + return func(v any) bool { return reflect.DeepEqual(v, other) } } @@ -45,19 +45,19 @@ func TestDecodeBody(t *testing.T) { } tests := []struct { - Body map[string]interface{} - Target func() interface{} - Check func(v interface{}) bool + Body map[string]any + Target func() any + Check func(v any) bool DiagCount int }{ { - map[string]interface{}{}, + map[string]any{}, makeInstantiateType(struct{}{}), deepEquals(struct{}{}), 0, }, { - map[string]interface{}{}, + map[string]any{}, makeInstantiateType(struct { Name string `hcl:"name"` }{}), @@ -67,7 +67,7 @@ func TestDecodeBody(t *testing.T) { 1, // name is required }, { - map[string]interface{}{}, + map[string]any{}, makeInstantiateType(struct { Name *string `hcl:"name"` }{}), @@ -77,7 +77,7 @@ func TestDecodeBody(t *testing.T) { 0, }, // name nil { - map[string]interface{}{}, + map[string]any{}, makeInstantiateType(struct { Name string `hcl:"name,optional"` }{}), @@ -87,9 +87,9 @@ func TestDecodeBody(t *testing.T) { 0, }, // name optional { - map[string]interface{}{}, + map[string]any{}, makeInstantiateType(withNameExpression{}), - func(v interface{}) bool { + func(v any) bool { if v == nil { return false } @@ -109,11 +109,11 @@ func TestDecodeBody(t *testing.T) { 0, }, { - map[string]interface{}{ + map[string]any{ "name": "Ermintrude", }, makeInstantiateType(withNameExpression{}), - func(v interface{}) bool { + func(v any) bool { if v == nil { return false } @@ -133,7 +133,7 @@ func TestDecodeBody(t *testing.T) { 0, }, { - map[string]interface{}{ + map[string]any{ "name": "Ermintrude", }, makeInstantiateType(struct { @@ -145,7 +145,7 @@ func TestDecodeBody(t *testing.T) { 0, }, { - map[string]interface{}{ + map[string]any{ "name": "Ermintrude", "age": 23, }, @@ -158,7 +158,7 @@ func TestDecodeBody(t *testing.T) { 1, // Extraneous "age" property }, { - map[string]interface{}{ + map[string]any{ "name": "Ermintrude", "age": 50, }, @@ -166,7 +166,7 @@ func TestDecodeBody(t *testing.T) { Name string `hcl:"name"` Attrs hcl.Attributes `hcl:",remain"` }{}), - func(gotI interface{}) bool { + func(gotI any) bool { got := gotI.(struct { Name string `hcl:"name"` Attrs hcl.Attributes `hcl:",remain"` @@ -176,7 +176,7 @@ func TestDecodeBody(t *testing.T) { 0, }, { - map[string]interface{}{ + map[string]any{ "name": "Ermintrude", "age": 50, }, @@ -184,7 +184,7 @@ func TestDecodeBody(t *testing.T) { Name string `hcl:"name"` Remain hcl.Body `hcl:",remain"` }{}), - func(gotI interface{}) bool { + func(gotI any) bool { got := gotI.(struct { Name string `hcl:"name"` Remain hcl.Body `hcl:",remain"` @@ -197,7 +197,7 @@ func TestDecodeBody(t *testing.T) { 0, }, { - map[string]interface{}{ + map[string]any{ "name": "Ermintrude", "living": true, }, @@ -217,7 +217,7 @@ func TestDecodeBody(t *testing.T) { 0, }, { - map[string]interface{}{ + map[string]any{ "name": "Ermintrude", "age": 50, }, @@ -226,7 +226,7 @@ func TestDecodeBody(t *testing.T) { Body hcl.Body `hcl:",body"` Remain hcl.Body `hcl:",remain"` }{}), - func(gotI interface{}) bool { + func(gotI any) bool { got := gotI.(struct { Name string `hcl:"name"` Body hcl.Body `hcl:",body"` @@ -241,76 +241,76 @@ func TestDecodeBody(t *testing.T) { 0, }, { - map[string]interface{}{ - "noodle": map[string]interface{}{}, + map[string]any{ + "noodle": map[string]any{}, }, makeInstantiateType(struct { Noodle struct{} `hcl:"noodle,block"` }{}), - func(gotI interface{}) bool { + func(gotI any) bool { // Generating no diagnostics is good enough for this one. return true }, 0, }, { - map[string]interface{}{ - "noodle": []map[string]interface{}{{}}, + map[string]any{ + "noodle": []map[string]any{{}}, }, makeInstantiateType(struct { Noodle struct{} `hcl:"noodle,block"` }{}), - func(gotI interface{}) bool { + func(gotI any) bool { // Generating no diagnostics is good enough for this one. return true }, 0, }, { - map[string]interface{}{ - "noodle": []map[string]interface{}{{}, {}}, + map[string]any{ + "noodle": []map[string]any{{}, {}}, }, makeInstantiateType(struct { Noodle struct{} `hcl:"noodle,block"` }{}), - func(gotI interface{}) bool { + func(gotI any) bool { // Generating one diagnostic is good enough for this one. return true }, 1, }, { - map[string]interface{}{}, + map[string]any{}, makeInstantiateType(struct { Noodle struct{} `hcl:"noodle,block"` }{}), - func(gotI interface{}) bool { + func(gotI any) bool { // Generating one diagnostic is good enough for this one. return true }, 1, }, { - map[string]interface{}{ - "noodle": []map[string]interface{}{}, + map[string]any{ + "noodle": []map[string]any{}, }, makeInstantiateType(struct { Noodle struct{} `hcl:"noodle,block"` }{}), - func(gotI interface{}) bool { + func(gotI any) bool { // Generating one diagnostic is good enough for this one. return true }, 1, }, { - map[string]interface{}{ - "noodle": map[string]interface{}{}, + map[string]any{ + "noodle": map[string]any{}, }, makeInstantiateType(struct { Noodle *struct{} `hcl:"noodle,block"` }{}), - func(gotI interface{}) bool { + func(gotI any) bool { return gotI.(struct { Noodle *struct{} `hcl:"noodle,block"` }).Noodle != nil @@ -318,13 +318,13 @@ func TestDecodeBody(t *testing.T) { 0, }, { - map[string]interface{}{ - "noodle": []map[string]interface{}{{}}, + map[string]any{ + "noodle": []map[string]any{{}}, }, makeInstantiateType(struct { Noodle *struct{} `hcl:"noodle,block"` }{}), - func(gotI interface{}) bool { + func(gotI any) bool { return gotI.(struct { Noodle *struct{} `hcl:"noodle,block"` }).Noodle != nil @@ -332,13 +332,13 @@ func TestDecodeBody(t *testing.T) { 0, }, { - map[string]interface{}{ - "noodle": []map[string]interface{}{}, + map[string]any{ + "noodle": []map[string]any{}, }, makeInstantiateType(struct { Noodle *struct{} `hcl:"noodle,block"` }{}), - func(gotI interface{}) bool { + func(gotI any) bool { return gotI.(struct { Noodle *struct{} `hcl:"noodle,block"` }).Noodle == nil @@ -346,26 +346,26 @@ func TestDecodeBody(t *testing.T) { 0, }, { - map[string]interface{}{ - "noodle": []map[string]interface{}{{}, {}}, + map[string]any{ + "noodle": []map[string]any{{}, {}}, }, makeInstantiateType(struct { Noodle *struct{} `hcl:"noodle,block"` }{}), - func(gotI interface{}) bool { + func(gotI any) bool { // Generating one diagnostic is good enough for this one. return true }, 1, }, { - map[string]interface{}{ - "noodle": []map[string]interface{}{}, + map[string]any{ + "noodle": []map[string]any{}, }, makeInstantiateType(struct { Noodle []struct{} `hcl:"noodle,block"` }{}), - func(gotI interface{}) bool { + func(gotI any) bool { noodle := gotI.(struct { Noodle []struct{} `hcl:"noodle,block"` }).Noodle @@ -374,13 +374,13 @@ func TestDecodeBody(t *testing.T) { 0, }, { - map[string]interface{}{ - "noodle": []map[string]interface{}{{}}, + map[string]any{ + "noodle": []map[string]any{{}}, }, makeInstantiateType(struct { Noodle []struct{} `hcl:"noodle,block"` }{}), - func(gotI interface{}) bool { + func(gotI any) bool { noodle := gotI.(struct { Noodle []struct{} `hcl:"noodle,block"` }).Noodle @@ -389,13 +389,13 @@ func TestDecodeBody(t *testing.T) { 0, }, { - map[string]interface{}{ - "noodle": []map[string]interface{}{{}, {}}, + map[string]any{ + "noodle": []map[string]any{{}, {}}, }, makeInstantiateType(struct { Noodle []struct{} `hcl:"noodle,block"` }{}), - func(gotI interface{}) bool { + func(gotI any) bool { noodle := gotI.(struct { Noodle []struct{} `hcl:"noodle,block"` }).Noodle @@ -404,15 +404,15 @@ func TestDecodeBody(t *testing.T) { 0, }, { - map[string]interface{}{ - "noodle": map[string]interface{}{}, + map[string]any{ + "noodle": map[string]any{}, }, makeInstantiateType(struct { Noodle struct { Name string `hcl:"name,label"` } `hcl:"noodle,block"` }{}), - func(gotI interface{}) bool { + func(gotI any) bool { //nolint:misspell // Generating two diagnostics is good enough for this one. // (one for the missing noodle block and the other for @@ -423,9 +423,9 @@ func TestDecodeBody(t *testing.T) { 2, }, { - map[string]interface{}{ - "noodle": map[string]interface{}{ - "foo_foo": map[string]interface{}{}, + map[string]any{ + "noodle": map[string]any{ + "foo_foo": map[string]any{}, }, }, makeInstantiateType(struct { @@ -433,7 +433,7 @@ func TestDecodeBody(t *testing.T) { Name string `hcl:"name,label"` } `hcl:"noodle,block"` }{}), - func(gotI interface{}) bool { + func(gotI any) bool { noodle := gotI.(struct { Noodle struct { Name string `hcl:"name,label"` @@ -444,10 +444,10 @@ func TestDecodeBody(t *testing.T) { 0, }, { - map[string]interface{}{ - "noodle": map[string]interface{}{ - "foo_foo": map[string]interface{}{}, - "bar_baz": map[string]interface{}{}, + map[string]any{ + "noodle": map[string]any{ + "foo_foo": map[string]any{}, + "bar_baz": map[string]any{}, }, }, makeInstantiateType(struct { @@ -455,17 +455,17 @@ func TestDecodeBody(t *testing.T) { Name string `hcl:"name,label"` } `hcl:"noodle,block"` }{}), - func(gotI interface{}) bool { + func(gotI any) bool { // One diagnostic is enough for this one. return true }, 1, }, { - map[string]interface{}{ - "noodle": map[string]interface{}{ - "foo_foo": map[string]interface{}{}, - "bar_baz": map[string]interface{}{}, + map[string]any{ + "noodle": map[string]any{ + "foo_foo": map[string]any{}, + "bar_baz": map[string]any{}, }, }, makeInstantiateType(struct { @@ -473,7 +473,7 @@ func TestDecodeBody(t *testing.T) { Name string `hcl:"name,label"` } `hcl:"noodle,block"` }{}), - func(gotI interface{}) bool { + func(gotI any) bool { noodles := gotI.(struct { Noodles []struct { Name string `hcl:"name,label"` @@ -484,9 +484,9 @@ func TestDecodeBody(t *testing.T) { 0, }, { - map[string]interface{}{ - "noodle": map[string]interface{}{ - "foo_foo": map[string]interface{}{ + map[string]any{ + "noodle": map[string]any{ + "foo_foo": map[string]any{ "type": "rice", }, }, @@ -497,7 +497,7 @@ func TestDecodeBody(t *testing.T) { Type string `hcl:"type"` } `hcl:"noodle,block"` }{}), - func(gotI interface{}) bool { + func(gotI any) bool { noodle := gotI.(struct { Noodle struct { Name string `hcl:"name,label"` @@ -510,7 +510,7 @@ func TestDecodeBody(t *testing.T) { }, { - map[string]interface{}{ + map[string]any{ "name": "Ermintrude", "age": 34, }, @@ -522,31 +522,31 @@ func TestDecodeBody(t *testing.T) { 0, }, { - map[string]interface{}{ + map[string]any{ "name": "Ermintrude", "age": 89, }, makeInstantiateType(map[string]*hcl.Attribute(nil)), - func(gotI interface{}) bool { + func(gotI any) bool { got := gotI.(map[string]*hcl.Attribute) return len(got) == 2 && got["name"] != nil && got["age"] != nil }, 0, }, { - map[string]interface{}{ + map[string]any{ "name": "Ermintrude", "age": 13, }, makeInstantiateType(map[string]hcl.Expression(nil)), - func(gotI interface{}) bool { + func(gotI any) bool { got := gotI.(map[string]hcl.Expression) return len(got) == 2 && got["name"] != nil && got["age"] != nil }, 0, }, { - map[string]interface{}{ + map[string]any{ "name": "Ermintrude", "living": true, }, @@ -559,10 +559,10 @@ func TestDecodeBody(t *testing.T) { }, { // Retain "nested" block while decoding - map[string]interface{}{ + map[string]any{ "plain": "foo", }, - func() interface{} { + func() any { return &withNestedBlock{ Plain: "bar", Nested: &withTwoAttributes{ @@ -570,7 +570,7 @@ func TestDecodeBody(t *testing.T) { }, } }, - func(gotI interface{}) bool { + func(gotI any) bool { foo := gotI.(withNestedBlock) return foo.Plain == "foo" && foo.Nested != nil && foo.Nested.A == "bar" }, @@ -578,19 +578,19 @@ func TestDecodeBody(t *testing.T) { }, { // Retain values in "nested" block while decoding - map[string]interface{}{ - "nested": map[string]interface{}{ + map[string]any{ + "nested": map[string]any{ "a": "foo", }, }, - func() interface{} { + func() any { return &withNestedBlock{ Nested: &withTwoAttributes{ B: "bar", }, } }, - func(gotI interface{}) bool { + func(gotI any) bool { foo := gotI.(withNestedBlock) return foo.Nested.A == "foo" && foo.Nested.B == "bar" }, @@ -598,14 +598,14 @@ func TestDecodeBody(t *testing.T) { }, { // Retain values in "nested" block list while decoding - map[string]interface{}{ - "nested": []map[string]interface{}{ + map[string]any{ + "nested": []map[string]any{ { "a": "foo", }, }, }, - func() interface{} { + func() any { return &withListofNestedBlocks{ Nested: []*withTwoAttributes{ { @@ -614,7 +614,7 @@ func TestDecodeBody(t *testing.T) { }, } }, - func(gotI interface{}) bool { + func(gotI any) bool { n := gotI.(withListofNestedBlocks) return n.Nested[0].A == "foo" && n.Nested[0].B == "bar" }, @@ -622,14 +622,14 @@ func TestDecodeBody(t *testing.T) { }, { // Remove additional elements from the list while decoding nested blocks - map[string]interface{}{ - "nested": []map[string]interface{}{ + map[string]any{ + "nested": []map[string]any{ { "a": "foo", }, }, }, - func() interface{} { + func() any { return &withListofNestedBlocks{ Nested: []*withTwoAttributes{ { @@ -641,7 +641,7 @@ func TestDecodeBody(t *testing.T) { }, } }, - func(gotI interface{}) bool { + func(gotI any) bool { n := gotI.(withListofNestedBlocks) return len(n.Nested) == 1 }, @@ -649,8 +649,8 @@ func TestDecodeBody(t *testing.T) { }, { // Make sure decoding value slices works the same as pointer slices. - map[string]interface{}{ - "nested": []map[string]interface{}{ + map[string]any{ + "nested": []map[string]any{ { "b": "bar", }, @@ -659,7 +659,7 @@ func TestDecodeBody(t *testing.T) { }, }, }, - func() interface{} { + func() any { return &withListofNestedBlocksNoPointers{ Nested: []withTwoAttributes{ { @@ -668,7 +668,7 @@ func TestDecodeBody(t *testing.T) { }, } }, - func(gotI interface{}) bool { + func(gotI any) bool { n := gotI.(withListofNestedBlocksNoPointers) return n.Nested[0].B == "bar" && len(n.Nested) == 2 }, @@ -710,8 +710,8 @@ func TestDecodeBody(t *testing.T) { func TestDecodeExpression(t *testing.T) { tests := []struct { Value cty.Value - Target interface{} - Want interface{} + Target any + Want any DiagCount int }{ { @@ -799,8 +799,8 @@ func (e *fixedExpression) Variables() []hcl.Traversal { return nil } -func makeInstantiateType(target interface{}) func() interface{} { - return func() interface{} { +func makeInstantiateType(target any) func() any { + return func() any { return reflect.New(reflect.TypeOf(target)).Interface() } } diff --git a/bake/hclparser/gohcl/encode.go b/bake/hclparser/gohcl/encode.go index 917cda965967..2d509072aa4e 100644 --- a/bake/hclparser/gohcl/encode.go +++ b/bake/hclparser/gohcl/encode.go @@ -36,7 +36,7 @@ import ( // Fields representing attributes should usually precede those representing // blocks so that the attributes can group together in the result. For more // control, use the hclwrite API directly. -func EncodeIntoBody(val interface{}, dst *hclwrite.Body) { +func EncodeIntoBody(val any, dst *hclwrite.Body) { rv := reflect.ValueOf(val) ty := rv.Type() if ty.Kind() == reflect.Ptr { @@ -60,7 +60,7 @@ func EncodeIntoBody(val interface{}, dst *hclwrite.Body) { // // This function has the same constraints as EncodeIntoBody and will panic // if they are violated. -func EncodeAsBlock(val interface{}, blockType string) *hclwrite.Block { +func EncodeAsBlock(val any, blockType string) *hclwrite.Block { rv := reflect.ValueOf(val) ty := rv.Type() if ty.Kind() == reflect.Ptr { @@ -158,7 +158,7 @@ func populateBody(rv reflect.Value, ty reflect.Type, tags *fieldTags, dst *hclwr if isSeq { l := fieldVal.Len() - for i := 0; i < l; i++ { + for i := range l { elemVal := fieldVal.Index(i) if !elemVal.IsValid() { continue // ignore (elem value is nil pointer) diff --git a/bake/hclparser/gohcl/schema.go b/bake/hclparser/gohcl/schema.go index 0c9ab5f31d51..53f678a72ab7 100644 --- a/bake/hclparser/gohcl/schema.go +++ b/bake/hclparser/gohcl/schema.go @@ -22,7 +22,7 @@ import ( // This uses the tags on the fields of the struct to discover how each // field's value should be expressed within configuration. If an invalid // mapping is attempted, this function will panic. -func ImpliedBodySchema(val interface{}) (schema *hcl.BodySchema, partial bool) { +func ImpliedBodySchema(val any) (schema *hcl.BodySchema, partial bool) { ty := reflect.TypeOf(val) if ty.Kind() == reflect.Ptr { @@ -134,7 +134,7 @@ func getFieldTags(ty reflect.Type) *fieldTags { } ct := ty.NumField() - for i := 0; i < ct; i++ { + for i := range ct { field := ty.Field(i) tag := field.Tag.Get("hcl") if tag == "" { diff --git a/bake/hclparser/gohcl/schema_test.go b/bake/hclparser/gohcl/schema_test.go index ca8c0ec1588f..acae420f0b09 100644 --- a/bake/hclparser/gohcl/schema_test.go +++ b/bake/hclparser/gohcl/schema_test.go @@ -14,7 +14,7 @@ import ( func TestImpliedBodySchema(t *testing.T) { tests := []struct { - val interface{} + val any wantSchema *hcl.BodySchema wantPartial bool }{ diff --git a/bake/hclparser/hclparser.go b/bake/hclparser/hclparser.go index fc820e4f5f03..6f98cfb6a4d2 100644 --- a/bake/hclparser/hclparser.go +++ b/bake/hclparser/hclparser.go @@ -7,6 +7,7 @@ import ( "math" "math/big" "reflect" + "slices" "strconv" "strings" @@ -589,7 +590,7 @@ type ParseMeta struct { AllVariables []*Variable } -func Parse(b hcl.Body, opt Opt, val interface{}) (*ParseMeta, hcl.Diagnostics) { +func Parse(b hcl.Body, opt Opt, val any) (*ParseMeta, hcl.Diagnostics) { reserved := map[string]struct{}{} schema, _ := gohcl.ImpliedBodySchema(val) @@ -763,7 +764,7 @@ func Parse(b hcl.Body, opt Opt, val interface{}) (*ParseMeta, hcl.Diagnostics) { types := map[string]field{} renamed := map[string]map[string][]string{} vt := reflect.ValueOf(val).Elem().Type() - for i := 0; i < vt.NumField(); i++ { + for i := range vt.NumField() { tags := strings.Split(vt.Field(i).Tag.Get("hcl"), ",") p.blockTypes[tags[0]] = vt.Field(i).Type.Elem().Elem() @@ -831,7 +832,7 @@ func Parse(b hcl.Body, opt Opt, val interface{}) (*ParseMeta, hcl.Diagnostics) { oldValue, exists := t.values[lblName] if !exists && lblExists { if v.Elem().Field(t.idx).Type().Kind() == reflect.Slice { - for i := 0; i < v.Elem().Field(t.idx).Len(); i++ { + for i := range v.Elem().Field(t.idx).Len() { if lblName == v.Elem().Field(t.idx).Index(i).Elem().Field(lblIndex).String() { exists = true oldValue = value{Value: v.Elem().Field(t.idx).Index(i), idx: i} @@ -898,7 +899,7 @@ func wrapErrorDiagnostic(message string, err error, subject *hcl.Range, context func setName(v reflect.Value, name string) { numFields := v.Elem().Type().NumField() - for i := 0; i < numFields; i++ { + for i := range numFields { parts := strings.Split(v.Elem().Type().Field(i).Tag.Get("hcl"), ",") for _, t := range parts[1:] { if t == "label" { @@ -910,12 +911,10 @@ func setName(v reflect.Value, name string) { func getName(v reflect.Value) (string, bool) { numFields := v.Elem().Type().NumField() - for i := 0; i < numFields; i++ { + for i := range numFields { parts := strings.Split(v.Elem().Type().Field(i).Tag.Get("hcl"), ",") - for _, t := range parts[1:] { - if t == "label" { - return v.Elem().Field(i).String(), true - } + if slices.Contains(parts[1:], "label") { + return v.Elem().Field(i).String(), true } } return "", false @@ -923,12 +922,10 @@ func getName(v reflect.Value) (string, bool) { func getNameIndex(v reflect.Value) (int, bool) { numFields := v.Elem().Type().NumField() - for i := 0; i < numFields; i++ { + for i := range numFields { parts := strings.Split(v.Elem().Type().Field(i).Tag.Get("hcl"), ",") - for _, t := range parts[1:] { - if t == "label" { - return i, true - } + if slices.Contains(parts[1:], "label") { + return i, true } } return 0, false @@ -988,7 +985,7 @@ func key(ks ...any) uint64 { return hash.Sum64() } -func decodeBody(body hcl.Body, ctx *hcl.EvalContext, val interface{}) hcl.Diagnostics { +func decodeBody(body hcl.Body, ctx *hcl.EvalContext, val any) hcl.Diagnostics { dec := gohcl.DecodeOptions{ImpliedType: ImpliedType} return dec.DecodeBody(body, ctx, val) } diff --git a/bake/hclparser/type_implied.go b/bake/hclparser/type_implied.go index 618be0934d5f..3468f20e2d19 100644 --- a/bake/hclparser/type_implied.go +++ b/bake/hclparser/type_implied.go @@ -43,7 +43,7 @@ import ( // In particular, ImpliedType will never use capsule types in its returned // type, because it cannot know the capsule types supported by the calling // program. -func ImpliedType(gv interface{}) (cty.Type, error) { +func ImpliedType(gv any) (cty.Type, error) { rt := reflect.TypeOf(gv) var path cty.Path return impliedType(rt, path) @@ -148,7 +148,7 @@ func structTagIndices(st reflect.Type) map[string]int { ct := st.NumField() ret := make(map[string]int, ct) - for i := 0; i < ct; i++ { + for i := range ct { field := st.Field(i) attrName := field.Tag.Get("cty") if attrName != "" { diff --git a/build/dial.go b/build/dial.go index ea13e312f137..b842419aa755 100644 --- a/build/dial.go +++ b/build/dial.go @@ -4,6 +4,7 @@ import ( "context" stderrors "errors" "net" + "slices" "github.com/containerd/platforms" "github.com/docker/buildx/builder" @@ -37,15 +38,7 @@ func Dial(ctx context.Context, nodes []builder.Node, pw progress.Writer, platfor for _, ls := range resolved { for _, rn := range ls { if platform != nil { - p := *platform - var found bool - for _, pp := range rn.platforms { - if platforms.Only(p).Match(pp) { - found = true - break - } - } - if !found { + if !slices.ContainsFunc(rn.platforms, platforms.Only(*platform).Match) { continue } } diff --git a/build/driver.go b/build/driver.go index 31fa33c67703..eaae14113489 100644 --- a/build/driver.go +++ b/build/driver.go @@ -3,6 +3,7 @@ package build import ( "context" "fmt" + "slices" "sync" "github.com/containerd/platforms" @@ -221,7 +222,7 @@ func (r *nodeResolver) get(p specs.Platform, matcher matchMaker, additionalPlatf for i, node := range r.nodes { platforms := node.Platforms if additionalPlatforms != nil { - platforms = append([]specs.Platform{}, platforms...) + platforms = slices.Clone(platforms) platforms = append(platforms, additionalPlatforms(i, node)...) } for _, p2 := range platforms { diff --git a/build/replicatedstream_test.go b/build/replicatedstream_test.go index 8704755bad2f..aefa7f315e1d 100644 --- a/build/replicatedstream_test.go +++ b/build/replicatedstream_test.go @@ -28,11 +28,11 @@ func TestSyncMultiReaderParallel(t *testing.T) { readers := make([]io.ReadCloser, numReaders) - for i := 0; i < numReaders; i++ { + for i := range numReaders { readers[i] = mr.NewReadCloser() } - for i := 0; i < numReaders; i++ { + for i := range numReaders { wg.Add(1) go func(readerId int) { defer wg.Done() diff --git a/builder/builder.go b/builder/builder.go index 8ab6ace1189a..bd2058ad8bf4 100644 --- a/builder/builder.go +++ b/builder/builder.go @@ -5,6 +5,7 @@ import ( "encoding/json" "net/url" "os" + "slices" "sort" "strings" "sync" @@ -656,13 +657,7 @@ func parseBuildkitdFlags(inp string, driver string, driverOpts map[string]string flags.StringArrayVar(&allowInsecureEntitlements, "allow-insecure-entitlement", nil, "") _ = flags.Parse(res) - var hasNetworkHostEntitlement bool - for _, e := range allowInsecureEntitlements { - if e == "network.host" { - hasNetworkHostEntitlement = true - break - } - } + hasNetworkHostEntitlement := slices.Contains(allowInsecureEntitlements, "network.host") var hasNetworkHostEntitlementInConf bool if buildkitdConfigFile != "" { @@ -671,11 +666,8 @@ func parseBuildkitdFlags(inp string, driver string, driverOpts map[string]string return nil, err } else if btoml != nil { if ies := btoml.GetArray("insecure-entitlements"); ies != nil { - for _, e := range ies.([]string) { - if e == "network.host" { - hasNetworkHostEntitlementInConf = true - break - } + if slices.Contains(ies.([]string), "network.host") { + hasNetworkHostEntitlementInConf = true } } } diff --git a/builder/node.go b/builder/node.go index d5af8750dcd6..b582503bb889 100644 --- a/builder/node.go +++ b/builder/node.go @@ -169,7 +169,7 @@ func (b *Builder) LoadNodes(ctx context.Context, opts ...LoadNodesOption) (_ []N // dynamic nodes are used in Kubernetes driver. // Kubernetes' pods are dynamically mapped to BuildKit Nodes. if di.DriverInfo != nil && len(di.DriverInfo.DynamicNodes) > 0 { - for i := 0; i < len(di.DriverInfo.DynamicNodes); i++ { + for i := range di.DriverInfo.DynamicNodes { diClone := di if pl := di.DriverInfo.DynamicNodes[i].Platforms; len(pl) > 0 { diClone.Platforms = pl diff --git a/commands/bake.go b/commands/bake.go index 6d66f0f55aa2..4afe2e51a154 100644 --- a/commands/bake.go +++ b/commands/bake.go @@ -305,7 +305,7 @@ func runBake(ctx context.Context, dockerCli command.Cli, targets []string, in ba desktop.PrintBuildDetails(os.Stderr, printer.BuildRefs(), term) } if len(in.metadataFile) > 0 { - dt := make(map[string]interface{}) + dt := make(map[string]any) for t, r := range resp { dt[t] = decodeExporterResponse(r.ExporterResponse) } diff --git a/commands/build.go b/commands/build.go index 9ee0933308c0..08eabd9345d8 100644 --- a/commands/build.go +++ b/commands/build.go @@ -11,6 +11,7 @@ import ( "io" "os" "path/filepath" + "slices" "strconv" "strings" "sync" @@ -156,7 +157,7 @@ func (o *buildOptions) toControllerOptions() (*controllerapi.BuildOptions, error return nil, err } - inAttests := append([]string{}, o.attests...) + inAttests := slices.Clone(o.attests) if o.provenance != "" { inAttests = append(inAttests, buildflags.CanonicalizeAttest("provenance", o.provenance)) } @@ -740,7 +741,7 @@ func checkWarnedFlags(f *pflag.Flag) { } } -func writeMetadataFile(filename string, dt interface{}) error { +func writeMetadataFile(filename string, dt any) error { b, err := json.MarshalIndent(dt, "", " ") if err != nil { return err @@ -748,7 +749,7 @@ func writeMetadataFile(filename string, dt interface{}) error { return atomicwriter.WriteFile(filename, b, 0644) } -func decodeExporterResponse(exporterResponse map[string]string) map[string]interface{} { +func decodeExporterResponse(exporterResponse map[string]string) map[string]any { decFunc := func(k, v string) ([]byte, error) { if k == "result.json" { // result.json is part of metadata response for subrequests which @@ -757,16 +758,16 @@ func decodeExporterResponse(exporterResponse map[string]string) map[string]inter } return base64.StdEncoding.DecodeString(v) } - out := make(map[string]interface{}) + out := make(map[string]any) for k, v := range exporterResponse { dt, err := decFunc(k, v) if err != nil { out[k] = v continue } - var raw map[string]interface{} + var raw map[string]any if err = json.Unmarshal(dt, &raw); err != nil || len(raw) == 0 { - var rawList []map[string]interface{} + var rawList []map[string]any if err = json.Unmarshal(dt, &rawList); err != nil || len(rawList) == 0 { out[k] = v continue diff --git a/commands/diskusage.go b/commands/diskusage.go index 4460c0fee38f..a1f8224d73d5 100644 --- a/commands/diskusage.go +++ b/commands/diskusage.go @@ -124,7 +124,7 @@ func duCmd(dockerCli command.Cli, rootOpts *rootOptions) *cobra.Command { return cmd } -func printKV(w io.Writer, k string, v interface{}) { +func printKV(w io.Writer, k string, v any) { fmt.Fprintf(w, "%s:\t%v\n", k, v) } diff --git a/commands/history/inspect.go b/commands/history/inspect.go index 97fefd5cdc9c..4ef739d3a4b0 100644 --- a/commands/history/inspect.go +++ b/commands/history/inspect.go @@ -375,7 +375,7 @@ workers0: out.Error.Name = name out.Error.Logs = logs } - out.Error.Stack = []byte(fmt.Sprintf("%+v", stack.Formatter(retErr))) + out.Error.Stack = fmt.Appendf(nil, "%+v", stack.Formatter(retErr)) } } diff --git a/commands/history/ls.go b/commands/history/ls.go index 07d1ef2402d3..f06cbdd27611 100644 --- a/commands/history/ls.go +++ b/commands/history/ls.go @@ -161,7 +161,7 @@ type lsContext struct { } func (c *lsContext) MarshalJSON() ([]byte, error) { - m := map[string]interface{}{ + m := map[string]any{ "ref": c.FullRef(), "name": c.Name(), "status": c.Status(), diff --git a/commands/imagetools/create.go b/commands/imagetools/create.go index 5344438276c2..fee838c64f73 100644 --- a/commands/imagetools/create.go +++ b/commands/imagetools/create.go @@ -194,7 +194,7 @@ func runCreate(ctx context.Context, dockerCli command.Cli, in createOptions, arg } s := s eg2.Go(func() error { - sub.Log(1, []byte(fmt.Sprintf("copying %s from %s to %s\n", s.Desc.Digest.String(), s.Ref.String(), t.String()))) + sub.Log(1, fmt.Appendf(nil, "copying %s from %s to %s\n", s.Desc.Digest.String(), s.Ref.String(), t.String())) return r.Copy(ctx, s, t) }) } @@ -202,7 +202,7 @@ func runCreate(ctx context.Context, dockerCli command.Cli, in createOptions, arg if err := eg2.Wait(); err != nil { return err } - sub.Log(1, []byte(fmt.Sprintf("pushing %s to %s\n", desc.Digest.String(), t.String()))) + sub.Log(1, fmt.Appendf(nil, "pushing %s to %s\n", desc.Digest.String(), t.String())) return r.Push(ctx, t, desc, dt) }) }) diff --git a/controller/pb/progress.go b/controller/pb/progress.go index dd68e7b4190a..02a98e8d2571 100644 --- a/controller/pb/progress.go +++ b/controller/pb/progress.go @@ -24,11 +24,11 @@ func (w *writer) Write(status *client.SolveStatus) { func (w *writer) WriteBuildRef(target string, ref string) {} -func (w *writer) ValidateLogSource(digest.Digest, interface{}) bool { +func (w *writer) ValidateLogSource(digest.Digest, any) bool { return true } -func (w *writer) ClearLogSource(interface{}) {} +func (w *writer) ClearLogSource(any) {} func ToControlStatus(s *client.SolveStatus) *StatusResponse { resp := StatusResponse{} diff --git a/controller/pb/ssh.go b/controller/pb/ssh.go index 3d026ebb9d60..6ce1ca1f19b8 100644 --- a/controller/pb/ssh.go +++ b/controller/pb/ssh.go @@ -1,6 +1,8 @@ package pb import ( + "slices" + "github.com/moby/buildkit/session" "github.com/moby/buildkit/session/sshforward/sshprovider" ) @@ -10,7 +12,7 @@ func CreateSSH(ssh []*SSH) (session.Attachable, error) { for _, ssh := range ssh { cfg := sshprovider.AgentConfig{ ID: ssh.ID, - Paths: append([]string{}, ssh.Paths...), + Paths: slices.Clone(ssh.Paths), } configs = append(configs, cfg) } diff --git a/controller/remote/controller.go b/controller/remote/controller.go index c9db86fd1c33..c0914d185c20 100644 --- a/controller/remote/controller.go +++ b/controller/remote/controller.go @@ -140,7 +140,7 @@ func serveCmd(dockerCli command.Cli) *cobra.Command { return err } pidF := filepath.Join(root, defaultPIDFilename) - if err := os.WriteFile(pidF, []byte(fmt.Sprintf("%d", os.Getpid())), 0600); err != nil { + if err := os.WriteFile(pidF, fmt.Appendf(nil, "%d", os.Getpid()), 0600); err != nil { return err } defer func() { diff --git a/driver/kubernetes/context/endpoint_test.go b/driver/kubernetes/context/endpoint_test.go index fd8b9348c76f..0ac70a8ba2a8 100644 --- a/driver/kubernetes/context/endpoint_test.go +++ b/driver/kubernetes/context/endpoint_test.go @@ -35,10 +35,10 @@ func testEndpoint(server, defaultNamespace string, ca, cert, key []byte, skipTLS } var testStoreCfg = store.NewConfig( - func() interface{} { - return &map[string]interface{}{} + func() any { + return &map[string]any{} }, - store.EndpointTypeGetter(KubernetesEndpoint, func() interface{} { return &EndpointMeta{} }), + store.EndpointTypeGetter(KubernetesEndpoint, func() any { return &EndpointMeta{} }), ) func TestSaveLoadContexts(t *testing.T) { @@ -197,7 +197,7 @@ func checkClientConfig(t *testing.T, ep Endpoint, server, namespace string, ca, func save(s store.Writer, ep Endpoint, name string) error { meta := store.Metadata{ - Endpoints: map[string]interface{}{ + Endpoints: map[string]any{ KubernetesEndpoint: ep.EndpointMeta, }, Name: name, diff --git a/driver/kubernetes/context/load.go b/driver/kubernetes/context/load.go index 2f0b35cbed13..a60c338cd32f 100644 --- a/driver/kubernetes/context/load.go +++ b/driver/kubernetes/context/load.go @@ -43,7 +43,7 @@ type Endpoint struct { func init() { command.RegisterDefaultStoreEndpoints( - store.EndpointTypeGetter(KubernetesEndpoint, func() interface{} { return &EndpointMeta{} }), + store.EndpointTypeGetter(KubernetesEndpoint, func() any { return &EndpointMeta{} }), ) } @@ -96,7 +96,7 @@ func (c *Endpoint) KubernetesConfig() clientcmd.ClientConfig { // ResolveDefault returns endpoint metadata for the default Kubernetes // endpoint, which is derived from the env-based kubeconfig. -func (c *EndpointMeta) ResolveDefault() (interface{}, *store.EndpointTLSData, error) { +func (c *EndpointMeta) ResolveDefault() (any, *store.EndpointTLSData, error) { kubeconfig := os.Getenv("KUBECONFIG") if kubeconfig == "" { kubeconfig = filepath.Join(homedir.Get(), ".kube/config") diff --git a/driver/kubernetes/util/generate.go b/driver/kubernetes/util/generate.go index 93988a11925a..aa90b787f71a 100644 --- a/driver/kubernetes/util/generate.go +++ b/driver/kubernetes/util/generate.go @@ -25,7 +25,7 @@ func GenerateNodeName(builderName string, txn *store.Txn) (string, error) { } var name string - for i := 0; i < 6; i++ { + for range 6 { name, err = randomName() if err != nil { return "", err diff --git a/hack/dockerfiles/lint.Dockerfile b/hack/dockerfiles/lint.Dockerfile index 211acb68e812..37c64ac69533 100644 --- a/hack/dockerfiles/lint.Dockerfile +++ b/hack/dockerfiles/lint.Dockerfile @@ -5,9 +5,10 @@ ARG ALPINE_VERSION=3.21 ARG XX_VERSION=1.6.1 ARG GOLANGCI_LINT_VERSION=1.62.0 -ARG GOPLS_VERSION=v0.26.0 +# v0.31 requires go1.24 +ARG GOPLS_VERSION=v0.30.0 # disabled: deprecated unusedvariable simplifyrange -ARG GOPLS_ANALYZERS="embeddirective fillreturns infertypeargs nonewvars noresultvalues simplifycompositelit simplifyslice undeclaredname unusedparams useany" +ARG GOPLS_ANALYZERS="embeddirective fillreturns hostport infertypeargs modernize nonewvars noresultvalues simplifycompositelit simplifyslice unusedparams yield" FROM --platform=$BUILDPLATFORM tonistiigi/xx:${XX_VERSION} AS xx diff --git a/monitor/commands/attach.go b/monitor/commands/attach.go index cbd5b48ba2ed..34b3dcba6ba3 100644 --- a/monitor/commands/attach.go +++ b/monitor/commands/attach.go @@ -4,6 +4,7 @@ import ( "context" "fmt" "io" + "slices" "github.com/docker/buildx/monitor/types" "github.com/pkg/errors" @@ -50,14 +51,7 @@ func (cm *AttachCmd) Exec(ctx context.Context, args []string) error { if err != nil { return errors.Errorf("failed to get the list of sessions: %v", err) } - found := false - for _, s := range refs { - if s == ref { - found = true - break - } - } - if !found { + if !slices.Contains(refs, ref) { return errors.Errorf("unknown ID: %q", ref) } cm.m.Detach() // Finish existing attach diff --git a/store/nodegroup.go b/store/nodegroup.go index ad3cdf07939c..06ca070ee9ae 100644 --- a/store/nodegroup.go +++ b/store/nodegroup.go @@ -2,6 +2,7 @@ package store import ( "fmt" + "slices" "time" "github.com/containerd/platforms" @@ -44,7 +45,7 @@ func (ng *NodeGroup) Leave(name string) error { if len(ng.Nodes) == 1 { return errors.Errorf("can not leave last node, do you want to rm instance instead?") } - ng.Nodes = append(ng.Nodes[:i], ng.Nodes[i+1:]...) + ng.Nodes = slices.Delete(ng.Nodes, i, i+1) return nil } diff --git a/store/util.go b/store/util.go index 269ca4a034e8..b8aede495925 100644 --- a/store/util.go +++ b/store/util.go @@ -39,7 +39,7 @@ func ValidateName(s string) (string, error) { func GenerateName(txn *Txn) (string, error) { var name string - for i := 0; i < 6; i++ { + for i := range 6 { name = namesgenerator.GetRandomName(i) if _, err := txn.NodeGroupByName(name); err != nil { if !os.IsNotExist(errors.Cause(err)) { diff --git a/tests/bake.go b/tests/bake.go index 4935e1153430..669c100e1371 100644 --- a/tests/bake.go +++ b/tests/bake.go @@ -1016,11 +1016,11 @@ FROM scratch COPY foo /foo `) destDir := t.TempDir() - bakefile := []byte(fmt.Sprintf(` + bakefile := fmt.Appendf(nil, ` target "default" { output = ["type=local,dest=%s/not/exists"] } -`, destDir)) +`, destDir) dir := tmpdir( t, fstest.CreateFile("docker-bake.hcl", bakefile, 0600), @@ -1050,11 +1050,11 @@ FROM scratch COPY foo /foo `) destDir := t.TempDir() - bakefile := []byte(fmt.Sprintf(` + bakefile := fmt.Appendf(nil, ` target "default" { output = ["type=local,dest=%s"] } -`, destDir)) +`, destDir) dir := tmpdir( t, fstest.CreateFile("docker-bake.hcl", bakefile, 0600), @@ -1151,11 +1151,11 @@ COPY Dockerfile /foo keyDir := t.TempDir() err := writeTempPrivateKey(filepath.Join(keyDir, "id_rsa")) require.NoError(t, err) - bakefile := []byte(fmt.Sprintf(` + bakefile := fmt.Appendf(nil, ` target "default" { ssh = ["key=%s"] } -`, filepath.Join(keyDir, "id_rsa"))) +`, filepath.Join(keyDir, "id_rsa")) dir := tmpdir( t, fstest.CreateFile("docker-bake.hcl", bakefile, 0600), @@ -1314,8 +1314,8 @@ target "default" { type mdT struct { Default struct { - BuildRef string `json:"buildx.build.ref"` - BuildProvenance map[string]interface{} `json:"buildx.build.provenance"` + BuildRef string `json:"buildx.build.ref"` + BuildProvenance map[string]any `json:"buildx.build.provenance"` } `json:"default"` } var md mdT diff --git a/tests/build.go b/tests/build.go index 6aaa74e48ffc..77b91a9d7afd 100644 --- a/tests/build.go +++ b/tests/build.go @@ -804,8 +804,8 @@ func buildMetadataProvenance(t *testing.T, sb integration.Sandbox, metadataMode require.NoError(t, err) type mdT struct { - BuildRef string `json:"buildx.build.ref"` - BuildProvenance map[string]interface{} `json:"buildx.build.provenance"` + BuildRef string `json:"buildx.build.ref"` + BuildProvenance map[string]any `json:"buildx.build.provenance"` } var md mdT err = json.Unmarshal(dt, &md) diff --git a/tests/integration.go b/tests/integration.go index 9d39a9efe593..574672a7ee79 100644 --- a/tests/integration.go +++ b/tests/integration.go @@ -50,7 +50,7 @@ func withDir(dir string) cmdOpt { func buildxCmd(sb integration.Sandbox, opts ...cmdOpt) *exec.Cmd { cmd := exec.Command("buildx") - cmd.Env = append([]string{}, os.Environ()...) + cmd.Env = os.Environ() for _, opt := range opts { opt(cmd) } @@ -77,7 +77,7 @@ func buildxCmd(sb integration.Sandbox, opts ...cmdOpt) *exec.Cmd { func dockerCmd(sb integration.Sandbox, opts ...cmdOpt) *exec.Cmd { cmd := exec.Command("docker") - cmd.Env = append([]string{}, os.Environ()...) + cmd.Env = os.Environ() for _, opt := range opts { opt(cmd) } @@ -214,7 +214,7 @@ func skipNoCompatBuildKit(t *testing.T, sb integration.Sandbox, constraint strin } } -func ptrstr(s interface{}) *string { +func ptrstr(s any) *string { var n *string if reflect.ValueOf(s).Kind() == reflect.String { ss := s.(string) diff --git a/tests/rm.go b/tests/rm.go index 5f7d45569cbe..1eb8c070e7dd 100644 --- a/tests/rm.go +++ b/tests/rm.go @@ -45,7 +45,7 @@ func testRmMulti(t *testing.T, sb integration.Sandbox) { } var builderNames []string - for i := 0; i < 3; i++ { + for range 3 { out, err := createCmd(sb, withArgs("--driver", "docker-container")) require.NoError(t, err, out) builderName := strings.TrimSpace(out) diff --git a/tests/workers/backend.go b/tests/workers/backend.go index c011dbafbb50..386bf7bd9f6b 100644 --- a/tests/workers/backend.go +++ b/tests/workers/backend.go @@ -2,6 +2,7 @@ package workers import ( "os" + "slices" "strings" "github.com/moby/buildkit/util/testutil/integration" @@ -49,23 +50,14 @@ func (s *backend) ExtraEnv() []string { func (s backend) Supports(feature string) bool { if enabledFeatures := os.Getenv("BUILDKIT_TEST_ENABLE_FEATURES"); enabledFeatures != "" { - for _, enabledFeature := range strings.Split(enabledFeatures, ",") { - if feature == enabledFeature { - return true - } + if slices.Contains(strings.Split(enabledFeatures, ","), feature) { + return true } } if disabledFeatures := os.Getenv("BUILDKIT_TEST_DISABLE_FEATURES"); disabledFeatures != "" { - for _, disabledFeature := range strings.Split(disabledFeatures, ",") { - if feature == disabledFeature { - return false - } - } - } - for _, unsupportedFeature := range s.unsupportedFeatures { - if feature == unsupportedFeature { + if slices.Contains(strings.Split(disabledFeatures, ","), feature) { return false } } - return true + return !slices.Contains(s.unsupportedFeatures, feature) } diff --git a/util/buildflags/attests.go b/util/buildflags/attests.go index 549973070e3e..8bf672448cc3 100644 --- a/util/buildflags/attests.go +++ b/util/buildflags/attests.go @@ -90,7 +90,7 @@ func (a *Attest) ToPB() *controllerapi.Attest { } func (a *Attest) MarshalJSON() ([]byte, error) { - m := make(map[string]interface{}, len(a.Attrs)+2) + m := make(map[string]any, len(a.Attrs)+2) for k, v := range a.Attrs { m[k] = v } @@ -102,7 +102,7 @@ func (a *Attest) MarshalJSON() ([]byte, error) { } func (a *Attest) UnmarshalJSON(data []byte) error { - var m map[string]interface{} + var m map[string]any if err := json.Unmarshal(data, &m); err != nil { return err } diff --git a/util/buildflags/cache.go b/util/buildflags/cache.go index f9c990348b13..50a30ab231b4 100644 --- a/util/buildflags/cache.go +++ b/util/buildflags/cache.go @@ -150,7 +150,7 @@ func (e *CacheOptionsEntry) UnmarshalText(text []byte) error { return e.validate(text) } -func (e *CacheOptionsEntry) validate(gv interface{}) error { +func (e *CacheOptionsEntry) validate(gv any) error { if e.Type == "" { var text []byte switch gv := gv.(type) { diff --git a/util/buildflags/utils.go b/util/buildflags/utils.go index c7aeffd5c060..53e04aeb9bce 100644 --- a/util/buildflags/utils.go +++ b/util/buildflags/utils.go @@ -33,7 +33,7 @@ func removeDupes[E comparable[E]](s []E) []E { return s } -func getAndDelete(m map[string]cty.Value, attr string, gv interface{}) error { +func getAndDelete(m map[string]cty.Value, attr string, gv any) error { if v, ok := m[attr]; ok && v.IsKnown() { delete(m, attr) return gocty.FromCtyValue(v, gv) diff --git a/util/imagetools/create.go b/util/imagetools/create.go index 2d82a98e84ab..6fdcac96d125 100644 --- a/util/imagetools/create.go +++ b/util/imagetools/create.go @@ -156,7 +156,7 @@ func (r *Resolver) Combine(ctx context.Context, srcs []*Source, ann map[exptypes case exptypes.AnnotationIndex: indexAnnotation[k.Key] = v case exptypes.AnnotationManifestDescriptor: - for i := 0; i < len(newDescs); i++ { + for i := range newDescs { if newDescs[i].Annotations == nil { newDescs[i].Annotations = map[string]string{} } diff --git a/util/imagetools/loader.go b/util/imagetools/loader.go index 7385ed7b8a0b..457e684e5743 100644 --- a/util/imagetools/loader.go +++ b/util/imagetools/loader.go @@ -278,8 +278,8 @@ func (l *loader) scanConfig(ctx context.Context, fetcher remotes.Fetcher, desc o } type sbomStub struct { - SPDX interface{} `json:",omitempty"` - AdditionalSPDXs []interface{} `json:",omitempty"` + SPDX any `json:",omitempty"` + AdditionalSPDXs []any `json:",omitempty"` } func (l *loader) scanSBOM(ctx context.Context, fetcher remotes.Fetcher, r *result, refs []digest.Digest, as *asset) error { @@ -309,7 +309,7 @@ func (l *loader) scanSBOM(ctx context.Context, fetcher remotes.Fetcher, r *resul } var spdx struct { - Predicate interface{} `json:"predicate"` + Predicate any `json:"predicate"` } if err := json.Unmarshal(dt, &spdx); err != nil { return nil, err @@ -330,7 +330,7 @@ func (l *loader) scanSBOM(ctx context.Context, fetcher remotes.Fetcher, r *resul } type provenanceStub struct { - SLSA interface{} `json:",omitempty"` + SLSA any `json:",omitempty"` } func (l *loader) scanProvenance(ctx context.Context, fetcher remotes.Fetcher, r *result, refs []digest.Digest, as *asset) error { @@ -360,7 +360,7 @@ func (l *loader) scanProvenance(ctx context.Context, fetcher remotes.Fetcher, r } var slsa struct { - Predicate interface{} `json:"predicate"` + Predicate any `json:"predicate"` } if err := json.Unmarshal(dt, &slsa); err != nil { return nil, err diff --git a/util/imagetools/printers.go b/util/imagetools/printers.go index 7728136d0888..ab6fef1ba7f9 100644 --- a/util/imagetools/printers.go +++ b/util/imagetools/printers.go @@ -89,7 +89,7 @@ func (p *Printer) Print(raw bool, out io.Writer) error { } tpl, err := template.New("").Funcs(template.FuncMap{ - "json": func(v interface{}) string { + "json": func(v any) string { b, _ := json.MarshalIndent(v, "", " ") return string(b) }, @@ -101,7 +101,7 @@ func (p *Printer) Print(raw bool, out io.Writer) error { imageconfigs := res.Configs() format := tpl.Root.String() - var mfst interface{} + var mfst any switch p.manifest.MediaType { case images.MediaTypeDockerSchema2Manifest, ocispecs.MediaTypeImageManifest: mfst = p.manifest @@ -206,7 +206,7 @@ func (p *Printer) printManifestList(out io.Writer) error { type tplInput struct { Name string `json:"name,omitempty"` - Manifest interface{} `json:"manifest,omitempty"` + Manifest any `json:"manifest,omitempty"` Image *ocispecs.Image `json:"image,omitempty"` result *result @@ -236,7 +236,7 @@ func (inp tplInput) Provenance() (provenanceStub, error) { type tplInputs struct { Name string `json:"name,omitempty"` - Manifest interface{} `json:"manifest,omitempty"` + Manifest any `json:"manifest,omitempty"` Image map[string]*ocispecs.Image `json:"image,omitempty"` result *result diff --git a/util/ioset/mux_test.go b/util/ioset/mux_test.go index af318be113d0..1f0edd0b1536 100644 --- a/util/ioset/mux_test.go +++ b/util/ioset/mux_test.go @@ -126,7 +126,7 @@ func TestMuxIO(t *testing.T) { if tt.outputsNum != len(tt.wants) { t.Fatalf("wants != outputsNum") } - for i := 0; i < tt.outputsNum; i++ { + for i := range tt.outputsNum { outBuf, out := newTestOut(i) outBufs = append(outBufs, outBuf) outs = append(outs, MuxOut{out, nil, nil}) @@ -304,7 +304,7 @@ func writeMasked(w io.Writer, s string) io.Writer { return } var masked string - for i := 0; i < n; i++ { + for range n { masked += s } if _, err := w.Write([]byte(masked)); err != nil { diff --git a/util/otelutil/jaeger/model.go b/util/otelutil/jaeger/model.go index 8606ddf5d2d4..369ed403d6a9 100644 --- a/util/otelutil/jaeger/model.go +++ b/util/otelutil/jaeger/model.go @@ -83,9 +83,9 @@ type Log struct { // KeyValue is a key-value pair with typed value. type KeyValue struct { - Key string `json:"key"` - Type ValueType `json:"type,omitempty"` - Value interface{} `json:"value"` + Key string `json:"key"` + Type ValueType `json:"type,omitempty"` + Value any `json:"value"` } // DependencyLink shows dependencies between services diff --git a/util/otelutil/span.go b/util/otelutil/span.go index 904bccb1985c..19fbb9bf861e 100644 --- a/util/otelutil/span.go +++ b/util/otelutil/span.go @@ -149,7 +149,7 @@ type keyValue struct { // value is a custom type used to unmarshal otel Value correctly. type value struct { Type string - Value interface{} + Value any } // UnmarshalJSON implements json.Unmarshaler for Span which allows correctly @@ -318,7 +318,7 @@ func (kv *keyValue) asAttributeKeyValue() (attribute.KeyValue, error) { switch sli := kv.Value.Value.(type) { case []string: strSli = sli - case []interface{}: + case []any: for i := range sli { var v string // best case we have a string, otherwise, cast it using diff --git a/util/otelutil/span_test.go b/util/otelutil/span_test.go index 0fe5fa6528b3..fb52d1097e07 100644 --- a/util/otelutil/span_test.go +++ b/util/otelutil/span_test.go @@ -131,7 +131,7 @@ func TestAsAttributeKeyValue(t *testing.T) { name: "stringslice (interface of string)", args: args{ Type: attribute.STRINGSLICE.String(), - value: []interface{}{"value1", "value2"}, + value: []any{"value1", "value2"}, }, want: attribute.StringSlice("key", []string{"value1", "value2"}), }, @@ -139,7 +139,7 @@ func TestAsAttributeKeyValue(t *testing.T) { name: "stringslice (interface mixed)", args: args{ Type: attribute.STRINGSLICE.String(), - value: []interface{}{"value1", 2}, + value: []any{"value1", 2}, }, want: attribute.StringSlice("key", []string{"value1", "2"}), }, diff --git a/util/progress/printer.go b/util/progress/printer.go index bb3f347d18f3..482641a18c02 100644 --- a/util/progress/printer.go +++ b/util/progress/printer.go @@ -27,7 +27,7 @@ type Printer struct { err error warnings []client.VertexWarning logMu sync.Mutex - logSourceMap map[digest.Digest]interface{} + logSourceMap map[digest.Digest]any metrics *metricWriter // TODO: remove once we can use result context to pass build ref @@ -74,7 +74,7 @@ func (p *Printer) Warnings() []client.VertexWarning { return dedupWarnings(p.warnings) } -func (p *Printer) ValidateLogSource(dgst digest.Digest, v interface{}) bool { +func (p *Printer) ValidateLogSource(dgst digest.Digest, v any) bool { p.logMu.Lock() defer p.logMu.Unlock() src, ok := p.logSourceMap[dgst] @@ -89,7 +89,7 @@ func (p *Printer) ValidateLogSource(dgst digest.Digest, v interface{}) bool { return false } -func (p *Printer) ClearLogSource(v interface{}) { +func (p *Printer) ClearLogSource(v any) { p.logMu.Lock() defer p.logMu.Unlock() for d := range p.logSourceMap { @@ -125,7 +125,7 @@ func NewPrinter(ctx context.Context, out console.File, mode progressui.DisplayMo pw.closeOnce = sync.Once{} pw.logMu.Lock() - pw.logSourceMap = map[digest.Digest]interface{}{} + pw.logSourceMap = map[digest.Digest]any{} pw.logMu.Unlock() resumeLogs := logutil.Pause(logrus.StandardLogger()) diff --git a/util/progress/writer.go b/util/progress/writer.go index 2a044e0153aa..c08056b3b4d5 100644 --- a/util/progress/writer.go +++ b/util/progress/writer.go @@ -11,8 +11,8 @@ import ( type Writer interface { Write(*client.SolveStatus) WriteBuildRef(string, string) - ValidateLogSource(digest.Digest, interface{}) bool - ClearLogSource(interface{}) + ValidateLogSource(digest.Digest, any) bool + ClearLogSource(any) } func Write(w Writer, name string, f func() error) error { diff --git a/util/waitmap/waitmap.go b/util/waitmap/waitmap.go index 582c8218d91f..99dfad89ea39 100644 --- a/util/waitmap/waitmap.go +++ b/util/waitmap/waitmap.go @@ -7,18 +7,18 @@ import ( type Map struct { mu sync.RWMutex - m map[string]interface{} + m map[string]any ch map[string]chan struct{} } func New() *Map { return &Map{ - m: make(map[string]interface{}), + m: make(map[string]any), ch: make(map[string]chan struct{}), } } -func (m *Map) Set(key string, value interface{}) { +func (m *Map) Set(key string, value any) { m.mu.Lock() defer m.mu.Unlock() @@ -32,13 +32,13 @@ func (m *Map) Set(key string, value interface{}) { m.ch[key] = nil } -func (m *Map) Get(ctx context.Context, keys ...string) (map[string]interface{}, error) { +func (m *Map) Get(ctx context.Context, keys ...string) (map[string]any, error) { if len(keys) == 0 { - return map[string]interface{}{}, nil + return map[string]any{}, nil } if len(keys) > 1 { - out := make(map[string]interface{}) + out := make(map[string]any) for _, key := range keys { mm, err := m.Get(ctx, key) if err != nil { @@ -70,5 +70,5 @@ func (m *Map) Get(ctx context.Context, keys ...string) (map[string]interface{}, res := m.m[key] m.mu.Unlock() - return map[string]interface{}{key: res}, nil + return map[string]any{key: res}, nil }