diff --git a/vendor/github.com/Sirupsen/logrus/entry_test.go b/vendor/github.com/Sirupsen/logrus/entry_test.go
deleted file mode 100644
index 99c3b41d..00000000
--- a/vendor/github.com/Sirupsen/logrus/entry_test.go
+++ /dev/null
@@ -1,77 +0,0 @@
-package logrus
-
-import (
- "bytes"
- "fmt"
- "testing"
-
- "github.com/stretchr/testify/assert"
-)
-
-func TestEntryWithError(t *testing.T) {
-
- assert := assert.New(t)
-
- defer func() {
- ErrorKey = "error"
- }()
-
- err := fmt.Errorf("kaboom at layer %d", 4711)
-
- assert.Equal(err, WithError(err).Data["error"])
-
- logger := New()
- logger.Out = &bytes.Buffer{}
- entry := NewEntry(logger)
-
- assert.Equal(err, entry.WithError(err).Data["error"])
-
- ErrorKey = "err"
-
- assert.Equal(err, entry.WithError(err).Data["err"])
-
-}
-
-func TestEntryPanicln(t *testing.T) {
- errBoom := fmt.Errorf("boom time")
-
- defer func() {
- p := recover()
- assert.NotNil(t, p)
-
- switch pVal := p.(type) {
- case *Entry:
- assert.Equal(t, "kaboom", pVal.Message)
- assert.Equal(t, errBoom, pVal.Data["err"])
- default:
- t.Fatalf("want type *Entry, got %T: %#v", pVal, pVal)
- }
- }()
-
- logger := New()
- logger.Out = &bytes.Buffer{}
- entry := NewEntry(logger)
- entry.WithField("err", errBoom).Panicln("kaboom")
-}
-
-func TestEntryPanicf(t *testing.T) {
- errBoom := fmt.Errorf("boom again")
-
- defer func() {
- p := recover()
- assert.NotNil(t, p)
-
- switch pVal := p.(type) {
- case *Entry:
- assert.Equal(t, "kaboom true", pVal.Message)
- assert.Equal(t, errBoom, pVal.Data["err"])
- default:
- t.Fatalf("want type *Entry, got %T: %#v", pVal, pVal)
- }
- }()
-
- logger := New()
- logger.Out = &bytes.Buffer{}
- entry := NewEntry(logger)
- entry.WithField("err", errBoom).Panicf("kaboom %v", true)
-}
diff --git a/vendor/github.com/Sirupsen/logrus/formatter_bench_test.go b/vendor/github.com/Sirupsen/logrus/formatter_bench_test.go
deleted file mode 100644
index c6d290c7..00000000
--- a/vendor/github.com/Sirupsen/logrus/formatter_bench_test.go
+++ /dev/null
@@ -1,98 +0,0 @@
-package logrus
-
-import (
- "fmt"
- "testing"
- "time"
-)
-
-// smallFields is a small size data set for benchmarking
-var smallFields = Fields{
- "foo": "bar",
- "baz": "qux",
- "one": "two",
- "three": "four",
-}
-
-// largeFields is a large size data set for benchmarking
-var largeFields = Fields{
- "foo": "bar",
- "baz": "qux",
- "one": "two",
- "three": "four",
- "five": "six",
- "seven": "eight",
- "nine": "ten",
- "eleven": "twelve",
- "thirteen": "fourteen",
- "fifteen": "sixteen",
- "seventeen": "eighteen",
- "nineteen": "twenty",
- "a": "b",
- "c": "d",
- "e": "f",
- "g": "h",
- "i": "j",
- "k": "l",
- "m": "n",
- "o": "p",
- "q": "r",
- "s": "t",
- "u": "v",
- "w": "x",
- "y": "z",
- "this": "will",
- "make": "thirty",
- "entries": "yeah",
-}
-
-var errorFields = Fields{
- "foo": fmt.Errorf("bar"),
- "baz": fmt.Errorf("qux"),
-}
-
-func BenchmarkErrorTextFormatter(b *testing.B) {
- doBenchmark(b, &TextFormatter{DisableColors: true}, errorFields)
-}
-
-func BenchmarkSmallTextFormatter(b *testing.B) {
- doBenchmark(b, &TextFormatter{DisableColors: true}, smallFields)
-}
-
-func BenchmarkLargeTextFormatter(b *testing.B) {
- doBenchmark(b, &TextFormatter{DisableColors: true}, largeFields)
-}
-
-func BenchmarkSmallColoredTextFormatter(b *testing.B) {
- doBenchmark(b, &TextFormatter{ForceColors: true}, smallFields)
-}
-
-func BenchmarkLargeColoredTextFormatter(b *testing.B) {
- doBenchmark(b, &TextFormatter{ForceColors: true}, largeFields)
-}
-
-func BenchmarkSmallJSONFormatter(b *testing.B) {
- doBenchmark(b, &JSONFormatter{}, smallFields)
-}
-
-func BenchmarkLargeJSONFormatter(b *testing.B) {
- doBenchmark(b, &JSONFormatter{}, largeFields)
-}
-
-func doBenchmark(b *testing.B, formatter Formatter, fields Fields) {
- entry := &Entry{
- Time: time.Time{},
- Level: InfoLevel,
- Message: "message",
- Data: fields,
- }
- var d []byte
- var err error
- for i := 0; i < b.N; i++ {
- d, err = formatter.Format(entry)
- if err != nil {
- b.Fatal(err)
- }
- b.SetBytes(int64(len(d)))
- }
-}
diff --git a/vendor/github.com/Sirupsen/logrus/hook_test.go b/vendor/github.com/Sirupsen/logrus/hook_test.go
deleted file mode 100644
index 13f34cb6..00000000
--- a/vendor/github.com/Sirupsen/logrus/hook_test.go
+++ /dev/null
@@ -1,122 +0,0 @@
-package logrus
-
-import (
- "testing"
-
- "github.com/stretchr/testify/assert"
-)
-
-type TestHook struct {
- Fired bool
-}
-
-func (hook *TestHook) Fire(entry *Entry) error {
- hook.Fired = true
- return nil
-}
-
-func (hook *TestHook) Levels() []Level {
- return []Level{
- DebugLevel,
- InfoLevel,
- WarnLevel,
- ErrorLevel,
- FatalLevel,
- PanicLevel,
- }
-}
-
-func TestHookFires(t *testing.T) {
- hook := new(TestHook)
-
- LogAndAssertJSON(t, func(log *Logger) {
- log.Hooks.Add(hook)
- assert.Equal(t, hook.Fired, false)
-
- log.Print("test")
- }, func(fields Fields) {
- assert.Equal(t, hook.Fired, true)
- })
-}
-
-type ModifyHook struct {
-}
-
-func (hook *ModifyHook) Fire(entry *Entry) error {
- entry.Data["wow"] = "whale"
- return nil
-}
-
-func (hook *ModifyHook) Levels() []Level {
- return []Level{
- DebugLevel,
- InfoLevel,
- WarnLevel,
- ErrorLevel,
- FatalLevel,
- PanicLevel,
- }
-}
-
-func TestHookCanModifyEntry(t *testing.T) {
- hook := new(ModifyHook)
-
- LogAndAssertJSON(t, func(log *Logger) {
- log.Hooks.Add(hook)
- log.WithField("wow", "elephant").Print("test")
- }, func(fields Fields) {
- assert.Equal(t, fields["wow"], "whale")
- })
-}
-
-func TestCanFireMultipleHooks(t *testing.T) {
- hook1 := new(ModifyHook)
- hook2 := new(TestHook)
-
- LogAndAssertJSON(t, func(log *Logger) {
- log.Hooks.Add(hook1)
- log.Hooks.Add(hook2)
-
- log.WithField("wow", "elephant").Print("test")
- }, func(fields Fields) {
- assert.Equal(t, fields["wow"], "whale")
- assert.Equal(t, hook2.Fired, true)
- })
-}
-
-type ErrorHook struct {
- Fired bool
-}
-
-func (hook *ErrorHook) Fire(entry *Entry) error {
- hook.Fired = true
- return nil
-}
-
-func (hook *ErrorHook) Levels() []Level {
- return []Level{
- ErrorLevel,
- }
-}
-
-func TestErrorHookShouldntFireOnInfo(t *testing.T) {
- hook := new(ErrorHook)
-
- LogAndAssertJSON(t, func(log *Logger) {
- log.Hooks.Add(hook)
- log.Info("test")
- }, func(fields Fields) {
- assert.Equal(t, hook.Fired, false)
- })
-}
-
-func TestErrorHookShouldFireOnError(t *testing.T) {
- hook := new(ErrorHook)
-
- LogAndAssertJSON(t, func(log *Logger) {
- log.Hooks.Add(hook)
- log.Error("test")
- }, func(fields Fields) {
- assert.Equal(t, hook.Fired, true)
- })
-}
diff --git a/vendor/github.com/Sirupsen/logrus/json_formatter_test.go b/vendor/github.com/Sirupsen/logrus/json_formatter_test.go
deleted file mode 100644
index 1d708732..00000000
--- a/vendor/github.com/Sirupsen/logrus/json_formatter_test.go
+++ /dev/null
@@ -1,120 +0,0 @@
-package logrus
-
-import (
- "encoding/json"
- "errors"
-
- "testing"
-)
-
-func TestErrorNotLost(t *testing.T) {
- formatter := &JSONFormatter{}
-
- b, err := formatter.Format(WithField("error", errors.New("wild walrus")))
- if err != nil {
- t.Fatal("Unable to format entry: ", err)
- }
-
- entry := make(map[string]interface{})
- err = json.Unmarshal(b, &entry)
- if err != nil {
- t.Fatal("Unable to unmarshal formatted entry: ", err)
- }
-
- if entry["error"] != "wild walrus" {
- t.Fatal("Error field not set")
- }
-}
-
-func TestErrorNotLostOnFieldNotNamedError(t *testing.T) {
- formatter := &JSONFormatter{}
-
- b, err := formatter.Format(WithField("omg", errors.New("wild walrus")))
- if err != nil {
- t.Fatal("Unable to format entry: ", err)
- }
-
- entry := make(map[string]interface{})
- err = json.Unmarshal(b, &entry)
- if err != nil {
- t.Fatal("Unable to unmarshal formatted entry: ", err)
- }
-
- if entry["omg"] != "wild walrus" {
- t.Fatal("Error field not set")
- }
-}
-
-func TestFieldClashWithTime(t *testing.T) {
- formatter := &JSONFormatter{}
-
- b, err := formatter.Format(WithField("time", "right now!"))
- if err != nil {
- t.Fatal("Unable to format entry: ", err)
- }
-
- entry := make(map[string]interface{})
- err = json.Unmarshal(b, &entry)
- if err != nil {
- t.Fatal("Unable to unmarshal formatted entry: ", err)
- }
-
- if entry["fields.time"] != "right now!" {
- t.Fatal("fields.time not set to original time field")
- }
-
- if entry["time"] != "0001-01-01T00:00:00Z" {
- t.Fatal("time field not set to current time, was: ", entry["time"])
- }
-}
-
-func TestFieldClashWithMsg(t *testing.T) {
- formatter := &JSONFormatter{}
-
- b, err := formatter.Format(WithField("msg", "something"))
- if err != nil {
- t.Fatal("Unable to format entry: ", err)
- }
-
- entry := make(map[string]interface{})
- err = json.Unmarshal(b, &entry)
- if err != nil {
- t.Fatal("Unable to unmarshal formatted entry: ", err)
- }
-
- if entry["fields.msg"] != "something" {
- t.Fatal("fields.msg not set to original msg field")
- }
-}
-
-func TestFieldClashWithLevel(t *testing.T) {
- formatter := &JSONFormatter{}
-
- b, err := formatter.Format(WithField("level", "something"))
- if err != nil {
- t.Fatal("Unable to format entry: ", err)
- }
-
- entry := make(map[string]interface{})
- err = json.Unmarshal(b, &entry)
- if err != nil {
- t.Fatal("Unable to unmarshal formatted entry: ", err)
- }
-
- if entry["fields.level"] != "something" {
- t.Fatal("fields.level not set to original level field")
- }
-}
-
-func TestJSONEntryEndsWithNewline(t *testing.T) {
- formatter := &JSONFormatter{}
-
- b, err := formatter.Format(WithField("level", "something"))
- if err != nil {
- t.Fatal("Unable to format entry: ", err)
- }
-
- if b[len(b)-1] != '\n' {
- t.Fatal("Expected JSON log entry to end with a newline")
- }
-}
diff --git a/vendor/github.com/Sirupsen/logrus/logrus_test.go b/vendor/github.com/Sirupsen/logrus/logrus_test.go
deleted file mode 100644
index b7d9302d..00000000
--- a/vendor/github.com/Sirupsen/logrus/logrus_test.go
+++ /dev/null
@@ -1,316 +0,0 @@
-package logrus
-
-import (
- "bytes"
- "encoding/json"
- "strconv"
- "strings"
- "sync"
- "testing"
-
- "github.com/stretchr/testify/assert"
-)
-
-func LogAndAssertJSON(t *testing.T, log func(*Logger), assertions func(fields Fields)) {
- var buffer bytes.Buffer
- var fields Fields
-
- logger := New()
- logger.Out = &buffer
- logger.Formatter = new(JSONFormatter)
-
- log(logger)
-
- err := json.Unmarshal(buffer.Bytes(), &fields)
- assert.Nil(t, err)
-
- assertions(fields)
-}
-
-func LogAndAssertText(t *testing.T, log func(*Logger), assertions func(fields map[string]string)) {
- var buffer bytes.Buffer
-
- logger := New()
- logger.Out = &buffer
- logger.Formatter = &TextFormatter{
- DisableColors: true,
- }
-
- log(logger)
-
- fields := make(map[string]string)
- for _, kv := range strings.Split(buffer.String(), " ") {
- if !strings.Contains(kv, "=") {
- continue
- }
- kvArr := strings.Split(kv, "=")
- key := strings.TrimSpace(kvArr[0])
- val := kvArr[1]
- if kvArr[1][0] == '"' {
- var err error
- val, err = strconv.Unquote(val)
- assert.NoError(t, err)
- }
- fields[key] = val
- }
- assertions(fields)
-}
-
-func TestPrint(t *testing.T) {
- LogAndAssertJSON(t, func(log *Logger) {
- log.Print("test")
- }, func(fields Fields) {
- assert.Equal(t, fields["msg"], "test")
- assert.Equal(t, fields["level"], "info")
- })
-}
-
-func TestInfo(t *testing.T) {
- LogAndAssertJSON(t, func(log *Logger) {
- log.Info("test")
- }, func(fields Fields) {
- assert.Equal(t, fields["msg"], "test")
- assert.Equal(t, fields["level"], "info")
- })
-}
-
-func TestWarn(t *testing.T) {
- LogAndAssertJSON(t, func(log *Logger) {
- log.Warn("test")
- }, func(fields Fields) {
- assert.Equal(t, fields["msg"], "test")
- assert.Equal(t, fields["level"], "warning")
- })
-}
-
-func TestInfolnShouldAddSpacesBetweenStrings(t *testing.T) {
- LogAndAssertJSON(t, func(log *Logger) {
- log.Infoln("test", "test")
- }, func(fields Fields) {
- assert.Equal(t, fields["msg"], "test test")
- })
-}
-
-func TestInfolnShouldAddSpacesBetweenStringAndNonstring(t *testing.T) {
- LogAndAssertJSON(t, func(log *Logger) {
- log.Infoln("test", 10)
- }, func(fields Fields) {
- assert.Equal(t, fields["msg"], "test 10")
- })
-}
-
-func TestInfolnShouldAddSpacesBetweenTwoNonStrings(t *testing.T) {
- LogAndAssertJSON(t, func(log *Logger) {
- log.Infoln(10, 10)
- }, func(fields Fields) {
- assert.Equal(t, fields["msg"], "10 10")
- })
-}
-
-func TestInfoShouldAddSpacesBetweenTwoNonStrings(t *testing.T) {
- LogAndAssertJSON(t, func(log *Logger) {
- log.Infoln(10, 10)
- }, func(fields Fields) {
- assert.Equal(t, fields["msg"], "10 10")
- })
-}
-
-func TestInfoShouldNotAddSpacesBetweenStringAndNonstring(t *testing.T) {
- LogAndAssertJSON(t, func(log *Logger) {
- log.Info("test", 10)
- }, func(fields Fields) {
- assert.Equal(t, fields["msg"], "test10")
- })
-}
-
-func TestInfoShouldNotAddSpacesBetweenStrings(t *testing.T) {
- LogAndAssertJSON(t, func(log *Logger) {
- log.Info("test", "test")
- }, func(fields Fields) {
- assert.Equal(t, fields["msg"], "testtest")
- })
-}
-
-func TestWithFieldsShouldAllowAssignments(t *testing.T) {
- var buffer bytes.Buffer
- var fields Fields
-
- logger := New()
- logger.Out = &buffer
- logger.Formatter = new(JSONFormatter)
-
- localLog := logger.WithFields(Fields{
- "key1": "value1",
- })
-
- localLog.WithField("key2", "value2").Info("test")
- err := json.Unmarshal(buffer.Bytes(), &fields)
- assert.Nil(t, err)
-
- assert.Equal(t, "value2", fields["key2"])
- assert.Equal(t, "value1", fields["key1"])
-
- buffer = bytes.Buffer{}
- fields = Fields{}
- localLog.Info("test")
- err = json.Unmarshal(buffer.Bytes(), &fields)
- assert.Nil(t, err)
-
- _, ok := fields["key2"]
- assert.Equal(t, false, ok)
- assert.Equal(t, "value1", fields["key1"])
-}
-
-func TestUserSuppliedFieldDoesNotOverwriteDefaults(t *testing.T) {
- LogAndAssertJSON(t, func(log *Logger) {
- log.WithField("msg", "hello").Info("test")
- }, func(fields Fields) {
- assert.Equal(t, fields["msg"], "test")
- })
-}
-
-func TestUserSuppliedMsgFieldHasPrefix(t *testing.T) {
- LogAndAssertJSON(t, func(log *Logger) {
- log.WithField("msg", "hello").Info("test")
- }, func(fields Fields) {
- assert.Equal(t, fields["msg"], "test")
- assert.Equal(t, fields["fields.msg"], "hello")
- })
-}
-
-func TestUserSuppliedTimeFieldHasPrefix(t *testing.T) {
- LogAndAssertJSON(t, func(log *Logger) {
- log.WithField("time", "hello").Info("test")
- }, func(fields Fields) {
- assert.Equal(t, fields["fields.time"], "hello")
- })
-}
-
-func TestUserSuppliedLevelFieldHasPrefix(t *testing.T) {
- LogAndAssertJSON(t, func(log *Logger) {
- log.WithField("level", 1).Info("test")
- }, func(fields Fields) {
- assert.Equal(t, fields["level"], "info")
- assert.Equal(t, fields["fields.level"], 1.0) // JSON has floats only
- })
-}
-
-func TestDefaultFieldsAreNotPrefixed(t *testing.T) {
- LogAndAssertText(t, func(log *Logger) {
- ll := log.WithField("herp", "derp")
- ll.Info("hello")
- ll.Info("bye")
- }, func(fields map[string]string) {
- for _, fieldName := range []string{"fields.level", "fields.time", "fields.msg"} {
- if _, ok := fields[fieldName]; ok {
- t.Fatalf("should not have prefixed %q: %v", fieldName, fields)
- }
- }
- })
-}
-
-func TestDoubleLoggingDoesntPrefixPreviousFields(t *testing.T) {
-
- var buffer bytes.Buffer
- var fields Fields
-
- logger := New()
- logger.Out = &buffer
- logger.Formatter = new(JSONFormatter)
-
- llog := logger.WithField("context", "eating raw fish")
-
- llog.Info("looks delicious")
-
- err := json.Unmarshal(buffer.Bytes(), &fields)
- assert.NoError(t, err, "should have decoded first message")
- assert.Equal(t, len(fields), 4, "should only have msg/time/level/context fields")
- assert.Equal(t, fields["msg"], "looks delicious")
- assert.Equal(t, fields["context"], "eating raw fish")
-
- buffer.Reset()
-
- llog.Warn("omg it is!")
-
- err = json.Unmarshal(buffer.Bytes(), &fields)
- assert.NoError(t, err, "should have decoded second message")
- assert.Equal(t, len(fields), 4, "should only have msg/time/level/context fields")
- assert.Equal(t, fields["msg"], "omg it is!")
- assert.Equal(t, fields["context"], "eating raw fish")
- assert.Nil(t, fields["fields.msg"], "should not have prefixed previous `msg` entry")
-
-}
-
-func TestConvertLevelToString(t *testing.T) {
- assert.Equal(t, "debug", DebugLevel.String())
- assert.Equal(t, "info", InfoLevel.String())
- assert.Equal(t, "warning", WarnLevel.String())
- assert.Equal(t, "error", ErrorLevel.String())
- assert.Equal(t, "fatal", FatalLevel.String())
- assert.Equal(t, "panic", PanicLevel.String())
-}
-
-func TestParseLevel(t *testing.T) {
- l, err := ParseLevel("panic")
- assert.Nil(t, err)
- assert.Equal(t, PanicLevel, l)
-
- l, err = ParseLevel("fatal")
- assert.Nil(t, err)
- assert.Equal(t, FatalLevel, l)
-
- l, err = ParseLevel("error")
- assert.Nil(t, err)
- assert.Equal(t, ErrorLevel, l)
-
- l, err = ParseLevel("warn")
- assert.Nil(t, err)
- assert.Equal(t, WarnLevel, l)
-
- l, err = ParseLevel("warning")
- assert.Nil(t, err)
- assert.Equal(t, WarnLevel, l)
-
- l, err = ParseLevel("info")
- assert.Nil(t, err)
- assert.Equal(t, InfoLevel, l)
-
- l, err = ParseLevel("debug")
- assert.Nil(t, err)
- assert.Equal(t, DebugLevel, l)
-
- l, err = ParseLevel("invalid")
- assert.Equal(t, "not a valid logrus Level: \"invalid\"", err.Error())
-}
-
-func TestGetSetLevelRace(t *testing.T) {
- wg := sync.WaitGroup{}
- for i := 0; i < 100; i++ {
- wg.Add(1)
- go func(i int) {
- defer wg.Done()
- if i%2 == 0 {
- SetLevel(InfoLevel)
- } else {
- GetLevel()
- }
- }(i)
-
- }
- wg.Wait()
-}
-
-func TestLoggingRace(t *testing.T) {
- logger := New()
-
- var wg sync.WaitGroup
- wg.Add(100)
-
- for i := 0; i < 100; i++ {
- go func() {
- logger.Info("info")
- wg.Done()
- }()
- }
- wg.Wait()
-}
diff --git a/vendor/github.com/Sirupsen/logrus/text_formatter_test.go b/vendor/github.com/Sirupsen/logrus/text_formatter_test.go
deleted file mode 100644
index e25a44f6..00000000
--- a/vendor/github.com/Sirupsen/logrus/text_formatter_test.go
+++ /dev/null
@@ -1,61 +0,0 @@
-package logrus
-
-import (
- "bytes"
- "errors"
- "testing"
- "time"
-)
-
-func TestQuoting(t *testing.T) {
- tf := &TextFormatter{DisableColors: true}
-
- checkQuoting := func(q bool, value interface{}) {
- b, _ := tf.Format(WithField("test", value))
- idx := bytes.Index(b, ([]byte)("test="))
- cont := bytes.Contains(b[idx+5:], []byte{'"'})
- if cont != q {
- if q {
- t.Errorf("quoting expected for: %#v", value)
- } else {
- t.Errorf("quoting not expected for: %#v", value)
- }
- }
- }
-
- checkQuoting(false, "abcd")
- checkQuoting(false, "v1.0")
- checkQuoting(false, "1234567890")
- checkQuoting(true, "/foobar")
- checkQuoting(true, "x y")
- checkQuoting(true, "x,y")
- checkQuoting(false, errors.New("invalid"))
- checkQuoting(true, errors.New("invalid argument"))
-}
-
-func TestTimestampFormat(t *testing.T) {
- checkTimeStr := func(format string) {
- customFormatter := &TextFormatter{DisableColors: true, TimestampFormat: format}
- customStr, _ := customFormatter.Format(WithField("test", "test"))
- timeStart := bytes.Index(customStr, ([]byte)("time="))
- timeEnd := bytes.Index(customStr, ([]byte)("level="))
- timeStr := customStr[timeStart+5 : timeEnd-1]
- if timeStr[0] == '"' && timeStr[len(timeStr)-1] == '"' {
- timeStr = timeStr[1 : len(timeStr)-1]
- }
- if format == "" {
- format = time.RFC3339
- }
- _, e := time.Parse(format, (string)(timeStr))
- if e != nil {
- t.Errorf("time string \"%s\" did not match provided time format \"%s\": %s", timeStr, format, e)
- }
- }
-
- checkTimeStr("2006-01-02T15:04:05.000000000Z07:00")
- checkTimeStr("Mon Jan _2 15:04:05 2006")
- checkTimeStr("")
-}
-
-// TODO add tests for sorting etc., this requires a parser for the text
-// formatter output.
diff --git a/vendor/github.com/cloudfoundry-incubator/candiedyaml/candiedyaml_suite_test.go b/vendor/github.com/cloudfoundry-incubator/candiedyaml/candiedyaml_suite_test.go
deleted file mode 100644
index 0b97fe94..00000000
--- a/vendor/github.com/cloudfoundry-incubator/candiedyaml/candiedyaml_suite_test.go
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
-Licensed under the Apache License, Version 2.0 (the "License");
-you may not use this file except in compliance with the License.
-You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS,
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-See the License for the specific language governing permissions and
-limitations under the License.
-*/
-
-package candiedyaml
-
-import (
- . "github.com/onsi/ginkgo"
- . "github.com/onsi/gomega"
-
- "testing"
-)
-
-func TestCandiedyaml(t *testing.T) {
- RegisterFailHandler(Fail)
- RunSpecs(t, "Candiedyaml Suite")
-}
diff --git a/vendor/github.com/cloudfoundry-incubator/candiedyaml/decode_test.go b/vendor/github.com/cloudfoundry-incubator/candiedyaml/decode_test.go
deleted file mode 100644
index dd180b57..00000000
--- a/vendor/github.com/cloudfoundry-incubator/candiedyaml/decode_test.go
+++ /dev/null
@@ -1,915 +0,0 @@
-/*
-Licensed under the Apache License, Version 2.0 (the "License");
-you may not use this file except in compliance with the License.
-You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS,
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-See the License for the specific language governing permissions and
-limitations under the License.
-*/
-
-package candiedyaml
-
-import (
- "math"
- "os"
- "strconv"
- "strings"
- "time"
-
- . "github.com/onsi/ginkgo"
- . "github.com/onsi/gomega"
-)
-
-var _ = Describe("Decode", func() {
- It("Decodes a file", func() {
- f, _ := os.Open("fixtures/specification/example2_1.yaml")
- d := NewDecoder(f)
- var v interface{}
- err := d.Decode(&v)
-
- Expect(err).NotTo(HaveOccurred())
- })
-
- Context("strings", func() {
- It("Decodes an empty string", func() {
- d := NewDecoder(strings.NewReader(`""
-`))
- var v string
- err := d.Decode(&v)
- Expect(err).NotTo(HaveOccurred())
- Expect(v).To(Equal(""))
- })
-
- It("Decodes an empty string to an interface", func() {
- d := NewDecoder(strings.NewReader(`""
-`))
- var v interface{}
- err := d.Decode(&v)
- Expect(err).NotTo(HaveOccurred())
- Expect(v).To(Equal(""))
- })
-
- It("Decodes a map containing empty strings to an interface", func() {
- d := NewDecoder(strings.NewReader(`"" : ""
-`))
- var v interface{}
- err := d.Decode(&v)
- Expect(err).NotTo(HaveOccurred())
- Expect(v).To(Equal(map[interface{}]interface{}{"": ""}))
- })
-
- It("Decodes strings starting with a colon", func() {
- d := NewDecoder(strings.NewReader(`:colon
-`))
- var v interface{}
- err := d.Decode(&v)
- Expect(err).NotTo(HaveOccurred())
- Expect(v).To(Equal(":colon"))
- })
- })
-
- Context("Sequence", func() {
- It("Decodes to interface{}s", func() {
- f, _ := os.Open("fixtures/specification/example2_1.yaml")
- d := NewDecoder(f)
- var v interface{}
- err := d.Decode(&v)
-
- Expect(err).NotTo(HaveOccurred())
- Expect((v).([]interface{})).To(Equal([]interface{}{"Mark McGwire", "Sammy Sosa", "Ken Griffey"}))
- })
-
- It("Decodes to []string", func() {
- f, _ := os.Open("fixtures/specification/example2_1.yaml")
- d := NewDecoder(f)
- v := make([]string, 0, 3)
-
- err := d.Decode(&v)
- Expect(err).NotTo(HaveOccurred())
- Expect(v).To(Equal([]string{"Mark McGwire", "Sammy Sosa", "Ken Griffey"}))
- })
-
- It("Decodes a sequence of maps", func() {
- f, _ := os.Open("fixtures/specification/example2_12.yaml")
- d := NewDecoder(f)
- v := make([]map[string]interface{}, 1)
-
- err := d.Decode(&v)
- Expect(err).NotTo(HaveOccurred())
- Expect(v).To(Equal([]map[string]interface{}{
- {"item": "Super Hoop", "quantity": int64(1)},
- {"item": "Basketball", "quantity": int64(4)},
- {"item": "Big Shoes", "quantity": int64(1)},
- }))
-
- })
-
- Describe("As structs", func() {
- It("Simple struct", func() {
- f, _ := os.Open("fixtures/specification/example2_4.yaml")
- d := NewDecoder(f)
-
- type batter struct {
- Name string
- HR int64
- AVG float64
- }
- v := make([]batter, 0, 1)
-
- err := d.Decode(&v)
- Expect(err).NotTo(HaveOccurred())
- Expect(v).To(Equal([]batter{
- batter{Name: "Mark McGwire", HR: 65, AVG: 0.278},
- batter{Name: "Sammy Sosa", HR: 63, AVG: 0.288},
- }))
-
- })
-
- It("Tagged struct", func() {
- f, _ := os.Open("fixtures/specification/example2_4.yaml")
- d := NewDecoder(f)
-
- type batter struct {
- N string `yaml:"name"`
- H int64 `yaml:"hr"`
- A float64 `yaml:"avg"`
- }
- v := make([]batter, 0, 1)
-
- err := d.Decode(&v)
- Expect(err).NotTo(HaveOccurred())
- Expect(v).To(Equal([]batter{
- batter{N: "Mark McGwire", H: 65, A: 0.278},
- batter{N: "Sammy Sosa", H: 63, A: 0.288},
- }))
-
- })
-
- It("handles null values", func() {
- type S struct {
- Default interface{}
- }
-
- d := NewDecoder(strings.NewReader(`
----
-default:
-`))
- var s S
- err := d.Decode(&s)
- Expect(err).NotTo(HaveOccurred())
- Expect(s).To(Equal(S{Default: nil}))
-
- })
-
- It("ignores missing tags", func() {
- f, _ := os.Open("fixtures/specification/example2_4.yaml")
- d := NewDecoder(f)
-
- type batter struct {
- N string `yaml:"name"`
- HR int64
- A float64
- }
- v := make([]batter, 0, 1)
-
- err := d.Decode(&v)
- Expect(err).NotTo(HaveOccurred())
- Expect(v).To(Equal([]batter{
- batter{N: "Mark McGwire", HR: 65},
- batter{N: "Sammy Sosa", HR: 63},
- }))
-
- })
- })
-
- It("Decodes a sequence of sequences", func() {
- f, _ := os.Open("fixtures/specification/example2_5.yaml")
- d := NewDecoder(f)
- v := make([][]interface{}, 1)
-
- err := d.Decode(&v)
- Expect(err).NotTo(HaveOccurred())
- Expect(v).To(Equal([][]interface{}{
- {"name", "hr", "avg"},
- {"Mark McGwire", int64(65), float64(0.278)},
- {"Sammy Sosa", int64(63), float64(0.288)},
- }))
-
- })
- })
-
- Context("Maps", func() {
- It("Decodes to interface{}s", func() {
- f, _ := os.Open("fixtures/specification/example2_2.yaml")
- d := NewDecoder(f)
- var v interface{}
-
- err := d.Decode(&v)
- Expect(err).NotTo(HaveOccurred())
- Expect((v).(map[interface{}]interface{})).To(Equal(map[interface{}]interface{}{
- "hr": int64(65),
- "avg": float64(0.278),
- "rbi": int64(147),
- }))
-
- })
-
- It("Decodes to a struct", func() {
- f, _ := os.Open("fixtures/specification/example2_2.yaml")
- d := NewDecoder(f)
-
- type batter struct {
- HR int64
- AVG float64
- RBI int64
- }
- v := batter{}
-
- err := d.Decode(&v)
- Expect(err).NotTo(HaveOccurred())
- Expect(v).To(Equal(batter{HR: 65, AVG: 0.278, RBI: 147}))
- })
-
- It("Decodes to a map of string arrays", func() {
- f, _ := os.Open("fixtures/specification/example2_9.yaml")
- d := NewDecoder(f)
- v := make(map[string][]string)
-
- err := d.Decode(&v)
- Expect(err).NotTo(HaveOccurred())
- Expect(v).To(Equal(map[string][]string{"hr": []string{"Mark McGwire", "Sammy Sosa"}, "rbi": []string{"Sammy Sosa", "Ken Griffey"}}))
- })
- })
-
- Context("Sequence of Maps", func() {
- It("Decodes to interface{}s", func() {
- f, _ := os.Open("fixtures/specification/example2_4.yaml")
- d := NewDecoder(f)
- var v interface{}
-
- err := d.Decode(&v)
- Expect(err).NotTo(HaveOccurred())
- Expect((v).([]interface{})).To(Equal([]interface{}{
- map[interface{}]interface{}{"name": "Mark McGwire", "hr": int64(65), "avg": float64(0.278)},
- map[interface{}]interface{}{"name": "Sammy Sosa", "hr": int64(63), "avg": float64(0.288)},
- }))
-
- })
- })
-
- It("Decodes ascii art", func() {
- f, _ := os.Open("fixtures/specification/example2_13.yaml")
- d := NewDecoder(f)
- v := ""
-
- err := d.Decode(&v)
- Expect(err).NotTo(HaveOccurred())
- Expect(v).To(Equal(`\//||\/||
-// || ||__
-`))
-
- })
-
- It("Decodes folded strings", func() {
- f, _ := os.Open("fixtures/specification/example2_15.yaml")
- d := NewDecoder(f)
- v := ""
-
- err := d.Decode(&v)
- Expect(err).NotTo(HaveOccurred())
- Expect(v).To(Equal("Sammy Sosa completed another fine season with great stats.\n\n 63 Home Runs\n 0.288 Batting Average\n\nWhat a year!\n"))
- })
-
- It("Decodes literal and folded strings with indents", func() {
- f, _ := os.Open("fixtures/specification/example2_16.yaml")
- d := NewDecoder(f)
- v := make(map[string]string)
-
- err := d.Decode(&v)
- Expect(err).NotTo(HaveOccurred())
- Expect(v).To(Equal(map[string]string{
- "name": "Mark McGwire",
- "accomplishment": `Mark set a major league home run record in 1998.
-`,
- "stats": `65 Home Runs
-0.278 Batting Average
-`,
- }))
-
- })
-
- It("Decodes single quoted", func() {
- f, _ := os.Open("fixtures/specification/example2_17_quoted.yaml")
- d := NewDecoder(f)
- v := make(map[string]string)
-
- err := d.Decode(&v)
- Expect(err).NotTo(HaveOccurred())
- Expect(v).To(Equal(map[string]string{
- "quoted": ` # not a 'comment'.`,
- }))
-
- })
-
- Context("ints", func() {
- It("Decodes into an interface{}", func() {
- f, _ := os.Open("fixtures/specification/example2_19.yaml")
- d := NewDecoder(f)
- v := make(map[string]interface{})
-
- err := d.Decode(&v)
- Expect(err).NotTo(HaveOccurred())
- Expect(v).To(Equal(map[string]interface{}{
- "canonical": int64(12345),
- "decimal": int64(12345),
- "octal": int64(12),
- "hexadecimal": int64(12),
- }))
-
- })
-
- It("Decodes into int64", func() {
- f, _ := os.Open("fixtures/specification/example2_19.yaml")
- d := NewDecoder(f)
- v := make(map[string]int64)
-
- err := d.Decode(&v)
- Expect(err).NotTo(HaveOccurred())
- Expect(v).To(Equal(map[string]int64{
- "canonical": int64(12345),
- "decimal": int64(12345),
- "octal": int64(12),
- "hexadecimal": int64(12),
- }))
-
- })
-
- Context("boundary values", func() {
- intoInt64 := func(val int64) {
- It("Decodes into an int64 value", func() {
- var v int64
-
- d := NewDecoder(strings.NewReader(strconv.FormatInt(val, 10)))
- err := d.Decode(&v)
- Expect(err).NotTo(HaveOccurred())
- Expect(v).To(Equal(val))
-
- })
- }
-
- intoInt := func(val int) {
- It("Decodes into an int value", func() {
- var v int
-
- d := NewDecoder(strings.NewReader(strconv.FormatInt(int64(val), 10)))
- err := d.Decode(&v)
- Expect(err).NotTo(HaveOccurred())
- Expect(v).To(Equal(val))
-
- })
- }
-
- intoInterface := func(val int64) {
- It("Decodes into an interface{}", func() {
- var v interface{}
-
- d := NewDecoder(strings.NewReader(strconv.FormatInt(val, 10)))
- err := d.Decode(&v)
- Expect(err).NotTo(HaveOccurred())
- Expect(v).To(Equal(val))
- })
- }
-
- intoInt64(math.MaxInt64)
- intoInterface(math.MaxInt64)
-
- intoInt64(math.MinInt64)
- intoInterface(math.MinInt64)
-
- intoInt(math.MaxInt32)
- intoInt(math.MinInt32)
- })
- })
-
- It("Decodes a variety of floats", func() {
- f, _ := os.Open("fixtures/specification/example2_20.yaml")
- d := NewDecoder(f)
- v := make(map[string]float64)
-
- err := d.Decode(&v)
- Expect(err).NotTo(HaveOccurred())
-
- Expect(math.IsNaN(v["not a number"])).To(BeTrue())
- delete(v, "not a number")
-
- Expect(v).To(Equal(map[string]float64{
- "canonical": float64(1230.15),
- "exponential": float64(1230.15),
- "fixed": float64(1230.15),
- "negative infinity": math.Inf(-1),
- }))
-
- })
-
- It("Decodes booleans, nil and strings", func() {
- f, _ := os.Open("fixtures/specification/example2_21.yaml")
- d := NewDecoder(f)
- v := make(map[string]interface{})
-
- err := d.Decode(&v)
- Expect(err).NotTo(HaveOccurred())
- Expect(v).To(Equal(map[string]interface{}{
- "": interface{}(nil),
- "true": true,
- "false": false,
- "string": "12345",
- }))
-
- })
-
- It("Decodes a null ptr", func() {
- d := NewDecoder(strings.NewReader(`null
-`))
- var v *bool
- err := d.Decode(&v)
- Expect(err).NotTo(HaveOccurred())
- Expect(v).To(BeNil())
- })
-
- It("Decodes dates/time", func() {
- f, _ := os.Open("fixtures/specification/example2_22.yaml")
- d := NewDecoder(f)
- v := make(map[string]time.Time)
-
- err := d.Decode(&v)
- Expect(err).NotTo(HaveOccurred())
- Expect(v).To(Equal(map[string]time.Time{
- "canonical": time.Date(2001, time.December, 15, 2, 59, 43, int(1*time.Millisecond), time.UTC),
- "iso8601": time.Date(2001, time.December, 14, 21, 59, 43, int(10*time.Millisecond), time.FixedZone("", -5*3600)),
- "spaced": time.Date(2001, time.December, 14, 21, 59, 43, int(10*time.Millisecond), time.FixedZone("", -5*3600)),
- "date": time.Date(2002, time.December, 14, 0, 0, 0, 0, time.UTC),
- }))
-
- })
-
- Context("Tags", func() {
- It("Respects tags", func() {
- f, _ := os.Open("fixtures/specification/example2_23_non_date.yaml")
- d := NewDecoder(f)
- v := make(map[string]string)
-
- err := d.Decode(&v)
- Expect(err).NotTo(HaveOccurred())
- Expect(v).To(Equal(map[string]string{
- "not-date": "2002-04-28",
- }))
-
- })
-
- It("handles non-specific tags", func() {
- d := NewDecoder(strings.NewReader(`
----
-not_parsed: ! 123
-`))
- v := make(map[string]int)
- err := d.Decode(&v)
- Expect(err).NotTo(HaveOccurred())
- Expect(v).To(Equal(map[string]int{"not_parsed": 123}))
- })
-
- It("handles non-specific tags", func() {
- d := NewDecoder(strings.NewReader(`
----
-? a complex key
-: ! "123"
-`))
- v := make(map[string]string)
- err := d.Decode(&v)
- Expect(err).NotTo(HaveOccurred())
- Expect(v).To(Equal(map[string]string{"a complex key": "123"}))
- })
- })
-
- Context("Decodes binary/base64", func() {
- It("to []byte", func() {
- f, _ := os.Open("fixtures/specification/example2_23_picture.yaml")
- d := NewDecoder(f)
- v := make(map[string][]byte)
-
- err := d.Decode(&v)
- Expect(err).NotTo(HaveOccurred())
- Expect(v).To(Equal(map[string][]byte{
- "picture": []byte{0x47, 0x49, 0x46, 0x38, 0x39, 0x61, 0x0c, 0x00,
- 0x0c, 0x00, 0x84, 0x00, 0x00, 0xff, 0xff, 0xf7, 0xf5, 0xf5, 0xee,
- 0xe9, 0xe9, 0xe5, 0x66, 0x66, 0x66, 0x00, 0x00, 0x00, 0xe7, 0xe7,
- 0xe7, 0x5e, 0x5e, 0x5e, 0xf3, 0xf3, 0xed, 0x8e, 0x8e, 0x8e, 0xe0,
- 0xe0, 0xe0, 0x9f, 0x9f, 0x9f, 0x93, 0x93, 0x93, 0xa7, 0xa7, 0xa7,
- 0x9e, 0x9e, 0x9e, 0x69, 0x5e, 0x10, 0x27, 0x20, 0x82, 0x0a, 0x01,
- 0x00, 0x3b},
- }))
-
- })
-
- It("to string", func() {
- d := NewDecoder(strings.NewReader("!binary YWJjZGVmZw=="))
- var v string
-
- err := d.Decode(&v)
- Expect(err).NotTo(HaveOccurred())
- Expect(v).To(Equal("abcdefg"))
- })
-
- It("to string via alternate form", func() {
- d := NewDecoder(strings.NewReader("!!binary YWJjZGVmZw=="))
- var v string
-
- err := d.Decode(&v)
- Expect(err).NotTo(HaveOccurred())
- Expect(v).To(Equal("abcdefg"))
- })
-
- It("to interface", func() {
- d := NewDecoder(strings.NewReader("!binary YWJjZGVmZw=="))
- var v interface{}
-
- err := d.Decode(&v)
- Expect(err).NotTo(HaveOccurred())
- Expect(v).To(Equal([]byte("abcdefg")))
- })
- })
-
- Context("Aliases", func() {
- Context("to known types", func() {
- It("aliases scalars", func() {
- f, _ := os.Open("fixtures/specification/example2_10.yaml")
- d := NewDecoder(f)
- v := make(map[string][]string)
-
- err := d.Decode(&v)
- Expect(err).NotTo(HaveOccurred())
- Expect(v).To(Equal(map[string][]string{
- "hr": {"Mark McGwire", "Sammy Sosa"},
- "rbi": {"Sammy Sosa", "Ken Griffey"},
- }))
-
- })
-
- It("aliases sequences", func() {
- d := NewDecoder(strings.NewReader(`
----
-hr: &ss
- - MG
- - SS
-rbi: *ss
-`))
- v := make(map[string][]string)
- err := d.Decode(&v)
- Expect(err).NotTo(HaveOccurred())
- Expect(v).To(Equal(map[string][]string{
- "hr": {"MG", "SS"},
- "rbi": {"MG", "SS"},
- }))
-
- })
-
- It("aliases maps", func() {
- d := NewDecoder(strings.NewReader(`
----
-hr: &ss
- MG : SS
-rbi: *ss
-`))
- v := make(map[string]map[string]string)
- err := d.Decode(&v)
- Expect(err).NotTo(HaveOccurred())
- Expect(v).To(Equal(map[string]map[string]string{
- "hr": {"MG": "SS"},
- "rbi": {"MG": "SS"},
- }))
-
- })
- })
-
- It("aliases to different types", func() {
- type S struct {
- A map[string]int
- C map[string]string
- }
- d := NewDecoder(strings.NewReader(`
----
-a: &map
- b : 1
-c: *map
-`))
- var s S
- err := d.Decode(&s)
- Expect(err).NotTo(HaveOccurred())
- Expect(s).To(Equal(S{
- A: map[string]int{"b": 1},
- C: map[string]string{"b": "1"},
- }))
-
- })
-
- It("fails if an anchor is undefined", func() {
- d := NewDecoder(strings.NewReader(`
----
-a: *missing
-`))
- m := make(map[string]string)
- err := d.Decode(&m)
- Expect(err).To(HaveOccurred())
- Expect(err.Error()).To(MatchRegexp("missing anchor.*line.*column.*"))
- })
-
- Context("to Interface", func() {
- It("aliases scalars", func() {
- f, _ := os.Open("fixtures/specification/example2_10.yaml")
- d := NewDecoder(f)
- v := make(map[string]interface{})
-
- err := d.Decode(&v)
- Expect(err).NotTo(HaveOccurred())
- Expect(v).To(Equal(map[string]interface{}{
- "hr": []interface{}{"Mark McGwire", "Sammy Sosa"},
- "rbi": []interface{}{"Sammy Sosa", "Ken Griffey"},
- }))
-
- })
-
- It("aliases sequences", func() {
- d := NewDecoder(strings.NewReader(`
----
-hr: &ss
- - MG
- - SS
-rbi: *ss
-`))
- v := make(map[string]interface{})
- err := d.Decode(&v)
- Expect(err).NotTo(HaveOccurred())
- Expect(v).To(Equal(map[string]interface{}{
- "hr": []interface{}{"MG", "SS"},
- "rbi": []interface{}{"MG", "SS"},
- }))
-
- })
-
- It("aliases maps", func() {
- d := NewDecoder(strings.NewReader(`
----
-hr: &ss
- MG : SS
-rbi: *ss
-`))
- v := make(map[string]interface{})
- err := d.Decode(&v)
- Expect(err).NotTo(HaveOccurred())
- Expect(v).To(Equal(map[string]interface{}{
- "hr": map[interface{}]interface{}{"MG": "SS"},
- "rbi": map[interface{}]interface{}{"MG": "SS"},
- }))
-
- })
-
- It("supports duplicate aliases", func() {
- d := NewDecoder(strings.NewReader(`
----
-a: &a
- b: 1
-x: *a
-y: *a
-`))
- v := make(map[string]interface{})
- err := d.Decode(&v)
- Expect(err).NotTo(HaveOccurred())
- Expect(v).To(Equal(map[string]interface{}{
- "a": map[interface{}]interface{}{"b": int64(1)},
- "x": map[interface{}]interface{}{"b": int64(1)},
- "y": map[interface{}]interface{}{"b": int64(1)},
- }))
-
- })
-
- It("supports overriden anchors", func() {
- d := NewDecoder(strings.NewReader(`
----
-First occurrence: &anchor Foo
-Second occurrence: *anchor
-Override anchor: &anchor Bar
-Reuse anchor: *anchor
-`))
- v := make(map[string]interface{})
- err := d.Decode(&v)
- Expect(err).NotTo(HaveOccurred())
- Expect(v).To(Equal(map[string]interface{}{
- "First occurrence": "Foo",
- "Second occurrence": "Foo",
- "Override anchor": "Bar",
- "Reuse anchor": "Bar",
- }))
-
- })
-
- It("fails if an anchor is undefined", func() {
- d := NewDecoder(strings.NewReader(`
----
-a: *missing
-`))
- var i interface{}
- err := d.Decode(&i)
- Expect(err).To(HaveOccurred())
- Expect(err.Error()).To(MatchRegexp("missing anchor.*line.*column.*"))
- })
-
- })
-
- It("supports composing aliases", func() {
- d := NewDecoder(strings.NewReader(`
----
-a: &a b
-x: &b
- d: *a
-z: *b
-`))
- v := make(map[string]interface{})
- err := d.Decode(&v)
- Expect(err).NotTo(HaveOccurred())
- Expect(v).To(Equal(map[string]interface{}{
- "a": "b",
- "x": map[interface{}]interface{}{"d": "b"},
- "z": map[interface{}]interface{}{"d": "b"},
- }))
-
- })
-
- It("redefinition while composing aliases", func() {
- d := NewDecoder(strings.NewReader(`
----
-a: &a b
-x: &c
- d : &a 1
-y: *a
-`))
- v := make(map[string]interface{})
- err := d.Decode(&v)
- Expect(err).NotTo(HaveOccurred())
- Expect(v).To(Equal(map[string]interface{}{
- "a": "b",
- "x": map[interface{}]interface{}{"d": int64(1)},
- "y": int64(1),
- }))
-
- })
-
- It("can parse nested anchors", func() {
- d := NewDecoder(strings.NewReader(`
----
-a:
- aa: &x
- aaa: 1
- ab:
- aba: &y
- abaa:
- abaaa: *x
-b:
-- ba:
- baa: *y
-`))
- v := make(map[string]interface{})
- err := d.Decode(&v)
- Expect(err).NotTo(HaveOccurred())
- })
- })
-
- Context("When decoding fails", func() {
- It("returns an error", func() {
- f, _ := os.Open("fixtures/specification/example_empty.yaml")
- d := NewDecoder(f)
- var v interface{}
-
- err := d.Decode(&v)
- Expect(err).To(HaveOccurred())
- Expect(err.Error()).To(Equal("Expected document start at line 0, column 0"))
- })
- })
-
- Context("Unmarshaler support", func() {
- Context("Receiver is a value", func() {
- It("the Marshaler interface is not used", func() {
- d := NewDecoder(strings.NewReader("abc\n"))
- v := hasMarshaler{}
-
- err := d.Decode(&v)
- Expect(err).NotTo(HaveOccurred())
- Expect(v.Value).To(BeNil())
- })
- })
-
- Context("Receiver is a pointer", func() {
- It("uses the Marshaler interface when a pointer", func() {
- d := NewDecoder(strings.NewReader("abc\n"))
- v := hasPtrMarshaler{}
-
- err := d.Decode(&v)
- Expect(err).NotTo(HaveOccurred())
- })
-
- It("marshals a scalar", func() {
- d := NewDecoder(strings.NewReader("abc\n"))
- v := hasPtrMarshaler{}
-
- err := d.Decode(&v)
- Expect(err).NotTo(HaveOccurred())
- Expect(v.Tag).To(Equal(yaml_STR_TAG))
- Expect(v.Value).To(Equal("abc"))
- })
-
- It("marshals a sequence", func() {
- d := NewDecoder(strings.NewReader("[abc, def]\n"))
- v := hasPtrMarshaler{}
-
- err := d.Decode(&v)
- Expect(err).NotTo(HaveOccurred())
- Expect(v.Tag).To(Equal(yaml_SEQ_TAG))
- Expect(v.Value).To(Equal([]interface{}{"abc", "def"}))
- })
-
- It("marshals a map", func() {
- d := NewDecoder(strings.NewReader("{ a: bc}\n"))
- v := hasPtrMarshaler{}
-
- err := d.Decode(&v)
- Expect(err).NotTo(HaveOccurred())
- Expect(v.Tag).To(Equal(yaml_MAP_TAG))
- Expect(v.Value).To(Equal(map[interface{}]interface{}{"a": "bc"}))
- })
- })
- })
-
- Context("Marshals into a Number", func() {
- It("when the number is an int", func() {
- d := NewDecoder(strings.NewReader("123\n"))
- d.UseNumber()
- var v Number
-
- err := d.Decode(&v)
- Expect(err).NotTo(HaveOccurred())
- Expect(v.String()).To(Equal("123"))
- })
-
- It("when the number is an float", func() {
- d := NewDecoder(strings.NewReader("1.23\n"))
- d.UseNumber()
- var v Number
-
- err := d.Decode(&v)
- Expect(err).NotTo(HaveOccurred())
- Expect(v.String()).To(Equal("1.23"))
- })
-
- It("it fails when its a non-Number", func() {
- d := NewDecoder(strings.NewReader("on\n"))
- d.UseNumber()
- var v Number
-
- err := d.Decode(&v)
- Expect(err).To(HaveOccurred())
- Expect(err.Error()).To(MatchRegexp("Not a number: 'on' at line 0, column 0"))
- })
-
- It("returns a Number", func() {
- d := NewDecoder(strings.NewReader("123\n"))
- d.UseNumber()
- var v interface{}
-
- err := d.Decode(&v)
- Expect(err).NotTo(HaveOccurred())
- Expect(v).To(BeAssignableToTypeOf(Number("")))
-
- n := v.(Number)
- Expect(n.String()).To(Equal("123"))
- })
- })
- Context("When there are special characters", func() {
- It("returns an error", func() {
- d := NewDecoder(strings.NewReader(`
----
-applications:
- - name: m
- services:
- - !@#
-`))
- var v interface{}
-
- err := d.Decode(&v)
- Expect(err).To(HaveOccurred())
- Expect(err.Error()).To(MatchRegexp("yaml.*did not find.*line.*column.*"))
- })
- })
-})
diff --git a/vendor/github.com/cloudfoundry-incubator/candiedyaml/encode_test.go b/vendor/github.com/cloudfoundry-incubator/candiedyaml/encode_test.go
deleted file mode 100644
index 82563c79..00000000
--- a/vendor/github.com/cloudfoundry-incubator/candiedyaml/encode_test.go
+++ /dev/null
@@ -1,642 +0,0 @@
-/*
-Licensed under the Apache License, Version 2.0 (the "License");
-you may not use this file except in compliance with the License.
-You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS,
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-See the License for the specific language governing permissions and
-limitations under the License.
-*/
-
-package candiedyaml
-
-import (
- "bytes"
- "errors"
- "math"
- "time"
-
- . "github.com/onsi/ginkgo"
- . "github.com/onsi/gomega"
-)
-
-var _ = Describe("Encode", func() {
- var buf *bytes.Buffer
- var enc *Encoder
-
- BeforeEach(func() {
- buf = &bytes.Buffer{}
- enc = NewEncoder(buf)
- })
-
- Context("Scalars", func() {
- It("handles strings", func() {
- err := enc.Encode("abc")
- Expect(err).NotTo(HaveOccurred())
- Expect(buf.String()).To(Equal(`abc
-`))
-
- })
-
- It("handles really short strings", func() {
- err := enc.Encode(".")
- Expect(err).NotTo(HaveOccurred())
- Expect(buf.String()).To(Equal(`.
-`))
-
- })
-
- It("encodes strings with multilines", func() {
- err := enc.Encode("a\nc")
- Expect(err).NotTo(HaveOccurred())
- Expect(buf.String()).To(Equal(`|-
- a
- c
-`))
-
- })
-
- It("handles strings that match known scalars", func() {
- err := enc.Encode("true")
- Expect(err).NotTo(HaveOccurred())
- Expect(buf.String()).To(Equal(`"true"
-`))
-
- })
-
- It("handles strings that contain colons followed by whitespace", func() {
- err := enc.Encode("contains: colon")
- Expect(err).NotTo(HaveOccurred())
- Expect(buf.String()).To(Equal(`'contains: colon'
-`))
-
- })
-
- Context("handles ints", func() {
- It("handles ints", func() {
- err := enc.Encode(13)
- Expect(err).NotTo(HaveOccurred())
- Expect(buf.String()).To(Equal("13\n"))
- })
-
- It("handles uints", func() {
- err := enc.Encode(uint64(1))
- Expect(err).NotTo(HaveOccurred())
- Expect(buf.String()).To(Equal("1\n"))
- })
- })
-
- Context("handles floats", func() {
- It("handles float32", func() {
- err := enc.Encode(float32(1.234))
- Expect(err).NotTo(HaveOccurred())
- Expect(buf.String()).To(Equal("1.234\n"))
-
- })
-
- It("handles float64", func() {
- err := enc.Encode(float64(1.2e23))
- Expect(err).NotTo(HaveOccurred())
- Expect(buf.String()).To(Equal("1.2e+23\n"))
- })
-
- It("handles NaN", func() {
- err := enc.Encode(math.NaN())
- Expect(err).NotTo(HaveOccurred())
- Expect(buf.String()).To(Equal(".nan\n"))
- })
-
- It("handles infinity", func() {
- err := enc.Encode(math.Inf(-1))
- Expect(err).NotTo(HaveOccurred())
- Expect(buf.String()).To(Equal("-.inf\n"))
- })
- })
-
- It("handles bools", func() {
- err := enc.Encode(true)
- Expect(err).NotTo(HaveOccurred())
- Expect(buf.String()).To(Equal("true\n"))
- })
-
- It("handles time.Time", func() {
- t := time.Now()
- err := enc.Encode(t)
- Expect(err).NotTo(HaveOccurred())
- bytes, _ := t.MarshalText()
- Expect(buf.String()).To(Equal(string(bytes) + "\n"))
- })
-
- Context("Null", func() {
- It("fails on nil", func() {
- err := enc.Encode(nil)
- Expect(err).To(HaveOccurred())
- })
- })
-
- It("handles []byte", func() {
- err := enc.Encode([]byte{'a', 'b', 'c'})
- Expect(err).NotTo(HaveOccurred())
- Expect(buf.String()).To(Equal("!!binary YWJj\n"))
- })
-
- Context("Ptrs", func() {
- It("handles ptr of a type", func() {
- p := new(int)
- *p = 10
- err := enc.Encode(p)
- Expect(err).NotTo(HaveOccurred())
- Expect(buf.String()).To(Equal("10\n"))
- })
-
- It("handles nil ptr", func() {
- var p *int
- err := enc.Encode(p)
- Expect(err).NotTo(HaveOccurred())
- Expect(buf.String()).To(Equal("null\n"))
- })
- })
-
- Context("Structs", func() {
- It("handles simple structs", func() {
- type batter struct {
- Name string
- HR int64
- AVG float64
- }
-
- batters := []batter{
- batter{Name: "Mark McGwire", HR: 65, AVG: 0.278},
- batter{Name: "Sammy Sosa", HR: 63, AVG: 0.288},
- }
- err := enc.Encode(batters)
- Expect(err).NotTo(HaveOccurred())
- Expect(buf.String()).To(Equal(`- Name: Mark McGwire
- HR: 65
- AVG: 0.278
-- Name: Sammy Sosa
- HR: 63
- AVG: 0.288
-`))
-
- })
-
- It("handles tagged structs", func() {
- type batter struct {
- Name string `yaml:"name"`
- HR int64
- AVG float64 `yaml:"avg"`
- }
-
- batters := []batter{
- batter{Name: "Mark McGwire", HR: 65, AVG: 0.278},
- batter{Name: "Sammy Sosa", HR: 63, AVG: 0.288},
- }
- err := enc.Encode(batters)
- Expect(err).NotTo(HaveOccurred())
- Expect(buf.String()).To(Equal(`- name: Mark McGwire
- HR: 65
- avg: 0.278
-- name: Sammy Sosa
- HR: 63
- avg: 0.288
-`))
-
- })
-
- It("handles nested structs", func() {
- type nestedConfig struct {
- AString string `yaml:"str"`
- Integer int `yaml:"int"`
- }
- type config struct {
- TopString string
- Nested nestedConfig
- }
-
- cfg := config{
- TopString: "def",
- Nested: nestedConfig{
- AString: "abc",
- Integer: 123,
- },
- }
-
- err := enc.Encode(cfg)
- Expect(err).NotTo(HaveOccurred())
-
- Expect(buf.String()).To(Equal(`TopString: def
-Nested:
- str: abc
- int: 123
-`))
-
- })
-
- It("handles inline structs", func() {
- type NestedConfig struct {
- AString string `yaml:"str"`
- Integer int `yaml:"int"`
- }
- type config struct {
- TopString string
- NestedConfig
- }
-
- cfg := config{
- TopString: "def",
- NestedConfig: NestedConfig{
- AString: "abc",
- Integer: 123,
- },
- }
-
- err := enc.Encode(cfg)
- Expect(err).NotTo(HaveOccurred())
-
- Expect(buf.String()).To(Equal(`TopString: def
-str: abc
-int: 123
-`))
-
- })
-
- It("handles inline structs with conflicts", func() {
- type NestedConfig struct {
- AString string `yaml:"str"`
- Integer int `yaml:"int"`
- }
- type config struct {
- AString string `yaml:"str"`
- NestedConfig
- }
-
- cfg := config{
- AString: "def",
- NestedConfig: NestedConfig{
- AString: "abc",
- Integer: 123,
- },
- }
-
- err := enc.Encode(cfg)
- Expect(err).NotTo(HaveOccurred())
-
- Expect(buf.String()).To(Equal(`str: def
-int: 123
-`))
-
- })
-
- })
-
- })
-
- Context("Sequence", func() {
- It("handles slices", func() {
- val := []string{"a", "b", "c"}
- err := enc.Encode(val)
- Expect(err).NotTo(HaveOccurred())
-
- Expect(buf.String()).To(Equal(`- a
-- b
-- c
-`))
-
- })
- })
-
- Context("Maps", func() {
- It("Encodes simple maps", func() {
- err := enc.Encode(&map[string]string{
- "name": "Mark McGwire",
- "hr": "65",
- "avg": "0.278",
- })
- Expect(err).NotTo(HaveOccurred())
-
- Expect(buf.String()).To(Equal(`avg: "0.278"
-hr: "65"
-name: Mark McGwire
-`))
- })
-
- It("sorts by key when strings otherwise by kind", func() {
- err := enc.Encode(&map[interface{}]string{
- 1.2: "float",
- 8: "integer",
- "name": "Mark McGwire",
- "hr": "65",
- "avg": "0.278",
- })
- Expect(err).NotTo(HaveOccurred())
-
- Expect(buf.String()).To(Equal(`8: integer
-1.2: float
-avg: "0.278"
-hr: "65"
-name: Mark McGwire
-`))
- })
-
- It("encodes mix types", func() {
- err := enc.Encode(&map[string]interface{}{
- "name": "Mark McGwire",
- "hr": 65,
- "avg": 0.278,
- })
- Expect(err).NotTo(HaveOccurred())
-
- Expect(buf.String()).To(Equal(`avg: 0.278
-hr: 65
-name: Mark McGwire
-`))
- })
- })
-
- Context("Sequence of Maps", func() {
- It("encodes", func() {
- err := enc.Encode([]map[string]interface{}{
- {"name": "Mark McGwire",
- "hr": 65,
- "avg": 0.278,
- },
- {"name": "Sammy Sosa",
- "hr": 63,
- "avg": 0.288,
- },
- })
- Expect(err).NotTo(HaveOccurred())
-
- Expect(buf.String()).To(Equal(`- avg: 0.278
- hr: 65
- name: Mark McGwire
-- avg: 0.288
- hr: 63
- name: Sammy Sosa
-`))
-
- })
- })
-
- Context("Maps of Sequence", func() {
- It("encodes", func() {
- err := enc.Encode(map[string][]interface{}{
- "name": []interface{}{"Mark McGwire", "Sammy Sosa"},
- "hr": []interface{}{65, 63},
- "avg": []interface{}{0.278, 0.288},
- })
- Expect(err).NotTo(HaveOccurred())
-
- Expect(buf.String()).To(Equal(`avg:
-- 0.278
-- 0.288
-hr:
-- 65
-- 63
-name:
-- Mark McGwire
-- Sammy Sosa
-`))
-
- })
- })
-
- Context("Flow", func() {
- It("flows structs", func() {
- type i struct {
- A string
- }
- type o struct {
- I i `yaml:"i,flow"`
- }
-
- err := enc.Encode(o{
- I: i{A: "abc"},
- })
- Expect(err).NotTo(HaveOccurred())
- Expect(buf.String()).To(Equal(`i: {A: abc}
-`))
-
- })
-
- It("flows sequences", func() {
- type i struct {
- A string
- }
- type o struct {
- I []i `yaml:"i,flow"`
- }
-
- err := enc.Encode(o{
- I: []i{{A: "abc"}},
- })
- Expect(err).NotTo(HaveOccurred())
- Expect(buf.String()).To(Equal(`i: [{A: abc}]
-`))
-
- })
- })
-
- Context("Omit empty", func() {
- It("omits nil ptrs", func() {
- type i struct {
- A *string `yaml:"a,omitempty"`
- }
- type o struct {
- I []i `yaml:"i,flow"`
- }
-
- err := enc.Encode(o{
- I: []i{{A: nil}},
- })
- Expect(err).NotTo(HaveOccurred())
- Expect(buf.String()).To(Equal(`i: [{}]
-`))
-
- })
-
- })
-
- Context("Skip field", func() {
- It("does not include the field", func() {
- type a struct {
- B string `yaml:"-"`
- C string
- }
-
- err := enc.Encode(a{B: "b", C: "c"})
- Expect(err).NotTo(HaveOccurred())
- Expect(buf.String()).To(Equal(`C: c
-`))
-
- })
- })
-
- Context("Marshaler support", func() {
- Context("Receiver is a value", func() {
- It("uses the Marshaler interface when a value", func() {
- err := enc.Encode(hasMarshaler{Value: 123})
- Expect(err).NotTo(HaveOccurred())
- Expect(buf.String()).To(Equal("123\n"))
- })
-
- It("uses the Marshaler interface when a pointer", func() {
- err := enc.Encode(&hasMarshaler{Value: "abc"})
- Expect(err).NotTo(HaveOccurred())
- Expect(buf.String()).To(Equal(`abc
-`))
- })
-
- Context("when it fails", func() {
- It("returns an error", func() {
- err := enc.Encode(&hasMarshaler{Value: "abc", Error: errors.New("fail")})
- Expect(err).To(MatchError("fail"))
- })
- })
- })
-
- Context("Receiver is a pointer", func() {
- It("uses the Marshaler interface when a pointer", func() {
- err := enc.Encode(&hasPtrMarshaler{Value: map[string]string{"a": "b"}})
- Expect(err).NotTo(HaveOccurred())
- Expect(buf.String()).To(Equal(`a: b
-`))
-
- })
-
- It("skips the Marshaler when its a value", func() {
- err := enc.Encode(hasPtrMarshaler{Value: map[string]string{"a": "b"}})
- Expect(err).NotTo(HaveOccurred())
- Expect(buf.String()).To(Equal(`Tag: ""
-Value:
- a: b
-Error: null
-`))
-
- })
-
- Context("the receiver is nil", func() {
- var ptr *hasPtrMarshaler
-
- Context("when it fails", func() {
- It("returns an error", func() {
- err := enc.Encode(&hasPtrMarshaler{Value: "abc", Error: errors.New("fail")})
- Expect(err).To(MatchError("fail"))
- })
- })
-
- It("returns a null", func() {
- err := enc.Encode(ptr)
- Expect(err).NotTo(HaveOccurred())
- Expect(buf.String()).To(Equal(`null
-`))
-
- })
-
- It("returns a null value for ptr types", func() {
- err := enc.Encode(map[string]*hasPtrMarshaler{"a": ptr})
- Expect(err).NotTo(HaveOccurred())
- Expect(buf.String()).To(Equal(`a: null
-`))
-
- })
-
- It("panics when used as a nil interface", func() {
- Expect(func() { enc.Encode(map[string]Marshaler{"a": ptr}) }).To(Panic())
- })
- })
-
- Context("the receiver has a nil value", func() {
- ptr := &hasPtrMarshaler{Value: nil}
-
- It("returns null", func() {
- err := enc.Encode(ptr)
- Expect(err).NotTo(HaveOccurred())
- Expect(buf.String()).To(Equal(`null
-`))
-
- })
-
- Context("in a map", func() {
- It("returns a null value for ptr types", func() {
- err := enc.Encode(map[string]*hasPtrMarshaler{"a": ptr})
- Expect(err).NotTo(HaveOccurred())
- Expect(buf.String()).To(Equal(`a: null
-`))
-
- })
-
- It("returns a null value for interface types", func() {
- err := enc.Encode(map[string]Marshaler{"a": ptr})
- Expect(err).NotTo(HaveOccurred())
- Expect(buf.String()).To(Equal(`a: null
-`))
-
- })
- })
-
- Context("in a slice", func() {
- It("returns a null value for ptr types", func() {
- err := enc.Encode([]*hasPtrMarshaler{ptr})
- Expect(err).NotTo(HaveOccurred())
- Expect(buf.String()).To(Equal(`- null
-`))
-
- })
-
- It("returns a null value for interface types", func() {
- err := enc.Encode([]Marshaler{ptr})
- Expect(err).NotTo(HaveOccurred())
- Expect(buf.String()).To(Equal(`- null
-`))
-
- })
- })
- })
- })
- })
-
- Context("Number type", func() {
- It("encodes as a number", func() {
- n := Number("12345")
- err := enc.Encode(n)
- Expect(err).NotTo(HaveOccurred())
- Expect(buf.String()).To(Equal("12345\n"))
- })
- })
-})
-
-type hasMarshaler struct {
- Value interface{}
- Error error
-}
-
-func (m hasMarshaler) MarshalYAML() (string, interface{}, error) {
- return "", m.Value, m.Error
-}
-
-func (m hasMarshaler) UnmarshalYAML(tag string, value interface{}) error {
- m.Value = value
- return nil
-}
-
-type hasPtrMarshaler struct {
- Tag string
- Value interface{}
- Error error
-}
-
-func (m *hasPtrMarshaler) MarshalYAML() (string, interface{}, error) {
- return "", m.Value, m.Error
-}
-
-func (m *hasPtrMarshaler) UnmarshalYAML(tag string, value interface{}) error {
- m.Tag = tag
- m.Value = value
- return nil
-}
diff --git a/vendor/github.com/cloudfoundry-incubator/candiedyaml/parser_test.go b/vendor/github.com/cloudfoundry-incubator/candiedyaml/parser_test.go
deleted file mode 100644
index 534ca5ec..00000000
--- a/vendor/github.com/cloudfoundry-incubator/candiedyaml/parser_test.go
+++ /dev/null
@@ -1,81 +0,0 @@
-/*
-Licensed under the Apache License, Version 2.0 (the "License");
-you may not use this file except in compliance with the License.
-You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS,
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-See the License for the specific language governing permissions and
-limitations under the License.
-*/
-
-package candiedyaml
-
-import (
- "io/ioutil"
- "os"
- "path/filepath"
-
- . "github.com/onsi/ginkgo"
- . "github.com/onsi/gomega"
-)
-
-var parses = func(filename string) {
- It("parses "+filename, func() {
- file, err := os.Open(filename)
- Expect(err).To(BeNil())
-
- parser := yaml_parser_t{}
- yaml_parser_initialize(&parser)
- yaml_parser_set_input_reader(&parser, file)
-
- failed := false
- event := yaml_event_t{}
-
- for {
- if !yaml_parser_parse(&parser, &event) {
- failed = true
- println("---", parser.error, parser.problem, parser.context, "line", parser.problem_mark.line, "col", parser.problem_mark.column)
- break
- }
-
- if event.event_type == yaml_STREAM_END_EVENT {
- break
- }
- }
-
- file.Close()
-
- // msg := "SUCCESS"
- // if failed {
- // msg = "FAILED"
- // if parser.error != yaml_NO_ERROR {
- // m := parser.problem_mark
- // fmt.Printf("ERROR: (%s) %s @ line: %d col: %d\n",
- // parser.context, parser.problem, m.line, m.column)
- // }
- // }
- Expect(failed).To(BeFalse())
- })
-}
-
-var parseYamls = func(dirname string) {
- fileInfos, err := ioutil.ReadDir(dirname)
- if err != nil {
- panic(err.Error())
- }
-
- for _, fileInfo := range fileInfos {
- if !fileInfo.IsDir() {
- parses(filepath.Join(dirname, fileInfo.Name()))
- }
- }
-}
-
-var _ = Describe("Parser", func() {
- parseYamls("fixtures/specification")
- parseYamls("fixtures/specification/types")
-})
diff --git a/vendor/github.com/cloudfoundry-incubator/candiedyaml/reader_test.go b/vendor/github.com/cloudfoundry-incubator/candiedyaml/reader_test.go
deleted file mode 100644
index 3771ee76..00000000
--- a/vendor/github.com/cloudfoundry-incubator/candiedyaml/reader_test.go
+++ /dev/null
@@ -1,291 +0,0 @@
-/*
-Licensed under the Apache License, Version 2.0 (the "License");
-you may not use this file except in compliance with the License.
-You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS,
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-See the License for the specific language governing permissions and
-limitations under the License.
-*/
-
-package candiedyaml
-
-import (
- // "fmt"
- . "github.com/onsi/ginkgo"
- . "github.com/onsi/gomega"
-)
-
-/*
- * Test cases are stolen from
- * http://www.cl.cam.ac.uk/~mgk25/ucs/examples/UTF-8-test.txt
- */
-
-type test_case struct {
- title string
- test string
- result bool
-}
-
-var _ = Describe("Reader", func() {
- LONG := 100000
-
- Context("UTF8 Sequences", func() {
- utf8_sequences := []test_case{
- /* {"title", "test 1|test 2|...|test N!", (0 or 1)}, */
-
- {"a simple test", "'test' is '\xd0\xbf\xd1\x80\xd0\xbe\xd0\xb2\xd0\xb5\xd1\x80\xd0\xba\xd0\xb0' in Russian!", true},
-
- {"an empty line", "!", true},
- {"u-0 is a control character", "\x00!", false},
- {"u-80 is a control character", "\xc2\x80!", false},
- {"u-800 is valid", "\xe0\xa0\x80!", true},
- {"u-10000 is valid", "\xf0\x90\x80\x80!", true},
- {"5 bytes sequences are not allowed", "\xf8\x88\x80\x80\x80!", false},
- {"6 bytes sequences are not allowed", "\xfc\x84\x80\x80\x80\x80!", false},
-
- {"u-7f is a control character", "\x7f!", false},
- {"u-7FF is valid", "\xdf\xbf!", true},
- {"u-FFFF is a control character", "\xef\xbf\xbf!", false},
- {"u-1FFFFF is too large", "\xf7\xbf\xbf\xbf!", false},
- {"u-3FFFFFF is 5 bytes", "\xfb\xbf\xbf\xbf\xbf!", false},
- {"u-7FFFFFFF is 6 bytes", "\xfd\xbf\xbf\xbf\xbf\xbf!", false},
-
- {"u-D7FF", "\xed\x9f\xbf!", true},
- {"u-E000", "\xee\x80\x80!", true},
- {"u-FFFD", "\xef\xbf\xbd!", true},
- {"u-10FFFF", "\xf4\x8f\xbf\xbf!", true},
- {"u-110000", "\xf4\x90\x80\x80!", false},
-
- {"first continuation byte", "\x80!", false},
- {"last continuation byte", "\xbf!", false},
-
- {"2 continuation bytes", "\x80\xbf!", false},
- {"3 continuation bytes", "\x80\xbf\x80!", false},
- {"4 continuation bytes", "\x80\xbf\x80\xbf!", false},
- {"5 continuation bytes", "\x80\xbf\x80\xbf\x80!", false},
- {"6 continuation bytes", "\x80\xbf\x80\xbf\x80\xbf!", false},
- {"7 continuation bytes", "\x80\xbf\x80\xbf\x80\xbf\x80!", false},
-
- {"sequence of all 64 possible continuation bytes",
- "\x80|\x81|\x82|\x83|\x84|\x85|\x86|\x87|\x88|\x89|\x8a|\x8b|\x8c|\x8d|\x8e|\x8f|" +
- "\x90|\x91|\x92|\x93|\x94|\x95|\x96|\x97|\x98|\x99|\x9a|\x9b|\x9c|\x9d|\x9e|\x9f|" +
- "\xa0|\xa1|\xa2|\xa3|\xa4|\xa5|\xa6|\xa7|\xa8|\xa9|\xaa|\xab|\xac|\xad|\xae|\xaf|" +
- "\xb0|\xb1|\xb2|\xb3|\xb4|\xb5|\xb6|\xb7|\xb8|\xb9|\xba|\xbb|\xbc|\xbd|\xbe|\xbf!", false},
- {"32 first bytes of 2-byte sequences {0xc0-0xdf}",
- "\xc0 |\xc1 |\xc2 |\xc3 |\xc4 |\xc5 |\xc6 |\xc7 |\xc8 |\xc9 |\xca |\xcb |\xcc |\xcd |\xce |\xcf |" +
- "\xd0 |\xd1 |\xd2 |\xd3 |\xd4 |\xd5 |\xd6 |\xd7 |\xd8 |\xd9 |\xda |\xdb |\xdc |\xdd |\xde |\xdf !", false},
- {"16 first bytes of 3-byte sequences {0xe0-0xef}",
- "\xe0 |\xe1 |\xe2 |\xe3 |\xe4 |\xe5 |\xe6 |\xe7 |\xe8 |\xe9 |\xea |\xeb |\xec |\xed |\xee |\xef !", false},
- {"8 first bytes of 4-byte sequences {0xf0-0xf7}", "\xf0 |\xf1 |\xf2 |\xf3 |\xf4 |\xf5 |\xf6 |\xf7 !", false},
- {"4 first bytes of 5-byte sequences {0xf8-0xfb}", "\xf8 |\xf9 |\xfa |\xfb !", false},
- {"2 first bytes of 6-byte sequences {0xfc-0xfd}", "\xfc |\xfd !", false},
-
- {"sequences with last byte missing {u-0}",
- "\xc0|\xe0\x80|\xf0\x80\x80|\xf8\x80\x80\x80|\xfc\x80\x80\x80\x80!", false},
- {"sequences with last byte missing {u-...FF}",
- "\xdf|\xef\xbf|\xf7\xbf\xbf|\xfb\xbf\xbf\xbf|\xfd\xbf\xbf\xbf\xbf!", false},
-
- {"impossible bytes", "\xfe|\xff|\xfe\xfe\xff\xff!", false},
-
- {"overlong sequences {u-2f}",
- "\xc0\xaf|\xe0\x80\xaf|\xf0\x80\x80\xaf|\xf8\x80\x80\x80\xaf|\xfc\x80\x80\x80\x80\xaf!", false},
-
- {"maximum overlong sequences",
- "\xc1\xbf|\xe0\x9f\xbf|\xf0\x8f\xbf\xbf|\xf8\x87\xbf\xbf\xbf|\xfc\x83\xbf\xbf\xbf\xbf!", false},
-
- {"overlong representation of the NUL character",
- "\xc0\x80|\xe0\x80\x80|\xf0\x80\x80\x80|\xf8\x80\x80\x80\x80|\xfc\x80\x80\x80\x80\x80!", false},
-
- {"single UTF-16 surrogates",
- "\xed\xa0\x80|\xed\xad\xbf|\xed\xae\x80|\xed\xaf\xbf|\xed\xb0\x80|\xed\xbe\x80|\xed\xbf\xbf!", false},
-
- {"paired UTF-16 surrogates",
- "\xed\xa0\x80\xed\xb0\x80|\xed\xa0\x80\xed\xbf\xbf|\xed\xad\xbf\xed\xb0\x80|" +
- "\xed\xad\xbf\xed\xbf\xbf|\xed\xae\x80\xed\xb0\x80|\xed\xae\x80\xed\xbf\xbf|" +
- "\xed\xaf\xbf\xed\xb0\x80|\xed\xaf\xbf\xed\xbf\xbf!", false},
-
- {"other illegal code positions", "\xef\xbf\xbe|\xef\xbf\xbf!", false},
- }
-
- check_sequence := func(tc test_case) {
- It(tc.title, func() {
- start := 0
- end := start
- bytes := []byte(tc.test)
-
- for {
- for bytes[end] != '|' && bytes[end] != '!' {
- end++
- }
-
- parser := yaml_parser_t{}
- yaml_parser_initialize(&parser)
- yaml_parser_set_input_string(&parser, bytes)
- result := yaml_parser_update_buffer(&parser, end-start)
- Expect(result).To(Equal(tc.result))
- // outcome := '+'
- // if result != tc.result {
- // outcome = '-'
- // }
- // fmt.Printf("\t\t %c %s", outcome, tc.title)
- // if parser.error == yaml_NO_ERROR {
- // fmt.Printf("(no error)\n")
- // } else if parser.error == yaml_READER_ERROR {
- // if parser.problem_value != -1 {
- // fmt.Printf("(reader error: %s: #%X at %d)\n",
- // parser.problem, parser.problem_value, parser.problem_offset)
- // } else {
- // fmt.Printf("(reader error: %s: at %d)\n",
- // parser.problem, parser.problem_offset)
- // }
- // }
-
- if bytes[end] == '!' {
- break
- }
-
- end++
- start = end
- yaml_parser_delete(&parser)
- }
- })
- }
-
- for _, test := range utf8_sequences {
- check_sequence(test)
- }
- })
-
- Context("BOMs", func() {
- boms := []test_case{
- /* {"title", "test!", lenth}, */
- {"no bom (utf-8)", "Hi is \xd0\x9f\xd1\x80\xd0\xb8\xd0\xb2\xd0\xb5\xd1\x82!", true},
- {"bom (utf-8)", "\xef\xbb\xbfHi is \xd0\x9f\xd1\x80\xd0\xb8\xd0\xb2\xd0\xb5\xd1\x82!", true},
- {"bom (utf-16-le)", "\xff\xfeH\x00i\x00 \x00i\x00s\x00 \x00\x1f\x04@\x04" + "8\x04" + "2\x04" + "5\x04" + "B\x04!", true},
- {"bom (utf-16-be)", "\xfe\xff\x00H\x00i\x00 \x00i\x00s\x00 \x04\x1f\x04@\x04" + "8\x04" + "2\x04" + "5\x04" + "B!", true},
- }
-
- check_bom := func(tc test_case) {
- It(tc.title, func() {
- start := 0
- end := start
- bytes := []byte(tc.test)
-
- for bytes[end] != '!' {
- end++
- }
-
- parser := yaml_parser_t{}
- yaml_parser_initialize(&parser)
- yaml_parser_set_input_string(&parser, bytes[:end-start])
- result := yaml_parser_update_buffer(&parser, end-start)
- Expect(result).To(Equal(tc.result))
- yaml_parser_delete(&parser)
- })
- }
-
- for _, test := range boms {
- check_bom(test)
- }
-
- })
-
- Context("Long UTF8", func() {
- It("parses properly", func() {
- buffer := make([]byte, 0, 3+LONG*2)
- buffer = append(buffer, '\xef', '\xbb', '\xbf')
- for j := 0; j < LONG; j++ {
- if j%2 == 1 {
- buffer = append(buffer, '\xd0', '\x90')
- } else {
- buffer = append(buffer, '\xd0', '\xaf')
- }
- }
- parser := yaml_parser_t{}
- yaml_parser_initialize(&parser)
- yaml_parser_set_input_string(&parser, buffer)
-
- for k := 0; k < LONG; k++ {
- if parser.unread == 0 {
- updated := yaml_parser_update_buffer(&parser, 1)
- Expect(updated).To(BeTrue())
- // printf("\treader error: %s at %d\n", parser.problem, parser.problem_offset);
- }
- Expect(parser.unread).NotTo(Equal(0))
- // printf("\tnot enough characters at %d\n", k);
- var ch0, ch1 byte
- if k%2 == 1 {
- ch0 = '\xd0'
- ch1 = '\x90'
- } else {
- ch0 = '\xd0'
- ch1 = '\xaf'
- }
- Expect(parser.buffer[parser.buffer_pos]).To(Equal(ch0))
- Expect(parser.buffer[parser.buffer_pos+1]).To(Equal(ch1))
- // printf("\tincorrect UTF-8 sequence: %X %X instead of %X %X\n",
- // (int)parser.buffer.pointer[0], (int)parser.buffer.pointer[1],
- // (int)ch0, (int)ch1);
-
- parser.buffer_pos += 2
- parser.unread -= 1
- }
- updated := yaml_parser_update_buffer(&parser, 1)
- Expect(updated).To(BeTrue())
- // printf("\treader error: %s at %d\n", parser.problem, parser.problem_offset);
- yaml_parser_delete(&parser)
- })
- })
-
- Context("Long UTF16", func() {
- It("parses properly", func() {
- buffer := make([]byte, 0, 2+LONG*2)
- buffer = append(buffer, '\xff', '\xfe')
- for j := 0; j < LONG; j++ {
- if j%2 == 1 {
- buffer = append(buffer, '\x10', '\x04')
- } else {
- buffer = append(buffer, '/', '\x04')
- }
- }
- parser := yaml_parser_t{}
- yaml_parser_initialize(&parser)
- yaml_parser_set_input_string(&parser, buffer)
-
- for k := 0; k < LONG; k++ {
- if parser.unread == 0 {
- updated := yaml_parser_update_buffer(&parser, 1)
- Expect(updated).To(BeTrue())
- // printf("\treader error: %s at %d\n", parser.problem, parser.problem_offset);
- }
- Expect(parser.unread).NotTo(Equal(0))
- // printf("\tnot enough characters at %d\n", k);
- var ch0, ch1 byte
- if k%2 == 1 {
- ch0 = '\xd0'
- ch1 = '\x90'
- } else {
- ch0 = '\xd0'
- ch1 = '\xaf'
- }
- Expect(parser.buffer[parser.buffer_pos]).To(Equal(ch0))
- Expect(parser.buffer[parser.buffer_pos+1]).To(Equal(ch1))
- // printf("\tincorrect UTF-8 sequence: %X %X instead of %X %X\n",
- // (int)parser.buffer.pointer[0], (int)parser.buffer.pointer[1],
- // (int)ch0, (int)ch1);
-
- parser.buffer_pos += 2
- parser.unread -= 1
- }
- updated := yaml_parser_update_buffer(&parser, 1)
- Expect(updated).To(BeTrue())
- // printf("\treader error: %s at %d\n", parser.problem, parser.problem_offset);
- yaml_parser_delete(&parser)
- })
- })
-})
diff --git a/vendor/github.com/cloudfoundry-incubator/candiedyaml/resolver_test.go b/vendor/github.com/cloudfoundry-incubator/candiedyaml/resolver_test.go
deleted file mode 100644
index 88e61fd0..00000000
--- a/vendor/github.com/cloudfoundry-incubator/candiedyaml/resolver_test.go
+++ /dev/null
@@ -1,665 +0,0 @@
-/*
-Licensed under the Apache License, Version 2.0 (the "License");
-you may not use this file except in compliance with the License.
-You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS,
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-See the License for the specific language governing permissions and
-limitations under the License.
-*/
-
-package candiedyaml
-
-import (
- "math"
- "reflect"
- "time"
-
- . "github.com/onsi/ginkgo"
- . "github.com/onsi/gomega"
-)
-
-var _ = Describe("Resolver", func() {
- var event yaml_event_t
-
- var nulls = []string{"~", "null", "Null", "NULL"}
-
- BeforeEach(func() {
- event = yaml_event_t{}
- })
-
- Context("Resolve", func() {
- Context("Implicit events", func() {
- checkNulls := func(f func()) {
- for _, null := range nulls {
- event = yaml_event_t{implicit: true}
- event.value = []byte(null)
- f()
- }
- }
-
- BeforeEach(func() {
- event.implicit = true
- })
-
- Context("String", func() {
- It("resolves a string", func() {
- aString := ""
- v := reflect.ValueOf(&aString)
- event.value = []byte("abc")
-
- tag, err := resolve(event, v.Elem(), false)
- Expect(err).NotTo(HaveOccurred())
- Expect(tag).To(Equal(yaml_STR_TAG))
- Expect(aString).To(Equal("abc"))
- })
-
- It("resolves the empty string", func() {
- aString := "abc"
- v := reflect.ValueOf(&aString)
- event.value = []byte("")
-
- tag, err := resolve(event, v.Elem(), false)
- Expect(err).NotTo(HaveOccurred())
- Expect(tag).To(Equal(yaml_STR_TAG))
- Expect(aString).To(Equal(""))
-
- })
-
- It("resolves null", func() {
- checkNulls(func() {
- aString := "abc"
- v := reflect.ValueOf(&aString)
-
- tag, err := resolve(event, v.Elem(), false)
- Expect(err).NotTo(HaveOccurred())
- Expect(tag).To(Equal(yaml_NULL_TAG))
- Expect(aString).To(Equal(""))
- })
- })
-
- It("resolves null pointers", func() {
- checkNulls(func() {
- aString := "abc"
- pString := &aString
- v := reflect.ValueOf(&pString)
-
- tag, err := resolve(event, v.Elem(), false)
- Expect(err).NotTo(HaveOccurred())
- Expect(tag).To(Equal(yaml_NULL_TAG))
- Expect(pString).To(BeNil())
- })
- })
-
- })
-
- Context("Booleans", func() {
- match_bool := func(val string, expected bool) {
- b := !expected
-
- v := reflect.ValueOf(&b)
- event.value = []byte(val)
-
- tag, err := resolve(event, v.Elem(), false)
- Expect(err).NotTo(HaveOccurred())
- Expect(tag).To(Equal(yaml_BOOL_TAG))
- Expect(b).To(Equal(expected))
- }
-
- It("resolves on", func() {
- match_bool("on", true)
- match_bool("ON", true)
- })
-
- It("resolves off", func() {
- match_bool("off", false)
- match_bool("OFF", false)
- })
-
- It("resolves true", func() {
- match_bool("true", true)
- match_bool("TRUE", true)
- })
-
- It("resolves false", func() {
- match_bool("false", false)
- match_bool("FALSE", false)
- })
-
- It("resolves yes", func() {
- match_bool("yes", true)
- match_bool("YES", true)
- })
-
- It("resolves no", func() {
- match_bool("no", false)
- match_bool("NO", false)
- })
-
- It("reports an error otherwise", func() {
- b := true
- v := reflect.ValueOf(&b)
- event.value = []byte("fail")
-
- _, err := resolve(event, v.Elem(), false)
- Expect(err).To(HaveOccurred())
- Expect(err.Error()).To(Equal("Invalid boolean: 'fail' at line 0, column 0"))
- })
-
- It("resolves null", func() {
- checkNulls(func() {
- b := true
- v := reflect.ValueOf(&b)
-
- tag, err := resolve(event, v.Elem(), false)
- Expect(err).NotTo(HaveOccurred())
- Expect(tag).To(Equal(yaml_NULL_TAG))
- Expect(b).To(BeFalse())
- })
- })
-
- It("resolves null pointers", func() {
- checkNulls(func() {
- b := true
- pb := &b
- v := reflect.ValueOf(&pb)
-
- tag, err := resolve(event, v.Elem(), false)
- Expect(err).NotTo(HaveOccurred())
- Expect(tag).To(Equal(yaml_NULL_TAG))
- Expect(pb).To(BeNil())
- })
- })
- })
-
- Context("Ints", func() {
- It("simple ints", func() {
- i := 0
- v := reflect.ValueOf(&i)
- event.value = []byte("1234")
-
- tag, err := resolve(event, v.Elem(), false)
- Expect(err).NotTo(HaveOccurred())
- Expect(tag).To(Equal(yaml_INT_TAG))
- Expect(i).To(Equal(1234))
- })
-
- It("positive ints", func() {
- i := int16(0)
- v := reflect.ValueOf(&i)
- event.value = []byte("+678")
-
- tag, err := resolve(event, v.Elem(), false)
- Expect(err).NotTo(HaveOccurred())
- Expect(tag).To(Equal(yaml_INT_TAG))
- Expect(i).To(Equal(int16(678)))
- })
-
- It("negative ints", func() {
- i := int32(0)
- v := reflect.ValueOf(&i)
- event.value = []byte("-2345")
-
- tag, err := resolve(event, v.Elem(), false)
- Expect(err).NotTo(HaveOccurred())
- Expect(tag).To(Equal(yaml_INT_TAG))
- Expect(i).To(Equal(int32(-2345)))
- })
-
- It("base 8", func() {
- i := 0
- v := reflect.ValueOf(&i)
- event.value = []byte("0o12")
-
- tag, err := resolve(event, v.Elem(), false)
- Expect(err).NotTo(HaveOccurred())
- Expect(tag).To(Equal(yaml_INT_TAG))
- Expect(i).To(Equal(10))
- })
-
- It("base 16", func() {
- i := 0
- v := reflect.ValueOf(&i)
- event.value = []byte("0xff")
-
- tag, err := resolve(event, v.Elem(), false)
- Expect(err).NotTo(HaveOccurred())
- Expect(tag).To(Equal(yaml_INT_TAG))
- Expect(i).To(Equal(255))
- })
-
- It("fails on overflow", func() {
- i := int8(0)
- v := reflect.ValueOf(&i)
- event.value = []byte("2345")
-
- _, err := resolve(event, v.Elem(), false)
- Expect(err).To(HaveOccurred())
- Expect(err.Error()).To(Equal("Invalid integer: '2345' at line 0, column 0"))
- })
-
- It("fails on invalid int", func() {
- i := 0
- v := reflect.ValueOf(&i)
- event.value = []byte("234f")
-
- _, err := resolve(event, v.Elem(), false)
- Expect(err).To(HaveOccurred())
- Expect(err.Error()).To(Equal("Invalid integer: '234f' at line 0, column 0"))
- })
-
- It("resolves null", func() {
- checkNulls(func() {
- i := 1
- v := reflect.ValueOf(&i)
-
- tag, err := resolve(event, v.Elem(), false)
- Expect(err).NotTo(HaveOccurred())
- Expect(tag).To(Equal(yaml_NULL_TAG))
- Expect(i).To(Equal(0))
- })
- })
-
- It("resolves null pointers", func() {
- checkNulls(func() {
- i := 1
- pi := &i
- v := reflect.ValueOf(&pi)
-
- tag, err := resolve(event, v.Elem(), false)
- Expect(err).NotTo(HaveOccurred())
- Expect(tag).To(Equal(yaml_NULL_TAG))
- Expect(pi).To(BeNil())
- })
- })
-
- It("returns a Number", func() {
- var i Number
- v := reflect.ValueOf(&i)
-
- tag, err := resolve_int("12345", v.Elem(), true, event)
- Expect(err).NotTo(HaveOccurred())
- Expect(tag).To(Equal(yaml_INT_TAG))
- Expect(i).To(Equal(Number("12345")))
- Expect(i.Int64()).To(Equal(int64(12345)))
-
- event.value = []byte("1234")
- tag, err = resolve(event, v.Elem(), true)
- Expect(err).NotTo(HaveOccurred())
- Expect(tag).To(Equal(yaml_INT_TAG))
- Expect(i).To(Equal(Number("1234")))
- })
- })
-
- Context("UInts", func() {
- It("resolves simple uints", func() {
- i := uint(0)
- v := reflect.ValueOf(&i)
- event.value = []byte("1234")
-
- tag, err := resolve(event, v.Elem(), false)
- Expect(err).NotTo(HaveOccurred())
- Expect(tag).To(Equal(yaml_INT_TAG))
- Expect(i).To(Equal(uint(1234)))
- })
-
- It("resolves positive uints", func() {
- i := uint16(0)
- v := reflect.ValueOf(&i)
- event.value = []byte("+678")
-
- tag, err := resolve(event, v.Elem(), false)
- Expect(err).NotTo(HaveOccurred())
- Expect(tag).To(Equal(yaml_INT_TAG))
- Expect(i).To(Equal(uint16(678)))
- })
-
- It("base 8", func() {
- i := uint(0)
- v := reflect.ValueOf(&i)
- event.value = []byte("0o12")
-
- tag, err := resolve(event, v.Elem(), false)
- Expect(err).NotTo(HaveOccurred())
- Expect(tag).To(Equal(yaml_INT_TAG))
- Expect(i).To(Equal(uint(10)))
- })
-
- It("base 16", func() {
- i := uint(0)
- v := reflect.ValueOf(&i)
- event.value = []byte("0xff")
-
- tag, err := resolve(event, v.Elem(), false)
- Expect(err).NotTo(HaveOccurred())
- Expect(tag).To(Equal(yaml_INT_TAG))
- Expect(i).To(Equal(uint(255)))
- })
-
- It("fails with negative ints", func() {
- i := uint(0)
- v := reflect.ValueOf(&i)
- event.value = []byte("-2345")
-
- _, err := resolve(event, v.Elem(), false)
- Expect(err).To(HaveOccurred())
- Expect(err.Error()).To(Equal("Unsigned int with negative value: '-2345' at line 0, column 0"))
- })
-
- It("fails on overflow", func() {
- i := uint8(0)
- v := reflect.ValueOf(&i)
- event.value = []byte("2345")
-
- _, err := resolve(event, v.Elem(), false)
- Expect(err).To(HaveOccurred())
- Expect(err.Error()).To(Equal("Invalid unsigned integer: '2345' at line 0, column 0"))
- })
-
- It("resolves null", func() {
- checkNulls(func() {
- i := uint(1)
- v := reflect.ValueOf(&i)
-
- tag, err := resolve(event, v.Elem(), false)
- Expect(err).NotTo(HaveOccurred())
- Expect(tag).To(Equal(yaml_NULL_TAG))
- Expect(i).To(Equal(uint(0)))
- })
- })
-
- It("resolves null pointers", func() {
- checkNulls(func() {
- i := uint(1)
- pi := &i
- v := reflect.ValueOf(&pi)
-
- tag, err := resolve(event, v.Elem(), false)
- Expect(err).NotTo(HaveOccurred())
- Expect(tag).To(Equal(yaml_NULL_TAG))
- Expect(pi).To(BeNil())
- })
- })
-
- It("returns a Number", func() {
- var i Number
- v := reflect.ValueOf(&i)
-
- tag, err := resolve_uint("12345", v.Elem(), true, event)
- Expect(err).NotTo(HaveOccurred())
- Expect(tag).To(Equal(yaml_INT_TAG))
- Expect(i).To(Equal(Number("12345")))
-
- event.value = []byte("1234")
- tag, err = resolve(event, v.Elem(), true)
- Expect(err).NotTo(HaveOccurred())
- Expect(tag).To(Equal(yaml_INT_TAG))
- Expect(i).To(Equal(Number("1234")))
- })
- })
-
- Context("Floats", func() {
- It("float32", func() {
- f := float32(0)
- v := reflect.ValueOf(&f)
- event.value = []byte("2345.01")
-
- tag, err := resolve(event, v.Elem(), false)
- Expect(err).NotTo(HaveOccurred())
- Expect(tag).To(Equal(yaml_FLOAT_TAG))
- Expect(f).To(Equal(float32(2345.01)))
- })
-
- It("float64", func() {
- f := float64(0)
- v := reflect.ValueOf(&f)
- event.value = []byte("-456456.01")
-
- tag, err := resolve(event, v.Elem(), false)
- Expect(err).NotTo(HaveOccurred())
- Expect(tag).To(Equal(yaml_FLOAT_TAG))
- Expect(f).To(Equal(float64(-456456.01)))
- })
-
- It("+inf", func() {
- f := float64(0)
- v := reflect.ValueOf(&f)
- event.value = []byte("+.inf")
-
- tag, err := resolve(event, v.Elem(), false)
- Expect(err).NotTo(HaveOccurred())
- Expect(tag).To(Equal(yaml_FLOAT_TAG))
- Expect(f).To(Equal(math.Inf(1)))
- })
-
- It("-inf", func() {
- f := float32(0)
- v := reflect.ValueOf(&f)
- event.value = []byte("-.inf")
-
- tag, err := resolve(event, v.Elem(), false)
- Expect(err).NotTo(HaveOccurred())
- Expect(tag).To(Equal(yaml_FLOAT_TAG))
- Expect(f).To(Equal(float32(math.Inf(-1))))
- })
-
- It("nan", func() {
- f := float64(0)
- v := reflect.ValueOf(&f)
- event.value = []byte(".NaN")
-
- tag, err := resolve(event, v.Elem(), false)
- Expect(err).NotTo(HaveOccurred())
- Expect(tag).To(Equal(yaml_FLOAT_TAG))
- Expect(math.IsNaN(f)).To(BeTrue())
- })
-
- It("fails on overflow", func() {
- i := float32(0)
- v := reflect.ValueOf(&i)
- event.value = []byte("123e10000")
-
- _, err := resolve(event, v.Elem(), false)
- Expect(err).To(HaveOccurred())
- Expect(err.Error()).To(Equal("Invalid float: '123e10000' at line 0, column 0"))
- })
-
- It("fails on invalid float", func() {
- i := float32(0)
- v := reflect.ValueOf(&i)
- event.value = []byte("123e1a")
-
- _, err := resolve(event, v.Elem(), false)
- Expect(err).To(HaveOccurred())
- Expect(err.Error()).To(Equal("Invalid float: '123e1a' at line 0, column 0"))
- })
-
- It("resolves null", func() {
- checkNulls(func() {
- f := float64(1)
- v := reflect.ValueOf(&f)
-
- tag, err := resolve(event, v.Elem(), false)
- Expect(err).NotTo(HaveOccurred())
- Expect(tag).To(Equal(yaml_NULL_TAG))
- Expect(f).To(Equal(0.0))
- })
- })
-
- It("resolves null pointers", func() {
- checkNulls(func() {
- f := float64(1)
- pf := &f
- v := reflect.ValueOf(&pf)
-
- tag, err := resolve(event, v.Elem(), false)
- Expect(err).NotTo(HaveOccurred())
- Expect(tag).To(Equal(yaml_NULL_TAG))
- Expect(pf).To(BeNil())
- })
- })
-
- It("returns a Number", func() {
- var i Number
- v := reflect.ValueOf(&i)
-
- tag, err := resolve_float("12.345", v.Elem(), true, event)
- Expect(err).NotTo(HaveOccurred())
- Expect(tag).To(Equal(yaml_FLOAT_TAG))
- Expect(i).To(Equal(Number("12.345")))
- Expect(i.Float64()).To(Equal(12.345))
-
- event.value = []byte("1.234")
- tag, err = resolve(event, v.Elem(), true)
- Expect(err).NotTo(HaveOccurred())
- Expect(tag).To(Equal(yaml_FLOAT_TAG))
- Expect(i).To(Equal(Number("1.234")))
- })
- })
-
- Context("Timestamps", func() {
- parse_date := func(val string, date time.Time) {
- d := time.Now()
- v := reflect.ValueOf(&d)
- event.value = []byte(val)
-
- tag, err := resolve(event, v.Elem(), false)
- Expect(err).NotTo(HaveOccurred())
- Expect(tag).To(Equal(""))
- Expect(d).To(Equal(date))
- }
-
- It("date", func() {
- parse_date("2002-12-14", time.Date(2002, time.December, 14, 0, 0, 0, 0, time.UTC))
- })
-
- It("canonical", func() {
- parse_date("2001-12-15T02:59:43.1Z", time.Date(2001, time.December, 15, 2, 59, 43, int(1*time.Millisecond), time.UTC))
- })
-
- It("iso8601", func() {
- parse_date("2001-12-14t21:59:43.10-05:00", time.Date(2001, time.December, 14, 21, 59, 43, int(10*time.Millisecond), time.FixedZone("", -5*3600)))
- })
-
- It("space separated", func() {
- parse_date("2001-12-14 21:59:43.10 -5", time.Date(2001, time.December, 14, 21, 59, 43, int(10*time.Millisecond), time.FixedZone("", -5*3600)))
- })
-
- It("no time zone", func() {
- parse_date("2001-12-15 2:59:43.10", time.Date(2001, time.December, 15, 2, 59, 43, int(10*time.Millisecond), time.UTC))
- })
-
- It("resolves null", func() {
- checkNulls(func() {
- d := time.Now()
- v := reflect.ValueOf(&d)
-
- tag, err := resolve(event, v.Elem(), false)
- Expect(err).NotTo(HaveOccurred())
- Expect(tag).To(Equal(yaml_NULL_TAG))
- Expect(d).To(Equal(time.Time{}))
- })
- })
-
- It("resolves null pointers", func() {
- checkNulls(func() {
- d := time.Now()
- pd := &d
- v := reflect.ValueOf(&pd)
-
- tag, err := resolve(event, v.Elem(), false)
- Expect(err).NotTo(HaveOccurred())
- Expect(tag).To(Equal(yaml_NULL_TAG))
- Expect(pd).To(BeNil())
- })
- })
- })
-
- Context("Binary tag", func() {
- It("string", func() {
- checkNulls(func() {
- event.value = []byte("YWJjZGVmZw==")
- event.tag = []byte("!binary")
- aString := ""
- v := reflect.ValueOf(&aString)
-
- tag, err := resolve(event, v.Elem(), false)
- Expect(err).NotTo(HaveOccurred())
- Expect(tag).To(Equal(yaml_STR_TAG))
- Expect(aString).To(Equal("abcdefg"))
- })
- })
-
- It("[]byte", func() {
- checkNulls(func() {
- event.value = []byte("YWJjZGVmZw==")
- event.tag = []byte("!binary")
- bytes := []byte(nil)
- v := reflect.ValueOf(&bytes)
-
- tag, err := resolve(event, v.Elem(), false)
- Expect(err).NotTo(HaveOccurred())
- Expect(tag).To(Equal(yaml_STR_TAG))
- Expect(bytes).To(Equal([]byte("abcdefg")))
- })
- })
-
- It("returns a []byte when provided no hints", func() {
- checkNulls(func() {
- event.value = []byte("YWJjZGVmZw==")
- event.tag = []byte("!binary")
- var intf interface{}
- v := reflect.ValueOf(&intf)
-
- tag, err := resolve(event, v.Elem(), false)
- Expect(err).NotTo(HaveOccurred())
- Expect(tag).To(Equal(yaml_STR_TAG))
- Expect(intf).To(Equal([]byte("abcdefg")))
- })
- })
- })
-
- It("fails to resolve a pointer", func() {
- aString := ""
- pString := &aString
- v := reflect.ValueOf(&pString)
- event.value = []byte("abc")
-
- _, err := resolve(event, v.Elem(), false)
- Expect(err).To(HaveOccurred())
- Expect(err.Error()).To(Equal("Unknown resolution for 'abc' using <*string Value> at line 0, column 0"))
- })
- })
-
- Context("Not an implicit event && no tag", func() {
- It("bool returns a string", func() {
- event.value = []byte("on")
-
- tag, result := resolveInterface(event, false)
- Expect(result).To(Equal("on"))
- Expect(tag).To(Equal(""))
- })
-
- It("number returns a string", func() {
- event.value = []byte("1234")
-
- tag, result := resolveInterface(event, false)
- Expect(result).To(Equal("1234"))
- Expect(tag).To(Equal(""))
- })
-
- It("returns the empty string", func() {
- event.value = []byte("")
- // event.implicit = true
-
- tag, result := resolveInterface(event, false)
- Expect(result).To(Equal(""))
- Expect(tag).To(Equal(""))
- })
- })
- })
-})
diff --git a/vendor/github.com/cloudfoundry-incubator/candiedyaml/scanner_test.go b/vendor/github.com/cloudfoundry-incubator/candiedyaml/scanner_test.go
deleted file mode 100644
index db31e651..00000000
--- a/vendor/github.com/cloudfoundry-incubator/candiedyaml/scanner_test.go
+++ /dev/null
@@ -1,80 +0,0 @@
-/*
-Licensed under the Apache License, Version 2.0 (the "License");
-you may not use this file except in compliance with the License.
-You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS,
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-See the License for the specific language governing permissions and
-limitations under the License.
-*/
-
-package candiedyaml
-
-import (
- "io/ioutil"
- "os"
- "path/filepath"
-
- . "github.com/onsi/ginkgo"
- . "github.com/onsi/gomega"
-)
-
-var scan = func(filename string) {
- It("scan "+filename, func() {
- file, err := os.Open(filename)
- Expect(err).To(BeNil())
-
- parser := yaml_parser_t{}
- yaml_parser_initialize(&parser)
- yaml_parser_set_input_reader(&parser, file)
-
- failed := false
- token := yaml_token_t{}
-
- for {
- if !yaml_parser_scan(&parser, &token) {
- failed = true
- break
- }
-
- if token.token_type == yaml_STREAM_END_TOKEN {
- break
- }
- }
-
- file.Close()
-
- // msg := "SUCCESS"
- // if failed {
- // msg = "FAILED"
- // if parser.error != yaml_NO_ERROR {
- // m := parser.problem_mark
- // fmt.Printf("ERROR: (%s) %s @ line: %d col: %d\n",
- // parser.context, parser.problem, m.line, m.column)
- // }
- // }
- Expect(failed).To(BeFalse())
- })
-}
-
-var scanYamls = func(dirname string) {
- fileInfos, err := ioutil.ReadDir(dirname)
- if err != nil {
- panic(err.Error())
- }
-
- for _, fileInfo := range fileInfos {
- if !fileInfo.IsDir() {
- scan(filepath.Join(dirname, fileInfo.Name()))
- }
- }
-}
-
-var _ = Describe("Scanner", func() {
- scanYamls("fixtures/specification")
- scanYamls("fixtures/specification/types")
-})
diff --git a/vendor/github.com/codegangsta/cli/.travis.yml b/vendor/github.com/codegangsta/cli/.travis.yml
index baf46abc..133722f0 100644
--- a/vendor/github.com/codegangsta/cli/.travis.yml
+++ b/vendor/github.com/codegangsta/cli/.travis.yml
@@ -1,6 +1,22 @@
language: go
-go: 1.1
+sudo: false
+
+go:
+- 1.1.2
+- 1.2.2
+- 1.3.3
+- 1.4.2
+- 1.5.1
+- tip
+
+matrix:
+ allow_failures:
+ - go: tip
+
+before_script:
+- go get github.com/meatballhat/gfmxr/...
script:
- go vet ./...
- go test -v ./...
+- gfmxr -c $(grep -c 'package main' README.md) -s README.md
diff --git a/vendor/github.com/codegangsta/cli/CHANGELOG.md b/vendor/github.com/codegangsta/cli/CHANGELOG.md
new file mode 100644
index 00000000..d7ea0a69
--- /dev/null
+++ b/vendor/github.com/codegangsta/cli/CHANGELOG.md
@@ -0,0 +1,298 @@
+# Change Log
+
+**ATTN**: This project uses [semantic versioning](http://semver.org/).
+
+## [Unreleased]
+### Added
+- Pluggable flag-level help text rendering via `cli.DefaultFlagStringFunc`
+
+### Changed
+- `Float64Flag`, `IntFlag`, and `DurationFlag` default values are no longer
+quoted in help text output.
+- All flag types now include `(default: {value})` strings following usage when a
+default value can be (reasonably) detected.
+- `IntSliceFlag` and `StringSliceFlag` usage strings are now more consistent
+with non-slice flag types
+
+## [1.16.0] - 2016-05-02
+### Added
+- `Hidden` field on all flag struct types to omit from generated help text
+
+### Changed
+- `BashCompletionFlag` (`--enable-bash-completion`) is now omitted from
+generated help text via the `Hidden` field
+
+### Fixed
+- handling of error values in `HandleAction` and `HandleExitCoder`
+
+## [1.15.0] - 2016-04-30
+### Added
+- This file!
+- Support for placeholders in flag usage strings
+- `App.Metadata` map for arbitrary data/state management
+- `Set` and `GlobalSet` methods on `*cli.Context` for altering values after
+parsing.
+- Support for nested lookup of dot-delimited keys in structures loaded from
+YAML.
+
+### Changed
+- The `App.Action` and `Command.Action` now prefer a return signature of
+`func(*cli.Context) error`, as defined by `cli.ActionFunc`. If a non-nil
+`error` is returned, there may be two outcomes:
+ - If the error fulfills `cli.ExitCoder`, then `os.Exit` will be called
+ automatically
+ - Else the error is bubbled up and returned from `App.Run`
+- Specifying an `Action` with the legacy return signature of
+`func(*cli.Context)` will produce a deprecation message to stderr
+- Specifying an `Action` that is not a `func` type will produce a non-zero exit
+from `App.Run`
+- Specifying an `Action` func that has an invalid (input) signature will
+produce a non-zero exit from `App.Run`
+
+### Deprecated
+-
+`cli.App.RunAndExitOnError`, which should now be done by returning an error
+that fulfills `cli.ExitCoder` to `cli.App.Run`.
+- the legacy signature for
+`cli.App.Action` of `func(*cli.Context)`, which should now have a return
+signature of `func(*cli.Context) error`, as defined by `cli.ActionFunc`.
+
+### Fixed
+- Added missing `*cli.Context.GlobalFloat64` method
+
+## [1.14.0] - 2016-04-03 (backfilled 2016-04-25)
+### Added
+- Codebeat badge
+- Support for categorization via `CategorizedHelp` and `Categories` on app.
+
+### Changed
+- Use `filepath.Base` instead of `path.Base` in `Name` and `HelpName`.
+
+### Fixed
+- Ensure version is not shown in help text when `HideVersion` set.
+
+## [1.13.0] - 2016-03-06 (backfilled 2016-04-25)
+### Added
+- YAML file input support.
+- `NArg` method on context.
+
+## [1.12.0] - 2016-02-17 (backfilled 2016-04-25)
+### Added
+- Custom usage error handling.
+- Custom text support in `USAGE` section of help output.
+- Improved help messages for empty strings.
+- AppVeyor CI configuration.
+
+### Changed
+- Removed `panic` from default help printer func.
+- De-duping and optimizations.
+
+### Fixed
+- Correctly handle `Before`/`After` at command level when no subcommands.
+- Case of literal `-` argument causing flag reordering.
+- Environment variable hints on Windows.
+- Docs updates.
+
+## [1.11.1] - 2015-12-21 (backfilled 2016-04-25)
+### Changed
+- Use `path.Base` in `Name` and `HelpName`
+- Export `GetName` on flag types.
+
+### Fixed
+- Flag parsing when skipping is enabled.
+- Test output cleanup.
+- Move completion check to account for empty input case.
+
+## [1.11.0] - 2015-11-15 (backfilled 2016-04-25)
+### Added
+- Destination scan support for flags.
+- Testing against `tip` in Travis CI config.
+
+### Changed
+- Go version in Travis CI config.
+
+### Fixed
+- Removed redundant tests.
+- Use correct example naming in tests.
+
+## [1.10.2] - 2015-10-29 (backfilled 2016-04-25)
+### Fixed
+- Remove unused var in bash completion.
+
+## [1.10.1] - 2015-10-21 (backfilled 2016-04-25)
+### Added
+- Coverage and reference logos in README.
+
+### Fixed
+- Use specified values in help and version parsing.
+- Only display app version and help message once.
+
+## [1.10.0] - 2015-10-06 (backfilled 2016-04-25)
+### Added
+- More tests for existing functionality.
+- `ArgsUsage` at app and command level for help text flexibility.
+
+### Fixed
+- Honor `HideHelp` and `HideVersion` in `App.Run`.
+- Remove juvenile word from README.
+
+## [1.9.0] - 2015-09-08 (backfilled 2016-04-25)
+### Added
+- `FullName` on command with accompanying help output update.
+- Set default `$PROG` in bash completion.
+
+### Changed
+- Docs formatting.
+
+### Fixed
+- Removed self-referential imports in tests.
+
+## [1.8.0] - 2015-06-30 (backfilled 2016-04-25)
+### Added
+- Support for `Copyright` at app level.
+- `Parent` func at context level to walk up context lineage.
+
+### Fixed
+- Global flag processing at top level.
+
+## [1.7.1] - 2015-06-11 (backfilled 2016-04-25)
+### Added
+- Aggregate errors from `Before`/`After` funcs.
+- Doc comments on flag structs.
+- Include non-global flags when checking version and help.
+- Travis CI config updates.
+
+### Fixed
+- Ensure slice type flags have non-nil values.
+- Collect global flags from the full command hierarchy.
+- Docs prose.
+
+## [1.7.0] - 2015-05-03 (backfilled 2016-04-25)
+### Changed
+- `HelpPrinter` signature includes output writer.
+
+### Fixed
+- Specify go 1.1+ in docs.
+- Set `Writer` when running command as app.
+
+## [1.6.0] - 2015-03-23 (backfilled 2016-04-25)
+### Added
+- Multiple author support.
+- `NumFlags` at context level.
+- `Aliases` at command level.
+
+### Deprecated
+- `ShortName` at command level.
+
+### Fixed
+- Subcommand help output.
+- Backward compatible support for deprecated `Author` and `Email` fields.
+- Docs regarding `Names`/`Aliases`.
+
+## [1.5.0] - 2015-02-20 (backfilled 2016-04-25)
+### Added
+- `After` hook func support at app and command level.
+
+### Fixed
+- Use parsed context when running command as subcommand.
+- Docs prose.
+
+## [1.4.1] - 2015-01-09 (backfilled 2016-04-25)
+### Added
+- Support for hiding `-h / --help` flags, but not `help` subcommand.
+- Stop flag parsing after `--`.
+
+### Fixed
+- Help text for generic flags to specify single value.
+- Use double quotes in output for defaults.
+- Use `ParseInt` instead of `ParseUint` for int environment var values.
+- Use `0` as base when parsing int environment var values.
+
+## [1.4.0] - 2014-12-12 (backfilled 2016-04-25)
+### Added
+- Support for environment variable lookup "cascade".
+- Support for `Stdout` on app for output redirection.
+
+### Fixed
+- Print command help instead of app help in `ShowCommandHelp`.
+
+## [1.3.1] - 2014-11-13 (backfilled 2016-04-25)
+### Added
+- Docs and example code updates.
+
+### Changed
+- Default `-v / --version` flag made optional.
+
+## [1.3.0] - 2014-08-10 (backfilled 2016-04-25)
+### Added
+- `FlagNames` at context level.
+- Exposed `VersionPrinter` var for more control over version output.
+- Zsh completion hook.
+- `AUTHOR` section in default app help template.
+- Contribution guidelines.
+- `DurationFlag` type.
+
+## [1.2.0] - 2014-08-02
+### Added
+- Support for environment variable defaults on flags plus tests.
+
+## [1.1.0] - 2014-07-15
+### Added
+- Bash completion.
+- Optional hiding of built-in help command.
+- Optional skipping of flag parsing at command level.
+- `Author`, `Email`, and `Compiled` metadata on app.
+- `Before` hook func support at app and command level.
+- `CommandNotFound` func support at app level.
+- Command reference available on context.
+- `GenericFlag` type.
+- `Float64Flag` type.
+- `BoolTFlag` type.
+- `IsSet` flag helper on context.
+- More flag lookup funcs at context level.
+- More tests & docs.
+
+### Changed
+- Help template updates to account for presence/absence of flags.
+- Separated subcommand help template.
+- Exposed `HelpPrinter` var for more control over help output.
+
+## [1.0.0] - 2013-11-01
+### Added
+- `help` flag in default app flag set and each command flag set.
+- Custom handling of argument parsing errors.
+- Command lookup by name at app level.
+- `StringSliceFlag` type and supporting `StringSlice` type.
+- `IntSliceFlag` type and supporting `IntSlice` type.
+- Slice type flag lookups by name at context level.
+- Export of app and command help functions.
+- More tests & docs.
+
+## 0.1.0 - 2013-07-22
+### Added
+- Initial implementation.
+
+[Unreleased]: https://github.com/codegangsta/cli/compare/v1.16.0...HEAD
+[1.16.0]: https://github.com/codegangsta/cli/compare/v1.15.0...v1.16.0
+[1.15.0]: https://github.com/codegangsta/cli/compare/v1.14.0...v1.15.0
+[1.14.0]: https://github.com/codegangsta/cli/compare/v1.13.0...v1.14.0
+[1.13.0]: https://github.com/codegangsta/cli/compare/v1.12.0...v1.13.0
+[1.12.0]: https://github.com/codegangsta/cli/compare/v1.11.1...v1.12.0
+[1.11.1]: https://github.com/codegangsta/cli/compare/v1.11.0...v1.11.1
+[1.11.0]: https://github.com/codegangsta/cli/compare/v1.10.2...v1.11.0
+[1.10.2]: https://github.com/codegangsta/cli/compare/v1.10.1...v1.10.2
+[1.10.1]: https://github.com/codegangsta/cli/compare/v1.10.0...v1.10.1
+[1.10.0]: https://github.com/codegangsta/cli/compare/v1.9.0...v1.10.0
+[1.9.0]: https://github.com/codegangsta/cli/compare/v1.8.0...v1.9.0
+[1.8.0]: https://github.com/codegangsta/cli/compare/v1.7.1...v1.8.0
+[1.7.1]: https://github.com/codegangsta/cli/compare/v1.7.0...v1.7.1
+[1.7.0]: https://github.com/codegangsta/cli/compare/v1.6.0...v1.7.0
+[1.6.0]: https://github.com/codegangsta/cli/compare/v1.5.0...v1.6.0
+[1.5.0]: https://github.com/codegangsta/cli/compare/v1.4.1...v1.5.0
+[1.4.1]: https://github.com/codegangsta/cli/compare/v1.4.0...v1.4.1
+[1.4.0]: https://github.com/codegangsta/cli/compare/v1.3.1...v1.4.0
+[1.3.1]: https://github.com/codegangsta/cli/compare/v1.3.0...v1.3.1
+[1.3.0]: https://github.com/codegangsta/cli/compare/v1.2.0...v1.3.0
+[1.2.0]: https://github.com/codegangsta/cli/compare/v1.1.0...v1.2.0
+[1.1.0]: https://github.com/codegangsta/cli/compare/v1.0.0...v1.1.0
+[1.0.0]: https://github.com/codegangsta/cli/compare/v0.1.0...v1.0.0
diff --git a/vendor/github.com/codegangsta/cli/README.md b/vendor/github.com/codegangsta/cli/README.md
index 2453c1af..06f7b844 100644
--- a/vendor/github.com/codegangsta/cli/README.md
+++ b/vendor/github.com/codegangsta/cli/README.md
@@ -1,31 +1,35 @@
-[](https://travis-ci.org/codegangsta/cli)
+[](http://gocover.io/github.com/codegangsta/cli)
+[](https://travis-ci.org/codegangsta/cli)
+[](https://godoc.org/github.com/codegangsta/cli)
+[](https://codebeat.co/projects/github-com-codegangsta-cli)
-# cli.go
-cli.go is simple, fast, and fun package for building command line apps in Go. The goal is to enable developers to write fast and distributable command line applications in an expressive way.
+# cli
-You can view the API docs here:
-http://godoc.org/github.com/codegangsta/cli
+cli is a simple, fast, and fun package for building command line apps in Go. The goal is to enable developers to write fast and distributable command line applications in an expressive way.
## Overview
+
Command line apps are usually so tiny that there is absolutely no reason why your code should *not* be self-documenting. Things like generating help text and parsing command flags/options should not hinder productivity when writing a command line app.
-This is where cli.go comes into play. cli.go makes command line programming fun, organized, and expressive!
+**This is where cli comes into play.** cli makes command line programming fun, organized, and expressive!
## Installation
-Make sure you have a working Go environment (go 1.1 is *required*). [See the install instructions](http://golang.org/doc/install.html).
-To install cli.go, simply run:
+Make sure you have a working Go environment (go 1.1+ is *required*). [See the install instructions](http://golang.org/doc/install.html).
+
+To install cli, simply run:
```
$ go get github.com/codegangsta/cli
```
-Make sure your PATH includes to the `$GOPATH/bin` directory so your commands can be easily used:
+Make sure your `PATH` includes to the `$GOPATH/bin` directory so your commands can be easily used:
```
export PATH=$PATH:$GOPATH/bin
```
## Getting Started
-One of the philosophies behind cli.go is that an API should be playful and full of discovery. So a cli.go app can be as little as one line of code in `main()`.
+
+One of the philosophies behind cli is that an API should be playful and full of discovery. So a cli app can be as little as one line of code in `main()`.
``` go
package main
@@ -46,7 +50,9 @@ This app will run and show help text, but is not very useful. Let's give an acti
package main
import (
+ "fmt"
"os"
+
"github.com/codegangsta/cli"
)
@@ -54,10 +60,11 @@ func main() {
app := cli.NewApp()
app.Name = "boom"
app.Usage = "make an explosive entrance"
- app.Action = func(c *cli.Context) {
- println("boom! I say!")
+ app.Action = func(c *cli.Context) error {
+ fmt.Println("boom! I say!")
+ return nil
}
-
+
app.Run(os.Args)
}
```
@@ -68,12 +75,15 @@ Running this already gives you a ton of functionality, plus support for things l
Being a programmer can be a lonely job. Thankfully by the power of automation that is not the case! Let's create a greeter app to fend off our demons of loneliness!
+Start by creating a directory named `greet`, and within it, add a file, `greet.go` with the following code in it:
+
``` go
-/* greet.go */
package main
import (
+ "fmt"
"os"
+
"github.com/codegangsta/cli"
)
@@ -81,10 +91,11 @@ func main() {
app := cli.NewApp()
app.Name = "greet"
app.Usage = "fight the loneliness!"
- app.Action = func(c *cli.Context) {
- println("Hello friend!")
+ app.Action = func(c *cli.Context) error {
+ fmt.Println("Hello friend!")
+ return nil
}
-
+
app.Run(os.Args)
}
```
@@ -102,7 +113,8 @@ $ greet
Hello friend!
```
-cli.go also generates some bitchass help text:
+cli also generates neat help text:
+
```
$ greet help
NAME:
@@ -122,18 +134,22 @@ GLOBAL OPTIONS
```
### Arguments
-You can lookup arguments by calling the `Args` function on cli.Context.
+
+You can lookup arguments by calling the `Args` function on `cli.Context`.
``` go
...
-app.Action = func(c *cli.Context) {
- println("Hello", c.Args()[0])
+app.Action = func(c *cli.Context) error {
+ fmt.Println("Hello", c.Args()[0])
+ return nil
}
...
```
### Flags
+
Setting and querying flags is simple.
+
``` go
...
app.Flags = []cli.Flag {
@@ -143,23 +159,75 @@ app.Flags = []cli.Flag {
Usage: "language for the greeting",
},
}
-app.Action = func(c *cli.Context) {
+app.Action = func(c *cli.Context) error {
name := "someone"
- if len(c.Args()) > 0 {
+ if c.NArg() > 0 {
name = c.Args()[0]
}
if c.String("lang") == "spanish" {
- println("Hola", name)
+ fmt.Println("Hola", name)
} else {
- println("Hello", name)
+ fmt.Println("Hello", name)
}
+ return nil
}
...
```
+You can also set a destination variable for a flag, to which the content will be scanned.
+
+``` go
+...
+var language string
+app.Flags = []cli.Flag {
+ cli.StringFlag{
+ Name: "lang",
+ Value: "english",
+ Usage: "language for the greeting",
+ Destination: &language,
+ },
+}
+app.Action = func(c *cli.Context) error {
+ name := "someone"
+ if c.NArg() > 0 {
+ name = c.Args()[0]
+ }
+ if language == "spanish" {
+ fmt.Println("Hola", name)
+ } else {
+ fmt.Println("Hello", name)
+ }
+ return nil
+}
+...
+```
+
+See full list of flags at http://godoc.org/github.com/codegangsta/cli
+
+#### Placeholder Values
+
+Sometimes it's useful to specify a flag's value within the usage string itself. Such placeholders are
+indicated with back quotes.
+
+For example this:
+```go
+cli.StringFlag{
+ Name: "config, c",
+ Usage: "Load configuration from `FILE`",
+}
+```
+
+Will result in help output like:
+
+```
+--config FILE, -c FILE Load configuration from FILE
+```
+
+Note that only the first placeholder is used. Subsequent back-quoted words will be left as-is.
+
#### Alternate Names
-You can set alternate (or short) names for flags by providing a comma-delimited list for the Name. e.g.
+You can set alternate (or short) names for flags by providing a comma-delimited list for the `Name`. e.g.
``` go
app.Flags = []cli.Flag {
@@ -171,9 +239,11 @@ app.Flags = []cli.Flag {
}
```
+That flag can then be set with `--lang spanish` or `-l spanish`. Note that giving two different forms of the same flag in the same command invocation is an error.
+
#### Values from the Environment
-You can also have the default value set from the environment via EnvVar. e.g.
+You can also have the default value set from the environment via `EnvVar`. e.g.
``` go
app.Flags = []cli.Flag {
@@ -186,61 +256,195 @@ app.Flags = []cli.Flag {
}
```
-That flag can then be set with `--lang spanish` or `-l spanish`. Note that giving two different forms of the same flag in the same command invocation is an error.
+The `EnvVar` may also be given as a comma-delimited "cascade", where the first environment variable that resolves is used as the default.
+
+``` go
+app.Flags = []cli.Flag {
+ cli.StringFlag{
+ Name: "lang, l",
+ Value: "english",
+ Usage: "language for the greeting",
+ EnvVar: "LEGACY_COMPAT_LANG,APP_LANG,LANG",
+ },
+}
+```
+
+#### Values from alternate input sources (YAML and others)
+
+There is a separate package altsrc that adds support for getting flag values from other input sources like YAML.
+
+In order to get values for a flag from an alternate input source the following code would be added to wrap an existing cli.Flag like below:
+
+``` go
+ altsrc.NewIntFlag(cli.IntFlag{Name: "test"})
+```
+
+Initialization must also occur for these flags. Below is an example initializing getting data from a yaml file below.
+
+``` go
+ command.Before = altsrc.InitInputSourceWithContext(command.Flags, NewYamlSourceFromFlagFunc("load"))
+```
+
+The code above will use the "load" string as a flag name to get the file name of a yaml file from the cli.Context.
+It will then use that file name to initialize the yaml input source for any flags that are defined on that command.
+As a note the "load" flag used would also have to be defined on the command flags in order for this code snipped to work.
+
+Currently only YAML files are supported but developers can add support for other input sources by implementing the
+altsrc.InputSourceContext for their given sources.
+
+Here is a more complete sample of a command using YAML support:
+
+``` go
+ command := &cli.Command{
+ Name: "test-cmd",
+ Aliases: []string{"tc"},
+ Usage: "this is for testing",
+ Description: "testing",
+ Action: func(c *cli.Context) error {
+ // Action to run
+ return nil
+ },
+ Flags: []cli.Flag{
+ NewIntFlag(cli.IntFlag{Name: "test"}),
+ cli.StringFlag{Name: "load"}},
+ }
+ command.Before = InitInputSourceWithContext(command.Flags, NewYamlSourceFromFlagFunc("load"))
+ err := command.Run(c)
+```
### Subcommands
Subcommands can be defined for a more git-like command line app.
+
```go
...
app.Commands = []cli.Command{
{
Name: "add",
- ShortName: "a",
+ Aliases: []string{"a"},
Usage: "add a task to the list",
- Action: func(c *cli.Context) {
- println("added task: ", c.Args().First())
+ Action: func(c *cli.Context) error {
+ fmt.Println("added task: ", c.Args().First())
+ return nil
},
},
{
Name: "complete",
- ShortName: "c",
+ Aliases: []string{"c"},
Usage: "complete a task on the list",
- Action: func(c *cli.Context) {
- println("completed task: ", c.Args().First())
+ Action: func(c *cli.Context) error {
+ fmt.Println("completed task: ", c.Args().First())
+ return nil
},
},
{
Name: "template",
- ShortName: "r",
+ Aliases: []string{"r"},
Usage: "options for task templates",
Subcommands: []cli.Command{
{
Name: "add",
Usage: "add a new template",
- Action: func(c *cli.Context) {
- println("new task template: ", c.Args().First())
+ Action: func(c *cli.Context) error {
+ fmt.Println("new task template: ", c.Args().First())
+ return nil
},
},
{
Name: "remove",
Usage: "remove an existing template",
- Action: func(c *cli.Context) {
- println("removed task template: ", c.Args().First())
+ Action: func(c *cli.Context) error {
+ fmt.Println("removed task template: ", c.Args().First())
+ return nil
},
},
},
- },
+ },
}
...
```
+### Subcommands categories
+
+For additional organization in apps that have many subcommands, you can
+associate a category for each command to group them together in the help
+output.
+
+E.g.
+
+```go
+...
+ app.Commands = []cli.Command{
+ {
+ Name: "noop",
+ },
+ {
+ Name: "add",
+ Category: "template",
+ },
+ {
+ Name: "remove",
+ Category: "template",
+ },
+ }
+...
+```
+
+Will include:
+
+```
+...
+COMMANDS:
+ noop
+
+ Template actions:
+ add
+ remove
+...
+```
+
+### Exit code
+
+Calling `App.Run` will not automatically call `os.Exit`, which means that by
+default the exit code will "fall through" to being `0`. An explicit exit code
+may be set by returning a non-nil error that fulfills `cli.ExitCoder`, *or* a
+`cli.MultiError` that includes an error that fulfills `cli.ExitCoder`, e.g.:
+
+``` go
+package main
+
+import (
+ "os"
+
+ "github.com/codegangsta/cli"
+)
+
+func main() {
+ app := cli.NewApp()
+ app.Flags = []cli.Flag{
+ cli.BoolTFlag{
+ Name: "ginger-crouton",
+ Usage: "is it in the soup?",
+ },
+ }
+ app.Action = func(ctx *cli.Context) error {
+ if !ctx.Bool("ginger-crouton") {
+ return cli.NewExitError("it is not in the soup", 86)
+ }
+ return nil
+ }
+
+ app.Run(os.Args)
+}
+```
+
### Bash Completion
-You can enable completion commands by setting the EnableBashCompletion
-flag on the App object. By default, this setting will only auto-complete to
+You can enable completion commands by setting the `EnableBashCompletion`
+flag on the `App` object. By default, this setting will only auto-complete to
show an app's subcommands, but you can write your own completion methods for
the App or its subcommands.
+
```go
...
var tasks = []string{"cook", "clean", "laundry", "eat", "sleep", "code"}
@@ -248,19 +452,20 @@ app := cli.NewApp()
app.EnableBashCompletion = true
app.Commands = []cli.Command{
{
- Name: "complete",
- ShortName: "c",
+ Name: "complete",
+ Aliases: []string{"c"},
Usage: "complete a task on the list",
- Action: func(c *cli.Context) {
- println("completed task: ", c.Args().First())
+ Action: func(c *cli.Context) error {
+ fmt.Println("completed task: ", c.Args().First())
+ return nil
},
BashComplete: func(c *cli.Context) {
// This will complete if no args are passed
- if len(c.Args()) > 0 {
+ if c.NArg() > 0 {
return
}
for _, t := range tasks {
- println(t)
+ fmt.Println(t)
}
},
}
@@ -270,11 +475,94 @@ app.Commands = []cli.Command{
#### To Enable
-Source the autocomplete/bash_autocomplete file in your .bashrc file while
-setting the PROG variable to the name of your program:
+Source the `autocomplete/bash_autocomplete` file in your `.bashrc` file while
+setting the `PROG` variable to the name of your program:
`PROG=myprogram source /.../cli/autocomplete/bash_autocomplete`
+#### To Distribute
-## About
-cli.go is written by none other than the [Code Gangsta](http://codegangsta.io)
+Copy `autocomplete/bash_autocomplete` into `/etc/bash_completion.d/` and rename
+it to the name of the program you wish to add autocomplete support for (or
+automatically install it there if you are distributing a package). Don't forget
+to source the file to make it active in the current shell.
+
+```
+sudo cp src/bash_autocomplete /etc/bash_completion.d/
+source /etc/bash_completion.d/
+```
+
+Alternatively, you can just document that users should source the generic
+`autocomplete/bash_autocomplete` in their bash configuration with `$PROG` set
+to the name of their program (as above).
+
+### Generated Help Text Customization
+
+All of the help text generation may be customized, and at multiple levels. The
+templates are exposed as variables `AppHelpTemplate`, `CommandHelpTemplate`, and
+`SubcommandHelpTemplate` which may be reassigned or augmented, and full override
+is possible by assigning a compatible func to the `cli.HelpPrinter` variable,
+e.g.:
+
+``` go
+package main
+
+import (
+ "fmt"
+ "io"
+ "os"
+
+ "github.com/codegangsta/cli"
+)
+
+func main() {
+ // EXAMPLE: Append to an existing template
+ cli.AppHelpTemplate = fmt.Sprintf(`%s
+
+WEBSITE: http://awesometown.example.com
+
+SUPPORT: support@awesometown.example.com
+
+`, cli.AppHelpTemplate)
+
+ // EXAMPLE: Override a template
+ cli.AppHelpTemplate = `NAME:
+ {{.Name}} - {{.Usage}}
+USAGE:
+ {{.HelpName}} {{if .VisibleFlags}}[global options]{{end}}{{if .Commands}} command
+[command options]{{end}} {{if
+.ArgsUsage}}{{.ArgsUsage}}{{else}}[arguments...]{{end}}
+ {{if len .Authors}}
+AUTHOR(S):
+ {{range .Authors}}{{ . }}{{end}}
+ {{end}}{{if .Commands}}
+COMMANDS:
+{{range .Commands}}{{if not .HideHelp}} {{join .Names ", "}}{{ "\t"
+}}{{.Usage}}{{ "\n" }}{{end}}{{end}}{{end}}{{if .VisibleFlags}}
+GLOBAL OPTIONS:
+ {{range .VisibleFlags}}{{.}}
+ {{end}}{{end}}{{if .Copyright }}
+COPYRIGHT:
+ {{.Copyright}}
+ {{end}}{{if .Version}}
+VERSION:
+ {{.Version}}
+ {{end}}
+`
+
+ // EXAMPLE: Replace the `HelpPrinter` func
+ cli.HelpPrinter = func(w io.Writer, templ string, data interface{}) {
+ fmt.Println("Ha HA. I pwnd the help!!1")
+ }
+
+ cli.NewApp().Run(os.Args)
+}
+```
+
+## Contribution Guidelines
+
+Feel free to put up a pull request to fix a bug or maybe add a feature. I will give it a code review and make sure that it does not break backwards compatibility. If I or any other collaborators agree that it is in line with the vision of the project, we will work with you to get the code into a mergeable state and merge it into the master branch.
+
+If you have contributed something significant to the project, I will most likely add you as a collaborator. As a collaborator you are given the ability to merge others pull requests. It is very important that new code does not break existing code, so be careful about what code you do choose to merge. If you have any questions feel free to link @codegangsta to the issue in question and we can review it together.
+
+If you feel like you have contributed to the project but have not yet been added as a collaborator, I probably forgot to add you. Hit @codegangsta up over email and we will get it figured out.
diff --git a/vendor/github.com/codegangsta/cli/app.go b/vendor/github.com/codegangsta/cli/app.go
index e193b828..89c741bf 100644
--- a/vendor/github.com/codegangsta/cli/app.go
+++ b/vendor/github.com/codegangsta/cli/app.go
@@ -2,18 +2,43 @@ package cli
import (
"fmt"
+ "io"
"io/ioutil"
"os"
+ "path/filepath"
+ "reflect"
+ "sort"
"time"
)
-// App is the main structure of a cli application. It is recomended that
-// and app be created with the cli.NewApp() function
+var (
+ changeLogURL = "https://github.com/codegangsta/cli/blob/master/CHANGELOG.md"
+ appActionDeprecationURL = fmt.Sprintf("%s#deprecated-cli-app-action-signature", changeLogURL)
+ runAndExitOnErrorDeprecationURL = fmt.Sprintf("%s#deprecated-cli-app-runandexitonerror", changeLogURL)
+
+ contactSysadmin = "This is an error in the application. Please contact the distributor of this application if this is not you."
+
+ errNonFuncAction = NewExitError("ERROR invalid Action type. "+
+ fmt.Sprintf("Must be a func of type `cli.ActionFunc`. %s", contactSysadmin)+
+ fmt.Sprintf("See %s", appActionDeprecationURL), 2)
+ errInvalidActionSignature = NewExitError("ERROR invalid Action signature. "+
+ fmt.Sprintf("Must be `cli.ActionFunc`. %s", contactSysadmin)+
+ fmt.Sprintf("See %s", appActionDeprecationURL), 2)
+)
+
+// App is the main structure of a cli application. It is recommended that
+// an app be created with the cli.NewApp() function
type App struct {
- // The name of the program. Defaults to os.Args[0]
+ // The name of the program. Defaults to path.Base(os.Args[0])
Name string
+ // Full name of command for help, defaults to Name
+ HelpName string
// Description of the program.
Usage string
+ // Text to override the USAGE section of help
+ UsageText string
+ // Description of the program argument format.
+ ArgsUsage string
// Version of the program
Version string
// List of commands to execute
@@ -24,21 +49,41 @@ type App struct {
EnableBashCompletion bool
// Boolean to hide built-in help command
HideHelp bool
+ // Boolean to hide built-in version flag and the VERSION section of help
+ HideVersion bool
+ // Populate on app startup, only gettable throught method Categories()
+ categories CommandCategories
// An action to execute when the bash-completion flag is set
- BashComplete func(context *Context)
+ BashComplete BashCompleteFunc
// An action to execute before any subcommands are run, but after the context is ready
// If a non-nil error is returned, no subcommands are run
- Before func(context *Context) error
+ Before BeforeFunc
+ // An action to execute after any subcommands are run, but after the subcommand has finished
+ // It is run even if Action() panics
+ After AfterFunc
// The action to execute when no subcommands are specified
- Action func(context *Context)
+ Action interface{}
+ // TODO: replace `Action: interface{}` with `Action: ActionFunc` once some kind
+ // of deprecation period has passed, maybe?
+
// Execute this function if the proper command cannot be found
- CommandNotFound func(context *Context, command string)
+ CommandNotFound CommandNotFoundFunc
+ // Execute this function if an usage error occurs
+ OnUsageError OnUsageErrorFunc
// Compilation date
Compiled time.Time
- // Author
+ // List of all authors who contributed
+ Authors []Author
+ // Copyright of the binary if any
+ Copyright string
+ // Name of Author (Note: Use App.Authors, this is deprecated)
Author string
- // Author e-mail
+ // Email of Author (Note: Use App.Authors, this is deprecated)
Email string
+ // Writer writer to write output to
+ Writer io.Writer
+ // Other custom info
+ Metadata map[string]interface{}
}
// Tries to find out when this binary was compiled.
@@ -54,67 +99,113 @@ func compileTime() time.Time {
// Creates a new cli Application with some reasonable defaults for Name, Usage, Version and Action.
func NewApp() *App {
return &App{
- Name: os.Args[0],
+ Name: filepath.Base(os.Args[0]),
+ HelpName: filepath.Base(os.Args[0]),
Usage: "A new cli application",
+ UsageText: "",
Version: "0.0.0",
BashComplete: DefaultAppComplete,
Action: helpCommand.Action,
Compiled: compileTime(),
- Author: "Author",
- Email: "unknown@email",
+ Writer: os.Stdout,
}
}
// Entry point to the cli app. Parses the arguments slice and routes to the proper flag/args combination
-func (a *App) Run(arguments []string) error {
+func (a *App) Run(arguments []string) (err error) {
+ if a.Author != "" || a.Email != "" {
+ a.Authors = append(a.Authors, Author{Name: a.Author, Email: a.Email})
+ }
+
+ newCmds := []Command{}
+ for _, c := range a.Commands {
+ if c.HelpName == "" {
+ c.HelpName = fmt.Sprintf("%s %s", a.HelpName, c.Name)
+ }
+ newCmds = append(newCmds, c)
+ }
+ a.Commands = newCmds
+
+ a.categories = CommandCategories{}
+ for _, command := range a.Commands {
+ a.categories = a.categories.AddCommand(command.Category, command)
+ }
+ sort.Sort(a.categories)
+
// append help to commands
if a.Command(helpCommand.Name) == nil && !a.HideHelp {
a.Commands = append(a.Commands, helpCommand)
- a.appendFlag(HelpFlag)
+ if (HelpFlag != BoolFlag{}) {
+ a.appendFlag(HelpFlag)
+ }
}
//append version/help flags
if a.EnableBashCompletion {
a.appendFlag(BashCompletionFlag)
}
- a.appendFlag(VersionFlag)
+
+ if !a.HideVersion {
+ a.appendFlag(VersionFlag)
+ }
// parse flags
set := flagSet(a.Name, a.Flags)
set.SetOutput(ioutil.Discard)
- err := set.Parse(arguments[1:])
+ err = set.Parse(arguments[1:])
nerr := normalizeFlags(a.Flags, set)
+ context := NewContext(a, set, nil)
if nerr != nil {
- fmt.Println(nerr)
- context := NewContext(a, set, set)
+ fmt.Fprintln(a.Writer, nerr)
ShowAppHelp(context)
- fmt.Println("")
return nerr
}
- context := NewContext(a, set, set)
-
- if err != nil {
- fmt.Printf("Incorrect Usage.\n\n")
- ShowAppHelp(context)
- fmt.Println("")
- return err
- }
if checkCompletions(context) {
return nil
}
- if checkHelp(context) {
+ if err != nil {
+ if a.OnUsageError != nil {
+ err := a.OnUsageError(context, err, false)
+ HandleExitCoder(err)
+ return err
+ } else {
+ fmt.Fprintf(a.Writer, "%s\n\n", "Incorrect Usage.")
+ ShowAppHelp(context)
+ return err
+ }
+ }
+
+ if !a.HideHelp && checkHelp(context) {
+ ShowAppHelp(context)
return nil
}
- if checkVersion(context) {
+ if !a.HideVersion && checkVersion(context) {
+ ShowVersion(context)
return nil
}
+ if a.After != nil {
+ defer func() {
+ if afterErr := a.After(context); afterErr != nil {
+ if err != nil {
+ err = NewMultiError(err, afterErr)
+ } else {
+ err = afterErr
+ }
+ }
+ }()
+ }
+
if a.Before != nil {
- err := a.Before(context)
- if err != nil {
+ beforeErr := a.Before(context)
+ if beforeErr != nil {
+ fmt.Fprintf(a.Writer, "%v\n\n", beforeErr)
+ ShowAppHelp(context)
+ HandleExitCoder(beforeErr)
+ err = beforeErr
return err
}
}
@@ -129,28 +220,44 @@ func (a *App) Run(arguments []string) error {
}
// Run default Action
- a.Action(context)
- return nil
+ err = HandleAction(a.Action, context)
+
+ HandleExitCoder(err)
+ return err
}
-// Another entry point to the cli app, takes care of passing arguments and error handling
+// DEPRECATED: Another entry point to the cli app, takes care of passing arguments and error handling
func (a *App) RunAndExitOnError() {
+ fmt.Fprintf(os.Stderr,
+ "DEPRECATED cli.App.RunAndExitOnError. %s See %s\n",
+ contactSysadmin, runAndExitOnErrorDeprecationURL)
if err := a.Run(os.Args); err != nil {
- os.Stderr.WriteString(fmt.Sprintln(err))
- os.Exit(1)
+ fmt.Fprintln(os.Stderr, err)
+ OsExiter(1)
}
}
// Invokes the subcommand given the context, parses ctx.Args() to generate command-specific flags
-func (a *App) RunAsSubcommand(ctx *Context) error {
+func (a *App) RunAsSubcommand(ctx *Context) (err error) {
// append help to commands
if len(a.Commands) > 0 {
if a.Command(helpCommand.Name) == nil && !a.HideHelp {
a.Commands = append(a.Commands, helpCommand)
- a.appendFlag(HelpFlag)
+ if (HelpFlag != BoolFlag{}) {
+ a.appendFlag(HelpFlag)
+ }
}
}
+ newCmds := []Command{}
+ for _, c := range a.Commands {
+ if c.HelpName == "" {
+ c.HelpName = fmt.Sprintf("%s %s", a.HelpName, c.Name)
+ }
+ newCmds = append(newCmds, c)
+ }
+ a.Commands = newCmds
+
// append flags
if a.EnableBashCompletion {
a.appendFlag(BashCompletionFlag)
@@ -159,31 +266,37 @@ func (a *App) RunAsSubcommand(ctx *Context) error {
// parse flags
set := flagSet(a.Name, a.Flags)
set.SetOutput(ioutil.Discard)
- err := set.Parse(ctx.Args().Tail())
+ err = set.Parse(ctx.Args().Tail())
nerr := normalizeFlags(a.Flags, set)
- context := NewContext(a, set, ctx.globalSet)
+ context := NewContext(a, set, ctx)
if nerr != nil {
- fmt.Println(nerr)
+ fmt.Fprintln(a.Writer, nerr)
+ fmt.Fprintln(a.Writer)
if len(a.Commands) > 0 {
ShowSubcommandHelp(context)
} else {
ShowCommandHelp(ctx, context.Args().First())
}
- fmt.Println("")
return nerr
}
- if err != nil {
- fmt.Printf("Incorrect Usage.\n\n")
- ShowSubcommandHelp(context)
- return err
- }
-
if checkCompletions(context) {
return nil
}
+ if err != nil {
+ if a.OnUsageError != nil {
+ err = a.OnUsageError(context, err, true)
+ HandleExitCoder(err)
+ return err
+ } else {
+ fmt.Fprintf(a.Writer, "%s\n\n", "Incorrect Usage.")
+ ShowSubcommandHelp(context)
+ return err
+ }
+ }
+
if len(a.Commands) > 0 {
if checkSubcommandHelp(context) {
return nil
@@ -194,9 +307,25 @@ func (a *App) RunAsSubcommand(ctx *Context) error {
}
}
+ if a.After != nil {
+ defer func() {
+ afterErr := a.After(context)
+ if afterErr != nil {
+ HandleExitCoder(err)
+ if err != nil {
+ err = NewMultiError(err, afterErr)
+ } else {
+ err = afterErr
+ }
+ }
+ }()
+ }
+
if a.Before != nil {
- err := a.Before(context)
- if err != nil {
+ beforeErr := a.Before(context)
+ if beforeErr != nil {
+ HandleExitCoder(beforeErr)
+ err = beforeErr
return err
}
}
@@ -211,13 +340,10 @@ func (a *App) RunAsSubcommand(ctx *Context) error {
}
// Run default Action
- if len(a.Commands) > 0 {
- a.Action(context)
- } else {
- a.Action(ctx)
- }
+ err = HandleAction(a.Action, context)
- return nil
+ HandleExitCoder(err)
+ return err
}
// Returns the named command on App. Returns nil if the command does not exist
@@ -231,6 +357,16 @@ func (a *App) Command(name string) *Command {
return nil
}
+// Returnes the array containing all the categories with the commands they contain
+func (a *App) Categories() CommandCategories {
+ return a.categories
+}
+
+// VisibleFlags returns a slice of the Flags with Hidden=false
+func (a *App) VisibleFlags() []Flag {
+ return visibleFlags(a.Flags)
+}
+
func (a *App) hasFlag(flag Flag) bool {
for _, f := range a.Flags {
if flag == f {
@@ -246,3 +382,59 @@ func (a *App) appendFlag(flag Flag) {
a.Flags = append(a.Flags, flag)
}
}
+
+// Author represents someone who has contributed to a cli project.
+type Author struct {
+ Name string // The Authors name
+ Email string // The Authors email
+}
+
+// String makes Author comply to the Stringer interface, to allow an easy print in the templating process
+func (a Author) String() string {
+ e := ""
+ if a.Email != "" {
+ e = "<" + a.Email + "> "
+ }
+
+ return fmt.Sprintf("%v %v", a.Name, e)
+}
+
+// HandleAction uses ✧✧✧reflection✧✧✧ to figure out if the given Action is an
+// ActionFunc, a func with the legacy signature for Action, or some other
+// invalid thing. If it's an ActionFunc or a func with the legacy signature for
+// Action, the func is run!
+func HandleAction(action interface{}, context *Context) (err error) {
+ defer func() {
+ if r := recover(); r != nil {
+ switch r.(type) {
+ case error:
+ err = r.(error)
+ default:
+ err = NewExitError(fmt.Sprintf("ERROR unknown Action error: %v. See %s", r, appActionDeprecationURL), 2)
+ }
+ }
+ }()
+
+ if reflect.TypeOf(action).Kind() != reflect.Func {
+ return errNonFuncAction
+ }
+
+ vals := reflect.ValueOf(action).Call([]reflect.Value{reflect.ValueOf(context)})
+
+ if len(vals) == 0 {
+ fmt.Fprintf(os.Stderr,
+ "DEPRECATED Action signature. Must be `cli.ActionFunc`. %s See %s\n",
+ contactSysadmin, appActionDeprecationURL)
+ return nil
+ }
+
+ if len(vals) > 1 {
+ return errInvalidActionSignature
+ }
+
+ if retErr, ok := vals[0].Interface().(error); vals[0].IsValid() && ok {
+ return retErr
+ }
+
+ return err
+}
diff --git a/vendor/github.com/codegangsta/cli/app_test.go b/vendor/github.com/codegangsta/cli/app_test.go
deleted file mode 100644
index d4216fee..00000000
--- a/vendor/github.com/codegangsta/cli/app_test.go
+++ /dev/null
@@ -1,403 +0,0 @@
-package cli_test
-
-import (
- "fmt"
- "os"
- "testing"
-
- "github.com/codegangsta/cli"
-)
-
-func ExampleApp() {
- // set args for examples sake
- os.Args = []string{"greet", "--name", "Jeremy"}
-
- app := cli.NewApp()
- app.Name = "greet"
- app.Flags = []cli.Flag{
- cli.StringFlag{Name: "name", Value: "bob", Usage: "a name to say"},
- }
- app.Action = func(c *cli.Context) {
- fmt.Printf("Hello %v\n", c.String("name"))
- }
- app.Run(os.Args)
- // Output:
- // Hello Jeremy
-}
-
-func ExampleAppSubcommand() {
- // set args for examples sake
- os.Args = []string{"say", "hi", "english", "--name", "Jeremy"}
- app := cli.NewApp()
- app.Name = "say"
- app.Commands = []cli.Command{
- {
- Name: "hello",
- ShortName: "hi",
- Usage: "use it to see a description",
- Description: "This is how we describe hello the function",
- Subcommands: []cli.Command{
- {
- Name: "english",
- ShortName: "en",
- Usage: "sends a greeting in english",
- Description: "greets someone in english",
- Flags: []cli.Flag{
- cli.StringFlag{
- Name: "name",
- Value: "Bob",
- Usage: "Name of the person to greet",
- },
- },
- Action: func(c *cli.Context) {
- fmt.Println("Hello,", c.String("name"))
- },
- },
- },
- },
- }
-
- app.Run(os.Args)
- // Output:
- // Hello, Jeremy
-}
-
-func ExampleAppHelp() {
- // set args for examples sake
- os.Args = []string{"greet", "h", "describeit"}
-
- app := cli.NewApp()
- app.Name = "greet"
- app.Flags = []cli.Flag{
- cli.StringFlag{Name: "name", Value: "bob", Usage: "a name to say"},
- }
- app.Commands = []cli.Command{
- {
- Name: "describeit",
- ShortName: "d",
- Usage: "use it to see a description",
- Description: "This is how we describe describeit the function",
- Action: func(c *cli.Context) {
- fmt.Printf("i like to describe things")
- },
- },
- }
- app.Run(os.Args)
- // Output:
- // NAME:
- // describeit - use it to see a description
- //
- // USAGE:
- // command describeit [arguments...]
- //
- // DESCRIPTION:
- // This is how we describe describeit the function
-}
-
-func ExampleAppBashComplete() {
- // set args for examples sake
- os.Args = []string{"greet", "--generate-bash-completion"}
-
- app := cli.NewApp()
- app.Name = "greet"
- app.EnableBashCompletion = true
- app.Commands = []cli.Command{
- {
- Name: "describeit",
- ShortName: "d",
- Usage: "use it to see a description",
- Description: "This is how we describe describeit the function",
- Action: func(c *cli.Context) {
- fmt.Printf("i like to describe things")
- },
- }, {
- Name: "next",
- Usage: "next example",
- Description: "more stuff to see when generating bash completion",
- Action: func(c *cli.Context) {
- fmt.Printf("the next example")
- },
- },
- }
-
- app.Run(os.Args)
- // Output:
- // describeit
- // d
- // next
- // help
- // h
-}
-
-func TestApp_Run(t *testing.T) {
- s := ""
-
- app := cli.NewApp()
- app.Action = func(c *cli.Context) {
- s = s + c.Args().First()
- }
-
- err := app.Run([]string{"command", "foo"})
- expect(t, err, nil)
- err = app.Run([]string{"command", "bar"})
- expect(t, err, nil)
- expect(t, s, "foobar")
-}
-
-var commandAppTests = []struct {
- name string
- expected bool
-}{
- {"foobar", true},
- {"batbaz", true},
- {"b", true},
- {"f", true},
- {"bat", false},
- {"nothing", false},
-}
-
-func TestApp_Command(t *testing.T) {
- app := cli.NewApp()
- fooCommand := cli.Command{Name: "foobar", ShortName: "f"}
- batCommand := cli.Command{Name: "batbaz", ShortName: "b"}
- app.Commands = []cli.Command{
- fooCommand,
- batCommand,
- }
-
- for _, test := range commandAppTests {
- expect(t, app.Command(test.name) != nil, test.expected)
- }
-}
-
-func TestApp_CommandWithArgBeforeFlags(t *testing.T) {
- var parsedOption, firstArg string
-
- app := cli.NewApp()
- command := cli.Command{
- Name: "cmd",
- Flags: []cli.Flag{
- cli.StringFlag{Name: "option", Value: "", Usage: "some option"},
- },
- Action: func(c *cli.Context) {
- parsedOption = c.String("option")
- firstArg = c.Args().First()
- },
- }
- app.Commands = []cli.Command{command}
-
- app.Run([]string{"", "cmd", "my-arg", "--option", "my-option"})
-
- expect(t, parsedOption, "my-option")
- expect(t, firstArg, "my-arg")
-}
-
-func TestApp_Float64Flag(t *testing.T) {
- var meters float64
-
- app := cli.NewApp()
- app.Flags = []cli.Flag{
- cli.Float64Flag{Name: "height", Value: 1.5, Usage: "Set the height, in meters"},
- }
- app.Action = func(c *cli.Context) {
- meters = c.Float64("height")
- }
-
- app.Run([]string{"", "--height", "1.93"})
- expect(t, meters, 1.93)
-}
-
-func TestApp_ParseSliceFlags(t *testing.T) {
- var parsedOption, firstArg string
- var parsedIntSlice []int
- var parsedStringSlice []string
-
- app := cli.NewApp()
- command := cli.Command{
- Name: "cmd",
- Flags: []cli.Flag{
- cli.IntSliceFlag{Name: "p", Value: &cli.IntSlice{}, Usage: "set one or more ip addr"},
- cli.StringSliceFlag{Name: "ip", Value: &cli.StringSlice{}, Usage: "set one or more ports to open"},
- },
- Action: func(c *cli.Context) {
- parsedIntSlice = c.IntSlice("p")
- parsedStringSlice = c.StringSlice("ip")
- parsedOption = c.String("option")
- firstArg = c.Args().First()
- },
- }
- app.Commands = []cli.Command{command}
-
- app.Run([]string{"", "cmd", "my-arg", "-p", "22", "-p", "80", "-ip", "8.8.8.8", "-ip", "8.8.4.4"})
-
- IntsEquals := func(a, b []int) bool {
- if len(a) != len(b) {
- return false
- }
- for i, v := range a {
- if v != b[i] {
- return false
- }
- }
- return true
- }
-
- StrsEquals := func(a, b []string) bool {
- if len(a) != len(b) {
- return false
- }
- for i, v := range a {
- if v != b[i] {
- return false
- }
- }
- return true
- }
- var expectedIntSlice = []int{22, 80}
- var expectedStringSlice = []string{"8.8.8.8", "8.8.4.4"}
-
- if !IntsEquals(parsedIntSlice, expectedIntSlice) {
- t.Errorf("%v does not match %v", parsedIntSlice, expectedIntSlice)
- }
-
- if !StrsEquals(parsedStringSlice, expectedStringSlice) {
- t.Errorf("%v does not match %v", parsedStringSlice, expectedStringSlice)
- }
-}
-
-func TestApp_BeforeFunc(t *testing.T) {
- beforeRun, subcommandRun := false, false
- beforeError := fmt.Errorf("fail")
- var err error
-
- app := cli.NewApp()
-
- app.Before = func(c *cli.Context) error {
- beforeRun = true
- s := c.String("opt")
- if s == "fail" {
- return beforeError
- }
-
- return nil
- }
-
- app.Commands = []cli.Command{
- cli.Command{
- Name: "sub",
- Action: func(c *cli.Context) {
- subcommandRun = true
- },
- },
- }
-
- app.Flags = []cli.Flag{
- cli.StringFlag{Name: "opt"},
- }
-
- // run with the Before() func succeeding
- err = app.Run([]string{"command", "--opt", "succeed", "sub"})
-
- if err != nil {
- t.Fatalf("Run error: %s", err)
- }
-
- if beforeRun == false {
- t.Errorf("Before() not executed when expected")
- }
-
- if subcommandRun == false {
- t.Errorf("Subcommand not executed when expected")
- }
-
- // reset
- beforeRun, subcommandRun = false, false
-
- // run with the Before() func failing
- err = app.Run([]string{"command", "--opt", "fail", "sub"})
-
- // should be the same error produced by the Before func
- if err != beforeError {
- t.Errorf("Run error expected, but not received")
- }
-
- if beforeRun == false {
- t.Errorf("Before() not executed when expected")
- }
-
- if subcommandRun == true {
- t.Errorf("Subcommand executed when NOT expected")
- }
-
-}
-
-func TestAppHelpPrinter(t *testing.T) {
- oldPrinter := cli.HelpPrinter
- defer func() {
- cli.HelpPrinter = oldPrinter
- }()
-
- var wasCalled = false
- cli.HelpPrinter = func(template string, data interface{}) {
- wasCalled = true
- }
-
- app := cli.NewApp()
- app.Run([]string{"-h"})
-
- if wasCalled == false {
- t.Errorf("Help printer expected to be called, but was not")
- }
-}
-
-func TestAppCommandNotFound(t *testing.T) {
- beforeRun, subcommandRun := false, false
- app := cli.NewApp()
-
- app.CommandNotFound = func(c *cli.Context, command string) {
- beforeRun = true
- }
-
- app.Commands = []cli.Command{
- cli.Command{
- Name: "bar",
- Action: func(c *cli.Context) {
- subcommandRun = true
- },
- },
- }
-
- app.Run([]string{"command", "foo"})
-
- expect(t, beforeRun, true)
- expect(t, subcommandRun, false)
-}
-
-func TestGlobalFlagsInSubcommands(t *testing.T) {
- subcommandRun := false
- app := cli.NewApp()
-
- app.Flags = []cli.Flag{
- cli.BoolFlag{Name: "debug, d", Usage: "Enable debugging"},
- }
-
- app.Commands = []cli.Command{
- cli.Command{
- Name: "foo",
- Subcommands: []cli.Command{
- {
- Name: "bar",
- Action: func(c *cli.Context) {
- if c.GlobalBool("debug") {
- subcommandRun = true
- }
- },
- },
- },
- },
- }
-
- app.Run([]string{"command", "-d", "foo", "bar"})
-
- expect(t, subcommandRun, true)
-}
diff --git a/vendor/github.com/codegangsta/cli/appveyor.yml b/vendor/github.com/codegangsta/cli/appveyor.yml
new file mode 100644
index 00000000..3ca7afab
--- /dev/null
+++ b/vendor/github.com/codegangsta/cli/appveyor.yml
@@ -0,0 +1,16 @@
+version: "{build}"
+
+os: Windows Server 2012 R2
+
+install:
+ - go version
+ - go env
+
+build_script:
+ - cd %APPVEYOR_BUILD_FOLDER%
+ - go vet ./...
+ - go test -v ./...
+
+test: off
+
+deploy: off
diff --git a/vendor/github.com/codegangsta/cli/category.go b/vendor/github.com/codegangsta/cli/category.go
new file mode 100644
index 00000000..7dbf2182
--- /dev/null
+++ b/vendor/github.com/codegangsta/cli/category.go
@@ -0,0 +1,30 @@
+package cli
+
+type CommandCategories []*CommandCategory
+
+type CommandCategory struct {
+ Name string
+ Commands Commands
+}
+
+func (c CommandCategories) Less(i, j int) bool {
+ return c[i].Name < c[j].Name
+}
+
+func (c CommandCategories) Len() int {
+ return len(c)
+}
+
+func (c CommandCategories) Swap(i, j int) {
+ c[i], c[j] = c[j], c[i]
+}
+
+func (c CommandCategories) AddCommand(category string, command Command) CommandCategories {
+ for _, commandCategory := range c {
+ if commandCategory.Name == category {
+ commandCategory.Commands = append(commandCategory.Commands, command)
+ return c
+ }
+ }
+ return append(c, &CommandCategory{Name: category, Commands: []Command{command}})
+}
diff --git a/vendor/github.com/codegangsta/cli/cli.go b/vendor/github.com/codegangsta/cli/cli.go
index b7425458..f0440c56 100644
--- a/vendor/github.com/codegangsta/cli/cli.go
+++ b/vendor/github.com/codegangsta/cli/cli.go
@@ -10,7 +10,7 @@
// app := cli.NewApp()
// app.Name = "greet"
// app.Usage = "say a greeting"
-// app.Action = func(c *cli.Context) {
+// app.Action = func(c *cli.Context) error {
// println("Greetings")
// }
//
diff --git a/vendor/github.com/codegangsta/cli/cli_test.go b/vendor/github.com/codegangsta/cli/cli_test.go
deleted file mode 100644
index 879a793d..00000000
--- a/vendor/github.com/codegangsta/cli/cli_test.go
+++ /dev/null
@@ -1,100 +0,0 @@
-package cli_test
-
-import (
- "os"
-
- "github.com/codegangsta/cli"
-)
-
-func Example() {
- app := cli.NewApp()
- app.Name = "todo"
- app.Usage = "task list on the command line"
- app.Commands = []cli.Command{
- {
- Name: "add",
- ShortName: "a",
- Usage: "add a task to the list",
- Action: func(c *cli.Context) {
- println("added task: ", c.Args().First())
- },
- },
- {
- Name: "complete",
- ShortName: "c",
- Usage: "complete a task on the list",
- Action: func(c *cli.Context) {
- println("completed task: ", c.Args().First())
- },
- },
- }
-
- app.Run(os.Args)
-}
-
-func ExampleSubcommand() {
- app := cli.NewApp()
- app.Name = "say"
- app.Commands = []cli.Command{
- {
- Name: "hello",
- ShortName: "hi",
- Usage: "use it to see a description",
- Description: "This is how we describe hello the function",
- Subcommands: []cli.Command{
- {
- Name: "english",
- ShortName: "en",
- Usage: "sends a greeting in english",
- Description: "greets someone in english",
- Flags: []cli.Flag{
- cli.StringFlag{
- Name: "name",
- Value: "Bob",
- Usage: "Name of the person to greet",
- },
- },
- Action: func(c *cli.Context) {
- println("Hello, ", c.String("name"))
- },
- }, {
- Name: "spanish",
- ShortName: "sp",
- Usage: "sends a greeting in spanish",
- Flags: []cli.Flag{
- cli.StringFlag{
- Name: "surname",
- Value: "Jones",
- Usage: "Surname of the person to greet",
- },
- },
- Action: func(c *cli.Context) {
- println("Hola, ", c.String("surname"))
- },
- }, {
- Name: "french",
- ShortName: "fr",
- Usage: "sends a greeting in french",
- Flags: []cli.Flag{
- cli.StringFlag{
- Name: "nickname",
- Value: "Stevie",
- Usage: "Nickname of the person to greet",
- },
- },
- Action: func(c *cli.Context) {
- println("Bonjour, ", c.String("nickname"))
- },
- },
- },
- }, {
- Name: "bye",
- Usage: "says goodbye",
- Action: func(c *cli.Context) {
- println("bye")
- },
- },
- }
-
- app.Run(os.Args)
-}
diff --git a/vendor/github.com/codegangsta/cli/command.go b/vendor/github.com/codegangsta/cli/command.go
index dcc8de5c..9ca7e518 100644
--- a/vendor/github.com/codegangsta/cli/command.go
+++ b/vendor/github.com/codegangsta/cli/command.go
@@ -3,6 +3,7 @@ package cli
import (
"fmt"
"io/ioutil"
+ "sort"
"strings"
)
@@ -10,37 +11,67 @@ import (
type Command struct {
// The name of the command
Name string
- // short name of the command. Typically one character
+ // short name of the command. Typically one character (deprecated, use `Aliases`)
ShortName string
+ // A list of aliases for the command
+ Aliases []string
// A short description of the usage of this command
Usage string
+ // Custom text to show on USAGE section of help
+ UsageText string
// A longer explanation of how the command works
Description string
+ // A short description of the arguments of this command
+ ArgsUsage string
+ // The category the command is part of
+ Category string
// The function to call when checking for bash command completions
- BashComplete func(context *Context)
+ BashComplete BashCompleteFunc
// An action to execute before any sub-subcommands are run, but after the context is ready
// If a non-nil error is returned, no sub-subcommands are run
- Before func(context *Context) error
+ Before BeforeFunc
+ // An action to execute after any subcommands are run, but after the subcommand has finished
+ // It is run even if Action() panics
+ After AfterFunc
// The function to call when this command is invoked
- Action func(context *Context)
+ Action interface{}
+ // TODO: replace `Action: interface{}` with `Action: ActionFunc` once some kind
+ // of deprecation period has passed, maybe?
+
+ // Execute this function if a usage error occurs.
+ OnUsageError OnUsageErrorFunc
// List of child commands
- Subcommands []Command
+ Subcommands Commands
// List of flags to parse
Flags []Flag
// Treat all flags as normal arguments if true
SkipFlagParsing bool
// Boolean to hide built-in help command
HideHelp bool
+
+ // Full name of command for help, defaults to full command name, including parent commands.
+ HelpName string
+ commandNamePath []string
}
-// Invokes the command given the context, parses ctx.Args() to generate command-specific flags
-func (c Command) Run(ctx *Context) error {
+// Returns the full name of the command.
+// For subcommands this ensures that parent commands are part of the command path
+func (c Command) FullName() string {
+ if c.commandNamePath == nil {
+ return c.Name
+ }
+ return strings.Join(c.commandNamePath, " ")
+}
- if len(c.Subcommands) > 0 || c.Before != nil {
+type Commands []Command
+
+// Invokes the command given the context, parses ctx.Args() to generate command-specific flags
+func (c Command) Run(ctx *Context) (err error) {
+ if len(c.Subcommands) > 0 {
return c.startApp(ctx)
}
- if !c.HideHelp {
+ if !c.HideHelp && (HelpFlag != BoolFlag{}) {
// append help to flags
c.Flags = append(
c.Flags,
@@ -55,40 +86,66 @@ func (c Command) Run(ctx *Context) error {
set := flagSet(c.Name, c.Flags)
set.SetOutput(ioutil.Discard)
- firstFlagIndex := -1
- for index, arg := range ctx.Args() {
- if strings.HasPrefix(arg, "-") {
- firstFlagIndex = index
- break
+ if !c.SkipFlagParsing {
+ firstFlagIndex := -1
+ terminatorIndex := -1
+ for index, arg := range ctx.Args() {
+ if arg == "--" {
+ terminatorIndex = index
+ break
+ } else if arg == "-" {
+ // Do nothing. A dash alone is not really a flag.
+ continue
+ } else if strings.HasPrefix(arg, "-") && firstFlagIndex == -1 {
+ firstFlagIndex = index
+ }
+ }
+
+ if firstFlagIndex > -1 {
+ args := ctx.Args()
+ regularArgs := make([]string, len(args[1:firstFlagIndex]))
+ copy(regularArgs, args[1:firstFlagIndex])
+
+ var flagArgs []string
+ if terminatorIndex > -1 {
+ flagArgs = args[firstFlagIndex:terminatorIndex]
+ regularArgs = append(regularArgs, args[terminatorIndex:]...)
+ } else {
+ flagArgs = args[firstFlagIndex:]
+ }
+
+ err = set.Parse(append(flagArgs, regularArgs...))
+ } else {
+ err = set.Parse(ctx.Args().Tail())
+ }
+ } else {
+ if c.SkipFlagParsing {
+ err = set.Parse(append([]string{"--"}, ctx.Args().Tail()...))
}
}
- var err error
- if firstFlagIndex > -1 && !c.SkipFlagParsing {
- args := ctx.Args()
- regularArgs := args[1:firstFlagIndex]
- flagArgs := args[firstFlagIndex:]
- err = set.Parse(append(flagArgs, regularArgs...))
- } else {
- err = set.Parse(ctx.Args().Tail())
- }
-
if err != nil {
- fmt.Printf("Incorrect Usage.\n\n")
- ShowCommandHelp(ctx, c.Name)
- fmt.Println("")
- return err
+ if c.OnUsageError != nil {
+ err := c.OnUsageError(ctx, err, false)
+ HandleExitCoder(err)
+ return err
+ } else {
+ fmt.Fprintln(ctx.App.Writer, "Incorrect Usage.")
+ fmt.Fprintln(ctx.App.Writer)
+ ShowCommandHelp(ctx, c.Name)
+ return err
+ }
}
nerr := normalizeFlags(c.Flags, set)
if nerr != nil {
- fmt.Println(nerr)
- fmt.Println("")
+ fmt.Fprintln(ctx.App.Writer, nerr)
+ fmt.Fprintln(ctx.App.Writer)
ShowCommandHelp(ctx, c.Name)
- fmt.Println("")
return nerr
}
- context := NewContext(ctx.App, set, ctx.globalSet)
+
+ context := NewContext(ctx.App, set, ctx)
if checkCommandCompletions(context, c.Name) {
return nil
@@ -97,32 +154,100 @@ func (c Command) Run(ctx *Context) error {
if checkCommandHelp(context, c.Name) {
return nil
}
+
+ if c.After != nil {
+ defer func() {
+ afterErr := c.After(context)
+ if afterErr != nil {
+ HandleExitCoder(err)
+ if err != nil {
+ err = NewMultiError(err, afterErr)
+ } else {
+ err = afterErr
+ }
+ }
+ }()
+ }
+
+ if c.Before != nil {
+ err = c.Before(context)
+ if err != nil {
+ fmt.Fprintln(ctx.App.Writer, err)
+ fmt.Fprintln(ctx.App.Writer)
+ ShowCommandHelp(ctx, c.Name)
+ HandleExitCoder(err)
+ return err
+ }
+ }
+
context.Command = c
- c.Action(context)
- return nil
+ err = HandleAction(c.Action, context)
+
+ if err != nil {
+ HandleExitCoder(err)
+ }
+ return err
+}
+
+func (c Command) Names() []string {
+ names := []string{c.Name}
+
+ if c.ShortName != "" {
+ names = append(names, c.ShortName)
+ }
+
+ return append(names, c.Aliases...)
}
// Returns true if Command.Name or Command.ShortName matches given name
func (c Command) HasName(name string) bool {
- return c.Name == name || c.ShortName == name
+ for _, n := range c.Names() {
+ if n == name {
+ return true
+ }
+ }
+ return false
}
func (c Command) startApp(ctx *Context) error {
app := NewApp()
-
+ app.Metadata = ctx.App.Metadata
// set the name and usage
app.Name = fmt.Sprintf("%s %s", ctx.App.Name, c.Name)
+ if c.HelpName == "" {
+ app.HelpName = c.HelpName
+ } else {
+ app.HelpName = app.Name
+ }
+
if c.Description != "" {
app.Usage = c.Description
} else {
app.Usage = c.Usage
}
+ // set CommandNotFound
+ app.CommandNotFound = ctx.App.CommandNotFound
+
// set the flags and commands
app.Commands = c.Subcommands
app.Flags = c.Flags
app.HideHelp = c.HideHelp
+ app.Version = ctx.App.Version
+ app.HideVersion = ctx.App.HideVersion
+ app.Compiled = ctx.App.Compiled
+ app.Author = ctx.App.Author
+ app.Email = ctx.App.Email
+ app.Writer = ctx.App.Writer
+
+ app.categories = CommandCategories{}
+ for _, command := range c.Subcommands {
+ app.categories = app.categories.AddCommand(command.Category, command)
+ }
+
+ sort.Sort(app.categories)
+
// bash completion
app.EnableBashCompletion = ctx.App.EnableBashCompletion
if c.BashComplete != nil {
@@ -131,11 +256,21 @@ func (c Command) startApp(ctx *Context) error {
// set the actions
app.Before = c.Before
+ app.After = c.After
if c.Action != nil {
app.Action = c.Action
} else {
app.Action = helpSubcommand.Action
}
+ for index, cc := range app.Commands {
+ app.Commands[index].commandNamePath = []string{c.Name, cc.Name}
+ }
+
return app.RunAsSubcommand(ctx)
}
+
+// VisibleFlags returns a slice of the Flags with Hidden=false
+func (c Command) VisibleFlags() []Flag {
+ return visibleFlags(c.Flags)
+}
diff --git a/vendor/github.com/codegangsta/cli/command_test.go b/vendor/github.com/codegangsta/cli/command_test.go
deleted file mode 100644
index 3afd83e7..00000000
--- a/vendor/github.com/codegangsta/cli/command_test.go
+++ /dev/null
@@ -1,48 +0,0 @@
-package cli_test
-
-import (
- "flag"
- "github.com/codegangsta/cli"
- "testing"
-)
-
-func TestCommandDoNotIgnoreFlags(t *testing.T) {
- app := cli.NewApp()
- set := flag.NewFlagSet("test", 0)
- test := []string{"blah", "blah", "-break"}
- set.Parse(test)
-
- c := cli.NewContext(app, set, set)
-
- command := cli.Command {
- Name: "test-cmd",
- ShortName: "tc",
- Usage: "this is for testing",
- Description: "testing",
- Action: func(_ *cli.Context) { },
- }
- err := command.Run(c)
-
- expect(t, err.Error(), "flag provided but not defined: -break")
-}
-
-func TestCommandIgnoreFlags(t *testing.T) {
- app := cli.NewApp()
- set := flag.NewFlagSet("test", 0)
- test := []string{"blah", "blah"}
- set.Parse(test)
-
- c := cli.NewContext(app, set, set)
-
- command := cli.Command {
- Name: "test-cmd",
- ShortName: "tc",
- Usage: "this is for testing",
- Description: "testing",
- Action: func(_ *cli.Context) { },
- SkipFlagParsing: true,
- }
- err := command.Run(c)
-
- expect(t, err, nil)
-}
diff --git a/vendor/github.com/codegangsta/cli/context.go b/vendor/github.com/codegangsta/cli/context.go
index 1e023cef..ef3d2fcc 100644
--- a/vendor/github.com/codegangsta/cli/context.go
+++ b/vendor/github.com/codegangsta/cli/context.go
@@ -5,6 +5,7 @@ import (
"flag"
"strconv"
"strings"
+ "time"
)
// Context is a type that is passed through to
@@ -12,16 +13,17 @@ import (
// can be used to retrieve context-specific Args and
// parsed command-line options.
type Context struct {
- App *App
- Command Command
- flagSet *flag.FlagSet
- globalSet *flag.FlagSet
- setFlags map[string]bool
+ App *App
+ Command Command
+ flagSet *flag.FlagSet
+ setFlags map[string]bool
+ globalSetFlags map[string]bool
+ parentContext *Context
}
// Creates a new context. For use in when invoking an App or Command action.
-func NewContext(app *App, set *flag.FlagSet, globalSet *flag.FlagSet) *Context {
- return &Context{App: app, flagSet: set, globalSet: globalSet}
+func NewContext(app *App, set *flag.FlagSet, parentCtx *Context) *Context {
+ return &Context{App: app, flagSet: set, parentContext: parentCtx}
}
// Looks up the value of a local int flag, returns 0 if no int flag exists
@@ -29,6 +31,11 @@ func (c *Context) Int(name string) int {
return lookupInt(name, c.flagSet)
}
+// Looks up the value of a local time.Duration flag, returns 0 if no time.Duration flag exists
+func (c *Context) Duration(name string) time.Duration {
+ return lookupDuration(name, c.flagSet)
+}
+
// Looks up the value of a local float64 flag, returns 0 if no float64 flag exists
func (c *Context) Float64(name string) float64 {
return lookupFloat64(name, c.flagSet)
@@ -66,35 +73,85 @@ func (c *Context) Generic(name string) interface{} {
// Looks up the value of a global int flag, returns 0 if no int flag exists
func (c *Context) GlobalInt(name string) int {
- return lookupInt(name, c.globalSet)
+ if fs := lookupGlobalFlagSet(name, c); fs != nil {
+ return lookupInt(name, fs)
+ }
+ return 0
+}
+
+// Looks up the value of a global float64 flag, returns float64(0) if no float64
+// flag exists
+func (c *Context) GlobalFloat64(name string) float64 {
+ if fs := lookupGlobalFlagSet(name, c); fs != nil {
+ return lookupFloat64(name, fs)
+ }
+ return float64(0)
+}
+
+// Looks up the value of a global time.Duration flag, returns 0 if no time.Duration flag exists
+func (c *Context) GlobalDuration(name string) time.Duration {
+ if fs := lookupGlobalFlagSet(name, c); fs != nil {
+ return lookupDuration(name, fs)
+ }
+ return 0
}
// Looks up the value of a global bool flag, returns false if no bool flag exists
func (c *Context) GlobalBool(name string) bool {
- return lookupBool(name, c.globalSet)
+ if fs := lookupGlobalFlagSet(name, c); fs != nil {
+ return lookupBool(name, fs)
+ }
+ return false
}
// Looks up the value of a global string flag, returns "" if no string flag exists
func (c *Context) GlobalString(name string) string {
- return lookupString(name, c.globalSet)
+ if fs := lookupGlobalFlagSet(name, c); fs != nil {
+ return lookupString(name, fs)
+ }
+ return ""
}
// Looks up the value of a global string slice flag, returns nil if no string slice flag exists
func (c *Context) GlobalStringSlice(name string) []string {
- return lookupStringSlice(name, c.globalSet)
+ if fs := lookupGlobalFlagSet(name, c); fs != nil {
+ return lookupStringSlice(name, fs)
+ }
+ return nil
}
// Looks up the value of a global int slice flag, returns nil if no int slice flag exists
func (c *Context) GlobalIntSlice(name string) []int {
- return lookupIntSlice(name, c.globalSet)
+ if fs := lookupGlobalFlagSet(name, c); fs != nil {
+ return lookupIntSlice(name, fs)
+ }
+ return nil
}
// Looks up the value of a global generic flag, returns nil if no generic flag exists
func (c *Context) GlobalGeneric(name string) interface{} {
- return lookupGeneric(name, c.globalSet)
+ if fs := lookupGlobalFlagSet(name, c); fs != nil {
+ return lookupGeneric(name, fs)
+ }
+ return nil
}
-// Determines if the flag was actually set exists
+// Returns the number of flags set
+func (c *Context) NumFlags() int {
+ return c.flagSet.NFlag()
+}
+
+// Set sets a context flag to a value.
+func (c *Context) Set(name, value string) error {
+ return c.flagSet.Set(name, value)
+}
+
+// GlobalSet sets a context flag to a value on the global flagset
+func (c *Context) GlobalSet(name, value string) error {
+ return globalContext(c).flagSet.Set(name, value)
+}
+
+// Determines if the flag was actually set
func (c *Context) IsSet(name string) bool {
if c.setFlags == nil {
c.setFlags = make(map[string]bool)
@@ -105,6 +162,52 @@ func (c *Context) IsSet(name string) bool {
return c.setFlags[name] == true
}
+// Determines if the global flag was actually set
+func (c *Context) GlobalIsSet(name string) bool {
+ if c.globalSetFlags == nil {
+ c.globalSetFlags = make(map[string]bool)
+ ctx := c
+ if ctx.parentContext != nil {
+ ctx = ctx.parentContext
+ }
+ for ; ctx != nil && c.globalSetFlags[name] == false; ctx = ctx.parentContext {
+ ctx.flagSet.Visit(func(f *flag.Flag) {
+ c.globalSetFlags[f.Name] = true
+ })
+ }
+ }
+ return c.globalSetFlags[name]
+}
+
+// Returns a slice of flag names used in this context.
+func (c *Context) FlagNames() (names []string) {
+ for _, flag := range c.Command.Flags {
+ name := strings.Split(flag.GetName(), ",")[0]
+ if name == "help" {
+ continue
+ }
+ names = append(names, name)
+ }
+ return
+}
+
+// Returns a slice of global flag names used by the app.
+func (c *Context) GlobalFlagNames() (names []string) {
+ for _, flag := range c.App.Flags {
+ name := strings.Split(flag.GetName(), ",")[0]
+ if name == "help" || name == "version" {
+ continue
+ }
+ names = append(names, name)
+ }
+ return
+}
+
+// Returns the parent context, if any
+func (c *Context) Parent() *Context {
+ return c.parentContext
+}
+
type Args []string
// Returns the command line arguments associated with the context.
@@ -113,6 +216,11 @@ func (c *Context) Args() Args {
return args
}
+// Returns the number of the command line arguments.
+func (c *Context) NArg() int {
+ return len(c.Args())
+}
+
// Returns the nth argument, or else a blank string
func (a Args) Get(n int) string {
if len(a) > n {
@@ -149,6 +257,31 @@ func (a Args) Swap(from, to int) error {
return nil
}
+func globalContext(ctx *Context) *Context {
+ if ctx == nil {
+ return nil
+ }
+
+ for {
+ if ctx.parentContext == nil {
+ return ctx
+ }
+ ctx = ctx.parentContext
+ }
+}
+
+func lookupGlobalFlagSet(name string, ctx *Context) *flag.FlagSet {
+ if ctx.parentContext != nil {
+ ctx = ctx.parentContext
+ }
+ for ; ctx != nil; ctx = ctx.parentContext {
+ if f := ctx.flagSet.Lookup(name); f != nil {
+ return ctx.flagSet
+ }
+ }
+ return nil
+}
+
func lookupInt(name string, set *flag.FlagSet) int {
f := set.Lookup(name)
if f != nil {
@@ -162,6 +295,18 @@ func lookupInt(name string, set *flag.FlagSet) int {
return 0
}
+func lookupDuration(name string, set *flag.FlagSet) time.Duration {
+ f := set.Lookup(name)
+ if f != nil {
+ val, err := time.ParseDuration(f.Value.String())
+ if err == nil {
+ return val
+ }
+ }
+
+ return 0
+}
+
func lookupFloat64(name string, set *flag.FlagSet) float64 {
f := set.Lookup(name)
if f != nil {
@@ -252,7 +397,7 @@ func normalizeFlags(flags []Flag, set *flag.FlagSet) error {
visited[f.Name] = true
})
for _, f := range flags {
- parts := strings.Split(f.getName(), ",")
+ parts := strings.Split(f.GetName(), ",")
if len(parts) == 1 {
continue
}
diff --git a/vendor/github.com/codegangsta/cli/context_test.go b/vendor/github.com/codegangsta/cli/context_test.go
deleted file mode 100644
index 89041b99..00000000
--- a/vendor/github.com/codegangsta/cli/context_test.go
+++ /dev/null
@@ -1,68 +0,0 @@
-package cli_test
-
-import (
- "flag"
- "github.com/codegangsta/cli"
- "testing"
-)
-
-func TestNewContext(t *testing.T) {
- set := flag.NewFlagSet("test", 0)
- set.Int("myflag", 12, "doc")
- globalSet := flag.NewFlagSet("test", 0)
- globalSet.Int("myflag", 42, "doc")
- command := cli.Command{Name: "mycommand"}
- c := cli.NewContext(nil, set, globalSet)
- c.Command = command
- expect(t, c.Int("myflag"), 12)
- expect(t, c.GlobalInt("myflag"), 42)
- expect(t, c.Command.Name, "mycommand")
-}
-
-func TestContext_Int(t *testing.T) {
- set := flag.NewFlagSet("test", 0)
- set.Int("myflag", 12, "doc")
- c := cli.NewContext(nil, set, set)
- expect(t, c.Int("myflag"), 12)
-}
-
-func TestContext_String(t *testing.T) {
- set := flag.NewFlagSet("test", 0)
- set.String("myflag", "hello world", "doc")
- c := cli.NewContext(nil, set, set)
- expect(t, c.String("myflag"), "hello world")
-}
-
-func TestContext_Bool(t *testing.T) {
- set := flag.NewFlagSet("test", 0)
- set.Bool("myflag", false, "doc")
- c := cli.NewContext(nil, set, set)
- expect(t, c.Bool("myflag"), false)
-}
-
-func TestContext_BoolT(t *testing.T) {
- set := flag.NewFlagSet("test", 0)
- set.Bool("myflag", true, "doc")
- c := cli.NewContext(nil, set, set)
- expect(t, c.BoolT("myflag"), true)
-}
-
-func TestContext_Args(t *testing.T) {
- set := flag.NewFlagSet("test", 0)
- set.Bool("myflag", false, "doc")
- c := cli.NewContext(nil, set, set)
- set.Parse([]string{"--myflag", "bat", "baz"})
- expect(t, len(c.Args()), 2)
- expect(t, c.Bool("myflag"), true)
-}
-
-func TestContext_IsSet(t *testing.T) {
- set := flag.NewFlagSet("test", 0)
- set.Bool("myflag", false, "doc")
- set.String("otherflag", "hello world", "doc")
- c := cli.NewContext(nil, set, set)
- set.Parse([]string{"--myflag", "bat", "baz"})
- expect(t, c.IsSet("myflag"), true)
- expect(t, c.IsSet("otherflag"), false)
- expect(t, c.IsSet("bogusflag"), false)
-}
diff --git a/vendor/github.com/codegangsta/cli/errors.go b/vendor/github.com/codegangsta/cli/errors.go
new file mode 100644
index 00000000..5f1e83be
--- /dev/null
+++ b/vendor/github.com/codegangsta/cli/errors.go
@@ -0,0 +1,83 @@
+package cli
+
+import (
+ "fmt"
+ "os"
+ "strings"
+)
+
+var OsExiter = os.Exit
+
+type MultiError struct {
+ Errors []error
+}
+
+func NewMultiError(err ...error) MultiError {
+ return MultiError{Errors: err}
+}
+
+func (m MultiError) Error() string {
+ errs := make([]string, len(m.Errors))
+ for i, err := range m.Errors {
+ errs[i] = err.Error()
+ }
+
+ return strings.Join(errs, "\n")
+}
+
+// ExitCoder is the interface checked by `App` and `Command` for a custom exit
+// code
+type ExitCoder interface {
+ error
+ ExitCode() int
+}
+
+// ExitError fulfills both the builtin `error` interface and `ExitCoder`
+type ExitError struct {
+ exitCode int
+ message string
+}
+
+// NewExitError makes a new *ExitError
+func NewExitError(message string, exitCode int) *ExitError {
+ return &ExitError{
+ exitCode: exitCode,
+ message: message,
+ }
+}
+
+// Error returns the string message, fulfilling the interface required by
+// `error`
+func (ee *ExitError) Error() string {
+ return ee.message
+}
+
+// ExitCode returns the exit code, fulfilling the interface required by
+// `ExitCoder`
+func (ee *ExitError) ExitCode() int {
+ return ee.exitCode
+}
+
+// HandleExitCoder checks if the error fulfills the ExitCoder interface, and if
+// so prints the error to stderr (if it is non-empty) and calls OsExiter with the
+// given exit code. If the given error is a MultiError, then this func is
+// called on all members of the Errors slice.
+func HandleExitCoder(err error) {
+ if err == nil {
+ return
+ }
+
+ if exitErr, ok := err.(ExitCoder); ok {
+ if err.Error() != "" {
+ fmt.Fprintln(os.Stderr, err)
+ }
+ OsExiter(exitErr.ExitCode())
+ return
+ }
+
+ if multiErr, ok := err.(MultiError); ok {
+ for _, merr := range multiErr.Errors {
+ HandleExitCoder(merr)
+ }
+ }
+}
diff --git a/vendor/github.com/codegangsta/cli/flag.go b/vendor/github.com/codegangsta/cli/flag.go
index 60353e22..3b6a2e19 100644
--- a/vendor/github.com/codegangsta/cli/flag.go
+++ b/vendor/github.com/codegangsta/cli/flag.go
@@ -4,13 +4,19 @@ import (
"flag"
"fmt"
"os"
+ "reflect"
+ "runtime"
"strconv"
"strings"
+ "time"
)
+const defaultPlaceholder = "value"
+
// This flag enables bash-completion for all commands and subcommands
var BashCompletionFlag = BoolFlag{
- Name: "generate-bash-completion",
+ Name: "generate-bash-completion",
+ Hidden: true,
}
// This flag prints the version for the application
@@ -20,19 +26,23 @@ var VersionFlag = BoolFlag{
}
// This flag prints the help for all commands and subcommands
+// Set to the zero value (BoolFlag{}) to disable flag -- keeps subcommand
+// unless HideHelp is set to true)
var HelpFlag = BoolFlag{
Name: "help, h",
Usage: "show help",
}
+var FlagStringer FlagStringFunc = stringifyFlag
+
// Flag is a common interface related to parsing flags in cli.
-// For more advanced flag parsing techniques, it is recomended that
+// For more advanced flag parsing techniques, it is recommended that
// this interface be implemented.
type Flag interface {
fmt.Stringer
// Apply Flag settings to the given flag set
Apply(*flag.FlagSet)
- getName() string
+ GetName() string
}
func flagSet(name string, flags []Flag) *flag.FlagSet {
@@ -64,17 +74,27 @@ type GenericFlag struct {
Value Generic
Usage string
EnvVar string
+ Hidden bool
}
+// String returns the string representation of the generic flag to display the
+// help text to the user (uses the String() method of the generic flag to show
+// the value)
func (f GenericFlag) String() string {
- return withEnvHint(f.EnvVar, fmt.Sprintf("%s%s %v\t`%v` %s", prefixFor(f.Name), f.Name, f.Value, "-"+f.Name+" option -"+f.Name+" option", f.Usage))
+ return FlagStringer(f)
}
+// Apply takes the flagset and calls Set on the generic flag with the value
+// provided by the user for parsing by the flag
func (f GenericFlag) Apply(set *flag.FlagSet) {
val := f.Value
if f.EnvVar != "" {
- if envVal := os.Getenv(f.EnvVar); envVal != "" {
- val.Set(envVal)
+ for _, envVar := range strings.Split(f.EnvVar, ",") {
+ envVar = strings.TrimSpace(envVar)
+ if envVal := os.Getenv(envVar); envVal != "" {
+ val.Set(envVal)
+ break
+ }
}
}
@@ -83,62 +103,78 @@ func (f GenericFlag) Apply(set *flag.FlagSet) {
})
}
-func (f GenericFlag) getName() string {
+func (f GenericFlag) GetName() string {
return f.Name
}
+// StringSlice is an opaque type for []string to satisfy flag.Value
type StringSlice []string
+// Set appends the string value to the list of values
func (f *StringSlice) Set(value string) error {
*f = append(*f, value)
return nil
}
+// String returns a readable representation of this value (for usage defaults)
func (f *StringSlice) String() string {
return fmt.Sprintf("%s", *f)
}
+// Value returns the slice of strings set by this flag
func (f *StringSlice) Value() []string {
return *f
}
+// StringSlice is a string flag that can be specified multiple times on the
+// command-line
type StringSliceFlag struct {
Name string
Value *StringSlice
Usage string
EnvVar string
+ Hidden bool
}
+// String returns the usage
func (f StringSliceFlag) String() string {
- firstName := strings.Trim(strings.Split(f.Name, ",")[0], " ")
- pref := prefixFor(firstName)
- return withEnvHint(f.EnvVar, fmt.Sprintf("%s '%v'\t%v", prefixedNames(f.Name), pref+firstName+" option "+pref+firstName+" option", f.Usage))
+ return FlagStringer(f)
}
+// Apply populates the flag given the flag set and environment
func (f StringSliceFlag) Apply(set *flag.FlagSet) {
if f.EnvVar != "" {
- if envVal := os.Getenv(f.EnvVar); envVal != "" {
- newVal := &StringSlice{}
- for _, s := range strings.Split(envVal, ",") {
- newVal.Set(s)
+ for _, envVar := range strings.Split(f.EnvVar, ",") {
+ envVar = strings.TrimSpace(envVar)
+ if envVal := os.Getenv(envVar); envVal != "" {
+ newVal := &StringSlice{}
+ for _, s := range strings.Split(envVal, ",") {
+ s = strings.TrimSpace(s)
+ newVal.Set(s)
+ }
+ f.Value = newVal
+ break
}
- f.Value = newVal
}
}
eachName(f.Name, func(name string) {
+ if f.Value == nil {
+ f.Value = &StringSlice{}
+ }
set.Var(f.Value, name, f.Usage)
})
}
-func (f StringSliceFlag) getName() string {
+func (f StringSliceFlag) GetName() string {
return f.Name
}
+// StringSlice is an opaque type for []int to satisfy flag.Value
type IntSlice []int
+// Set parses the value into an integer and appends it to the list of values
func (f *IntSlice) Set(value string) error {
-
tmp, err := strconv.Atoi(value)
if err != nil {
return err
@@ -148,206 +184,331 @@ func (f *IntSlice) Set(value string) error {
return nil
}
+// String returns a readable representation of this value (for usage defaults)
func (f *IntSlice) String() string {
return fmt.Sprintf("%d", *f)
}
+// Value returns the slice of ints set by this flag
func (f *IntSlice) Value() []int {
return *f
}
+// IntSliceFlag is an int flag that can be specified multiple times on the
+// command-line
type IntSliceFlag struct {
Name string
Value *IntSlice
Usage string
EnvVar string
+ Hidden bool
}
+// String returns the usage
func (f IntSliceFlag) String() string {
- firstName := strings.Trim(strings.Split(f.Name, ",")[0], " ")
- pref := prefixFor(firstName)
- return withEnvHint(f.EnvVar, fmt.Sprintf("%s '%v'\t%v", prefixedNames(f.Name), pref+firstName+" option "+pref+firstName+" option", f.Usage))
+ return FlagStringer(f)
}
+// Apply populates the flag given the flag set and environment
func (f IntSliceFlag) Apply(set *flag.FlagSet) {
if f.EnvVar != "" {
- if envVal := os.Getenv(f.EnvVar); envVal != "" {
- newVal := &IntSlice{}
- for _, s := range strings.Split(envVal, ",") {
- err := newVal.Set(s)
- if err != nil {
- fmt.Fprintf(os.Stderr, err.Error())
+ for _, envVar := range strings.Split(f.EnvVar, ",") {
+ envVar = strings.TrimSpace(envVar)
+ if envVal := os.Getenv(envVar); envVal != "" {
+ newVal := &IntSlice{}
+ for _, s := range strings.Split(envVal, ",") {
+ s = strings.TrimSpace(s)
+ err := newVal.Set(s)
+ if err != nil {
+ fmt.Fprintf(os.Stderr, err.Error())
+ }
}
+ f.Value = newVal
+ break
}
- f.Value = newVal
}
}
eachName(f.Name, func(name string) {
+ if f.Value == nil {
+ f.Value = &IntSlice{}
+ }
set.Var(f.Value, name, f.Usage)
})
}
-func (f IntSliceFlag) getName() string {
+func (f IntSliceFlag) GetName() string {
return f.Name
}
+// BoolFlag is a switch that defaults to false
type BoolFlag struct {
- Name string
- Usage string
- EnvVar string
+ Name string
+ Usage string
+ EnvVar string
+ Destination *bool
+ Hidden bool
}
+// String returns a readable representation of this value (for usage defaults)
func (f BoolFlag) String() string {
- return withEnvHint(f.EnvVar, fmt.Sprintf("%s\t%v", prefixedNames(f.Name), f.Usage))
+ return FlagStringer(f)
}
+// Apply populates the flag given the flag set and environment
func (f BoolFlag) Apply(set *flag.FlagSet) {
val := false
if f.EnvVar != "" {
- if envVal := os.Getenv(f.EnvVar); envVal != "" {
- envValBool, err := strconv.ParseBool(envVal)
- if err == nil {
- val = envValBool
+ for _, envVar := range strings.Split(f.EnvVar, ",") {
+ envVar = strings.TrimSpace(envVar)
+ if envVal := os.Getenv(envVar); envVal != "" {
+ envValBool, err := strconv.ParseBool(envVal)
+ if err == nil {
+ val = envValBool
+ }
+ break
}
}
}
eachName(f.Name, func(name string) {
+ if f.Destination != nil {
+ set.BoolVar(f.Destination, name, val, f.Usage)
+ return
+ }
set.Bool(name, val, f.Usage)
})
}
-func (f BoolFlag) getName() string {
+func (f BoolFlag) GetName() string {
return f.Name
}
+// BoolTFlag this represents a boolean flag that is true by default, but can
+// still be set to false by --some-flag=false
type BoolTFlag struct {
- Name string
- Usage string
- EnvVar string
+ Name string
+ Usage string
+ EnvVar string
+ Destination *bool
+ Hidden bool
}
+// String returns a readable representation of this value (for usage defaults)
func (f BoolTFlag) String() string {
- return withEnvHint(f.EnvVar, fmt.Sprintf("%s\t%v", prefixedNames(f.Name), f.Usage))
+ return FlagStringer(f)
}
+// Apply populates the flag given the flag set and environment
func (f BoolTFlag) Apply(set *flag.FlagSet) {
val := true
if f.EnvVar != "" {
- if envVal := os.Getenv(f.EnvVar); envVal != "" {
- envValBool, err := strconv.ParseBool(envVal)
- if err == nil {
- val = envValBool
+ for _, envVar := range strings.Split(f.EnvVar, ",") {
+ envVar = strings.TrimSpace(envVar)
+ if envVal := os.Getenv(envVar); envVal != "" {
+ envValBool, err := strconv.ParseBool(envVal)
+ if err == nil {
+ val = envValBool
+ break
+ }
}
}
}
eachName(f.Name, func(name string) {
+ if f.Destination != nil {
+ set.BoolVar(f.Destination, name, val, f.Usage)
+ return
+ }
set.Bool(name, val, f.Usage)
})
}
-func (f BoolTFlag) getName() string {
+func (f BoolTFlag) GetName() string {
return f.Name
}
+// StringFlag represents a flag that takes as string value
type StringFlag struct {
- Name string
- Value string
- Usage string
- EnvVar string
+ Name string
+ Value string
+ Usage string
+ EnvVar string
+ Destination *string
+ Hidden bool
}
+// String returns the usage
func (f StringFlag) String() string {
- var fmtString string
- fmtString = "%s %v\t%v"
-
- if len(f.Value) > 0 {
- fmtString = "%s '%v'\t%v"
- } else {
- fmtString = "%s %v\t%v"
- }
-
- return withEnvHint(f.EnvVar, fmt.Sprintf(fmtString, prefixedNames(f.Name), f.Value, f.Usage))
+ return FlagStringer(f)
}
+// Apply populates the flag given the flag set and environment
func (f StringFlag) Apply(set *flag.FlagSet) {
if f.EnvVar != "" {
- if envVal := os.Getenv(f.EnvVar); envVal != "" {
- f.Value = envVal
+ for _, envVar := range strings.Split(f.EnvVar, ",") {
+ envVar = strings.TrimSpace(envVar)
+ if envVal := os.Getenv(envVar); envVal != "" {
+ f.Value = envVal
+ break
+ }
}
}
eachName(f.Name, func(name string) {
+ if f.Destination != nil {
+ set.StringVar(f.Destination, name, f.Value, f.Usage)
+ return
+ }
set.String(name, f.Value, f.Usage)
})
}
-func (f StringFlag) getName() string {
+func (f StringFlag) GetName() string {
return f.Name
}
+// IntFlag is a flag that takes an integer
+// Errors if the value provided cannot be parsed
type IntFlag struct {
- Name string
- Value int
- Usage string
- EnvVar string
+ Name string
+ Value int
+ Usage string
+ EnvVar string
+ Destination *int
+ Hidden bool
}
+// String returns the usage
func (f IntFlag) String() string {
- return withEnvHint(f.EnvVar, fmt.Sprintf("%s '%v'\t%v", prefixedNames(f.Name), f.Value, f.Usage))
+ return FlagStringer(f)
}
+// Apply populates the flag given the flag set and environment
func (f IntFlag) Apply(set *flag.FlagSet) {
if f.EnvVar != "" {
- if envVal := os.Getenv(f.EnvVar); envVal != "" {
- envValInt, err := strconv.ParseUint(envVal, 10, 64)
- if err == nil {
- f.Value = int(envValInt)
+ for _, envVar := range strings.Split(f.EnvVar, ",") {
+ envVar = strings.TrimSpace(envVar)
+ if envVal := os.Getenv(envVar); envVal != "" {
+ envValInt, err := strconv.ParseInt(envVal, 0, 64)
+ if err == nil {
+ f.Value = int(envValInt)
+ break
+ }
}
}
}
eachName(f.Name, func(name string) {
+ if f.Destination != nil {
+ set.IntVar(f.Destination, name, f.Value, f.Usage)
+ return
+ }
set.Int(name, f.Value, f.Usage)
})
}
-func (f IntFlag) getName() string {
+func (f IntFlag) GetName() string {
return f.Name
}
-type Float64Flag struct {
- Name string
- Value float64
- Usage string
- EnvVar string
+// DurationFlag is a flag that takes a duration specified in Go's duration
+// format: https://golang.org/pkg/time/#ParseDuration
+type DurationFlag struct {
+ Name string
+ Value time.Duration
+ Usage string
+ EnvVar string
+ Destination *time.Duration
+ Hidden bool
}
-func (f Float64Flag) String() string {
- return withEnvHint(f.EnvVar, fmt.Sprintf("%s '%v'\t%v", prefixedNames(f.Name), f.Value, f.Usage))
+// String returns a readable representation of this value (for usage defaults)
+func (f DurationFlag) String() string {
+ return FlagStringer(f)
}
-func (f Float64Flag) Apply(set *flag.FlagSet) {
+// Apply populates the flag given the flag set and environment
+func (f DurationFlag) Apply(set *flag.FlagSet) {
if f.EnvVar != "" {
- if envVal := os.Getenv(f.EnvVar); envVal != "" {
- envValFloat, err := strconv.ParseFloat(envVal, 10)
- if err == nil {
- f.Value = float64(envValFloat)
+ for _, envVar := range strings.Split(f.EnvVar, ",") {
+ envVar = strings.TrimSpace(envVar)
+ if envVal := os.Getenv(envVar); envVal != "" {
+ envValDuration, err := time.ParseDuration(envVal)
+ if err == nil {
+ f.Value = envValDuration
+ break
+ }
}
}
}
eachName(f.Name, func(name string) {
+ if f.Destination != nil {
+ set.DurationVar(f.Destination, name, f.Value, f.Usage)
+ return
+ }
+ set.Duration(name, f.Value, f.Usage)
+ })
+}
+
+func (f DurationFlag) GetName() string {
+ return f.Name
+}
+
+// Float64Flag is a flag that takes an float value
+// Errors if the value provided cannot be parsed
+type Float64Flag struct {
+ Name string
+ Value float64
+ Usage string
+ EnvVar string
+ Destination *float64
+ Hidden bool
+}
+
+// String returns the usage
+func (f Float64Flag) String() string {
+ return FlagStringer(f)
+}
+
+// Apply populates the flag given the flag set and environment
+func (f Float64Flag) Apply(set *flag.FlagSet) {
+ if f.EnvVar != "" {
+ for _, envVar := range strings.Split(f.EnvVar, ",") {
+ envVar = strings.TrimSpace(envVar)
+ if envVal := os.Getenv(envVar); envVal != "" {
+ envValFloat, err := strconv.ParseFloat(envVal, 10)
+ if err == nil {
+ f.Value = float64(envValFloat)
+ }
+ }
+ }
+ }
+
+ eachName(f.Name, func(name string) {
+ if f.Destination != nil {
+ set.Float64Var(f.Destination, name, f.Value, f.Usage)
+ return
+ }
set.Float64(name, f.Value, f.Usage)
})
}
-func (f Float64Flag) getName() string {
+func (f Float64Flag) GetName() string {
return f.Name
}
+func visibleFlags(fl []Flag) []Flag {
+ visible := []Flag{}
+ for _, flag := range fl {
+ if !reflect.ValueOf(flag).FieldByName("Hidden").Bool() {
+ visible = append(visible, flag)
+ }
+ }
+ return visible
+}
+
func prefixFor(name string) (prefix string) {
if len(name) == 1 {
prefix = "-"
@@ -358,22 +519,131 @@ func prefixFor(name string) (prefix string) {
return
}
-func prefixedNames(fullName string) (prefixed string) {
+// Returns the placeholder, if any, and the unquoted usage string.
+func unquoteUsage(usage string) (string, string) {
+ for i := 0; i < len(usage); i++ {
+ if usage[i] == '`' {
+ for j := i + 1; j < len(usage); j++ {
+ if usage[j] == '`' {
+ name := usage[i+1 : j]
+ usage = usage[:i] + name + usage[j+1:]
+ return name, usage
+ }
+ }
+ break
+ }
+ }
+ return "", usage
+}
+
+func prefixedNames(fullName, placeholder string) string {
+ var prefixed string
parts := strings.Split(fullName, ",")
for i, name := range parts {
name = strings.Trim(name, " ")
prefixed += prefixFor(name) + name
+ if placeholder != "" {
+ prefixed += " " + placeholder
+ }
if i < len(parts)-1 {
prefixed += ", "
}
}
- return
+ return prefixed
}
func withEnvHint(envVar, str string) string {
envText := ""
if envVar != "" {
- envText = fmt.Sprintf(" [$%s]", envVar)
+ prefix := "$"
+ suffix := ""
+ sep := ", $"
+ if runtime.GOOS == "windows" {
+ prefix = "%"
+ suffix = "%"
+ sep = "%, %"
+ }
+ envText = fmt.Sprintf(" [%s%s%s]", prefix, strings.Join(strings.Split(envVar, ","), sep), suffix)
}
return str + envText
}
+
+func stringifyFlag(f Flag) string {
+ fv := reflect.ValueOf(f)
+
+ switch f.(type) {
+ case IntSliceFlag:
+ return withEnvHint(fv.FieldByName("EnvVar").String(),
+ stringifyIntSliceFlag(f.(IntSliceFlag)))
+ case StringSliceFlag:
+ return withEnvHint(fv.FieldByName("EnvVar").String(),
+ stringifyStringSliceFlag(f.(StringSliceFlag)))
+ }
+
+ placeholder, usage := unquoteUsage(fv.FieldByName("Usage").String())
+
+ needsPlaceholder := false
+ defaultValueString := ""
+ val := fv.FieldByName("Value")
+
+ if val.IsValid() {
+ needsPlaceholder = true
+ defaultValueString = fmt.Sprintf(" (default: %v)", val.Interface())
+
+ if val.Kind() == reflect.String && val.String() != "" {
+ defaultValueString = fmt.Sprintf(" (default: %q)", val.String())
+ }
+ }
+
+ if defaultValueString == " (default: )" {
+ defaultValueString = ""
+ }
+
+ if needsPlaceholder && placeholder == "" {
+ placeholder = defaultPlaceholder
+ }
+
+ usageWithDefault := strings.TrimSpace(fmt.Sprintf("%s%s", usage, defaultValueString))
+
+ return withEnvHint(fv.FieldByName("EnvVar").String(),
+ fmt.Sprintf("%s\t%s", prefixedNames(fv.FieldByName("Name").String(), placeholder), usageWithDefault))
+}
+
+func stringifyIntSliceFlag(f IntSliceFlag) string {
+ defaultVals := []string{}
+ if f.Value != nil && len(f.Value.Value()) > 0 {
+ for _, i := range f.Value.Value() {
+ defaultVals = append(defaultVals, fmt.Sprintf("%d", i))
+ }
+ }
+
+ return stringifySliceFlag(f.Usage, f.Name, defaultVals)
+}
+
+func stringifyStringSliceFlag(f StringSliceFlag) string {
+ defaultVals := []string{}
+ if f.Value != nil && len(f.Value.Value()) > 0 {
+ for _, s := range f.Value.Value() {
+ if len(s) > 0 {
+ defaultVals = append(defaultVals, fmt.Sprintf("%q", s))
+ }
+ }
+ }
+
+ return stringifySliceFlag(f.Usage, f.Name, defaultVals)
+}
+
+func stringifySliceFlag(usage, name string, defaultVals []string) string {
+ placeholder, usage := unquoteUsage(usage)
+ if placeholder == "" {
+ placeholder = defaultPlaceholder
+ }
+
+ defaultVal := ""
+ if len(defaultVals) > 0 {
+ defaultVal = fmt.Sprintf(" (default: %s)", strings.Join(defaultVals, ", "))
+ }
+
+ usageWithDefault := strings.TrimSpace(fmt.Sprintf("%s%s", usage, defaultVal))
+ return fmt.Sprintf("%s\t%s", prefixedNames(name, placeholder), usageWithDefault)
+}
diff --git a/vendor/github.com/codegangsta/cli/flag_test.go b/vendor/github.com/codegangsta/cli/flag_test.go
deleted file mode 100644
index 41032361..00000000
--- a/vendor/github.com/codegangsta/cli/flag_test.go
+++ /dev/null
@@ -1,554 +0,0 @@
-package cli_test
-
-import (
- "github.com/codegangsta/cli"
-
- "fmt"
- "os"
- "reflect"
- "strings"
- "testing"
-)
-
-var boolFlagTests = []struct {
- name string
- expected string
-}{
- {"help", "--help\t"},
- {"h", "-h\t"},
-}
-
-func TestBoolFlagHelpOutput(t *testing.T) {
-
- for _, test := range boolFlagTests {
- flag := cli.BoolFlag{Name: test.name}
- output := flag.String()
-
- if output != test.expected {
- t.Errorf("%s does not match %s", output, test.expected)
- }
- }
-}
-
-var stringFlagTests = []struct {
- name string
- value string
- expected string
-}{
- {"help", "", "--help \t"},
- {"h", "", "-h \t"},
- {"h", "", "-h \t"},
- {"test", "Something", "--test 'Something'\t"},
-}
-
-func TestStringFlagHelpOutput(t *testing.T) {
-
- for _, test := range stringFlagTests {
- flag := cli.StringFlag{Name: test.name, Value: test.value}
- output := flag.String()
-
- if output != test.expected {
- t.Errorf("%s does not match %s", output, test.expected)
- }
- }
-}
-
-func TestStringFlagWithEnvVarHelpOutput(t *testing.T) {
-
- os.Setenv("APP_FOO", "derp")
- for _, test := range stringFlagTests {
- flag := cli.StringFlag{Name: test.name, Value: test.value, EnvVar: "APP_FOO"}
- output := flag.String()
-
- if !strings.HasSuffix(output, " [$APP_FOO]") {
- t.Errorf("%s does not end with [$APP_FOO]", output)
- }
- }
-}
-
-var stringSliceFlagTests = []struct {
- name string
- value *cli.StringSlice
- expected string
-}{
- {"help", func() *cli.StringSlice {
- s := &cli.StringSlice{}
- s.Set("")
- return s
- }(), "--help '--help option --help option'\t"},
- {"h", func() *cli.StringSlice {
- s := &cli.StringSlice{}
- s.Set("")
- return s
- }(), "-h '-h option -h option'\t"},
- {"h", func() *cli.StringSlice {
- s := &cli.StringSlice{}
- s.Set("")
- return s
- }(), "-h '-h option -h option'\t"},
- {"test", func() *cli.StringSlice {
- s := &cli.StringSlice{}
- s.Set("Something")
- return s
- }(), "--test '--test option --test option'\t"},
-}
-
-func TestStringSliceFlagHelpOutput(t *testing.T) {
-
- for _, test := range stringSliceFlagTests {
- flag := cli.StringSliceFlag{Name: test.name, Value: test.value}
- output := flag.String()
-
- if output != test.expected {
- t.Errorf("%q does not match %q", output, test.expected)
- }
- }
-}
-
-func TestStringSliceFlagWithEnvVarHelpOutput(t *testing.T) {
-
- os.Setenv("APP_QWWX", "11,4")
- for _, test := range stringSliceFlagTests {
- flag := cli.StringSliceFlag{Name: test.name, Value: test.value, EnvVar: "APP_QWWX"}
- output := flag.String()
-
- if !strings.HasSuffix(output, " [$APP_QWWX]") {
- t.Errorf("%q does not end with [$APP_QWWX]", output)
- }
- }
-}
-
-var intFlagTests = []struct {
- name string
- expected string
-}{
- {"help", "--help '0'\t"},
- {"h", "-h '0'\t"},
-}
-
-func TestIntFlagHelpOutput(t *testing.T) {
-
- for _, test := range intFlagTests {
- flag := cli.IntFlag{Name: test.name}
- output := flag.String()
-
- if output != test.expected {
- t.Errorf("%s does not match %s", output, test.expected)
- }
- }
-}
-
-func TestIntFlagWithEnvVarHelpOutput(t *testing.T) {
-
- os.Setenv("APP_BAR", "2")
- for _, test := range intFlagTests {
- flag := cli.IntFlag{Name: test.name, EnvVar: "APP_BAR"}
- output := flag.String()
-
- if !strings.HasSuffix(output, " [$APP_BAR]") {
- t.Errorf("%s does not end with [$APP_BAR]", output)
- }
- }
-}
-
-var intSliceFlagTests = []struct {
- name string
- value *cli.IntSlice
- expected string
-}{
- {"help", &cli.IntSlice{}, "--help '--help option --help option'\t"},
- {"h", &cli.IntSlice{}, "-h '-h option -h option'\t"},
- {"h", &cli.IntSlice{}, "-h '-h option -h option'\t"},
- {"test", func() *cli.IntSlice {
- i := &cli.IntSlice{}
- i.Set("9")
- return i
- }(), "--test '--test option --test option'\t"},
-}
-
-func TestIntSliceFlagHelpOutput(t *testing.T) {
-
- for _, test := range intSliceFlagTests {
- flag := cli.IntSliceFlag{Name: test.name, Value: test.value}
- output := flag.String()
-
- if output != test.expected {
- t.Errorf("%q does not match %q", output, test.expected)
- }
- }
-}
-
-func TestIntSliceFlagWithEnvVarHelpOutput(t *testing.T) {
-
- os.Setenv("APP_SMURF", "42,3")
- for _, test := range intSliceFlagTests {
- flag := cli.IntSliceFlag{Name: test.name, Value: test.value, EnvVar: "APP_SMURF"}
- output := flag.String()
-
- if !strings.HasSuffix(output, " [$APP_SMURF]") {
- t.Errorf("%q does not end with [$APP_SMURF]", output)
- }
- }
-}
-
-var float64FlagTests = []struct {
- name string
- expected string
-}{
- {"help", "--help '0'\t"},
- {"h", "-h '0'\t"},
-}
-
-func TestFloat64FlagHelpOutput(t *testing.T) {
-
- for _, test := range float64FlagTests {
- flag := cli.Float64Flag{Name: test.name}
- output := flag.String()
-
- if output != test.expected {
- t.Errorf("%s does not match %s", output, test.expected)
- }
- }
-}
-
-func TestFloat64FlagWithEnvVarHelpOutput(t *testing.T) {
-
- os.Setenv("APP_BAZ", "99.4")
- for _, test := range float64FlagTests {
- flag := cli.Float64Flag{Name: test.name, EnvVar: "APP_BAZ"}
- output := flag.String()
-
- if !strings.HasSuffix(output, " [$APP_BAZ]") {
- t.Errorf("%s does not end with [$APP_BAZ]", output)
- }
- }
-}
-
-var genericFlagTests = []struct {
- name string
- value cli.Generic
- expected string
-}{
- {"help", &Parser{}, "--help \t`-help option -help option` "},
- {"h", &Parser{}, "-h \t`-h option -h option` "},
- {"test", &Parser{}, "--test \t`-test option -test option` "},
-}
-
-func TestGenericFlagHelpOutput(t *testing.T) {
-
- for _, test := range genericFlagTests {
- flag := cli.GenericFlag{Name: test.name}
- output := flag.String()
-
- if output != test.expected {
- t.Errorf("%q does not match %q", output, test.expected)
- }
- }
-}
-
-func TestGenericFlagWithEnvVarHelpOutput(t *testing.T) {
-
- os.Setenv("APP_ZAP", "3")
- for _, test := range genericFlagTests {
- flag := cli.GenericFlag{Name: test.name, EnvVar: "APP_ZAP"}
- output := flag.String()
-
- if !strings.HasSuffix(output, " [$APP_ZAP]") {
- t.Errorf("%s does not end with [$APP_ZAP]", output)
- }
- }
-}
-
-func TestParseMultiString(t *testing.T) {
- (&cli.App{
- Flags: []cli.Flag{
- cli.StringFlag{Name: "serve, s"},
- },
- Action: func(ctx *cli.Context) {
- if ctx.String("serve") != "10" {
- t.Errorf("main name not set")
- }
- if ctx.String("s") != "10" {
- t.Errorf("short name not set")
- }
- },
- }).Run([]string{"run", "-s", "10"})
-}
-
-func TestParseMultiStringFromEnv(t *testing.T) {
- os.Setenv("APP_COUNT", "20")
- (&cli.App{
- Flags: []cli.Flag{
- cli.StringFlag{Name: "count, c", EnvVar: "APP_COUNT"},
- },
- Action: func(ctx *cli.Context) {
- if ctx.String("count") != "20" {
- t.Errorf("main name not set")
- }
- if ctx.String("c") != "20" {
- t.Errorf("short name not set")
- }
- },
- }).Run([]string{"run"})
-}
-
-func TestParseMultiStringSlice(t *testing.T) {
- (&cli.App{
- Flags: []cli.Flag{
- cli.StringSliceFlag{Name: "serve, s", Value: &cli.StringSlice{}},
- },
- Action: func(ctx *cli.Context) {
- if !reflect.DeepEqual(ctx.StringSlice("serve"), []string{"10", "20"}) {
- t.Errorf("main name not set")
- }
- if !reflect.DeepEqual(ctx.StringSlice("s"), []string{"10", "20"}) {
- t.Errorf("short name not set")
- }
- },
- }).Run([]string{"run", "-s", "10", "-s", "20"})
-}
-
-func TestParseMultiStringSliceFromEnv(t *testing.T) {
- os.Setenv("APP_INTERVALS", "20,30,40")
-
- (&cli.App{
- Flags: []cli.Flag{
- cli.StringSliceFlag{Name: "intervals, i", Value: &cli.StringSlice{}, EnvVar: "APP_INTERVALS"},
- },
- Action: func(ctx *cli.Context) {
- if !reflect.DeepEqual(ctx.StringSlice("intervals"), []string{"20", "30", "40"}) {
- t.Errorf("main name not set from env")
- }
- if !reflect.DeepEqual(ctx.StringSlice("i"), []string{"20", "30", "40"}) {
- t.Errorf("short name not set from env")
- }
- },
- }).Run([]string{"run"})
-}
-
-func TestParseMultiInt(t *testing.T) {
- a := cli.App{
- Flags: []cli.Flag{
- cli.IntFlag{Name: "serve, s"},
- },
- Action: func(ctx *cli.Context) {
- if ctx.Int("serve") != 10 {
- t.Errorf("main name not set")
- }
- if ctx.Int("s") != 10 {
- t.Errorf("short name not set")
- }
- },
- }
- a.Run([]string{"run", "-s", "10"})
-}
-
-func TestParseMultiIntFromEnv(t *testing.T) {
- os.Setenv("APP_TIMEOUT_SECONDS", "10")
- a := cli.App{
- Flags: []cli.Flag{
- cli.IntFlag{Name: "timeout, t", EnvVar: "APP_TIMEOUT_SECONDS"},
- },
- Action: func(ctx *cli.Context) {
- if ctx.Int("timeout") != 10 {
- t.Errorf("main name not set")
- }
- if ctx.Int("t") != 10 {
- t.Errorf("short name not set")
- }
- },
- }
- a.Run([]string{"run"})
-}
-
-func TestParseMultiIntSlice(t *testing.T) {
- (&cli.App{
- Flags: []cli.Flag{
- cli.IntSliceFlag{Name: "serve, s", Value: &cli.IntSlice{}},
- },
- Action: func(ctx *cli.Context) {
- if !reflect.DeepEqual(ctx.IntSlice("serve"), []int{10, 20}) {
- t.Errorf("main name not set")
- }
- if !reflect.DeepEqual(ctx.IntSlice("s"), []int{10, 20}) {
- t.Errorf("short name not set")
- }
- },
- }).Run([]string{"run", "-s", "10", "-s", "20"})
-}
-
-func TestParseMultiIntSliceFromEnv(t *testing.T) {
- os.Setenv("APP_INTERVALS", "20,30,40")
-
- (&cli.App{
- Flags: []cli.Flag{
- cli.IntSliceFlag{Name: "intervals, i", Value: &cli.IntSlice{}, EnvVar: "APP_INTERVALS"},
- },
- Action: func(ctx *cli.Context) {
- if !reflect.DeepEqual(ctx.IntSlice("intervals"), []int{20, 30, 40}) {
- t.Errorf("main name not set from env")
- }
- if !reflect.DeepEqual(ctx.IntSlice("i"), []int{20, 30, 40}) {
- t.Errorf("short name not set from env")
- }
- },
- }).Run([]string{"run"})
-}
-
-func TestParseMultiFloat64(t *testing.T) {
- a := cli.App{
- Flags: []cli.Flag{
- cli.Float64Flag{Name: "serve, s"},
- },
- Action: func(ctx *cli.Context) {
- if ctx.Float64("serve") != 10.2 {
- t.Errorf("main name not set")
- }
- if ctx.Float64("s") != 10.2 {
- t.Errorf("short name not set")
- }
- },
- }
- a.Run([]string{"run", "-s", "10.2"})
-}
-
-func TestParseMultiFloat64FromEnv(t *testing.T) {
- os.Setenv("APP_TIMEOUT_SECONDS", "15.5")
- a := cli.App{
- Flags: []cli.Flag{
- cli.Float64Flag{Name: "timeout, t", EnvVar: "APP_TIMEOUT_SECONDS"},
- },
- Action: func(ctx *cli.Context) {
- if ctx.Float64("timeout") != 15.5 {
- t.Errorf("main name not set")
- }
- if ctx.Float64("t") != 15.5 {
- t.Errorf("short name not set")
- }
- },
- }
- a.Run([]string{"run"})
-}
-
-func TestParseMultiBool(t *testing.T) {
- a := cli.App{
- Flags: []cli.Flag{
- cli.BoolFlag{Name: "serve, s"},
- },
- Action: func(ctx *cli.Context) {
- if ctx.Bool("serve") != true {
- t.Errorf("main name not set")
- }
- if ctx.Bool("s") != true {
- t.Errorf("short name not set")
- }
- },
- }
- a.Run([]string{"run", "--serve"})
-}
-
-func TestParseMultiBoolFromEnv(t *testing.T) {
- os.Setenv("APP_DEBUG", "1")
- a := cli.App{
- Flags: []cli.Flag{
- cli.BoolFlag{Name: "debug, d", EnvVar: "APP_DEBUG"},
- },
- Action: func(ctx *cli.Context) {
- if ctx.Bool("debug") != true {
- t.Errorf("main name not set from env")
- }
- if ctx.Bool("d") != true {
- t.Errorf("short name not set from env")
- }
- },
- }
- a.Run([]string{"run"})
-}
-
-func TestParseMultiBoolT(t *testing.T) {
- a := cli.App{
- Flags: []cli.Flag{
- cli.BoolTFlag{Name: "serve, s"},
- },
- Action: func(ctx *cli.Context) {
- if ctx.BoolT("serve") != true {
- t.Errorf("main name not set")
- }
- if ctx.BoolT("s") != true {
- t.Errorf("short name not set")
- }
- },
- }
- a.Run([]string{"run", "--serve"})
-}
-
-func TestParseMultiBoolTFromEnv(t *testing.T) {
- os.Setenv("APP_DEBUG", "0")
- a := cli.App{
- Flags: []cli.Flag{
- cli.BoolTFlag{Name: "debug, d", EnvVar: "APP_DEBUG"},
- },
- Action: func(ctx *cli.Context) {
- if ctx.BoolT("debug") != false {
- t.Errorf("main name not set from env")
- }
- if ctx.BoolT("d") != false {
- t.Errorf("short name not set from env")
- }
- },
- }
- a.Run([]string{"run"})
-}
-
-type Parser [2]string
-
-func (p *Parser) Set(value string) error {
- parts := strings.Split(value, ",")
- if len(parts) != 2 {
- return fmt.Errorf("invalid format")
- }
-
- (*p)[0] = parts[0]
- (*p)[1] = parts[1]
-
- return nil
-}
-
-func (p *Parser) String() string {
- return fmt.Sprintf("%s,%s", p[0], p[1])
-}
-
-func TestParseGeneric(t *testing.T) {
- a := cli.App{
- Flags: []cli.Flag{
- cli.GenericFlag{Name: "serve, s", Value: &Parser{}},
- },
- Action: func(ctx *cli.Context) {
- if !reflect.DeepEqual(ctx.Generic("serve"), &Parser{"10", "20"}) {
- t.Errorf("main name not set")
- }
- if !reflect.DeepEqual(ctx.Generic("s"), &Parser{"10", "20"}) {
- t.Errorf("short name not set")
- }
- },
- }
- a.Run([]string{"run", "-s", "10,20"})
-}
-
-func TestParseGenericFromEnv(t *testing.T) {
- os.Setenv("APP_SERVE", "20,30")
- a := cli.App{
- Flags: []cli.Flag{
- cli.GenericFlag{Name: "serve, s", Value: &Parser{}, EnvVar: "APP_SERVE"},
- },
- Action: func(ctx *cli.Context) {
- if !reflect.DeepEqual(ctx.Generic("serve"), &Parser{"20", "30"}) {
- t.Errorf("main name not set from env")
- }
- if !reflect.DeepEqual(ctx.Generic("s"), &Parser{"20", "30"}) {
- t.Errorf("short name not set from env")
- }
- },
- }
- a.Run([]string{"run"})
-}
diff --git a/vendor/github.com/codegangsta/cli/funcs.go b/vendor/github.com/codegangsta/cli/funcs.go
new file mode 100644
index 00000000..6b2a8463
--- /dev/null
+++ b/vendor/github.com/codegangsta/cli/funcs.go
@@ -0,0 +1,28 @@
+package cli
+
+// An action to execute when the bash-completion flag is set
+type BashCompleteFunc func(*Context)
+
+// An action to execute before any subcommands are run, but after the context is ready
+// If a non-nil error is returned, no subcommands are run
+type BeforeFunc func(*Context) error
+
+// An action to execute after any subcommands are run, but after the subcommand has finished
+// It is run even if Action() panics
+type AfterFunc func(*Context) error
+
+// The action to execute when no subcommands are specified
+type ActionFunc func(*Context) error
+
+// Execute this function if the proper command cannot be found
+type CommandNotFoundFunc func(*Context, string)
+
+// Execute this function if an usage error occurs. This is useful for displaying
+// customized usage error messages. This function is able to replace the
+// original error messages. If this function is not set, the "Incorrect usage"
+// is displayed and the execution is interrupted.
+type OnUsageErrorFunc func(context *Context, err error, isSubcommand bool) error
+
+// FlagStringFunc is used by the help generation to display a flag, which is
+// expected to be a single line.
+type FlagStringFunc func(Flag) string
diff --git a/vendor/github.com/codegangsta/cli/help.go b/vendor/github.com/codegangsta/cli/help.go
index ccca0362..45e8603b 100644
--- a/vendor/github.com/codegangsta/cli/help.go
+++ b/vendor/github.com/codegangsta/cli/help.go
@@ -2,7 +2,8 @@ package cli
import (
"fmt"
- "os"
+ "io"
+ "strings"
"text/tabwriter"
"text/template"
)
@@ -14,33 +15,43 @@ var AppHelpTemplate = `NAME:
{{.Name}} - {{.Usage}}
USAGE:
- {{.Name}} {{ if .Flags }}[global options] {{ end }}command{{ if .Flags }} [command options]{{ end }} [arguments...]
-
+ {{if .UsageText}}{{.UsageText}}{{else}}{{.HelpName}} {{if .VisibleFlags}}[global options]{{end}}{{if .Commands}} command [command options]{{end}} {{if .ArgsUsage}}{{.ArgsUsage}}{{else}}[arguments...]{{end}}{{end}}
+ {{if .Version}}{{if not .HideVersion}}
VERSION:
{{.Version}}
-
-COMMANDS:
- {{range .Commands}}{{.Name}}{{with .ShortName}}, {{.}}{{end}}{{ "\t" }}{{.Usage}}
- {{end}}{{ if .Flags }}
+ {{end}}{{end}}{{if len .Authors}}
+AUTHOR(S):
+ {{range .Authors}}{{ . }}{{end}}
+ {{end}}{{if .Commands}}
+COMMANDS:{{range .Categories}}{{if .Name}}
+ {{.Name}}{{ ":" }}{{end}}{{range .Commands}}
+ {{.Name}}{{with .ShortName}}, {{.}}{{end}}{{ "\t" }}{{.Usage}}{{end}}
+{{end}}{{end}}{{if .VisibleFlags}}
GLOBAL OPTIONS:
- {{range .Flags}}{{.}}
- {{end}}{{ end }}
+ {{range .VisibleFlags}}{{.}}
+ {{end}}{{end}}{{if .Copyright }}
+COPYRIGHT:
+ {{.Copyright}}
+ {{end}}
`
// The text template for the command help topic.
// cli.go uses text/template to render templates. You can
// render custom help text by setting this variable.
var CommandHelpTemplate = `NAME:
- {{.Name}} - {{.Usage}}
+ {{.HelpName}} - {{.Usage}}
USAGE:
- command {{.Name}}{{ if .Flags }} [command options]{{ end }} [arguments...]
+ {{.HelpName}}{{if .VisibleFlags}} [command options]{{end}} {{if .ArgsUsage}}{{.ArgsUsage}}{{else}}[arguments...]{{end}}{{if .Category}}
+
+CATEGORY:
+ {{.Category}}{{end}}{{if .Description}}
DESCRIPTION:
- {{.Description}}{{ if .Flags }}
+ {{.Description}}{{end}}{{if .VisibleFlags}}
OPTIONS:
- {{range .Flags}}{{.}}
+ {{range .VisibleFlags}}{{.}}
{{end}}{{ end }}
`
@@ -48,88 +59,107 @@ OPTIONS:
// cli.go uses text/template to render templates. You can
// render custom help text by setting this variable.
var SubcommandHelpTemplate = `NAME:
- {{.Name}} - {{.Usage}}
+ {{.HelpName}} - {{.Usage}}
USAGE:
- {{.Name}} command{{ if .Flags }} [command options]{{ end }} [arguments...]
+ {{.HelpName}} command{{if .VisibleFlags}} [command options]{{end}} {{if .ArgsUsage}}{{.ArgsUsage}}{{else}}[arguments...]{{end}}
-COMMANDS:
- {{range .Commands}}{{.Name}}{{with .ShortName}}, {{.}}{{end}}{{ "\t" }}{{.Usage}}
- {{end}}{{ if .Flags }}
+COMMANDS:{{range .Categories}}{{if .Name}}
+ {{.Name}}{{ ":" }}{{end}}{{range .Commands}}
+ {{.Name}}{{with .ShortName}}, {{.}}{{end}}{{ "\t" }}{{.Usage}}{{end}}
+{{end}}{{if .VisibleFlags}}
OPTIONS:
- {{range .Flags}}{{.}}
- {{end}}{{ end }}
+ {{range .VisibleFlags}}{{.}}
+ {{end}}{{end}}
`
var helpCommand = Command{
Name: "help",
- ShortName: "h",
+ Aliases: []string{"h"},
Usage: "Shows a list of commands or help for one command",
- Action: func(c *Context) {
+ ArgsUsage: "[command]",
+ Action: func(c *Context) error {
args := c.Args()
if args.Present() {
ShowCommandHelp(c, args.First())
} else {
ShowAppHelp(c)
}
+ return nil
},
}
var helpSubcommand = Command{
Name: "help",
- ShortName: "h",
+ Aliases: []string{"h"},
Usage: "Shows a list of commands or help for one command",
- Action: func(c *Context) {
+ ArgsUsage: "[command]",
+ Action: func(c *Context) error {
args := c.Args()
if args.Present() {
ShowCommandHelp(c, args.First())
} else {
ShowSubcommandHelp(c)
}
+ return nil
},
}
-// Prints help for the App
-var HelpPrinter = printHelp
+// Prints help for the App or Command
+type helpPrinter func(w io.Writer, templ string, data interface{})
+
+var HelpPrinter helpPrinter = printHelp
+
+// Prints version for the App
+var VersionPrinter = printVersion
func ShowAppHelp(c *Context) {
- HelpPrinter(AppHelpTemplate, c.App)
+ HelpPrinter(c.App.Writer, AppHelpTemplate, c.App)
}
// Prints the list of subcommands as the default app completion method
func DefaultAppComplete(c *Context) {
for _, command := range c.App.Commands {
- fmt.Println(command.Name)
- if command.ShortName != "" {
- fmt.Println(command.ShortName)
+ for _, name := range command.Names() {
+ fmt.Fprintln(c.App.Writer, name)
}
}
}
// Prints help for the given command
-func ShowCommandHelp(c *Context, command string) {
- for _, c := range c.App.Commands {
+func ShowCommandHelp(ctx *Context, command string) {
+ // show the subcommand help for a command with subcommands
+ if command == "" {
+ HelpPrinter(ctx.App.Writer, SubcommandHelpTemplate, ctx.App)
+ return
+ }
+
+ for _, c := range ctx.App.Commands {
if c.HasName(command) {
- HelpPrinter(CommandHelpTemplate, c)
+ HelpPrinter(ctx.App.Writer, CommandHelpTemplate, c)
return
}
}
- if c.App.CommandNotFound != nil {
- c.App.CommandNotFound(c, command)
+ if ctx.App.CommandNotFound != nil {
+ ctx.App.CommandNotFound(ctx, command)
} else {
- fmt.Printf("No help topic for '%v'\n", command)
+ fmt.Fprintf(ctx.App.Writer, "No help topic for '%v'\n", command)
}
}
// Prints help for the given subcommand
func ShowSubcommandHelp(c *Context) {
- HelpPrinter(SubcommandHelpTemplate, c.App)
+ ShowCommandHelp(c, c.Command.Name)
}
// Prints the version number of the App
func ShowVersion(c *Context) {
- fmt.Printf("%v version %v\n", c.App.Name, c.App.Version)
+ VersionPrinter(c)
+}
+
+func printVersion(c *Context) {
+ fmt.Fprintf(c.App.Writer, "%v version %v\n", c.App.Name, c.App.Version)
}
// Prints the lists of commands within a given context
@@ -148,32 +178,44 @@ func ShowCommandCompletions(ctx *Context, command string) {
}
}
-func printHelp(templ string, data interface{}) {
- w := tabwriter.NewWriter(os.Stdout, 0, 8, 1, '\t', 0)
- t := template.Must(template.New("help").Parse(templ))
+func printHelp(out io.Writer, templ string, data interface{}) {
+ funcMap := template.FuncMap{
+ "join": strings.Join,
+ }
+
+ w := tabwriter.NewWriter(out, 0, 8, 1, '\t', 0)
+ t := template.Must(template.New("help").Funcs(funcMap).Parse(templ))
err := t.Execute(w, data)
if err != nil {
- panic(err)
+ // If the writer is closed, t.Execute will fail, and there's nothing
+ // we can do to recover. We could send this to os.Stderr if we need.
+ return
}
w.Flush()
}
func checkVersion(c *Context) bool {
- if c.GlobalBool("version") {
- ShowVersion(c)
- return true
+ found := false
+ if VersionFlag.Name != "" {
+ eachName(VersionFlag.Name, func(name string) {
+ if c.GlobalBool(name) || c.Bool(name) {
+ found = true
+ }
+ })
}
-
- return false
+ return found
}
func checkHelp(c *Context) bool {
- if c.GlobalBool("h") || c.GlobalBool("help") {
- ShowAppHelp(c)
- return true
+ found := false
+ if HelpFlag.Name != "" {
+ eachName(HelpFlag.Name, func(name string) {
+ if c.GlobalBool(name) || c.Bool(name) {
+ found = true
+ }
+ })
}
-
- return false
+ return found
}
func checkCommandHelp(c *Context, name string) bool {
@@ -195,7 +237,7 @@ func checkSubcommandHelp(c *Context) bool {
}
func checkCompletions(c *Context) bool {
- if c.GlobalBool(BashCompletionFlag.Name) && c.App.EnableBashCompletion {
+ if (c.GlobalBool(BashCompletionFlag.Name) || c.Bool(BashCompletionFlag.Name)) && c.App.EnableBashCompletion {
ShowCompletions(c)
return true
}
diff --git a/vendor/github.com/codegangsta/cli/helpers_test.go b/vendor/github.com/codegangsta/cli/helpers_test.go
deleted file mode 100644
index cdc4feb2..00000000
--- a/vendor/github.com/codegangsta/cli/helpers_test.go
+++ /dev/null
@@ -1,19 +0,0 @@
-package cli_test
-
-import (
- "reflect"
- "testing"
-)
-
-/* Test Helpers */
-func expect(t *testing.T, a interface{}, b interface{}) {
- if a != b {
- t.Errorf("Expected %v (type %v) - Got %v (type %v)", b, reflect.TypeOf(b), a, reflect.TypeOf(a))
- }
-}
-
-func refute(t *testing.T, a interface{}, b interface{}) {
- if a == b {
- t.Errorf("Did not expect %v (type %v) - Got %v (type %v)", b, reflect.TypeOf(b), a, reflect.TypeOf(a))
- }
-}
diff --git a/vendor/github.com/coreos/coreos-cloudinit/config/config_test.go b/vendor/github.com/coreos/coreos-cloudinit/config/config_test.go
deleted file mode 100644
index efcdd18b..00000000
--- a/vendor/github.com/coreos/coreos-cloudinit/config/config_test.go
+++ /dev/null
@@ -1,502 +0,0 @@
-// Copyright 2015 CoreOS, Inc.
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-package config
-
-import (
- "reflect"
- "regexp"
- "strings"
- "testing"
-)
-
-func TestNewCloudConfig(t *testing.T) {
- tests := []struct {
- contents string
-
- config CloudConfig
- }{
- {},
- {
- contents: "#cloud-config\nwrite_files:\n - path: underscore",
- config: CloudConfig{WriteFiles: []File{File{Path: "underscore"}}},
- },
- {
- contents: "#cloud-config\nwrite-files:\n - path: hyphen",
- config: CloudConfig{WriteFiles: []File{File{Path: "hyphen"}}},
- },
- {
- contents: "#cloud-config\ncoreos:\n update:\n reboot-strategy: off",
- config: CloudConfig{CoreOS: CoreOS{Update: Update{RebootStrategy: "off"}}},
- },
- {
- contents: "#cloud-config\ncoreos:\n update:\n reboot-strategy: false",
- config: CloudConfig{CoreOS: CoreOS{Update: Update{RebootStrategy: "false"}}},
- },
- {
- contents: "#cloud-config\nwrite_files:\n - permissions: 0744",
- config: CloudConfig{WriteFiles: []File{File{RawFilePermissions: "0744"}}},
- },
- {
- contents: "#cloud-config\nwrite_files:\n - permissions: 744",
- config: CloudConfig{WriteFiles: []File{File{RawFilePermissions: "744"}}},
- },
- {
- contents: "#cloud-config\nwrite_files:\n - permissions: '0744'",
- config: CloudConfig{WriteFiles: []File{File{RawFilePermissions: "0744"}}},
- },
- {
- contents: "#cloud-config\nwrite_files:\n - permissions: '744'",
- config: CloudConfig{WriteFiles: []File{File{RawFilePermissions: "744"}}},
- },
- }
-
- for i, tt := range tests {
- config, err := NewCloudConfig(tt.contents)
- if err != nil {
- t.Errorf("bad error (test case #%d): want %v, got %s", i, nil, err)
- }
- if !reflect.DeepEqual(&tt.config, config) {
- t.Errorf("bad config (test case #%d): want %#v, got %#v", i, tt.config, config)
- }
- }
-}
-
-func TestIsZero(t *testing.T) {
- tests := []struct {
- c interface{}
-
- empty bool
- }{
- {struct{}{}, true},
- {struct{ a, b string }{}, true},
- {struct{ A, b string }{}, true},
- {struct{ A, B string }{}, true},
- {struct{ A string }{A: "hello"}, false},
- {struct{ A int }{}, true},
- {struct{ A int }{A: 1}, false},
- }
-
- for _, tt := range tests {
- if empty := IsZero(tt.c); tt.empty != empty {
- t.Errorf("bad result (%q): want %t, got %t", tt.c, tt.empty, empty)
- }
- }
-}
-
-func TestAssertStructValid(t *testing.T) {
- tests := []struct {
- c interface{}
-
- err error
- }{
- {struct{}{}, nil},
- {struct {
- A, b string `valid:"^1|2$"`
- }{}, nil},
- {struct {
- A, b string `valid:"^1|2$"`
- }{A: "1", b: "2"}, nil},
- {struct {
- A, b string `valid:"^1|2$"`
- }{A: "1", b: "hello"}, nil},
- {struct {
- A, b string `valid:"^1|2$"`
- }{A: "hello", b: "2"}, &ErrorValid{Value: "hello", Field: "A", Valid: "^1|2$"}},
- {struct {
- A, b int `valid:"^1|2$"`
- }{}, nil},
- {struct {
- A, b int `valid:"^1|2$"`
- }{A: 1, b: 2}, nil},
- {struct {
- A, b int `valid:"^1|2$"`
- }{A: 1, b: 9}, nil},
- {struct {
- A, b int `valid:"^1|2$"`
- }{A: 9, b: 2}, &ErrorValid{Value: "9", Field: "A", Valid: "^1|2$"}},
- }
-
- for _, tt := range tests {
- if err := AssertStructValid(tt.c); !reflect.DeepEqual(tt.err, err) {
- t.Errorf("bad result (%q): want %q, got %q", tt.c, tt.err, err)
- }
- }
-}
-
-func TestConfigCompile(t *testing.T) {
- tests := []interface{}{
- Etcd{},
- File{},
- Flannel{},
- Fleet{},
- Locksmith{},
- OEM{},
- Unit{},
- Update{},
- }
-
- for _, tt := range tests {
- ttt := reflect.TypeOf(tt)
- for i := 0; i < ttt.NumField(); i++ {
- ft := ttt.Field(i)
- if !isFieldExported(ft) {
- continue
- }
-
- if _, err := regexp.Compile(ft.Tag.Get("valid")); err != nil {
- t.Errorf("bad regexp(%s.%s): want %v, got %s", ttt.Name(), ft.Name, nil, err)
- }
- }
- }
-}
-
-func TestCloudConfigUnknownKeys(t *testing.T) {
- contents := `
-coreos:
- etcd:
- discovery: "https://discovery.etcd.io/827c73219eeb2fa5530027c37bf18877"
- coreos_unknown:
- foo: "bar"
-section_unknown:
- dunno:
- something
-bare_unknown:
- bar
-write_files:
- - content: fun
- path: /var/party
- file_unknown: nofun
-users:
- - name: fry
- passwd: somehash
- user_unknown: philip
-hostname:
- foo
-`
- cfg, err := NewCloudConfig(contents)
- if err != nil {
- t.Fatalf("error instantiating CloudConfig with unknown keys: %v", err)
- }
- if cfg.Hostname != "foo" {
- t.Fatalf("hostname not correctly set when invalid keys are present")
- }
- if cfg.CoreOS.Etcd.Discovery != "https://discovery.etcd.io/827c73219eeb2fa5530027c37bf18877" {
- t.Fatalf("etcd section not correctly set when invalid keys are present")
- }
- if len(cfg.WriteFiles) < 1 || cfg.WriteFiles[0].Content != "fun" || cfg.WriteFiles[0].Path != "/var/party" {
- t.Fatalf("write_files section not correctly set when invalid keys are present")
- }
- if len(cfg.Users) < 1 || cfg.Users[0].Name != "fry" || cfg.Users[0].PasswordHash != "somehash" {
- t.Fatalf("users section not correctly set when invalid keys are present")
- }
-}
-
-// Assert that the parsing of a cloud config file "generally works"
-func TestCloudConfigEmpty(t *testing.T) {
- cfg, err := NewCloudConfig("")
- if err != nil {
- t.Fatalf("Encountered unexpected error :%v", err)
- }
-
- keys := cfg.SSHAuthorizedKeys
- if len(keys) != 0 {
- t.Error("Parsed incorrect number of SSH keys")
- }
-
- if len(cfg.WriteFiles) != 0 {
- t.Error("Expected zero WriteFiles")
- }
-
- if cfg.Hostname != "" {
- t.Errorf("Expected hostname to be empty, got '%s'", cfg.Hostname)
- }
-}
-
-// Assert that the parsing of a cloud config file "generally works"
-func TestCloudConfig(t *testing.T) {
- contents := `
-coreos:
- etcd:
- discovery: "https://discovery.etcd.io/827c73219eeb2fa5530027c37bf18877"
- update:
- reboot_strategy: reboot
- units:
- - name: 50-eth0.network
- runtime: yes
- content: '[Match]
-
- Name=eth47
-
-
- [Network]
-
- Address=10.209.171.177/19
-
-'
- oem:
- id: rackspace
- name: Rackspace Cloud Servers
- version_id: 168.0.0
- home_url: https://www.rackspace.com/cloud/servers/
- bug_report_url: https://github.com/coreos/coreos-overlay
-ssh_authorized_keys:
- - foobar
- - foobaz
-write_files:
- - content: |
- penny
- elroy
- path: /etc/dogepack.conf
- permissions: '0644'
- owner: root:dogepack
-hostname: trontastic
-`
- cfg, err := NewCloudConfig(contents)
- if err != nil {
- t.Fatalf("Encountered unexpected error :%v", err)
- }
-
- keys := cfg.SSHAuthorizedKeys
- if len(keys) != 2 {
- t.Error("Parsed incorrect number of SSH keys")
- } else if keys[0] != "foobar" {
- t.Error("Expected first SSH key to be 'foobar'")
- } else if keys[1] != "foobaz" {
- t.Error("Expected first SSH key to be 'foobaz'")
- }
-
- if len(cfg.WriteFiles) != 1 {
- t.Error("Failed to parse correct number of write_files")
- } else {
- wf := cfg.WriteFiles[0]
- if wf.Content != "penny\nelroy\n" {
- t.Errorf("WriteFile has incorrect contents '%s'", wf.Content)
- }
- if wf.Encoding != "" {
- t.Errorf("WriteFile has incorrect encoding %s", wf.Encoding)
- }
- if wf.RawFilePermissions != "0644" {
- t.Errorf("WriteFile has incorrect permissions %s", wf.RawFilePermissions)
- }
- if wf.Path != "/etc/dogepack.conf" {
- t.Errorf("WriteFile has incorrect path %s", wf.Path)
- }
- if wf.Owner != "root:dogepack" {
- t.Errorf("WriteFile has incorrect owner %s", wf.Owner)
- }
- }
-
- if len(cfg.CoreOS.Units) != 1 {
- t.Error("Failed to parse correct number of units")
- } else {
- u := cfg.CoreOS.Units[0]
- expect := `[Match]
-Name=eth47
-
-[Network]
-Address=10.209.171.177/19
-`
- if u.Content != expect {
- t.Errorf("Unit has incorrect contents '%s'.\nExpected '%s'.", u.Content, expect)
- }
- if u.Runtime != true {
- t.Errorf("Unit has incorrect runtime value")
- }
- if u.Name != "50-eth0.network" {
- t.Errorf("Unit has incorrect name %s", u.Name)
- }
- }
-
- if cfg.CoreOS.OEM.ID != "rackspace" {
- t.Errorf("Failed parsing coreos.oem. Expected ID 'rackspace', got %q.", cfg.CoreOS.OEM.ID)
- }
-
- if cfg.Hostname != "trontastic" {
- t.Errorf("Failed to parse hostname")
- }
- if cfg.CoreOS.Update.RebootStrategy != "reboot" {
- t.Errorf("Failed to parse locksmith strategy")
- }
-}
-
-// Assert that our interface conversion doesn't panic
-func TestCloudConfigKeysNotList(t *testing.T) {
- contents := `
-ssh_authorized_keys:
- - foo: bar
-`
- cfg, err := NewCloudConfig(contents)
- if err != nil {
- t.Fatalf("Encountered unexpected error: %v", err)
- }
-
- keys := cfg.SSHAuthorizedKeys
- if len(keys) != 0 {
- t.Error("Parsed incorrect number of SSH keys")
- }
-}
-
-func TestCloudConfigSerializationHeader(t *testing.T) {
- cfg, _ := NewCloudConfig("")
- contents := cfg.String()
- header := strings.SplitN(contents, "\n", 2)[0]
- if header != "#cloud-config" {
- t.Fatalf("Serialized config did not have expected header")
- }
-}
-
-func TestCloudConfigUsers(t *testing.T) {
- contents := `
-users:
- - name: elroy
- passwd: somehash
- ssh_authorized_keys:
- - somekey
- gecos: arbitrary comment
- homedir: /home/place
- no_create_home: yes
- primary_group: things
- groups:
- - ping
- - pong
- no_user_group: true
- system: y
- no_log_init: True
- shell: /bin/sh
-`
- cfg, err := NewCloudConfig(contents)
- if err != nil {
- t.Fatalf("Encountered unexpected error: %v", err)
- }
-
- if len(cfg.Users) != 1 {
- t.Fatalf("Parsed %d users, expected 1", len(cfg.Users))
- }
-
- user := cfg.Users[0]
-
- if user.Name != "elroy" {
- t.Errorf("User name is %q, expected 'elroy'", user.Name)
- }
-
- if user.PasswordHash != "somehash" {
- t.Errorf("User passwd is %q, expected 'somehash'", user.PasswordHash)
- }
-
- if keys := user.SSHAuthorizedKeys; len(keys) != 1 {
- t.Errorf("Parsed %d ssh keys, expected 1", len(keys))
- } else {
- key := user.SSHAuthorizedKeys[0]
- if key != "somekey" {
- t.Errorf("User SSH key is %q, expected 'somekey'", key)
- }
- }
-
- if user.GECOS != "arbitrary comment" {
- t.Errorf("Failed to parse gecos field, got %q", user.GECOS)
- }
-
- if user.Homedir != "/home/place" {
- t.Errorf("Failed to parse homedir field, got %q", user.Homedir)
- }
-
- if !user.NoCreateHome {
- t.Errorf("Failed to parse no_create_home field")
- }
-
- if user.PrimaryGroup != "things" {
- t.Errorf("Failed to parse primary_group field, got %q", user.PrimaryGroup)
- }
-
- if len(user.Groups) != 2 {
- t.Errorf("Failed to parse 2 goups, got %d", len(user.Groups))
- } else {
- if user.Groups[0] != "ping" {
- t.Errorf("First group was %q, not expected value 'ping'", user.Groups[0])
- }
- if user.Groups[1] != "pong" {
- t.Errorf("First group was %q, not expected value 'pong'", user.Groups[1])
- }
- }
-
- if !user.NoUserGroup {
- t.Errorf("Failed to parse no_user_group field")
- }
-
- if !user.System {
- t.Errorf("Failed to parse system field")
- }
-
- if !user.NoLogInit {
- t.Errorf("Failed to parse no_log_init field")
- }
-
- if user.Shell != "/bin/sh" {
- t.Errorf("Failed to parse shell field, got %q", user.Shell)
- }
-}
-
-func TestCloudConfigUsersGithubUser(t *testing.T) {
-
- contents := `
-users:
- - name: elroy
- coreos_ssh_import_github: bcwaldon
-`
- cfg, err := NewCloudConfig(contents)
- if err != nil {
- t.Fatalf("Encountered unexpected error: %v", err)
- }
-
- if len(cfg.Users) != 1 {
- t.Fatalf("Parsed %d users, expected 1", len(cfg.Users))
- }
-
- user := cfg.Users[0]
-
- if user.Name != "elroy" {
- t.Errorf("User name is %q, expected 'elroy'", user.Name)
- }
-
- if user.SSHImportGithubUser != "bcwaldon" {
- t.Errorf("github user is %q, expected 'bcwaldon'", user.SSHImportGithubUser)
- }
-}
-
-func TestCloudConfigUsersSSHImportURL(t *testing.T) {
- contents := `
-users:
- - name: elroy
- coreos_ssh_import_url: https://token:x-auth-token@github.enterprise.com/api/v3/polvi/keys
-`
- cfg, err := NewCloudConfig(contents)
- if err != nil {
- t.Fatalf("Encountered unexpected error: %v", err)
- }
-
- if len(cfg.Users) != 1 {
- t.Fatalf("Parsed %d users, expected 1", len(cfg.Users))
- }
-
- user := cfg.Users[0]
-
- if user.Name != "elroy" {
- t.Errorf("User name is %q, expected 'elroy'", user.Name)
- }
-
- if user.SSHImportURL != "https://token:x-auth-token@github.enterprise.com/api/v3/polvi/keys" {
- t.Errorf("ssh import url is %q, expected 'https://token:x-auth-token@github.enterprise.com/api/v3/polvi/keys'", user.SSHImportURL)
- }
-}
diff --git a/vendor/github.com/coreos/coreos-cloudinit/config/file_test.go b/vendor/github.com/coreos/coreos-cloudinit/config/file_test.go
deleted file mode 100644
index 60a8efe2..00000000
--- a/vendor/github.com/coreos/coreos-cloudinit/config/file_test.go
+++ /dev/null
@@ -1,69 +0,0 @@
-// Copyright 2015 CoreOS, Inc.
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-package config
-
-import (
- "testing"
-)
-
-func TestEncodingValid(t *testing.T) {
- tests := []struct {
- value string
-
- isValid bool
- }{
- {value: "base64", isValid: true},
- {value: "b64", isValid: true},
- {value: "gz", isValid: true},
- {value: "gzip", isValid: true},
- {value: "gz+base64", isValid: true},
- {value: "gzip+base64", isValid: true},
- {value: "gz+b64", isValid: true},
- {value: "gzip+b64", isValid: true},
- {value: "gzzzzbase64", isValid: false},
- {value: "gzipppbase64", isValid: false},
- {value: "unknown", isValid: false},
- }
-
- for _, tt := range tests {
- isValid := (nil == AssertStructValid(File{Encoding: tt.value}))
- if tt.isValid != isValid {
- t.Errorf("bad assert (%s): want %t, got %t", tt.value, tt.isValid, isValid)
- }
- }
-}
-
-func TestRawFilePermissionsValid(t *testing.T) {
- tests := []struct {
- value string
-
- isValid bool
- }{
- {value: "744", isValid: true},
- {value: "0744", isValid: true},
- {value: "1744", isValid: true},
- {value: "01744", isValid: true},
- {value: "11744", isValid: false},
- {value: "rwxr--r--", isValid: false},
- {value: "800", isValid: false},
- }
-
- for _, tt := range tests {
- isValid := (nil == AssertStructValid(File{RawFilePermissions: tt.value}))
- if tt.isValid != isValid {
- t.Errorf("bad assert (%s): want %t, got %t", tt.value, tt.isValid, isValid)
- }
- }
-}
diff --git a/vendor/github.com/coreos/coreos-cloudinit/config/locksmith_test.go b/vendor/github.com/coreos/coreos-cloudinit/config/locksmith_test.go
deleted file mode 100644
index a8c4eb57..00000000
--- a/vendor/github.com/coreos/coreos-cloudinit/config/locksmith_test.go
+++ /dev/null
@@ -1,76 +0,0 @@
-// Copyright 2015 CoreOS, Inc.
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-package config
-
-import (
- "testing"
-)
-
-func TestRebootWindowStart(t *testing.T) {
- tests := []struct {
- value string
-
- isValid bool
- }{
- {value: "Sun 0:0", isValid: true},
- {value: "Sun 00:00", isValid: true},
- {value: "sUn 23:59", isValid: true},
- {value: "mon 0:0", isValid: true},
- {value: "tue 0:0", isValid: true},
- {value: "tues 0:0", isValid: false},
- {value: "wed 0:0", isValid: true},
- {value: "thu 0:0", isValid: true},
- {value: "thur 0:0", isValid: false},
- {value: "fri 0:0", isValid: true},
- {value: "sat 0:0", isValid: true},
- {value: "sat00:00", isValid: false},
- {value: "00:00", isValid: true},
- {value: "10:10", isValid: true},
- {value: "20:20", isValid: true},
- {value: "20:30", isValid: true},
- {value: "20:40", isValid: true},
- {value: "20:50", isValid: true},
- {value: "20:60", isValid: false},
- {value: "24:00", isValid: false},
- }
-
- for _, tt := range tests {
- isValid := (nil == AssertStructValid(Locksmith{RebootWindowStart: tt.value}))
- if tt.isValid != isValid {
- t.Errorf("bad assert (%s): want %t, got %t", tt.value, tt.isValid, isValid)
- }
- }
-}
-
-func TestRebootWindowLength(t *testing.T) {
- tests := []struct {
- value string
-
- isValid bool
- }{
- {value: "1h", isValid: true},
- {value: "1d", isValid: true},
- {value: "0d", isValid: true},
- {value: "0.5h", isValid: true},
- {value: "0.5.0h", isValid: false},
- }
-
- for _, tt := range tests {
- isValid := (nil == AssertStructValid(Locksmith{RebootWindowLength: tt.value}))
- if tt.isValid != isValid {
- t.Errorf("bad assert (%s): want %t, got %t", tt.value, tt.isValid, isValid)
- }
- }
-}
diff --git a/vendor/github.com/coreos/coreos-cloudinit/config/unit_test.go b/vendor/github.com/coreos/coreos-cloudinit/config/unit_test.go
deleted file mode 100644
index d94dd8ba..00000000
--- a/vendor/github.com/coreos/coreos-cloudinit/config/unit_test.go
+++ /dev/null
@@ -1,46 +0,0 @@
-/*
- Copyright 2014 CoreOS, Inc.
-
- Licensed under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License.
- You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
-*/
-
-package config
-
-import (
- "testing"
-)
-
-func TestCommandValid(t *testing.T) {
- tests := []struct {
- value string
-
- isValid bool
- }{
- {value: "start", isValid: true},
- {value: "stop", isValid: true},
- {value: "restart", isValid: true},
- {value: "reload", isValid: true},
- {value: "try-restart", isValid: true},
- {value: "reload-or-restart", isValid: true},
- {value: "reload-or-try-restart", isValid: true},
- {value: "tryrestart", isValid: false},
- {value: "unknown", isValid: false},
- }
-
- for _, tt := range tests {
- isValid := (nil == AssertStructValid(Unit{Command: tt.value}))
- if tt.isValid != isValid {
- t.Errorf("bad assert (%s): want %t, got %t", tt.value, tt.isValid, isValid)
- }
- }
-}
diff --git a/vendor/github.com/coreos/coreos-cloudinit/config/update_test.go b/vendor/github.com/coreos/coreos-cloudinit/config/update_test.go
deleted file mode 100644
index 2b0851eb..00000000
--- a/vendor/github.com/coreos/coreos-cloudinit/config/update_test.go
+++ /dev/null
@@ -1,43 +0,0 @@
-/*
- Copyright 2014 CoreOS, Inc.
-
- Licensed under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License.
- You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
-*/
-
-package config
-
-import (
- "testing"
-)
-
-func TestRebootStrategyValid(t *testing.T) {
- tests := []struct {
- value string
-
- isValid bool
- }{
- {value: "best-effort", isValid: true},
- {value: "etcd-lock", isValid: true},
- {value: "reboot", isValid: true},
- {value: "off", isValid: true},
- {value: "besteffort", isValid: false},
- {value: "unknown", isValid: false},
- }
-
- for _, tt := range tests {
- isValid := (nil == AssertStructValid(Update{RebootStrategy: tt.value}))
- if tt.isValid != isValid {
- t.Errorf("bad assert (%s): want %t, got %t", tt.value, tt.isValid, isValid)
- }
- }
-}
diff --git a/vendor/github.com/coreos/coreos-cloudinit/coreos-cloudinit.go b/vendor/github.com/coreos/coreos-cloudinit/coreos-cloudinit.go
deleted file mode 100644
index d82a72dd..00000000
--- a/vendor/github.com/coreos/coreos-cloudinit/coreos-cloudinit.go
+++ /dev/null
@@ -1,423 +0,0 @@
-// Copyright 2015 CoreOS, Inc.
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-package main
-
-import (
- "bytes"
- "compress/gzip"
- "flag"
- "fmt"
- "io/ioutil"
- "log"
- "os"
- "runtime"
- "sync"
- "time"
-
- "github.com/coreos/coreos-cloudinit/config"
- "github.com/coreos/coreos-cloudinit/config/validate"
- "github.com/coreos/coreos-cloudinit/datasource"
- "github.com/coreos/coreos-cloudinit/datasource/configdrive"
- "github.com/coreos/coreos-cloudinit/datasource/file"
- "github.com/coreos/coreos-cloudinit/datasource/metadata/cloudsigma"
- "github.com/coreos/coreos-cloudinit/datasource/metadata/digitalocean"
- "github.com/coreos/coreos-cloudinit/datasource/metadata/ec2"
- "github.com/coreos/coreos-cloudinit/datasource/metadata/packet"
- "github.com/coreos/coreos-cloudinit/datasource/proc_cmdline"
- "github.com/coreos/coreos-cloudinit/datasource/url"
- "github.com/coreos/coreos-cloudinit/datasource/vmware"
- "github.com/coreos/coreos-cloudinit/datasource/waagent"
- "github.com/coreos/coreos-cloudinit/initialize"
- "github.com/coreos/coreos-cloudinit/network"
- "github.com/coreos/coreos-cloudinit/pkg"
- "github.com/coreos/coreos-cloudinit/system"
-)
-
-const (
- datasourceInterval = 100 * time.Millisecond
- datasourceMaxInterval = 30 * time.Second
- datasourceTimeout = 5 * time.Minute
-)
-
-var (
- flags = struct {
- printVersion bool
- ignoreFailure bool
- sources struct {
- file string
- configDrive string
- waagent string
- metadataService bool
- ec2MetadataService string
- cloudSigmaMetadataService bool
- digitalOceanMetadataService string
- packetMetadataService string
- url string
- procCmdLine bool
- vmware bool
- }
- convertNetconf string
- workspace string
- sshKeyName string
- oem string
- validate bool
- }{}
- version = "was not built properly"
-)
-
-func init() {
- flag.BoolVar(&flags.printVersion, "version", false, "Print the version and exit")
- flag.BoolVar(&flags.ignoreFailure, "ignore-failure", false, "Exits with 0 status in the event of malformed input from user-data")
- flag.StringVar(&flags.sources.file, "from-file", "", "Read user-data from provided file")
- flag.StringVar(&flags.sources.configDrive, "from-configdrive", "", "Read data from provided cloud-drive directory")
- flag.StringVar(&flags.sources.waagent, "from-waagent", "", "Read data from provided waagent directory")
- flag.BoolVar(&flags.sources.metadataService, "from-metadata-service", false, "[DEPRECATED - Use -from-ec2-metadata] Download data from metadata service")
- flag.StringVar(&flags.sources.ec2MetadataService, "from-ec2-metadata", "", "Download EC2 data from the provided url")
- flag.BoolVar(&flags.sources.cloudSigmaMetadataService, "from-cloudsigma-metadata", false, "Download data from CloudSigma server context")
- flag.StringVar(&flags.sources.digitalOceanMetadataService, "from-digitalocean-metadata", "", "Download DigitalOcean data from the provided url")
- flag.StringVar(&flags.sources.packetMetadataService, "from-packet-metadata", "", "Download Packet data from metadata service")
- flag.StringVar(&flags.sources.url, "from-url", "", "Download user-data from provided url")
- flag.BoolVar(&flags.sources.procCmdLine, "from-proc-cmdline", false, fmt.Sprintf("Parse %s for '%s=', using the cloud-config served by an HTTP GET to ", proc_cmdline.ProcCmdlineLocation, proc_cmdline.ProcCmdlineCloudConfigFlag))
- flag.BoolVar(&flags.sources.vmware, "from-vmware-guestinfo", false, "Read data from VMware guestinfo")
- flag.StringVar(&flags.oem, "oem", "", "Use the settings specific to the provided OEM")
- flag.StringVar(&flags.convertNetconf, "convert-netconf", "", "Read the network config provided in cloud-drive and translate it from the specified format into networkd unit files")
- flag.StringVar(&flags.workspace, "workspace", "/var/lib/coreos-cloudinit", "Base directory coreos-cloudinit should use to store data")
- flag.StringVar(&flags.sshKeyName, "ssh-key-name", initialize.DefaultSSHKeyName, "Add SSH keys to the system with the given name")
- flag.BoolVar(&flags.validate, "validate", false, "[EXPERIMENTAL] Validate the user-data but do not apply it to the system")
-}
-
-type oemConfig map[string]string
-
-var (
- oemConfigs = map[string]oemConfig{
- "digitalocean": oemConfig{
- "from-digitalocean-metadata": "http://169.254.169.254/",
- "convert-netconf": "digitalocean",
- },
- "ec2-compat": oemConfig{
- "from-ec2-metadata": "http://169.254.169.254/",
- "from-configdrive": "/media/configdrive",
- },
- "rackspace-onmetal": oemConfig{
- "from-configdrive": "/media/configdrive",
- "convert-netconf": "debian",
- },
- "azure": oemConfig{
- "from-waagent": "/var/lib/waagent",
- },
- "cloudsigma": oemConfig{
- "from-cloudsigma-metadata": "true",
- },
- "packet": oemConfig{
- "from-packet-metadata": "https://metadata.packet.net/",
- },
- "vmware": oemConfig{
- "from-vmware-guestinfo": "true",
- "convert-netconf": "vmware",
- },
- }
-)
-
-func main() {
- failure := false
-
- // Conservative Go 1.5 upgrade strategy:
- // keep GOMAXPROCS' default at 1 for now.
- if os.Getenv("GOMAXPROCS") == "" {
- runtime.GOMAXPROCS(1)
- }
-
- flag.Parse()
-
- if c, ok := oemConfigs[flags.oem]; ok {
- for k, v := range c {
- flag.Set(k, v)
- }
- } else if flags.oem != "" {
- oems := make([]string, 0, len(oemConfigs))
- for k := range oemConfigs {
- oems = append(oems, k)
- }
- fmt.Printf("Invalid option to -oem: %q. Supported options: %q\n", flags.oem, oems)
- os.Exit(2)
- }
-
- if flags.printVersion == true {
- fmt.Printf("coreos-cloudinit %s\n", version)
- os.Exit(0)
- }
-
- switch flags.convertNetconf {
- case "":
- case "debian":
- case "digitalocean":
- case "packet":
- case "vmware":
- default:
- fmt.Printf("Invalid option to -convert-netconf: '%s'. Supported options: 'debian, digitalocean, packet, vmware'\n", flags.convertNetconf)
- os.Exit(2)
- }
-
- dss := getDatasources()
- if len(dss) == 0 {
- fmt.Println("Provide at least one of --from-file, --from-configdrive, --from-ec2-metadata, --from-cloudsigma-metadata, --from-packet-metadata, --from-digitalocean-metadata, --from-vmware-guestinfo, --from-waagent, --from-url or --from-proc-cmdline")
- os.Exit(2)
- }
-
- ds := selectDatasource(dss)
- if ds == nil {
- log.Println("No datasources available in time")
- os.Exit(1)
- }
-
- log.Printf("Fetching user-data from datasource of type %q\n", ds.Type())
- userdataBytes, err := ds.FetchUserdata()
- if err != nil {
- log.Printf("Failed fetching user-data from datasource: %v. Continuing...\n", err)
- failure = true
- }
- userdataBytes, err = decompressIfGzip(userdataBytes)
- if err != nil {
- log.Printf("Failed decompressing user-data from datasource: %v. Continuing...\n", err)
- failure = true
- }
-
- if report, err := validate.Validate(userdataBytes); err == nil {
- ret := 0
- for _, e := range report.Entries() {
- log.Println(e)
- ret = 1
- }
- if flags.validate {
- os.Exit(ret)
- }
- } else {
- log.Printf("Failed while validating user_data (%q)\n", err)
- if flags.validate {
- os.Exit(1)
- }
- }
-
- log.Printf("Fetching meta-data from datasource of type %q\n", ds.Type())
- metadata, err := ds.FetchMetadata()
- if err != nil {
- log.Printf("Failed fetching meta-data from datasource: %v\n", err)
- os.Exit(1)
- }
-
- // Apply environment to user-data
- env := initialize.NewEnvironment("/", ds.ConfigRoot(), flags.workspace, flags.sshKeyName, metadata)
- userdata := env.Apply(string(userdataBytes))
-
- var ccu *config.CloudConfig
- var script *config.Script
- switch ud, err := initialize.ParseUserData(userdata); err {
- case initialize.ErrIgnitionConfig:
- fmt.Printf("Detected an Ignition config. Exiting...")
- os.Exit(0)
- case nil:
- switch t := ud.(type) {
- case *config.CloudConfig:
- ccu = t
- case *config.Script:
- script = t
- }
- default:
- fmt.Printf("Failed to parse user-data: %v\nContinuing...\n", err)
- failure = true
- }
-
- log.Println("Merging cloud-config from meta-data and user-data")
- cc := mergeConfigs(ccu, metadata)
-
- var ifaces []network.InterfaceGenerator
- if flags.convertNetconf != "" {
- var err error
- switch flags.convertNetconf {
- case "debian":
- ifaces, err = network.ProcessDebianNetconf(metadata.NetworkConfig.([]byte))
- case "digitalocean":
- ifaces, err = network.ProcessDigitalOceanNetconf(metadata.NetworkConfig.(digitalocean.Metadata))
- case "packet":
- ifaces, err = network.ProcessPacketNetconf(metadata.NetworkConfig.(packet.NetworkData))
- case "vmware":
- ifaces, err = network.ProcessVMwareNetconf(metadata.NetworkConfig.(map[string]string))
- default:
- err = fmt.Errorf("Unsupported network config format %q", flags.convertNetconf)
- }
- if err != nil {
- log.Printf("Failed to generate interfaces: %v\n", err)
- os.Exit(1)
- }
- }
-
- if err = initialize.Apply(cc, ifaces, env); err != nil {
- log.Printf("Failed to apply cloud-config: %v\n", err)
- os.Exit(1)
- }
-
- if script != nil {
- if err = runScript(*script, env); err != nil {
- log.Printf("Failed to run script: %v\n", err)
- os.Exit(1)
- }
- }
-
- if failure && !flags.ignoreFailure {
- os.Exit(1)
- }
-}
-
-// mergeConfigs merges certain options from md (meta-data from the datasource)
-// onto cc (a CloudConfig derived from user-data), if they are not already set
-// on cc (i.e. user-data always takes precedence)
-func mergeConfigs(cc *config.CloudConfig, md datasource.Metadata) (out config.CloudConfig) {
- if cc != nil {
- out = *cc
- }
-
- if md.Hostname != "" {
- if out.Hostname != "" {
- log.Printf("Warning: user-data hostname (%s) overrides metadata hostname (%s)\n", out.Hostname, md.Hostname)
- } else {
- out.Hostname = md.Hostname
- }
- }
- for _, key := range md.SSHPublicKeys {
- out.SSHAuthorizedKeys = append(out.SSHAuthorizedKeys, key)
- }
- return
-}
-
-// getDatasources creates a slice of possible Datasources for cloudinit based
-// on the different source command-line flags.
-func getDatasources() []datasource.Datasource {
- dss := make([]datasource.Datasource, 0, 5)
- if flags.sources.file != "" {
- dss = append(dss, file.NewDatasource(flags.sources.file))
- }
- if flags.sources.url != "" {
- dss = append(dss, url.NewDatasource(flags.sources.url))
- }
- if flags.sources.configDrive != "" {
- dss = append(dss, configdrive.NewDatasource(flags.sources.configDrive))
- }
- if flags.sources.metadataService {
- dss = append(dss, ec2.NewDatasource(ec2.DefaultAddress))
- }
- if flags.sources.ec2MetadataService != "" {
- dss = append(dss, ec2.NewDatasource(flags.sources.ec2MetadataService))
- }
- if flags.sources.cloudSigmaMetadataService {
- dss = append(dss, cloudsigma.NewServerContextService())
- }
- if flags.sources.digitalOceanMetadataService != "" {
- dss = append(dss, digitalocean.NewDatasource(flags.sources.digitalOceanMetadataService))
- }
- if flags.sources.waagent != "" {
- dss = append(dss, waagent.NewDatasource(flags.sources.waagent))
- }
- if flags.sources.packetMetadataService != "" {
- dss = append(dss, packet.NewDatasource(flags.sources.packetMetadataService))
- }
- if flags.sources.procCmdLine {
- dss = append(dss, proc_cmdline.NewDatasource())
- }
- if flags.sources.vmware {
- dss = append(dss, vmware.NewDatasource())
- }
- return dss
-}
-
-// selectDatasource attempts to choose a valid Datasource to use based on its
-// current availability. The first Datasource to report to be available is
-// returned. Datasources will be retried if possible if they are not
-// immediately available. If all Datasources are permanently unavailable or
-// datasourceTimeout is reached before one becomes available, nil is returned.
-func selectDatasource(sources []datasource.Datasource) datasource.Datasource {
- ds := make(chan datasource.Datasource)
- stop := make(chan struct{})
- var wg sync.WaitGroup
-
- for _, s := range sources {
- wg.Add(1)
- go func(s datasource.Datasource) {
- defer wg.Done()
-
- duration := datasourceInterval
- for {
- log.Printf("Checking availability of %q\n", s.Type())
- if s.IsAvailable() {
- ds <- s
- return
- } else if !s.AvailabilityChanges() {
- return
- }
- select {
- case <-stop:
- return
- case <-time.After(duration):
- duration = pkg.ExpBackoff(duration, datasourceMaxInterval)
- }
- }
- }(s)
- }
-
- done := make(chan struct{})
- go func() {
- wg.Wait()
- close(done)
- }()
-
- var s datasource.Datasource
- select {
- case s = <-ds:
- case <-done:
- case <-time.After(datasourceTimeout):
- }
-
- close(stop)
- return s
-}
-
-// TODO(jonboulle): this should probably be refactored and moved into a different module
-func runScript(script config.Script, env *initialize.Environment) error {
- err := initialize.PrepWorkspace(env.Workspace())
- if err != nil {
- log.Printf("Failed preparing workspace: %v\n", err)
- return err
- }
- path, err := initialize.PersistScriptInWorkspace(script, env.Workspace())
- if err == nil {
- var name string
- name, err = system.ExecuteScript(path)
- initialize.PersistUnitNameInWorkspace(name, env.Workspace())
- }
- return err
-}
-
-const gzipMagicBytes = "\x1f\x8b"
-
-func decompressIfGzip(userdataBytes []byte) ([]byte, error) {
- if !bytes.HasPrefix(userdataBytes, []byte(gzipMagicBytes)) {
- return userdataBytes, nil
- }
- gzr, err := gzip.NewReader(bytes.NewReader(userdataBytes))
- if err != nil {
- return nil, err
- }
- defer gzr.Close()
- return ioutil.ReadAll(gzr)
-}
diff --git a/vendor/github.com/coreos/coreos-cloudinit/coreos-cloudinit_test.go b/vendor/github.com/coreos/coreos-cloudinit/coreos-cloudinit_test.go
deleted file mode 100644
index cd5c6da4..00000000
--- a/vendor/github.com/coreos/coreos-cloudinit/coreos-cloudinit_test.go
+++ /dev/null
@@ -1,147 +0,0 @@
-// Copyright 2015 CoreOS, Inc.
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-package main
-
-import (
- "bytes"
- "encoding/base64"
- "errors"
- "reflect"
- "testing"
-
- "github.com/coreos/coreos-cloudinit/config"
- "github.com/coreos/coreos-cloudinit/datasource"
-)
-
-func TestMergeConfigs(t *testing.T) {
- tests := []struct {
- cc *config.CloudConfig
- md datasource.Metadata
-
- out config.CloudConfig
- }{
- {
- // If md is empty and cc is nil, result should be empty
- out: config.CloudConfig{},
- },
- {
- // If md and cc are empty, result should be empty
- cc: &config.CloudConfig{},
- out: config.CloudConfig{},
- },
- {
- // If cc is empty, cc should be returned unchanged
- cc: &config.CloudConfig{SSHAuthorizedKeys: []string{"abc", "def"}, Hostname: "cc-host"},
- out: config.CloudConfig{SSHAuthorizedKeys: []string{"abc", "def"}, Hostname: "cc-host"},
- },
- {
- // If cc is empty, cc should be returned unchanged(overridden)
- cc: &config.CloudConfig{},
- md: datasource.Metadata{Hostname: "md-host", SSHPublicKeys: map[string]string{"key": "ghi"}},
- out: config.CloudConfig{SSHAuthorizedKeys: []string{"ghi"}, Hostname: "md-host"},
- },
- {
- // If cc is nil, cc should be returned unchanged(overridden)
- md: datasource.Metadata{Hostname: "md-host", SSHPublicKeys: map[string]string{"key": "ghi"}},
- out: config.CloudConfig{SSHAuthorizedKeys: []string{"ghi"}, Hostname: "md-host"},
- },
- {
- // user-data should override completely in the case of conflicts
- cc: &config.CloudConfig{SSHAuthorizedKeys: []string{"abc", "def"}, Hostname: "cc-host"},
- md: datasource.Metadata{Hostname: "md-host"},
- out: config.CloudConfig{SSHAuthorizedKeys: []string{"abc", "def"}, Hostname: "cc-host"},
- },
- {
- // Mixed merge should succeed
- cc: &config.CloudConfig{SSHAuthorizedKeys: []string{"abc", "def"}, Hostname: "cc-host"},
- md: datasource.Metadata{Hostname: "md-host", SSHPublicKeys: map[string]string{"key": "ghi"}},
- out: config.CloudConfig{SSHAuthorizedKeys: []string{"abc", "def", "ghi"}, Hostname: "cc-host"},
- },
- {
- // Completely non-conflicting merge should be fine
- cc: &config.CloudConfig{Hostname: "cc-host"},
- md: datasource.Metadata{SSHPublicKeys: map[string]string{"zaphod": "beeblebrox"}},
- out: config.CloudConfig{Hostname: "cc-host", SSHAuthorizedKeys: []string{"beeblebrox"}},
- },
- {
- // Non-mergeable settings in user-data should not be affected
- cc: &config.CloudConfig{Hostname: "cc-host", ManageEtcHosts: config.EtcHosts("lolz")},
- md: datasource.Metadata{Hostname: "md-host"},
- out: config.CloudConfig{Hostname: "cc-host", ManageEtcHosts: config.EtcHosts("lolz")},
- },
- }
-
- for i, tt := range tests {
- out := mergeConfigs(tt.cc, tt.md)
- if !reflect.DeepEqual(tt.out, out) {
- t.Errorf("bad config (%d): want %#v, got %#v", i, tt.out, out)
- }
- }
-}
-
-func mustDecode(in string) []byte {
- out, err := base64.StdEncoding.DecodeString(in)
- if err != nil {
- panic(err)
- }
- return out
-}
-
-func TestDecompressIfGzip(t *testing.T) {
- tests := []struct {
- in []byte
-
- out []byte
- err error
- }{
- {
- in: nil,
-
- out: nil,
- err: nil,
- },
- {
- in: []byte{},
-
- out: []byte{},
- err: nil,
- },
- {
- in: mustDecode("H4sIAJWV/VUAA1NOzskvTdFNzs9Ly0wHABt6mQENAAAA"),
-
- out: []byte("#cloud-config"),
- err: nil,
- },
- {
- in: []byte("#cloud-config"),
-
- out: []byte("#cloud-config"),
- err: nil,
- },
- {
- in: mustDecode("H4sCORRUPT=="),
-
- out: nil,
- err: errors.New("any error"),
- },
- }
- for i, tt := range tests {
- out, err := decompressIfGzip(tt.in)
- if !bytes.Equal(out, tt.out) || (tt.err != nil && err == nil) {
- t.Errorf("bad gzip (%d): want (%s, %#v), got (%s, %#v)", i, string(tt.out), tt.err, string(out), err)
- }
- }
-
-}
diff --git a/vendor/github.com/coreos/coreos-cloudinit/datasource/configdrive/configdrive_test.go b/vendor/github.com/coreos/coreos-cloudinit/datasource/configdrive/configdrive_test.go
deleted file mode 100644
index e40a8fd5..00000000
--- a/vendor/github.com/coreos/coreos-cloudinit/datasource/configdrive/configdrive_test.go
+++ /dev/null
@@ -1,145 +0,0 @@
-// Copyright 2015 CoreOS, Inc.
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-package configdrive
-
-import (
- "reflect"
- "testing"
-
- "github.com/coreos/coreos-cloudinit/datasource"
- "github.com/coreos/coreos-cloudinit/datasource/test"
-)
-
-func TestFetchMetadata(t *testing.T) {
- for _, tt := range []struct {
- root string
- files test.MockFilesystem
-
- metadata datasource.Metadata
- }{
- {
- root: "/",
- files: test.NewMockFilesystem(test.File{Path: "/openstack/latest/meta_data.json", Contents: ""}),
- },
- {
- root: "/",
- files: test.NewMockFilesystem(test.File{Path: "/openstack/latest/meta_data.json", Contents: `{"ignore": "me"}`}),
- },
- {
- root: "/",
- files: test.NewMockFilesystem(test.File{Path: "/openstack/latest/meta_data.json", Contents: `{"hostname": "host"}`}),
- metadata: datasource.Metadata{Hostname: "host"},
- },
- {
- root: "/media/configdrive",
- files: test.NewMockFilesystem(test.File{Path: "/media/configdrive/openstack/latest/meta_data.json", Contents: `{"hostname": "host", "network_config": {"content_path": "config_file.json"}, "public_keys":{"1": "key1", "2": "key2"}}`},
- test.File{Path: "/media/configdrive/openstack/config_file.json", Contents: "make it work"},
- ),
- metadata: datasource.Metadata{
- Hostname: "host",
- NetworkConfig: []byte("make it work"),
- SSHPublicKeys: map[string]string{
- "1": "key1",
- "2": "key2",
- },
- },
- },
- } {
- cd := configDrive{tt.root, tt.files.ReadFile}
- metadata, err := cd.FetchMetadata()
- if err != nil {
- t.Fatalf("bad error for %+v: want %v, got %q", tt, nil, err)
- }
- if !reflect.DeepEqual(tt.metadata, metadata) {
- t.Fatalf("bad metadata for %+v: want %#v, got %#v", tt, tt.metadata, metadata)
- }
- }
-}
-
-func TestFetchUserdata(t *testing.T) {
- for _, tt := range []struct {
- root string
- files test.MockFilesystem
-
- userdata string
- }{
- {
- "/",
- test.NewMockFilesystem(),
- "",
- },
- {
- "/",
- test.NewMockFilesystem(test.File{Path: "/openstack/latest/user_data", Contents: "userdata"}),
- "userdata",
- },
- {
- "/media/configdrive",
- test.NewMockFilesystem(test.File{Path: "/media/configdrive/openstack/latest/user_data", Contents: "userdata"}),
- "userdata",
- },
- } {
- cd := configDrive{tt.root, tt.files.ReadFile}
- userdata, err := cd.FetchUserdata()
- if err != nil {
- t.Fatalf("bad error for %+v: want %v, got %q", tt, nil, err)
- }
- if string(userdata) != tt.userdata {
- t.Fatalf("bad userdata for %+v: want %q, got %q", tt, tt.userdata, userdata)
- }
- }
-}
-
-func TestConfigRoot(t *testing.T) {
- for _, tt := range []struct {
- root string
- configRoot string
- }{
- {
- "/",
- "/openstack",
- },
- {
- "/media/configdrive",
- "/media/configdrive/openstack",
- },
- } {
- cd := configDrive{tt.root, nil}
- if configRoot := cd.ConfigRoot(); configRoot != tt.configRoot {
- t.Fatalf("bad config root for %q: want %q, got %q", tt, tt.configRoot, configRoot)
- }
- }
-}
-
-func TestNewDatasource(t *testing.T) {
- for _, tt := range []struct {
- root string
- expectRoot string
- }{
- {
- root: "",
- expectRoot: "",
- },
- {
- root: "/media/configdrive",
- expectRoot: "/media/configdrive",
- },
- } {
- service := NewDatasource(tt.root)
- if service.root != tt.expectRoot {
- t.Fatalf("bad root (%q): want %q, got %q", tt.root, tt.expectRoot, service.root)
- }
- }
-}
diff --git a/vendor/github.com/coreos/coreos-cloudinit/datasource/metadata/digitalocean/metadata_test.go b/vendor/github.com/coreos/coreos-cloudinit/datasource/metadata/digitalocean/metadata_test.go
deleted file mode 100644
index fd8a0a0c..00000000
--- a/vendor/github.com/coreos/coreos-cloudinit/datasource/metadata/digitalocean/metadata_test.go
+++ /dev/null
@@ -1,143 +0,0 @@
-// Copyright 2015 CoreOS, Inc.
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-package digitalocean
-
-import (
- "fmt"
- "net"
- "reflect"
- "testing"
-
- "github.com/coreos/coreos-cloudinit/datasource"
- "github.com/coreos/coreos-cloudinit/datasource/metadata"
- "github.com/coreos/coreos-cloudinit/datasource/metadata/test"
- "github.com/coreos/coreos-cloudinit/pkg"
-)
-
-func TestType(t *testing.T) {
- want := "digitalocean-metadata-service"
- if kind := (metadataService{}).Type(); kind != want {
- t.Fatalf("bad type: want %q, got %q", want, kind)
- }
-}
-
-func TestFetchMetadata(t *testing.T) {
- for _, tt := range []struct {
- root string
- metadataPath string
- resources map[string]string
- expect datasource.Metadata
- clientErr error
- expectErr error
- }{
- {
- root: "/",
- metadataPath: "v1.json",
- resources: map[string]string{
- "/v1.json": "bad",
- },
- expectErr: fmt.Errorf("invalid character 'b' looking for beginning of value"),
- },
- {
- root: "/",
- metadataPath: "v1.json",
- resources: map[string]string{
- "/v1.json": `{
- "droplet_id": 1,
- "user_data": "hello",
- "vendor_data": "hello",
- "public_keys": [
- "publickey1",
- "publickey2"
- ],
- "region": "nyc2",
- "interfaces": {
- "public": [
- {
- "ipv4": {
- "ip_address": "192.168.1.2",
- "netmask": "255.255.255.0",
- "gateway": "192.168.1.1"
- },
- "ipv6": {
- "ip_address": "fe00::",
- "cidr": 126,
- "gateway": "fe00::"
- },
- "mac": "ab:cd:ef:gh:ij",
- "type": "public"
- }
- ]
- }
-}`,
- },
- expect: datasource.Metadata{
- PublicIPv4: net.ParseIP("192.168.1.2"),
- PublicIPv6: net.ParseIP("fe00::"),
- SSHPublicKeys: map[string]string{
- "0": "publickey1",
- "1": "publickey2",
- },
- NetworkConfig: Metadata{
- Interfaces: Interfaces{
- Public: []Interface{
- Interface{
- IPv4: &Address{
- IPAddress: "192.168.1.2",
- Netmask: "255.255.255.0",
- Gateway: "192.168.1.1",
- },
- IPv6: &Address{
- IPAddress: "fe00::",
- Cidr: 126,
- Gateway: "fe00::",
- },
- MAC: "ab:cd:ef:gh:ij",
- Type: "public",
- },
- },
- },
- PublicKeys: []string{"publickey1", "publickey2"},
- },
- },
- },
- {
- clientErr: pkg.ErrTimeout{Err: fmt.Errorf("test error")},
- expectErr: pkg.ErrTimeout{Err: fmt.Errorf("test error")},
- },
- } {
- service := &metadataService{
- MetadataService: metadata.MetadataService{
- Root: tt.root,
- Client: &test.HttpClient{Resources: tt.resources, Err: tt.clientErr},
- MetadataPath: tt.metadataPath,
- },
- }
- metadata, err := service.FetchMetadata()
- if Error(err) != Error(tt.expectErr) {
- t.Fatalf("bad error (%q): want %q, got %q", tt.resources, tt.expectErr, err)
- }
- if !reflect.DeepEqual(tt.expect, metadata) {
- t.Fatalf("bad fetch (%q): want %#q, got %#q", tt.resources, tt.expect, metadata)
- }
- }
-}
-
-func Error(err error) string {
- if err != nil {
- return err.Error()
- }
- return ""
-}
diff --git a/vendor/github.com/coreos/coreos-cloudinit/datasource/metadata/ec2/metadata_test.go b/vendor/github.com/coreos/coreos-cloudinit/datasource/metadata/ec2/metadata_test.go
deleted file mode 100644
index ba463c28..00000000
--- a/vendor/github.com/coreos/coreos-cloudinit/datasource/metadata/ec2/metadata_test.go
+++ /dev/null
@@ -1,222 +0,0 @@
-// Copyright 2015 CoreOS, Inc.
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-package ec2
-
-import (
- "fmt"
- "net"
- "reflect"
- "testing"
-
- "github.com/coreos/coreos-cloudinit/datasource"
- "github.com/coreos/coreos-cloudinit/datasource/metadata"
- "github.com/coreos/coreos-cloudinit/datasource/metadata/test"
- "github.com/coreos/coreos-cloudinit/pkg"
-)
-
-func TestType(t *testing.T) {
- want := "ec2-metadata-service"
- if kind := (metadataService{}).Type(); kind != want {
- t.Fatalf("bad type: want %q, got %q", want, kind)
- }
-}
-
-func TestFetchAttributes(t *testing.T) {
- for _, s := range []struct {
- resources map[string]string
- err error
- tests []struct {
- path string
- val []string
- }
- }{
- {
- resources: map[string]string{
- "/": "a\nb\nc/",
- "/c/": "d\ne/",
- "/c/e/": "f",
- "/a": "1",
- "/b": "2",
- "/c/d": "3",
- "/c/e/f": "4",
- },
- tests: []struct {
- path string
- val []string
- }{
- {"/", []string{"a", "b", "c/"}},
- {"/b", []string{"2"}},
- {"/c/d", []string{"3"}},
- {"/c/e/", []string{"f"}},
- },
- },
- {
- err: fmt.Errorf("test error"),
- tests: []struct {
- path string
- val []string
- }{
- {"", nil},
- },
- },
- } {
- service := metadataService{metadata.MetadataService{
- Client: &test.HttpClient{Resources: s.resources, Err: s.err},
- }}
- for _, tt := range s.tests {
- attrs, err := service.fetchAttributes(tt.path)
- if err != s.err {
- t.Fatalf("bad error for %q (%q): want %q, got %q", tt.path, s.resources, s.err, err)
- }
- if !reflect.DeepEqual(attrs, tt.val) {
- t.Fatalf("bad fetch for %q (%q): want %q, got %q", tt.path, s.resources, tt.val, attrs)
- }
- }
- }
-}
-
-func TestFetchAttribute(t *testing.T) {
- for _, s := range []struct {
- resources map[string]string
- err error
- tests []struct {
- path string
- val string
- }
- }{
- {
- resources: map[string]string{
- "/": "a\nb\nc/",
- "/c/": "d\ne/",
- "/c/e/": "f",
- "/a": "1",
- "/b": "2",
- "/c/d": "3",
- "/c/e/f": "4",
- },
- tests: []struct {
- path string
- val string
- }{
- {"/a", "1"},
- {"/b", "2"},
- {"/c/d", "3"},
- {"/c/e/f", "4"},
- },
- },
- {
- err: fmt.Errorf("test error"),
- tests: []struct {
- path string
- val string
- }{
- {"", ""},
- },
- },
- } {
- service := metadataService{metadata.MetadataService{
- Client: &test.HttpClient{Resources: s.resources, Err: s.err},
- }}
- for _, tt := range s.tests {
- attr, err := service.fetchAttribute(tt.path)
- if err != s.err {
- t.Fatalf("bad error for %q (%q): want %q, got %q", tt.path, s.resources, s.err, err)
- }
- if attr != tt.val {
- t.Fatalf("bad fetch for %q (%q): want %q, got %q", tt.path, s.resources, tt.val, attr)
- }
- }
- }
-}
-
-func TestFetchMetadata(t *testing.T) {
- for _, tt := range []struct {
- root string
- metadataPath string
- resources map[string]string
- expect datasource.Metadata
- clientErr error
- expectErr error
- }{
- {
- root: "/",
- metadataPath: "2009-04-04/meta-data",
- resources: map[string]string{
- "/2009-04-04/meta-data/public-keys": "bad\n",
- },
- expectErr: fmt.Errorf("malformed public key: \"bad\""),
- },
- {
- root: "/",
- metadataPath: "2009-04-04/meta-data",
- resources: map[string]string{
- "/2009-04-04/meta-data/hostname": "host",
- "/2009-04-04/meta-data/local-ipv4": "1.2.3.4",
- "/2009-04-04/meta-data/public-ipv4": "5.6.7.8",
- "/2009-04-04/meta-data/public-keys": "0=test1\n",
- "/2009-04-04/meta-data/public-keys/0": "openssh-key",
- "/2009-04-04/meta-data/public-keys/0/openssh-key": "key",
- },
- expect: datasource.Metadata{
- Hostname: "host",
- PrivateIPv4: net.ParseIP("1.2.3.4"),
- PublicIPv4: net.ParseIP("5.6.7.8"),
- SSHPublicKeys: map[string]string{"test1": "key"},
- },
- },
- {
- root: "/",
- metadataPath: "2009-04-04/meta-data",
- resources: map[string]string{
- "/2009-04-04/meta-data/hostname": "host domain another_domain",
- "/2009-04-04/meta-data/local-ipv4": "1.2.3.4",
- "/2009-04-04/meta-data/public-ipv4": "5.6.7.8",
- "/2009-04-04/meta-data/public-keys": "0=test1\n",
- "/2009-04-04/meta-data/public-keys/0": "openssh-key",
- "/2009-04-04/meta-data/public-keys/0/openssh-key": "key",
- },
- expect: datasource.Metadata{
- Hostname: "host",
- PrivateIPv4: net.ParseIP("1.2.3.4"),
- PublicIPv4: net.ParseIP("5.6.7.8"),
- SSHPublicKeys: map[string]string{"test1": "key"},
- },
- },
- {
- clientErr: pkg.ErrTimeout{Err: fmt.Errorf("test error")},
- expectErr: pkg.ErrTimeout{Err: fmt.Errorf("test error")},
- },
- } {
- service := &metadataService{metadata.MetadataService{
- Root: tt.root,
- Client: &test.HttpClient{Resources: tt.resources, Err: tt.clientErr},
- MetadataPath: tt.metadataPath,
- }}
- metadata, err := service.FetchMetadata()
- if Error(err) != Error(tt.expectErr) {
- t.Fatalf("bad error (%q): want %q, got %q", tt.resources, tt.expectErr, err)
- }
- if !reflect.DeepEqual(tt.expect, metadata) {
- t.Fatalf("bad fetch (%q): want %#v, got %#v", tt.resources, tt.expect, metadata)
- }
- }
-}
-
-func Error(err error) string {
- if err != nil {
- return err.Error()
- }
- return ""
-}
diff --git a/vendor/github.com/coreos/coreos-cloudinit/datasource/metadata/metadata_test.go b/vendor/github.com/coreos/coreos-cloudinit/datasource/metadata/metadata_test.go
deleted file mode 100644
index 9d6b4b29..00000000
--- a/vendor/github.com/coreos/coreos-cloudinit/datasource/metadata/metadata_test.go
+++ /dev/null
@@ -1,185 +0,0 @@
-// Copyright 2015 CoreOS, Inc.
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-package metadata
-
-import (
- "bytes"
- "fmt"
- "testing"
-
- "github.com/coreos/coreos-cloudinit/datasource/metadata/test"
- "github.com/coreos/coreos-cloudinit/pkg"
-)
-
-func TestAvailabilityChanges(t *testing.T) {
- want := true
- if ac := (MetadataService{}).AvailabilityChanges(); ac != want {
- t.Fatalf("bad AvailabilityChanges: want %t, got %t", want, ac)
- }
-}
-
-func TestIsAvailable(t *testing.T) {
- for _, tt := range []struct {
- root string
- apiVersion string
- resources map[string]string
- expect bool
- }{
- {
- root: "/",
- apiVersion: "2009-04-04",
- resources: map[string]string{
- "/2009-04-04": "",
- },
- expect: true,
- },
- {
- root: "/",
- resources: map[string]string{},
- expect: false,
- },
- } {
- service := &MetadataService{
- Root: tt.root,
- Client: &test.HttpClient{Resources: tt.resources, Err: nil},
- ApiVersion: tt.apiVersion,
- }
- if a := service.IsAvailable(); a != tt.expect {
- t.Fatalf("bad isAvailable (%q): want %t, got %t", tt.resources, tt.expect, a)
- }
- }
-}
-
-func TestFetchUserdata(t *testing.T) {
- for _, tt := range []struct {
- root string
- userdataPath string
- resources map[string]string
- userdata []byte
- clientErr error
- expectErr error
- }{
- {
- root: "/",
- userdataPath: "2009-04-04/user-data",
- resources: map[string]string{
- "/2009-04-04/user-data": "hello",
- },
- userdata: []byte("hello"),
- },
- {
- root: "/",
- clientErr: pkg.ErrNotFound{Err: fmt.Errorf("test not found error")},
- userdata: []byte{},
- },
- {
- root: "/",
- clientErr: pkg.ErrTimeout{Err: fmt.Errorf("test timeout error")},
- expectErr: pkg.ErrTimeout{Err: fmt.Errorf("test timeout error")},
- },
- } {
- service := &MetadataService{
- Root: tt.root,
- Client: &test.HttpClient{Resources: tt.resources, Err: tt.clientErr},
- UserdataPath: tt.userdataPath,
- }
- data, err := service.FetchUserdata()
- if Error(err) != Error(tt.expectErr) {
- t.Fatalf("bad error (%q): want %q, got %q", tt.resources, tt.expectErr, err)
- }
- if !bytes.Equal(data, tt.userdata) {
- t.Fatalf("bad userdata (%q): want %q, got %q", tt.resources, tt.userdata, data)
- }
- }
-}
-
-func TestUrls(t *testing.T) {
- for _, tt := range []struct {
- root string
- userdataPath string
- metadataPath string
- expectRoot string
- userdata string
- metadata string
- }{
- {
- root: "/",
- userdataPath: "2009-04-04/user-data",
- metadataPath: "2009-04-04/meta-data",
- expectRoot: "/",
- userdata: "/2009-04-04/user-data",
- metadata: "/2009-04-04/meta-data",
- },
- {
- root: "http://169.254.169.254/",
- userdataPath: "2009-04-04/user-data",
- metadataPath: "2009-04-04/meta-data",
- expectRoot: "http://169.254.169.254/",
- userdata: "http://169.254.169.254/2009-04-04/user-data",
- metadata: "http://169.254.169.254/2009-04-04/meta-data",
- },
- } {
- service := &MetadataService{
- Root: tt.root,
- UserdataPath: tt.userdataPath,
- MetadataPath: tt.metadataPath,
- }
- if url := service.UserdataUrl(); url != tt.userdata {
- t.Fatalf("bad url (%q): want %q, got %q", tt.root, tt.userdata, url)
- }
- if url := service.MetadataUrl(); url != tt.metadata {
- t.Fatalf("bad url (%q): want %q, got %q", tt.root, tt.metadata, url)
- }
- if url := service.ConfigRoot(); url != tt.expectRoot {
- t.Fatalf("bad url (%q): want %q, got %q", tt.root, tt.expectRoot, url)
- }
- }
-}
-
-func TestNewDatasource(t *testing.T) {
- for _, tt := range []struct {
- root string
- expectRoot string
- }{
- {
- root: "",
- expectRoot: "/",
- },
- {
- root: "/",
- expectRoot: "/",
- },
- {
- root: "http://169.254.169.254",
- expectRoot: "http://169.254.169.254/",
- },
- {
- root: "http://169.254.169.254/",
- expectRoot: "http://169.254.169.254/",
- },
- } {
- service := NewDatasource(tt.root, "", "", "")
- if service.Root != tt.expectRoot {
- t.Fatalf("bad root (%q): want %q, got %q", tt.root, tt.expectRoot, service.Root)
- }
- }
-}
-
-func Error(err error) string {
- if err != nil {
- return err.Error()
- }
- return ""
-}
diff --git a/vendor/github.com/coreos/coreos-cloudinit/datasource/proc_cmdline/proc_cmdline_test.go b/vendor/github.com/coreos/coreos-cloudinit/datasource/proc_cmdline/proc_cmdline_test.go
deleted file mode 100644
index a0245812..00000000
--- a/vendor/github.com/coreos/coreos-cloudinit/datasource/proc_cmdline/proc_cmdline_test.go
+++ /dev/null
@@ -1,102 +0,0 @@
-// Copyright 2015 CoreOS, Inc.
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-package proc_cmdline
-
-import (
- "fmt"
- "io/ioutil"
- "net/http"
- "net/http/httptest"
- "os"
- "testing"
-)
-
-func TestParseCmdlineCloudConfigFound(t *testing.T) {
- tests := []struct {
- input string
- expect string
- }{
- {
- "cloud-config-url=example.com",
- "example.com",
- },
- {
- "cloud_config_url=example.com",
- "example.com",
- },
- {
- "cloud-config-url cloud-config-url=example.com",
- "example.com",
- },
- {
- "cloud-config-url= cloud-config-url=example.com",
- "example.com",
- },
- {
- "cloud-config-url=one.example.com cloud-config-url=two.example.com",
- "two.example.com",
- },
- {
- "foo=bar cloud-config-url=example.com ping=pong",
- "example.com",
- },
- }
-
- for i, tt := range tests {
- output, err := findCloudConfigURL(tt.input)
- if output != tt.expect {
- t.Errorf("Test case %d failed: %s != %s", i, output, tt.expect)
- }
- if err != nil {
- t.Errorf("Test case %d produced error: %v", i, err)
- }
- }
-}
-
-func TestProcCmdlineAndFetchConfig(t *testing.T) {
-
- var (
- ProcCmdlineTmpl = "foo=bar cloud-config-url=%s/config\n"
- CloudConfigContent = "#cloud-config\n"
- )
-
- ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- if r.Method == "GET" && r.RequestURI == "/config" {
- fmt.Fprint(w, CloudConfigContent)
- }
- }))
- defer ts.Close()
-
- file, err := ioutil.TempFile(os.TempDir(), "test_proc_cmdline")
- defer os.Remove(file.Name())
- if err != nil {
- t.Errorf("Test produced error: %v", err)
- }
- _, err = file.Write([]byte(fmt.Sprintf(ProcCmdlineTmpl, ts.URL)))
- if err != nil {
- t.Errorf("Test produced error: %v", err)
- }
-
- p := NewDatasource()
- p.Location = file.Name()
- cfg, err := p.FetchUserdata()
- if err != nil {
- t.Errorf("Test produced error: %v", err)
- }
-
- if string(cfg) != CloudConfigContent {
- t.Errorf("Test failed, response body: %s != %s", cfg, CloudConfigContent)
- }
-}
diff --git a/vendor/github.com/coreos/coreos-cloudinit/initialize/config_test.go b/vendor/github.com/coreos/coreos-cloudinit/initialize/config_test.go
deleted file mode 100644
index 33be737e..00000000
--- a/vendor/github.com/coreos/coreos-cloudinit/initialize/config_test.go
+++ /dev/null
@@ -1,299 +0,0 @@
-// Copyright 2015 CoreOS, Inc.
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-package initialize
-
-import (
- "reflect"
- "testing"
-
- "github.com/coreos/coreos-cloudinit/config"
- "github.com/coreos/coreos-cloudinit/network"
- "github.com/coreos/coreos-cloudinit/system"
-)
-
-type TestUnitManager struct {
- placed []string
- enabled []string
- masked []string
- unmasked []string
- commands []UnitAction
- reload bool
-}
-
-type UnitAction struct {
- unit string
- command string
-}
-
-func (tum *TestUnitManager) PlaceUnit(u system.Unit) error {
- tum.placed = append(tum.placed, u.Name)
- return nil
-}
-func (tum *TestUnitManager) PlaceUnitDropIn(u system.Unit, d config.UnitDropIn) error {
- tum.placed = append(tum.placed, u.Name+".d/"+d.Name)
- return nil
-}
-func (tum *TestUnitManager) EnableUnitFile(u system.Unit) error {
- tum.enabled = append(tum.enabled, u.Name)
- return nil
-}
-func (tum *TestUnitManager) RunUnitCommand(u system.Unit, c string) (string, error) {
- tum.commands = append(tum.commands, UnitAction{u.Name, c})
- return "", nil
-}
-func (tum *TestUnitManager) DaemonReload() error {
- tum.reload = true
- return nil
-}
-func (tum *TestUnitManager) MaskUnit(u system.Unit) error {
- tum.masked = append(tum.masked, u.Name)
- return nil
-}
-func (tum *TestUnitManager) UnmaskUnit(u system.Unit) error {
- tum.unmasked = append(tum.unmasked, u.Name)
- return nil
-}
-
-type mockInterface struct {
- name string
- filename string
- netdev string
- link string
- network string
- kind string
- modprobeParams string
-}
-
-func (i mockInterface) Name() string {
- return i.name
-}
-
-func (i mockInterface) Filename() string {
- return i.filename
-}
-
-func (i mockInterface) Netdev() string {
- return i.netdev
-}
-
-func (i mockInterface) Link() string {
- return i.link
-}
-
-func (i mockInterface) Network() string {
- return i.network
-}
-
-func (i mockInterface) Type() string {
- return i.kind
-}
-
-func (i mockInterface) ModprobeParams() string {
- return i.modprobeParams
-}
-
-func TestCreateNetworkingUnits(t *testing.T) {
- for _, tt := range []struct {
- interfaces []network.InterfaceGenerator
- expect []system.Unit
- }{
- {nil, nil},
- {
- []network.InterfaceGenerator{
- network.InterfaceGenerator(mockInterface{filename: "test"}),
- },
- nil,
- },
- {
- []network.InterfaceGenerator{
- network.InterfaceGenerator(mockInterface{filename: "test1", netdev: "test netdev"}),
- network.InterfaceGenerator(mockInterface{filename: "test2", link: "test link"}),
- network.InterfaceGenerator(mockInterface{filename: "test3", network: "test network"}),
- },
- []system.Unit{
- system.Unit{Unit: config.Unit{Name: "test1.netdev", Runtime: true, Content: "test netdev"}},
- system.Unit{Unit: config.Unit{Name: "test2.link", Runtime: true, Content: "test link"}},
- system.Unit{Unit: config.Unit{Name: "test3.network", Runtime: true, Content: "test network"}},
- },
- },
- {
- []network.InterfaceGenerator{
- network.InterfaceGenerator(mockInterface{filename: "test", netdev: "test netdev", link: "test link", network: "test network"}),
- },
- []system.Unit{
- system.Unit{Unit: config.Unit{Name: "test.netdev", Runtime: true, Content: "test netdev"}},
- system.Unit{Unit: config.Unit{Name: "test.link", Runtime: true, Content: "test link"}},
- system.Unit{Unit: config.Unit{Name: "test.network", Runtime: true, Content: "test network"}},
- },
- },
- } {
- units := createNetworkingUnits(tt.interfaces)
- if !reflect.DeepEqual(tt.expect, units) {
- t.Errorf("bad units (%+v): want %#v, got %#v", tt.interfaces, tt.expect, units)
- }
- }
-}
-
-func TestProcessUnits(t *testing.T) {
- tests := []struct {
- units []system.Unit
-
- result TestUnitManager
- }{
- {
- units: []system.Unit{
- system.Unit{Unit: config.Unit{
- Name: "foo",
- Mask: true,
- }},
- },
- result: TestUnitManager{
- masked: []string{"foo"},
- },
- },
- {
- units: []system.Unit{
- system.Unit{Unit: config.Unit{
- Name: "baz.service",
- Content: "[Service]\nExecStart=/bin/baz",
- Command: "start",
- }},
- system.Unit{Unit: config.Unit{
- Name: "foo.network",
- Content: "[Network]\nFoo=true",
- }},
- system.Unit{Unit: config.Unit{
- Name: "bar.network",
- Content: "[Network]\nBar=true",
- }},
- },
- result: TestUnitManager{
- placed: []string{"baz.service", "foo.network", "bar.network"},
- commands: []UnitAction{
- UnitAction{"systemd-networkd.service", "restart"},
- UnitAction{"baz.service", "start"},
- },
- reload: true,
- },
- },
- {
- units: []system.Unit{
- system.Unit{Unit: config.Unit{
- Name: "baz.service",
- Content: "[Service]\nExecStart=/bin/true",
- }},
- },
- result: TestUnitManager{
- placed: []string{"baz.service"},
- reload: true,
- },
- },
- {
- units: []system.Unit{
- system.Unit{Unit: config.Unit{
- Name: "locksmithd.service",
- Runtime: true,
- }},
- },
- result: TestUnitManager{
- unmasked: []string{"locksmithd.service"},
- },
- },
- {
- units: []system.Unit{
- system.Unit{Unit: config.Unit{
- Name: "woof",
- Enable: true,
- }},
- },
- result: TestUnitManager{
- enabled: []string{"woof"},
- },
- },
- {
- units: []system.Unit{
- system.Unit{Unit: config.Unit{
- Name: "hi.service",
- Runtime: true,
- Content: "[Service]\nExecStart=/bin/echo hi",
- DropIns: []config.UnitDropIn{
- {
- Name: "lo.conf",
- Content: "[Service]\nExecStart=/bin/echo lo",
- },
- {
- Name: "bye.conf",
- Content: "[Service]\nExecStart=/bin/echo bye",
- },
- },
- }},
- },
- result: TestUnitManager{
- placed: []string{"hi.service", "hi.service.d/lo.conf", "hi.service.d/bye.conf"},
- unmasked: []string{"hi.service"},
- reload: true,
- },
- },
- {
- units: []system.Unit{
- system.Unit{Unit: config.Unit{
- DropIns: []config.UnitDropIn{
- {
- Name: "lo.conf",
- Content: "[Service]\nExecStart=/bin/echo lo",
- },
- },
- }},
- },
- result: TestUnitManager{},
- },
- {
- units: []system.Unit{
- system.Unit{Unit: config.Unit{
- Name: "hi.service",
- DropIns: []config.UnitDropIn{
- {
- Content: "[Service]\nExecStart=/bin/echo lo",
- },
- },
- }},
- },
- result: TestUnitManager{},
- },
- {
- units: []system.Unit{
- system.Unit{Unit: config.Unit{
- Name: "hi.service",
- DropIns: []config.UnitDropIn{
- {
- Name: "lo.conf",
- },
- },
- }},
- },
- result: TestUnitManager{},
- },
- }
-
- for _, tt := range tests {
- tum := &TestUnitManager{}
- if err := processUnits(tt.units, "", tum); err != nil {
- t.Errorf("bad error (%+v): want nil, got %s", tt.units, err)
- }
- if !reflect.DeepEqual(tt.result, *tum) {
- t.Errorf("bad result (%+v): want %+v, got %+v", tt.units, tt.result, tum)
- }
- }
-}
diff --git a/vendor/github.com/coreos/coreos-cloudinit/initialize/env_test.go b/vendor/github.com/coreos/coreos-cloudinit/initialize/env_test.go
deleted file mode 100644
index abb770cf..00000000
--- a/vendor/github.com/coreos/coreos-cloudinit/initialize/env_test.go
+++ /dev/null
@@ -1,148 +0,0 @@
-// Copyright 2015 CoreOS, Inc.
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-package initialize
-
-import (
- "io/ioutil"
- "net"
- "os"
- "path"
- "testing"
-
- "github.com/coreos/coreos-cloudinit/datasource"
- "github.com/coreos/coreos-cloudinit/system"
-)
-
-func TestEnvironmentApply(t *testing.T) {
- os.Setenv("COREOS_PUBLIC_IPV4", "1.2.3.4")
- os.Setenv("COREOS_PRIVATE_IPV4", "5.6.7.8")
- os.Setenv("COREOS_PUBLIC_IPV6", "1234::")
- os.Setenv("COREOS_PRIVATE_IPV6", "5678::")
- for _, tt := range []struct {
- metadata datasource.Metadata
- input string
- out string
- }{
- {
- // Substituting both values directly should always take precedence
- // over environment variables
- datasource.Metadata{
- PublicIPv4: net.ParseIP("192.0.2.3"),
- PrivateIPv4: net.ParseIP("192.0.2.203"),
- PublicIPv6: net.ParseIP("fe00:1234::"),
- PrivateIPv6: net.ParseIP("fe00:5678::"),
- },
- `[Service]
-ExecStart=/usr/bin/echo "$public_ipv4 $public_ipv6"
-ExecStop=/usr/bin/echo $private_ipv4 $private_ipv6
-ExecStop=/usr/bin/echo $unknown`,
- `[Service]
-ExecStart=/usr/bin/echo "192.0.2.3 fe00:1234::"
-ExecStop=/usr/bin/echo 192.0.2.203 fe00:5678::
-ExecStop=/usr/bin/echo $unknown`,
- },
- {
- // Substituting one value directly while falling back with the other
- datasource.Metadata{
- PrivateIPv4: net.ParseIP("127.0.0.1"),
- },
- "$private_ipv4\n$public_ipv4",
- "127.0.0.1\n1.2.3.4",
- },
- {
- // Falling back to environment variables for both values
- datasource.Metadata{},
- "$private_ipv4\n$public_ipv4",
- "5.6.7.8\n1.2.3.4",
- },
- {
- // No substitutions
- datasource.Metadata{},
- "$private_ipv4\nfoobar",
- "5.6.7.8\nfoobar",
- },
- {
- // Escaping substitutions
- datasource.Metadata{
- PrivateIPv4: net.ParseIP("127.0.0.1"),
- },
- `\$private_ipv4
-$private_ipv4
-addr: \$private_ipv4
-\\$private_ipv4`,
- `$private_ipv4
-127.0.0.1
-addr: $private_ipv4
-\$private_ipv4`,
- },
- {
- // No substitutions with escaping
- datasource.Metadata{},
- "\\$test\n$test",
- "\\$test\n$test",
- },
- } {
-
- env := NewEnvironment("./", "./", "./", "", tt.metadata)
- got := env.Apply(tt.input)
- if got != tt.out {
- t.Fatalf("Environment incorrectly applied.\ngot:\n%s\nwant:\n%s", got, tt.out)
- }
- }
-}
-
-func TestEnvironmentFile(t *testing.T) {
- metadata := datasource.Metadata{
- PublicIPv4: net.ParseIP("1.2.3.4"),
- PrivateIPv4: net.ParseIP("5.6.7.8"),
- PublicIPv6: net.ParseIP("1234::"),
- PrivateIPv6: net.ParseIP("5678::"),
- }
- expect := "COREOS_PRIVATE_IPV4=5.6.7.8\nCOREOS_PRIVATE_IPV6=5678::\nCOREOS_PUBLIC_IPV4=1.2.3.4\nCOREOS_PUBLIC_IPV6=1234::\n"
-
- dir, err := ioutil.TempDir(os.TempDir(), "coreos-cloudinit-")
- if err != nil {
- t.Fatalf("Unable to create tempdir: %v", err)
- }
- defer os.RemoveAll(dir)
-
- env := NewEnvironment("./", "./", "./", "", metadata)
- ef := env.DefaultEnvironmentFile()
- err = system.WriteEnvFile(ef, dir)
- if err != nil {
- t.Fatalf("WriteEnvFile failed: %v", err)
- }
-
- fullPath := path.Join(dir, "etc", "environment")
- contents, err := ioutil.ReadFile(fullPath)
- if err != nil {
- t.Fatalf("Unable to read expected file: %v", err)
- }
-
- if string(contents) != expect {
- t.Fatalf("File has incorrect contents: %q", contents)
- }
-}
-
-func TestEnvironmentFileNil(t *testing.T) {
- os.Clearenv()
- metadata := datasource.Metadata{}
-
- env := NewEnvironment("./", "./", "./", "", metadata)
- ef := env.DefaultEnvironmentFile()
- if ef != nil {
- t.Fatalf("Environment file not nil: %v", ef)
- }
-}
diff --git a/vendor/github.com/coreos/coreos-cloudinit/initialize/ssh_keys_test.go b/vendor/github.com/coreos/coreos-cloudinit/initialize/ssh_keys_test.go
deleted file mode 100644
index 86395797..00000000
--- a/vendor/github.com/coreos/coreos-cloudinit/initialize/ssh_keys_test.go
+++ /dev/null
@@ -1,56 +0,0 @@
-// Copyright 2015 CoreOS, Inc.
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-package initialize
-
-import (
- "fmt"
- "net/http"
- "net/http/httptest"
- "testing"
-)
-
-func TestCloudConfigUsersUrlMarshal(t *testing.T) {
- ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- gh_res := `
-[
- {
- "key": "ssh-dss AAAAB3NzaC1kc3MAAACBAIHAu822ggSkIHrJYvhmBceOSVjuflfQm8RbMMDNVe9relQfuPbN+nxGGTCKzPLebeOcX+Wwi77TPXWwK3BZMglfXxhABlFPsuMb63Tqp94pBYsJdx/iFj9iGo6pKoM1k8ubOcqsUnq+BR9895zRbE7MjdwkGo67+QhCEwvkwAnNAAAAFQCuddVqXLCubzqnWmeHLQE+2GFfHwAAAIBnlXW5h15ndVuwi0htF4oodVSB1KwnTWcuBK+aE1zRs76yvRb0Ws+oifumThDwB/Tec6FQuAfRKfy6piChZqsu5KvL98I+2t5yyi1td+kMvdTnVL2lW44etDKseOcozmknCOmh4Dqvhl/2MwrDAhlPaN08EEq9h3w3mXtNLWH64QAAAIBAzDOKr17llngaKIdDXh+LtXKh87+zfjlTA36/9r2uF2kYE5uApDtu9sPCkt7+YBQt7R8prADPckwAiXwVdk0xijIOpLDBmoydQJJRQ+zTMxvpQmUr/1kUOv0zb+lB657CgvN0vVTmP2swPeMvgntt3C4vw7Ab+O+MS9peOAJbbQ=="
- },
- {
- "key": "ssh-dss AAAAB3NzaC1kc3MAAACBANxpzIbTzKTeBRaOIdUxwwGwvDasTfU/PonhbNIuhYjc+xFGvBRTumox2F+luVAKKs4WdvA4nJXaY1OFi6DZftk5Bp4E2JaSzp8ulAzHsMexDdv6LGHGEJj/qdHAL1vHk2K89PpwRFSRZI8XRBLjvkr4ZgBKLG5ZILXPJEPP2j3lAAAAFQCtxoTnV8wy0c4grcGrQ+1sCsD7WQAAAIAqZsW2GviMe1RQrbZT0xAZmI64XRPrnLsoLxycHWlS7r6uUln2c6Ae2MB/YF0d4Kd1XZii9GHj7rrypqEo7MW8uSabhu70nmu1J8m2O3Dsr+4oJLeat9vwPsJV92IKO0jQwjKnAOHOiB9JKGeCw+NfXfogbti9/q38Q6XcS+SI5wAAAIEA1803Y2h+tOOpZXAsNIwl9mRfExWzLQ3L7knwJdznQu/6SW1H/1oyoYLebuk187Qj2UFI5qQ6AZNc49DvohWx0Cg6ABcyubNyoaCjZKWIdxVnItHWNbLe//+tyTu0I2eQwJOORsEPK5gMpf599C7wXQ//DzZOWbTWiHEX52gCTmk="
- },
- {
- "id": 5224438,
- "key": "ssh-dss AAAAB3NzaC1kc3MAAACBAPKRWdKhzGZuLAJL6M1eM51hWViMqNBC2C6lm2OqGRYLuIf1GJ391widUuSf4wQqnkR22Q9PCmAZ19XCf11wBRMnuw9I/Z3Bt5bXfc+dzFBCmHYGJ6wNSv++H9jxyMb+usmsenWOFZGNO2jN0wrJ4ay8Yt0bwtRU+VCXpuRLszMzAAAAFQDZUIuPjcfK5HLgnwZ/J3lvtvlUjQAAAIEApIkAwLuCQV5j3U6DmI/Y6oELqSUR2purFm8jo8jePFfe1t+ghikgD254/JXlhDCVgY0NLXcak+coJfGCTT23quJ7I5xdpTn/OZO2Q6Woum/bijFC/UWwQbLz0R2nU3DoHv5v6XHQZxuIG4Fsxa91S+vWjZFtI7RuYlBCZA//ANMAAACBAJO0FojzkX6IeaWLqrgu9GTkFwGFazZ+LPH5JOWPoPn1hQKuR32Uf6qNcBZcIjY7SF0P7HF5rLQd6zKZzHqqQQ92MV555NEwjsnJglYU8CaaZsfYooaGPgA1YN7RhTSAuDmUW5Hyfj5BH4NTtrzrvJxIhDoQLf31Fasjw00r4R0O"
- }
-]
-`
- fmt.Fprintln(w, gh_res)
- }))
- defer ts.Close()
-
- keys, err := fetchUserKeys(ts.URL)
- if err != nil {
- t.Fatalf("Encountered unexpected error: %v", err)
- }
- expected := "ssh-dss AAAAB3NzaC1kc3MAAACBAIHAu822ggSkIHrJYvhmBceOSVjuflfQm8RbMMDNVe9relQfuPbN+nxGGTCKzPLebeOcX+Wwi77TPXWwK3BZMglfXxhABlFPsuMb63Tqp94pBYsJdx/iFj9iGo6pKoM1k8ubOcqsUnq+BR9895zRbE7MjdwkGo67+QhCEwvkwAnNAAAAFQCuddVqXLCubzqnWmeHLQE+2GFfHwAAAIBnlXW5h15ndVuwi0htF4oodVSB1KwnTWcuBK+aE1zRs76yvRb0Ws+oifumThDwB/Tec6FQuAfRKfy6piChZqsu5KvL98I+2t5yyi1td+kMvdTnVL2lW44etDKseOcozmknCOmh4Dqvhl/2MwrDAhlPaN08EEq9h3w3mXtNLWH64QAAAIBAzDOKr17llngaKIdDXh+LtXKh87+zfjlTA36/9r2uF2kYE5uApDtu9sPCkt7+YBQt7R8prADPckwAiXwVdk0xijIOpLDBmoydQJJRQ+zTMxvpQmUr/1kUOv0zb+lB657CgvN0vVTmP2swPeMvgntt3C4vw7Ab+O+MS9peOAJbbQ=="
- if keys[0] != expected {
- t.Fatalf("expected %s, got %s", expected, keys[0])
- }
- expected = "ssh-dss AAAAB3NzaC1kc3MAAACBAPKRWdKhzGZuLAJL6M1eM51hWViMqNBC2C6lm2OqGRYLuIf1GJ391widUuSf4wQqnkR22Q9PCmAZ19XCf11wBRMnuw9I/Z3Bt5bXfc+dzFBCmHYGJ6wNSv++H9jxyMb+usmsenWOFZGNO2jN0wrJ4ay8Yt0bwtRU+VCXpuRLszMzAAAAFQDZUIuPjcfK5HLgnwZ/J3lvtvlUjQAAAIEApIkAwLuCQV5j3U6DmI/Y6oELqSUR2purFm8jo8jePFfe1t+ghikgD254/JXlhDCVgY0NLXcak+coJfGCTT23quJ7I5xdpTn/OZO2Q6Woum/bijFC/UWwQbLz0R2nU3DoHv5v6XHQZxuIG4Fsxa91S+vWjZFtI7RuYlBCZA//ANMAAACBAJO0FojzkX6IeaWLqrgu9GTkFwGFazZ+LPH5JOWPoPn1hQKuR32Uf6qNcBZcIjY7SF0P7HF5rLQd6zKZzHqqQQ92MV555NEwjsnJglYU8CaaZsfYooaGPgA1YN7RhTSAuDmUW5Hyfj5BH4NTtrzrvJxIhDoQLf31Fasjw00r4R0O"
- if keys[2] != expected {
- t.Fatalf("expected %s, got %s", expected, keys[2])
- }
-}
diff --git a/vendor/github.com/coreos/coreos-cloudinit/initialize/user_data_test.go b/vendor/github.com/coreos/coreos-cloudinit/initialize/user_data_test.go
deleted file mode 100644
index 7a5acc98..00000000
--- a/vendor/github.com/coreos/coreos-cloudinit/initialize/user_data_test.go
+++ /dev/null
@@ -1,74 +0,0 @@
-// Copyright 2015 CoreOS, Inc.
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-package initialize
-
-import (
- "testing"
-
- "github.com/coreos/coreos-cloudinit/config"
-)
-
-func TestParseHeaderCRLF(t *testing.T) {
- configs := []string{
- "#cloud-config\nfoo: bar",
- "#cloud-config\r\nfoo: bar",
- }
-
- for i, config := range configs {
- _, err := ParseUserData(config)
- if err != nil {
- t.Errorf("Failed parsing config %d: %v", i, err)
- }
- }
-
- scripts := []string{
- "#!bin/bash\necho foo",
- "#!bin/bash\r\necho foo",
- }
-
- for i, script := range scripts {
- _, err := ParseUserData(script)
- if err != nil {
- t.Errorf("Failed parsing script %d: %v", i, err)
- }
- }
-}
-
-func TestParseConfigCRLF(t *testing.T) {
- contents := "#cloud-config \r\nhostname: foo\r\nssh_authorized_keys:\r\n - foobar\r\n"
- ud, err := ParseUserData(contents)
- if err != nil {
- t.Fatalf("Failed parsing config: %v", err)
- }
-
- cfg := ud.(*config.CloudConfig)
-
- if cfg.Hostname != "foo" {
- t.Error("Failed parsing hostname from config")
- }
-
- if len(cfg.SSHAuthorizedKeys) != 1 {
- t.Error("Parsed incorrect number of SSH keys")
- }
-}
-
-func TestParseConfigEmpty(t *testing.T) {
- i, e := ParseUserData(``)
- if i != nil {
- t.Error("ParseUserData of empty string returned non-nil unexpectedly")
- } else if e != nil {
- t.Error("ParseUserData of empty string returned error unexpectedly")
- }
-}
diff --git a/vendor/github.com/coreos/coreos-cloudinit/network/debian_test.go b/vendor/github.com/coreos/coreos-cloudinit/network/debian_test.go
deleted file mode 100644
index da9e281d..00000000
--- a/vendor/github.com/coreos/coreos-cloudinit/network/debian_test.go
+++ /dev/null
@@ -1,56 +0,0 @@
-// Copyright 2015 CoreOS, Inc.
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-package network
-
-import (
- "testing"
-)
-
-func TestFormatConfigs(t *testing.T) {
- for in, n := range map[string]int{
- "": 0,
- "line1\\\nis long": 1,
- "#comment": 0,
- "#comment\\\ncomment": 0,
- " #comment \\\n comment\nline 1\nline 2\\\n is long": 2,
- } {
- lines := formatConfig(in)
- if len(lines) != n {
- t.Fatalf("bad number of lines for config %q: got %d, want %d", in, len(lines), n)
- }
- }
-}
-
-func TestProcessDebianNetconf(t *testing.T) {
- for _, tt := range []struct {
- in string
- fail bool
- n int
- }{
- {"", false, 0},
- {"iface", true, -1},
- {"auto eth1\nauto eth2", false, 0},
- {"iface eth1 inet manual", false, 1},
- } {
- interfaces, err := ProcessDebianNetconf([]byte(tt.in))
- failed := err != nil
- if tt.fail != failed {
- t.Fatalf("bad failure state for %q: got %t, want %t", tt.in, failed, tt.fail)
- }
- if tt.n != -1 && tt.n != len(interfaces) {
- t.Fatalf("bad number of interfaces for %q: got %d, want %q", tt.in, len(interfaces), tt.n)
- }
- }
-}
diff --git a/vendor/github.com/coreos/coreos-cloudinit/network/digitalocean_test.go b/vendor/github.com/coreos/coreos-cloudinit/network/digitalocean_test.go
deleted file mode 100644
index fc4fc6d5..00000000
--- a/vendor/github.com/coreos/coreos-cloudinit/network/digitalocean_test.go
+++ /dev/null
@@ -1,481 +0,0 @@
-// Copyright 2015 CoreOS, Inc.
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-package network
-
-import (
- "errors"
- "net"
- "reflect"
- "testing"
-
- "github.com/coreos/coreos-cloudinit/datasource/metadata/digitalocean"
-)
-
-func TestParseNameservers(t *testing.T) {
- for _, tt := range []struct {
- dns digitalocean.DNS
- nss []net.IP
- err error
- }{
- {
- dns: digitalocean.DNS{},
- nss: []net.IP{},
- },
- {
- dns: digitalocean.DNS{Nameservers: []string{"1.2.3.4"}},
- nss: []net.IP{net.ParseIP("1.2.3.4")},
- },
- {
- dns: digitalocean.DNS{Nameservers: []string{"bad"}},
- err: errors.New("could not parse \"bad\" as nameserver IP address"),
- },
- } {
- nss, err := parseNameservers(tt.dns)
- if !errorsEqual(tt.err, err) {
- t.Fatalf("bad error (%+v): want %q, got %q", tt.dns, tt.err, err)
- }
- if !reflect.DeepEqual(tt.nss, nss) {
- t.Fatalf("bad nameservers (%+v): want %#v, got %#v", tt.dns, tt.nss, nss)
- }
- }
-}
-
-func mkInvalidMAC() error {
- if isGo15 {
- return &net.AddrError{Err: "invalid MAC address", Addr: "bad"}
- } else {
- return errors.New("invalid MAC address: bad")
- }
-}
-
-func TestParseInterface(t *testing.T) {
- for _, tt := range []struct {
- cfg digitalocean.Interface
- nss []net.IP
- useRoute bool
- iface *logicalInterface
- err error
- }{
- {
- cfg: digitalocean.Interface{
- MAC: "bad",
- },
- err: mkInvalidMAC(),
- },
- {
- cfg: digitalocean.Interface{
- MAC: "01:23:45:67:89:AB",
- },
- nss: []net.IP{},
- iface: &logicalInterface{
- hwaddr: net.HardwareAddr([]byte{0x01, 0x23, 0x45, 0x67, 0x89, 0xab}),
- config: configMethodStatic{
- addresses: []net.IPNet{},
- nameservers: []net.IP{},
- routes: []route{},
- },
- },
- },
- {
- cfg: digitalocean.Interface{
- MAC: "01:23:45:67:89:AB",
- },
- useRoute: true,
- nss: []net.IP{net.ParseIP("1.2.3.4")},
- iface: &logicalInterface{
- hwaddr: net.HardwareAddr([]byte{0x01, 0x23, 0x45, 0x67, 0x89, 0xab}),
- config: configMethodStatic{
- addresses: []net.IPNet{},
- nameservers: []net.IP{net.ParseIP("1.2.3.4")},
- routes: []route{},
- },
- },
- },
- {
- cfg: digitalocean.Interface{
- MAC: "01:23:45:67:89:AB",
- IPv4: &digitalocean.Address{
- IPAddress: "bad",
- Netmask: "255.255.0.0",
- },
- },
- nss: []net.IP{},
- err: errors.New("could not parse \"bad\" as IPv4 address"),
- },
- {
- cfg: digitalocean.Interface{
- MAC: "01:23:45:67:89:AB",
- IPv4: &digitalocean.Address{
- IPAddress: "1.2.3.4",
- Netmask: "bad",
- },
- },
- nss: []net.IP{},
- err: errors.New("could not parse \"bad\" as IPv4 mask"),
- },
- {
- cfg: digitalocean.Interface{
- MAC: "01:23:45:67:89:AB",
- IPv4: &digitalocean.Address{
- IPAddress: "1.2.3.4",
- Netmask: "255.255.0.0",
- Gateway: "ignoreme",
- },
- },
- nss: []net.IP{},
- iface: &logicalInterface{
- hwaddr: net.HardwareAddr([]byte{0x01, 0x23, 0x45, 0x67, 0x89, 0xab}),
- config: configMethodStatic{
- addresses: []net.IPNet{net.IPNet{
- IP: net.ParseIP("1.2.3.4"),
- Mask: net.IPMask(net.ParseIP("255.255.0.0")),
- }},
- nameservers: []net.IP{},
- routes: []route{},
- },
- },
- },
- {
- cfg: digitalocean.Interface{
- MAC: "01:23:45:67:89:AB",
- IPv4: &digitalocean.Address{
- IPAddress: "1.2.3.4",
- Netmask: "255.255.0.0",
- Gateway: "bad",
- },
- },
- useRoute: true,
- nss: []net.IP{},
- err: errors.New("could not parse \"bad\" as IPv4 gateway"),
- },
- {
- cfg: digitalocean.Interface{
- MAC: "01:23:45:67:89:AB",
- IPv4: &digitalocean.Address{
- IPAddress: "1.2.3.4",
- Netmask: "255.255.0.0",
- Gateway: "5.6.7.8",
- },
- },
- useRoute: true,
- nss: []net.IP{},
- iface: &logicalInterface{
- hwaddr: net.HardwareAddr([]byte{0x01, 0x23, 0x45, 0x67, 0x89, 0xab}),
- config: configMethodStatic{
- addresses: []net.IPNet{net.IPNet{
- IP: net.ParseIP("1.2.3.4"),
- Mask: net.IPMask(net.ParseIP("255.255.0.0")),
- }},
- nameservers: []net.IP{},
- routes: []route{route{
- net.IPNet{IP: net.IPv4zero, Mask: net.IPMask(net.IPv4zero)},
- net.ParseIP("5.6.7.8"),
- }},
- },
- },
- },
- {
- cfg: digitalocean.Interface{
- MAC: "01:23:45:67:89:AB",
- IPv6: &digitalocean.Address{
- IPAddress: "bad",
- Cidr: 16,
- },
- },
- nss: []net.IP{},
- err: errors.New("could not parse \"bad\" as IPv6 address"),
- },
- {
- cfg: digitalocean.Interface{
- MAC: "01:23:45:67:89:AB",
- IPv6: &digitalocean.Address{
- IPAddress: "fe00::",
- Cidr: 16,
- Gateway: "ignoreme",
- },
- },
- nss: []net.IP{},
- iface: &logicalInterface{
- hwaddr: net.HardwareAddr([]byte{0x01, 0x23, 0x45, 0x67, 0x89, 0xab}),
- config: configMethodStatic{
- addresses: []net.IPNet{net.IPNet{
- IP: net.ParseIP("fe00::"),
- Mask: net.IPMask(net.ParseIP("ffff::")),
- }},
- nameservers: []net.IP{},
- routes: []route{},
- },
- },
- },
- {
- cfg: digitalocean.Interface{
- MAC: "01:23:45:67:89:AB",
- IPv6: &digitalocean.Address{
- IPAddress: "fe00::",
- Cidr: 16,
- Gateway: "bad",
- },
- },
- useRoute: true,
- nss: []net.IP{},
- err: errors.New("could not parse \"bad\" as IPv6 gateway"),
- },
- {
- cfg: digitalocean.Interface{
- MAC: "01:23:45:67:89:AB",
- IPv6: &digitalocean.Address{
- IPAddress: "fe00::",
- Cidr: 16,
- Gateway: "fe00:1234::",
- },
- },
- useRoute: true,
- nss: []net.IP{},
- iface: &logicalInterface{
- hwaddr: net.HardwareAddr([]byte{0x01, 0x23, 0x45, 0x67, 0x89, 0xab}),
- config: configMethodStatic{
- addresses: []net.IPNet{net.IPNet{
- IP: net.ParseIP("fe00::"),
- Mask: net.IPMask(net.ParseIP("ffff::")),
- }},
- nameservers: []net.IP{},
- routes: []route{route{
- net.IPNet{IP: net.IPv6zero, Mask: net.IPMask(net.IPv6zero)},
- net.ParseIP("fe00:1234::"),
- }},
- },
- },
- },
-
- {
- cfg: digitalocean.Interface{
- MAC: "01:23:45:67:89:AB",
- AnchorIPv4: &digitalocean.Address{
- IPAddress: "bad",
- Netmask: "255.255.0.0",
- },
- },
- nss: []net.IP{},
- err: errors.New("could not parse \"bad\" as anchor IPv4 address"),
- },
- {
- cfg: digitalocean.Interface{
- MAC: "01:23:45:67:89:AB",
- AnchorIPv4: &digitalocean.Address{
- IPAddress: "1.2.3.4",
- Netmask: "bad",
- },
- },
- nss: []net.IP{},
- err: errors.New("could not parse \"bad\" as anchor IPv4 mask"),
- },
- {
- cfg: digitalocean.Interface{
- MAC: "01:23:45:67:89:AB",
- IPv4: &digitalocean.Address{
- IPAddress: "1.2.3.4",
- Netmask: "255.255.0.0",
- Gateway: "5.6.7.8",
- },
- AnchorIPv4: &digitalocean.Address{
- IPAddress: "7.8.9.10",
- Netmask: "255.255.0.0",
- },
- },
- useRoute: true,
- nss: []net.IP{},
- iface: &logicalInterface{
- hwaddr: net.HardwareAddr([]byte{0x01, 0x23, 0x45, 0x67, 0x89, 0xab}),
- config: configMethodStatic{
- addresses: []net.IPNet{
- {
- IP: net.ParseIP("1.2.3.4"),
- Mask: net.IPMask(net.ParseIP("255.255.0.0")),
- },
- {
- IP: net.ParseIP("7.8.9.10"),
- Mask: net.IPMask(net.ParseIP("255.255.0.0")),
- },
- },
- nameservers: []net.IP{},
- routes: []route{
- {
- destination: net.IPNet{IP: net.IPv4zero, Mask: net.IPMask(net.IPv4zero)},
- gateway: net.ParseIP("5.6.7.8"),
- },
- {
- destination: net.IPNet{IP: net.IPv4zero, Mask: net.IPMask(net.IPv4zero)},
- },
- },
- },
- },
- },
- } {
- iface, err := parseInterface(tt.cfg, tt.nss, tt.useRoute)
- if !errorsEqual(tt.err, err) {
- t.Fatalf("bad error (%+v): want %q, got %q", tt.cfg, tt.err, err)
- }
- if !reflect.DeepEqual(tt.iface, iface) {
- t.Fatalf("bad interface (%+v): want %#v, got %#v", tt.cfg, tt.iface, iface)
- }
- }
-}
-
-func TestParseInterfaces(t *testing.T) {
- for _, tt := range []struct {
- cfg digitalocean.Interfaces
- nss []net.IP
- ifaces []InterfaceGenerator
- err error
- }{
- {
- ifaces: []InterfaceGenerator{},
- },
- {
- cfg: digitalocean.Interfaces{
- Public: []digitalocean.Interface{{MAC: "01:23:45:67:89:AB"}},
- },
- ifaces: []InterfaceGenerator{
- &physicalInterface{logicalInterface{
- hwaddr: net.HardwareAddr([]byte{0x01, 0x23, 0x45, 0x67, 0x89, 0xab}),
- config: configMethodStatic{
- addresses: []net.IPNet{},
- nameservers: []net.IP{},
- routes: []route{},
- },
- }},
- },
- },
- {
- cfg: digitalocean.Interfaces{
- Private: []digitalocean.Interface{{MAC: "01:23:45:67:89:AB"}},
- },
- ifaces: []InterfaceGenerator{
- &physicalInterface{logicalInterface{
- hwaddr: net.HardwareAddr([]byte{0x01, 0x23, 0x45, 0x67, 0x89, 0xab}),
- config: configMethodStatic{
- addresses: []net.IPNet{},
- nameservers: []net.IP{},
- routes: []route{},
- },
- }},
- },
- },
- {
- cfg: digitalocean.Interfaces{
- Public: []digitalocean.Interface{{MAC: "01:23:45:67:89:AB"}},
- },
- nss: []net.IP{net.ParseIP("1.2.3.4")},
- ifaces: []InterfaceGenerator{
- &physicalInterface{logicalInterface{
- hwaddr: net.HardwareAddr([]byte{0x01, 0x23, 0x45, 0x67, 0x89, 0xab}),
- config: configMethodStatic{
- addresses: []net.IPNet{},
- nameservers: []net.IP{net.ParseIP("1.2.3.4")},
- routes: []route{},
- },
- }},
- },
- },
- {
- cfg: digitalocean.Interfaces{
- Private: []digitalocean.Interface{{MAC: "01:23:45:67:89:AB"}},
- },
- nss: []net.IP{net.ParseIP("1.2.3.4")},
- ifaces: []InterfaceGenerator{
- &physicalInterface{logicalInterface{
- hwaddr: net.HardwareAddr([]byte{0x01, 0x23, 0x45, 0x67, 0x89, 0xab}),
- config: configMethodStatic{
- addresses: []net.IPNet{},
- nameservers: []net.IP{},
- routes: []route{},
- },
- }},
- },
- },
- {
- cfg: digitalocean.Interfaces{
- Public: []digitalocean.Interface{{MAC: "bad"}},
- },
- err: mkInvalidMAC(),
- },
- {
- cfg: digitalocean.Interfaces{
- Private: []digitalocean.Interface{{MAC: "bad"}},
- },
- err: mkInvalidMAC(),
- },
- } {
- ifaces, err := parseInterfaces(tt.cfg, tt.nss)
- if !errorsEqual(tt.err, err) {
- t.Fatalf("bad error (%+v): want %q, got %q", tt.cfg, tt.err, err)
- }
- if !reflect.DeepEqual(tt.ifaces, ifaces) {
- t.Fatalf("bad interfaces (%+v): want %#v, got %#v", tt.cfg, tt.ifaces, ifaces)
- }
- }
-}
-
-func TestProcessDigitalOceanNetconf(t *testing.T) {
- for _, tt := range []struct {
- cfg digitalocean.Metadata
- ifaces []InterfaceGenerator
- err error
- }{
- {
- cfg: digitalocean.Metadata{
- DNS: digitalocean.DNS{
- Nameservers: []string{"bad"},
- },
- },
- err: errors.New("could not parse \"bad\" as nameserver IP address"),
- },
- {
- cfg: digitalocean.Metadata{
- Interfaces: digitalocean.Interfaces{
- Public: []digitalocean.Interface{
- digitalocean.Interface{
- IPv4: &digitalocean.Address{
- IPAddress: "bad",
- },
- },
- },
- },
- },
- err: errors.New("could not parse \"bad\" as IPv4 address"),
- },
- {
- ifaces: []InterfaceGenerator{},
- },
- } {
- ifaces, err := ProcessDigitalOceanNetconf(tt.cfg)
- if !errorsEqual(tt.err, err) {
- t.Fatalf("bad error (%q): want %q, got %q", tt.cfg, tt.err, err)
- }
- if !reflect.DeepEqual(tt.ifaces, ifaces) {
- t.Fatalf("bad interfaces (%q): want %#v, got %#v", tt.cfg, tt.ifaces, ifaces)
- }
- }
-}
-
-func errorsEqual(a, b error) bool {
- if a == nil && b == nil {
- return true
- }
- if (a != nil && b == nil) || (a == nil && b != nil) {
- return false
- }
- return (a.Error() == b.Error())
-}
diff --git a/vendor/github.com/coreos/coreos-cloudinit/network/interface_test.go b/vendor/github.com/coreos/coreos-cloudinit/network/interface_test.go
deleted file mode 100644
index 5cafc939..00000000
--- a/vendor/github.com/coreos/coreos-cloudinit/network/interface_test.go
+++ /dev/null
@@ -1,368 +0,0 @@
-// Copyright 2015 CoreOS, Inc.
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-package network
-
-import (
- "net"
- "reflect"
- "testing"
-)
-
-func TestInterfaceGenerators(t *testing.T) {
- for _, tt := range []struct {
- name string
- netdev string
- link string
- network string
- kind string
- iface InterfaceGenerator
- }{
- {
- name: "",
- network: "[Match]\nMACAddress=00:01:02:03:04:05\n\n[Network]\n",
- kind: "physical",
- iface: &physicalInterface{logicalInterface{
- hwaddr: net.HardwareAddr([]byte{0, 1, 2, 3, 4, 5}),
- }},
- },
- {
- name: "testname",
- network: "[Match]\nName=testname\n\n[Network]\nBond=testbond1\nVLAN=testvlan1\nVLAN=testvlan2\n",
- kind: "physical",
- iface: &physicalInterface{logicalInterface{
- name: "testname",
- children: []networkInterface{
- &bondInterface{logicalInterface: logicalInterface{name: "testbond1"}},
- &vlanInterface{logicalInterface: logicalInterface{name: "testvlan1"}, id: 1},
- &vlanInterface{logicalInterface: logicalInterface{name: "testvlan2"}, id: 1},
- },
- }},
- },
- {
- name: "testname",
- netdev: "[NetDev]\nKind=bond\nName=testname\n\n[Bond]\n",
- network: "[Match]\nName=testname\n\n[Network]\nBond=testbond1\nVLAN=testvlan1\nVLAN=testvlan2\nDHCP=true\n",
- kind: "bond",
- iface: &bondInterface{logicalInterface: logicalInterface{
- name: "testname",
- config: configMethodDHCP{},
- children: []networkInterface{
- &bondInterface{logicalInterface: logicalInterface{name: "testbond1"}},
- &vlanInterface{logicalInterface: logicalInterface{name: "testvlan1"}, id: 1},
- &vlanInterface{logicalInterface: logicalInterface{name: "testvlan2"}, id: 1},
- },
- }},
- },
- {
- name: "testname",
- netdev: "[NetDev]\nKind=vlan\nName=testname\n\n[VLAN]\nId=1\n",
- network: "[Match]\nName=testname\n\n[Network]\n",
- kind: "vlan",
- iface: &vlanInterface{logicalInterface{name: "testname"}, 1, ""},
- },
- {
- name: "testname",
- netdev: "[NetDev]\nKind=vlan\nName=testname\nMACAddress=00:01:02:03:04:05\n\n[VLAN]\nId=1\n",
- network: "[Match]\nName=testname\n\n[Network]\n",
- kind: "vlan",
- iface: &vlanInterface{logicalInterface{name: "testname", config: configMethodStatic{hwaddress: net.HardwareAddr([]byte{0, 1, 2, 3, 4, 5})}}, 1, ""},
- },
- {
- name: "testname",
- netdev: "[NetDev]\nKind=vlan\nName=testname\nMACAddress=00:01:02:03:04:05\n\n[VLAN]\nId=1\n",
- network: "[Match]\nName=testname\n\n[Network]\nDHCP=true\n",
- kind: "vlan",
- iface: &vlanInterface{logicalInterface{name: "testname", config: configMethodDHCP{hwaddress: net.HardwareAddr([]byte{0, 1, 2, 3, 4, 5})}}, 1, ""},
- },
- {
- name: "testname",
- netdev: "[NetDev]\nKind=vlan\nName=testname\n\n[VLAN]\nId=0\n",
- network: "[Match]\nName=testname\n\n[Network]\nDNS=8.8.8.8\n\n[Address]\nAddress=192.168.1.100/24\n\n[Route]\nDestination=0.0.0.0/0\nGateway=1.2.3.4\n",
- kind: "vlan",
- iface: &vlanInterface{logicalInterface: logicalInterface{
- name: "testname",
- config: configMethodStatic{
- addresses: []net.IPNet{{IP: []byte{192, 168, 1, 100}, Mask: []byte{255, 255, 255, 0}}},
- nameservers: []net.IP{[]byte{8, 8, 8, 8}},
- routes: []route{route{destination: net.IPNet{IP: []byte{0, 0, 0, 0}, Mask: []byte{0, 0, 0, 0}}, gateway: []byte{1, 2, 3, 4}}},
- },
- }},
- },
- } {
- if name := tt.iface.Name(); name != tt.name {
- t.Fatalf("bad name (%q): want %q, got %q", tt.iface, tt.name, name)
- }
- if netdev := tt.iface.Netdev(); netdev != tt.netdev {
- t.Fatalf("bad netdev (%q): want %q, got %q", tt.iface, tt.netdev, netdev)
- }
- if link := tt.iface.Link(); link != tt.link {
- t.Fatalf("bad link (%q): want %q, got %q", tt.iface, tt.link, link)
- }
- if network := tt.iface.Network(); network != tt.network {
- t.Fatalf("bad network (%q): want %q, got %q", tt.iface, tt.network, network)
- }
- if kind := tt.iface.Type(); kind != tt.kind {
- t.Fatalf("bad type (%q): want %q, got %q", tt.iface, tt.kind, kind)
- }
- }
-}
-
-func TestModprobeParams(t *testing.T) {
- for _, tt := range []struct {
- i InterfaceGenerator
- p string
- }{
- {
- i: &physicalInterface{},
- p: "",
- },
- {
- i: &vlanInterface{},
- p: "",
- },
- {
- i: &bondInterface{
- logicalInterface{},
- nil,
- map[string]string{
- "a": "1",
- "b": "2",
- },
- },
- p: "a=1 b=2",
- },
- } {
- if p := tt.i.ModprobeParams(); p != tt.p {
- t.Fatalf("bad params (%q): got %s, want %s", tt.i, p, tt.p)
- }
- }
-}
-
-func TestBuildInterfacesLo(t *testing.T) {
- stanzas := []*stanzaInterface{
- &stanzaInterface{
- name: "lo",
- kind: interfacePhysical,
- auto: false,
- configMethod: configMethodLoopback{},
- options: map[string][]string{},
- },
- }
- interfaces := buildInterfaces(stanzas)
- if len(interfaces) != 0 {
- t.FailNow()
- }
-}
-
-func TestBuildInterfacesBlindBond(t *testing.T) {
- stanzas := []*stanzaInterface{
- {
- name: "bond0",
- kind: interfaceBond,
- auto: false,
- configMethod: configMethodManual{},
- options: map[string][]string{
- "bond-slaves": []string{"eth0"},
- },
- },
- }
- interfaces := buildInterfaces(stanzas)
- bond0 := &bondInterface{
- logicalInterface{
- name: "bond0",
- config: configMethodManual{},
- children: []networkInterface{},
- configDepth: 0,
- },
- []string{"eth0"},
- map[string]string{},
- }
- eth0 := &physicalInterface{
- logicalInterface{
- name: "eth0",
- config: configMethodManual{},
- children: []networkInterface{bond0},
- configDepth: 1,
- },
- }
- expect := []InterfaceGenerator{bond0, eth0}
- if !reflect.DeepEqual(interfaces, expect) {
- t.FailNow()
- }
-}
-
-func TestBuildInterfacesBlindVLAN(t *testing.T) {
- stanzas := []*stanzaInterface{
- {
- name: "vlan0",
- kind: interfaceVLAN,
- auto: false,
- configMethod: configMethodManual{},
- options: map[string][]string{
- "id": []string{"0"},
- "raw_device": []string{"eth0"},
- },
- },
- }
- interfaces := buildInterfaces(stanzas)
- vlan0 := &vlanInterface{
- logicalInterface{
- name: "vlan0",
- config: configMethodManual{},
- children: []networkInterface{},
- configDepth: 0,
- },
- 0,
- "eth0",
- }
- eth0 := &physicalInterface{
- logicalInterface{
- name: "eth0",
- config: configMethodManual{},
- children: []networkInterface{vlan0},
- configDepth: 1,
- },
- }
- expect := []InterfaceGenerator{eth0, vlan0}
- if !reflect.DeepEqual(interfaces, expect) {
- t.FailNow()
- }
-}
-
-func TestBuildInterfaces(t *testing.T) {
- stanzas := []*stanzaInterface{
- &stanzaInterface{
- name: "eth0",
- kind: interfacePhysical,
- auto: false,
- configMethod: configMethodManual{},
- options: map[string][]string{},
- },
- &stanzaInterface{
- name: "bond0",
- kind: interfaceBond,
- auto: false,
- configMethod: configMethodManual{},
- options: map[string][]string{
- "bond-slaves": []string{"eth0"},
- "bond-mode": []string{"4"},
- "bond-miimon": []string{"100"},
- },
- },
- &stanzaInterface{
- name: "bond1",
- kind: interfaceBond,
- auto: false,
- configMethod: configMethodManual{},
- options: map[string][]string{
- "bond-slaves": []string{"bond0"},
- },
- },
- &stanzaInterface{
- name: "vlan0",
- kind: interfaceVLAN,
- auto: false,
- configMethod: configMethodManual{},
- options: map[string][]string{
- "id": []string{"0"},
- "raw_device": []string{"eth0"},
- },
- },
- &stanzaInterface{
- name: "vlan1",
- kind: interfaceVLAN,
- auto: false,
- configMethod: configMethodManual{},
- options: map[string][]string{
- "id": []string{"1"},
- "raw_device": []string{"bond0"},
- },
- },
- }
- interfaces := buildInterfaces(stanzas)
- vlan1 := &vlanInterface{
- logicalInterface{
- name: "vlan1",
- config: configMethodManual{},
- children: []networkInterface{},
- configDepth: 0,
- },
- 1,
- "bond0",
- }
- vlan0 := &vlanInterface{
- logicalInterface{
- name: "vlan0",
- config: configMethodManual{},
- children: []networkInterface{},
- configDepth: 0,
- },
- 0,
- "eth0",
- }
- bond1 := &bondInterface{
- logicalInterface{
- name: "bond1",
- config: configMethodManual{},
- children: []networkInterface{},
- configDepth: 0,
- },
- []string{"bond0"},
- map[string]string{},
- }
- bond0 := &bondInterface{
- logicalInterface{
- name: "bond0",
- config: configMethodManual{},
- children: []networkInterface{bond1, vlan1},
- configDepth: 1,
- },
- []string{"eth0"},
- map[string]string{
- "mode": "4",
- "miimon": "100",
- },
- }
- eth0 := &physicalInterface{
- logicalInterface{
- name: "eth0",
- config: configMethodManual{},
- children: []networkInterface{bond0, vlan0},
- configDepth: 2,
- },
- }
- expect := []InterfaceGenerator{bond0, bond1, eth0, vlan0, vlan1}
- if !reflect.DeepEqual(interfaces, expect) {
- t.FailNow()
- }
-}
-
-func TestFilename(t *testing.T) {
- for _, tt := range []struct {
- i logicalInterface
- f string
- }{
- {logicalInterface{name: "iface", configDepth: 0}, "00-iface"},
- {logicalInterface{name: "iface", configDepth: 9}, "09-iface"},
- {logicalInterface{name: "iface", configDepth: 10}, "0a-iface"},
- {logicalInterface{name: "iface", configDepth: 53}, "35-iface"},
- {logicalInterface{hwaddr: net.HardwareAddr([]byte{0x01, 0x23, 0x45, 0x67, 0x89, 0xab}), configDepth: 1}, "01-01:23:45:67:89:ab"},
- {logicalInterface{name: "iface", hwaddr: net.HardwareAddr([]byte{0x01, 0x23, 0x45, 0x67, 0x89, 0xab}), configDepth: 1}, "01-iface"},
- } {
- if tt.i.Filename() != tt.f {
- t.Fatalf("bad filename (%q): got %q, want %q", tt.i, tt.i.Filename(), tt.f)
- }
- }
-}
diff --git a/vendor/github.com/coreos/coreos-cloudinit/network/is_go15_false_test.go b/vendor/github.com/coreos/coreos-cloudinit/network/is_go15_false_test.go
deleted file mode 100644
index 85d5f0db..00000000
--- a/vendor/github.com/coreos/coreos-cloudinit/network/is_go15_false_test.go
+++ /dev/null
@@ -1,5 +0,0 @@
-// +build !go1.5
-
-package network
-
-const isGo15 = false
diff --git a/vendor/github.com/coreos/coreos-cloudinit/network/is_go15_true_test.go b/vendor/github.com/coreos/coreos-cloudinit/network/is_go15_true_test.go
deleted file mode 100644
index 953836de..00000000
--- a/vendor/github.com/coreos/coreos-cloudinit/network/is_go15_true_test.go
+++ /dev/null
@@ -1,5 +0,0 @@
-// +build go1.5
-
-package network
-
-const isGo15 = true
diff --git a/vendor/github.com/coreos/coreos-cloudinit/network/stanza_test.go b/vendor/github.com/coreos/coreos-cloudinit/network/stanza_test.go
deleted file mode 100644
index 9f476380..00000000
--- a/vendor/github.com/coreos/coreos-cloudinit/network/stanza_test.go
+++ /dev/null
@@ -1,582 +0,0 @@
-// Copyright 2015 CoreOS, Inc.
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-package network
-
-import (
- "net"
- "reflect"
- "strings"
- "testing"
-)
-
-func TestSplitStanzasNoParent(t *testing.T) {
- in := []string{"test"}
- e := "missing stanza start"
- _, err := splitStanzas(in)
- if err == nil || !strings.HasPrefix(err.Error(), e) {
- t.Fatalf("bad error for splitStanzas(%q): got %q, want %q", in, err, e)
- }
-}
-
-func TestBadParseStanzas(t *testing.T) {
- for in, e := range map[string]string{
- "": "missing stanza start",
- "iface": "malformed stanza start",
- "allow-?? unknown": "unknown stanza",
- } {
- _, err := parseStanzas([]string{in})
- if err == nil || !strings.HasPrefix(err.Error(), e) {
- t.Fatalf("bad error for parseStanzas(%q): got %q, want %q", in, err, e)
- }
-
- }
-}
-
-func TestBadParseInterfaceStanza(t *testing.T) {
- for _, tt := range []struct {
- in []string
- opts []string
- e string
- }{
- {[]string{}, nil, "incorrect number of attributes"},
- {[]string{"eth", "inet", "invalid"}, nil, "invalid config method"},
- {[]string{"eth", "inet", "static"}, []string{"address 192.168.1.100"}, "malformed static network config"},
- {[]string{"eth", "inet", "static"}, []string{"netmask 255.255.255.0"}, "malformed static network config"},
- {[]string{"eth", "inet", "static"}, []string{"address invalid", "netmask 255.255.255.0"}, "malformed static network config"},
- {[]string{"eth", "inet", "static"}, []string{"address 192.168.1.100", "netmask invalid"}, "malformed static network config"},
- {[]string{"eth", "inet", "static"}, []string{"address 192.168.1.100", "netmask 255.255.255.0", "hwaddress ether NotAnAddress"}, "malformed hwaddress option"},
- {[]string{"eth", "inet", "dhcp"}, []string{"hwaddress ether NotAnAddress"}, "malformed hwaddress option"},
- } {
- _, err := parseInterfaceStanza(tt.in, tt.opts)
- if err == nil || !strings.HasPrefix(err.Error(), tt.e) {
- t.Fatalf("bad error parsing interface stanza %q: got %q, want %q", tt.in, err.Error(), tt.e)
- }
- }
-}
-
-func TestBadParseVLANStanzas(t *testing.T) {
- conf := configMethodManual{}
- options := map[string][]string{}
- for _, in := range []string{"myvlan", "eth.vlan"} {
- _, err := parseVLANStanza(in, conf, nil, options)
- if err == nil || !strings.HasPrefix(err.Error(), "malformed vlan name") {
- t.Fatalf("did not error on bad vlan %q", in)
- }
- }
-}
-
-func TestSplitStanzas(t *testing.T) {
- expect := [][]string{
- {"auto lo"},
- {"iface eth1", "option: 1"},
- {"mapping"},
- {"allow-"},
- }
- lines := make([]string, 0, 5)
- for _, stanza := range expect {
- for _, line := range stanza {
- lines = append(lines, line)
- }
- }
-
- stanzas, err := splitStanzas(lines)
- if err != nil {
- t.FailNow()
- }
- for i, stanza := range stanzas {
- if len(stanza) != len(expect[i]) {
- t.FailNow()
- }
- for j, line := range stanza {
- if line != expect[i][j] {
- t.FailNow()
- }
- }
- }
-}
-
-func TestParseStanzaNil(t *testing.T) {
- defer func() {
- if r := recover(); r == nil {
- t.Fatal("parseStanza(nil) did not panic")
- }
- }()
- parseStanza(nil)
-}
-
-func TestParseStanzaSuccess(t *testing.T) {
- for _, in := range []string{
- "auto a",
- "iface a inet manual",
- } {
- if _, err := parseStanza([]string{in}); err != nil {
- t.Fatalf("unexpected error parsing stanza %q: %s", in, err)
- }
- }
-}
-
-func TestParseAutoStanza(t *testing.T) {
- interfaces := []string{"test", "attribute"}
- stanza, err := parseAutoStanza(interfaces, nil)
- if err != nil {
- t.Fatalf("unexpected error parsing auto stanza %q: %s", interfaces, err)
- }
- if !reflect.DeepEqual(stanza.interfaces, interfaces) {
- t.FailNow()
- }
-}
-
-func TestParseBondStanzaNoSlaves(t *testing.T) {
- bond, err := parseBondStanza("", nil, nil, map[string][]string{})
- if err != nil {
- t.FailNow()
- }
- if bond.options["bond-slaves"] != nil {
- t.FailNow()
- }
-}
-
-func TestParseBondStanza(t *testing.T) {
- conf := configMethodManual{}
- options := map[string][]string{
- "bond-slaves": []string{"1", "2"},
- }
- bond, err := parseBondStanza("test", conf, nil, options)
- if err != nil {
- t.FailNow()
- }
- if bond.name != "test" {
- t.FailNow()
- }
- if bond.kind != interfaceBond {
- t.FailNow()
- }
- if bond.configMethod != conf {
- t.FailNow()
- }
-}
-
-func TestParsePhysicalStanza(t *testing.T) {
- conf := configMethodManual{}
- options := map[string][]string{
- "a": []string{"1", "2"},
- "b": []string{"1"},
- }
- physical, err := parsePhysicalStanza("test", conf, nil, options)
- if err != nil {
- t.FailNow()
- }
- if physical.name != "test" {
- t.FailNow()
- }
- if physical.kind != interfacePhysical {
- t.FailNow()
- }
- if physical.configMethod != conf {
- t.FailNow()
- }
- if !reflect.DeepEqual(physical.options, options) {
- t.FailNow()
- }
-}
-
-func TestParseVLANStanzas(t *testing.T) {
- conf := configMethodManual{}
- options := map[string][]string{}
- for _, in := range []string{"vlan25", "eth.25"} {
- vlan, err := parseVLANStanza(in, conf, nil, options)
- if err != nil {
- t.Fatalf("unexpected error from parseVLANStanza(%q): %s", in, err)
- }
- if !reflect.DeepEqual(vlan.options["id"], []string{"25"}) {
- t.FailNow()
- }
- }
-}
-
-func TestParseInterfaceStanzaStaticAddress(t *testing.T) {
- options := []string{"address 192.168.1.100", "netmask 255.255.255.0"}
- expect := []net.IPNet{
- {
- IP: net.IPv4(192, 168, 1, 100),
- Mask: net.IPv4Mask(255, 255, 255, 0),
- },
- }
-
- iface, err := parseInterfaceStanza([]string{"eth", "inet", "static"}, options)
- if err != nil {
- t.FailNow()
- }
- static, ok := iface.configMethod.(configMethodStatic)
- if !ok {
- t.FailNow()
- }
- if !reflect.DeepEqual(static.addresses, expect) {
- t.FailNow()
- }
-}
-
-func TestParseInterfaceStanzaStaticGateway(t *testing.T) {
- options := []string{"address 192.168.1.100", "netmask 255.255.255.0", "gateway 192.168.1.1"}
- expect := []route{
- {
- destination: net.IPNet{
- IP: net.IPv4(0, 0, 0, 0),
- Mask: net.IPv4Mask(0, 0, 0, 0),
- },
- gateway: net.IPv4(192, 168, 1, 1),
- },
- }
-
- iface, err := parseInterfaceStanza([]string{"eth", "inet", "static"}, options)
- if err != nil {
- t.FailNow()
- }
- static, ok := iface.configMethod.(configMethodStatic)
- if !ok {
- t.FailNow()
- }
- if !reflect.DeepEqual(static.routes, expect) {
- t.FailNow()
- }
-}
-
-func TestParseInterfaceStanzaStaticDNS(t *testing.T) {
- options := []string{"address 192.168.1.100", "netmask 255.255.255.0", "dns-nameservers 192.168.1.10 192.168.1.11 192.168.1.12"}
- expect := []net.IP{
- net.IPv4(192, 168, 1, 10),
- net.IPv4(192, 168, 1, 11),
- net.IPv4(192, 168, 1, 12),
- }
- iface, err := parseInterfaceStanza([]string{"eth", "inet", "static"}, options)
- if err != nil {
- t.FailNow()
- }
- static, ok := iface.configMethod.(configMethodStatic)
- if !ok {
- t.FailNow()
- }
- if !reflect.DeepEqual(static.nameservers, expect) {
- t.FailNow()
- }
-}
-
-func TestBadParseInterfaceStanzasStaticPostUp(t *testing.T) {
- for _, in := range []string{
- "post-up invalid",
- "post-up route add",
- "post-up route add -net",
- "post-up route add gw",
- "post-up route add netmask",
- "gateway",
- "gateway 192.168.1.1 192.168.1.2",
- } {
- options := []string{"address 192.168.1.100", "netmask 255.255.255.0", in}
- iface, err := parseInterfaceStanza([]string{"eth", "inet", "static"}, options)
- if err != nil {
- t.Fatalf("parseInterfaceStanza with options %s got unexpected error", options)
- }
- static, ok := iface.configMethod.(configMethodStatic)
- if !ok {
- t.Fatalf("parseInterfaceStanza with options %s did not return configMethodStatic", options)
- }
- if len(static.routes) != 0 {
- t.Fatalf("parseInterfaceStanza with options %s did not return zero-length static routes", options)
- }
- }
-}
-
-func TestParseInterfaceStanzaStaticPostUp(t *testing.T) {
- for _, tt := range []struct {
- options []string
- expect []route
- }{
- {
- options: []string{
- "address 192.168.1.100",
- "netmask 255.255.255.0",
- "post-up route add gw 192.168.1.1 -net 192.168.1.0 netmask 255.255.255.0",
- },
- expect: []route{
- {
- destination: net.IPNet{
- IP: net.IPv4(192, 168, 1, 0),
- Mask: net.IPv4Mask(255, 255, 255, 0),
- },
- gateway: net.IPv4(192, 168, 1, 1),
- },
- },
- },
- {
- options: []string{
- "address 192.168.1.100",
- "netmask 255.255.255.0",
- "post-up route add gw 192.168.1.1 -net 192.168.1.0/24 || true",
- },
- expect: []route{
- {
- destination: func() net.IPNet {
- if _, net, err := net.ParseCIDR("192.168.1.0/24"); err == nil {
- return *net
- } else {
- panic(err)
- }
- }(),
- gateway: net.IPv4(192, 168, 1, 1),
- },
- },
- },
- } {
- iface, err := parseInterfaceStanza([]string{"eth", "inet", "static"}, tt.options)
- if err != nil {
- t.Fatalf("bad error (%+v): want nil, got %s\n", tt, err)
- }
- static, ok := iface.configMethod.(configMethodStatic)
- if !ok {
- t.Fatalf("bad config method (%+v): want configMethodStatic, got %T\n", tt, iface.configMethod)
- }
- if !reflect.DeepEqual(static.routes, tt.expect) {
- t.Fatalf("bad routes (%+v): want %#v, got %#v\n", tt, tt.expect, static.routes)
- }
- }
-}
-
-func TestParseInterfaceStanzaLoopback(t *testing.T) {
- iface, err := parseInterfaceStanza([]string{"eth", "inet", "loopback"}, nil)
- if err != nil {
- t.FailNow()
- }
- if _, ok := iface.configMethod.(configMethodLoopback); !ok {
- t.FailNow()
- }
-}
-
-func TestParseInterfaceStanzaManual(t *testing.T) {
- iface, err := parseInterfaceStanza([]string{"eth", "inet", "manual"}, nil)
- if err != nil {
- t.FailNow()
- }
- if _, ok := iface.configMethod.(configMethodManual); !ok {
- t.FailNow()
- }
-}
-
-func TestParseInterfaceStanzaDHCP(t *testing.T) {
- iface, err := parseInterfaceStanza([]string{"eth", "inet", "dhcp"}, nil)
- if err != nil {
- t.FailNow()
- }
- if _, ok := iface.configMethod.(configMethodDHCP); !ok {
- t.FailNow()
- }
-}
-
-func TestParseInterfaceStanzaPostUpOption(t *testing.T) {
- options := []string{
- "post-up",
- "post-up 1 2",
- "post-up 3 4",
- }
- iface, err := parseInterfaceStanza([]string{"eth", "inet", "manual"}, options)
- if err != nil {
- t.FailNow()
- }
- if !reflect.DeepEqual(iface.options["post-up"], []string{"1 2", "3 4"}) {
- t.Log(iface.options["post-up"])
- t.FailNow()
- }
-}
-
-func TestParseInterfaceStanzaPreDownOption(t *testing.T) {
- options := []string{
- "pre-down",
- "pre-down 3",
- "pre-down 4",
- }
- iface, err := parseInterfaceStanza([]string{"eth", "inet", "manual"}, options)
- if err != nil {
- t.FailNow()
- }
- if !reflect.DeepEqual(iface.options["pre-down"], []string{"3", "4"}) {
- t.Log(iface.options["pre-down"])
- t.FailNow()
- }
-}
-
-func TestParseInterfaceStanzaEmptyOption(t *testing.T) {
- options := []string{
- "test",
- }
- iface, err := parseInterfaceStanza([]string{"eth", "inet", "manual"}, options)
- if err != nil {
- t.FailNow()
- }
- if !reflect.DeepEqual(iface.options["test"], []string{}) {
- t.FailNow()
- }
-}
-
-func TestParseInterfaceStanzaOptions(t *testing.T) {
- options := []string{
- "test1 1",
- "test2 2 3",
- "test1 5 6",
- }
- iface, err := parseInterfaceStanza([]string{"eth", "inet", "manual"}, options)
- if err != nil {
- t.FailNow()
- }
- if !reflect.DeepEqual(iface.options["test1"], []string{"5", "6"}) {
- t.Log(iface.options["test1"])
- t.FailNow()
- }
- if !reflect.DeepEqual(iface.options["test2"], []string{"2", "3"}) {
- t.Log(iface.options["test2"])
- t.FailNow()
- }
-}
-
-func TestParseInterfaceStanzaHwaddress(t *testing.T) {
- for _, tt := range []struct {
- attr []string
- opt []string
- hw net.HardwareAddr
- }{
- {
- []string{"mybond", "inet", "dhcp"},
- []string{},
- nil,
- },
- {
- []string{"mybond", "inet", "dhcp"},
- []string{"hwaddress ether 00:01:02:03:04:05"},
- net.HardwareAddr([]byte{0, 1, 2, 3, 4, 5}),
- },
- {
- []string{"mybond", "inet", "static"},
- []string{"hwaddress ether 00:01:02:03:04:05", "address 192.168.1.100", "netmask 255.255.255.0"},
- net.HardwareAddr([]byte{0, 1, 2, 3, 4, 5}),
- },
- } {
- iface, err := parseInterfaceStanza(tt.attr, tt.opt)
- if err != nil {
- t.Fatalf("error in parseInterfaceStanza (%q, %q): %q", tt.attr, tt.opt, err)
- }
- switch c := iface.configMethod.(type) {
- case configMethodStatic:
- if !reflect.DeepEqual(c.hwaddress, tt.hw) {
- t.Fatalf("bad hwaddress (%q, %q): got %q, want %q", tt.attr, tt.opt, c.hwaddress, tt.hw)
- }
- case configMethodDHCP:
- if !reflect.DeepEqual(c.hwaddress, tt.hw) {
- t.Fatalf("bad hwaddress (%q, %q): got %q, want %q", tt.attr, tt.opt, c.hwaddress, tt.hw)
- }
- }
- }
-}
-
-func TestParseInterfaceStanzaBond(t *testing.T) {
- iface, err := parseInterfaceStanza([]string{"mybond", "inet", "manual"}, []string{"bond-slaves eth"})
- if err != nil {
- t.FailNow()
- }
- if iface.kind != interfaceBond {
- t.FailNow()
- }
-}
-
-func TestParseInterfaceStanzaVLANName(t *testing.T) {
- iface, err := parseInterfaceStanza([]string{"eth0.1", "inet", "manual"}, nil)
- if err != nil {
- t.FailNow()
- }
- if iface.kind != interfaceVLAN {
- t.FailNow()
- }
-}
-
-func TestParseInterfaceStanzaVLANOption(t *testing.T) {
- iface, err := parseInterfaceStanza([]string{"vlan1", "inet", "manual"}, []string{"vlan_raw_device eth"})
- if err != nil {
- t.FailNow()
- }
- if iface.kind != interfaceVLAN {
- t.FailNow()
- }
-}
-
-func TestParseStanzasNone(t *testing.T) {
- stanzas, err := parseStanzas(nil)
- if err != nil {
- t.FailNow()
- }
- if len(stanzas) != 0 {
- t.FailNow()
- }
-}
-
-func TestParseStanzas(t *testing.T) {
- lines := []string{
- "auto lo",
- "iface lo inet loopback",
- "iface eth1 inet manual",
- "iface eth2 inet manual",
- "iface eth3 inet manual",
- "auto eth1 eth3",
- }
- expect := []stanza{
- &stanzaAuto{
- interfaces: []string{"lo"},
- },
- &stanzaInterface{
- name: "lo",
- kind: interfacePhysical,
- auto: true,
- configMethod: configMethodLoopback{},
- options: map[string][]string{},
- },
- &stanzaInterface{
- name: "eth1",
- kind: interfacePhysical,
- auto: true,
- configMethod: configMethodManual{},
- options: map[string][]string{},
- },
- &stanzaInterface{
- name: "eth2",
- kind: interfacePhysical,
- auto: false,
- configMethod: configMethodManual{},
- options: map[string][]string{},
- },
- &stanzaInterface{
- name: "eth3",
- kind: interfacePhysical,
- auto: true,
- configMethod: configMethodManual{},
- options: map[string][]string{},
- },
- &stanzaAuto{
- interfaces: []string{"eth1", "eth3"},
- },
- }
- stanzas, err := parseStanzas(lines)
- if err != err {
- t.FailNow()
- }
- if !reflect.DeepEqual(stanzas, expect) {
- t.FailNow()
- }
-}
diff --git a/vendor/github.com/coreos/coreos-cloudinit/network/vmware_test.go b/vendor/github.com/coreos/coreos-cloudinit/network/vmware_test.go
deleted file mode 100644
index 010568c9..00000000
--- a/vendor/github.com/coreos/coreos-cloudinit/network/vmware_test.go
+++ /dev/null
@@ -1,361 +0,0 @@
-// Copyright 2015 CoreOS, Inc.
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-package network
-
-import (
- "errors"
- "net"
- "reflect"
- "testing"
-)
-
-func mustParseMac(mac net.HardwareAddr, err error) net.HardwareAddr {
- if err != nil {
- panic(err)
- }
- return mac
-}
-
-func TestProcessVMwareNetconf(t *testing.T) {
- tests := []struct {
- config map[string]string
-
- interfaces []InterfaceGenerator
- err error
- }{
- {},
- {
- config: map[string]string{
- "interface.0.dhcp": "yes",
- },
- interfaces: []InterfaceGenerator{
- &physicalInterface{logicalInterface{
- config: configMethodDHCP{},
- }},
- },
- },
- {
- config: map[string]string{
- "interface.0.mac": "00:11:22:33:44:55",
- "interface.0.dhcp": "yes",
- },
- interfaces: []InterfaceGenerator{
- &physicalInterface{logicalInterface{
- hwaddr: mustParseMac(net.ParseMAC("00:11:22:33:44:55")),
- config: configMethodDHCP{hwaddress: mustParseMac(net.ParseMAC("00:11:22:33:44:55"))},
- }},
- },
- },
- {
- config: map[string]string{
- "interface.0.name": "eth0",
- "interface.0.dhcp": "yes",
- },
- interfaces: []InterfaceGenerator{
- &physicalInterface{logicalInterface{
- name: "eth0",
- config: configMethodDHCP{},
- }},
- },
- },
- {
- config: map[string]string{
- "interface.0.mac": "00:11:22:33:44:55",
- "interface.0.ip.0.address": "10.0.0.100/24",
- "interface.0.route.0.gateway": "10.0.0.1",
- "interface.0.route.0.destination": "0.0.0.0/0",
- },
- interfaces: []InterfaceGenerator{
- &physicalInterface{logicalInterface{
- hwaddr: mustParseMac(net.ParseMAC("00:11:22:33:44:55")),
- config: configMethodStatic{
- hwaddress: mustParseMac(net.ParseMAC("00:11:22:33:44:55")),
- addresses: []net.IPNet{net.IPNet{IP: net.ParseIP("10.0.0.100"), Mask: net.CIDRMask(24, net.IPv4len*8)}},
- // I realize how upset you must be that I am shoving an IPMask into an IP. This is because net.IPv4zero is
- // actually a magic IPv6 address which ruins our equality check. What's that? Just use IP::Equal()? I'd rather
- // DeepEqual just handle that for me, but until Go gets operator overloading, we are stuck with this.
- routes: []route{route{
- destination: net.IPNet{IP: net.IP(net.CIDRMask(0, net.IPv4len*8)), Mask: net.CIDRMask(0, net.IPv4len*8)},
- gateway: net.ParseIP("10.0.0.1")},
- },
- },
- }},
- },
- },
- {
- config: map[string]string{
- "dns.server.0": "1.2.3.4",
- "dns.server.1": "5.6.7.8",
- "interface.0.mac": "00:11:22:33:44:55",
- "interface.0.ip.0.address": "10.0.0.100/24",
- "interface.0.ip.1.address": "10.0.0.101/24",
- "interface.0.route.0.gateway": "10.0.0.1",
- "interface.0.route.0.destination": "0.0.0.0/0",
- "interface.1.name": "eth0",
- "interface.1.ip.0.address": "10.0.1.100/24",
- "interface.1.route.0.gateway": "10.0.1.1",
- "interface.1.route.0.destination": "0.0.0.0/0",
- "interface.2.dhcp": "yes",
- "interface.2.mac": "00:11:22:33:44:77",
- },
- interfaces: []InterfaceGenerator{
- &physicalInterface{logicalInterface{
- hwaddr: mustParseMac(net.ParseMAC("00:11:22:33:44:55")),
- config: configMethodStatic{
- hwaddress: mustParseMac(net.ParseMAC("00:11:22:33:44:55")),
- addresses: []net.IPNet{
- net.IPNet{IP: net.ParseIP("10.0.0.100"), Mask: net.CIDRMask(24, net.IPv4len*8)},
- net.IPNet{IP: net.ParseIP("10.0.0.101"), Mask: net.CIDRMask(24, net.IPv4len*8)},
- },
- routes: []route{route{
- destination: net.IPNet{IP: net.IP(net.CIDRMask(0, net.IPv4len*8)), Mask: net.CIDRMask(0, net.IPv4len*8)},
- gateway: net.ParseIP("10.0.0.1")},
- },
- nameservers: []net.IP{net.ParseIP("1.2.3.4"), net.ParseIP("5.6.7.8")},
- },
- }},
- &physicalInterface{logicalInterface{
- name: "eth0",
- config: configMethodStatic{
- addresses: []net.IPNet{net.IPNet{IP: net.ParseIP("10.0.1.100"), Mask: net.CIDRMask(24, net.IPv4len*8)}},
- routes: []route{route{
- destination: net.IPNet{IP: net.IP(net.CIDRMask(0, net.IPv4len*8)), Mask: net.CIDRMask(0, net.IPv4len*8)},
- gateway: net.ParseIP("10.0.1.1")},
- },
- nameservers: []net.IP{net.ParseIP("1.2.3.4"), net.ParseIP("5.6.7.8")},
- },
- }},
- &physicalInterface{logicalInterface{
- hwaddr: mustParseMac(net.ParseMAC("00:11:22:33:44:77")),
- config: configMethodDHCP{hwaddress: mustParseMac(net.ParseMAC("00:11:22:33:44:77"))},
- }},
- },
- },
- {
- config: map[string]string{"dns.server.0": "test dns"},
- err: errors.New(`invalid nameserver: "test dns"`),
- },
- }
-
- for i, tt := range tests {
- interfaces, err := ProcessVMwareNetconf(tt.config)
- if !reflect.DeepEqual(tt.err, err) {
- t.Errorf("bad error (#%d): want %v, got %v", i, tt.err, err)
- }
- if !reflect.DeepEqual(tt.interfaces, interfaces) {
- t.Errorf("bad interfaces (#%d): want %#v, got %#v", i, tt.interfaces, interfaces)
- for _, iface := range tt.interfaces {
- t.Logf(" want: %#v", iface)
- }
- for _, iface := range interfaces {
- t.Logf(" got: %#v", iface)
- }
- }
- }
-}
-
-func TestProcessAddressConfig(t *testing.T) {
- tests := []struct {
- config map[string]string
- prefix string
-
- addresses []net.IPNet
- err error
- }{
- {},
-
- // static - ipv4
- {
- config: map[string]string{
- "ip.0.address": "10.0.0.100/24",
- },
-
- addresses: []net.IPNet{{IP: net.ParseIP("10.0.0.100"), Mask: net.CIDRMask(24, net.IPv4len*8)}},
- },
- {
- config: map[string]string{
- "this.is.a.prefix.ip.0.address": "10.0.0.100/24",
- },
- prefix: "this.is.a.prefix.",
-
- addresses: []net.IPNet{{IP: net.ParseIP("10.0.0.100"), Mask: net.CIDRMask(24, net.IPv4len*8)}},
- },
- {
- config: map[string]string{
- "ip.0.address": "10.0.0.100/24",
- "ip.1.address": "10.0.0.101/24",
- "ip.2.address": "10.0.0.102/24",
- },
-
- addresses: []net.IPNet{
- {IP: net.ParseIP("10.0.0.100"), Mask: net.CIDRMask(24, net.IPv4len*8)},
- {IP: net.ParseIP("10.0.0.101"), Mask: net.CIDRMask(24, net.IPv4len*8)},
- {IP: net.ParseIP("10.0.0.102"), Mask: net.CIDRMask(24, net.IPv4len*8)},
- },
- },
-
- // static - ipv6
- {
- config: map[string]string{
- "ip.0.address": "fe00::100/64",
- },
-
- addresses: []net.IPNet{{IP: net.ParseIP("fe00::100"), Mask: net.IPMask(net.CIDRMask(64, net.IPv6len*8))}},
- },
- {
- config: map[string]string{
- "ip.0.address": "fe00::100/64",
- "ip.1.address": "fe00::101/64",
- "ip.2.address": "fe00::102/64",
- },
-
- addresses: []net.IPNet{
- {IP: net.ParseIP("fe00::100"), Mask: net.CIDRMask(64, net.IPv6len*8)},
- {IP: net.ParseIP("fe00::101"), Mask: net.CIDRMask(64, net.IPv6len*8)},
- {IP: net.ParseIP("fe00::102"), Mask: net.CIDRMask(64, net.IPv6len*8)},
- },
- },
-
- // invalid
- {
- config: map[string]string{
- "ip.0.address": "test address",
- },
-
- err: errors.New(`invalid address: "test address"`),
- },
- }
-
- for i, tt := range tests {
- addresses, err := processAddressConfig(tt.config, tt.prefix)
- if !reflect.DeepEqual(tt.err, err) {
- t.Errorf("bad error (#%d): want %v, got %v", i, tt.err, err)
- }
- if err != nil {
- continue
- }
-
- if !reflect.DeepEqual(tt.addresses, addresses) {
- t.Errorf("bad addresses (#%d): want %#v, got %#v", i, tt.addresses, addresses)
- }
- }
-}
-
-func TestProcessRouteConfig(t *testing.T) {
- tests := []struct {
- config map[string]string
- prefix string
-
- routes []route
- err error
- }{
- {},
-
- {
- config: map[string]string{
- "route.0.gateway": "10.0.0.1",
- "route.0.destination": "0.0.0.0/0",
- },
-
- routes: []route{{destination: net.IPNet{IP: net.IP(net.CIDRMask(0, net.IPv4len*8)), Mask: net.CIDRMask(0, net.IPv4len*8)}, gateway: net.ParseIP("10.0.0.1")}},
- },
- {
- config: map[string]string{
- "this.is.a.prefix.route.0.gateway": "10.0.0.1",
- "this.is.a.prefix.route.0.destination": "0.0.0.0/0",
- },
- prefix: "this.is.a.prefix.",
-
- routes: []route{{destination: net.IPNet{IP: net.IP(net.CIDRMask(0, net.IPv4len*8)), Mask: net.CIDRMask(0, net.IPv4len*8)}, gateway: net.ParseIP("10.0.0.1")}},
- },
- {
- config: map[string]string{
- "route.0.gateway": "fe00::1",
- "route.0.destination": "::/0",
- },
-
- routes: []route{{destination: net.IPNet{IP: net.IPv6zero, Mask: net.IPMask(net.IPv6zero)}, gateway: net.ParseIP("fe00::1")}},
- },
-
- // invalid
- {
- config: map[string]string{
- "route.0.gateway": "test gateway",
- "route.0.destination": "0.0.0.0/0",
- },
-
- err: errors.New(`invalid gateway: "test gateway"`),
- },
- {
- config: map[string]string{
- "route.0.gateway": "10.0.0.1",
- "route.0.destination": "test destination",
- },
-
- err: &net.ParseError{Type: "CIDR address", Text: "test destination"},
- },
- }
-
- for i, tt := range tests {
- routes, err := processRouteConfig(tt.config, tt.prefix)
- if !reflect.DeepEqual(tt.err, err) {
- t.Errorf("bad error (#%d): want %v, got %v", i, tt.err, err)
- }
- if err != nil {
- continue
- }
-
- if !reflect.DeepEqual(tt.routes, routes) {
- t.Errorf("bad routes (#%d): want %#v, got %#v", i, tt.routes, routes)
- }
- }
-}
-
-func TestProcessDHCPConfig(t *testing.T) {
- tests := []struct {
- config map[string]string
- prefix string
-
- dhcp bool
- err error
- }{
- {},
-
- // prefix
- {config: map[string]string{"this.is.a.prefix.mac": ""}, prefix: "this.is.a.prefix.", dhcp: false},
- {config: map[string]string{"this.is.a.prefix.dhcp": "yes"}, prefix: "this.is.a.prefix.", dhcp: true},
-
- // dhcp
- {config: map[string]string{"dhcp": "yes"}, dhcp: true},
- {config: map[string]string{"dhcp": "no"}, dhcp: false},
-
- // invalid
- {config: map[string]string{"dhcp": "blah"}, err: errors.New(`invalid DHCP option: "blah"`)},
- }
-
- for i, tt := range tests {
- dhcp, err := processDHCPConfig(tt.config, tt.prefix)
- if !reflect.DeepEqual(tt.err, err) {
- t.Errorf("bad error (#%d): want %v, got %v", i, tt.err, err)
- }
- if err != nil {
- continue
- }
-
- if tt.dhcp != dhcp {
- t.Errorf("bad dhcp (#%d): want %v, got %v", i, tt.dhcp, dhcp)
- }
- }
-}
diff --git a/vendor/github.com/coreos/coreos-cloudinit/pkg/http_client_test.go b/vendor/github.com/coreos/coreos-cloudinit/pkg/http_client_test.go
deleted file mode 100644
index d581d94e..00000000
--- a/vendor/github.com/coreos/coreos-cloudinit/pkg/http_client_test.go
+++ /dev/null
@@ -1,154 +0,0 @@
-// Copyright 2015 CoreOS, Inc.
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-package pkg
-
-import (
- "fmt"
- "io"
- "math"
- "net/http"
- "net/http/httptest"
- "testing"
- "time"
-)
-
-func TestExpBackoff(t *testing.T) {
- duration := time.Millisecond
- max := time.Hour
- for i := 0; i < math.MaxUint16; i++ {
- duration = ExpBackoff(duration, max)
- if duration < 0 {
- t.Fatalf("duration too small: %v %v", duration, i)
- }
- if duration > max {
- t.Fatalf("duration too large: %v %v", duration, i)
- }
- }
-}
-
-// Test exponential backoff and that it continues retrying if a 5xx response is
-// received
-func TestGetURLExpBackOff(t *testing.T) {
- var expBackoffTests = []struct {
- count int
- body string
- }{
- {0, "number of attempts: 0"},
- {1, "number of attempts: 1"},
- {2, "number of attempts: 2"},
- }
- client := NewHttpClient()
-
- for i, tt := range expBackoffTests {
- mux := http.NewServeMux()
- count := 0
- mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
- if count == tt.count {
- io.WriteString(w, fmt.Sprintf("number of attempts: %d", count))
- return
- }
- count++
- http.Error(w, "", 500)
- })
- ts := httptest.NewServer(mux)
- defer ts.Close()
-
- data, err := client.GetRetry(ts.URL)
- if err != nil {
- t.Errorf("Test case %d produced error: %v", i, err)
- }
-
- if count != tt.count {
- t.Errorf("Test case %d failed: %d != %d", i, count, tt.count)
- }
-
- if string(data) != tt.body {
- t.Errorf("Test case %d failed: %s != %s", i, tt.body, data)
- }
- }
-}
-
-// Test that it stops retrying if a 4xx response comes back
-func TestGetURL4xx(t *testing.T) {
- client := NewHttpClient()
- retries := 0
- ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- retries++
- http.Error(w, "", 404)
- }))
- defer ts.Close()
-
- _, err := client.GetRetry(ts.URL)
- if err == nil {
- t.Errorf("Incorrect result\ngot: %s\nwant: %s", err.Error(), "Not found. HTTP status code: 404")
- }
-
- if retries > 1 {
- t.Errorf("Number of retries:\n%d\nExpected number of retries:\n%d", retries, 1)
- }
-}
-
-// Test that it fetches and returns user-data just fine
-func TestGetURL2xx(t *testing.T) {
- var cloudcfg = `
-#cloud-config
-coreos:
- oem:
- id: test
- name: CoreOS.box for Test
- version-id: %VERSION_ID%+%BUILD_ID%
- home-url: https://github.com/coreos/coreos-cloudinit
- bug-report-url: https://github.com/coreos/coreos-cloudinit
- update:
- reboot-strategy: best-effort
-`
-
- client := NewHttpClient()
- ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
- fmt.Fprint(w, cloudcfg)
- }))
- defer ts.Close()
-
- data, err := client.GetRetry(ts.URL)
- if err != nil {
- t.Errorf("Incorrect result\ngot: %v\nwant: %v", err, nil)
- }
-
- if string(data) != cloudcfg {
- t.Errorf("Incorrect result\ngot: %s\nwant: %s", string(data), cloudcfg)
- }
-}
-
-// Test attempt to fetching using malformed URL
-func TestGetMalformedURL(t *testing.T) {
- client := NewHttpClient()
-
- var tests = []struct {
- url string
- want string
- }{
- {"boo", "URL boo does not have a valid HTTP scheme. Skipping."},
- {"mailto://boo", "URL mailto://boo does not have a valid HTTP scheme. Skipping."},
- {"ftp://boo", "URL ftp://boo does not have a valid HTTP scheme. Skipping."},
- {"", "URL is empty. Skipping."},
- }
-
- for _, test := range tests {
- _, err := client.GetRetry(test.url)
- if err == nil || err.Error() != test.want {
- t.Errorf("Incorrect result\ngot: %v\nwant: %v", err, test.want)
- }
- }
-}
diff --git a/vendor/github.com/coreos/coreos-cloudinit/system/env_file_test.go b/vendor/github.com/coreos/coreos-cloudinit/system/env_file_test.go
deleted file mode 100644
index 5ec03640..00000000
--- a/vendor/github.com/coreos/coreos-cloudinit/system/env_file_test.go
+++ /dev/null
@@ -1,442 +0,0 @@
-// Copyright 2015 CoreOS, Inc.
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-package system
-
-import (
- "io/ioutil"
- "os"
- "path"
- "strings"
- "syscall"
- "testing"
-
- "github.com/coreos/coreos-cloudinit/config"
-)
-
-const (
- base = "# a file\nFOO=base\n\nBAR= hi there\n"
- baseNoNewline = "# a file\nFOO=base\n\nBAR= hi there"
- baseDos = "# a file\r\nFOO=base\r\n\r\nBAR= hi there\r\n"
- expectUpdate = "# a file\nFOO=test\n\nBAR= hi there\nNEW=a value\n"
- expectCreate = "FOO=test\nNEW=a value\n"
-)
-
-var (
- valueUpdate = map[string]string{
- "FOO": "test",
- "NEW": "a value",
- }
- valueNoop = map[string]string{
- "FOO": "base",
- }
- valueEmpty = map[string]string{}
- valueInvalid = map[string]string{
- "FOO-X": "test",
- }
-)
-
-func TestWriteEnvFileUpdate(t *testing.T) {
- dir, err := ioutil.TempDir(os.TempDir(), "coreos-cloudinit-")
- if err != nil {
- t.Fatalf("Unable to create tempdir: %v", err)
- }
- defer os.RemoveAll(dir)
-
- name := "foo.conf"
- fullPath := path.Join(dir, name)
- ioutil.WriteFile(fullPath, []byte(base), 0644)
-
- oldStat, err := os.Stat(fullPath)
- if err != nil {
- t.Fatalf("Unable to stat file: %v", err)
- }
-
- ef := EnvFile{
- File: &File{config.File{
- Path: name,
- }},
- Vars: valueUpdate,
- }
-
- err = WriteEnvFile(&ef, dir)
- if err != nil {
- t.Fatalf("WriteFile failed: %v", err)
- }
-
- contents, err := ioutil.ReadFile(fullPath)
- if err != nil {
- t.Fatalf("Unable to read expected file: %v", err)
- }
-
- if string(contents) != expectUpdate {
- t.Fatalf("File has incorrect contents: %q", contents)
- }
-
- newStat, err := os.Stat(fullPath)
- if err != nil {
- t.Fatalf("Unable to stat file: %v", err)
- }
-
- if oldStat.Sys().(*syscall.Stat_t).Ino == newStat.Sys().(*syscall.Stat_t).Ino {
- t.Fatalf("File was not replaced: %s", fullPath)
- }
-}
-
-func TestWriteEnvFileUpdateNoNewline(t *testing.T) {
- dir, err := ioutil.TempDir(os.TempDir(), "coreos-cloudinit-")
- if err != nil {
- t.Fatalf("Unable to create tempdir: %v", err)
- }
- defer os.RemoveAll(dir)
-
- name := "foo.conf"
- fullPath := path.Join(dir, name)
- ioutil.WriteFile(fullPath, []byte(baseNoNewline), 0644)
-
- oldStat, err := os.Stat(fullPath)
- if err != nil {
- t.Fatalf("Unable to stat file: %v", err)
- }
-
- ef := EnvFile{
- File: &File{config.File{
- Path: name,
- }},
- Vars: valueUpdate,
- }
-
- err = WriteEnvFile(&ef, dir)
- if err != nil {
- t.Fatalf("WriteFile failed: %v", err)
- }
-
- contents, err := ioutil.ReadFile(fullPath)
- if err != nil {
- t.Fatalf("Unable to read expected file: %v", err)
- }
-
- if string(contents) != expectUpdate {
- t.Fatalf("File has incorrect contents: %q", contents)
- }
-
- newStat, err := os.Stat(fullPath)
- if err != nil {
- t.Fatalf("Unable to stat file: %v", err)
- }
-
- if oldStat.Sys().(*syscall.Stat_t).Ino == newStat.Sys().(*syscall.Stat_t).Ino {
- t.Fatalf("File was not replaced: %s", fullPath)
- }
-}
-
-func TestWriteEnvFileCreate(t *testing.T) {
- dir, err := ioutil.TempDir(os.TempDir(), "coreos-cloudinit-")
- if err != nil {
- t.Fatalf("Unable to create tempdir: %v", err)
- }
- defer os.RemoveAll(dir)
-
- name := "foo.conf"
- fullPath := path.Join(dir, name)
-
- ef := EnvFile{
- File: &File{config.File{
- Path: name,
- }},
- Vars: valueUpdate,
- }
-
- err = WriteEnvFile(&ef, dir)
- if err != nil {
- t.Fatalf("WriteFile failed: %v", err)
- }
-
- contents, err := ioutil.ReadFile(fullPath)
- if err != nil {
- t.Fatalf("Unable to read expected file: %v", err)
- }
-
- if string(contents) != expectCreate {
- t.Fatalf("File has incorrect contents: %q", contents)
- }
-}
-
-func TestWriteEnvFileNoop(t *testing.T) {
- dir, err := ioutil.TempDir(os.TempDir(), "coreos-cloudinit-")
- if err != nil {
- t.Fatalf("Unable to create tempdir: %v", err)
- }
- defer os.RemoveAll(dir)
-
- name := "foo.conf"
- fullPath := path.Join(dir, name)
- ioutil.WriteFile(fullPath, []byte(base), 0644)
-
- oldStat, err := os.Stat(fullPath)
- if err != nil {
- t.Fatalf("Unable to stat file: %v", err)
- }
-
- ef := EnvFile{
- File: &File{config.File{
- Path: name,
- }},
- Vars: valueNoop,
- }
-
- err = WriteEnvFile(&ef, dir)
- if err != nil {
- t.Fatalf("WriteFile failed: %v", err)
- }
-
- contents, err := ioutil.ReadFile(fullPath)
- if err != nil {
- t.Fatalf("Unable to read expected file: %v", err)
- }
-
- if string(contents) != base {
- t.Fatalf("File has incorrect contents: %q", contents)
- }
-
- newStat, err := os.Stat(fullPath)
- if err != nil {
- t.Fatalf("Unable to stat file: %v", err)
- }
-
- if oldStat.Sys().(*syscall.Stat_t).Ino != newStat.Sys().(*syscall.Stat_t).Ino {
- t.Fatalf("File was replaced: %s", fullPath)
- }
-}
-
-func TestWriteEnvFileUpdateDos(t *testing.T) {
- dir, err := ioutil.TempDir(os.TempDir(), "coreos-cloudinit-")
- if err != nil {
- t.Fatalf("Unable to create tempdir: %v", err)
- }
- defer os.RemoveAll(dir)
-
- name := "foo.conf"
- fullPath := path.Join(dir, name)
- ioutil.WriteFile(fullPath, []byte(baseDos), 0644)
-
- oldStat, err := os.Stat(fullPath)
- if err != nil {
- t.Fatalf("Unable to stat file: %v", err)
- }
-
- ef := EnvFile{
- File: &File{config.File{
- Path: name,
- }},
- Vars: valueUpdate,
- }
-
- err = WriteEnvFile(&ef, dir)
- if err != nil {
- t.Fatalf("WriteFile failed: %v", err)
- }
-
- contents, err := ioutil.ReadFile(fullPath)
- if err != nil {
- t.Fatalf("Unable to read expected file: %v", err)
- }
-
- if string(contents) != expectUpdate {
- t.Fatalf("File has incorrect contents: %q", contents)
- }
-
- newStat, err := os.Stat(fullPath)
- if err != nil {
- t.Fatalf("Unable to stat file: %v", err)
- }
-
- if oldStat.Sys().(*syscall.Stat_t).Ino == newStat.Sys().(*syscall.Stat_t).Ino {
- t.Fatalf("File was not replaced: %s", fullPath)
- }
-}
-
-// A middle ground noop, values are unchanged but we did have a value.
-// Seems reasonable to rewrite the file in Unix format anyway.
-func TestWriteEnvFileDos2Unix(t *testing.T) {
- dir, err := ioutil.TempDir(os.TempDir(), "coreos-cloudinit-")
- if err != nil {
- t.Fatalf("Unable to create tempdir: %v", err)
- }
- defer os.RemoveAll(dir)
-
- name := "foo.conf"
- fullPath := path.Join(dir, name)
- ioutil.WriteFile(fullPath, []byte(baseDos), 0644)
-
- oldStat, err := os.Stat(fullPath)
- if err != nil {
- t.Fatalf("Unable to stat file: %v", err)
- }
-
- ef := EnvFile{
- File: &File{config.File{
- Path: name,
- }},
- Vars: valueNoop,
- }
-
- err = WriteEnvFile(&ef, dir)
- if err != nil {
- t.Fatalf("WriteFile failed: %v", err)
- }
-
- contents, err := ioutil.ReadFile(fullPath)
- if err != nil {
- t.Fatalf("Unable to read expected file: %v", err)
- }
-
- if string(contents) != base {
- t.Fatalf("File has incorrect contents: %q", contents)
- }
-
- newStat, err := os.Stat(fullPath)
- if err != nil {
- t.Fatalf("Unable to stat file: %v", err)
- }
-
- if oldStat.Sys().(*syscall.Stat_t).Ino == newStat.Sys().(*syscall.Stat_t).Ino {
- t.Fatalf("File was not replaced: %s", fullPath)
- }
-}
-
-// If it really is a noop (structure is empty) don't even do dos2unix
-func TestWriteEnvFileEmpty(t *testing.T) {
- dir, err := ioutil.TempDir(os.TempDir(), "coreos-cloudinit-")
- if err != nil {
- t.Fatalf("Unable to create tempdir: %v", err)
- }
- defer os.RemoveAll(dir)
-
- name := "foo.conf"
- fullPath := path.Join(dir, name)
- ioutil.WriteFile(fullPath, []byte(baseDos), 0644)
-
- oldStat, err := os.Stat(fullPath)
- if err != nil {
- t.Fatalf("Unable to stat file: %v", err)
- }
-
- ef := EnvFile{
- File: &File{config.File{
- Path: name,
- }},
- Vars: valueEmpty,
- }
-
- err = WriteEnvFile(&ef, dir)
- if err != nil {
- t.Fatalf("WriteFile failed: %v", err)
- }
-
- contents, err := ioutil.ReadFile(fullPath)
- if err != nil {
- t.Fatalf("Unable to read expected file: %v", err)
- }
-
- if string(contents) != baseDos {
- t.Fatalf("File has incorrect contents: %q", contents)
- }
-
- newStat, err := os.Stat(fullPath)
- if err != nil {
- t.Fatalf("Unable to stat file: %v", err)
- }
-
- if oldStat.Sys().(*syscall.Stat_t).Ino != newStat.Sys().(*syscall.Stat_t).Ino {
- t.Fatalf("File was replaced: %s", fullPath)
- }
-}
-
-// no point in creating empty files
-func TestWriteEnvFileEmptyNoCreate(t *testing.T) {
- dir, err := ioutil.TempDir(os.TempDir(), "coreos-cloudinit-")
- if err != nil {
- t.Fatalf("Unable to create tempdir: %v", err)
- }
- defer os.RemoveAll(dir)
-
- name := "foo.conf"
- fullPath := path.Join(dir, name)
-
- ef := EnvFile{
- File: &File{config.File{
- Path: name,
- }},
- Vars: valueEmpty,
- }
-
- err = WriteEnvFile(&ef, dir)
- if err != nil {
- t.Fatalf("WriteFile failed: %v", err)
- }
-
- contents, err := ioutil.ReadFile(fullPath)
- if err == nil {
- t.Fatalf("File has incorrect contents: %q", contents)
- } else if !os.IsNotExist(err) {
- t.Fatalf("Unexpected error while reading file: %v", err)
- }
-}
-
-func TestWriteEnvFilePermFailure(t *testing.T) {
- dir, err := ioutil.TempDir(os.TempDir(), "coreos-cloudinit-")
- if err != nil {
- t.Fatalf("Unable to create tempdir: %v", err)
- }
- defer os.RemoveAll(dir)
-
- name := "foo.conf"
- fullPath := path.Join(dir, name)
- ioutil.WriteFile(fullPath, []byte(base), 0000)
-
- ef := EnvFile{
- File: &File{config.File{
- Path: name,
- }},
- Vars: valueUpdate,
- }
-
- err = WriteEnvFile(&ef, dir)
- if !os.IsPermission(err) {
- t.Fatalf("Not a pemission denied error: %v", err)
- }
-}
-
-func TestWriteEnvFileNameFailure(t *testing.T) {
- dir, err := ioutil.TempDir(os.TempDir(), "coreos-cloudinit-")
- if err != nil {
- t.Fatalf("Unable to create tempdir: %v", err)
- }
- defer os.RemoveAll(dir)
-
- name := "foo.conf"
-
- ef := EnvFile{
- File: &File{config.File{
- Path: name,
- }},
- Vars: valueInvalid,
- }
-
- err = WriteEnvFile(&ef, dir)
- if err == nil || !strings.HasPrefix(err.Error(), "Invalid name") {
- t.Fatalf("Not an invalid name error: %v", err)
- }
-}
diff --git a/vendor/github.com/coreos/coreos-cloudinit/system/env_test.go b/vendor/github.com/coreos/coreos-cloudinit/system/env_test.go
deleted file mode 100644
index 9d62aed5..00000000
--- a/vendor/github.com/coreos/coreos-cloudinit/system/env_test.go
+++ /dev/null
@@ -1,69 +0,0 @@
-// Copyright 2015 CoreOS, Inc.
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-package system
-
-import (
- "testing"
-)
-
-func TestServiceContents(t *testing.T) {
- tests := []struct {
- Config interface{}
- Contents string
- }{
- {
- struct{}{},
- "",
- },
- {
- struct {
- A string `env:"A"`
- B int `env:"B"`
- C bool `env:"C"`
- D float64 `env:"D"`
- }{
- "hi", 1, true, 0.12345,
- },
- `[Service]
-Environment="A=hi"
-Environment="B=1"
-Environment="C=true"
-Environment="D=0.12345"
-`,
- },
- {
- struct {
- A float64 `env:"A"`
- B float64 `env:"B"`
- C float64 `env:"C"`
- D float64 `env:"D"`
- }{
- 0.000001, 1, 0.9999999, 0.1,
- },
- `[Service]
-Environment="A=1e-06"
-Environment="B=1"
-Environment="C=0.9999999"
-Environment="D=0.1"
-`,
- },
- }
-
- for _, tt := range tests {
- if c := serviceContents(tt.Config); c != tt.Contents {
- t.Errorf("bad contents (%+v): want %q, got %q", tt, tt.Contents, c)
- }
- }
-}
diff --git a/vendor/github.com/coreos/coreos-cloudinit/system/etc_hosts_test.go b/vendor/github.com/coreos/coreos-cloudinit/system/etc_hosts_test.go
deleted file mode 100644
index e5efd7c4..00000000
--- a/vendor/github.com/coreos/coreos-cloudinit/system/etc_hosts_test.go
+++ /dev/null
@@ -1,60 +0,0 @@
-// Copyright 2015 CoreOS, Inc.
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-package system
-
-import (
- "fmt"
- "os"
- "reflect"
- "testing"
-
- "github.com/coreos/coreos-cloudinit/config"
-)
-
-func TestEtcdHostsFile(t *testing.T) {
- hostname, err := os.Hostname()
- if err != nil {
- panic(err)
- }
-
- for _, tt := range []struct {
- config config.EtcHosts
- file *File
- err error
- }{
- {
- "invalid",
- nil,
- fmt.Errorf("Invalid option to manage_etc_hosts"),
- },
- {
- "localhost",
- &File{config.File{
- Content: fmt.Sprintf("127.0.0.1 %s\n", hostname),
- Path: "etc/hosts",
- RawFilePermissions: "0644",
- }},
- nil,
- },
- } {
- file, err := EtcHosts{tt.config}.File()
- if !reflect.DeepEqual(tt.err, err) {
- t.Errorf("bad error (%q): want %q, got %q", tt.config, tt.err, err)
- }
- if !reflect.DeepEqual(tt.file, file) {
- t.Errorf("bad units (%q): want %#v, got %#v", tt.config, tt.file, file)
- }
- }
-}
diff --git a/vendor/github.com/coreos/coreos-cloudinit/system/etcd_test.go b/vendor/github.com/coreos/coreos-cloudinit/system/etcd_test.go
deleted file mode 100644
index 5fc17f02..00000000
--- a/vendor/github.com/coreos/coreos-cloudinit/system/etcd_test.go
+++ /dev/null
@@ -1,79 +0,0 @@
-// Copyright 2015 CoreOS, Inc.
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-package system
-
-import (
- "reflect"
- "testing"
-
- "github.com/coreos/coreos-cloudinit/config"
-)
-
-func TestEtcdUnits(t *testing.T) {
- for _, tt := range []struct {
- config config.Etcd
- units []Unit
- }{
- {
- config.Etcd{},
- []Unit{{config.Unit{
- Name: "etcd.service",
- Runtime: true,
- DropIns: []config.UnitDropIn{{Name: "20-cloudinit.conf"}},
- }}},
- },
- {
- config.Etcd{
- Discovery: "http://disco.example.com/foobar",
- PeerBindAddr: "127.0.0.1:7002",
- },
- []Unit{{config.Unit{
- Name: "etcd.service",
- Runtime: true,
- DropIns: []config.UnitDropIn{{
- Name: "20-cloudinit.conf",
- Content: `[Service]
-Environment="ETCD_DISCOVERY=http://disco.example.com/foobar"
-Environment="ETCD_PEER_BIND_ADDR=127.0.0.1:7002"
-`,
- }},
- }}},
- },
- {
- config.Etcd{
- Name: "node001",
- Discovery: "http://disco.example.com/foobar",
- PeerBindAddr: "127.0.0.1:7002",
- },
- []Unit{{config.Unit{
- Name: "etcd.service",
- Runtime: true,
- DropIns: []config.UnitDropIn{{
- Name: "20-cloudinit.conf",
- Content: `[Service]
-Environment="ETCD_DISCOVERY=http://disco.example.com/foobar"
-Environment="ETCD_NAME=node001"
-Environment="ETCD_PEER_BIND_ADDR=127.0.0.1:7002"
-`,
- }},
- }}},
- },
- } {
- units := Etcd{tt.config}.Units()
- if !reflect.DeepEqual(tt.units, units) {
- t.Errorf("bad units (%+v): want %#v, got %#v", tt.config, tt.units, units)
- }
- }
-}
diff --git a/vendor/github.com/coreos/coreos-cloudinit/system/file_test.go b/vendor/github.com/coreos/coreos-cloudinit/system/file_test.go
deleted file mode 100644
index f68ec2fa..00000000
--- a/vendor/github.com/coreos/coreos-cloudinit/system/file_test.go
+++ /dev/null
@@ -1,253 +0,0 @@
-// Copyright 2015 CoreOS, Inc.
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-package system
-
-import (
- "io/ioutil"
- "os"
- "path"
- "testing"
-
- "github.com/coreos/coreos-cloudinit/config"
-)
-
-func TestWriteFileUnencodedContent(t *testing.T) {
- dir, err := ioutil.TempDir(os.TempDir(), "coreos-cloudinit-")
- if err != nil {
- t.Fatalf("Unable to create tempdir: %v", err)
- }
- defer os.RemoveAll(dir)
-
- fn := "foo"
- fullPath := path.Join(dir, fn)
-
- wf := File{config.File{
- Path: fn,
- Content: "bar",
- RawFilePermissions: "0644",
- }}
-
- path, err := WriteFile(&wf, dir)
- if err != nil {
- t.Fatalf("Processing of WriteFile failed: %v", err)
- } else if path != fullPath {
- t.Fatalf("WriteFile returned bad path: want %s, got %s", fullPath, path)
- }
-
- fi, err := os.Stat(fullPath)
- if err != nil {
- t.Fatalf("Unable to stat file: %v", err)
- }
-
- if fi.Mode() != os.FileMode(0644) {
- t.Errorf("File has incorrect mode: %v", fi.Mode())
- }
-
- contents, err := ioutil.ReadFile(fullPath)
- if err != nil {
- t.Fatalf("Unable to read expected file: %v", err)
- }
-
- if string(contents) != "bar" {
- t.Fatalf("File has incorrect contents")
- }
-}
-
-func TestWriteFileInvalidPermission(t *testing.T) {
- dir, err := ioutil.TempDir(os.TempDir(), "coreos-cloudinit-")
- if err != nil {
- t.Fatalf("Unable to create tempdir: %v", err)
- }
- defer os.RemoveAll(dir)
-
- wf := File{config.File{
- Path: path.Join(dir, "tmp", "foo"),
- Content: "bar",
- RawFilePermissions: "pants",
- }}
-
- if _, err := WriteFile(&wf, dir); err == nil {
- t.Fatalf("Expected error to be raised when writing file with invalid permission")
- }
-}
-
-func TestDecimalFilePermissions(t *testing.T) {
- dir, err := ioutil.TempDir(os.TempDir(), "coreos-cloudinit-")
- if err != nil {
- t.Fatalf("Unable to create tempdir: %v", err)
- }
- defer os.RemoveAll(dir)
-
- fn := "foo"
- fullPath := path.Join(dir, fn)
-
- wf := File{config.File{
- Path: fn,
- RawFilePermissions: "744",
- }}
-
- path, err := WriteFile(&wf, dir)
- if err != nil {
- t.Fatalf("Processing of WriteFile failed: %v", err)
- } else if path != fullPath {
- t.Fatalf("WriteFile returned bad path: want %s, got %s", fullPath, path)
- }
-
- fi, err := os.Stat(fullPath)
- if err != nil {
- t.Fatalf("Unable to stat file: %v", err)
- }
-
- if fi.Mode() != os.FileMode(0744) {
- t.Errorf("File has incorrect mode: %v", fi.Mode())
- }
-}
-
-func TestWriteFilePermissions(t *testing.T) {
- dir, err := ioutil.TempDir(os.TempDir(), "coreos-cloudinit-")
- if err != nil {
- t.Fatalf("Unable to create tempdir: %v", err)
- }
- defer os.RemoveAll(dir)
-
- fn := "foo"
- fullPath := path.Join(dir, fn)
-
- wf := File{config.File{
- Path: fn,
- RawFilePermissions: "0755",
- }}
-
- path, err := WriteFile(&wf, dir)
- if err != nil {
- t.Fatalf("Processing of WriteFile failed: %v", err)
- } else if path != fullPath {
- t.Fatalf("WriteFile returned bad path: want %s, got %s", fullPath, path)
- }
-
- fi, err := os.Stat(fullPath)
- if err != nil {
- t.Fatalf("Unable to stat file: %v", err)
- }
-
- if fi.Mode() != os.FileMode(0755) {
- t.Errorf("File has incorrect mode: %v", fi.Mode())
- }
-}
-
-func TestWriteFileEncodedContent(t *testing.T) {
- dir, err := ioutil.TempDir(os.TempDir(), "coreos-cloudinit-")
- if err != nil {
- t.Fatalf("Unable to create tempdir: %v", err)
- }
- defer os.RemoveAll(dir)
-
- //all of these decode to "bar"
- content_tests := map[string]string{
- "base64": "YmFy",
- "b64": "YmFy",
- "gz": "\x1f\x8b\x08\x08w\x14\x87T\x02\xffok\x00KJ,\x02\x00\xaa\x8c\xffv\x03\x00\x00\x00",
- "gzip": "\x1f\x8b\x08\x08w\x14\x87T\x02\xffok\x00KJ,\x02\x00\xaa\x8c\xffv\x03\x00\x00\x00",
- "gz+base64": "H4sIABMVh1QAA0tKLAIAqoz/dgMAAAA=",
- "gzip+base64": "H4sIABMVh1QAA0tKLAIAqoz/dgMAAAA=",
- "gz+b64": "H4sIABMVh1QAA0tKLAIAqoz/dgMAAAA=",
- "gzip+b64": "H4sIABMVh1QAA0tKLAIAqoz/dgMAAAA=",
- }
-
- for encoding, content := range content_tests {
- fullPath := path.Join(dir, encoding)
-
- wf := File{config.File{
- Path: encoding,
- Encoding: encoding,
- Content: content,
- RawFilePermissions: "0644",
- }}
-
- path, err := WriteFile(&wf, dir)
- if err != nil {
- t.Fatalf("Processing of WriteFile failed: %v", err)
- } else if path != fullPath {
- t.Fatalf("WriteFile returned bad path: want %s, got %s", fullPath, path)
- }
-
- fi, err := os.Stat(fullPath)
- if err != nil {
- t.Fatalf("Unable to stat file: %v", err)
- }
-
- if fi.Mode() != os.FileMode(0644) {
- t.Errorf("File has incorrect mode: %v", fi.Mode())
- }
-
- contents, err := ioutil.ReadFile(fullPath)
- if err != nil {
- t.Fatalf("Unable to read expected file: %v", err)
- }
-
- if string(contents) != "bar" {
- t.Fatalf("File has incorrect contents: '%s'", contents)
- }
- }
-}
-
-func TestWriteFileInvalidEncodedContent(t *testing.T) {
- dir, err := ioutil.TempDir(os.TempDir(), "coreos-cloudinit-")
- if err != nil {
- t.Fatalf("Unable to create tempdir: %v", err)
- }
- defer os.RemoveAll(dir)
-
- content_encodings := []string{
- "base64",
- "b64",
- "gz",
- "gzip",
- "gz+base64",
- "gzip+base64",
- "gz+b64",
- "gzip+b64",
- }
-
- for _, encoding := range content_encodings {
- wf := File{config.File{
- Path: path.Join(dir, "tmp", "foo"),
- Content: "@&*#%invalid data*@&^#*&",
- Encoding: encoding,
- }}
-
- if _, err := WriteFile(&wf, dir); err == nil {
- t.Fatalf("Expected error to be raised when writing file with encoding")
- }
- }
-}
-
-func TestWriteFileUnknownEncodedContent(t *testing.T) {
- dir, err := ioutil.TempDir(os.TempDir(), "coreos-cloudinit-")
- if err != nil {
- t.Fatalf("Unable to create tempdir: %v", err)
- }
- defer os.RemoveAll(dir)
-
- wf := File{config.File{
- Path: path.Join(dir, "tmp", "foo"),
- Content: "",
- Encoding: "no-such-encoding",
- }}
-
- if _, err := WriteFile(&wf, dir); err == nil {
- t.Fatalf("Expected error to be raised when writing file with encoding")
- }
-}
diff --git a/vendor/github.com/coreos/coreos-cloudinit/system/flannel_test.go b/vendor/github.com/coreos/coreos-cloudinit/system/flannel_test.go
deleted file mode 100644
index 7bc9f7f6..00000000
--- a/vendor/github.com/coreos/coreos-cloudinit/system/flannel_test.go
+++ /dev/null
@@ -1,76 +0,0 @@
-// Copyright 2015 CoreOS, Inc.
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-package system
-
-import (
- "reflect"
- "testing"
-
- "github.com/coreos/coreos-cloudinit/config"
-)
-
-func TestFlannelEnvVars(t *testing.T) {
- for _, tt := range []struct {
- config config.Flannel
- contents string
- }{
- {
- config.Flannel{},
- "",
- },
- {
- config.Flannel{
- EtcdEndpoints: "http://12.34.56.78:4001",
- EtcdPrefix: "/coreos.com/network/tenant1",
- },
- `FLANNELD_ETCD_ENDPOINTS=http://12.34.56.78:4001
-FLANNELD_ETCD_PREFIX=/coreos.com/network/tenant1`,
- },
- } {
- out := Flannel{tt.config}.envVars()
- if out != tt.contents {
- t.Errorf("bad contents (%+v): want %q, got %q", tt, tt.contents, out)
- }
- }
-}
-
-func TestFlannelFile(t *testing.T) {
- for _, tt := range []struct {
- config config.Flannel
- file *File
- }{
- {
- config.Flannel{},
- nil,
- },
- {
- config.Flannel{
- EtcdEndpoints: "http://12.34.56.78:4001",
- EtcdPrefix: "/coreos.com/network/tenant1",
- },
- &File{config.File{
- Path: "run/flannel/options.env",
- RawFilePermissions: "0644",
- Content: `FLANNELD_ETCD_ENDPOINTS=http://12.34.56.78:4001
-FLANNELD_ETCD_PREFIX=/coreos.com/network/tenant1`,
- }},
- },
- } {
- file, _ := Flannel{tt.config}.File()
- if !reflect.DeepEqual(tt.file, file) {
- t.Errorf("bad units (%q): want %#v, got %#v", tt.config, tt.file, file)
- }
- }
-}
diff --git a/vendor/github.com/coreos/coreos-cloudinit/system/fleet_test.go b/vendor/github.com/coreos/coreos-cloudinit/system/fleet_test.go
deleted file mode 100644
index dfe7c3f5..00000000
--- a/vendor/github.com/coreos/coreos-cloudinit/system/fleet_test.go
+++ /dev/null
@@ -1,58 +0,0 @@
-// Copyright 2015 CoreOS, Inc.
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-package system
-
-import (
- "reflect"
- "testing"
-
- "github.com/coreos/coreos-cloudinit/config"
-)
-
-func TestFleetUnits(t *testing.T) {
- for _, tt := range []struct {
- config config.Fleet
- units []Unit
- }{
- {
- config.Fleet{},
- []Unit{{config.Unit{
- Name: "fleet.service",
- Runtime: true,
- DropIns: []config.UnitDropIn{{Name: "20-cloudinit.conf"}},
- }}},
- },
- {
- config.Fleet{
- PublicIP: "12.34.56.78",
- },
- []Unit{{config.Unit{
- Name: "fleet.service",
- Runtime: true,
- DropIns: []config.UnitDropIn{{
- Name: "20-cloudinit.conf",
- Content: `[Service]
-Environment="FLEET_PUBLIC_IP=12.34.56.78"
-`,
- }},
- }}},
- },
- } {
- units := Fleet{tt.config}.Units()
- if !reflect.DeepEqual(units, tt.units) {
- t.Errorf("bad units (%+v): want %#v, got %#v", tt.config, tt.units, units)
- }
- }
-}
diff --git a/vendor/github.com/coreos/coreos-cloudinit/system/locksmith_test.go b/vendor/github.com/coreos/coreos-cloudinit/system/locksmith_test.go
deleted file mode 100644
index 6d7d9887..00000000
--- a/vendor/github.com/coreos/coreos-cloudinit/system/locksmith_test.go
+++ /dev/null
@@ -1,58 +0,0 @@
-// Copyright 2015 CoreOS, Inc.
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-package system
-
-import (
- "reflect"
- "testing"
-
- "github.com/coreos/coreos-cloudinit/config"
-)
-
-func TestLocksmithUnits(t *testing.T) {
- for _, tt := range []struct {
- config config.Locksmith
- units []Unit
- }{
- {
- config.Locksmith{},
- []Unit{{config.Unit{
- Name: "locksmithd.service",
- Runtime: true,
- DropIns: []config.UnitDropIn{{Name: "20-cloudinit.conf"}},
- }}},
- },
- {
- config.Locksmith{
- Endpoint: "12.34.56.78:4001",
- },
- []Unit{{config.Unit{
- Name: "locksmithd.service",
- Runtime: true,
- DropIns: []config.UnitDropIn{{
- Name: "20-cloudinit.conf",
- Content: `[Service]
-Environment="LOCKSMITHD_ENDPOINT=12.34.56.78:4001"
-`,
- }},
- }}},
- },
- } {
- units := Locksmith{tt.config}.Units()
- if !reflect.DeepEqual(units, tt.units) {
- t.Errorf("bad units (%+v): want %#v, got %#v", tt.config, tt.units, units)
- }
- }
-}
diff --git a/vendor/github.com/coreos/coreos-cloudinit/system/oem_test.go b/vendor/github.com/coreos/coreos-cloudinit/system/oem_test.go
deleted file mode 100644
index 38661201..00000000
--- a/vendor/github.com/coreos/coreos-cloudinit/system/oem_test.go
+++ /dev/null
@@ -1,61 +0,0 @@
-// Copyright 2015 CoreOS, Inc.
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-package system
-
-import (
- "reflect"
- "testing"
-
- "github.com/coreos/coreos-cloudinit/config"
-)
-
-func TestOEMFile(t *testing.T) {
- for _, tt := range []struct {
- config config.OEM
- file *File
- }{
- {
- config.OEM{},
- nil,
- },
- {
- config.OEM{
- ID: "rackspace",
- Name: "Rackspace Cloud Servers",
- VersionID: "168.0.0",
- HomeURL: "https://www.rackspace.com/cloud/servers/",
- BugReportURL: "https://github.com/coreos/coreos-overlay",
- },
- &File{config.File{
- Path: "etc/oem-release",
- RawFilePermissions: "0644",
- Content: `ID=rackspace
-VERSION_ID=168.0.0
-NAME="Rackspace Cloud Servers"
-HOME_URL="https://www.rackspace.com/cloud/servers/"
-BUG_REPORT_URL="https://github.com/coreos/coreos-overlay"
-`,
- }},
- },
- } {
- file, err := OEM{tt.config}.File()
- if err != nil {
- t.Errorf("bad error (%q): want %v, got %q", tt.config, nil, err)
- }
- if !reflect.DeepEqual(tt.file, file) {
- t.Errorf("bad file (%q): want %#v, got %#v", tt.config, tt.file, file)
- }
- }
-}
diff --git a/vendor/github.com/coreos/coreos-cloudinit/system/systemd_test.go b/vendor/github.com/coreos/coreos-cloudinit/system/systemd_test.go
deleted file mode 100644
index 82052abc..00000000
--- a/vendor/github.com/coreos/coreos-cloudinit/system/systemd_test.go
+++ /dev/null
@@ -1,280 +0,0 @@
-// Copyright 2015 CoreOS, Inc.
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-package system
-
-import (
- "fmt"
- "io/ioutil"
- "os"
- "path"
- "testing"
-
- "github.com/coreos/coreos-cloudinit/config"
-)
-
-func TestPlaceUnit(t *testing.T) {
- tests := []config.Unit{
- {
- Name: "50-eth0.network",
- Runtime: true,
- Content: "[Match]\nName=eth47\n\n[Network]\nAddress=10.209.171.177/19\n",
- },
- {
- Name: "media-state.mount",
- Content: "[Mount]\nWhat=/dev/sdb1\nWhere=/media/state\n",
- },
- }
-
- for _, tt := range tests {
- dir, err := ioutil.TempDir(os.TempDir(), "coreos-cloudinit-")
- if err != nil {
- panic(fmt.Sprintf("Unable to create tempdir: %v", err))
- }
-
- u := Unit{tt}
- sd := &systemd{dir}
-
- if err := sd.PlaceUnit(u); err != nil {
- t.Fatalf("PlaceUnit(): bad error (%+v): want nil, got %s", tt, err)
- }
-
- fi, err := os.Stat(u.Destination(dir))
- if err != nil {
- t.Fatalf("Stat(): bad error (%+v): want nil, got %s", tt, err)
- }
-
- if mode := fi.Mode(); mode != os.FileMode(0644) {
- t.Errorf("bad filemode (%+v): want %v, got %v", tt, os.FileMode(0644), mode)
- }
-
- c, err := ioutil.ReadFile(u.Destination(dir))
- if err != nil {
- t.Fatalf("ReadFile(): bad error (%+v): want nil, got %s", tt, err)
- }
-
- if string(c) != tt.Content {
- t.Errorf("bad contents (%+v): want %q, got %q", tt, tt.Content, string(c))
- }
-
- os.RemoveAll(dir)
- }
-}
-
-func TestPlaceUnitDropIn(t *testing.T) {
- tests := []config.Unit{
- {
- Name: "false.service",
- Runtime: true,
- DropIns: []config.UnitDropIn{
- {
- Name: "00-true.conf",
- Content: "[Service]\nExecStart=\nExecStart=/usr/bin/true\n",
- },
- },
- },
- {
- Name: "true.service",
- DropIns: []config.UnitDropIn{
- {
- Name: "00-false.conf",
- Content: "[Service]\nExecStart=\nExecStart=/usr/bin/false\n",
- },
- },
- },
- }
-
- for _, tt := range tests {
- dir, err := ioutil.TempDir(os.TempDir(), "coreos-cloudinit-")
- if err != nil {
- panic(fmt.Sprintf("Unable to create tempdir: %v", err))
- }
-
- u := Unit{tt}
- sd := &systemd{dir}
-
- if err := sd.PlaceUnitDropIn(u, u.DropIns[0]); err != nil {
- t.Fatalf("PlaceUnit(): bad error (%+v): want nil, got %s", tt, err)
- }
-
- fi, err := os.Stat(u.DropInDestination(dir, u.DropIns[0]))
- if err != nil {
- t.Fatalf("Stat(): bad error (%+v): want nil, got %s", tt, err)
- }
-
- if mode := fi.Mode(); mode != os.FileMode(0644) {
- t.Errorf("bad filemode (%+v): want %v, got %v", tt, os.FileMode(0644), mode)
- }
-
- c, err := ioutil.ReadFile(u.DropInDestination(dir, u.DropIns[0]))
- if err != nil {
- t.Fatalf("ReadFile(): bad error (%+v): want nil, got %s", tt, err)
- }
-
- if string(c) != u.DropIns[0].Content {
- t.Errorf("bad contents (%+v): want %q, got %q", tt, u.DropIns[0].Content, string(c))
- }
-
- os.RemoveAll(dir)
- }
-}
-
-func TestMachineID(t *testing.T) {
- dir, err := ioutil.TempDir(os.TempDir(), "coreos-cloudinit-")
- if err != nil {
- t.Fatalf("Unable to create tempdir: %v", err)
- }
- defer os.RemoveAll(dir)
-
- os.Mkdir(path.Join(dir, "etc"), os.FileMode(0755))
- ioutil.WriteFile(path.Join(dir, "etc", "machine-id"), []byte("node007\n"), os.FileMode(0444))
-
- if MachineID(dir) != "node007" {
- t.Fatalf("File has incorrect contents")
- }
-}
-
-func TestMaskUnit(t *testing.T) {
- dir, err := ioutil.TempDir(os.TempDir(), "coreos-cloudinit-")
- if err != nil {
- t.Fatalf("Unable to create tempdir: %v", err)
- }
- defer os.RemoveAll(dir)
-
- sd := &systemd{dir}
-
- // Ensure mask works with units that do not currently exist
- uf := Unit{config.Unit{Name: "foo.service"}}
- if err := sd.MaskUnit(uf); err != nil {
- t.Fatalf("Unable to mask new unit: %v", err)
- }
- fooPath := path.Join(dir, "etc", "systemd", "system", "foo.service")
- fooTgt, err := os.Readlink(fooPath)
- if err != nil {
- t.Fatal("Unable to read link", err)
- }
- if fooTgt != "/dev/null" {
- t.Fatal("unit not masked, got unit target", fooTgt)
- }
-
- // Ensure mask works with unit files that already exist
- ub := Unit{config.Unit{Name: "bar.service"}}
- barPath := path.Join(dir, "etc", "systemd", "system", "bar.service")
- if _, err := os.Create(barPath); err != nil {
- t.Fatalf("Error creating new unit file: %v", err)
- }
- if err := sd.MaskUnit(ub); err != nil {
- t.Fatalf("Unable to mask existing unit: %v", err)
- }
- barTgt, err := os.Readlink(barPath)
- if err != nil {
- t.Fatal("Unable to read link", err)
- }
- if barTgt != "/dev/null" {
- t.Fatal("unit not masked, got unit target", barTgt)
- }
-}
-
-func TestUnmaskUnit(t *testing.T) {
- dir, err := ioutil.TempDir(os.TempDir(), "coreos-cloudinit-")
- if err != nil {
- t.Fatalf("Unable to create tempdir: %v", err)
- }
- defer os.RemoveAll(dir)
-
- sd := &systemd{dir}
-
- nilUnit := Unit{config.Unit{Name: "null.service"}}
- if err := sd.UnmaskUnit(nilUnit); err != nil {
- t.Errorf("unexpected error from unmasking nonexistent unit: %v", err)
- }
-
- uf := Unit{config.Unit{Name: "foo.service", Content: "[Service]\nExecStart=/bin/true"}}
- dst := uf.Destination(dir)
- if err := os.MkdirAll(path.Dir(dst), os.FileMode(0755)); err != nil {
- t.Fatalf("Unable to create unit directory: %v", err)
- }
- if _, err := os.Create(dst); err != nil {
- t.Fatalf("Unable to write unit file: %v", err)
- }
-
- if err := ioutil.WriteFile(dst, []byte(uf.Content), 700); err != nil {
- t.Fatalf("Unable to write unit file: %v", err)
- }
- if err := sd.UnmaskUnit(uf); err != nil {
- t.Errorf("unmask of non-empty unit returned unexpected error: %v", err)
- }
- got, _ := ioutil.ReadFile(dst)
- if string(got) != uf.Content {
- t.Errorf("unmask of non-empty unit mutated unit contents unexpectedly")
- }
-
- ub := Unit{config.Unit{Name: "bar.service"}}
- dst = ub.Destination(dir)
- if err := os.Symlink("/dev/null", dst); err != nil {
- t.Fatalf("Unable to create masked unit: %v", err)
- }
- if err := sd.UnmaskUnit(ub); err != nil {
- t.Errorf("unmask of unit returned unexpected error: %v", err)
- }
- if _, err := os.Stat(dst); !os.IsNotExist(err) {
- t.Errorf("expected %s to not exist after unmask, but got err: %s", dst, err)
- }
-}
-
-func TestNullOrEmpty(t *testing.T) {
- dir, err := ioutil.TempDir(os.TempDir(), "coreos-cloudinit-")
- if err != nil {
- t.Fatalf("Unable to create tempdir: %v", err)
- }
- defer os.RemoveAll(dir)
-
- non := path.Join(dir, "does_not_exist")
- ne, err := nullOrEmpty(non)
- if !os.IsNotExist(err) {
- t.Errorf("nullOrEmpty on nonexistent file returned bad error: %v", err)
- }
- if ne {
- t.Errorf("nullOrEmpty returned true unxpectedly")
- }
-
- regEmpty := path.Join(dir, "regular_empty_file")
- _, err = os.Create(regEmpty)
- if err != nil {
- t.Fatalf("Unable to create tempfile: %v", err)
- }
- gotNe, gotErr := nullOrEmpty(regEmpty)
- if !gotNe || gotErr != nil {
- t.Errorf("nullOrEmpty of regular empty file returned %t, %v - want true, nil", gotNe, gotErr)
- }
-
- reg := path.Join(dir, "regular_file")
- if err := ioutil.WriteFile(reg, []byte("asdf"), 700); err != nil {
- t.Fatalf("Unable to create tempfile: %v", err)
- }
- gotNe, gotErr = nullOrEmpty(reg)
- if gotNe || gotErr != nil {
- t.Errorf("nullOrEmpty of regular file returned %t, %v - want false, nil", gotNe, gotErr)
- }
-
- null := path.Join(dir, "null")
- if err := os.Symlink(os.DevNull, null); err != nil {
- t.Fatalf("Unable to create /dev/null link: %s", err)
- }
- gotNe, gotErr = nullOrEmpty(null)
- if !gotNe || gotErr != nil {
- t.Errorf("nullOrEmpty of null symlink returned %t, %v - want true, nil", gotNe, gotErr)
- }
-
-}
diff --git a/vendor/github.com/coreos/coreos-cloudinit/system/unit_test.go b/vendor/github.com/coreos/coreos-cloudinit/system/unit_test.go
deleted file mode 100644
index c995b592..00000000
--- a/vendor/github.com/coreos/coreos-cloudinit/system/unit_test.go
+++ /dev/null
@@ -1,136 +0,0 @@
-// Copyright 2015 CoreOS, Inc.
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-package system
-
-import (
- "testing"
-
- "github.com/coreos/coreos-cloudinit/config"
-)
-
-func TestType(t *testing.T) {
- tests := []struct {
- name string
-
- typ string
- }{
- {},
- {"test.service", "service"},
- {"hello", ""},
- {"lots.of.dots", "dots"},
- }
-
- for _, tt := range tests {
- u := Unit{config.Unit{
- Name: tt.name,
- }}
- if typ := u.Type(); tt.typ != typ {
- t.Errorf("bad type (%+v): want %q, got %q", tt, tt.typ, typ)
- }
- }
-}
-
-func TestGroup(t *testing.T) {
- tests := []struct {
- name string
-
- group string
- }{
- {"test.service", "system"},
- {"test.link", "network"},
- {"test.network", "network"},
- {"test.netdev", "network"},
- {"test.conf", "system"},
- }
-
- for _, tt := range tests {
- u := Unit{config.Unit{
- Name: tt.name,
- }}
- if group := u.Group(); tt.group != group {
- t.Errorf("bad group (%+v): want %q, got %q", tt, tt.group, group)
- }
- }
-}
-
-func TestDestination(t *testing.T) {
- tests := []struct {
- root string
- name string
- runtime bool
-
- destination string
- }{
- {
- root: "/some/dir",
- name: "foobar.service",
- destination: "/some/dir/etc/systemd/system/foobar.service",
- },
- {
- root: "/some/dir",
- name: "foobar.service",
- runtime: true,
- destination: "/some/dir/run/systemd/system/foobar.service",
- },
- }
-
- for _, tt := range tests {
- u := Unit{config.Unit{
- Name: tt.name,
- Runtime: tt.runtime,
- }}
- if d := u.Destination(tt.root); tt.destination != d {
- t.Errorf("bad destination (%+v): want %q, got %q", tt, tt.destination, d)
- }
- }
-}
-
-func TestDropInDestination(t *testing.T) {
- tests := []struct {
- root string
- unitName string
- dropInName string
- runtime bool
-
- destination string
- }{
- {
- root: "/some/dir",
- unitName: "foo.service",
- dropInName: "bar.conf",
- destination: "/some/dir/etc/systemd/system/foo.service.d/bar.conf",
- },
- {
- root: "/some/dir",
- unitName: "foo.service",
- dropInName: "bar.conf",
- runtime: true,
- destination: "/some/dir/run/systemd/system/foo.service.d/bar.conf",
- },
- }
-
- for _, tt := range tests {
- u := Unit{config.Unit{
- Name: tt.unitName,
- Runtime: tt.runtime,
- DropIns: []config.UnitDropIn{{
- Name: tt.dropInName,
- }},
- }}
- if d := u.DropInDestination(tt.root, u.DropIns[0]); tt.destination != d {
- t.Errorf("bad destination (%+v): want %q, got %q", tt, tt.destination, d)
- }
- }
-}
diff --git a/vendor/github.com/coreos/coreos-cloudinit/system/update_test.go b/vendor/github.com/coreos/coreos-cloudinit/system/update_test.go
deleted file mode 100644
index ae3972b8..00000000
--- a/vendor/github.com/coreos/coreos-cloudinit/system/update_test.go
+++ /dev/null
@@ -1,161 +0,0 @@
-// Copyright 2015 CoreOS, Inc.
-//
-// Licensed under the Apache License, Version 2.0 (the "License");
-// you may not use this file except in compliance with the License.
-// You may obtain a copy of the License at
-//
-// http://www.apache.org/licenses/LICENSE-2.0
-//
-// Unless required by applicable law or agreed to in writing, software
-// distributed under the License is distributed on an "AS IS" BASIS,
-// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-// See the License for the specific language governing permissions and
-// limitations under the License.
-
-package system
-
-import (
- "io"
- "reflect"
- "strings"
- "testing"
-
- "github.com/coreos/coreos-cloudinit/config"
-)
-
-func testReadConfig(config string) func() (io.Reader, error) {
- return func() (io.Reader, error) {
- return strings.NewReader(config), nil
- }
-}
-
-func TestUpdateUnits(t *testing.T) {
- for _, tt := range []struct {
- config config.Update
- units []Unit
- err error
- }{
- {
- config: config.Update{},
- },
- {
- config: config.Update{Group: "master", Server: "http://foo.com"},
- units: []Unit{{config.Unit{
- Name: "update-engine.service",
- Command: "restart",
- }}},
- },
- {
- config: config.Update{RebootStrategy: "best-effort"},
- units: []Unit{{config.Unit{
- Name: "locksmithd.service",
- Command: "restart",
- Runtime: true,
- }}},
- },
- {
- config: config.Update{RebootStrategy: "etcd-lock"},
- units: []Unit{{config.Unit{
- Name: "locksmithd.service",
- Command: "restart",
- Runtime: true,
- }}},
- },
- {
- config: config.Update{RebootStrategy: "reboot"},
- units: []Unit{{config.Unit{
- Name: "locksmithd.service",
- Command: "restart",
- Runtime: true,
- }}},
- },
- {
- config: config.Update{RebootStrategy: "off"},
- units: []Unit{{config.Unit{
- Name: "locksmithd.service",
- Command: "stop",
- Runtime: true,
- Mask: true,
- }}},
- },
- } {
- units := Update{Update: tt.config, ReadConfig: testReadConfig("")}.Units()
- if !reflect.DeepEqual(tt.units, units) {
- t.Errorf("bad units (%q): want %#v, got %#v", tt.config, tt.units, units)
- }
- }
-}
-
-func TestUpdateFile(t *testing.T) {
- for _, tt := range []struct {
- config config.Update
- orig string
- file *File
- err error
- }{
- {
- config: config.Update{},
- },
- {
- config: config.Update{RebootStrategy: "wizzlewazzle"},
- err: &config.ErrorValid{Value: "wizzlewazzle", Field: "RebootStrategy", Valid: "^(best-effort|etcd-lock|reboot|off)$"},
- },
- {
- config: config.Update{Group: "master", Server: "http://foo.com"},
- file: &File{config.File{
- Content: "GROUP=master\nSERVER=http://foo.com\n",
- Path: "etc/coreos/update.conf",
- RawFilePermissions: "0644",
- }},
- },
- {
- config: config.Update{RebootStrategy: "best-effort"},
- file: &File{config.File{
- Content: "REBOOT_STRATEGY=best-effort\n",
- Path: "etc/coreos/update.conf",
- RawFilePermissions: "0644",
- }},
- },
- {
- config: config.Update{RebootStrategy: "etcd-lock"},
- file: &File{config.File{
- Content: "REBOOT_STRATEGY=etcd-lock\n",
- Path: "etc/coreos/update.conf",
- RawFilePermissions: "0644",
- }},
- },
- {
- config: config.Update{RebootStrategy: "reboot"},
- file: &File{config.File{
- Content: "REBOOT_STRATEGY=reboot\n",
- Path: "etc/coreos/update.conf",
- RawFilePermissions: "0644",
- }},
- },
- {
- config: config.Update{RebootStrategy: "off"},
- file: &File{config.File{
- Content: "REBOOT_STRATEGY=off\n",
- Path: "etc/coreos/update.conf",
- RawFilePermissions: "0644",
- }},
- },
- {
- config: config.Update{RebootStrategy: "etcd-lock"},
- orig: "SERVER=https://example.com\nGROUP=thegroupc\nREBOOT_STRATEGY=awesome",
- file: &File{config.File{
- Content: "SERVER=https://example.com\nGROUP=thegroupc\nREBOOT_STRATEGY=etcd-lock\n",
- Path: "etc/coreos/update.conf",
- RawFilePermissions: "0644",
- }},
- },
- } {
- file, err := Update{Update: tt.config, ReadConfig: testReadConfig(tt.orig)}.File()
- if !reflect.DeepEqual(tt.err, err) {
- t.Errorf("bad error (%q): want %q, got %q", tt.config, tt.err, err)
- }
- if !reflect.DeepEqual(tt.file, file) {
- t.Errorf("bad units (%q): want %#v, got %#v", tt.config, tt.file, file)
- }
- }
-}
diff --git a/vendor/github.com/coreos/go-systemd/dbus/dbus_test.go b/vendor/github.com/coreos/go-systemd/dbus/dbus_test.go
deleted file mode 100644
index 2e80f73e..00000000
--- a/vendor/github.com/coreos/go-systemd/dbus/dbus_test.go
+++ /dev/null
@@ -1,41 +0,0 @@
-/*
-Copyright 2013 CoreOS Inc.
-
-Licensed under the Apache License, Version 2.0 (the "License");
-you may not use this file except in compliance with the License.
-You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS,
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-See the License for the specific language governing permissions and
-limitations under the License.
-*/
-
-package dbus
-
-import (
- "testing"
-)
-
-// TestObjectPath ensures path encoding of the systemd rules works.
-func TestObjectPath(t *testing.T) {
- input := "/silly-path/to@a/unit..service"
- output := ObjectPath(input)
- expected := "/silly_2dpath/to_40a/unit_2e_2eservice"
-
- if string(output) != expected {
- t.Fatalf("Output '%s' did not match expected '%s'", output, expected)
- }
-}
-
-// TestNew ensures that New() works without errors.
-func TestNew(t *testing.T) {
- _, err := New()
-
- if err != nil {
- t.Fatal(err)
- }
-}
diff --git a/vendor/github.com/coreos/go-systemd/dbus/methods_test.go b/vendor/github.com/coreos/go-systemd/dbus/methods_test.go
deleted file mode 100644
index 9e2f2232..00000000
--- a/vendor/github.com/coreos/go-systemd/dbus/methods_test.go
+++ /dev/null
@@ -1,314 +0,0 @@
-/*
-Copyright 2013 CoreOS Inc.
-
-Licensed under the Apache License, Version 2.0 (the "License");
-you may not use this file except in compliance with the License.
-You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
-Unless required by applicable law or agreed to in writing, software
-distributed under the License is distributed on an "AS IS" BASIS,
-WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-See the License for the specific language governing permissions and
-limitations under the License.
-*/
-
-package dbus
-
-import (
- "fmt"
- "github.com/guelfey/go.dbus"
- "math/rand"
- "os"
- "path/filepath"
- "reflect"
- "testing"
-)
-
-func setupConn(t *testing.T) *Conn {
- conn, err := New()
- if err != nil {
- t.Fatal(err)
- }
-
- return conn
-}
-
-func setupUnit(target string, conn *Conn, t *testing.T) {
- // Blindly stop the unit in case it is running
- conn.StopUnit(target, "replace")
-
- // Blindly remove the symlink in case it exists
- targetRun := filepath.Join("/run/systemd/system/", target)
- err := os.Remove(targetRun)
-
- // 1. Enable the unit
- abs, err := filepath.Abs("../fixtures/" + target)
- if err != nil {
- t.Fatal(err)
- }
-
- fixture := []string{abs}
-
- install, changes, err := conn.EnableUnitFiles(fixture, true, true)
- if err != nil {
- t.Fatal(err)
- }
-
- if install != false {
- t.Fatal("Install was true")
- }
-
- if len(changes) < 1 {
- t.Fatalf("Expected one change, got %v", changes)
- }
-
- if changes[0].Filename != targetRun {
- t.Fatal("Unexpected target filename")
- }
-}
-
-// Ensure that basic unit starting and stopping works.
-func TestStartStopUnit(t *testing.T) {
- target := "start-stop.service"
- conn := setupConn(t)
-
- setupUnit(target, conn, t)
-
- // 2. Start the unit
- job, err := conn.StartUnit(target, "replace")
- if err != nil {
- t.Fatal(err)
- }
-
- if job != "done" {
- t.Fatal("Job is not done, %v", job)
- }
-
- units, err := conn.ListUnits()
-
- var unit *UnitStatus
- for _, u := range units {
- if u.Name == target {
- unit = &u
- }
- }
-
- if unit == nil {
- t.Fatalf("Test unit not found in list")
- }
-
- if unit.ActiveState != "active" {
- t.Fatalf("Test unit not active")
- }
-
- // 3. Stop the unit
- job, err = conn.StopUnit(target, "replace")
- if err != nil {
- t.Fatal(err)
- }
-
- units, err = conn.ListUnits()
-
- unit = nil
- for _, u := range units {
- if u.Name == target {
- unit = &u
- }
- }
-
- if unit != nil {
- t.Fatalf("Test unit found in list, should be stopped")
- }
-}
-
-// Enables a unit and then immediately tears it down
-func TestEnableDisableUnit(t *testing.T) {
- target := "enable-disable.service"
- conn := setupConn(t)
-
- setupUnit(target, conn, t)
-
- abs, err := filepath.Abs("../fixtures/" + target)
- if err != nil {
- t.Fatal(err)
- }
-
- path := filepath.Join("/run/systemd/system/", target)
-
- // 2. Disable the unit
- changes, err := conn.DisableUnitFiles([]string{abs}, true)
- if err != nil {
- t.Fatal(err)
- }
-
- if len(changes) != 1 {
- t.Fatalf("Changes should include the path, %v", changes)
- }
- if changes[0].Filename != path {
- t.Fatalf("Change should include correct filename, %+v", changes[0])
- }
- if changes[0].Destination != "" {
- t.Fatalf("Change destination should be empty, %+v", changes[0])
- }
-}
-
-// TestGetUnitProperties reads the `-.mount` which should exist on all systemd
-// systems and ensures that one of its properties is valid.
-func TestGetUnitProperties(t *testing.T) {
- conn := setupConn(t)
-
- unit := "-.mount"
-
- info, err := conn.GetUnitProperties(unit)
- if err != nil {
- t.Fatal(err)
- }
-
- names := info["Wants"].([]string)
-
- if len(names) < 1 {
- t.Fatal("/ is unwanted")
- }
-
- if names[0] != "system.slice" {
- t.Fatal("unexpected wants for /")
- }
-
- prop, err := conn.GetUnitProperty(unit, "Wants")
- if err != nil {
- t.Fatal(err)
- }
-
- if prop.Name != "Wants" {
- t.Fatal("unexpected property name")
- }
-
- val := prop.Value.Value().([]string)
- if !reflect.DeepEqual(val, names) {
- t.Fatal("unexpected property value")
- }
-}
-
-// TestGetUnitPropertiesRejectsInvalidName attempts to get the properties for a
-// unit with an invalid name. This test should be run with --test.timeout set,
-// as a fail will manifest as GetUnitProperties hanging indefinitely.
-func TestGetUnitPropertiesRejectsInvalidName(t *testing.T) {
- conn := setupConn(t)
-
- unit := "//invalid#$^/"
-
- _, err := conn.GetUnitProperties(unit)
- if err == nil {
- t.Fatal("Expected an error, got nil")
- }
-
- _, err = conn.GetUnitProperty(unit, "Wants")
- if err == nil {
- t.Fatal("Expected an error, got nil")
- }
-}
-
-// TestSetUnitProperties changes a cgroup setting on the `tmp.mount`
-// which should exist on all systemd systems and ensures that the
-// property was set.
-func TestSetUnitProperties(t *testing.T) {
- conn := setupConn(t)
-
- unit := "tmp.mount"
-
- if err := conn.SetUnitProperties(unit, true, Property{"CPUShares", dbus.MakeVariant(uint64(1023))}); err != nil {
- t.Fatal(err)
- }
-
- info, err := conn.GetUnitTypeProperties(unit, "Mount")
- if err != nil {
- t.Fatal(err)
- }
-
- value := info["CPUShares"].(uint64)
- if value != 1023 {
- t.Fatal("CPUShares of unit is not 1023, %s", value)
- }
-}
-
-// Ensure that basic transient unit starting and stopping works.
-func TestStartStopTransientUnit(t *testing.T) {
- conn := setupConn(t)
-
- props := []Property{
- PropExecStart([]string{"/bin/sleep", "400"}, false),
- }
- target := fmt.Sprintf("testing-transient-%d.service", rand.Int())
-
- // Start the unit
- job, err := conn.StartTransientUnit(target, "replace", props...)
- if err != nil {
- t.Fatal(err)
- }
-
- if job != "done" {
- t.Fatal("Job is not done, %v", job)
- }
-
- units, err := conn.ListUnits()
-
- var unit *UnitStatus
- for _, u := range units {
- if u.Name == target {
- unit = &u
- }
- }
-
- if unit == nil {
- t.Fatalf("Test unit not found in list")
- }
-
- if unit.ActiveState != "active" {
- t.Fatalf("Test unit not active")
- }
-
- // 3. Stop the unit
- job, err = conn.StopUnit(target, "replace")
- if err != nil {
- t.Fatal(err)
- }
-
- units, err = conn.ListUnits()
-
- unit = nil
- for _, u := range units {
- if u.Name == target {
- unit = &u
- }
- }
-
- if unit != nil {
- t.Fatalf("Test unit found in list, should be stopped")
- }
-}
-
-func TestConnJobListener(t *testing.T) {
- target := "start-stop.service"
- conn := setupConn(t)
-
- setupUnit(target, conn, t)
-
- jobSize := len(conn.jobListener.jobs)
-
- _, err := conn.StartUnit(target, "replace")
- if err != nil {
- t.Fatal(err)
- }
-
- _, err = conn.StopUnit(target, "replace")
- if err != nil {
- t.Fatal(err)
- }
-
- currentJobSize := len(conn.jobListener.jobs)
- if jobSize != currentJobSize {
- t.Fatal("JobListener jobs leaked")
- }
-}
diff --git a/vendor/github.com/coreos/go-systemd/dbus/set_test.go b/vendor/github.com/coreos/go-systemd/dbus/set_test.go
deleted file mode 100644
index d8d174d0..00000000
--- a/vendor/github.com/coreos/go-systemd/dbus/set_test.go
+++ /dev/null
@@ -1,26 +0,0 @@
-package dbus
-
-import (
- "testing"
-)
-
-// TestBasicSetActions asserts that Add & Remove behavior is correct
-func TestBasicSetActions(t *testing.T) {
- s := newSet()
-
- if s.Contains("foo") {
- t.Fatal("set should not contain 'foo'")
- }
-
- s.Add("foo")
-
- if !s.Contains("foo") {
- t.Fatal("set should contain 'foo'")
- }
-
- s.Remove("foo")
-
- if s.Contains("foo") {
- t.Fatal("set should not contain 'foo'")
- }
-}
diff --git a/vendor/github.com/coreos/go-systemd/dbus/subscription_set_test.go b/vendor/github.com/coreos/go-systemd/dbus/subscription_set_test.go
deleted file mode 100644
index db600850..00000000
--- a/vendor/github.com/coreos/go-systemd/dbus/subscription_set_test.go
+++ /dev/null
@@ -1,67 +0,0 @@
-package dbus
-
-import (
- "testing"
- "time"
-)
-
-// TestSubscribeUnit exercises the basics of subscription of a particular unit.
-func TestSubscriptionSetUnit(t *testing.T) {
- target := "subscribe-events-set.service"
-
- conn, err := New()
-
- if err != nil {
- t.Fatal(err)
- }
-
- err = conn.Subscribe()
- if err != nil {
- t.Fatal(err)
- }
-
- subSet := conn.NewSubscriptionSet()
- evChan, errChan := subSet.Subscribe()
-
- subSet.Add(target)
- setupUnit(target, conn, t)
-
- job, err := conn.StartUnit(target, "replace")
- if err != nil {
- t.Fatal(err)
- }
-
- if job != "done" {
- t.Fatal("Couldn't start", target)
- }
-
- timeout := make(chan bool, 1)
- go func() {
- time.Sleep(3 * time.Second)
- close(timeout)
- }()
-
- for {
- select {
- case changes := <-evChan:
- tCh, ok := changes[target]
-
- if !ok {
- t.Fatal("Unexpected event %v", changes)
- }
-
- if tCh.ActiveState == "active" && tCh.Name == target {
- goto success
- }
- case err = <-errChan:
- t.Fatal(err)
- case <-timeout:
- t.Fatal("Reached timeout")
- }
- }
-
-success:
- return
-}
-
-
diff --git a/vendor/github.com/coreos/go-systemd/dbus/subscription_test.go b/vendor/github.com/coreos/go-systemd/dbus/subscription_test.go
deleted file mode 100644
index 6f4d0b32..00000000
--- a/vendor/github.com/coreos/go-systemd/dbus/subscription_test.go
+++ /dev/null
@@ -1,90 +0,0 @@
-package dbus
-
-import (
- "testing"
- "time"
-)
-
-// TestSubscribe exercises the basics of subscription
-func TestSubscribe(t *testing.T) {
- conn, err := New()
-
- if err != nil {
- t.Fatal(err)
- }
-
- err = conn.Subscribe()
- if err != nil {
- t.Fatal(err)
- }
-
- err = conn.Unsubscribe()
- if err != nil {
- t.Fatal(err)
- }
-}
-
-// TestSubscribeUnit exercises the basics of subscription of a particular unit.
-func TestSubscribeUnit(t *testing.T) {
- target := "subscribe-events.service"
-
- conn, err := New()
-
- if err != nil {
- t.Fatal(err)
- }
-
- err = conn.Subscribe()
- if err != nil {
- t.Fatal(err)
- }
-
- err = conn.Unsubscribe()
- if err != nil {
- t.Fatal(err)
- }
-
- evChan, errChan := conn.SubscribeUnits(time.Second)
-
- setupUnit(target, conn, t)
-
- job, err := conn.StartUnit(target, "replace")
- if err != nil {
- t.Fatal(err)
- }
-
- if job != "done" {
- t.Fatal("Couldn't start", target)
- }
-
- timeout := make(chan bool, 1)
- go func() {
- time.Sleep(3 * time.Second)
- close(timeout)
- }()
-
- for {
- select {
- case changes := <-evChan:
- tCh, ok := changes[target]
-
- // Just continue until we see our event.
- if !ok {
- continue
- }
-
- if tCh.ActiveState == "active" && tCh.Name == target {
- goto success
- }
- case err = <-errChan:
- t.Fatal(err)
- case <-timeout:
- t.Fatal("Reached timeout")
- }
- }
-
-success:
- return
-}
-
-
diff --git a/vendor/github.com/coreos/yaml/decode_test.go b/vendor/github.com/coreos/yaml/decode_test.go
deleted file mode 100644
index 349bee7d..00000000
--- a/vendor/github.com/coreos/yaml/decode_test.go
+++ /dev/null
@@ -1,720 +0,0 @@
-package yaml_test
-
-import (
- "github.com/coreos/yaml"
- . "gopkg.in/check.v1"
- "math"
- "reflect"
- "strings"
- "time"
-)
-
-var unmarshalIntTest = 123
-
-var unmarshalTests = []struct {
- data string
- value interface{}
-}{
- {
- "",
- &struct{}{},
- }, {
- "{}", &struct{}{},
- }, {
- "v: hi",
- map[string]string{"v": "hi"},
- }, {
- "v: hi", map[string]interface{}{"v": "hi"},
- }, {
- "v: true",
- map[string]string{"v": "true"},
- }, {
- "v: true",
- map[string]interface{}{"v": true},
- }, {
- "v: 10",
- map[string]interface{}{"v": 10},
- }, {
- "v: 0b10",
- map[string]interface{}{"v": 2},
- }, {
- "v: 0xA",
- map[string]interface{}{"v": 10},
- }, {
- "v: 4294967296",
- map[string]int64{"v": 4294967296},
- }, {
- "v: 0.1",
- map[string]interface{}{"v": 0.1},
- }, {
- "v: .1",
- map[string]interface{}{"v": 0.1},
- }, {
- "v: .Inf",
- map[string]interface{}{"v": math.Inf(+1)},
- }, {
- "v: -.Inf",
- map[string]interface{}{"v": math.Inf(-1)},
- }, {
- "v: -10",
- map[string]interface{}{"v": -10},
- }, {
- "v: -.1",
- map[string]interface{}{"v": -0.1},
- },
-
- // Simple values.
- {
- "123",
- &unmarshalIntTest,
- },
-
- // Floats from spec
- {
- "canonical: 6.8523e+5",
- map[string]interface{}{"canonical": 6.8523e+5},
- }, {
- "expo: 685.230_15e+03",
- map[string]interface{}{"expo": 685.23015e+03},
- }, {
- "fixed: 685_230.15",
- map[string]interface{}{"fixed": 685230.15},
- }, {
- "neginf: -.inf",
- map[string]interface{}{"neginf": math.Inf(-1)},
- }, {
- "fixed: 685_230.15",
- map[string]float64{"fixed": 685230.15},
- },
- //{"sexa: 190:20:30.15", map[string]interface{}{"sexa": 0}}, // Unsupported
- //{"notanum: .NaN", map[string]interface{}{"notanum": math.NaN()}}, // Equality of NaN fails.
-
- // Bools from spec
- {
- "canonical: y",
- map[string]interface{}{"canonical": true},
- }, {
- "answer: NO",
- map[string]interface{}{"answer": false},
- }, {
- "logical: True",
- map[string]interface{}{"logical": true},
- }, {
- "option: on",
- map[string]interface{}{"option": true},
- }, {
- "option: on",
- map[string]bool{"option": true},
- },
- // Ints from spec
- {
- "canonical: 685230",
- map[string]interface{}{"canonical": 685230},
- }, {
- "decimal: +685_230",
- map[string]interface{}{"decimal": 685230},
- }, {
- "octal: 02472256",
- map[string]interface{}{"octal": 685230},
- }, {
- "hexa: 0x_0A_74_AE",
- map[string]interface{}{"hexa": 685230},
- }, {
- "bin: 0b1010_0111_0100_1010_1110",
- map[string]interface{}{"bin": 685230},
- }, {
- "bin: -0b101010",
- map[string]interface{}{"bin": -42},
- }, {
- "decimal: +685_230",
- map[string]int{"decimal": 685230},
- },
-
- //{"sexa: 190:20:30", map[string]interface{}{"sexa": 0}}, // Unsupported
-
- // Nulls from spec
- {
- "empty:",
- map[string]interface{}{"empty": nil},
- }, {
- "canonical: ~",
- map[string]interface{}{"canonical": nil},
- }, {
- "english: null",
- map[string]interface{}{"english": nil},
- }, {
- "~: null key",
- map[interface{}]string{nil: "null key"},
- }, {
- "empty:",
- map[string]*bool{"empty": nil},
- },
-
- // Flow sequence
- {
- "seq: [A,B]",
- map[string]interface{}{"seq": []interface{}{"A", "B"}},
- }, {
- "seq: [A,B,C,]",
- map[string][]string{"seq": []string{"A", "B", "C"}},
- }, {
- "seq: [A,1,C]",
- map[string][]string{"seq": []string{"A", "1", "C"}},
- }, {
- "seq: [A,1,C]",
- map[string][]int{"seq": []int{1}},
- }, {
- "seq: [A,1,C]",
- map[string]interface{}{"seq": []interface{}{"A", 1, "C"}},
- },
- // Block sequence
- {
- "seq:\n - A\n - B",
- map[string]interface{}{"seq": []interface{}{"A", "B"}},
- }, {
- "seq:\n - A\n - B\n - C",
- map[string][]string{"seq": []string{"A", "B", "C"}},
- }, {
- "seq:\n - A\n - 1\n - C",
- map[string][]string{"seq": []string{"A", "1", "C"}},
- }, {
- "seq:\n - A\n - 1\n - C",
- map[string][]int{"seq": []int{1}},
- }, {
- "seq:\n - A\n - 1\n - C",
- map[string]interface{}{"seq": []interface{}{"A", 1, "C"}},
- },
-
- // Literal block scalar
- {
- "scalar: | # Comment\n\n literal\n\n \ttext\n\n",
- map[string]string{"scalar": "\nliteral\n\n\ttext\n"},
- },
-
- // Folded block scalar
- {
- "scalar: > # Comment\n\n folded\n line\n \n next\n line\n * one\n * two\n\n last\n line\n\n",
- map[string]string{"scalar": "\nfolded line\nnext line\n * one\n * two\n\nlast line\n"},
- },
-
- // Map inside interface with no type hints.
- {
- "a: {b: c}",
- map[string]interface{}{"a": map[interface{}]interface{}{"b": "c"}},
- },
-
- // Structs and type conversions.
- {
- "hello: world",
- &struct{ Hello string }{"world"},
- }, {
- "a: {b: c}",
- &struct{ A struct{ B string } }{struct{ B string }{"c"}},
- }, {
- "a: {b: c}",
- &struct{ A *struct{ B string } }{&struct{ B string }{"c"}},
- }, {
- "a: {b: c}",
- &struct{ A map[string]string }{map[string]string{"b": "c"}},
- }, {
- "a: {b: c}",
- &struct{ A *map[string]string }{&map[string]string{"b": "c"}},
- }, {
- "a:",
- &struct{ A map[string]string }{},
- }, {
- "a: 1",
- &struct{ A int }{1},
- }, {
- "a: 1",
- &struct{ A float64 }{1},
- }, {
- "a: 1.0",
- &struct{ A int }{1},
- }, {
- "a: 1.0",
- &struct{ A uint }{1},
- }, {
- "a: [1, 2]",
- &struct{ A []int }{[]int{1, 2}},
- }, {
- "a: 1",
- &struct{ B int }{0},
- }, {
- "a: 1",
- &struct {
- B int "a"
- }{1},
- }, {
- "a: y",
- &struct{ A bool }{true},
- },
-
- // Some cross type conversions
- {
- "v: 42",
- map[string]uint{"v": 42},
- }, {
- "v: -42",
- map[string]uint{},
- }, {
- "v: 4294967296",
- map[string]uint64{"v": 4294967296},
- }, {
- "v: -4294967296",
- map[string]uint64{},
- },
-
- // Overflow cases.
- {
- "v: 4294967297",
- map[string]int32{},
- }, {
- "v: 128",
- map[string]int8{},
- },
-
- // Quoted values.
- {
- "'1': '\"2\"'",
- map[interface{}]interface{}{"1": "\"2\""},
- }, {
- "v:\n- A\n- 'B\n\n C'\n",
- map[string][]string{"v": []string{"A", "B\nC"}},
- },
-
- // Explicit tags.
- {
- "v: !!float '1.1'",
- map[string]interface{}{"v": 1.1},
- }, {
- "v: !!null ''",
- map[string]interface{}{"v": nil},
- }, {
- "%TAG !y! tag:yaml.org,2002:\n---\nv: !y!int '1'",
- map[string]interface{}{"v": 1},
- },
-
- // Anchors and aliases.
- {
- "a: &x 1\nb: &y 2\nc: *x\nd: *y\n",
- &struct{ A, B, C, D int }{1, 2, 1, 2},
- }, {
- "a: &a {c: 1}\nb: *a",
- &struct {
- A, B struct {
- C int
- }
- }{struct{ C int }{1}, struct{ C int }{1}},
- }, {
- "a: &a [1, 2]\nb: *a",
- &struct{ B []int }{[]int{1, 2}},
- },
-
- // Bug #1133337
- {
- "foo: ''",
- map[string]*string{"foo": new(string)},
- }, {
- "foo: null",
- map[string]string{"foo": ""},
- }, {
- "foo: null",
- map[string]interface{}{"foo": nil},
- },
-
- // Ignored field
- {
- "a: 1\nb: 2\n",
- &struct {
- A int
- B int "-"
- }{1, 0},
- },
-
- // Bug #1191981
- {
- "" +
- "%YAML 1.1\n" +
- "--- !!str\n" +
- `"Generic line break (no glyph)\n\` + "\n" +
- ` Generic line break (glyphed)\n\` + "\n" +
- ` Line separator\u2028\` + "\n" +
- ` Paragraph separator\u2029"` + "\n",
- "" +
- "Generic line break (no glyph)\n" +
- "Generic line break (glyphed)\n" +
- "Line separator\u2028Paragraph separator\u2029",
- },
-
- // Struct inlining
- {
- "a: 1\nb: 2\nc: 3\n",
- &struct {
- A int
- C inlineB `yaml:",inline"`
- }{1, inlineB{2, inlineC{3}}},
- },
-
- // bug 1243827
- {
- "a: -b_c",
- map[string]interface{}{"a": "-b_c"},
- },
- {
- "a: +b_c",
- map[string]interface{}{"a": "+b_c"},
- },
- {
- "a: 50cent_of_dollar",
- map[string]interface{}{"a": "50cent_of_dollar"},
- },
-
- // Duration
- {
- "a: 3s",
- map[string]time.Duration{"a": 3 * time.Second},
- },
-
- // Issue #24.
- {
- "a: ",
- map[string]string{"a": ""},
- },
-
- // Base 60 floats are obsolete and unsupported.
- {
- "a: 1:1\n",
- map[string]string{"a": "1:1"},
- },
-
- // Binary data.
- {
- "a: !!binary gIGC\n",
- map[string]string{"a": "\x80\x81\x82"},
- }, {
- "a: !!binary |\n " + strings.Repeat("kJCQ", 17) + "kJ\n CQ\n",
- map[string]string{"a": strings.Repeat("\x90", 54)},
- }, {
- "a: !!binary |\n " + strings.Repeat("A", 70) + "\n ==\n",
- map[string]string{"a": strings.Repeat("\x00", 52)},
- },
-}
-
-type inlineB struct {
- B int
- inlineC `yaml:",inline"`
-}
-
-type inlineC struct {
- C int
-}
-
-func (s *S) TestUnmarshal(c *C) {
- for i, item := range unmarshalTests {
- t := reflect.ValueOf(item.value).Type()
- var value interface{}
- switch t.Kind() {
- case reflect.Map:
- value = reflect.MakeMap(t).Interface()
- case reflect.String:
- t := reflect.ValueOf(item.value).Type()
- v := reflect.New(t)
- value = v.Interface()
- default:
- pt := reflect.ValueOf(item.value).Type()
- pv := reflect.New(pt.Elem())
- value = pv.Interface()
- }
- err := yaml.Unmarshal([]byte(item.data), value)
- c.Assert(err, IsNil, Commentf("Item #%d", i))
- if t.Kind() == reflect.String {
- c.Assert(*value.(*string), Equals, item.value, Commentf("Item #%d", i))
- } else {
- c.Assert(value, DeepEquals, item.value, Commentf("Item #%d", i))
- }
- }
-}
-
-func (s *S) TestUnmarshalNaN(c *C) {
- value := map[string]interface{}{}
- err := yaml.Unmarshal([]byte("notanum: .NaN"), &value)
- c.Assert(err, IsNil)
- c.Assert(math.IsNaN(value["notanum"].(float64)), Equals, true)
-}
-
-var unmarshalErrorTests = []struct {
- data, error string
-}{
- {"v: !!float 'error'", "YAML error: cannot decode !!str `error` as a !!float"},
- {"v: [A,", "YAML error: line 1: did not find expected node content"},
- {"v:\n- [A,", "YAML error: line 2: did not find expected node content"},
- {"a: *b\n", "YAML error: Unknown anchor 'b' referenced"},
- {"a: &a\n b: *a\n", "YAML error: Anchor 'a' value contains itself"},
- {"value: -", "YAML error: block sequence entries are not allowed in this context"},
- {"a: !!binary ==", "YAML error: !!binary value contains invalid base64 data"},
- {"{[.]}", `YAML error: invalid map key: \[\]interface \{\}\{"\."\}`},
- {"{{.}}", `YAML error: invalid map key: map\[interface\ \{\}\]interface \{\}\{".":interface \{\}\(nil\)\}`},
-}
-
-func (s *S) TestUnmarshalErrors(c *C) {
- for _, item := range unmarshalErrorTests {
- var value interface{}
- err := yaml.Unmarshal([]byte(item.data), &value)
- c.Assert(err, ErrorMatches, item.error, Commentf("Partial unmarshal: %#v", value))
- }
-}
-
-var setterTests = []struct {
- data, tag string
- value interface{}
-}{
- {"_: {hi: there}", "!!map", map[interface{}]interface{}{"hi": "there"}},
- {"_: [1,A]", "!!seq", []interface{}{1, "A"}},
- {"_: 10", "!!int", 10},
- {"_: null", "!!null", nil},
- {`_: BAR!`, "!!str", "BAR!"},
- {`_: "BAR!"`, "!!str", "BAR!"},
- {"_: !!foo 'BAR!'", "!!foo", "BAR!"},
-}
-
-var setterResult = map[int]bool{}
-
-type typeWithSetter struct {
- tag string
- value interface{}
-}
-
-func (o *typeWithSetter) SetYAML(tag string, value interface{}) (ok bool) {
- o.tag = tag
- o.value = value
- if i, ok := value.(int); ok {
- if result, ok := setterResult[i]; ok {
- return result
- }
- }
- return true
-}
-
-type setterPointerType struct {
- Field *typeWithSetter "_"
-}
-
-type setterValueType struct {
- Field typeWithSetter "_"
-}
-
-func (s *S) TestUnmarshalWithPointerSetter(c *C) {
- for _, item := range setterTests {
- obj := &setterPointerType{}
- err := yaml.Unmarshal([]byte(item.data), obj)
- c.Assert(err, IsNil)
- c.Assert(obj.Field, NotNil, Commentf("Pointer not initialized (%#v)", item.value))
- c.Assert(obj.Field.tag, Equals, item.tag)
- c.Assert(obj.Field.value, DeepEquals, item.value)
- }
-}
-
-func (s *S) TestUnmarshalWithValueSetter(c *C) {
- for _, item := range setterTests {
- obj := &setterValueType{}
- err := yaml.Unmarshal([]byte(item.data), obj)
- c.Assert(err, IsNil)
- c.Assert(obj.Field, NotNil, Commentf("Pointer not initialized (%#v)", item.value))
- c.Assert(obj.Field.tag, Equals, item.tag)
- c.Assert(obj.Field.value, DeepEquals, item.value)
- }
-}
-
-func (s *S) TestUnmarshalWholeDocumentWithSetter(c *C) {
- obj := &typeWithSetter{}
- err := yaml.Unmarshal([]byte(setterTests[0].data), obj)
- c.Assert(err, IsNil)
- c.Assert(obj.tag, Equals, setterTests[0].tag)
- value, ok := obj.value.(map[interface{}]interface{})
- c.Assert(ok, Equals, true)
- c.Assert(value["_"], DeepEquals, setterTests[0].value)
-}
-
-func (s *S) TestUnmarshalWithFalseSetterIgnoresValue(c *C) {
- setterResult[2] = false
- setterResult[4] = false
- defer func() {
- delete(setterResult, 2)
- delete(setterResult, 4)
- }()
-
- m := map[string]*typeWithSetter{}
- data := `{abc: 1, def: 2, ghi: 3, jkl: 4}`
- err := yaml.Unmarshal([]byte(data), m)
- c.Assert(err, IsNil)
- c.Assert(m["abc"], NotNil)
- c.Assert(m["def"], IsNil)
- c.Assert(m["ghi"], NotNil)
- c.Assert(m["jkl"], IsNil)
-
- c.Assert(m["abc"].value, Equals, 1)
- c.Assert(m["ghi"].value, Equals, 3)
-}
-
-func (s *S) TestUnmarshalWithTransform(c *C) {
- data := `{a_b: 1, c-d: 2, e-f_g: 3, h_i-j: 4}`
- expect := map[string]int{
- "a_b": 1,
- "c_d": 2,
- "e_f_g": 3,
- "h_i_j": 4,
- }
- m := map[string]int{}
- yaml.UnmarshalMappingKeyTransform = func(i string) string {
- return strings.Replace(i, "-", "_", -1)
- }
- err := yaml.Unmarshal([]byte(data), m)
- c.Assert(err, IsNil)
- c.Assert(m, DeepEquals, expect)
-}
-
-// From http://yaml.org/type/merge.html
-var mergeTests = `
-anchors:
- - &CENTER { "x": 1, "y": 2 }
- - &LEFT { "x": 0, "y": 2 }
- - &BIG { "r": 10 }
- - &SMALL { "r": 1 }
-
-# All the following maps are equal:
-
-plain:
- # Explicit keys
- "x": 1
- "y": 2
- "r": 10
- label: center/big
-
-mergeOne:
- # Merge one map
- << : *CENTER
- "r": 10
- label: center/big
-
-mergeMultiple:
- # Merge multiple maps
- << : [ *CENTER, *BIG ]
- label: center/big
-
-override:
- # Override
- << : [ *BIG, *LEFT, *SMALL ]
- "x": 1
- label: center/big
-
-shortTag:
- # Explicit short merge tag
- !!merge "<<" : [ *CENTER, *BIG ]
- label: center/big
-
-longTag:
- # Explicit merge long tag
- ! "<<" : [ *CENTER, *BIG ]
- label: center/big
-
-inlineMap:
- # Inlined map
- << : {"x": 1, "y": 2, "r": 10}
- label: center/big
-
-inlineSequenceMap:
- # Inlined map in sequence
- << : [ *CENTER, {"r": 10} ]
- label: center/big
-`
-
-func (s *S) TestMerge(c *C) {
- var want = map[interface{}]interface{}{
- "x": 1,
- "y": 2,
- "r": 10,
- "label": "center/big",
- }
-
- var m map[string]interface{}
- err := yaml.Unmarshal([]byte(mergeTests), &m)
- c.Assert(err, IsNil)
- for name, test := range m {
- if name == "anchors" {
- continue
- }
- c.Assert(test, DeepEquals, want, Commentf("test %q failed", name))
- }
-}
-
-func (s *S) TestMergeStruct(c *C) {
- type Data struct {
- X, Y, R int
- Label string
- }
- want := Data{1, 2, 10, "center/big"}
-
- var m map[string]Data
- err := yaml.Unmarshal([]byte(mergeTests), &m)
- c.Assert(err, IsNil)
- for name, test := range m {
- if name == "anchors" {
- continue
- }
- c.Assert(test, Equals, want, Commentf("test %q failed", name))
- }
-}
-
-var unmarshalNullTests = []func() interface{}{
- func() interface{} { var v interface{}; v = "v"; return &v },
- func() interface{} { var s = "s"; return &s },
- func() interface{} { var s = "s"; sptr := &s; return &sptr },
- func() interface{} { var i = 1; return &i },
- func() interface{} { var i = 1; iptr := &i; return &iptr },
- func() interface{} { m := map[string]int{"s": 1}; return &m },
- func() interface{} { m := map[string]int{"s": 1}; return m },
-}
-
-func (s *S) TestUnmarshalNull(c *C) {
- for _, test := range unmarshalNullTests {
- item := test()
- zero := reflect.Zero(reflect.TypeOf(item).Elem()).Interface()
- err := yaml.Unmarshal([]byte("null"), item)
- c.Assert(err, IsNil)
- if reflect.TypeOf(item).Kind() == reflect.Map {
- c.Assert(reflect.ValueOf(item).Interface(), DeepEquals, reflect.MakeMap(reflect.TypeOf(item)).Interface())
- } else {
- c.Assert(reflect.ValueOf(item).Elem().Interface(), DeepEquals, zero)
- }
- }
-}
-
-//var data []byte
-//func init() {
-// var err error
-// data, err = ioutil.ReadFile("/tmp/file.yaml")
-// if err != nil {
-// panic(err)
-// }
-//}
-//
-//func (s *S) BenchmarkUnmarshal(c *C) {
-// var err error
-// for i := 0; i < c.N; i++ {
-// var v map[string]interface{}
-// err = yaml.Unmarshal(data, &v)
-// }
-// if err != nil {
-// panic(err)
-// }
-//}
-//
-//func (s *S) BenchmarkMarshal(c *C) {
-// var v map[string]interface{}
-// yaml.Unmarshal(data, &v)
-// c.ResetTimer()
-// for i := 0; i < c.N; i++ {
-// yaml.Marshal(&v)
-// }
-//}
diff --git a/vendor/github.com/coreos/yaml/encode_test.go b/vendor/github.com/coreos/yaml/encode_test.go
deleted file mode 100644
index 2cd0ea7f..00000000
--- a/vendor/github.com/coreos/yaml/encode_test.go
+++ /dev/null
@@ -1,433 +0,0 @@
-package yaml_test
-
-import (
- "fmt"
- "math"
- "strconv"
- "strings"
- "time"
-
- "github.com/coreos/yaml"
- . "gopkg.in/check.v1"
-)
-
-var marshalIntTest = 123
-
-var marshalTests = []struct {
- value interface{}
- data string
-}{
- {
- nil,
- "null\n",
- }, {
- &struct{}{},
- "{}\n",
- }, {
- map[string]string{"v": "hi"},
- "v: hi\n",
- }, {
- map[string]interface{}{"v": "hi"},
- "v: hi\n",
- }, {
- map[string]string{"v": "true"},
- "v: \"true\"\n",
- }, {
- map[string]string{"v": "false"},
- "v: \"false\"\n",
- }, {
- map[string]interface{}{"v": true},
- "v: true\n",
- }, {
- map[string]interface{}{"v": false},
- "v: false\n",
- }, {
- map[string]interface{}{"v": 10},
- "v: 10\n",
- }, {
- map[string]interface{}{"v": -10},
- "v: -10\n",
- }, {
- map[string]uint{"v": 42},
- "v: 42\n",
- }, {
- map[string]interface{}{"v": int64(4294967296)},
- "v: 4294967296\n",
- }, {
- map[string]int64{"v": int64(4294967296)},
- "v: 4294967296\n",
- }, {
- map[string]uint64{"v": 4294967296},
- "v: 4294967296\n",
- }, {
- map[string]interface{}{"v": "10"},
- "v: \"10\"\n",
- }, {
- map[string]interface{}{"v": 0.1},
- "v: 0.1\n",
- }, {
- map[string]interface{}{"v": float64(0.1)},
- "v: 0.1\n",
- }, {
- map[string]interface{}{"v": -0.1},
- "v: -0.1\n",
- }, {
- map[string]interface{}{"v": math.Inf(+1)},
- "v: .inf\n",
- }, {
- map[string]interface{}{"v": math.Inf(-1)},
- "v: -.inf\n",
- }, {
- map[string]interface{}{"v": math.NaN()},
- "v: .nan\n",
- }, {
- map[string]interface{}{"v": nil},
- "v: null\n",
- }, {
- map[string]interface{}{"v": ""},
- "v: \"\"\n",
- }, {
- map[string][]string{"v": []string{"A", "B"}},
- "v:\n- A\n- B\n",
- }, {
- map[string][]string{"v": []string{"A", "B\nC"}},
- "v:\n- A\n- |-\n B\n C\n",
- }, {
- map[string][]interface{}{"v": []interface{}{"A", 1, map[string][]int{"B": []int{2, 3}}}},
- "v:\n- A\n- 1\n- B:\n - 2\n - 3\n",
- }, {
- map[string]interface{}{"a": map[interface{}]interface{}{"b": "c"}},
- "a:\n b: c\n",
- }, {
- map[string]interface{}{"a": "-"},
- "a: '-'\n",
- },
-
- // Simple values.
- {
- &marshalIntTest,
- "123\n",
- },
-
- // Structures
- {
- &struct{ Hello string }{"world"},
- "hello: world\n",
- }, {
- &struct {
- A struct {
- B string
- }
- }{struct{ B string }{"c"}},
- "a:\n b: c\n",
- }, {
- &struct {
- A *struct {
- B string
- }
- }{&struct{ B string }{"c"}},
- "a:\n b: c\n",
- }, {
- &struct {
- A *struct {
- B string
- }
- }{},
- "a: null\n",
- }, {
- &struct{ A int }{1},
- "a: 1\n",
- }, {
- &struct{ A []int }{[]int{1, 2}},
- "a:\n- 1\n- 2\n",
- }, {
- &struct {
- B int "a"
- }{1},
- "a: 1\n",
- }, {
- &struct{ A bool }{true},
- "a: true\n",
- },
-
- // Conditional flag
- {
- &struct {
- A int "a,omitempty"
- B int "b,omitempty"
- }{1, 0},
- "a: 1\n",
- }, {
- &struct {
- A int "a,omitempty"
- B int "b,omitempty"
- }{0, 0},
- "{}\n",
- }, {
- &struct {
- A *struct{ X int } "a,omitempty"
- B int "b,omitempty"
- }{nil, 0},
- "{}\n",
- },
-
- // Flow flag
- {
- &struct {
- A []int "a,flow"
- }{[]int{1, 2}},
- "a: [1, 2]\n",
- }, {
- &struct {
- A map[string]string "a,flow"
- }{map[string]string{"b": "c", "d": "e"}},
- "a: {b: c, d: e}\n",
- }, {
- &struct {
- A struct {
- B, D string
- } "a,flow"
- }{struct{ B, D string }{"c", "e"}},
- "a: {b: c, d: e}\n",
- },
-
- // Unexported field
- {
- &struct {
- u int
- A int
- }{0, 1},
- "a: 1\n",
- },
-
- // Ignored field
- {
- &struct {
- A int
- B int "-"
- }{1, 2},
- "a: 1\n",
- },
-
- // Struct inlining
- {
- &struct {
- A int
- C inlineB `yaml:",inline"`
- }{1, inlineB{2, inlineC{3}}},
- "a: 1\nb: 2\nc: 3\n",
- },
-
- // Duration
- {
- map[string]time.Duration{"a": 3 * time.Second},
- "a: 3s\n",
- },
-
- // Issue #24: bug in map merging logic.
- {
- map[string]string{"a": ""},
- "a: \n",
- },
-
- // Issue #34: marshal unsupported base 60 floats quoted for compatibility
- // with old YAML 1.1 parsers.
- {
- map[string]string{"a": "1:1"},
- "a: \"1:1\"\n",
- },
-
- // Binary data.
- {
- map[string]string{"a": "\x00"},
- "a: \"\\0\"\n",
- }, {
- map[string]string{"a": "\x80\x81\x82"},
- "a: !!binary gIGC\n",
- }, {
- map[string]string{"a": strings.Repeat("\x90", 54)},
- "a: !!binary |\n " + strings.Repeat("kJCQ", 17) + "kJ\n CQ\n",
- }, {
- map[string]interface{}{"a": typeWithGetter{"!!str", "\x80\x81\x82"}},
- "a: !!binary gIGC\n",
- },
-
- // Escaping of tags.
- {
- map[string]interface{}{"a": typeWithGetter{"foo!bar", 1}},
- "a: ! 1\n",
- },
-}
-
-func (s *S) TestMarshal(c *C) {
- for _, item := range marshalTests {
- data, err := yaml.Marshal(item.value)
- c.Assert(err, IsNil)
- c.Assert(string(data), Equals, item.data)
- }
-}
-
-var marshalErrorTests = []struct {
- value interface{}
- error string
- panic string
-}{{
- value: &struct {
- B int
- inlineB ",inline"
- }{1, inlineB{2, inlineC{3}}},
- panic: `Duplicated key 'b' in struct struct \{ B int; .*`,
-}, {
- value: typeWithGetter{"!!binary", "\x80"},
- error: "YAML error: explicitly tagged !!binary data must be base64-encoded",
-}, {
- value: typeWithGetter{"!!float", "\x80"},
- error: `YAML error: cannot marshal invalid UTF-8 data as !!float`,
-}}
-
-func (s *S) TestMarshalErrors(c *C) {
- for _, item := range marshalErrorTests {
- if item.panic != "" {
- c.Assert(func() { yaml.Marshal(item.value) }, PanicMatches, item.panic)
- } else {
- _, err := yaml.Marshal(item.value)
- c.Assert(err, ErrorMatches, item.error)
- }
- }
-}
-
-var marshalTaggedIfaceTest interface{} = &struct{ A string }{"B"}
-
-var getterTests = []struct {
- data, tag string
- value interface{}
-}{
- {"_:\n hi: there\n", "", map[interface{}]interface{}{"hi": "there"}},
- {"_:\n- 1\n- A\n", "", []interface{}{1, "A"}},
- {"_: 10\n", "", 10},
- {"_: null\n", "", nil},
- {"_: !foo BAR!\n", "!foo", "BAR!"},
- {"_: !foo 1\n", "!foo", "1"},
- {"_: !foo '\"1\"'\n", "!foo", "\"1\""},
- {"_: !foo 1.1\n", "!foo", 1.1},
- {"_: !foo 1\n", "!foo", 1},
- {"_: !foo 1\n", "!foo", uint(1)},
- {"_: !foo true\n", "!foo", true},
- {"_: !foo\n- A\n- B\n", "!foo", []string{"A", "B"}},
- {"_: !foo\n A: B\n", "!foo", map[string]string{"A": "B"}},
- {"_: !foo\n a: B\n", "!foo", &marshalTaggedIfaceTest},
-}
-
-func (s *S) TestMarshalTypeCache(c *C) {
- var data []byte
- var err error
- func() {
- type T struct{ A int }
- data, err = yaml.Marshal(&T{})
- c.Assert(err, IsNil)
- }()
- func() {
- type T struct{ B int }
- data, err = yaml.Marshal(&T{})
- c.Assert(err, IsNil)
- }()
- c.Assert(string(data), Equals, "b: 0\n")
-}
-
-type typeWithGetter struct {
- tag string
- value interface{}
-}
-
-func (o typeWithGetter) GetYAML() (tag string, value interface{}) {
- return o.tag, o.value
-}
-
-type typeWithGetterField struct {
- Field typeWithGetter "_"
-}
-
-func (s *S) TestMashalWithGetter(c *C) {
- for _, item := range getterTests {
- obj := &typeWithGetterField{}
- obj.Field.tag = item.tag
- obj.Field.value = item.value
- data, err := yaml.Marshal(obj)
- c.Assert(err, IsNil)
- c.Assert(string(data), Equals, string(item.data))
- }
-}
-
-func (s *S) TestUnmarshalWholeDocumentWithGetter(c *C) {
- obj := &typeWithGetter{}
- obj.tag = ""
- obj.value = map[string]string{"hello": "world!"}
- data, err := yaml.Marshal(obj)
- c.Assert(err, IsNil)
- c.Assert(string(data), Equals, "hello: world!\n")
-}
-
-func (s *S) TestSortedOutput(c *C) {
- order := []interface{}{
- false,
- true,
- 1,
- uint(1),
- 1.0,
- 1.1,
- 1.2,
- 2,
- uint(2),
- 2.0,
- 2.1,
- "",
- ".1",
- ".2",
- ".a",
- "1",
- "2",
- "a!10",
- "a/2",
- "a/10",
- "a~10",
- "ab/1",
- "b/1",
- "b/01",
- "b/2",
- "b/02",
- "b/3",
- "b/03",
- "b1",
- "b01",
- "b3",
- "c2.10",
- "c10.2",
- "d1",
- "d12",
- "d12a",
- }
- m := make(map[interface{}]int)
- for _, k := range order {
- m[k] = 1
- }
- data, err := yaml.Marshal(m)
- c.Assert(err, IsNil)
- out := "\n" + string(data)
- last := 0
- for i, k := range order {
- repr := fmt.Sprint(k)
- if s, ok := k.(string); ok {
- if _, err = strconv.ParseFloat(repr, 32); s == "" || err == nil {
- repr = `"` + repr + `"`
- }
- }
- index := strings.Index(out, "\n"+repr+":")
- if index == -1 {
- c.Fatalf("%#v is not in the output: %#v", k, out)
- }
- if index < last {
- c.Fatalf("%#v was generated before %#v: %q", k, order[i-1], out)
- }
- last = index
- }
-}
diff --git a/vendor/github.com/coreos/yaml/suite_test.go b/vendor/github.com/coreos/yaml/suite_test.go
deleted file mode 100644
index c5cf1ed4..00000000
--- a/vendor/github.com/coreos/yaml/suite_test.go
+++ /dev/null
@@ -1,12 +0,0 @@
-package yaml_test
-
-import (
- . "gopkg.in/check.v1"
- "testing"
-)
-
-func Test(t *testing.T) { TestingT(t) }
-
-type S struct{}
-
-var _ = Suite(&S{})
diff --git a/vendor/github.com/davecgh/go-spew/spew/common_test.go b/vendor/github.com/davecgh/go-spew/spew/common_test.go
deleted file mode 100644
index 39b7525b..00000000
--- a/vendor/github.com/davecgh/go-spew/spew/common_test.go
+++ /dev/null
@@ -1,298 +0,0 @@
-/*
- * Copyright (c) 2013 Dave Collins
- *
- * Permission to use, copy, modify, and distribute this software for any
- * purpose with or without fee is hereby granted, provided that the above
- * copyright notice and this permission notice appear in all copies.
- *
- * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
- * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
- * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
- * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
- * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
- * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
- */
-
-package spew_test
-
-import (
- "fmt"
- "reflect"
- "testing"
-
- "github.com/davecgh/go-spew/spew"
-)
-
-// custom type to test Stinger interface on non-pointer receiver.
-type stringer string
-
-// String implements the Stringer interface for testing invocation of custom
-// stringers on types with non-pointer receivers.
-func (s stringer) String() string {
- return "stringer " + string(s)
-}
-
-// custom type to test Stinger interface on pointer receiver.
-type pstringer string
-
-// String implements the Stringer interface for testing invocation of custom
-// stringers on types with only pointer receivers.
-func (s *pstringer) String() string {
- return "stringer " + string(*s)
-}
-
-// xref1 and xref2 are cross referencing structs for testing circular reference
-// detection.
-type xref1 struct {
- ps2 *xref2
-}
-type xref2 struct {
- ps1 *xref1
-}
-
-// indirCir1, indirCir2, and indirCir3 are used to generate an indirect circular
-// reference for testing detection.
-type indirCir1 struct {
- ps2 *indirCir2
-}
-type indirCir2 struct {
- ps3 *indirCir3
-}
-type indirCir3 struct {
- ps1 *indirCir1
-}
-
-// embed is used to test embedded structures.
-type embed struct {
- a string
-}
-
-// embedwrap is used to test embedded structures.
-type embedwrap struct {
- *embed
- e *embed
-}
-
-// panicer is used to intentionally cause a panic for testing spew properly
-// handles them
-type panicer int
-
-func (p panicer) String() string {
- panic("test panic")
-}
-
-// customError is used to test custom error interface invocation.
-type customError int
-
-func (e customError) Error() string {
- return fmt.Sprintf("error: %d", int(e))
-}
-
-// stringizeWants converts a slice of wanted test output into a format suitable
-// for a test error message.
-func stringizeWants(wants []string) string {
- s := ""
- for i, want := range wants {
- if i > 0 {
- s += fmt.Sprintf("want%d: %s", i+1, want)
- } else {
- s += "want: " + want
- }
- }
- return s
-}
-
-// testFailed returns whether or not a test failed by checking if the result
-// of the test is in the slice of wanted strings.
-func testFailed(result string, wants []string) bool {
- for _, want := range wants {
- if result == want {
- return false
- }
- }
- return true
-}
-
-type sortableStruct struct {
- x int
-}
-
-func (ss sortableStruct) String() string {
- return fmt.Sprintf("ss.%d", ss.x)
-}
-
-type unsortableStruct struct {
- x int
-}
-
-type sortTestCase struct {
- input []reflect.Value
- expected []reflect.Value
-}
-
-func helpTestSortValues(tests []sortTestCase, cs *spew.ConfigState, t *testing.T) {
- getInterfaces := func(values []reflect.Value) []interface{} {
- interfaces := []interface{}{}
- for _, v := range values {
- interfaces = append(interfaces, v.Interface())
- }
- return interfaces
- }
-
- for _, test := range tests {
- spew.SortValues(test.input, cs)
- // reflect.DeepEqual cannot really make sense of reflect.Value,
- // probably because of all the pointer tricks. For instance,
- // v(2.0) != v(2.0) on a 32-bits system. Turn them into interface{}
- // instead.
- input := getInterfaces(test.input)
- expected := getInterfaces(test.expected)
- if !reflect.DeepEqual(input, expected) {
- t.Errorf("Sort mismatch:\n %v != %v", input, expected)
- }
- }
-}
-
-// TestSortValues ensures the sort functionality for relect.Value based sorting
-// works as intended.
-func TestSortValues(t *testing.T) {
- v := reflect.ValueOf
-
- a := v("a")
- b := v("b")
- c := v("c")
- embedA := v(embed{"a"})
- embedB := v(embed{"b"})
- embedC := v(embed{"c"})
- tests := []sortTestCase{
- // No values.
- {
- []reflect.Value{},
- []reflect.Value{},
- },
- // Bools.
- {
- []reflect.Value{v(false), v(true), v(false)},
- []reflect.Value{v(false), v(false), v(true)},
- },
- // Ints.
- {
- []reflect.Value{v(2), v(1), v(3)},
- []reflect.Value{v(1), v(2), v(3)},
- },
- // Uints.
- {
- []reflect.Value{v(uint8(2)), v(uint8(1)), v(uint8(3))},
- []reflect.Value{v(uint8(1)), v(uint8(2)), v(uint8(3))},
- },
- // Floats.
- {
- []reflect.Value{v(2.0), v(1.0), v(3.0)},
- []reflect.Value{v(1.0), v(2.0), v(3.0)},
- },
- // Strings.
- {
- []reflect.Value{b, a, c},
- []reflect.Value{a, b, c},
- },
- // Array
- {
- []reflect.Value{v([3]int{3, 2, 1}), v([3]int{1, 3, 2}), v([3]int{1, 2, 3})},
- []reflect.Value{v([3]int{1, 2, 3}), v([3]int{1, 3, 2}), v([3]int{3, 2, 1})},
- },
- // Uintptrs.
- {
- []reflect.Value{v(uintptr(2)), v(uintptr(1)), v(uintptr(3))},
- []reflect.Value{v(uintptr(1)), v(uintptr(2)), v(uintptr(3))},
- },
- // SortableStructs.
- {
- // Note: not sorted - DisableMethods is set.
- []reflect.Value{v(sortableStruct{2}), v(sortableStruct{1}), v(sortableStruct{3})},
- []reflect.Value{v(sortableStruct{2}), v(sortableStruct{1}), v(sortableStruct{3})},
- },
- // UnsortableStructs.
- {
- // Note: not sorted - SpewKeys is false.
- []reflect.Value{v(unsortableStruct{2}), v(unsortableStruct{1}), v(unsortableStruct{3})},
- []reflect.Value{v(unsortableStruct{2}), v(unsortableStruct{1}), v(unsortableStruct{3})},
- },
- // Invalid.
- {
- []reflect.Value{embedB, embedA, embedC},
- []reflect.Value{embedB, embedA, embedC},
- },
- }
- cs := spew.ConfigState{DisableMethods: true, SpewKeys: false}
- helpTestSortValues(tests, &cs, t)
-}
-
-// TestSortValuesWithMethods ensures the sort functionality for relect.Value
-// based sorting works as intended when using string methods.
-func TestSortValuesWithMethods(t *testing.T) {
- v := reflect.ValueOf
-
- a := v("a")
- b := v("b")
- c := v("c")
- tests := []sortTestCase{
- // Ints.
- {
- []reflect.Value{v(2), v(1), v(3)},
- []reflect.Value{v(1), v(2), v(3)},
- },
- // Strings.
- {
- []reflect.Value{b, a, c},
- []reflect.Value{a, b, c},
- },
- // SortableStructs.
- {
- []reflect.Value{v(sortableStruct{2}), v(sortableStruct{1}), v(sortableStruct{3})},
- []reflect.Value{v(sortableStruct{1}), v(sortableStruct{2}), v(sortableStruct{3})},
- },
- // UnsortableStructs.
- {
- // Note: not sorted - SpewKeys is false.
- []reflect.Value{v(unsortableStruct{2}), v(unsortableStruct{1}), v(unsortableStruct{3})},
- []reflect.Value{v(unsortableStruct{2}), v(unsortableStruct{1}), v(unsortableStruct{3})},
- },
- }
- cs := spew.ConfigState{DisableMethods: false, SpewKeys: false}
- helpTestSortValues(tests, &cs, t)
-}
-
-// TestSortValuesWithSpew ensures the sort functionality for relect.Value
-// based sorting works as intended when using spew to stringify keys.
-func TestSortValuesWithSpew(t *testing.T) {
- v := reflect.ValueOf
-
- a := v("a")
- b := v("b")
- c := v("c")
- tests := []sortTestCase{
- // Ints.
- {
- []reflect.Value{v(2), v(1), v(3)},
- []reflect.Value{v(1), v(2), v(3)},
- },
- // Strings.
- {
- []reflect.Value{b, a, c},
- []reflect.Value{a, b, c},
- },
- // SortableStructs.
- {
- []reflect.Value{v(sortableStruct{2}), v(sortableStruct{1}), v(sortableStruct{3})},
- []reflect.Value{v(sortableStruct{1}), v(sortableStruct{2}), v(sortableStruct{3})},
- },
- // UnsortableStructs.
- {
- []reflect.Value{v(unsortableStruct{2}), v(unsortableStruct{1}), v(unsortableStruct{3})},
- []reflect.Value{v(unsortableStruct{1}), v(unsortableStruct{2}), v(unsortableStruct{3})},
- },
- }
- cs := spew.ConfigState{DisableMethods: true, SpewKeys: true}
- helpTestSortValues(tests, &cs, t)
-}
diff --git a/vendor/github.com/davecgh/go-spew/spew/dump_test.go b/vendor/github.com/davecgh/go-spew/spew/dump_test.go
deleted file mode 100644
index 2b320401..00000000
--- a/vendor/github.com/davecgh/go-spew/spew/dump_test.go
+++ /dev/null
@@ -1,1042 +0,0 @@
-/*
- * Copyright (c) 2013 Dave Collins
- *
- * Permission to use, copy, modify, and distribute this software for any
- * purpose with or without fee is hereby granted, provided that the above
- * copyright notice and this permission notice appear in all copies.
- *
- * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
- * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
- * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
- * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
- * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
- * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
- */
-
-/*
-Test Summary:
-NOTE: For each test, a nil pointer, a single pointer and double pointer to the
-base test element are also tested to ensure proper indirection across all types.
-
-- Max int8, int16, int32, int64, int
-- Max uint8, uint16, uint32, uint64, uint
-- Boolean true and false
-- Standard complex64 and complex128
-- Array containing standard ints
-- Array containing type with custom formatter on pointer receiver only
-- Array containing interfaces
-- Array containing bytes
-- Slice containing standard float32 values
-- Slice containing type with custom formatter on pointer receiver only
-- Slice containing interfaces
-- Slice containing bytes
-- Nil slice
-- Standard string
-- Nil interface
-- Sub-interface
-- Map with string keys and int vals
-- Map with custom formatter type on pointer receiver only keys and vals
-- Map with interface keys and values
-- Map with nil interface value
-- Struct with primitives
-- Struct that contains another struct
-- Struct that contains custom type with Stringer pointer interface via both
- exported and unexported fields
-- Struct that contains embedded struct and field to same struct
-- Uintptr to 0 (null pointer)
-- Uintptr address of real variable
-- Unsafe.Pointer to 0 (null pointer)
-- Unsafe.Pointer to address of real variable
-- Nil channel
-- Standard int channel
-- Function with no params and no returns
-- Function with param and no returns
-- Function with multiple params and multiple returns
-- Struct that is circular through self referencing
-- Structs that are circular through cross referencing
-- Structs that are indirectly circular
-- Type that panics in its Stringer interface
-*/
-
-package spew_test
-
-import (
- "bytes"
- "fmt"
- "testing"
- "unsafe"
-
- "github.com/davecgh/go-spew/spew"
-)
-
-// dumpTest is used to describe a test to be perfomed against the Dump method.
-type dumpTest struct {
- in interface{}
- wants []string
-}
-
-// dumpTests houses all of the tests to be performed against the Dump method.
-var dumpTests = make([]dumpTest, 0)
-
-// addDumpTest is a helper method to append the passed input and desired result
-// to dumpTests
-func addDumpTest(in interface{}, wants ...string) {
- test := dumpTest{in, wants}
- dumpTests = append(dumpTests, test)
-}
-
-func addIntDumpTests() {
- // Max int8.
- v := int8(127)
- nv := (*int8)(nil)
- pv := &v
- vAddr := fmt.Sprintf("%p", pv)
- pvAddr := fmt.Sprintf("%p", &pv)
- vt := "int8"
- vs := "127"
- addDumpTest(v, "("+vt+") "+vs+"\n")
- addDumpTest(pv, "(*"+vt+")("+vAddr+")("+vs+")\n")
- addDumpTest(&pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")("+vs+")\n")
- addDumpTest(nv, "(*"+vt+")()\n")
-
- // Max int16.
- v2 := int16(32767)
- nv2 := (*int16)(nil)
- pv2 := &v2
- v2Addr := fmt.Sprintf("%p", pv2)
- pv2Addr := fmt.Sprintf("%p", &pv2)
- v2t := "int16"
- v2s := "32767"
- addDumpTest(v2, "("+v2t+") "+v2s+"\n")
- addDumpTest(pv2, "(*"+v2t+")("+v2Addr+")("+v2s+")\n")
- addDumpTest(&pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")("+v2s+")\n")
- addDumpTest(nv2, "(*"+v2t+")()\n")
-
- // Max int32.
- v3 := int32(2147483647)
- nv3 := (*int32)(nil)
- pv3 := &v3
- v3Addr := fmt.Sprintf("%p", pv3)
- pv3Addr := fmt.Sprintf("%p", &pv3)
- v3t := "int32"
- v3s := "2147483647"
- addDumpTest(v3, "("+v3t+") "+v3s+"\n")
- addDumpTest(pv3, "(*"+v3t+")("+v3Addr+")("+v3s+")\n")
- addDumpTest(&pv3, "(**"+v3t+")("+pv3Addr+"->"+v3Addr+")("+v3s+")\n")
- addDumpTest(nv3, "(*"+v3t+")()\n")
-
- // Max int64.
- v4 := int64(9223372036854775807)
- nv4 := (*int64)(nil)
- pv4 := &v4
- v4Addr := fmt.Sprintf("%p", pv4)
- pv4Addr := fmt.Sprintf("%p", &pv4)
- v4t := "int64"
- v4s := "9223372036854775807"
- addDumpTest(v4, "("+v4t+") "+v4s+"\n")
- addDumpTest(pv4, "(*"+v4t+")("+v4Addr+")("+v4s+")\n")
- addDumpTest(&pv4, "(**"+v4t+")("+pv4Addr+"->"+v4Addr+")("+v4s+")\n")
- addDumpTest(nv4, "(*"+v4t+")()\n")
-
- // Max int.
- v5 := int(2147483647)
- nv5 := (*int)(nil)
- pv5 := &v5
- v5Addr := fmt.Sprintf("%p", pv5)
- pv5Addr := fmt.Sprintf("%p", &pv5)
- v5t := "int"
- v5s := "2147483647"
- addDumpTest(v5, "("+v5t+") "+v5s+"\n")
- addDumpTest(pv5, "(*"+v5t+")("+v5Addr+")("+v5s+")\n")
- addDumpTest(&pv5, "(**"+v5t+")("+pv5Addr+"->"+v5Addr+")("+v5s+")\n")
- addDumpTest(nv5, "(*"+v5t+")()\n")
-}
-
-func addUintDumpTests() {
- // Max uint8.
- v := uint8(255)
- nv := (*uint8)(nil)
- pv := &v
- vAddr := fmt.Sprintf("%p", pv)
- pvAddr := fmt.Sprintf("%p", &pv)
- vt := "uint8"
- vs := "255"
- addDumpTest(v, "("+vt+") "+vs+"\n")
- addDumpTest(pv, "(*"+vt+")("+vAddr+")("+vs+")\n")
- addDumpTest(&pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")("+vs+")\n")
- addDumpTest(nv, "(*"+vt+")()\n")
-
- // Max uint16.
- v2 := uint16(65535)
- nv2 := (*uint16)(nil)
- pv2 := &v2
- v2Addr := fmt.Sprintf("%p", pv2)
- pv2Addr := fmt.Sprintf("%p", &pv2)
- v2t := "uint16"
- v2s := "65535"
- addDumpTest(v2, "("+v2t+") "+v2s+"\n")
- addDumpTest(pv2, "(*"+v2t+")("+v2Addr+")("+v2s+")\n")
- addDumpTest(&pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")("+v2s+")\n")
- addDumpTest(nv2, "(*"+v2t+")()\n")
-
- // Max uint32.
- v3 := uint32(4294967295)
- nv3 := (*uint32)(nil)
- pv3 := &v3
- v3Addr := fmt.Sprintf("%p", pv3)
- pv3Addr := fmt.Sprintf("%p", &pv3)
- v3t := "uint32"
- v3s := "4294967295"
- addDumpTest(v3, "("+v3t+") "+v3s+"\n")
- addDumpTest(pv3, "(*"+v3t+")("+v3Addr+")("+v3s+")\n")
- addDumpTest(&pv3, "(**"+v3t+")("+pv3Addr+"->"+v3Addr+")("+v3s+")\n")
- addDumpTest(nv3, "(*"+v3t+")()\n")
-
- // Max uint64.
- v4 := uint64(18446744073709551615)
- nv4 := (*uint64)(nil)
- pv4 := &v4
- v4Addr := fmt.Sprintf("%p", pv4)
- pv4Addr := fmt.Sprintf("%p", &pv4)
- v4t := "uint64"
- v4s := "18446744073709551615"
- addDumpTest(v4, "("+v4t+") "+v4s+"\n")
- addDumpTest(pv4, "(*"+v4t+")("+v4Addr+")("+v4s+")\n")
- addDumpTest(&pv4, "(**"+v4t+")("+pv4Addr+"->"+v4Addr+")("+v4s+")\n")
- addDumpTest(nv4, "(*"+v4t+")()\n")
-
- // Max uint.
- v5 := uint(4294967295)
- nv5 := (*uint)(nil)
- pv5 := &v5
- v5Addr := fmt.Sprintf("%p", pv5)
- pv5Addr := fmt.Sprintf("%p", &pv5)
- v5t := "uint"
- v5s := "4294967295"
- addDumpTest(v5, "("+v5t+") "+v5s+"\n")
- addDumpTest(pv5, "(*"+v5t+")("+v5Addr+")("+v5s+")\n")
- addDumpTest(&pv5, "(**"+v5t+")("+pv5Addr+"->"+v5Addr+")("+v5s+")\n")
- addDumpTest(nv5, "(*"+v5t+")()\n")
-}
-
-func addBoolDumpTests() {
- // Boolean true.
- v := bool(true)
- nv := (*bool)(nil)
- pv := &v
- vAddr := fmt.Sprintf("%p", pv)
- pvAddr := fmt.Sprintf("%p", &pv)
- vt := "bool"
- vs := "true"
- addDumpTest(v, "("+vt+") "+vs+"\n")
- addDumpTest(pv, "(*"+vt+")("+vAddr+")("+vs+")\n")
- addDumpTest(&pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")("+vs+")\n")
- addDumpTest(nv, "(*"+vt+")()\n")
-
- // Boolean false.
- v2 := bool(false)
- pv2 := &v2
- v2Addr := fmt.Sprintf("%p", pv2)
- pv2Addr := fmt.Sprintf("%p", &pv2)
- v2t := "bool"
- v2s := "false"
- addDumpTest(v2, "("+v2t+") "+v2s+"\n")
- addDumpTest(pv2, "(*"+v2t+")("+v2Addr+")("+v2s+")\n")
- addDumpTest(&pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")("+v2s+")\n")
-}
-
-func addFloatDumpTests() {
- // Standard float32.
- v := float32(3.1415)
- nv := (*float32)(nil)
- pv := &v
- vAddr := fmt.Sprintf("%p", pv)
- pvAddr := fmt.Sprintf("%p", &pv)
- vt := "float32"
- vs := "3.1415"
- addDumpTest(v, "("+vt+") "+vs+"\n")
- addDumpTest(pv, "(*"+vt+")("+vAddr+")("+vs+")\n")
- addDumpTest(&pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")("+vs+")\n")
- addDumpTest(nv, "(*"+vt+")()\n")
-
- // Standard float64.
- v2 := float64(3.1415926)
- nv2 := (*float64)(nil)
- pv2 := &v2
- v2Addr := fmt.Sprintf("%p", pv2)
- pv2Addr := fmt.Sprintf("%p", &pv2)
- v2t := "float64"
- v2s := "3.1415926"
- addDumpTest(v2, "("+v2t+") "+v2s+"\n")
- addDumpTest(pv2, "(*"+v2t+")("+v2Addr+")("+v2s+")\n")
- addDumpTest(&pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")("+v2s+")\n")
- addDumpTest(nv2, "(*"+v2t+")()\n")
-}
-
-func addComplexDumpTests() {
- // Standard complex64.
- v := complex(float32(6), -2)
- nv := (*complex64)(nil)
- pv := &v
- vAddr := fmt.Sprintf("%p", pv)
- pvAddr := fmt.Sprintf("%p", &pv)
- vt := "complex64"
- vs := "(6-2i)"
- addDumpTest(v, "("+vt+") "+vs+"\n")
- addDumpTest(pv, "(*"+vt+")("+vAddr+")("+vs+")\n")
- addDumpTest(&pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")("+vs+")\n")
- addDumpTest(nv, "(*"+vt+")()\n")
-
- // Standard complex128.
- v2 := complex(float64(-6), 2)
- nv2 := (*complex128)(nil)
- pv2 := &v2
- v2Addr := fmt.Sprintf("%p", pv2)
- pv2Addr := fmt.Sprintf("%p", &pv2)
- v2t := "complex128"
- v2s := "(-6+2i)"
- addDumpTest(v2, "("+v2t+") "+v2s+"\n")
- addDumpTest(pv2, "(*"+v2t+")("+v2Addr+")("+v2s+")\n")
- addDumpTest(&pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")("+v2s+")\n")
- addDumpTest(nv2, "(*"+v2t+")()\n")
-}
-
-func addArrayDumpTests() {
- // Array containing standard ints.
- v := [3]int{1, 2, 3}
- vLen := fmt.Sprintf("%d", len(v))
- vCap := fmt.Sprintf("%d", cap(v))
- nv := (*[3]int)(nil)
- pv := &v
- vAddr := fmt.Sprintf("%p", pv)
- pvAddr := fmt.Sprintf("%p", &pv)
- vt := "int"
- vs := "(len=" + vLen + " cap=" + vCap + ") {\n (" + vt + ") 1,\n (" +
- vt + ") 2,\n (" + vt + ") 3\n}"
- addDumpTest(v, "([3]"+vt+") "+vs+"\n")
- addDumpTest(pv, "(*[3]"+vt+")("+vAddr+")("+vs+")\n")
- addDumpTest(&pv, "(**[3]"+vt+")("+pvAddr+"->"+vAddr+")("+vs+")\n")
- addDumpTest(nv, "(*[3]"+vt+")()\n")
-
- // Array containing type with custom formatter on pointer receiver only.
- v2i0 := pstringer("1")
- v2i1 := pstringer("2")
- v2i2 := pstringer("3")
- v2 := [3]pstringer{v2i0, v2i1, v2i2}
- v2i0Len := fmt.Sprintf("%d", len(v2i0))
- v2i1Len := fmt.Sprintf("%d", len(v2i1))
- v2i2Len := fmt.Sprintf("%d", len(v2i2))
- v2Len := fmt.Sprintf("%d", len(v2))
- v2Cap := fmt.Sprintf("%d", cap(v2))
- nv2 := (*[3]pstringer)(nil)
- pv2 := &v2
- v2Addr := fmt.Sprintf("%p", pv2)
- pv2Addr := fmt.Sprintf("%p", &pv2)
- v2t := "spew_test.pstringer"
- v2sp := "(len=" + v2Len + " cap=" + v2Cap + ") {\n (" + v2t +
- ") (len=" + v2i0Len + ") stringer 1,\n (" + v2t +
- ") (len=" + v2i1Len + ") stringer 2,\n (" + v2t +
- ") (len=" + v2i2Len + ") " + "stringer 3\n}"
- v2s := v2sp
- if spew.UnsafeDisabled {
- v2s = "(len=" + v2Len + " cap=" + v2Cap + ") {\n (" + v2t +
- ") (len=" + v2i0Len + ") \"1\",\n (" + v2t + ") (len=" +
- v2i1Len + ") \"2\",\n (" + v2t + ") (len=" + v2i2Len +
- ") " + "\"3\"\n}"
- }
- addDumpTest(v2, "([3]"+v2t+") "+v2s+"\n")
- addDumpTest(pv2, "(*[3]"+v2t+")("+v2Addr+")("+v2sp+")\n")
- addDumpTest(&pv2, "(**[3]"+v2t+")("+pv2Addr+"->"+v2Addr+")("+v2sp+")\n")
- addDumpTest(nv2, "(*[3]"+v2t+")()\n")
-
- // Array containing interfaces.
- v3i0 := "one"
- v3 := [3]interface{}{v3i0, int(2), uint(3)}
- v3i0Len := fmt.Sprintf("%d", len(v3i0))
- v3Len := fmt.Sprintf("%d", len(v3))
- v3Cap := fmt.Sprintf("%d", cap(v3))
- nv3 := (*[3]interface{})(nil)
- pv3 := &v3
- v3Addr := fmt.Sprintf("%p", pv3)
- pv3Addr := fmt.Sprintf("%p", &pv3)
- v3t := "[3]interface {}"
- v3t2 := "string"
- v3t3 := "int"
- v3t4 := "uint"
- v3s := "(len=" + v3Len + " cap=" + v3Cap + ") {\n (" + v3t2 + ") " +
- "(len=" + v3i0Len + ") \"one\",\n (" + v3t3 + ") 2,\n (" +
- v3t4 + ") 3\n}"
- addDumpTest(v3, "("+v3t+") "+v3s+"\n")
- addDumpTest(pv3, "(*"+v3t+")("+v3Addr+")("+v3s+")\n")
- addDumpTest(&pv3, "(**"+v3t+")("+pv3Addr+"->"+v3Addr+")("+v3s+")\n")
- addDumpTest(nv3, "(*"+v3t+")()\n")
-
- // Array containing bytes.
- v4 := [34]byte{
- 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18,
- 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20,
- 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28,
- 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, 0x30,
- 0x31, 0x32,
- }
- v4Len := fmt.Sprintf("%d", len(v4))
- v4Cap := fmt.Sprintf("%d", cap(v4))
- nv4 := (*[34]byte)(nil)
- pv4 := &v4
- v4Addr := fmt.Sprintf("%p", pv4)
- pv4Addr := fmt.Sprintf("%p", &pv4)
- v4t := "[34]uint8"
- v4s := "(len=" + v4Len + " cap=" + v4Cap + ") " +
- "{\n 00000000 11 12 13 14 15 16 17 18 19 1a 1b 1c 1d 1e 1f 20" +
- " |............... |\n" +
- " 00000010 21 22 23 24 25 26 27 28 29 2a 2b 2c 2d 2e 2f 30" +
- " |!\"#$%&'()*+,-./0|\n" +
- " 00000020 31 32 " +
- " |12|\n}"
- addDumpTest(v4, "("+v4t+") "+v4s+"\n")
- addDumpTest(pv4, "(*"+v4t+")("+v4Addr+")("+v4s+")\n")
- addDumpTest(&pv4, "(**"+v4t+")("+pv4Addr+"->"+v4Addr+")("+v4s+")\n")
- addDumpTest(nv4, "(*"+v4t+")()\n")
-}
-
-func addSliceDumpTests() {
- // Slice containing standard float32 values.
- v := []float32{3.14, 6.28, 12.56}
- vLen := fmt.Sprintf("%d", len(v))
- vCap := fmt.Sprintf("%d", cap(v))
- nv := (*[]float32)(nil)
- pv := &v
- vAddr := fmt.Sprintf("%p", pv)
- pvAddr := fmt.Sprintf("%p", &pv)
- vt := "float32"
- vs := "(len=" + vLen + " cap=" + vCap + ") {\n (" + vt + ") 3.14,\n (" +
- vt + ") 6.28,\n (" + vt + ") 12.56\n}"
- addDumpTest(v, "([]"+vt+") "+vs+"\n")
- addDumpTest(pv, "(*[]"+vt+")("+vAddr+")("+vs+")\n")
- addDumpTest(&pv, "(**[]"+vt+")("+pvAddr+"->"+vAddr+")("+vs+")\n")
- addDumpTest(nv, "(*[]"+vt+")()\n")
-
- // Slice containing type with custom formatter on pointer receiver only.
- v2i0 := pstringer("1")
- v2i1 := pstringer("2")
- v2i2 := pstringer("3")
- v2 := []pstringer{v2i0, v2i1, v2i2}
- v2i0Len := fmt.Sprintf("%d", len(v2i0))
- v2i1Len := fmt.Sprintf("%d", len(v2i1))
- v2i2Len := fmt.Sprintf("%d", len(v2i2))
- v2Len := fmt.Sprintf("%d", len(v2))
- v2Cap := fmt.Sprintf("%d", cap(v2))
- nv2 := (*[]pstringer)(nil)
- pv2 := &v2
- v2Addr := fmt.Sprintf("%p", pv2)
- pv2Addr := fmt.Sprintf("%p", &pv2)
- v2t := "spew_test.pstringer"
- v2s := "(len=" + v2Len + " cap=" + v2Cap + ") {\n (" + v2t + ") (len=" +
- v2i0Len + ") stringer 1,\n (" + v2t + ") (len=" + v2i1Len +
- ") stringer 2,\n (" + v2t + ") (len=" + v2i2Len + ") " +
- "stringer 3\n}"
- addDumpTest(v2, "([]"+v2t+") "+v2s+"\n")
- addDumpTest(pv2, "(*[]"+v2t+")("+v2Addr+")("+v2s+")\n")
- addDumpTest(&pv2, "(**[]"+v2t+")("+pv2Addr+"->"+v2Addr+")("+v2s+")\n")
- addDumpTest(nv2, "(*[]"+v2t+")()\n")
-
- // Slice containing interfaces.
- v3i0 := "one"
- v3 := []interface{}{v3i0, int(2), uint(3), nil}
- v3i0Len := fmt.Sprintf("%d", len(v3i0))
- v3Len := fmt.Sprintf("%d", len(v3))
- v3Cap := fmt.Sprintf("%d", cap(v3))
- nv3 := (*[]interface{})(nil)
- pv3 := &v3
- v3Addr := fmt.Sprintf("%p", pv3)
- pv3Addr := fmt.Sprintf("%p", &pv3)
- v3t := "[]interface {}"
- v3t2 := "string"
- v3t3 := "int"
- v3t4 := "uint"
- v3t5 := "interface {}"
- v3s := "(len=" + v3Len + " cap=" + v3Cap + ") {\n (" + v3t2 + ") " +
- "(len=" + v3i0Len + ") \"one\",\n (" + v3t3 + ") 2,\n (" +
- v3t4 + ") 3,\n (" + v3t5 + ") \n}"
- addDumpTest(v3, "("+v3t+") "+v3s+"\n")
- addDumpTest(pv3, "(*"+v3t+")("+v3Addr+")("+v3s+")\n")
- addDumpTest(&pv3, "(**"+v3t+")("+pv3Addr+"->"+v3Addr+")("+v3s+")\n")
- addDumpTest(nv3, "(*"+v3t+")()\n")
-
- // Slice containing bytes.
- v4 := []byte{
- 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18,
- 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20,
- 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28,
- 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, 0x30,
- 0x31, 0x32,
- }
- v4Len := fmt.Sprintf("%d", len(v4))
- v4Cap := fmt.Sprintf("%d", cap(v4))
- nv4 := (*[]byte)(nil)
- pv4 := &v4
- v4Addr := fmt.Sprintf("%p", pv4)
- pv4Addr := fmt.Sprintf("%p", &pv4)
- v4t := "[]uint8"
- v4s := "(len=" + v4Len + " cap=" + v4Cap + ") " +
- "{\n 00000000 11 12 13 14 15 16 17 18 19 1a 1b 1c 1d 1e 1f 20" +
- " |............... |\n" +
- " 00000010 21 22 23 24 25 26 27 28 29 2a 2b 2c 2d 2e 2f 30" +
- " |!\"#$%&'()*+,-./0|\n" +
- " 00000020 31 32 " +
- " |12|\n}"
- addDumpTest(v4, "("+v4t+") "+v4s+"\n")
- addDumpTest(pv4, "(*"+v4t+")("+v4Addr+")("+v4s+")\n")
- addDumpTest(&pv4, "(**"+v4t+")("+pv4Addr+"->"+v4Addr+")("+v4s+")\n")
- addDumpTest(nv4, "(*"+v4t+")()\n")
-
- // Nil slice.
- v5 := []int(nil)
- nv5 := (*[]int)(nil)
- pv5 := &v5
- v5Addr := fmt.Sprintf("%p", pv5)
- pv5Addr := fmt.Sprintf("%p", &pv5)
- v5t := "[]int"
- v5s := ""
- addDumpTest(v5, "("+v5t+") "+v5s+"\n")
- addDumpTest(pv5, "(*"+v5t+")("+v5Addr+")("+v5s+")\n")
- addDumpTest(&pv5, "(**"+v5t+")("+pv5Addr+"->"+v5Addr+")("+v5s+")\n")
- addDumpTest(nv5, "(*"+v5t+")()\n")
-}
-
-func addStringDumpTests() {
- // Standard string.
- v := "test"
- vLen := fmt.Sprintf("%d", len(v))
- nv := (*string)(nil)
- pv := &v
- vAddr := fmt.Sprintf("%p", pv)
- pvAddr := fmt.Sprintf("%p", &pv)
- vt := "string"
- vs := "(len=" + vLen + ") \"test\""
- addDumpTest(v, "("+vt+") "+vs+"\n")
- addDumpTest(pv, "(*"+vt+")("+vAddr+")("+vs+")\n")
- addDumpTest(&pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")("+vs+")\n")
- addDumpTest(nv, "(*"+vt+")()\n")
-}
-
-func addInterfaceDumpTests() {
- // Nil interface.
- var v interface{}
- nv := (*interface{})(nil)
- pv := &v
- vAddr := fmt.Sprintf("%p", pv)
- pvAddr := fmt.Sprintf("%p", &pv)
- vt := "interface {}"
- vs := ""
- addDumpTest(v, "("+vt+") "+vs+"\n")
- addDumpTest(pv, "(*"+vt+")("+vAddr+")("+vs+")\n")
- addDumpTest(&pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")("+vs+")\n")
- addDumpTest(nv, "(*"+vt+")()\n")
-
- // Sub-interface.
- v2 := interface{}(uint16(65535))
- pv2 := &v2
- v2Addr := fmt.Sprintf("%p", pv2)
- pv2Addr := fmt.Sprintf("%p", &pv2)
- v2t := "uint16"
- v2s := "65535"
- addDumpTest(v2, "("+v2t+") "+v2s+"\n")
- addDumpTest(pv2, "(*"+v2t+")("+v2Addr+")("+v2s+")\n")
- addDumpTest(&pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")("+v2s+")\n")
-}
-
-func addMapDumpTests() {
- // Map with string keys and int vals.
- k := "one"
- kk := "two"
- m := map[string]int{k: 1, kk: 2}
- klen := fmt.Sprintf("%d", len(k)) // not kLen to shut golint up
- kkLen := fmt.Sprintf("%d", len(kk))
- mLen := fmt.Sprintf("%d", len(m))
- nilMap := map[string]int(nil)
- nm := (*map[string]int)(nil)
- pm := &m
- mAddr := fmt.Sprintf("%p", pm)
- pmAddr := fmt.Sprintf("%p", &pm)
- mt := "map[string]int"
- mt1 := "string"
- mt2 := "int"
- ms := "(len=" + mLen + ") {\n (" + mt1 + ") (len=" + klen + ") " +
- "\"one\": (" + mt2 + ") 1,\n (" + mt1 + ") (len=" + kkLen +
- ") \"two\": (" + mt2 + ") 2\n}"
- ms2 := "(len=" + mLen + ") {\n (" + mt1 + ") (len=" + kkLen + ") " +
- "\"two\": (" + mt2 + ") 2,\n (" + mt1 + ") (len=" + klen +
- ") \"one\": (" + mt2 + ") 1\n}"
- addDumpTest(m, "("+mt+") "+ms+"\n", "("+mt+") "+ms2+"\n")
- addDumpTest(pm, "(*"+mt+")("+mAddr+")("+ms+")\n",
- "(*"+mt+")("+mAddr+")("+ms2+")\n")
- addDumpTest(&pm, "(**"+mt+")("+pmAddr+"->"+mAddr+")("+ms+")\n",
- "(**"+mt+")("+pmAddr+"->"+mAddr+")("+ms2+")\n")
- addDumpTest(nm, "(*"+mt+")()\n")
- addDumpTest(nilMap, "("+mt+") \n")
-
- // Map with custom formatter type on pointer receiver only keys and vals.
- k2 := pstringer("one")
- v2 := pstringer("1")
- m2 := map[pstringer]pstringer{k2: v2}
- k2Len := fmt.Sprintf("%d", len(k2))
- v2Len := fmt.Sprintf("%d", len(v2))
- m2Len := fmt.Sprintf("%d", len(m2))
- nilMap2 := map[pstringer]pstringer(nil)
- nm2 := (*map[pstringer]pstringer)(nil)
- pm2 := &m2
- m2Addr := fmt.Sprintf("%p", pm2)
- pm2Addr := fmt.Sprintf("%p", &pm2)
- m2t := "map[spew_test.pstringer]spew_test.pstringer"
- m2t1 := "spew_test.pstringer"
- m2t2 := "spew_test.pstringer"
- m2s := "(len=" + m2Len + ") {\n (" + m2t1 + ") (len=" + k2Len + ") " +
- "stringer one: (" + m2t2 + ") (len=" + v2Len + ") stringer 1\n}"
- if spew.UnsafeDisabled {
- m2s = "(len=" + m2Len + ") {\n (" + m2t1 + ") (len=" + k2Len +
- ") " + "\"one\": (" + m2t2 + ") (len=" + v2Len +
- ") \"1\"\n}"
- }
- addDumpTest(m2, "("+m2t+") "+m2s+"\n")
- addDumpTest(pm2, "(*"+m2t+")("+m2Addr+")("+m2s+")\n")
- addDumpTest(&pm2, "(**"+m2t+")("+pm2Addr+"->"+m2Addr+")("+m2s+")\n")
- addDumpTest(nm2, "(*"+m2t+")()\n")
- addDumpTest(nilMap2, "("+m2t+") \n")
-
- // Map with interface keys and values.
- k3 := "one"
- k3Len := fmt.Sprintf("%d", len(k3))
- m3 := map[interface{}]interface{}{k3: 1}
- m3Len := fmt.Sprintf("%d", len(m3))
- nilMap3 := map[interface{}]interface{}(nil)
- nm3 := (*map[interface{}]interface{})(nil)
- pm3 := &m3
- m3Addr := fmt.Sprintf("%p", pm3)
- pm3Addr := fmt.Sprintf("%p", &pm3)
- m3t := "map[interface {}]interface {}"
- m3t1 := "string"
- m3t2 := "int"
- m3s := "(len=" + m3Len + ") {\n (" + m3t1 + ") (len=" + k3Len + ") " +
- "\"one\": (" + m3t2 + ") 1\n}"
- addDumpTest(m3, "("+m3t+") "+m3s+"\n")
- addDumpTest(pm3, "(*"+m3t+")("+m3Addr+")("+m3s+")\n")
- addDumpTest(&pm3, "(**"+m3t+")("+pm3Addr+"->"+m3Addr+")("+m3s+")\n")
- addDumpTest(nm3, "(*"+m3t+")()\n")
- addDumpTest(nilMap3, "("+m3t+") \n")
-
- // Map with nil interface value.
- k4 := "nil"
- k4Len := fmt.Sprintf("%d", len(k4))
- m4 := map[string]interface{}{k4: nil}
- m4Len := fmt.Sprintf("%d", len(m4))
- nilMap4 := map[string]interface{}(nil)
- nm4 := (*map[string]interface{})(nil)
- pm4 := &m4
- m4Addr := fmt.Sprintf("%p", pm4)
- pm4Addr := fmt.Sprintf("%p", &pm4)
- m4t := "map[string]interface {}"
- m4t1 := "string"
- m4t2 := "interface {}"
- m4s := "(len=" + m4Len + ") {\n (" + m4t1 + ") (len=" + k4Len + ")" +
- " \"nil\": (" + m4t2 + ") \n}"
- addDumpTest(m4, "("+m4t+") "+m4s+"\n")
- addDumpTest(pm4, "(*"+m4t+")("+m4Addr+")("+m4s+")\n")
- addDumpTest(&pm4, "(**"+m4t+")("+pm4Addr+"->"+m4Addr+")("+m4s+")\n")
- addDumpTest(nm4, "(*"+m4t+")()\n")
- addDumpTest(nilMap4, "("+m4t+") \n")
-}
-
-func addStructDumpTests() {
- // Struct with primitives.
- type s1 struct {
- a int8
- b uint8
- }
- v := s1{127, 255}
- nv := (*s1)(nil)
- pv := &v
- vAddr := fmt.Sprintf("%p", pv)
- pvAddr := fmt.Sprintf("%p", &pv)
- vt := "spew_test.s1"
- vt2 := "int8"
- vt3 := "uint8"
- vs := "{\n a: (" + vt2 + ") 127,\n b: (" + vt3 + ") 255\n}"
- addDumpTest(v, "("+vt+") "+vs+"\n")
- addDumpTest(pv, "(*"+vt+")("+vAddr+")("+vs+")\n")
- addDumpTest(&pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")("+vs+")\n")
- addDumpTest(nv, "(*"+vt+")()\n")
-
- // Struct that contains another struct.
- type s2 struct {
- s1 s1
- b bool
- }
- v2 := s2{s1{127, 255}, true}
- nv2 := (*s2)(nil)
- pv2 := &v2
- v2Addr := fmt.Sprintf("%p", pv2)
- pv2Addr := fmt.Sprintf("%p", &pv2)
- v2t := "spew_test.s2"
- v2t2 := "spew_test.s1"
- v2t3 := "int8"
- v2t4 := "uint8"
- v2t5 := "bool"
- v2s := "{\n s1: (" + v2t2 + ") {\n a: (" + v2t3 + ") 127,\n b: (" +
- v2t4 + ") 255\n },\n b: (" + v2t5 + ") true\n}"
- addDumpTest(v2, "("+v2t+") "+v2s+"\n")
- addDumpTest(pv2, "(*"+v2t+")("+v2Addr+")("+v2s+")\n")
- addDumpTest(&pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")("+v2s+")\n")
- addDumpTest(nv2, "(*"+v2t+")()\n")
-
- // Struct that contains custom type with Stringer pointer interface via both
- // exported and unexported fields.
- type s3 struct {
- s pstringer
- S pstringer
- }
- v3 := s3{"test", "test2"}
- nv3 := (*s3)(nil)
- pv3 := &v3
- v3Addr := fmt.Sprintf("%p", pv3)
- pv3Addr := fmt.Sprintf("%p", &pv3)
- v3t := "spew_test.s3"
- v3t2 := "spew_test.pstringer"
- v3s := "{\n s: (" + v3t2 + ") (len=4) stringer test,\n S: (" + v3t2 +
- ") (len=5) stringer test2\n}"
- v3sp := v3s
- if spew.UnsafeDisabled {
- v3s = "{\n s: (" + v3t2 + ") (len=4) \"test\",\n S: (" +
- v3t2 + ") (len=5) \"test2\"\n}"
- v3sp = "{\n s: (" + v3t2 + ") (len=4) \"test\",\n S: (" +
- v3t2 + ") (len=5) stringer test2\n}"
- }
- addDumpTest(v3, "("+v3t+") "+v3s+"\n")
- addDumpTest(pv3, "(*"+v3t+")("+v3Addr+")("+v3sp+")\n")
- addDumpTest(&pv3, "(**"+v3t+")("+pv3Addr+"->"+v3Addr+")("+v3sp+")\n")
- addDumpTest(nv3, "(*"+v3t+")()\n")
-
- // Struct that contains embedded struct and field to same struct.
- e := embed{"embedstr"}
- eLen := fmt.Sprintf("%d", len("embedstr"))
- v4 := embedwrap{embed: &e, e: &e}
- nv4 := (*embedwrap)(nil)
- pv4 := &v4
- eAddr := fmt.Sprintf("%p", &e)
- v4Addr := fmt.Sprintf("%p", pv4)
- pv4Addr := fmt.Sprintf("%p", &pv4)
- v4t := "spew_test.embedwrap"
- v4t2 := "spew_test.embed"
- v4t3 := "string"
- v4s := "{\n embed: (*" + v4t2 + ")(" + eAddr + ")({\n a: (" + v4t3 +
- ") (len=" + eLen + ") \"embedstr\"\n }),\n e: (*" + v4t2 +
- ")(" + eAddr + ")({\n a: (" + v4t3 + ") (len=" + eLen + ")" +
- " \"embedstr\"\n })\n}"
- addDumpTest(v4, "("+v4t+") "+v4s+"\n")
- addDumpTest(pv4, "(*"+v4t+")("+v4Addr+")("+v4s+")\n")
- addDumpTest(&pv4, "(**"+v4t+")("+pv4Addr+"->"+v4Addr+")("+v4s+")\n")
- addDumpTest(nv4, "(*"+v4t+")()\n")
-}
-
-func addUintptrDumpTests() {
- // Null pointer.
- v := uintptr(0)
- pv := &v
- vAddr := fmt.Sprintf("%p", pv)
- pvAddr := fmt.Sprintf("%p", &pv)
- vt := "uintptr"
- vs := ""
- addDumpTest(v, "("+vt+") "+vs+"\n")
- addDumpTest(pv, "(*"+vt+")("+vAddr+")("+vs+")\n")
- addDumpTest(&pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")("+vs+")\n")
-
- // Address of real variable.
- i := 1
- v2 := uintptr(unsafe.Pointer(&i))
- nv2 := (*uintptr)(nil)
- pv2 := &v2
- v2Addr := fmt.Sprintf("%p", pv2)
- pv2Addr := fmt.Sprintf("%p", &pv2)
- v2t := "uintptr"
- v2s := fmt.Sprintf("%p", &i)
- addDumpTest(v2, "("+v2t+") "+v2s+"\n")
- addDumpTest(pv2, "(*"+v2t+")("+v2Addr+")("+v2s+")\n")
- addDumpTest(&pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")("+v2s+")\n")
- addDumpTest(nv2, "(*"+v2t+")()\n")
-}
-
-func addUnsafePointerDumpTests() {
- // Null pointer.
- v := unsafe.Pointer(uintptr(0))
- nv := (*unsafe.Pointer)(nil)
- pv := &v
- vAddr := fmt.Sprintf("%p", pv)
- pvAddr := fmt.Sprintf("%p", &pv)
- vt := "unsafe.Pointer"
- vs := ""
- addDumpTest(v, "("+vt+") "+vs+"\n")
- addDumpTest(pv, "(*"+vt+")("+vAddr+")("+vs+")\n")
- addDumpTest(&pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")("+vs+")\n")
- addDumpTest(nv, "(*"+vt+")()\n")
-
- // Address of real variable.
- i := 1
- v2 := unsafe.Pointer(&i)
- pv2 := &v2
- v2Addr := fmt.Sprintf("%p", pv2)
- pv2Addr := fmt.Sprintf("%p", &pv2)
- v2t := "unsafe.Pointer"
- v2s := fmt.Sprintf("%p", &i)
- addDumpTest(v2, "("+v2t+") "+v2s+"\n")
- addDumpTest(pv2, "(*"+v2t+")("+v2Addr+")("+v2s+")\n")
- addDumpTest(&pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")("+v2s+")\n")
- addDumpTest(nv, "(*"+vt+")()\n")
-}
-
-func addChanDumpTests() {
- // Nil channel.
- var v chan int
- pv := &v
- nv := (*chan int)(nil)
- vAddr := fmt.Sprintf("%p", pv)
- pvAddr := fmt.Sprintf("%p", &pv)
- vt := "chan int"
- vs := ""
- addDumpTest(v, "("+vt+") "+vs+"\n")
- addDumpTest(pv, "(*"+vt+")("+vAddr+")("+vs+")\n")
- addDumpTest(&pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")("+vs+")\n")
- addDumpTest(nv, "(*"+vt+")()\n")
-
- // Real channel.
- v2 := make(chan int)
- pv2 := &v2
- v2Addr := fmt.Sprintf("%p", pv2)
- pv2Addr := fmt.Sprintf("%p", &pv2)
- v2t := "chan int"
- v2s := fmt.Sprintf("%p", v2)
- addDumpTest(v2, "("+v2t+") "+v2s+"\n")
- addDumpTest(pv2, "(*"+v2t+")("+v2Addr+")("+v2s+")\n")
- addDumpTest(&pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")("+v2s+")\n")
-}
-
-func addFuncDumpTests() {
- // Function with no params and no returns.
- v := addIntDumpTests
- nv := (*func())(nil)
- pv := &v
- vAddr := fmt.Sprintf("%p", pv)
- pvAddr := fmt.Sprintf("%p", &pv)
- vt := "func()"
- vs := fmt.Sprintf("%p", v)
- addDumpTest(v, "("+vt+") "+vs+"\n")
- addDumpTest(pv, "(*"+vt+")("+vAddr+")("+vs+")\n")
- addDumpTest(&pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")("+vs+")\n")
- addDumpTest(nv, "(*"+vt+")()\n")
-
- // Function with param and no returns.
- v2 := TestDump
- nv2 := (*func(*testing.T))(nil)
- pv2 := &v2
- v2Addr := fmt.Sprintf("%p", pv2)
- pv2Addr := fmt.Sprintf("%p", &pv2)
- v2t := "func(*testing.T)"
- v2s := fmt.Sprintf("%p", v2)
- addDumpTest(v2, "("+v2t+") "+v2s+"\n")
- addDumpTest(pv2, "(*"+v2t+")("+v2Addr+")("+v2s+")\n")
- addDumpTest(&pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")("+v2s+")\n")
- addDumpTest(nv2, "(*"+v2t+")()\n")
-
- // Function with multiple params and multiple returns.
- var v3 = func(i int, s string) (b bool, err error) {
- return true, nil
- }
- nv3 := (*func(int, string) (bool, error))(nil)
- pv3 := &v3
- v3Addr := fmt.Sprintf("%p", pv3)
- pv3Addr := fmt.Sprintf("%p", &pv3)
- v3t := "func(int, string) (bool, error)"
- v3s := fmt.Sprintf("%p", v3)
- addDumpTest(v3, "("+v3t+") "+v3s+"\n")
- addDumpTest(pv3, "(*"+v3t+")("+v3Addr+")("+v3s+")\n")
- addDumpTest(&pv3, "(**"+v3t+")("+pv3Addr+"->"+v3Addr+")("+v3s+")\n")
- addDumpTest(nv3, "(*"+v3t+")()\n")
-}
-
-func addCircularDumpTests() {
- // Struct that is circular through self referencing.
- type circular struct {
- c *circular
- }
- v := circular{nil}
- v.c = &v
- pv := &v
- vAddr := fmt.Sprintf("%p", pv)
- pvAddr := fmt.Sprintf("%p", &pv)
- vt := "spew_test.circular"
- vs := "{\n c: (*" + vt + ")(" + vAddr + ")({\n c: (*" + vt + ")(" +
- vAddr + ")()\n })\n}"
- vs2 := "{\n c: (*" + vt + ")(" + vAddr + ")()\n}"
- addDumpTest(v, "("+vt+") "+vs+"\n")
- addDumpTest(pv, "(*"+vt+")("+vAddr+")("+vs2+")\n")
- addDumpTest(&pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")("+vs2+")\n")
-
- // Structs that are circular through cross referencing.
- v2 := xref1{nil}
- ts2 := xref2{&v2}
- v2.ps2 = &ts2
- pv2 := &v2
- ts2Addr := fmt.Sprintf("%p", &ts2)
- v2Addr := fmt.Sprintf("%p", pv2)
- pv2Addr := fmt.Sprintf("%p", &pv2)
- v2t := "spew_test.xref1"
- v2t2 := "spew_test.xref2"
- v2s := "{\n ps2: (*" + v2t2 + ")(" + ts2Addr + ")({\n ps1: (*" + v2t +
- ")(" + v2Addr + ")({\n ps2: (*" + v2t2 + ")(" + ts2Addr +
- ")()\n })\n })\n}"
- v2s2 := "{\n ps2: (*" + v2t2 + ")(" + ts2Addr + ")({\n ps1: (*" + v2t +
- ")(" + v2Addr + ")()\n })\n}"
- addDumpTest(v2, "("+v2t+") "+v2s+"\n")
- addDumpTest(pv2, "(*"+v2t+")("+v2Addr+")("+v2s2+")\n")
- addDumpTest(&pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")("+v2s2+")\n")
-
- // Structs that are indirectly circular.
- v3 := indirCir1{nil}
- tic2 := indirCir2{nil}
- tic3 := indirCir3{&v3}
- tic2.ps3 = &tic3
- v3.ps2 = &tic2
- pv3 := &v3
- tic2Addr := fmt.Sprintf("%p", &tic2)
- tic3Addr := fmt.Sprintf("%p", &tic3)
- v3Addr := fmt.Sprintf("%p", pv3)
- pv3Addr := fmt.Sprintf("%p", &pv3)
- v3t := "spew_test.indirCir1"
- v3t2 := "spew_test.indirCir2"
- v3t3 := "spew_test.indirCir3"
- v3s := "{\n ps2: (*" + v3t2 + ")(" + tic2Addr + ")({\n ps3: (*" + v3t3 +
- ")(" + tic3Addr + ")({\n ps1: (*" + v3t + ")(" + v3Addr +
- ")({\n ps2: (*" + v3t2 + ")(" + tic2Addr +
- ")()\n })\n })\n })\n}"
- v3s2 := "{\n ps2: (*" + v3t2 + ")(" + tic2Addr + ")({\n ps3: (*" + v3t3 +
- ")(" + tic3Addr + ")({\n ps1: (*" + v3t + ")(" + v3Addr +
- ")()\n })\n })\n}"
- addDumpTest(v3, "("+v3t+") "+v3s+"\n")
- addDumpTest(pv3, "(*"+v3t+")("+v3Addr+")("+v3s2+")\n")
- addDumpTest(&pv3, "(**"+v3t+")("+pv3Addr+"->"+v3Addr+")("+v3s2+")\n")
-}
-
-func addPanicDumpTests() {
- // Type that panics in its Stringer interface.
- v := panicer(127)
- nv := (*panicer)(nil)
- pv := &v
- vAddr := fmt.Sprintf("%p", pv)
- pvAddr := fmt.Sprintf("%p", &pv)
- vt := "spew_test.panicer"
- vs := "(PANIC=test panic)127"
- addDumpTest(v, "("+vt+") "+vs+"\n")
- addDumpTest(pv, "(*"+vt+")("+vAddr+")("+vs+")\n")
- addDumpTest(&pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")("+vs+")\n")
- addDumpTest(nv, "(*"+vt+")()\n")
-}
-
-func addErrorDumpTests() {
- // Type that has a custom Error interface.
- v := customError(127)
- nv := (*customError)(nil)
- pv := &v
- vAddr := fmt.Sprintf("%p", pv)
- pvAddr := fmt.Sprintf("%p", &pv)
- vt := "spew_test.customError"
- vs := "error: 127"
- addDumpTest(v, "("+vt+") "+vs+"\n")
- addDumpTest(pv, "(*"+vt+")("+vAddr+")("+vs+")\n")
- addDumpTest(&pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")("+vs+")\n")
- addDumpTest(nv, "(*"+vt+")()\n")
-}
-
-// TestDump executes all of the tests described by dumpTests.
-func TestDump(t *testing.T) {
- // Setup tests.
- addIntDumpTests()
- addUintDumpTests()
- addBoolDumpTests()
- addFloatDumpTests()
- addComplexDumpTests()
- addArrayDumpTests()
- addSliceDumpTests()
- addStringDumpTests()
- addInterfaceDumpTests()
- addMapDumpTests()
- addStructDumpTests()
- addUintptrDumpTests()
- addUnsafePointerDumpTests()
- addChanDumpTests()
- addFuncDumpTests()
- addCircularDumpTests()
- addPanicDumpTests()
- addErrorDumpTests()
- addCgoDumpTests()
-
- t.Logf("Running %d tests", len(dumpTests))
- for i, test := range dumpTests {
- buf := new(bytes.Buffer)
- spew.Fdump(buf, test.in)
- s := buf.String()
- if testFailed(s, test.wants) {
- t.Errorf("Dump #%d\n got: %s %s", i, s, stringizeWants(test.wants))
- continue
- }
- }
-}
-
-func TestDumpSortedKeys(t *testing.T) {
- cfg := spew.ConfigState{SortKeys: true}
- s := cfg.Sdump(map[int]string{1: "1", 3: "3", 2: "2"})
- expected := "(map[int]string) (len=3) {\n(int) 1: (string) (len=1) " +
- "\"1\",\n(int) 2: (string) (len=1) \"2\",\n(int) 3: (string) " +
- "(len=1) \"3\"\n" +
- "}\n"
- if s != expected {
- t.Errorf("Sorted keys mismatch:\n %v %v", s, expected)
- }
-
- s = cfg.Sdump(map[stringer]int{"1": 1, "3": 3, "2": 2})
- expected = "(map[spew_test.stringer]int) (len=3) {\n" +
- "(spew_test.stringer) (len=1) stringer 1: (int) 1,\n" +
- "(spew_test.stringer) (len=1) stringer 2: (int) 2,\n" +
- "(spew_test.stringer) (len=1) stringer 3: (int) 3\n" +
- "}\n"
- if s != expected {
- t.Errorf("Sorted keys mismatch:\n %v %v", s, expected)
- }
-
- s = cfg.Sdump(map[pstringer]int{pstringer("1"): 1, pstringer("3"): 3, pstringer("2"): 2})
- expected = "(map[spew_test.pstringer]int) (len=3) {\n" +
- "(spew_test.pstringer) (len=1) stringer 1: (int) 1,\n" +
- "(spew_test.pstringer) (len=1) stringer 2: (int) 2,\n" +
- "(spew_test.pstringer) (len=1) stringer 3: (int) 3\n" +
- "}\n"
- if spew.UnsafeDisabled {
- expected = "(map[spew_test.pstringer]int) (len=3) {\n" +
- "(spew_test.pstringer) (len=1) \"1\": (int) 1,\n" +
- "(spew_test.pstringer) (len=1) \"2\": (int) 2,\n" +
- "(spew_test.pstringer) (len=1) \"3\": (int) 3\n" +
- "}\n"
- }
- if s != expected {
- t.Errorf("Sorted keys mismatch:\n %v %v", s, expected)
- }
-
- s = cfg.Sdump(map[customError]int{customError(1): 1, customError(3): 3, customError(2): 2})
- expected = "(map[spew_test.customError]int) (len=3) {\n" +
- "(spew_test.customError) error: 1: (int) 1,\n" +
- "(spew_test.customError) error: 2: (int) 2,\n" +
- "(spew_test.customError) error: 3: (int) 3\n" +
- "}\n"
- if s != expected {
- t.Errorf("Sorted keys mismatch:\n %v %v", s, expected)
- }
-
-}
diff --git a/vendor/github.com/davecgh/go-spew/spew/dumpcgo_test.go b/vendor/github.com/davecgh/go-spew/spew/dumpcgo_test.go
deleted file mode 100644
index 18a38358..00000000
--- a/vendor/github.com/davecgh/go-spew/spew/dumpcgo_test.go
+++ /dev/null
@@ -1,98 +0,0 @@
-// Copyright (c) 2013 Dave Collins
-//
-// Permission to use, copy, modify, and distribute this software for any
-// purpose with or without fee is hereby granted, provided that the above
-// copyright notice and this permission notice appear in all copies.
-//
-// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
-// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
-// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
-// ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
-// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
-// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
-// OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
-
-// NOTE: Due to the following build constraints, this file will only be compiled
-// when both cgo is supported and "-tags testcgo" is added to the go test
-// command line. This means the cgo tests are only added (and hence run) when
-// specifially requested. This configuration is used because spew itself
-// does not require cgo to run even though it does handle certain cgo types
-// specially. Rather than forcing all clients to require cgo and an external
-// C compiler just to run the tests, this scheme makes them optional.
-// +build cgo,testcgo
-
-package spew_test
-
-import (
- "fmt"
-
- "github.com/davecgh/go-spew/spew/testdata"
-)
-
-func addCgoDumpTests() {
- // C char pointer.
- v := testdata.GetCgoCharPointer()
- nv := testdata.GetCgoNullCharPointer()
- pv := &v
- vcAddr := fmt.Sprintf("%p", v)
- vAddr := fmt.Sprintf("%p", pv)
- pvAddr := fmt.Sprintf("%p", &pv)
- vt := "*testdata._Ctype_char"
- vs := "116"
- addDumpTest(v, "("+vt+")("+vcAddr+")("+vs+")\n")
- addDumpTest(pv, "(*"+vt+")("+vAddr+"->"+vcAddr+")("+vs+")\n")
- addDumpTest(&pv, "(**"+vt+")("+pvAddr+"->"+vAddr+"->"+vcAddr+")("+vs+")\n")
- addDumpTest(nv, "("+vt+")()\n")
-
- // C char array.
- v2, v2l, v2c := testdata.GetCgoCharArray()
- v2Len := fmt.Sprintf("%d", v2l)
- v2Cap := fmt.Sprintf("%d", v2c)
- v2t := "[6]testdata._Ctype_char"
- v2s := "(len=" + v2Len + " cap=" + v2Cap + ") " +
- "{\n 00000000 74 65 73 74 32 00 " +
- " |test2.|\n}"
- addDumpTest(v2, "("+v2t+") "+v2s+"\n")
-
- // C unsigned char array.
- v3, v3l, v3c := testdata.GetCgoUnsignedCharArray()
- v3Len := fmt.Sprintf("%d", v3l)
- v3Cap := fmt.Sprintf("%d", v3c)
- v3t := "[6]testdata._Ctype_unsignedchar"
- v3s := "(len=" + v3Len + " cap=" + v3Cap + ") " +
- "{\n 00000000 74 65 73 74 33 00 " +
- " |test3.|\n}"
- addDumpTest(v3, "("+v3t+") "+v3s+"\n")
-
- // C signed char array.
- v4, v4l, v4c := testdata.GetCgoSignedCharArray()
- v4Len := fmt.Sprintf("%d", v4l)
- v4Cap := fmt.Sprintf("%d", v4c)
- v4t := "[6]testdata._Ctype_schar"
- v4t2 := "testdata._Ctype_schar"
- v4s := "(len=" + v4Len + " cap=" + v4Cap + ") " +
- "{\n (" + v4t2 + ") 116,\n (" + v4t2 + ") 101,\n (" + v4t2 +
- ") 115,\n (" + v4t2 + ") 116,\n (" + v4t2 + ") 52,\n (" + v4t2 +
- ") 0\n}"
- addDumpTest(v4, "("+v4t+") "+v4s+"\n")
-
- // C uint8_t array.
- v5, v5l, v5c := testdata.GetCgoUint8tArray()
- v5Len := fmt.Sprintf("%d", v5l)
- v5Cap := fmt.Sprintf("%d", v5c)
- v5t := "[6]testdata._Ctype_uint8_t"
- v5s := "(len=" + v5Len + " cap=" + v5Cap + ") " +
- "{\n 00000000 74 65 73 74 35 00 " +
- " |test5.|\n}"
- addDumpTest(v5, "("+v5t+") "+v5s+"\n")
-
- // C typedefed unsigned char array.
- v6, v6l, v6c := testdata.GetCgoTypdefedUnsignedCharArray()
- v6Len := fmt.Sprintf("%d", v6l)
- v6Cap := fmt.Sprintf("%d", v6c)
- v6t := "[6]testdata._Ctype_custom_uchar_t"
- v6s := "(len=" + v6Len + " cap=" + v6Cap + ") " +
- "{\n 00000000 74 65 73 74 36 00 " +
- " |test6.|\n}"
- addDumpTest(v6, "("+v6t+") "+v6s+"\n")
-}
diff --git a/vendor/github.com/davecgh/go-spew/spew/dumpnocgo_test.go b/vendor/github.com/davecgh/go-spew/spew/dumpnocgo_test.go
deleted file mode 100644
index 52a0971f..00000000
--- a/vendor/github.com/davecgh/go-spew/spew/dumpnocgo_test.go
+++ /dev/null
@@ -1,26 +0,0 @@
-// Copyright (c) 2013 Dave Collins
-//
-// Permission to use, copy, modify, and distribute this software for any
-// purpose with or without fee is hereby granted, provided that the above
-// copyright notice and this permission notice appear in all copies.
-//
-// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
-// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
-// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
-// ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
-// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
-// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
-// OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
-
-// NOTE: Due to the following build constraints, this file will only be compiled
-// when either cgo is not supported or "-tags testcgo" is not added to the go
-// test command line. This file intentionally does not setup any cgo tests in
-// this scenario.
-// +build !cgo !testcgo
-
-package spew_test
-
-func addCgoDumpTests() {
- // Don't add any tests for cgo since this file is only compiled when
- // there should not be any cgo tests.
-}
diff --git a/vendor/github.com/davecgh/go-spew/spew/example_test.go b/vendor/github.com/davecgh/go-spew/spew/example_test.go
deleted file mode 100644
index de6c4e30..00000000
--- a/vendor/github.com/davecgh/go-spew/spew/example_test.go
+++ /dev/null
@@ -1,226 +0,0 @@
-/*
- * Copyright (c) 2013 Dave Collins
- *
- * Permission to use, copy, modify, and distribute this software for any
- * purpose with or without fee is hereby granted, provided that the above
- * copyright notice and this permission notice appear in all copies.
- *
- * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
- * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
- * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
- * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
- * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
- * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
- */
-
-package spew_test
-
-import (
- "fmt"
-
- "github.com/davecgh/go-spew/spew"
-)
-
-type Flag int
-
-const (
- flagOne Flag = iota
- flagTwo
-)
-
-var flagStrings = map[Flag]string{
- flagOne: "flagOne",
- flagTwo: "flagTwo",
-}
-
-func (f Flag) String() string {
- if s, ok := flagStrings[f]; ok {
- return s
- }
- return fmt.Sprintf("Unknown flag (%d)", int(f))
-}
-
-type Bar struct {
- data uintptr
-}
-
-type Foo struct {
- unexportedField Bar
- ExportedField map[interface{}]interface{}
-}
-
-// This example demonstrates how to use Dump to dump variables to stdout.
-func ExampleDump() {
- // The following package level declarations are assumed for this example:
- /*
- type Flag int
-
- const (
- flagOne Flag = iota
- flagTwo
- )
-
- var flagStrings = map[Flag]string{
- flagOne: "flagOne",
- flagTwo: "flagTwo",
- }
-
- func (f Flag) String() string {
- if s, ok := flagStrings[f]; ok {
- return s
- }
- return fmt.Sprintf("Unknown flag (%d)", int(f))
- }
-
- type Bar struct {
- data uintptr
- }
-
- type Foo struct {
- unexportedField Bar
- ExportedField map[interface{}]interface{}
- }
- */
-
- // Setup some sample data structures for the example.
- bar := Bar{uintptr(0)}
- s1 := Foo{bar, map[interface{}]interface{}{"one": true}}
- f := Flag(5)
- b := []byte{
- 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18,
- 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20,
- 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28,
- 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, 0x30,
- 0x31, 0x32,
- }
-
- // Dump!
- spew.Dump(s1, f, b)
-
- // Output:
- // (spew_test.Foo) {
- // unexportedField: (spew_test.Bar) {
- // data: (uintptr)
- // },
- // ExportedField: (map[interface {}]interface {}) (len=1) {
- // (string) (len=3) "one": (bool) true
- // }
- // }
- // (spew_test.Flag) Unknown flag (5)
- // ([]uint8) (len=34 cap=34) {
- // 00000000 11 12 13 14 15 16 17 18 19 1a 1b 1c 1d 1e 1f 20 |............... |
- // 00000010 21 22 23 24 25 26 27 28 29 2a 2b 2c 2d 2e 2f 30 |!"#$%&'()*+,-./0|
- // 00000020 31 32 |12|
- // }
- //
-}
-
-// This example demonstrates how to use Printf to display a variable with a
-// format string and inline formatting.
-func ExamplePrintf() {
- // Create a double pointer to a uint 8.
- ui8 := uint8(5)
- pui8 := &ui8
- ppui8 := &pui8
-
- // Create a circular data type.
- type circular struct {
- ui8 uint8
- c *circular
- }
- c := circular{ui8: 1}
- c.c = &c
-
- // Print!
- spew.Printf("ppui8: %v\n", ppui8)
- spew.Printf("circular: %v\n", c)
-
- // Output:
- // ppui8: <**>5
- // circular: {1 <*>{1 <*>}}
-}
-
-// This example demonstrates how to use a ConfigState.
-func ExampleConfigState() {
- // Modify the indent level of the ConfigState only. The global
- // configuration is not modified.
- scs := spew.ConfigState{Indent: "\t"}
-
- // Output using the ConfigState instance.
- v := map[string]int{"one": 1}
- scs.Printf("v: %v\n", v)
- scs.Dump(v)
-
- // Output:
- // v: map[one:1]
- // (map[string]int) (len=1) {
- // (string) (len=3) "one": (int) 1
- // }
-}
-
-// This example demonstrates how to use ConfigState.Dump to dump variables to
-// stdout
-func ExampleConfigState_Dump() {
- // See the top-level Dump example for details on the types used in this
- // example.
-
- // Create two ConfigState instances with different indentation.
- scs := spew.ConfigState{Indent: "\t"}
- scs2 := spew.ConfigState{Indent: " "}
-
- // Setup some sample data structures for the example.
- bar := Bar{uintptr(0)}
- s1 := Foo{bar, map[interface{}]interface{}{"one": true}}
-
- // Dump using the ConfigState instances.
- scs.Dump(s1)
- scs2.Dump(s1)
-
- // Output:
- // (spew_test.Foo) {
- // unexportedField: (spew_test.Bar) {
- // data: (uintptr)
- // },
- // ExportedField: (map[interface {}]interface {}) (len=1) {
- // (string) (len=3) "one": (bool) true
- // }
- // }
- // (spew_test.Foo) {
- // unexportedField: (spew_test.Bar) {
- // data: (uintptr)
- // },
- // ExportedField: (map[interface {}]interface {}) (len=1) {
- // (string) (len=3) "one": (bool) true
- // }
- // }
- //
-}
-
-// This example demonstrates how to use ConfigState.Printf to display a variable
-// with a format string and inline formatting.
-func ExampleConfigState_Printf() {
- // See the top-level Dump example for details on the types used in this
- // example.
-
- // Create two ConfigState instances and modify the method handling of the
- // first ConfigState only.
- scs := spew.NewDefaultConfig()
- scs2 := spew.NewDefaultConfig()
- scs.DisableMethods = true
-
- // Alternatively
- // scs := spew.ConfigState{Indent: " ", DisableMethods: true}
- // scs2 := spew.ConfigState{Indent: " "}
-
- // This is of type Flag which implements a Stringer and has raw value 1.
- f := flagTwo
-
- // Dump using the ConfigState instances.
- scs.Printf("f: %v\n", f)
- scs2.Printf("f: %v\n", f)
-
- // Output:
- // f: 1
- // f: flagTwo
-}
diff --git a/vendor/github.com/davecgh/go-spew/spew/format_test.go b/vendor/github.com/davecgh/go-spew/spew/format_test.go
deleted file mode 100644
index b664b3f1..00000000
--- a/vendor/github.com/davecgh/go-spew/spew/format_test.go
+++ /dev/null
@@ -1,1558 +0,0 @@
-/*
- * Copyright (c) 2013 Dave Collins
- *
- * Permission to use, copy, modify, and distribute this software for any
- * purpose with or without fee is hereby granted, provided that the above
- * copyright notice and this permission notice appear in all copies.
- *
- * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
- * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
- * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
- * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
- * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
- * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
- * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
- */
-
-/*
-Test Summary:
-NOTE: For each test, a nil pointer, a single pointer and double pointer to the
-base test element are also tested to ensure proper indirection across all types.
-
-- Max int8, int16, int32, int64, int
-- Max uint8, uint16, uint32, uint64, uint
-- Boolean true and false
-- Standard complex64 and complex128
-- Array containing standard ints
-- Array containing type with custom formatter on pointer receiver only
-- Array containing interfaces
-- Slice containing standard float32 values
-- Slice containing type with custom formatter on pointer receiver only
-- Slice containing interfaces
-- Nil slice
-- Standard string
-- Nil interface
-- Sub-interface
-- Map with string keys and int vals
-- Map with custom formatter type on pointer receiver only keys and vals
-- Map with interface keys and values
-- Map with nil interface value
-- Struct with primitives
-- Struct that contains another struct
-- Struct that contains custom type with Stringer pointer interface via both
- exported and unexported fields
-- Struct that contains embedded struct and field to same struct
-- Uintptr to 0 (null pointer)
-- Uintptr address of real variable
-- Unsafe.Pointer to 0 (null pointer)
-- Unsafe.Pointer to address of real variable
-- Nil channel
-- Standard int channel
-- Function with no params and no returns
-- Function with param and no returns
-- Function with multiple params and multiple returns
-- Struct that is circular through self referencing
-- Structs that are circular through cross referencing
-- Structs that are indirectly circular
-- Type that panics in its Stringer interface
-- Type that has a custom Error interface
-- %x passthrough with uint
-- %#x passthrough with uint
-- %f passthrough with precision
-- %f passthrough with width and precision
-- %d passthrough with width
-- %q passthrough with string
-*/
-
-package spew_test
-
-import (
- "bytes"
- "fmt"
- "testing"
- "unsafe"
-
- "github.com/davecgh/go-spew/spew"
-)
-
-// formatterTest is used to describe a test to be perfomed against NewFormatter.
-type formatterTest struct {
- format string
- in interface{}
- wants []string
-}
-
-// formatterTests houses all of the tests to be performed against NewFormatter.
-var formatterTests = make([]formatterTest, 0)
-
-// addFormatterTest is a helper method to append the passed input and desired
-// result to formatterTests.
-func addFormatterTest(format string, in interface{}, wants ...string) {
- test := formatterTest{format, in, wants}
- formatterTests = append(formatterTests, test)
-}
-
-func addIntFormatterTests() {
- // Max int8.
- v := int8(127)
- nv := (*int8)(nil)
- pv := &v
- vAddr := fmt.Sprintf("%p", pv)
- pvAddr := fmt.Sprintf("%p", &pv)
- vt := "int8"
- vs := "127"
- addFormatterTest("%v", v, vs)
- addFormatterTest("%v", pv, "<*>"+vs)
- addFormatterTest("%v", &pv, "<**>"+vs)
- addFormatterTest("%v", nv, "")
- addFormatterTest("%+v", v, vs)
- addFormatterTest("%+v", pv, "<*>("+vAddr+")"+vs)
- addFormatterTest("%+v", &pv, "<**>("+pvAddr+"->"+vAddr+")"+vs)
- addFormatterTest("%+v", nv, "")
- addFormatterTest("%#v", v, "("+vt+")"+vs)
- addFormatterTest("%#v", pv, "(*"+vt+")"+vs)
- addFormatterTest("%#v", &pv, "(**"+vt+")"+vs)
- addFormatterTest("%#v", nv, "(*"+vt+")"+"")
- addFormatterTest("%#+v", v, "("+vt+")"+vs)
- addFormatterTest("%#+v", pv, "(*"+vt+")("+vAddr+")"+vs)
- addFormatterTest("%#+v", &pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs)
- addFormatterTest("%#+v", nv, "(*"+vt+")"+"")
-
- // Max int16.
- v2 := int16(32767)
- nv2 := (*int16)(nil)
- pv2 := &v2
- v2Addr := fmt.Sprintf("%p", pv2)
- pv2Addr := fmt.Sprintf("%p", &pv2)
- v2t := "int16"
- v2s := "32767"
- addFormatterTest("%v", v2, v2s)
- addFormatterTest("%v", pv2, "<*>"+v2s)
- addFormatterTest("%v", &pv2, "<**>"+v2s)
- addFormatterTest("%v", nv2, "")
- addFormatterTest("%+v", v2, v2s)
- addFormatterTest("%+v", pv2, "<*>("+v2Addr+")"+v2s)
- addFormatterTest("%+v", &pv2, "<**>("+pv2Addr+"->"+v2Addr+")"+v2s)
- addFormatterTest("%+v", nv2, "")
- addFormatterTest("%#v", v2, "("+v2t+")"+v2s)
- addFormatterTest("%#v", pv2, "(*"+v2t+")"+v2s)
- addFormatterTest("%#v", &pv2, "(**"+v2t+")"+v2s)
- addFormatterTest("%#v", nv2, "(*"+v2t+")"+"")
- addFormatterTest("%#+v", v2, "("+v2t+")"+v2s)
- addFormatterTest("%#+v", pv2, "(*"+v2t+")("+v2Addr+")"+v2s)
- addFormatterTest("%#+v", &pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")"+v2s)
- addFormatterTest("%#+v", nv2, "(*"+v2t+")"+"")
-
- // Max int32.
- v3 := int32(2147483647)
- nv3 := (*int32)(nil)
- pv3 := &v3
- v3Addr := fmt.Sprintf("%p", pv3)
- pv3Addr := fmt.Sprintf("%p", &pv3)
- v3t := "int32"
- v3s := "2147483647"
- addFormatterTest("%v", v3, v3s)
- addFormatterTest("%v", pv3, "<*>"+v3s)
- addFormatterTest("%v", &pv3, "<**>"+v3s)
- addFormatterTest("%v", nv3, "")
- addFormatterTest("%+v", v3, v3s)
- addFormatterTest("%+v", pv3, "<*>("+v3Addr+")"+v3s)
- addFormatterTest("%+v", &pv3, "<**>("+pv3Addr+"->"+v3Addr+")"+v3s)
- addFormatterTest("%+v", nv3, "")
- addFormatterTest("%#v", v3, "("+v3t+")"+v3s)
- addFormatterTest("%#v", pv3, "(*"+v3t+")"+v3s)
- addFormatterTest("%#v", &pv3, "(**"+v3t+")"+v3s)
- addFormatterTest("%#v", nv3, "(*"+v3t+")"+"")
- addFormatterTest("%#+v", v3, "("+v3t+")"+v3s)
- addFormatterTest("%#+v", pv3, "(*"+v3t+")("+v3Addr+")"+v3s)
- addFormatterTest("%#+v", &pv3, "(**"+v3t+")("+pv3Addr+"->"+v3Addr+")"+v3s)
- addFormatterTest("%#v", nv3, "(*"+v3t+")"+"")
-
- // Max int64.
- v4 := int64(9223372036854775807)
- nv4 := (*int64)(nil)
- pv4 := &v4
- v4Addr := fmt.Sprintf("%p", pv4)
- pv4Addr := fmt.Sprintf("%p", &pv4)
- v4t := "int64"
- v4s := "9223372036854775807"
- addFormatterTest("%v", v4, v4s)
- addFormatterTest("%v", pv4, "<*>"+v4s)
- addFormatterTest("%v", &pv4, "<**>"+v4s)
- addFormatterTest("%v", nv4, "")
- addFormatterTest("%+v", v4, v4s)
- addFormatterTest("%+v", pv4, "<*>("+v4Addr+")"+v4s)
- addFormatterTest("%+v", &pv4, "<**>("+pv4Addr+"->"+v4Addr+")"+v4s)
- addFormatterTest("%+v", nv4, "")
- addFormatterTest("%#v", v4, "("+v4t+")"+v4s)
- addFormatterTest("%#v", pv4, "(*"+v4t+")"+v4s)
- addFormatterTest("%#v", &pv4, "(**"+v4t+")"+v4s)
- addFormatterTest("%#v", nv4, "(*"+v4t+")"+"")
- addFormatterTest("%#+v", v4, "("+v4t+")"+v4s)
- addFormatterTest("%#+v", pv4, "(*"+v4t+")("+v4Addr+")"+v4s)
- addFormatterTest("%#+v", &pv4, "(**"+v4t+")("+pv4Addr+"->"+v4Addr+")"+v4s)
- addFormatterTest("%#+v", nv4, "(*"+v4t+")"+"")
-
- // Max int.
- v5 := int(2147483647)
- nv5 := (*int)(nil)
- pv5 := &v5
- v5Addr := fmt.Sprintf("%p", pv5)
- pv5Addr := fmt.Sprintf("%p", &pv5)
- v5t := "int"
- v5s := "2147483647"
- addFormatterTest("%v", v5, v5s)
- addFormatterTest("%v", pv5, "<*>"+v5s)
- addFormatterTest("%v", &pv5, "<**>"+v5s)
- addFormatterTest("%v", nv5, "")
- addFormatterTest("%+v", v5, v5s)
- addFormatterTest("%+v", pv5, "<*>("+v5Addr+")"+v5s)
- addFormatterTest("%+v", &pv5, "<**>("+pv5Addr+"->"+v5Addr+")"+v5s)
- addFormatterTest("%+v", nv5, "")
- addFormatterTest("%#v", v5, "("+v5t+")"+v5s)
- addFormatterTest("%#v", pv5, "(*"+v5t+")"+v5s)
- addFormatterTest("%#v", &pv5, "(**"+v5t+")"+v5s)
- addFormatterTest("%#v", nv5, "(*"+v5t+")"+"")
- addFormatterTest("%#+v", v5, "("+v5t+")"+v5s)
- addFormatterTest("%#+v", pv5, "(*"+v5t+")("+v5Addr+")"+v5s)
- addFormatterTest("%#+v", &pv5, "(**"+v5t+")("+pv5Addr+"->"+v5Addr+")"+v5s)
- addFormatterTest("%#+v", nv5, "(*"+v5t+")"+"")
-}
-
-func addUintFormatterTests() {
- // Max uint8.
- v := uint8(255)
- nv := (*uint8)(nil)
- pv := &v
- vAddr := fmt.Sprintf("%p", pv)
- pvAddr := fmt.Sprintf("%p", &pv)
- vt := "uint8"
- vs := "255"
- addFormatterTest("%v", v, vs)
- addFormatterTest("%v", pv, "<*>"+vs)
- addFormatterTest("%v", &pv, "<**>"+vs)
- addFormatterTest("%v", nv, "")
- addFormatterTest("%+v", v, vs)
- addFormatterTest("%+v", pv, "<*>("+vAddr+")"+vs)
- addFormatterTest("%+v", &pv, "<**>("+pvAddr+"->"+vAddr+")"+vs)
- addFormatterTest("%+v", nv, "")
- addFormatterTest("%#v", v, "("+vt+")"+vs)
- addFormatterTest("%#v", pv, "(*"+vt+")"+vs)
- addFormatterTest("%#v", &pv, "(**"+vt+")"+vs)
- addFormatterTest("%#v", nv, "(*"+vt+")"+"")
- addFormatterTest("%#+v", v, "("+vt+")"+vs)
- addFormatterTest("%#+v", pv, "(*"+vt+")("+vAddr+")"+vs)
- addFormatterTest("%#+v", &pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs)
- addFormatterTest("%#+v", nv, "(*"+vt+")"+"")
-
- // Max uint16.
- v2 := uint16(65535)
- nv2 := (*uint16)(nil)
- pv2 := &v2
- v2Addr := fmt.Sprintf("%p", pv2)
- pv2Addr := fmt.Sprintf("%p", &pv2)
- v2t := "uint16"
- v2s := "65535"
- addFormatterTest("%v", v2, v2s)
- addFormatterTest("%v", pv2, "<*>"+v2s)
- addFormatterTest("%v", &pv2, "<**>"+v2s)
- addFormatterTest("%v", nv2, "")
- addFormatterTest("%+v", v2, v2s)
- addFormatterTest("%+v", pv2, "<*>("+v2Addr+")"+v2s)
- addFormatterTest("%+v", &pv2, "<**>("+pv2Addr+"->"+v2Addr+")"+v2s)
- addFormatterTest("%+v", nv2, "")
- addFormatterTest("%#v", v2, "("+v2t+")"+v2s)
- addFormatterTest("%#v", pv2, "(*"+v2t+")"+v2s)
- addFormatterTest("%#v", &pv2, "(**"+v2t+")"+v2s)
- addFormatterTest("%#v", nv2, "(*"+v2t+")"+"")
- addFormatterTest("%#+v", v2, "("+v2t+")"+v2s)
- addFormatterTest("%#+v", pv2, "(*"+v2t+")("+v2Addr+")"+v2s)
- addFormatterTest("%#+v", &pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")"+v2s)
- addFormatterTest("%#+v", nv2, "(*"+v2t+")"+"")
-
- // Max uint32.
- v3 := uint32(4294967295)
- nv3 := (*uint32)(nil)
- pv3 := &v3
- v3Addr := fmt.Sprintf("%p", pv3)
- pv3Addr := fmt.Sprintf("%p", &pv3)
- v3t := "uint32"
- v3s := "4294967295"
- addFormatterTest("%v", v3, v3s)
- addFormatterTest("%v", pv3, "<*>"+v3s)
- addFormatterTest("%v", &pv3, "<**>"+v3s)
- addFormatterTest("%v", nv3, "")
- addFormatterTest("%+v", v3, v3s)
- addFormatterTest("%+v", pv3, "<*>("+v3Addr+")"+v3s)
- addFormatterTest("%+v", &pv3, "<**>("+pv3Addr+"->"+v3Addr+")"+v3s)
- addFormatterTest("%+v", nv3, "")
- addFormatterTest("%#v", v3, "("+v3t+")"+v3s)
- addFormatterTest("%#v", pv3, "(*"+v3t+")"+v3s)
- addFormatterTest("%#v", &pv3, "(**"+v3t+")"+v3s)
- addFormatterTest("%#v", nv3, "(*"+v3t+")"+"")
- addFormatterTest("%#+v", v3, "("+v3t+")"+v3s)
- addFormatterTest("%#+v", pv3, "(*"+v3t+")("+v3Addr+")"+v3s)
- addFormatterTest("%#+v", &pv3, "(**"+v3t+")("+pv3Addr+"->"+v3Addr+")"+v3s)
- addFormatterTest("%#v", nv3, "(*"+v3t+")"+"")
-
- // Max uint64.
- v4 := uint64(18446744073709551615)
- nv4 := (*uint64)(nil)
- pv4 := &v4
- v4Addr := fmt.Sprintf("%p", pv4)
- pv4Addr := fmt.Sprintf("%p", &pv4)
- v4t := "uint64"
- v4s := "18446744073709551615"
- addFormatterTest("%v", v4, v4s)
- addFormatterTest("%v", pv4, "<*>"+v4s)
- addFormatterTest("%v", &pv4, "<**>"+v4s)
- addFormatterTest("%v", nv4, "")
- addFormatterTest("%+v", v4, v4s)
- addFormatterTest("%+v", pv4, "<*>("+v4Addr+")"+v4s)
- addFormatterTest("%+v", &pv4, "<**>("+pv4Addr+"->"+v4Addr+")"+v4s)
- addFormatterTest("%+v", nv4, "")
- addFormatterTest("%#v", v4, "("+v4t+")"+v4s)
- addFormatterTest("%#v", pv4, "(*"+v4t+")"+v4s)
- addFormatterTest("%#v", &pv4, "(**"+v4t+")"+v4s)
- addFormatterTest("%#v", nv4, "(*"+v4t+")"+"")
- addFormatterTest("%#+v", v4, "("+v4t+")"+v4s)
- addFormatterTest("%#+v", pv4, "(*"+v4t+")("+v4Addr+")"+v4s)
- addFormatterTest("%#+v", &pv4, "(**"+v4t+")("+pv4Addr+"->"+v4Addr+")"+v4s)
- addFormatterTest("%#+v", nv4, "(*"+v4t+")"+"")
-
- // Max uint.
- v5 := uint(4294967295)
- nv5 := (*uint)(nil)
- pv5 := &v5
- v5Addr := fmt.Sprintf("%p", pv5)
- pv5Addr := fmt.Sprintf("%p", &pv5)
- v5t := "uint"
- v5s := "4294967295"
- addFormatterTest("%v", v5, v5s)
- addFormatterTest("%v", pv5, "<*>"+v5s)
- addFormatterTest("%v", &pv5, "<**>"+v5s)
- addFormatterTest("%v", nv5, "")
- addFormatterTest("%+v", v5, v5s)
- addFormatterTest("%+v", pv5, "<*>("+v5Addr+")"+v5s)
- addFormatterTest("%+v", &pv5, "<**>("+pv5Addr+"->"+v5Addr+")"+v5s)
- addFormatterTest("%+v", nv5, "")
- addFormatterTest("%#v", v5, "("+v5t+")"+v5s)
- addFormatterTest("%#v", pv5, "(*"+v5t+")"+v5s)
- addFormatterTest("%#v", &pv5, "(**"+v5t+")"+v5s)
- addFormatterTest("%#v", nv5, "(*"+v5t+")"+"")
- addFormatterTest("%#+v", v5, "("+v5t+")"+v5s)
- addFormatterTest("%#+v", pv5, "(*"+v5t+")("+v5Addr+")"+v5s)
- addFormatterTest("%#+v", &pv5, "(**"+v5t+")("+pv5Addr+"->"+v5Addr+")"+v5s)
- addFormatterTest("%#v", nv5, "(*"+v5t+")"+"")
-}
-
-func addBoolFormatterTests() {
- // Boolean true.
- v := bool(true)
- nv := (*bool)(nil)
- pv := &v
- vAddr := fmt.Sprintf("%p", pv)
- pvAddr := fmt.Sprintf("%p", &pv)
- vt := "bool"
- vs := "true"
- addFormatterTest("%v", v, vs)
- addFormatterTest("%v", pv, "<*>"+vs)
- addFormatterTest("%v", &pv, "<**>"+vs)
- addFormatterTest("%v", nv, "")
- addFormatterTest("%+v", v, vs)
- addFormatterTest("%+v", pv, "<*>("+vAddr+")"+vs)
- addFormatterTest("%+v", &pv, "<**>("+pvAddr+"->"+vAddr+")"+vs)
- addFormatterTest("%+v", nv, "")
- addFormatterTest("%#v", v, "("+vt+")"+vs)
- addFormatterTest("%#v", pv, "(*"+vt+")"+vs)
- addFormatterTest("%#v", &pv, "(**"+vt+")"+vs)
- addFormatterTest("%#v", nv, "(*"+vt+")"+"")
- addFormatterTest("%#+v", v, "("+vt+")"+vs)
- addFormatterTest("%#+v", pv, "(*"+vt+")("+vAddr+")"+vs)
- addFormatterTest("%#+v", &pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs)
- addFormatterTest("%#+v", nv, "(*"+vt+")"+"")
-
- // Boolean false.
- v2 := bool(false)
- pv2 := &v2
- v2Addr := fmt.Sprintf("%p", pv2)
- pv2Addr := fmt.Sprintf("%p", &pv2)
- v2t := "bool"
- v2s := "false"
- addFormatterTest("%v", v2, v2s)
- addFormatterTest("%v", pv2, "<*>"+v2s)
- addFormatterTest("%v", &pv2, "<**>"+v2s)
- addFormatterTest("%+v", v2, v2s)
- addFormatterTest("%+v", pv2, "<*>("+v2Addr+")"+v2s)
- addFormatterTest("%+v", &pv2, "<**>("+pv2Addr+"->"+v2Addr+")"+v2s)
- addFormatterTest("%#v", v2, "("+v2t+")"+v2s)
- addFormatterTest("%#v", pv2, "(*"+v2t+")"+v2s)
- addFormatterTest("%#v", &pv2, "(**"+v2t+")"+v2s)
- addFormatterTest("%#+v", v2, "("+v2t+")"+v2s)
- addFormatterTest("%#+v", pv2, "(*"+v2t+")("+v2Addr+")"+v2s)
- addFormatterTest("%#+v", &pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")"+v2s)
-}
-
-func addFloatFormatterTests() {
- // Standard float32.
- v := float32(3.1415)
- nv := (*float32)(nil)
- pv := &v
- vAddr := fmt.Sprintf("%p", pv)
- pvAddr := fmt.Sprintf("%p", &pv)
- vt := "float32"
- vs := "3.1415"
- addFormatterTest("%v", v, vs)
- addFormatterTest("%v", pv, "<*>"+vs)
- addFormatterTest("%v", &pv, "<**>"+vs)
- addFormatterTest("%v", nv, "")
- addFormatterTest("%+v", v, vs)
- addFormatterTest("%+v", pv, "<*>("+vAddr+")"+vs)
- addFormatterTest("%+v", &pv, "<**>("+pvAddr+"->"+vAddr+")"+vs)
- addFormatterTest("%+v", nv, "")
- addFormatterTest("%#v", v, "("+vt+")"+vs)
- addFormatterTest("%#v", pv, "(*"+vt+")"+vs)
- addFormatterTest("%#v", &pv, "(**"+vt+")"+vs)
- addFormatterTest("%#v", nv, "(*"+vt+")"+"")
- addFormatterTest("%#+v", v, "("+vt+")"+vs)
- addFormatterTest("%#+v", pv, "(*"+vt+")("+vAddr+")"+vs)
- addFormatterTest("%#+v", &pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs)
- addFormatterTest("%#+v", nv, "(*"+vt+")"+"")
-
- // Standard float64.
- v2 := float64(3.1415926)
- nv2 := (*float64)(nil)
- pv2 := &v2
- v2Addr := fmt.Sprintf("%p", pv2)
- pv2Addr := fmt.Sprintf("%p", &pv2)
- v2t := "float64"
- v2s := "3.1415926"
- addFormatterTest("%v", v2, v2s)
- addFormatterTest("%v", pv2, "<*>"+v2s)
- addFormatterTest("%v", &pv2, "<**>"+v2s)
- addFormatterTest("%+v", nv2, "")
- addFormatterTest("%+v", v2, v2s)
- addFormatterTest("%+v", pv2, "<*>("+v2Addr+")"+v2s)
- addFormatterTest("%+v", &pv2, "<**>("+pv2Addr+"->"+v2Addr+")"+v2s)
- addFormatterTest("%+v", nv2, "")
- addFormatterTest("%#v", v2, "("+v2t+")"+v2s)
- addFormatterTest("%#v", pv2, "(*"+v2t+")"+v2s)
- addFormatterTest("%#v", &pv2, "(**"+v2t+")"+v2s)
- addFormatterTest("%#v", nv2, "(*"+v2t+")"+"")
- addFormatterTest("%#+v", v2, "("+v2t+")"+v2s)
- addFormatterTest("%#+v", pv2, "(*"+v2t+")("+v2Addr+")"+v2s)
- addFormatterTest("%#+v", &pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")"+v2s)
- addFormatterTest("%#+v", nv2, "(*"+v2t+")"+"")
-}
-
-func addComplexFormatterTests() {
- // Standard complex64.
- v := complex(float32(6), -2)
- nv := (*complex64)(nil)
- pv := &v
- vAddr := fmt.Sprintf("%p", pv)
- pvAddr := fmt.Sprintf("%p", &pv)
- vt := "complex64"
- vs := "(6-2i)"
- addFormatterTest("%v", v, vs)
- addFormatterTest("%v", pv, "<*>"+vs)
- addFormatterTest("%v", &pv, "<**>"+vs)
- addFormatterTest("%+v", nv, "")
- addFormatterTest("%+v", v, vs)
- addFormatterTest("%+v", pv, "<*>("+vAddr+")"+vs)
- addFormatterTest("%+v", &pv, "<**>("+pvAddr+"->"+vAddr+")"+vs)
- addFormatterTest("%+v", nv, "")
- addFormatterTest("%#v", v, "("+vt+")"+vs)
- addFormatterTest("%#v", pv, "(*"+vt+")"+vs)
- addFormatterTest("%#v", &pv, "(**"+vt+")"+vs)
- addFormatterTest("%#v", nv, "(*"+vt+")"+"")
- addFormatterTest("%#+v", v, "("+vt+")"+vs)
- addFormatterTest("%#+v", pv, "(*"+vt+")("+vAddr+")"+vs)
- addFormatterTest("%#+v", &pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs)
- addFormatterTest("%#+v", nv, "(*"+vt+")"+"")
-
- // Standard complex128.
- v2 := complex(float64(-6), 2)
- nv2 := (*complex128)(nil)
- pv2 := &v2
- v2Addr := fmt.Sprintf("%p", pv2)
- pv2Addr := fmt.Sprintf("%p", &pv2)
- v2t := "complex128"
- v2s := "(-6+2i)"
- addFormatterTest("%v", v2, v2s)
- addFormatterTest("%v", pv2, "<*>"+v2s)
- addFormatterTest("%v", &pv2, "<**>"+v2s)
- addFormatterTest("%+v", nv2, "")
- addFormatterTest("%+v", v2, v2s)
- addFormatterTest("%+v", pv2, "<*>("+v2Addr+")"+v2s)
- addFormatterTest("%+v", &pv2, "<**>("+pv2Addr+"->"+v2Addr+")"+v2s)
- addFormatterTest("%+v", nv2, "")
- addFormatterTest("%#v", v2, "("+v2t+")"+v2s)
- addFormatterTest("%#v", pv2, "(*"+v2t+")"+v2s)
- addFormatterTest("%#v", &pv2, "(**"+v2t+")"+v2s)
- addFormatterTest("%#v", nv2, "(*"+v2t+")"+"")
- addFormatterTest("%#+v", v2, "("+v2t+")"+v2s)
- addFormatterTest("%#+v", pv2, "(*"+v2t+")("+v2Addr+")"+v2s)
- addFormatterTest("%#+v", &pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")"+v2s)
- addFormatterTest("%#+v", nv2, "(*"+v2t+")"+"")
-}
-
-func addArrayFormatterTests() {
- // Array containing standard ints.
- v := [3]int{1, 2, 3}
- nv := (*[3]int)(nil)
- pv := &v
- vAddr := fmt.Sprintf("%p", pv)
- pvAddr := fmt.Sprintf("%p", &pv)
- vt := "[3]int"
- vs := "[1 2 3]"
- addFormatterTest("%v", v, vs)
- addFormatterTest("%v", pv, "<*>"+vs)
- addFormatterTest("%v", &pv, "<**>"+vs)
- addFormatterTest("%+v", nv, "")
- addFormatterTest("%+v", v, vs)
- addFormatterTest("%+v", pv, "<*>("+vAddr+")"+vs)
- addFormatterTest("%+v", &pv, "<**>("+pvAddr+"->"+vAddr+")"+vs)
- addFormatterTest("%+v", nv, "")
- addFormatterTest("%#v", v, "("+vt+")"+vs)
- addFormatterTest("%#v", pv, "(*"+vt+")"+vs)
- addFormatterTest("%#v", &pv, "(**"+vt+")"+vs)
- addFormatterTest("%#v", nv, "(*"+vt+")"+"")
- addFormatterTest("%#+v", v, "("+vt+")"+vs)
- addFormatterTest("%#+v", pv, "(*"+vt+")("+vAddr+")"+vs)
- addFormatterTest("%#+v", &pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs)
- addFormatterTest("%#+v", nv, "(*"+vt+")"+"")
-
- // Array containing type with custom formatter on pointer receiver only.
- v2 := [3]pstringer{"1", "2", "3"}
- nv2 := (*[3]pstringer)(nil)
- pv2 := &v2
- v2Addr := fmt.Sprintf("%p", pv2)
- pv2Addr := fmt.Sprintf("%p", &pv2)
- v2t := "[3]spew_test.pstringer"
- v2sp := "[stringer 1 stringer 2 stringer 3]"
- v2s := v2sp
- if spew.UnsafeDisabled {
- v2s = "[1 2 3]"
- }
- addFormatterTest("%v", v2, v2s)
- addFormatterTest("%v", pv2, "<*>"+v2sp)
- addFormatterTest("%v", &pv2, "<**>"+v2sp)
- addFormatterTest("%+v", nv2, "")
- addFormatterTest("%+v", v2, v2s)
- addFormatterTest("%+v", pv2, "<*>("+v2Addr+")"+v2sp)
- addFormatterTest("%+v", &pv2, "<**>("+pv2Addr+"->"+v2Addr+")"+v2sp)
- addFormatterTest("%+v", nv2, "")
- addFormatterTest("%#v", v2, "("+v2t+")"+v2s)
- addFormatterTest("%#v", pv2, "(*"+v2t+")"+v2sp)
- addFormatterTest("%#v", &pv2, "(**"+v2t+")"+v2sp)
- addFormatterTest("%#v", nv2, "(*"+v2t+")"+"")
- addFormatterTest("%#+v", v2, "("+v2t+")"+v2s)
- addFormatterTest("%#+v", pv2, "(*"+v2t+")("+v2Addr+")"+v2sp)
- addFormatterTest("%#+v", &pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")"+v2sp)
- addFormatterTest("%#+v", nv2, "(*"+v2t+")"+"")
-
- // Array containing interfaces.
- v3 := [3]interface{}{"one", int(2), uint(3)}
- nv3 := (*[3]interface{})(nil)
- pv3 := &v3
- v3Addr := fmt.Sprintf("%p", pv3)
- pv3Addr := fmt.Sprintf("%p", &pv3)
- v3t := "[3]interface {}"
- v3t2 := "string"
- v3t3 := "int"
- v3t4 := "uint"
- v3s := "[one 2 3]"
- v3s2 := "[(" + v3t2 + ")one (" + v3t3 + ")2 (" + v3t4 + ")3]"
- addFormatterTest("%v", v3, v3s)
- addFormatterTest("%v", pv3, "<*>"+v3s)
- addFormatterTest("%v", &pv3, "<**>"+v3s)
- addFormatterTest("%+v", nv3, "")
- addFormatterTest("%+v", v3, v3s)
- addFormatterTest("%+v", pv3, "<*>("+v3Addr+")"+v3s)
- addFormatterTest("%+v", &pv3, "<**>("+pv3Addr+"->"+v3Addr+")"+v3s)
- addFormatterTest("%+v", nv3, "")
- addFormatterTest("%#v", v3, "("+v3t+")"+v3s2)
- addFormatterTest("%#v", pv3, "(*"+v3t+")"+v3s2)
- addFormatterTest("%#v", &pv3, "(**"+v3t+")"+v3s2)
- addFormatterTest("%#v", nv3, "(*"+v3t+")"+"")
- addFormatterTest("%#+v", v3, "("+v3t+")"+v3s2)
- addFormatterTest("%#+v", pv3, "(*"+v3t+")("+v3Addr+")"+v3s2)
- addFormatterTest("%#+v", &pv3, "(**"+v3t+")("+pv3Addr+"->"+v3Addr+")"+v3s2)
- addFormatterTest("%#+v", nv3, "(*"+v3t+")"+"")
-}
-
-func addSliceFormatterTests() {
- // Slice containing standard float32 values.
- v := []float32{3.14, 6.28, 12.56}
- nv := (*[]float32)(nil)
- pv := &v
- vAddr := fmt.Sprintf("%p", pv)
- pvAddr := fmt.Sprintf("%p", &pv)
- vt := "[]float32"
- vs := "[3.14 6.28 12.56]"
- addFormatterTest("%v", v, vs)
- addFormatterTest("%v", pv, "<*>"+vs)
- addFormatterTest("%v", &pv, "<**>"+vs)
- addFormatterTest("%+v", nv, "")
- addFormatterTest("%+v", v, vs)
- addFormatterTest("%+v", pv, "<*>("+vAddr+")"+vs)
- addFormatterTest("%+v", &pv, "<**>("+pvAddr+"->"+vAddr+")"+vs)
- addFormatterTest("%+v", nv, "")
- addFormatterTest("%#v", v, "("+vt+")"+vs)
- addFormatterTest("%#v", pv, "(*"+vt+")"+vs)
- addFormatterTest("%#v", &pv, "(**"+vt+")"+vs)
- addFormatterTest("%#v", nv, "(*"+vt+")"+"")
- addFormatterTest("%#+v", v, "("+vt+")"+vs)
- addFormatterTest("%#+v", pv, "(*"+vt+")("+vAddr+")"+vs)
- addFormatterTest("%#+v", &pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs)
- addFormatterTest("%#+v", nv, "(*"+vt+")"+"")
-
- // Slice containing type with custom formatter on pointer receiver only.
- v2 := []pstringer{"1", "2", "3"}
- nv2 := (*[]pstringer)(nil)
- pv2 := &v2
- v2Addr := fmt.Sprintf("%p", pv2)
- pv2Addr := fmt.Sprintf("%p", &pv2)
- v2t := "[]spew_test.pstringer"
- v2s := "[stringer 1 stringer 2 stringer 3]"
- addFormatterTest("%v", v2, v2s)
- addFormatterTest("%v", pv2, "<*>"+v2s)
- addFormatterTest("%v", &pv2, "<**>"+v2s)
- addFormatterTest("%+v", nv2, "")
- addFormatterTest("%+v", v2, v2s)
- addFormatterTest("%+v", pv2, "<*>("+v2Addr+")"+v2s)
- addFormatterTest("%+v", &pv2, "<**>("+pv2Addr+"->"+v2Addr+")"+v2s)
- addFormatterTest("%+v", nv2, "")
- addFormatterTest("%#v", v2, "("+v2t+")"+v2s)
- addFormatterTest("%#v", pv2, "(*"+v2t+")"+v2s)
- addFormatterTest("%#v", &pv2, "(**"+v2t+")"+v2s)
- addFormatterTest("%#v", nv2, "(*"+v2t+")"+"")
- addFormatterTest("%#+v", v2, "("+v2t+")"+v2s)
- addFormatterTest("%#+v", pv2, "(*"+v2t+")("+v2Addr+")"+v2s)
- addFormatterTest("%#+v", &pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")"+v2s)
- addFormatterTest("%#+v", nv2, "(*"+v2t+")"+"")
-
- // Slice containing interfaces.
- v3 := []interface{}{"one", int(2), uint(3), nil}
- nv3 := (*[]interface{})(nil)
- pv3 := &v3
- v3Addr := fmt.Sprintf("%p", pv3)
- pv3Addr := fmt.Sprintf("%p", &pv3)
- v3t := "[]interface {}"
- v3t2 := "string"
- v3t3 := "int"
- v3t4 := "uint"
- v3t5 := "interface {}"
- v3s := "[one 2 3 ]"
- v3s2 := "[(" + v3t2 + ")one (" + v3t3 + ")2 (" + v3t4 + ")3 (" + v3t5 +
- ")]"
- addFormatterTest("%v", v3, v3s)
- addFormatterTest("%v", pv3, "<*>"+v3s)
- addFormatterTest("%v", &pv3, "<**>"+v3s)
- addFormatterTest("%+v", nv3, "")
- addFormatterTest("%+v", v3, v3s)
- addFormatterTest("%+v", pv3, "<*>("+v3Addr+")"+v3s)
- addFormatterTest("%+v", &pv3, "<**>("+pv3Addr+"->"+v3Addr+")"+v3s)
- addFormatterTest("%+v", nv3, "")
- addFormatterTest("%#v", v3, "("+v3t+")"+v3s2)
- addFormatterTest("%#v", pv3, "(*"+v3t+")"+v3s2)
- addFormatterTest("%#v", &pv3, "(**"+v3t+")"+v3s2)
- addFormatterTest("%#v", nv3, "(*"+v3t+")"+"")
- addFormatterTest("%#+v", v3, "("+v3t+")"+v3s2)
- addFormatterTest("%#+v", pv3, "(*"+v3t+")("+v3Addr+")"+v3s2)
- addFormatterTest("%#+v", &pv3, "(**"+v3t+")("+pv3Addr+"->"+v3Addr+")"+v3s2)
- addFormatterTest("%#+v", nv3, "(*"+v3t+")"+"")
-
- // Nil slice.
- var v4 []int
- nv4 := (*[]int)(nil)
- pv4 := &v4
- v4Addr := fmt.Sprintf("%p", pv4)
- pv4Addr := fmt.Sprintf("%p", &pv4)
- v4t := "[]int"
- v4s := ""
- addFormatterTest("%v", v4, v4s)
- addFormatterTest("%v", pv4, "<*>"+v4s)
- addFormatterTest("%v", &pv4, "<**>"+v4s)
- addFormatterTest("%+v", nv4, "")
- addFormatterTest("%+v", v4, v4s)
- addFormatterTest("%+v", pv4, "<*>("+v4Addr+")"+v4s)
- addFormatterTest("%+v", &pv4, "<**>("+pv4Addr+"->"+v4Addr+")"+v4s)
- addFormatterTest("%+v", nv4, "")
- addFormatterTest("%#v", v4, "("+v4t+")"+v4s)
- addFormatterTest("%#v", pv4, "(*"+v4t+")"+v4s)
- addFormatterTest("%#v", &pv4, "(**"+v4t+")"+v4s)
- addFormatterTest("%#v", nv4, "(*"+v4t+")"+"")
- addFormatterTest("%#+v", v4, "("+v4t+")"+v4s)
- addFormatterTest("%#+v", pv4, "(*"+v4t+")("+v4Addr+")"+v4s)
- addFormatterTest("%#+v", &pv4, "(**"+v4t+")("+pv4Addr+"->"+v4Addr+")"+v4s)
- addFormatterTest("%#+v", nv4, "(*"+v4t+")"+"")
-}
-
-func addStringFormatterTests() {
- // Standard string.
- v := "test"
- nv := (*string)(nil)
- pv := &v
- vAddr := fmt.Sprintf("%p", pv)
- pvAddr := fmt.Sprintf("%p", &pv)
- vt := "string"
- vs := "test"
- addFormatterTest("%v", v, vs)
- addFormatterTest("%v", pv, "<*>"+vs)
- addFormatterTest("%v", &pv, "<**>"+vs)
- addFormatterTest("%+v", nv, "")
- addFormatterTest("%+v", v, vs)
- addFormatterTest("%+v", pv, "<*>("+vAddr+")"+vs)
- addFormatterTest("%+v", &pv, "<**>("+pvAddr+"->"+vAddr+")"+vs)
- addFormatterTest("%+v", nv, "")
- addFormatterTest("%#v", v, "("+vt+")"+vs)
- addFormatterTest("%#v", pv, "(*"+vt+")"+vs)
- addFormatterTest("%#v", &pv, "(**"+vt+")"+vs)
- addFormatterTest("%#v", nv, "(*"+vt+")"+"")
- addFormatterTest("%#+v", v, "("+vt+")"+vs)
- addFormatterTest("%#+v", pv, "(*"+vt+")("+vAddr+")"+vs)
- addFormatterTest("%#+v", &pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs)
- addFormatterTest("%#+v", nv, "(*"+vt+")"+"")
-}
-
-func addInterfaceFormatterTests() {
- // Nil interface.
- var v interface{}
- nv := (*interface{})(nil)
- pv := &v
- vAddr := fmt.Sprintf("%p", pv)
- pvAddr := fmt.Sprintf("%p", &pv)
- vt := "interface {}"
- vs := ""
- addFormatterTest("%v", v, vs)
- addFormatterTest("%v", pv, "<*>"+vs)
- addFormatterTest("%v", &pv, "<**>"+vs)
- addFormatterTest("%+v", nv, "")
- addFormatterTest("%+v", v, vs)
- addFormatterTest("%+v", pv, "<*>("+vAddr+")"+vs)
- addFormatterTest("%+v", &pv, "<**>("+pvAddr+"->"+vAddr+")"+vs)
- addFormatterTest("%+v", nv, "")
- addFormatterTest("%#v", v, "("+vt+")"+vs)
- addFormatterTest("%#v", pv, "(*"+vt+")"+vs)
- addFormatterTest("%#v", &pv, "(**"+vt+")"+vs)
- addFormatterTest("%#v", nv, "(*"+vt+")"+"")
- addFormatterTest("%#+v", v, "("+vt+")"+vs)
- addFormatterTest("%#+v", pv, "(*"+vt+")("+vAddr+")"+vs)
- addFormatterTest("%#+v", &pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs)
- addFormatterTest("%#+v", nv, "(*"+vt+")"+"")
-
- // Sub-interface.
- v2 := interface{}(uint16(65535))
- pv2 := &v2
- v2Addr := fmt.Sprintf("%p", pv2)
- pv2Addr := fmt.Sprintf("%p", &pv2)
- v2t := "uint16"
- v2s := "65535"
- addFormatterTest("%v", v2, v2s)
- addFormatterTest("%v", pv2, "<*>"+v2s)
- addFormatterTest("%v", &pv2, "<**>"+v2s)
- addFormatterTest("%+v", v2, v2s)
- addFormatterTest("%+v", pv2, "<*>("+v2Addr+")"+v2s)
- addFormatterTest("%+v", &pv2, "<**>("+pv2Addr+"->"+v2Addr+")"+v2s)
- addFormatterTest("%#v", v2, "("+v2t+")"+v2s)
- addFormatterTest("%#v", pv2, "(*"+v2t+")"+v2s)
- addFormatterTest("%#v", &pv2, "(**"+v2t+")"+v2s)
- addFormatterTest("%#+v", v2, "("+v2t+")"+v2s)
- addFormatterTest("%#+v", pv2, "(*"+v2t+")("+v2Addr+")"+v2s)
- addFormatterTest("%#+v", &pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")"+v2s)
-}
-
-func addMapFormatterTests() {
- // Map with string keys and int vals.
- v := map[string]int{"one": 1, "two": 2}
- nilMap := map[string]int(nil)
- nv := (*map[string]int)(nil)
- pv := &v
- vAddr := fmt.Sprintf("%p", pv)
- pvAddr := fmt.Sprintf("%p", &pv)
- vt := "map[string]int"
- vs := "map[one:1 two:2]"
- vs2 := "map[two:2 one:1]"
- addFormatterTest("%v", v, vs, vs2)
- addFormatterTest("%v", pv, "<*>"+vs, "<*>"+vs2)
- addFormatterTest("%v", &pv, "<**>"+vs, "<**>"+vs2)
- addFormatterTest("%+v", nilMap, "")
- addFormatterTest("%+v", nv, "")
- addFormatterTest("%+v", v, vs, vs2)
- addFormatterTest("%+v", pv, "<*>("+vAddr+")"+vs, "<*>("+vAddr+")"+vs2)
- addFormatterTest("%+v", &pv, "<**>("+pvAddr+"->"+vAddr+")"+vs,
- "<**>("+pvAddr+"->"+vAddr+")"+vs2)
- addFormatterTest("%+v", nilMap, "")
- addFormatterTest("%+v", nv, "")
- addFormatterTest("%#v", v, "("+vt+")"+vs, "("+vt+")"+vs2)
- addFormatterTest("%#v", pv, "(*"+vt+")"+vs, "(*"+vt+")"+vs2)
- addFormatterTest("%#v", &pv, "(**"+vt+")"+vs, "(**"+vt+")"+vs2)
- addFormatterTest("%#v", nilMap, "("+vt+")"+"")
- addFormatterTest("%#v", nv, "(*"+vt+")"+"")
- addFormatterTest("%#+v", v, "("+vt+")"+vs, "("+vt+")"+vs2)
- addFormatterTest("%#+v", pv, "(*"+vt+")("+vAddr+")"+vs,
- "(*"+vt+")("+vAddr+")"+vs2)
- addFormatterTest("%#+v", &pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs,
- "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs2)
- addFormatterTest("%#+v", nilMap, "("+vt+")"+"")
- addFormatterTest("%#+v", nv, "(*"+vt+")"+"")
-
- // Map with custom formatter type on pointer receiver only keys and vals.
- v2 := map[pstringer]pstringer{"one": "1"}
- nv2 := (*map[pstringer]pstringer)(nil)
- pv2 := &v2
- v2Addr := fmt.Sprintf("%p", pv2)
- pv2Addr := fmt.Sprintf("%p", &pv2)
- v2t := "map[spew_test.pstringer]spew_test.pstringer"
- v2s := "map[stringer one:stringer 1]"
- if spew.UnsafeDisabled {
- v2s = "map[one:1]"
- }
- addFormatterTest("%v", v2, v2s)
- addFormatterTest("%v", pv2, "<*>"+v2s)
- addFormatterTest("%v", &pv2, "<**>"+v2s)
- addFormatterTest("%+v", nv2, "")
- addFormatterTest("%+v", v2, v2s)
- addFormatterTest("%+v", pv2, "<*>("+v2Addr+")"+v2s)
- addFormatterTest("%+v", &pv2, "<**>("+pv2Addr+"->"+v2Addr+")"+v2s)
- addFormatterTest("%+v", nv2, "")
- addFormatterTest("%#v", v2, "("+v2t+")"+v2s)
- addFormatterTest("%#v", pv2, "(*"+v2t+")"+v2s)
- addFormatterTest("%#v", &pv2, "(**"+v2t+")"+v2s)
- addFormatterTest("%#v", nv2, "(*"+v2t+")"+"")
- addFormatterTest("%#+v", v2, "("+v2t+")"+v2s)
- addFormatterTest("%#+v", pv2, "(*"+v2t+")("+v2Addr+")"+v2s)
- addFormatterTest("%#+v", &pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")"+v2s)
- addFormatterTest("%#+v", nv2, "(*"+v2t+")"+"")
-
- // Map with interface keys and values.
- v3 := map[interface{}]interface{}{"one": 1}
- nv3 := (*map[interface{}]interface{})(nil)
- pv3 := &v3
- v3Addr := fmt.Sprintf("%p", pv3)
- pv3Addr := fmt.Sprintf("%p", &pv3)
- v3t := "map[interface {}]interface {}"
- v3t1 := "string"
- v3t2 := "int"
- v3s := "map[one:1]"
- v3s2 := "map[(" + v3t1 + ")one:(" + v3t2 + ")1]"
- addFormatterTest("%v", v3, v3s)
- addFormatterTest("%v", pv3, "<*>"+v3s)
- addFormatterTest("%v", &pv3, "<**>"+v3s)
- addFormatterTest("%+v", nv3, "")
- addFormatterTest("%+v", v3, v3s)
- addFormatterTest("%+v", pv3, "<*>("+v3Addr+")"+v3s)
- addFormatterTest("%+v", &pv3, "<**>("+pv3Addr+"->"+v3Addr+")"+v3s)
- addFormatterTest("%+v", nv3, "")
- addFormatterTest("%#v", v3, "("+v3t+")"+v3s2)
- addFormatterTest("%#v", pv3, "(*"+v3t+")"+v3s2)
- addFormatterTest("%#v", &pv3, "(**"+v3t+")"+v3s2)
- addFormatterTest("%#v", nv3, "(*"+v3t+")"+"")
- addFormatterTest("%#+v", v3, "("+v3t+")"+v3s2)
- addFormatterTest("%#+v", pv3, "(*"+v3t+")("+v3Addr+")"+v3s2)
- addFormatterTest("%#+v", &pv3, "(**"+v3t+")("+pv3Addr+"->"+v3Addr+")"+v3s2)
- addFormatterTest("%#+v", nv3, "(*"+v3t+")"+"")
-
- // Map with nil interface value
- v4 := map[string]interface{}{"nil": nil}
- nv4 := (*map[string]interface{})(nil)
- pv4 := &v4
- v4Addr := fmt.Sprintf("%p", pv4)
- pv4Addr := fmt.Sprintf("%p", &pv4)
- v4t := "map[string]interface {}"
- v4t1 := "interface {}"
- v4s := "map[nil:]"
- v4s2 := "map[nil:(" + v4t1 + ")]"
- addFormatterTest("%v", v4, v4s)
- addFormatterTest("%v", pv4, "<*>"+v4s)
- addFormatterTest("%v", &pv4, "<**>"+v4s)
- addFormatterTest("%+v", nv4, "")
- addFormatterTest("%+v", v4, v4s)
- addFormatterTest("%+v", pv4, "<*>("+v4Addr+")"+v4s)
- addFormatterTest("%+v", &pv4, "<**>("+pv4Addr+"->"+v4Addr+")"+v4s)
- addFormatterTest("%+v", nv4, "")
- addFormatterTest("%#v", v4, "("+v4t+")"+v4s2)
- addFormatterTest("%#v", pv4, "(*"+v4t+")"+v4s2)
- addFormatterTest("%#v", &pv4, "(**"+v4t+")"+v4s2)
- addFormatterTest("%#v", nv4, "(*"+v4t+")"+"")
- addFormatterTest("%#+v", v4, "("+v4t+")"+v4s2)
- addFormatterTest("%#+v", pv4, "(*"+v4t+")("+v4Addr+")"+v4s2)
- addFormatterTest("%#+v", &pv4, "(**"+v4t+")("+pv4Addr+"->"+v4Addr+")"+v4s2)
- addFormatterTest("%#+v", nv4, "(*"+v4t+")"+"")
-}
-
-func addStructFormatterTests() {
- // Struct with primitives.
- type s1 struct {
- a int8
- b uint8
- }
- v := s1{127, 255}
- nv := (*s1)(nil)
- pv := &v
- vAddr := fmt.Sprintf("%p", pv)
- pvAddr := fmt.Sprintf("%p", &pv)
- vt := "spew_test.s1"
- vt2 := "int8"
- vt3 := "uint8"
- vs := "{127 255}"
- vs2 := "{a:127 b:255}"
- vs3 := "{a:(" + vt2 + ")127 b:(" + vt3 + ")255}"
- addFormatterTest("%v", v, vs)
- addFormatterTest("%v", pv, "<*>"+vs)
- addFormatterTest("%v", &pv, "<**>"+vs)
- addFormatterTest("%+v", nv, "")
- addFormatterTest("%+v", v, vs2)
- addFormatterTest("%+v", pv, "<*>("+vAddr+")"+vs2)
- addFormatterTest("%+v", &pv, "<**>("+pvAddr+"->"+vAddr+")"+vs2)
- addFormatterTest("%+v", nv, "")
- addFormatterTest("%#v", v, "("+vt+")"+vs3)
- addFormatterTest("%#v", pv, "(*"+vt+")"+vs3)
- addFormatterTest("%#v", &pv, "(**"+vt+")"+vs3)
- addFormatterTest("%#v", nv, "(*"+vt+")"+"")
- addFormatterTest("%#+v", v, "("+vt+")"+vs3)
- addFormatterTest("%#+v", pv, "(*"+vt+")("+vAddr+")"+vs3)
- addFormatterTest("%#+v", &pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs3)
- addFormatterTest("%#+v", nv, "(*"+vt+")"+"")
-
- // Struct that contains another struct.
- type s2 struct {
- s1 s1
- b bool
- }
- v2 := s2{s1{127, 255}, true}
- nv2 := (*s2)(nil)
- pv2 := &v2
- v2Addr := fmt.Sprintf("%p", pv2)
- pv2Addr := fmt.Sprintf("%p", &pv2)
- v2t := "spew_test.s2"
- v2t2 := "spew_test.s1"
- v2t3 := "int8"
- v2t4 := "uint8"
- v2t5 := "bool"
- v2s := "{{127 255} true}"
- v2s2 := "{s1:{a:127 b:255} b:true}"
- v2s3 := "{s1:(" + v2t2 + "){a:(" + v2t3 + ")127 b:(" + v2t4 + ")255} b:(" +
- v2t5 + ")true}"
- addFormatterTest("%v", v2, v2s)
- addFormatterTest("%v", pv2, "<*>"+v2s)
- addFormatterTest("%v", &pv2, "<**>"+v2s)
- addFormatterTest("%+v", nv2, "")
- addFormatterTest("%+v", v2, v2s2)
- addFormatterTest("%+v", pv2, "<*>("+v2Addr+")"+v2s2)
- addFormatterTest("%+v", &pv2, "<**>("+pv2Addr+"->"+v2Addr+")"+v2s2)
- addFormatterTest("%+v", nv2, "")
- addFormatterTest("%#v", v2, "("+v2t+")"+v2s3)
- addFormatterTest("%#v", pv2, "(*"+v2t+")"+v2s3)
- addFormatterTest("%#v", &pv2, "(**"+v2t+")"+v2s3)
- addFormatterTest("%#v", nv2, "(*"+v2t+")"+"")
- addFormatterTest("%#+v", v2, "("+v2t+")"+v2s3)
- addFormatterTest("%#+v", pv2, "(*"+v2t+")("+v2Addr+")"+v2s3)
- addFormatterTest("%#+v", &pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")"+v2s3)
- addFormatterTest("%#+v", nv2, "(*"+v2t+")"+"")
-
- // Struct that contains custom type with Stringer pointer interface via both
- // exported and unexported fields.
- type s3 struct {
- s pstringer
- S pstringer
- }
- v3 := s3{"test", "test2"}
- nv3 := (*s3)(nil)
- pv3 := &v3
- v3Addr := fmt.Sprintf("%p", pv3)
- pv3Addr := fmt.Sprintf("%p", &pv3)
- v3t := "spew_test.s3"
- v3t2 := "spew_test.pstringer"
- v3s := "{stringer test stringer test2}"
- v3sp := v3s
- v3s2 := "{s:stringer test S:stringer test2}"
- v3s2p := v3s2
- v3s3 := "{s:(" + v3t2 + ")stringer test S:(" + v3t2 + ")stringer test2}"
- v3s3p := v3s3
- if spew.UnsafeDisabled {
- v3s = "{test test2}"
- v3sp = "{test stringer test2}"
- v3s2 = "{s:test S:test2}"
- v3s2p = "{s:test S:stringer test2}"
- v3s3 = "{s:(" + v3t2 + ")test S:(" + v3t2 + ")test2}"
- v3s3p = "{s:(" + v3t2 + ")test S:(" + v3t2 + ")stringer test2}"
- }
- addFormatterTest("%v", v3, v3s)
- addFormatterTest("%v", pv3, "<*>"+v3sp)
- addFormatterTest("%v", &pv3, "<**>"+v3sp)
- addFormatterTest("%+v", nv3, "")
- addFormatterTest("%+v", v3, v3s2)
- addFormatterTest("%+v", pv3, "<*>("+v3Addr+")"+v3s2p)
- addFormatterTest("%+v", &pv3, "<**>("+pv3Addr+"->"+v3Addr+")"+v3s2p)
- addFormatterTest("%+v", nv3, "")
- addFormatterTest("%#v", v3, "("+v3t+")"+v3s3)
- addFormatterTest("%#v", pv3, "(*"+v3t+")"+v3s3p)
- addFormatterTest("%#v", &pv3, "(**"+v3t+")"+v3s3p)
- addFormatterTest("%#v", nv3, "(*"+v3t+")"+"")
- addFormatterTest("%#+v", v3, "("+v3t+")"+v3s3)
- addFormatterTest("%#+v", pv3, "(*"+v3t+")("+v3Addr+")"+v3s3p)
- addFormatterTest("%#+v", &pv3, "(**"+v3t+")("+pv3Addr+"->"+v3Addr+")"+v3s3p)
- addFormatterTest("%#+v", nv3, "(*"+v3t+")"+"")
-
- // Struct that contains embedded struct and field to same struct.
- e := embed{"embedstr"}
- v4 := embedwrap{embed: &e, e: &e}
- nv4 := (*embedwrap)(nil)
- pv4 := &v4
- eAddr := fmt.Sprintf("%p", &e)
- v4Addr := fmt.Sprintf("%p", pv4)
- pv4Addr := fmt.Sprintf("%p", &pv4)
- v4t := "spew_test.embedwrap"
- v4t2 := "spew_test.embed"
- v4t3 := "string"
- v4s := "{<*>{embedstr} <*>{embedstr}}"
- v4s2 := "{embed:<*>(" + eAddr + "){a:embedstr} e:<*>(" + eAddr +
- "){a:embedstr}}"
- v4s3 := "{embed:(*" + v4t2 + "){a:(" + v4t3 + ")embedstr} e:(*" + v4t2 +
- "){a:(" + v4t3 + ")embedstr}}"
- v4s4 := "{embed:(*" + v4t2 + ")(" + eAddr + "){a:(" + v4t3 +
- ")embedstr} e:(*" + v4t2 + ")(" + eAddr + "){a:(" + v4t3 + ")embedstr}}"
- addFormatterTest("%v", v4, v4s)
- addFormatterTest("%v", pv4, "<*>"+v4s)
- addFormatterTest("%v", &pv4, "<**>"+v4s)
- addFormatterTest("%+v", nv4, "")
- addFormatterTest("%+v", v4, v4s2)
- addFormatterTest("%+v", pv4, "<*>("+v4Addr+")"+v4s2)
- addFormatterTest("%+v", &pv4, "<**>("+pv4Addr+"->"+v4Addr+")"+v4s2)
- addFormatterTest("%+v", nv4, "")
- addFormatterTest("%#v", v4, "("+v4t+")"+v4s3)
- addFormatterTest("%#v", pv4, "(*"+v4t+")"+v4s3)
- addFormatterTest("%#v", &pv4, "(**"+v4t+")"+v4s3)
- addFormatterTest("%#v", nv4, "(*"+v4t+")"+"")
- addFormatterTest("%#+v", v4, "("+v4t+")"+v4s4)
- addFormatterTest("%#+v", pv4, "(*"+v4t+")("+v4Addr+")"+v4s4)
- addFormatterTest("%#+v", &pv4, "(**"+v4t+")("+pv4Addr+"->"+v4Addr+")"+v4s4)
- addFormatterTest("%#+v", nv4, "(*"+v4t+")"+"")
-}
-
-func addUintptrFormatterTests() {
- // Null pointer.
- v := uintptr(0)
- nv := (*uintptr)(nil)
- pv := &v
- vAddr := fmt.Sprintf("%p", pv)
- pvAddr := fmt.Sprintf("%p", &pv)
- vt := "uintptr"
- vs := ""
- addFormatterTest("%v", v, vs)
- addFormatterTest("%v", pv, "<*>"+vs)
- addFormatterTest("%v", &pv, "<**>"+vs)
- addFormatterTest("%+v", nv, "")
- addFormatterTest("%+v", v, vs)
- addFormatterTest("%+v", pv, "<*>("+vAddr+")"+vs)
- addFormatterTest("%+v", &pv, "<**>("+pvAddr+"->"+vAddr+")"+vs)
- addFormatterTest("%+v", nv, "")
- addFormatterTest("%#v", v, "("+vt+")"+vs)
- addFormatterTest("%#v", pv, "(*"+vt+")"+vs)
- addFormatterTest("%#v", &pv, "(**"+vt+")"+vs)
- addFormatterTest("%#v", nv, "(*"+vt+")"+"")
- addFormatterTest("%#+v", v, "("+vt+")"+vs)
- addFormatterTest("%#+v", pv, "(*"+vt+")("+vAddr+")"+vs)
- addFormatterTest("%#+v", &pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs)
- addFormatterTest("%#+v", nv, "(*"+vt+")"+"")
-
- // Address of real variable.
- i := 1
- v2 := uintptr(unsafe.Pointer(&i))
- pv2 := &v2
- v2Addr := fmt.Sprintf("%p", pv2)
- pv2Addr := fmt.Sprintf("%p", &pv2)
- v2t := "uintptr"
- v2s := fmt.Sprintf("%p", &i)
- addFormatterTest("%v", v2, v2s)
- addFormatterTest("%v", pv2, "<*>"+v2s)
- addFormatterTest("%v", &pv2, "<**>"+v2s)
- addFormatterTest("%+v", v2, v2s)
- addFormatterTest("%+v", pv2, "<*>("+v2Addr+")"+v2s)
- addFormatterTest("%+v", &pv2, "<**>("+pv2Addr+"->"+v2Addr+")"+v2s)
- addFormatterTest("%#v", v2, "("+v2t+")"+v2s)
- addFormatterTest("%#v", pv2, "(*"+v2t+")"+v2s)
- addFormatterTest("%#v", &pv2, "(**"+v2t+")"+v2s)
- addFormatterTest("%#+v", v2, "("+v2t+")"+v2s)
- addFormatterTest("%#+v", pv2, "(*"+v2t+")("+v2Addr+")"+v2s)
- addFormatterTest("%#+v", &pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")"+v2s)
-}
-
-func addUnsafePointerFormatterTests() {
- // Null pointer.
- v := unsafe.Pointer(uintptr(0))
- nv := (*unsafe.Pointer)(nil)
- pv := &v
- vAddr := fmt.Sprintf("%p", pv)
- pvAddr := fmt.Sprintf("%p", &pv)
- vt := "unsafe.Pointer"
- vs := ""
- addFormatterTest("%v", v, vs)
- addFormatterTest("%v", pv, "<*>"+vs)
- addFormatterTest("%v", &pv, "<**>"+vs)
- addFormatterTest("%+v", nv, "")
- addFormatterTest("%+v", v, vs)
- addFormatterTest("%+v", pv, "<*>("+vAddr+")"+vs)
- addFormatterTest("%+v", &pv, "<**>("+pvAddr+"->"+vAddr+")"+vs)
- addFormatterTest("%+v", nv, "")
- addFormatterTest("%#v", v, "("+vt+")"+vs)
- addFormatterTest("%#v", pv, "(*"+vt+")"+vs)
- addFormatterTest("%#v", &pv, "(**"+vt+")"+vs)
- addFormatterTest("%#v", nv, "(*"+vt+")"+"")
- addFormatterTest("%#+v", v, "("+vt+")"+vs)
- addFormatterTest("%#+v", pv, "(*"+vt+")("+vAddr+")"+vs)
- addFormatterTest("%#+v", &pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs)
- addFormatterTest("%#+v", nv, "(*"+vt+")"+"")
-
- // Address of real variable.
- i := 1
- v2 := unsafe.Pointer(&i)
- pv2 := &v2
- v2Addr := fmt.Sprintf("%p", pv2)
- pv2Addr := fmt.Sprintf("%p", &pv2)
- v2t := "unsafe.Pointer"
- v2s := fmt.Sprintf("%p", &i)
- addFormatterTest("%v", v2, v2s)
- addFormatterTest("%v", pv2, "<*>"+v2s)
- addFormatterTest("%v", &pv2, "<**>"+v2s)
- addFormatterTest("%+v", v2, v2s)
- addFormatterTest("%+v", pv2, "<*>("+v2Addr+")"+v2s)
- addFormatterTest("%+v", &pv2, "<**>("+pv2Addr+"->"+v2Addr+")"+v2s)
- addFormatterTest("%#v", v2, "("+v2t+")"+v2s)
- addFormatterTest("%#v", pv2, "(*"+v2t+")"+v2s)
- addFormatterTest("%#v", &pv2, "(**"+v2t+")"+v2s)
- addFormatterTest("%#+v", v2, "("+v2t+")"+v2s)
- addFormatterTest("%#+v", pv2, "(*"+v2t+")("+v2Addr+")"+v2s)
- addFormatterTest("%#+v", &pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")"+v2s)
-}
-
-func addChanFormatterTests() {
- // Nil channel.
- var v chan int
- pv := &v
- nv := (*chan int)(nil)
- vAddr := fmt.Sprintf("%p", pv)
- pvAddr := fmt.Sprintf("%p", &pv)
- vt := "chan int"
- vs := ""
- addFormatterTest("%v", v, vs)
- addFormatterTest("%v", pv, "<*>"+vs)
- addFormatterTest("%v", &pv, "<**>"+vs)
- addFormatterTest("%+v", nv, "")
- addFormatterTest("%+v", v, vs)
- addFormatterTest("%+v", pv, "<*>("+vAddr+")"+vs)
- addFormatterTest("%+v", &pv, "<**>("+pvAddr+"->"+vAddr+")"+vs)
- addFormatterTest("%+v", nv, "")
- addFormatterTest("%#v", v, "("+vt+")"+vs)
- addFormatterTest("%#v", pv, "(*"+vt+")"+vs)
- addFormatterTest("%#v", &pv, "(**"+vt+")"+vs)
- addFormatterTest("%#v", nv, "(*"+vt+")"+"")
- addFormatterTest("%#+v", v, "("+vt+")"+vs)
- addFormatterTest("%#+v", pv, "(*"+vt+")("+vAddr+")"+vs)
- addFormatterTest("%#+v", &pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs)
- addFormatterTest("%#+v", nv, "(*"+vt+")"+"")
-
- // Real channel.
- v2 := make(chan int)
- pv2 := &v2
- v2Addr := fmt.Sprintf("%p", pv2)
- pv2Addr := fmt.Sprintf("%p", &pv2)
- v2t := "chan int"
- v2s := fmt.Sprintf("%p", v2)
- addFormatterTest("%v", v2, v2s)
- addFormatterTest("%v", pv2, "<*>"+v2s)
- addFormatterTest("%v", &pv2, "<**>"+v2s)
- addFormatterTest("%+v", v2, v2s)
- addFormatterTest("%+v", pv2, "<*>("+v2Addr+")"+v2s)
- addFormatterTest("%+v", &pv2, "<**>("+pv2Addr+"->"+v2Addr+")"+v2s)
- addFormatterTest("%#v", v2, "("+v2t+")"+v2s)
- addFormatterTest("%#v", pv2, "(*"+v2t+")"+v2s)
- addFormatterTest("%#v", &pv2, "(**"+v2t+")"+v2s)
- addFormatterTest("%#+v", v2, "("+v2t+")"+v2s)
- addFormatterTest("%#+v", pv2, "(*"+v2t+")("+v2Addr+")"+v2s)
- addFormatterTest("%#+v", &pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")"+v2s)
-}
-
-func addFuncFormatterTests() {
- // Function with no params and no returns.
- v := addIntFormatterTests
- nv := (*func())(nil)
- pv := &v
- vAddr := fmt.Sprintf("%p", pv)
- pvAddr := fmt.Sprintf("%p", &pv)
- vt := "func()"
- vs := fmt.Sprintf("%p", v)
- addFormatterTest("%v", v, vs)
- addFormatterTest("%v", pv, "<*>"+vs)
- addFormatterTest("%v", &pv, "<**>"+vs)
- addFormatterTest("%+v", nv, "")
- addFormatterTest("%+v", v, vs)
- addFormatterTest("%+v", pv, "<*>("+vAddr+")"+vs)
- addFormatterTest("%+v", &pv, "<**>("+pvAddr+"->"+vAddr+")"+vs)
- addFormatterTest("%+v", nv, "")
- addFormatterTest("%#v", v, "("+vt+")"+vs)
- addFormatterTest("%#v", pv, "(*"+vt+")"+vs)
- addFormatterTest("%#v", &pv, "(**"+vt+")"+vs)
- addFormatterTest("%#v", nv, "(*"+vt+")"+"")
- addFormatterTest("%#+v", v, "("+vt+")"+vs)
- addFormatterTest("%#+v", pv, "(*"+vt+")("+vAddr+")"+vs)
- addFormatterTest("%#+v", &pv, "(**"+vt+")("+pvAddr+"->"+vAddr+")"+vs)
- addFormatterTest("%#+v", nv, "(*"+vt+")"+"")
-
- // Function with param and no returns.
- v2 := TestFormatter
- nv2 := (*func(*testing.T))(nil)
- pv2 := &v2
- v2Addr := fmt.Sprintf("%p", pv2)
- pv2Addr := fmt.Sprintf("%p", &pv2)
- v2t := "func(*testing.T)"
- v2s := fmt.Sprintf("%p", v2)
- addFormatterTest("%v", v2, v2s)
- addFormatterTest("%v", pv2, "<*>"+v2s)
- addFormatterTest("%v", &pv2, "<**>"+v2s)
- addFormatterTest("%+v", nv2, "")
- addFormatterTest("%+v", v2, v2s)
- addFormatterTest("%+v", pv2, "<*>("+v2Addr+")"+v2s)
- addFormatterTest("%+v", &pv2, "<**>("+pv2Addr+"->"+v2Addr+")"+v2s)
- addFormatterTest("%+v", nv2, "")
- addFormatterTest("%#v", v2, "("+v2t+")"+v2s)
- addFormatterTest("%#v", pv2, "(*"+v2t+")"+v2s)
- addFormatterTest("%#v", &pv2, "(**"+v2t+")"+v2s)
- addFormatterTest("%#v", nv2, "(*"+v2t+")"+"")
- addFormatterTest("%#+v", v2, "("+v2t+")"+v2s)
- addFormatterTest("%#+v", pv2, "(*"+v2t+")("+v2Addr+")"+v2s)
- addFormatterTest("%#+v", &pv2, "(**"+v2t+")("+pv2Addr+"->"+v2Addr+")"+v2s)
- addFormatterTest("%#+v", nv2, "(*"+v2t+")"+"")
-
- // Function with multiple params and multiple returns.
- var v3 = func(i int, s string) (b bool, err error) {
- return true, nil
- }
- nv3 := (*func(int, string) (bool, error))(nil)
- pv3 := &v3
- v3Addr := fmt.Sprintf("%p", pv3)
- pv3Addr := fmt.Sprintf("%p", &pv3)
- v3t := "func(int, string) (bool, error)"
- v3s := fmt.Sprintf("%p", v3)
- addFormatterTest("%v", v3, v3s)
- addFormatterTest("%v", pv3, "<*>"+v3s)
- addFormatterTest("%v", &pv3, "<**>"+v3s)
- addFormatterTest("%+v", nv3, "")
- addFormatterTest("%+v", v3, v3s)
- addFormatterTest("%+v", pv3, "<*>("+v3Addr+")"+v3s)
- addFormatterTest("%+v", &pv3, "<**>("+pv3Addr+"->"+v3Addr+")"+v3s)
- addFormatterTest("%+v", nv3, "")
- addFormatterTest("%#v", v3, "("+v3t+")"+v3s)
- addFormatterTest("%#v", pv3, "(*"+v3t+")"+v3s)
- addFormatterTest("%#v", &pv3, "(**"+v3t+")"+v3s)
- addFormatterTest("%#v", nv3, "(*"+v3t+")"+"")
- addFormatterTest("%#+v", v3, "("+v3t+")"+v3s)
- addFormatterTest("%#+v", pv3, "(*"+v3t+")("+v3Addr+")"+v3s)
- addFormatterTest("%#+v", &pv3, "(**"+v3t+")("+pv3Addr+"->"+v3Addr+")"+v3s)
- addFormatterTest("%#+v", nv3, "(*"+v3t+")"+"")
-}
-
-func addCircularFormatterTests() {
- // Struct that is circular through self referencing.
- type circular struct {
- c *circular
- }
- v := circular{nil}
- v.c = &v
- pv := &v
- vAddr := fmt.Sprintf("%p", pv)
- pvAddr := fmt.Sprintf("%p", &pv)
- vt := "spew_test.circular"
- vs := "{<*>{<*>}}"
- vs2 := "{<*>}"
- vs3 := "{c:<*>(" + vAddr + "){c:<*>(" + vAddr + ")}}"
- vs4 := "{c:<*>(" + vAddr + ")}"
- vs5 := "{c:(*" + vt + "){c:(*" + vt + ")}}"
- vs6 := "{c:(*" + vt + ")