From 2f114f234cb8fc9057dc8d33576a0b5ded117f0c Mon Sep 17 00:00:00 2001 From: Nicolas De Loof Date: Tue, 25 Jun 2024 12:53:03 +0200 Subject: [PATCH] set default TCP protocol Signed-off-by: Nicolas De Loof --- transform/defaults.go | 1 + transform/ports.go | 15 +++++++++++++++ transform/ports_test.go | 37 +++++++++++++++++++++++++++++++++++++ 3 files changed, 53 insertions(+) diff --git a/transform/defaults.go b/transform/defaults.go index 276b1370..96693c65 100644 --- a/transform/defaults.go +++ b/transform/defaults.go @@ -25,6 +25,7 @@ var defaultValues = map[tree.Path]transformFunc{} func init() { defaultValues["services.*.build"] = defaultBuildContext defaultValues["services.*.secrets.*"] = defaultSecretMount + defaultValues["services.*.ports.*"] = portDefaults } // SetDefaultValues transforms a compose model to set default values to missing attributes diff --git a/transform/ports.go b/transform/ports.go index 7bb8e724..5399c146 100644 --- a/transform/ports.go +++ b/transform/ports.go @@ -87,3 +87,18 @@ func encode(v any) (map[string]any, error) { err = decoder.Decode(v) return m, err } + +func portDefaults(data any, p tree.Path, _ bool) (any, error) { + switch v := data.(type) { + case map[string]any: + if _, ok := v["protocol"]; !ok { + v["protocol"] = "tcp" + } + if _, ok := v["mode"]; !ok { + v["mode"] = "ingress" + } + return v, nil + default: + return data, nil + } +} diff --git a/transform/ports_test.go b/transform/ports_test.go index 2722bfa5..27af78a8 100644 --- a/transform/ports_test.go +++ b/transform/ports_test.go @@ -87,3 +87,40 @@ func Test_transformPorts(t *testing.T) { }) } } + +func Test_portDefaults(t *testing.T) { + tests := []struct { + name string + yaml any + ignoreParseError bool + want any + wantErr string + }{ + { + name: "default port", + yaml: map[string]any{ + "target": 80, + "published": 8080, + }, + want: map[string]any{ + "mode": "ingress", + "protocol": "tcp", + "published": 8080, + "target": 80, + }, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + got, err := portDefaults(tt.yaml, tree.NewPath("services.foo.ports"), tt.ignoreParseError) + if tt.wantErr != "" { + assert.Error(t, err, tt.wantErr) + return + } + assert.NilError(t, err) + if !reflect.DeepEqual(got, tt.want) { + t.Errorf("transformPorts() got = %v, want %v", got, tt.want) + } + }) + } +}