mirror of
https://github.com/thegeeklab/wp-plugin-go.git
synced 2024-11-21 14:10:39 +00:00
feat: add custom StringSliceFlag type that allows escaping (#21)
This commit is contained in:
parent
83dd67c25f
commit
9bf0cbdf85
40
drone/types.go
Normal file
40
drone/types.go
Normal file
@ -0,0 +1,40 @@
|
|||||||
|
package drone
|
||||||
|
|
||||||
|
import (
|
||||||
|
"strings"
|
||||||
|
)
|
||||||
|
|
||||||
|
// StringSliceFlag is a flag type which support comma separated values and escaping to not split at unwanted lines
|
||||||
|
type StringSliceFlag struct {
|
||||||
|
slice []string
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *StringSliceFlag) String() string {
|
||||||
|
return strings.Join(s.slice, " ")
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *StringSliceFlag) Set(value string) error {
|
||||||
|
s.slice = splitWithEscaping(value, ",", "\\")
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *StringSliceFlag) Get() []string {
|
||||||
|
return s.slice
|
||||||
|
}
|
||||||
|
|
||||||
|
func splitWithEscaping(s, separator, escapeString string) []string {
|
||||||
|
if len(s) == 0 {
|
||||||
|
return []string{}
|
||||||
|
}
|
||||||
|
|
||||||
|
a := strings.Split(s, separator)
|
||||||
|
|
||||||
|
for i := len(a) - 2; i >= 0; i-- {
|
||||||
|
if strings.HasSuffix(a[i], escapeString) {
|
||||||
|
a[i] = a[i][:len(a[i])-len(escapeString)] + separator + a[i+1]
|
||||||
|
a = append(a[:i+1], a[i+2:]...)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return a
|
||||||
|
}
|
27
drone/types_test.go
Normal file
27
drone/types_test.go
Normal file
@ -0,0 +1,27 @@
|
|||||||
|
package drone
|
||||||
|
|
||||||
|
import (
|
||||||
|
"reflect"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestSplitWithEscaping(t *testing.T) {
|
||||||
|
tests := []struct {
|
||||||
|
Input string
|
||||||
|
Output []string
|
||||||
|
}{
|
||||||
|
{"", []string{}},
|
||||||
|
{"a,b", []string{"a", "b"}},
|
||||||
|
{",,,", []string{"", "", "", ""}},
|
||||||
|
{",a\\,", []string{"", "a,"}},
|
||||||
|
{"a,b\\,c\\\\d,e", []string{"a", "b,c\\\\d", "e"}},
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, test := range tests {
|
||||||
|
strings := splitWithEscaping(test.Input, ",", "\\")
|
||||||
|
got, want := strings, test.Output
|
||||||
|
if !reflect.DeepEqual(got, want) {
|
||||||
|
t.Errorf("Got tag %v, want %v", got, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
Loading…
Reference in New Issue
Block a user