From a1186f054eb0ae279926d12218f68a242dc76d0d Mon Sep 17 00:00:00 2001 From: Jorge Araya Navarro Date: Tue, 16 Jul 2024 14:09:26 -0600 Subject: [PATCH] Add type slice (only for strings) type (#176) --- pkg/config/config.go | 12 ++++++++++++ pkg/field/fields.go | 24 ++++++++++++++++++++++++ 2 files changed, 36 insertions(+) diff --git a/pkg/config/config.go b/pkg/config/config.go index 4ad50ec9..de6caf1f 100644 --- a/pkg/config/config.go +++ b/pkg/config/config.go @@ -94,6 +94,18 @@ func DefineConfiguration( } mainCMD.PersistentFlags(). StringP(field.FieldName, field.CLIShortHand, value, field.GetDescription()) + case reflect.Slice: + value, err := field.StringArray() + if err != nil { + return nil, nil, fmt.Errorf( + "field %s, %s: %w", + field.FieldName, + field.FieldType, + err, + ) + } + mainCMD.PersistentFlags(). + StringArrayP(field.FieldName, field.CLIShortHand, value, field.GetDescription()) default: return nil, nil, fmt.Errorf( "field %s, %s is not yet supported", diff --git a/pkg/field/fields.go b/pkg/field/fields.go index 8d735e58..7b08deb8 100644 --- a/pkg/field/fields.go +++ b/pkg/field/fields.go @@ -51,6 +51,16 @@ func (s SchemaField) String() (string, error) { return value, nil } +// StringArray retuns the default value as a string array. +func (s SchemaField) StringArray() ([]string, error) { + value, ok := s.DefaultValue.([]string) + if !ok { + return nil, WrongValueTypeErr + } + + return value, nil +} + func (s SchemaField) GetDescription() string { var line string if s.Description == "" { @@ -120,6 +130,20 @@ func IntField(name string, optional ...fieldOption) SchemaField { return field } +func StringArrayField(name string, optional ...fieldOption) SchemaField { + field := SchemaField{ + FieldName: name, + FieldType: reflect.Slice, + DefaultValue: []string{}, + } + + for _, o := range optional { + field = o(field) + } + + return field +} + func toUpperCase(i string) string { return strings.ReplaceAll(strings.ToUpper(i), "-", "_") }