From 8eeed60a68c6837b13ebd10747220b8b902cdf42 Mon Sep 17 00:00:00 2001 From: Daniel Nephin Date: Thu, 29 Dec 2016 17:28:28 -0500 Subject: [PATCH] Add quoted string flag Value. Signed-off-by: Daniel Nephin --- opts/quotedstring.go | 30 ++++++++++++++++++++++++++++++ opts/quotedstring_test.go | 24 ++++++++++++++++++++++++ 2 files changed, 54 insertions(+) create mode 100644 opts/quotedstring.go create mode 100644 opts/quotedstring_test.go diff --git a/opts/quotedstring.go b/opts/quotedstring.go new file mode 100644 index 0000000000..8ddeee8085 --- /dev/null +++ b/opts/quotedstring.go @@ -0,0 +1,30 @@ +package opts + +// QuotedString is a string that may have extra quotes around the value. The +// quotes are stripped from the value. +type QuotedString string + +// Set sets a new value +func (s *QuotedString) Set(val string) error { + *s = QuotedString(trimQuotes(val)) + return nil +} + +// Type returns the type of the value +func (s *QuotedString) Type() string { + return "string" +} + +func (s *QuotedString) String() string { + return string(*s) +} + +func trimQuotes(value string) string { + lastIndex := len(value) - 1 + for _, char := range []byte{'\'', '"'} { + if value[0] == char && value[lastIndex] == char { + return value[1:lastIndex] + } + } + return value +} diff --git a/opts/quotedstring_test.go b/opts/quotedstring_test.go new file mode 100644 index 0000000000..a508b9d210 --- /dev/null +++ b/opts/quotedstring_test.go @@ -0,0 +1,24 @@ +package opts + +import ( + "github.com/docker/docker/pkg/testutil/assert" + "testing" +) + +func TestQuotedStringSetWithQuotes(t *testing.T) { + qs := QuotedString("") + assert.NilError(t, qs.Set("\"something\"")) + assert.Equal(t, qs.String(), "something") +} + +func TestQuotedStringSetWithMismatchedQuotes(t *testing.T) { + qs := QuotedString("") + assert.NilError(t, qs.Set("\"something'")) + assert.Equal(t, qs.String(), "\"something'") +} + +func TestQuotedStringSetWithNoQuotes(t *testing.T) { + qs := QuotedString("") + assert.NilError(t, qs.Set("something")) + assert.Equal(t, qs.String(), "something") +}