Skip to content

Commit

Permalink
Merge pull request #49 from buildkite/plugin-config-empty-nil
Browse files Browse the repository at this point in the history
Canonicalise empty plugin configs to nil
  • Loading branch information
DrJosh9000 authored Sep 5, 2024
2 parents 09eb8d4 + 35b420a commit b236161
Show file tree
Hide file tree
Showing 2 changed files with 65 additions and 4 deletions.
20 changes: 17 additions & 3 deletions plugin.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,13 +35,27 @@ func (p *Plugin) MarshalJSON() ([]byte, error) {
return json.Marshal(o)
}

// MarshalYAML returns the plugin in either "one-item map" form. Plugin sources
// MarshalYAML returns the plugin in "one-item map" form. Plugin sources
// are marshalled into "full" form. Plugins originally specified as a single
// string (no config, only source) are canonicalised into "one-item map" with
// config nil.
// config nil. Configs that are zero-length maps are canonicalised to nil.
func (p *Plugin) MarshalYAML() (any, error) {
cfg := p.Config
switch x := cfg.(type) {
case map[string]any:
if len(x) == 0 {
cfg = nil
}

case []any:
// Should be invalid, but a different part of the process should be
// responsible for checking and complaining.
if len(x) == 0 {
cfg = nil
}
}
return map[string]any{
p.FullSource(): p.Config,
p.FullSource(): cfg,
}, nil
}

Expand Down
49 changes: 48 additions & 1 deletion plugin_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package pipeline

import (
"encoding/json"
"testing"

"github.com/google/go-cmp/cmp"
Expand Down Expand Up @@ -87,6 +88,53 @@ func TestPluginFullSource(t *testing.T) {
}
}

func TestPluginMarshalJSON_Canonicalisation(t *testing.T) {
t.Parallel()

tests := []struct {
name string
p *Plugin
}{
{
name: "nil interface",
p: &Plugin{Source: "docker#v1.2.3", Config: nil},
},
{
name: "nil map",
p: &Plugin{Source: "docker#v1.2.3", Config: map[string]any(nil)},
},
{
name: "empty map",
p: &Plugin{Source: "docker#v1.2.3", Config: map[string]any{}},
},
{
name: "nil slice??",
p: &Plugin{Source: "docker#v1.2.3", Config: []any(nil)},
},
{
name: "empty slice??",
p: &Plugin{Source: "docker#v1.2.3", Config: []any{}},
},
}

const want = `{"github.com/buildkite-plugins/docker-buildkite-plugin#v1.2.3":null}`

for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
t.Parallel()

got, err := json.Marshal(test.p)
if err != nil {
t.Errorf("json.Marshal(%+v) error = %v", test.p, err)
}

if diff := cmp.Diff(string(got), want); diff != "" {
t.Errorf("JSON marshalled plugin diff (-got +want):\n%s", diff)
}
})
}
}

func TestPluginMatrixInterpolate(t *testing.T) {
t.Parallel()

Expand Down Expand Up @@ -151,5 +199,4 @@ func TestPluginMatrixInterpolate(t *testing.T) {
}
})
}

}

0 comments on commit b236161

Please sign in to comment.