From 535fbe477180e5d19cad0b81e7267431e3323500 Mon Sep 17 00:00:00 2001 From: Robert Kaussow Date: Sat, 19 Aug 2023 15:25:53 +0200 Subject: [PATCH] feat: add custom cli types for string maps (#18) BREAKING CHANGE: The existing type `StringSliceFlag` was moved to the new `types` package. --- types/stringmap.go | 74 +++++++++++++++++++ plugin/types.go => types/stringslice.go | 6 +- .../stringslice_test.go | 2 +- 3 files changed, 77 insertions(+), 5 deletions(-) create mode 100644 types/stringmap.go rename plugin/types.go => types/stringslice.go (95%) rename plugin/types_test.go => types/stringslice_test.go (97%) diff --git a/types/stringmap.go b/types/stringmap.go new file mode 100644 index 0000000..a30dca1 --- /dev/null +++ b/types/stringmap.go @@ -0,0 +1,74 @@ +package types + +import "encoding/json" + +type DeepStringMapFlag struct { + parts map[string]map[string]string +} + +func (d *DeepStringMapFlag) String() string { + return "" +} + +func (d *DeepStringMapFlag) Get() map[string]map[string]string { + return d.parts +} + +func (d *DeepStringMapFlag) Set(value string) error { + d.parts = map[string]map[string]string{} + + err := json.Unmarshal([]byte(value), &d.parts) + if err != nil { + single := map[string]string{} + + err := json.Unmarshal([]byte(value), &single) + if err != nil { + return err + } + + d.parts["*"] = single + } + + return nil +} + +type StringMapFlag struct { + parts map[string]string +} + +func (s *StringMapFlag) String() string { + return "" +} + +func (s *StringMapFlag) Get() map[string]string { + return s.parts +} + +func (s *StringMapFlag) Set(value string) error { + s.parts = map[string]string{} + + err := json.Unmarshal([]byte(value), &s.parts) + if err != nil { + s.parts["*"] = value + } + + return nil +} + +type MapFlag struct { + parts map[string]string +} + +func (m *MapFlag) String() string { + return "" +} + +func (m *MapFlag) Get() map[string]string { + return m.parts +} + +func (m *MapFlag) Set(value string) error { + m.parts = map[string]string{} + + return json.Unmarshal([]byte(value), &m.parts) +} diff --git a/plugin/types.go b/types/stringslice.go similarity index 95% rename from plugin/types.go rename to types/stringslice.go index e18693d..92739f9 100644 --- a/plugin/types.go +++ b/types/stringslice.go @@ -1,8 +1,6 @@ -package plugin +package types -import ( - "strings" -) +import "strings" // StringSliceFlag is a flag type which support comma separated values and escaping to not split at unwanted lines. type StringSliceFlag struct { diff --git a/plugin/types_test.go b/types/stringslice_test.go similarity index 97% rename from plugin/types_test.go rename to types/stringslice_test.go index 29dfdec..f9775cf 100644 --- a/plugin/types_test.go +++ b/types/stringslice_test.go @@ -1,4 +1,4 @@ -package plugin +package types import ( "reflect"