Procházet zdrojové kódy

Add quoted string flag Value.

Signed-off-by: Daniel Nephin <dnephin@docker.com>
(cherry picked from commit e4c1f0772923c3069ce14a82d445cd55af3382bc)
Signed-off-by: Victor Vieux <vieux@docker.com>
Daniel Nephin před 8 roky
rodič
revize
a2dc349c74
2 změnil soubory, kde provedl 54 přidání a 0 odebrání
  1. 30 0
      opts/quotedstring.go
  2. 24 0
      opts/quotedstring_test.go

+ 30 - 0
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
+}

+ 24 - 0
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")
+}