summaryrefslogtreecommitdiffstats
path: root/vendor/github.com/spf13
diff options
context:
space:
mode:
authorChristopher Speller <crspeller@gmail.com>2018-04-16 05:37:14 -0700
committerJoram Wilander <jwawilander@gmail.com>2018-04-16 08:37:14 -0400
commit6e2cb00008cbf09e556b00f87603797fcaa47e09 (patch)
tree3c0eb55ff4226a3f024aad373140d1fb860a6404 /vendor/github.com/spf13
parentbf24f51c4e1cc6286885460672f7f449e8c6f5ef (diff)
downloadchat-6e2cb00008cbf09e556b00f87603797fcaa47e09.tar.gz
chat-6e2cb00008cbf09e556b00f87603797fcaa47e09.tar.bz2
chat-6e2cb00008cbf09e556b00f87603797fcaa47e09.zip
Depenancy upgrades and movign to dep. (#8630)
Diffstat (limited to 'vendor/github.com/spf13')
-rw-r--r--vendor/github.com/spf13/afero/.travis.yml2
-rw-r--r--vendor/github.com/spf13/afero/afero_test.go699
-rw-r--r--vendor/github.com/spf13/afero/basepath.go47
-rw-r--r--vendor/github.com/spf13/afero/basepath_test.go142
-rw-r--r--vendor/github.com/spf13/afero/cacheOnReadFs.go6
-rw-r--r--vendor/github.com/spf13/afero/composite_test.go404
-rw-r--r--vendor/github.com/spf13/afero/copyOnWriteFs.go53
-rw-r--r--vendor/github.com/spf13/afero/copyOnWriteFs_test.go39
-rw-r--r--vendor/github.com/spf13/afero/ioutil_test.go112
-rw-r--r--vendor/github.com/spf13/afero/lstater.go (renamed from vendor/github.com/spf13/cobra/cobra/main.go)17
-rw-r--r--vendor/github.com/spf13/afero/match.go4
-rw-r--r--vendor/github.com/spf13/afero/match_test.go183
-rw-r--r--vendor/github.com/spf13/afero/mem/file_test.go154
-rw-r--r--vendor/github.com/spf13/afero/memmap_test.go451
-rw-r--r--vendor/github.com/spf13/afero/os.go7
-rw-r--r--vendor/github.com/spf13/afero/path.go18
-rw-r--r--vendor/github.com/spf13/afero/path_test.go69
-rw-r--r--vendor/github.com/spf13/afero/readonlyfs.go10
-rw-r--r--vendor/github.com/spf13/afero/ro_regexp_test.go96
-rw-r--r--vendor/github.com/spf13/afero/sftpfs/file.go95
-rw-r--r--vendor/github.com/spf13/afero/sftpfs/sftp.go129
-rw-r--r--vendor/github.com/spf13/afero/sftpfs/sftp_test_go286
-rw-r--r--vendor/github.com/spf13/afero/unionFile.go189
-rw-r--r--vendor/github.com/spf13/afero/util_test.go450
-rw-r--r--vendor/github.com/spf13/cast/cast_test.go1208
-rw-r--r--vendor/github.com/spf13/cobra/.circleci/config.yml38
-rw-r--r--vendor/github.com/spf13/cobra/.travis.yml4
-rw-r--r--vendor/github.com/spf13/cobra/args_test.go241
-rw-r--r--vendor/github.com/spf13/cobra/bash_completions.go22
-rw-r--r--vendor/github.com/spf13/cobra/bash_completions.md25
-rw-r--r--vendor/github.com/spf13/cobra/bash_completions_test.go197
-rw-r--r--vendor/github.com/spf13/cobra/cobra/README.md94
-rw-r--r--vendor/github.com/spf13/cobra/cobra/cmd/add.go179
-rw-r--r--vendor/github.com/spf13/cobra/cobra/cmd/add_test.go109
-rw-r--r--vendor/github.com/spf13/cobra/cobra/cmd/golden_test.go77
-rw-r--r--vendor/github.com/spf13/cobra/cobra/cmd/helpers.go168
-rw-r--r--vendor/github.com/spf13/cobra/cobra/cmd/init.go234
-rw-r--r--vendor/github.com/spf13/cobra/cobra/cmd/init_test.go83
-rw-r--r--vendor/github.com/spf13/cobra/cobra/cmd/project.go200
-rw-r--r--vendor/github.com/spf13/cobra/cobra/cmd/project_test.go24
-rw-r--r--vendor/github.com/spf13/cobra/cobra/cmd/root.go79
-rw-r--r--vendor/github.com/spf13/cobra/cobra/cmd/testdata/main.go.golden21
-rw-r--r--vendor/github.com/spf13/cobra/cobra/cmd/testdata/root.go.golden89
-rw-r--r--vendor/github.com/spf13/cobra/cobra/cmd/testdata/test.go.golden50
-rw-r--r--vendor/github.com/spf13/cobra/cobra_test.go22
-rw-r--r--vendor/github.com/spf13/cobra/command.go3
-rw-r--r--vendor/github.com/spf13/cobra/command_test.go1628
-rw-r--r--vendor/github.com/spf13/cobra/doc/cmd_test.go86
-rw-r--r--vendor/github.com/spf13/cobra/doc/man_docs.go236
-rw-r--r--vendor/github.com/spf13/cobra/doc/man_docs.md31
-rw-r--r--vendor/github.com/spf13/cobra/doc/man_docs_test.go177
-rw-r--r--vendor/github.com/spf13/cobra/doc/man_examples_test.go35
-rw-r--r--vendor/github.com/spf13/cobra/doc/md_docs.go159
-rw-r--r--vendor/github.com/spf13/cobra/doc/md_docs.md115
-rw-r--r--vendor/github.com/spf13/cobra/doc/md_docs_test.go74
-rw-r--r--vendor/github.com/spf13/cobra/doc/rest_docs.go185
-rw-r--r--vendor/github.com/spf13/cobra/doc/rest_docs.md114
-rw-r--r--vendor/github.com/spf13/cobra/doc/rest_docs_test.go76
-rw-r--r--vendor/github.com/spf13/cobra/doc/util.go51
-rw-r--r--vendor/github.com/spf13/cobra/doc/yaml_docs.go169
-rw-r--r--vendor/github.com/spf13/cobra/doc/yaml_docs.md112
-rw-r--r--vendor/github.com/spf13/cobra/doc/yaml_docs_test.go74
-rw-r--r--vendor/github.com/spf13/cobra/zsh_completions_test.go89
-rw-r--r--vendor/github.com/spf13/jwalterweatherman/default_notepad_test.go102
-rw-r--r--vendor/github.com/spf13/jwalterweatherman/notepad_test.go50
-rw-r--r--vendor/github.com/spf13/pflag/bool_slice_test.go215
-rw-r--r--vendor/github.com/spf13/pflag/bool_test.go179
-rw-r--r--vendor/github.com/spf13/pflag/bytes.go105
-rw-r--r--vendor/github.com/spf13/pflag/count_test.go56
-rw-r--r--vendor/github.com/spf13/pflag/duration_slice_test.go165
-rw-r--r--vendor/github.com/spf13/pflag/example_test.go36
-rw-r--r--vendor/github.com/spf13/pflag/export_test.go29
-rw-r--r--vendor/github.com/spf13/pflag/flag.go98
-rw-r--r--vendor/github.com/spf13/pflag/flag_test.go1158
-rw-r--r--vendor/github.com/spf13/pflag/golangflag.go4
-rw-r--r--vendor/github.com/spf13/pflag/golangflag_test.go39
-rw-r--r--vendor/github.com/spf13/pflag/int_slice_test.go165
-rw-r--r--vendor/github.com/spf13/pflag/ip_slice_test.go222
-rw-r--r--vendor/github.com/spf13/pflag/ip_test.go63
-rw-r--r--vendor/github.com/spf13/pflag/ipnet_test.go70
-rw-r--r--vendor/github.com/spf13/pflag/string_array.go8
-rw-r--r--vendor/github.com/spf13/pflag/string_array_test.go233
-rw-r--r--vendor/github.com/spf13/pflag/string_slice.go20
-rw-r--r--vendor/github.com/spf13/pflag/string_slice_test.go253
-rw-r--r--vendor/github.com/spf13/pflag/uint_slice_test.go161
-rwxr-xr-xvendor/github.com/spf13/pflag/verify/all.sh69
-rwxr-xr-xvendor/github.com/spf13/pflag/verify/gofmt.sh19
-rwxr-xr-xvendor/github.com/spf13/pflag/verify/golint.sh15
-rw-r--r--vendor/github.com/spf13/viper/flags_test.go65
-rw-r--r--vendor/github.com/spf13/viper/overrides_test.go173
-rw-r--r--vendor/github.com/spf13/viper/remote/remote.go105
-rw-r--r--vendor/github.com/spf13/viper/util_test.go54
-rw-r--r--vendor/github.com/spf13/viper/viper_test.go1406
93 files changed, 497 insertions, 15080 deletions
diff --git a/vendor/github.com/spf13/afero/.travis.yml b/vendor/github.com/spf13/afero/.travis.yml
index e002181fe..0637db726 100644
--- a/vendor/github.com/spf13/afero/.travis.yml
+++ b/vendor/github.com/spf13/afero/.travis.yml
@@ -2,8 +2,8 @@ sudo: false
language: go
go:
- - 1.8
- 1.9
+ - "1.10"
- tip
os:
diff --git a/vendor/github.com/spf13/afero/afero_test.go b/vendor/github.com/spf13/afero/afero_test.go
deleted file mode 100644
index 526afa975..000000000
--- a/vendor/github.com/spf13/afero/afero_test.go
+++ /dev/null
@@ -1,699 +0,0 @@
-// Copyright © 2014 Steve Francia <spf@spf13.com>.
-// Copyright 2009 The Go Authors. All rights reserved.
-//
-// 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 afero
-
-import (
- "bytes"
- "fmt"
- "io"
- "io/ioutil"
- "os"
- "path/filepath"
- "runtime"
- "strings"
- "syscall"
- "testing"
-)
-
-var testName = "test.txt"
-var Fss = []Fs{&MemMapFs{}, &OsFs{}}
-
-var testRegistry map[Fs][]string = make(map[Fs][]string)
-
-func testDir(fs Fs) string {
- name, err := TempDir(fs, "", "afero")
- if err != nil {
- panic(fmt.Sprint("unable to work with test dir", err))
- }
- testRegistry[fs] = append(testRegistry[fs], name)
-
- return name
-}
-
-func tmpFile(fs Fs) File {
- x, err := TempFile(fs, "", "afero")
-
- if err != nil {
- panic(fmt.Sprint("unable to work with temp file", err))
- }
-
- testRegistry[fs] = append(testRegistry[fs], x.Name())
-
- return x
-}
-
-//Read with length 0 should not return EOF.
-func TestRead0(t *testing.T) {
- for _, fs := range Fss {
- f := tmpFile(fs)
- defer f.Close()
- f.WriteString("Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.")
-
- var b []byte
- // b := make([]byte, 0)
- n, err := f.Read(b)
- if n != 0 || err != nil {
- t.Errorf("%v: Read(0) = %d, %v, want 0, nil", fs.Name(), n, err)
- }
- f.Seek(0, 0)
- b = make([]byte, 100)
- n, err = f.Read(b)
- if n <= 0 || err != nil {
- t.Errorf("%v: Read(100) = %d, %v, want >0, nil", fs.Name(), n, err)
- }
- }
-}
-
-func TestOpenFile(t *testing.T) {
- defer removeAllTestFiles(t)
- for _, fs := range Fss {
- tmp := testDir(fs)
- path := filepath.Join(tmp, testName)
-
- f, err := fs.OpenFile(path, os.O_RDWR|os.O_CREATE, 0600)
- if err != nil {
- t.Error(fs.Name(), "OpenFile (O_CREATE) failed:", err)
- continue
- }
- io.WriteString(f, "initial")
- f.Close()
-
- f, err = fs.OpenFile(path, os.O_WRONLY|os.O_APPEND, 0600)
- if err != nil {
- t.Error(fs.Name(), "OpenFile (O_APPEND) failed:", err)
- continue
- }
- io.WriteString(f, "|append")
- f.Close()
-
- f, err = fs.OpenFile(path, os.O_RDONLY, 0600)
- contents, _ := ioutil.ReadAll(f)
- expectedContents := "initial|append"
- if string(contents) != expectedContents {
- t.Errorf("%v: appending, expected '%v', got: '%v'", fs.Name(), expectedContents, string(contents))
- }
- f.Close()
-
- f, err = fs.OpenFile(path, os.O_RDWR|os.O_TRUNC, 0600)
- if err != nil {
- t.Error(fs.Name(), "OpenFile (O_TRUNC) failed:", err)
- continue
- }
- contents, _ = ioutil.ReadAll(f)
- if string(contents) != "" {
- t.Errorf("%v: expected truncated file, got: '%v'", fs.Name(), string(contents))
- }
- f.Close()
- }
-}
-
-func TestCreate(t *testing.T) {
- defer removeAllTestFiles(t)
- for _, fs := range Fss {
- tmp := testDir(fs)
- path := filepath.Join(tmp, testName)
-
- f, err := fs.Create(path)
- if err != nil {
- t.Error(fs.Name(), "Create failed:", err)
- f.Close()
- continue
- }
- io.WriteString(f, "initial")
- f.Close()
-
- f, err = fs.Create(path)
- if err != nil {
- t.Error(fs.Name(), "Create failed:", err)
- f.Close()
- continue
- }
- secondContent := "second create"
- io.WriteString(f, secondContent)
- f.Close()
-
- f, err = fs.Open(path)
- if err != nil {
- t.Error(fs.Name(), "Open failed:", err)
- f.Close()
- continue
- }
- buf, err := ReadAll(f)
- if err != nil {
- t.Error(fs.Name(), "ReadAll failed:", err)
- f.Close()
- continue
- }
- if string(buf) != secondContent {
- t.Error(fs.Name(), "Content should be", "\""+secondContent+"\" but is \""+string(buf)+"\"")
- f.Close()
- continue
- }
- f.Close()
- }
-}
-
-func TestMemFileRead(t *testing.T) {
- f := tmpFile(new(MemMapFs))
- // f := MemFileCreate("testfile")
- f.WriteString("abcd")
- f.Seek(0, 0)
- b := make([]byte, 8)
- n, err := f.Read(b)
- if n != 4 {
- t.Errorf("didn't read all bytes: %v %v %v", n, err, b)
- }
- if err != nil {
- t.Errorf("err is not nil: %v %v %v", n, err, b)
- }
- n, err = f.Read(b)
- if n != 0 {
- t.Errorf("read more bytes: %v %v %v", n, err, b)
- }
- if err != io.EOF {
- t.Errorf("error is not EOF: %v %v %v", n, err, b)
- }
-}
-
-func TestRename(t *testing.T) {
- defer removeAllTestFiles(t)
- for _, fs := range Fss {
- tDir := testDir(fs)
- from := filepath.Join(tDir, "/renamefrom")
- to := filepath.Join(tDir, "/renameto")
- exists := filepath.Join(tDir, "/renameexists")
- file, err := fs.Create(from)
- if err != nil {
- t.Fatalf("%s: open %q failed: %v", fs.Name(), to, err)
- }
- if err = file.Close(); err != nil {
- t.Errorf("%s: close %q failed: %v", fs.Name(), to, err)
- }
- file, err = fs.Create(exists)
- if err != nil {
- t.Fatalf("%s: open %q failed: %v", fs.Name(), to, err)
- }
- if err = file.Close(); err != nil {
- t.Errorf("%s: close %q failed: %v", fs.Name(), to, err)
- }
- err = fs.Rename(from, to)
- if err != nil {
- t.Fatalf("%s: rename %q, %q failed: %v", fs.Name(), to, from, err)
- }
- file, err = fs.Create(from)
- if err != nil {
- t.Fatalf("%s: open %q failed: %v", fs.Name(), to, err)
- }
- if err = file.Close(); err != nil {
- t.Errorf("%s: close %q failed: %v", fs.Name(), to, err)
- }
- err = fs.Rename(from, exists)
- if err != nil {
- t.Errorf("%s: rename %q, %q failed: %v", fs.Name(), exists, from, err)
- }
- names, err := readDirNames(fs, tDir)
- if err != nil {
- t.Errorf("%s: readDirNames error: %v", fs.Name(), err)
- }
- found := false
- for _, e := range names {
- if e == "renamefrom" {
- t.Error("File is still called renamefrom")
- }
- if e == "renameto" {
- found = true
- }
- }
- if !found {
- t.Error("File was not renamed to renameto")
- }
-
- _, err = fs.Stat(to)
- if err != nil {
- t.Errorf("%s: stat %q failed: %v", fs.Name(), to, err)
- }
- }
-}
-
-func TestRemove(t *testing.T) {
- for _, fs := range Fss {
-
- x, err := TempFile(fs, "", "afero")
- if err != nil {
- t.Error(fmt.Sprint("unable to work with temp file", err))
- }
-
- path := x.Name()
- x.Close()
-
- tDir := filepath.Dir(path)
-
- err = fs.Remove(path)
- if err != nil {
- t.Errorf("%v: Remove() failed: %v", fs.Name(), err)
- continue
- }
-
- _, err = fs.Stat(path)
- if !os.IsNotExist(err) {
- t.Errorf("%v: Remove() didn't remove file", fs.Name())
- continue
- }
-
- // Deleting non-existent file should raise error
- err = fs.Remove(path)
- if !os.IsNotExist(err) {
- t.Errorf("%v: Remove() didn't raise error for non-existent file", fs.Name())
- }
-
- f, err := fs.Open(tDir)
- if err != nil {
- t.Error("TestDir should still exist:", err)
- }
-
- names, err := f.Readdirnames(-1)
- if err != nil {
- t.Error("Readdirnames failed:", err)
- }
-
- for _, e := range names {
- if e == testName {
- t.Error("File was not removed from parent directory")
- }
- }
- }
-}
-
-func TestTruncate(t *testing.T) {
- defer removeAllTestFiles(t)
- for _, fs := range Fss {
- f := tmpFile(fs)
- defer f.Close()
-
- checkSize(t, f, 0)
- f.Write([]byte("hello, world\n"))
- checkSize(t, f, 13)
- f.Truncate(10)
- checkSize(t, f, 10)
- f.Truncate(1024)
- checkSize(t, f, 1024)
- f.Truncate(0)
- checkSize(t, f, 0)
- _, err := f.Write([]byte("surprise!"))
- if err == nil {
- checkSize(t, f, 13+9) // wrote at offset past where hello, world was.
- }
- }
-}
-
-func TestSeek(t *testing.T) {
- defer removeAllTestFiles(t)
- for _, fs := range Fss {
- f := tmpFile(fs)
- defer f.Close()
-
- const data = "hello, world\n"
- io.WriteString(f, data)
-
- type test struct {
- in int64
- whence int
- out int64
- }
- var tests = []test{
- {0, 1, int64(len(data))},
- {0, 0, 0},
- {5, 0, 5},
- {0, 2, int64(len(data))},
- {0, 0, 0},
- {-1, 2, int64(len(data)) - 1},
- {1 << 33, 0, 1 << 33},
- {1 << 33, 2, 1<<33 + int64(len(data))},
- }
- for i, tt := range tests {
- off, err := f.Seek(tt.in, tt.whence)
- if off != tt.out || err != nil {
- if e, ok := err.(*os.PathError); ok && e.Err == syscall.EINVAL && tt.out > 1<<32 {
- // Reiserfs rejects the big seeks.
- // http://code.google.com/p/go/issues/detail?id=91
- break
- }
- t.Errorf("#%d: Seek(%v, %v) = %v, %v want %v, nil", i, tt.in, tt.whence, off, err, tt.out)
- }
- }
- }
-}
-
-func TestReadAt(t *testing.T) {
- defer removeAllTestFiles(t)
- for _, fs := range Fss {
- f := tmpFile(fs)
- defer f.Close()
-
- const data = "hello, world\n"
- io.WriteString(f, data)
-
- b := make([]byte, 5)
- n, err := f.ReadAt(b, 7)
- if err != nil || n != len(b) {
- t.Fatalf("ReadAt 7: %d, %v", n, err)
- }
- if string(b) != "world" {
- t.Fatalf("ReadAt 7: have %q want %q", string(b), "world")
- }
- }
-}
-
-func TestWriteAt(t *testing.T) {
- defer removeAllTestFiles(t)
- for _, fs := range Fss {
- f := tmpFile(fs)
- defer f.Close()
-
- const data = "hello, world\n"
- io.WriteString(f, data)
-
- n, err := f.WriteAt([]byte("WORLD"), 7)
- if err != nil || n != 5 {
- t.Fatalf("WriteAt 7: %d, %v", n, err)
- }
-
- f2, err := fs.Open(f.Name())
- if err != nil {
- t.Fatalf("%v: ReadFile %s: %v", fs.Name(), f.Name(), err)
- }
- defer f2.Close()
- buf := new(bytes.Buffer)
- buf.ReadFrom(f2)
- b := buf.Bytes()
- if string(b) != "hello, WORLD\n" {
- t.Fatalf("after write: have %q want %q", string(b), "hello, WORLD\n")
- }
-
- }
-}
-
-func setupTestDir(t *testing.T, fs Fs) string {
- path := testDir(fs)
- return setupTestFiles(t, fs, path)
-}
-
-func setupTestDirRoot(t *testing.T, fs Fs) string {
- path := testDir(fs)
- setupTestFiles(t, fs, path)
- return path
-}
-
-func setupTestDirReusePath(t *testing.T, fs Fs, path string) string {
- testRegistry[fs] = append(testRegistry[fs], path)
- return setupTestFiles(t, fs, path)
-}
-
-func setupTestFiles(t *testing.T, fs Fs, path string) string {
- testSubDir := filepath.Join(path, "more", "subdirectories", "for", "testing", "we")
- err := fs.MkdirAll(testSubDir, 0700)
- if err != nil && !os.IsExist(err) {
- t.Fatal(err)
- }
-
- f, err := fs.Create(filepath.Join(testSubDir, "testfile1"))
- if err != nil {
- t.Fatal(err)
- }
- f.WriteString("Testfile 1 content")
- f.Close()
-
- f, err = fs.Create(filepath.Join(testSubDir, "testfile2"))
- if err != nil {
- t.Fatal(err)
- }
- f.WriteString("Testfile 2 content")
- f.Close()
-
- f, err = fs.Create(filepath.Join(testSubDir, "testfile3"))
- if err != nil {
- t.Fatal(err)
- }
- f.WriteString("Testfile 3 content")
- f.Close()
-
- f, err = fs.Create(filepath.Join(testSubDir, "testfile4"))
- if err != nil {
- t.Fatal(err)
- }
- f.WriteString("Testfile 4 content")
- f.Close()
- return testSubDir
-}
-
-func TestReaddirnames(t *testing.T) {
- defer removeAllTestFiles(t)
- for _, fs := range Fss {
- testSubDir := setupTestDir(t, fs)
- tDir := filepath.Dir(testSubDir)
-
- root, err := fs.Open(tDir)
- if err != nil {
- t.Fatal(fs.Name(), tDir, err)
- }
- defer root.Close()
-
- namesRoot, err := root.Readdirnames(-1)
- if err != nil {
- t.Fatal(fs.Name(), namesRoot, err)
- }
-
- sub, err := fs.Open(testSubDir)
- if err != nil {
- t.Fatal(err)
- }
- defer sub.Close()
-
- namesSub, err := sub.Readdirnames(-1)
- if err != nil {
- t.Fatal(fs.Name(), namesSub, err)
- }
-
- findNames(fs, t, tDir, testSubDir, namesRoot, namesSub)
- }
-}
-
-func TestReaddirSimple(t *testing.T) {
- defer removeAllTestFiles(t)
- for _, fs := range Fss {
- testSubDir := setupTestDir(t, fs)
- tDir := filepath.Dir(testSubDir)
-
- root, err := fs.Open(tDir)
- if err != nil {
- t.Fatal(err)
- }
- defer root.Close()
-
- rootInfo, err := root.Readdir(1)
- if err != nil {
- t.Log(myFileInfo(rootInfo))
- t.Error(err)
- }
-
- rootInfo, err = root.Readdir(5)
- if err != io.EOF {
- t.Log(myFileInfo(rootInfo))
- t.Error(err)
- }
-
- sub, err := fs.Open(testSubDir)
- if err != nil {
- t.Fatal(err)
- }
- defer sub.Close()
-
- subInfo, err := sub.Readdir(5)
- if err != nil {
- t.Log(myFileInfo(subInfo))
- t.Error(err)
- }
- }
-}
-
-func TestReaddir(t *testing.T) {
- defer removeAllTestFiles(t)
- for num := 0; num < 6; num++ {
- outputs := make([]string, len(Fss))
- infos := make([]string, len(Fss))
- for i, fs := range Fss {
- testSubDir := setupTestDir(t, fs)
- //tDir := filepath.Dir(testSubDir)
- root, err := fs.Open(testSubDir)
- if err != nil {
- t.Fatal(err)
- }
- defer root.Close()
-
- for j := 0; j < 6; j++ {
- info, err := root.Readdir(num)
- outputs[i] += fmt.Sprintf("%v Error: %v\n", myFileInfo(info), err)
- infos[i] += fmt.Sprintln(len(info), err)
- }
- }
-
- fail := false
- for i, o := range infos {
- if i == 0 {
- continue
- }
- if o != infos[i-1] {
- fail = true
- break
- }
- }
- if fail {
- t.Log("Readdir outputs not equal for Readdir(", num, ")")
- for i, o := range outputs {
- t.Log(Fss[i].Name())
- t.Log(o)
- }
- t.Fail()
- }
- }
-}
-
-type myFileInfo []os.FileInfo
-
-func (m myFileInfo) String() string {
- out := "Fileinfos:\n"
- for _, e := range m {
- out += " " + e.Name() + "\n"
- }
- return out
-}
-
-func TestReaddirAll(t *testing.T) {
- defer removeAllTestFiles(t)
- for _, fs := range Fss {
- testSubDir := setupTestDir(t, fs)
- tDir := filepath.Dir(testSubDir)
-
- root, err := fs.Open(tDir)
- if err != nil {
- t.Fatal(err)
- }
- defer root.Close()
-
- rootInfo, err := root.Readdir(-1)
- if err != nil {
- t.Fatal(err)
- }
- var namesRoot = []string{}
- for _, e := range rootInfo {
- namesRoot = append(namesRoot, e.Name())
- }
-
- sub, err := fs.Open(testSubDir)
- if err != nil {
- t.Fatal(err)
- }
- defer sub.Close()
-
- subInfo, err := sub.Readdir(-1)
- if err != nil {
- t.Fatal(err)
- }
- var namesSub = []string{}
- for _, e := range subInfo {
- namesSub = append(namesSub, e.Name())
- }
-
- findNames(fs, t, tDir, testSubDir, namesRoot, namesSub)
- }
-}
-
-func findNames(fs Fs, t *testing.T, tDir, testSubDir string, root, sub []string) {
- var foundRoot bool
- for _, e := range root {
- f, err := fs.Open(filepath.Join(tDir, e))
- if err != nil {
- t.Error("Open", filepath.Join(tDir, e), ":", err)
- }
- defer f.Close()
-
- if equal(e, "we") {
- foundRoot = true
- }
- }
- if !foundRoot {
- t.Logf("Names root: %v", root)
- t.Logf("Names sub: %v", sub)
- t.Error("Didn't find subdirectory we")
- }
-
- var found1, found2 bool
- for _, e := range sub {
- f, err := fs.Open(filepath.Join(testSubDir, e))
- if err != nil {
- t.Error("Open", filepath.Join(testSubDir, e), ":", err)
- }
- defer f.Close()
-
- if equal(e, "testfile1") {
- found1 = true
- }
- if equal(e, "testfile2") {
- found2 = true
- }
- }
-
- if !found1 {
- t.Logf("Names root: %v", root)
- t.Logf("Names sub: %v", sub)
- t.Error("Didn't find testfile1")
- }
- if !found2 {
- t.Logf("Names root: %v", root)
- t.Logf("Names sub: %v", sub)
- t.Error("Didn't find testfile2")
- }
-}
-
-func removeAllTestFiles(t *testing.T) {
- for fs, list := range testRegistry {
- for _, path := range list {
- if err := fs.RemoveAll(path); err != nil {
- t.Error(fs.Name(), err)
- }
- }
- }
- testRegistry = make(map[Fs][]string)
-}
-
-func equal(name1, name2 string) (r bool) {
- switch runtime.GOOS {
- case "windows":
- r = strings.ToLower(name1) == strings.ToLower(name2)
- default:
- r = name1 == name2
- }
- return
-}
-
-func checkSize(t *testing.T, f File, size int64) {
- dir, err := f.Stat()
- if err != nil {
- t.Fatalf("Stat %q (looking for size %d): %s", f.Name(), size, err)
- }
- if dir.Size() != size {
- t.Errorf("Stat %q: size %d want %d", f.Name(), dir.Size(), size)
- }
-}
diff --git a/vendor/github.com/spf13/afero/basepath.go b/vendor/github.com/spf13/afero/basepath.go
index 5e4fc2ec0..616ff8ff7 100644
--- a/vendor/github.com/spf13/afero/basepath.go
+++ b/vendor/github.com/spf13/afero/basepath.go
@@ -1,7 +1,6 @@
package afero
import (
- "errors"
"os"
"path/filepath"
"runtime"
@@ -9,6 +8,8 @@ import (
"time"
)
+var _ Lstater = (*BasePathFs)(nil)
+
// The BasePathFs restricts all operations to a given path within an Fs.
// The given file name to the operations on this Fs will be prepended with
// the base path before calling the base Fs.
@@ -22,6 +23,16 @@ type BasePathFs struct {
path string
}
+type BasePathFile struct {
+ File
+ path string
+}
+
+func (f *BasePathFile) Name() string {
+ sourcename := f.File.Name()
+ return strings.TrimPrefix(sourcename, filepath.Clean(f.path))
+}
+
func NewBasePathFs(source Fs, path string) Fs {
return &BasePathFs{source: source, path: path}
}
@@ -30,7 +41,7 @@ func NewBasePathFs(source Fs, path string) Fs {
// else the given file with the base path prepended
func (b *BasePathFs) RealPath(name string) (path string, err error) {
if err := validateBasePathName(name); err != nil {
- return "", err
+ return name, err
}
bpath := filepath.Clean(b.path)
@@ -52,7 +63,7 @@ func validateBasePathName(name string) error {
// On Windows a common mistake would be to provide an absolute OS path
// We could strip out the base part, but that would not be very portable.
if filepath.IsAbs(name) {
- return &os.PathError{Op: "realPath", Path: name, Err: errors.New("got a real OS path instead of a virtual")}
+ return os.ErrNotExist
}
return nil
@@ -111,14 +122,22 @@ func (b *BasePathFs) OpenFile(name string, flag int, mode os.FileMode) (f File,
if name, err = b.RealPath(name); err != nil {
return nil, &os.PathError{Op: "openfile", Path: name, Err: err}
}
- return b.source.OpenFile(name, flag, mode)
+ sourcef, err := b.source.OpenFile(name, flag, mode)
+ if err != nil {
+ return nil, err
+ }
+ return &BasePathFile{sourcef, b.path}, nil
}
func (b *BasePathFs) Open(name string) (f File, err error) {
if name, err = b.RealPath(name); err != nil {
return nil, &os.PathError{Op: "open", Path: name, Err: err}
}
- return b.source.Open(name)
+ sourcef, err := b.source.Open(name)
+ if err != nil {
+ return nil, err
+ }
+ return &BasePathFile{File: sourcef, path: b.path}, nil
}
func (b *BasePathFs) Mkdir(name string, mode os.FileMode) (err error) {
@@ -139,7 +158,23 @@ func (b *BasePathFs) Create(name string) (f File, err error) {
if name, err = b.RealPath(name); err != nil {
return nil, &os.PathError{Op: "create", Path: name, Err: err}
}
- return b.source.Create(name)
+ sourcef, err := b.source.Create(name)
+ if err != nil {
+ return nil, err
+ }
+ return &BasePathFile{File: sourcef, path: b.path}, nil
+}
+
+func (b *BasePathFs) LstatIfPossible(name string) (os.FileInfo, bool, error) {
+ name, err := b.RealPath(name)
+ if err != nil {
+ return nil, false, &os.PathError{Op: "lstat", Path: name, Err: err}
+ }
+ if lstater, ok := b.source.(Lstater); ok {
+ return lstater.LstatIfPossible(name)
+ }
+ fi, err := b.source.Stat(name)
+ return fi, false, err
}
// vim: ts=4 sw=4 noexpandtab nolist syn=go
diff --git a/vendor/github.com/spf13/afero/basepath_test.go b/vendor/github.com/spf13/afero/basepath_test.go
deleted file mode 100644
index abc22b9f6..000000000
--- a/vendor/github.com/spf13/afero/basepath_test.go
+++ /dev/null
@@ -1,142 +0,0 @@
-package afero
-
-import (
- "os"
- "path/filepath"
- "runtime"
- "testing"
-)
-
-func TestBasePath(t *testing.T) {
- baseFs := &MemMapFs{}
- baseFs.MkdirAll("/base/path/tmp", 0777)
- bp := NewBasePathFs(baseFs, "/base/path")
-
- if _, err := bp.Create("/tmp/foo"); err != nil {
- t.Errorf("Failed to set real path")
- }
-
- if fh, err := bp.Create("../tmp/bar"); err == nil {
- t.Errorf("succeeded in creating %s ...", fh.Name())
- }
-}
-
-func TestBasePathRoot(t *testing.T) {
- baseFs := &MemMapFs{}
- baseFs.MkdirAll("/base/path/foo/baz", 0777)
- baseFs.MkdirAll("/base/path/boo/", 0777)
- bp := NewBasePathFs(baseFs, "/base/path")
-
- rd, err := ReadDir(bp, string(os.PathSeparator))
-
- if len(rd) != 2 {
- t.Errorf("base path doesn't respect root")
- }
-
- if err != nil {
- t.Error(err)
- }
-}
-
-func TestRealPath(t *testing.T) {
- fs := NewOsFs()
- baseDir, err := TempDir(fs, "", "base")
- if err != nil {
- t.Fatal("error creating tempDir", err)
- }
- defer fs.RemoveAll(baseDir)
- anotherDir, err := TempDir(fs, "", "another")
- if err != nil {
- t.Fatal("error creating tempDir", err)
- }
- defer fs.RemoveAll(anotherDir)
-
- bp := NewBasePathFs(fs, baseDir).(*BasePathFs)
-
- subDir := filepath.Join(baseDir, "s1")
-
- realPath, err := bp.RealPath("/s1")
-
- if err != nil {
- t.Errorf("Got error %s", err)
- }
-
- if realPath != subDir {
- t.Errorf("Expected \n%s got \n%s", subDir, realPath)
- }
-
- if runtime.GOOS == "windows" {
- _, err = bp.RealPath(anotherDir)
-
- if err == nil {
- t.Errorf("Expected error")
- }
-
- } else {
- // on *nix we have no way of just looking at the path and tell that anotherDir
- // is not inside the base file system.
- // The user will receive an os.ErrNotExist later.
- surrealPath, err := bp.RealPath(anotherDir)
-
- if err != nil {
- t.Errorf("Got error %s", err)
- }
-
- excpected := filepath.Join(baseDir, anotherDir)
-
- if surrealPath != excpected {
- t.Errorf("Expected \n%s got \n%s", excpected, surrealPath)
- }
- }
-
-}
-
-func TestNestedBasePaths(t *testing.T) {
- type dirSpec struct {
- Dir1, Dir2, Dir3 string
- }
- dirSpecs := []dirSpec{
- dirSpec{Dir1: "/", Dir2: "/", Dir3: "/"},
- dirSpec{Dir1: "/", Dir2: "/path2", Dir3: "/"},
- dirSpec{Dir1: "/path1/dir", Dir2: "/path2/dir/", Dir3: "/path3/dir"},
- dirSpec{Dir1: "C:/path1", Dir2: "path2/dir", Dir3: "/path3/dir/"},
- }
-
- for _, ds := range dirSpecs {
- memFs := NewMemMapFs()
- level1Fs := NewBasePathFs(memFs, ds.Dir1)
- level2Fs := NewBasePathFs(level1Fs, ds.Dir2)
- level3Fs := NewBasePathFs(level2Fs, ds.Dir3)
-
- type spec struct {
- BaseFs Fs
- FileName string
- }
- specs := []spec{
- spec{BaseFs: level3Fs, FileName: "f.txt"},
- spec{BaseFs: level2Fs, FileName: "f.txt"},
- spec{BaseFs: level1Fs, FileName: "f.txt"},
- }
-
- for _, s := range specs {
- if err := s.BaseFs.MkdirAll(s.FileName, 0755); err != nil {
- t.Errorf("Got error %s", err.Error())
- }
- if _, err := s.BaseFs.Stat(s.FileName); err != nil {
- t.Errorf("Got error %s", err.Error())
- }
-
- if s.BaseFs == level3Fs {
- pathToExist := filepath.Join(ds.Dir3, s.FileName)
- if _, err := level2Fs.Stat(pathToExist); err != nil {
- t.Errorf("Got error %s (path %s)", err.Error(), pathToExist)
- }
- } else if s.BaseFs == level2Fs {
- pathToExist := filepath.Join(ds.Dir2, ds.Dir3, s.FileName)
- if _, err := level1Fs.Stat(pathToExist); err != nil {
- t.Errorf("Got error %s (path %s)", err.Error(), pathToExist)
- }
- }
- }
- }
-}
diff --git a/vendor/github.com/spf13/afero/cacheOnReadFs.go b/vendor/github.com/spf13/afero/cacheOnReadFs.go
index b026e0de8..29a26c67d 100644
--- a/vendor/github.com/spf13/afero/cacheOnReadFs.go
+++ b/vendor/github.com/spf13/afero/cacheOnReadFs.go
@@ -205,7 +205,7 @@ func (u *CacheOnReadFs) OpenFile(name string, flag int, perm os.FileMode) (File,
bfi.Close() // oops, what if O_TRUNC was set and file opening in the layer failed...?
return nil, err
}
- return &UnionFile{base: bfi, layer: lfi}, nil
+ return &UnionFile{Base: bfi, Layer: lfi}, nil
}
return u.layer.OpenFile(name, flag, perm)
}
@@ -251,7 +251,7 @@ func (u *CacheOnReadFs) Open(name string) (File, error) {
if err != nil && bfile == nil {
return nil, err
}
- return &UnionFile{base: bfile, layer: lfile}, nil
+ return &UnionFile{Base: bfile, Layer: lfile}, nil
}
func (u *CacheOnReadFs) Mkdir(name string, perm os.FileMode) error {
@@ -286,5 +286,5 @@ func (u *CacheOnReadFs) Create(name string) (File, error) {
bfh.Close()
return nil, err
}
- return &UnionFile{base: bfh, layer: lfh}, nil
+ return &UnionFile{Base: bfh, Layer: lfh}, nil
}
diff --git a/vendor/github.com/spf13/afero/composite_test.go b/vendor/github.com/spf13/afero/composite_test.go
deleted file mode 100644
index 8e44611dc..000000000
--- a/vendor/github.com/spf13/afero/composite_test.go
+++ /dev/null
@@ -1,404 +0,0 @@
-package afero
-
-import (
- "bytes"
- "fmt"
- "io/ioutil"
- "os"
- "testing"
- "time"
-)
-
-var tempDirs []string
-
-func NewTempOsBaseFs(t *testing.T) Fs {
- name, err := TempDir(NewOsFs(), "", "")
- if err != nil {
- t.Error("error creating tempDir", err)
- }
-
- tempDirs = append(tempDirs, name)
-
- return NewBasePathFs(NewOsFs(), name)
-}
-
-func CleanupTempDirs(t *testing.T) {
- osfs := NewOsFs()
- type ev struct {
- path string
- e error
- }
-
- errs := []ev{}
-
- for _, x := range tempDirs {
- err := osfs.RemoveAll(x)
- if err != nil {
- errs = append(errs, ev{path: x, e: err})
- }
- }
-
- for _, e := range errs {
- fmt.Println("error removing tempDir", e.path, e.e)
- }
-
- if len(errs) > 0 {
- t.Error("error cleaning up tempDirs")
- }
- tempDirs = []string{}
-}
-
-func TestUnionCreateExisting(t *testing.T) {
- base := &MemMapFs{}
- roBase := &ReadOnlyFs{source: base}
-
- ufs := NewCopyOnWriteFs(roBase, &MemMapFs{})
-
- base.MkdirAll("/home/test", 0777)
- fh, _ := base.Create("/home/test/file.txt")
- fh.WriteString("This is a test")
- fh.Close()
-
- fh, err := ufs.OpenFile("/home/test/file.txt", os.O_RDWR, 0666)
- if err != nil {
- t.Errorf("Failed to open file r/w: %s", err)
- }
-
- _, err = fh.Write([]byte("####"))
- if err != nil {
- t.Errorf("Failed to write file: %s", err)
- }
- fh.Seek(0, 0)
- data, err := ioutil.ReadAll(fh)
- if err != nil {
- t.Errorf("Failed to read file: %s", err)
- }
- if string(data) != "#### is a test" {
- t.Errorf("Got wrong data")
- }
- fh.Close()
-
- fh, _ = base.Open("/home/test/file.txt")
- data, err = ioutil.ReadAll(fh)
- if string(data) != "This is a test" {
- t.Errorf("Got wrong data in base file")
- }
- fh.Close()
-
- fh, err = ufs.Create("/home/test/file.txt")
- switch err {
- case nil:
- if fi, _ := fh.Stat(); fi.Size() != 0 {
- t.Errorf("Create did not truncate file")
- }
- fh.Close()
- default:
- t.Errorf("Create failed on existing file")
- }
-
-}
-
-func TestUnionMergeReaddir(t *testing.T) {
- base := &MemMapFs{}
- roBase := &ReadOnlyFs{source: base}
-
- ufs := &CopyOnWriteFs{base: roBase, layer: &MemMapFs{}}
-
- base.MkdirAll("/home/test", 0777)
- fh, _ := base.Create("/home/test/file.txt")
- fh.WriteString("This is a test")
- fh.Close()
-
- fh, _ = ufs.Create("/home/test/file2.txt")
- fh.WriteString("This is a test")
- fh.Close()
-
- fh, _ = ufs.Open("/home/test")
- files, err := fh.Readdirnames(-1)
- if err != nil {
- t.Errorf("Readdirnames failed")
- }
- if len(files) != 2 {
- t.Errorf("Got wrong number of files: %v", files)
- }
-}
-
-func TestExistingDirectoryCollisionReaddir(t *testing.T) {
- base := &MemMapFs{}
- roBase := &ReadOnlyFs{source: base}
- overlay := &MemMapFs{}
-
- ufs := &CopyOnWriteFs{base: roBase, layer: overlay}
-
- base.MkdirAll("/home/test", 0777)
- fh, _ := base.Create("/home/test/file.txt")
- fh.WriteString("This is a test")
- fh.Close()
-
- overlay.MkdirAll("home/test", 0777)
- fh, _ = overlay.Create("/home/test/file2.txt")
- fh.WriteString("This is a test")
- fh.Close()
-
- fh, _ = ufs.Create("/home/test/file3.txt")
- fh.WriteString("This is a test")
- fh.Close()
-
- fh, _ = ufs.Open("/home/test")
- files, err := fh.Readdirnames(-1)
- if err != nil {
- t.Errorf("Readdirnames failed")
- }
- if len(files) != 3 {
- t.Errorf("Got wrong number of files in union: %v", files)
- }
-
- fh, _ = overlay.Open("/home/test")
- files, err = fh.Readdirnames(-1)
- if err != nil {
- t.Errorf("Readdirnames failed")
- }
- if len(files) != 2 {
- t.Errorf("Got wrong number of files in overlay: %v", files)
- }
-}
-
-func TestNestedDirBaseReaddir(t *testing.T) {
- base := &MemMapFs{}
- roBase := &ReadOnlyFs{source: base}
- overlay := &MemMapFs{}
-
- ufs := &CopyOnWriteFs{base: roBase, layer: overlay}
-
- base.MkdirAll("/home/test/foo/bar", 0777)
- fh, _ := base.Create("/home/test/file.txt")
- fh.WriteString("This is a test")
- fh.Close()
-
- fh, _ = base.Create("/home/test/foo/file2.txt")
- fh.WriteString("This is a test")
- fh.Close()
- fh, _ = base.Create("/home/test/foo/bar/file3.txt")
- fh.WriteString("This is a test")
- fh.Close()
-
- overlay.MkdirAll("/", 0777)
-
- // Opening something only in the base
- fh, _ = ufs.Open("/home/test/foo")
- list, err := fh.Readdir(-1)
- if err != nil {
- t.Errorf("Readdir failed %s", err)
- }
- if len(list) != 2 {
- for _, x := range list {
- fmt.Println(x.Name())
- }
- t.Errorf("Got wrong number of files in union: %v", len(list))
- }
-}
-
-func TestNestedDirOverlayReaddir(t *testing.T) {
- base := &MemMapFs{}
- roBase := &ReadOnlyFs{source: base}
- overlay := &MemMapFs{}
-
- ufs := &CopyOnWriteFs{base: roBase, layer: overlay}
-
- base.MkdirAll("/", 0777)
- overlay.MkdirAll("/home/test/foo/bar", 0777)
- fh, _ := overlay.Create("/home/test/file.txt")
- fh.WriteString("This is a test")
- fh.Close()
- fh, _ = overlay.Create("/home/test/foo/file2.txt")
- fh.WriteString("This is a test")
- fh.Close()
- fh, _ = overlay.Create("/home/test/foo/bar/file3.txt")
- fh.WriteString("This is a test")
- fh.Close()
-
- // Opening nested dir only in the overlay
- fh, _ = ufs.Open("/home/test/foo")
- list, err := fh.Readdir(-1)
- if err != nil {
- t.Errorf("Readdir failed %s", err)
- }
- if len(list) != 2 {
- for _, x := range list {
- fmt.Println(x.Name())
- }
- t.Errorf("Got wrong number of files in union: %v", len(list))
- }
-}
-
-func TestNestedDirOverlayOsFsReaddir(t *testing.T) {
- defer CleanupTempDirs(t)
- base := NewTempOsBaseFs(t)
- roBase := &ReadOnlyFs{source: base}
- overlay := NewTempOsBaseFs(t)
-
- ufs := &CopyOnWriteFs{base: roBase, layer: overlay}
-
- base.MkdirAll("/", 0777)
- overlay.MkdirAll("/home/test/foo/bar", 0777)
- fh, _ := overlay.Create("/home/test/file.txt")
- fh.WriteString("This is a test")
- fh.Close()
- fh, _ = overlay.Create("/home/test/foo/file2.txt")
- fh.WriteString("This is a test")
- fh.Close()
- fh, _ = overlay.Create("/home/test/foo/bar/file3.txt")
- fh.WriteString("This is a test")
- fh.Close()
-
- // Opening nested dir only in the overlay
- fh, _ = ufs.Open("/home/test/foo")
- list, err := fh.Readdir(-1)
- fh.Close()
- if err != nil {
- t.Errorf("Readdir failed %s", err)
- }
- if len(list) != 2 {
- for _, x := range list {
- fmt.Println(x.Name())
- }
- t.Errorf("Got wrong number of files in union: %v", len(list))
- }
-}
-
-func TestCopyOnWriteFsWithOsFs(t *testing.T) {
- defer CleanupTempDirs(t)
- base := NewTempOsBaseFs(t)
- roBase := &ReadOnlyFs{source: base}
- overlay := NewTempOsBaseFs(t)
-
- ufs := &CopyOnWriteFs{base: roBase, layer: overlay}
-
- base.MkdirAll("/home/test", 0777)
- fh, _ := base.Create("/home/test/file.txt")
- fh.WriteString("This is a test")
- fh.Close()
-
- overlay.MkdirAll("home/test", 0777)
- fh, _ = overlay.Create("/home/test/file2.txt")
- fh.WriteString("This is a test")
- fh.Close()
-
- fh, _ = ufs.Create("/home/test/file3.txt")
- fh.WriteString("This is a test")
- fh.Close()
-
- fh, _ = ufs.Open("/home/test")
- files, err := fh.Readdirnames(-1)
- fh.Close()
- if err != nil {
- t.Errorf("Readdirnames failed")
- }
- if len(files) != 3 {
- t.Errorf("Got wrong number of files in union: %v", files)
- }
-
- fh, _ = overlay.Open("/home/test")
- files, err = fh.Readdirnames(-1)
- fh.Close()
- if err != nil {
- t.Errorf("Readdirnames failed")
- }
- if len(files) != 2 {
- t.Errorf("Got wrong number of files in overlay: %v", files)
- }
-}
-
-func TestUnionCacheWrite(t *testing.T) {
- base := &MemMapFs{}
- layer := &MemMapFs{}
-
- ufs := NewCacheOnReadFs(base, layer, 0)
-
- base.Mkdir("/data", 0777)
-
- fh, err := ufs.Create("/data/file.txt")
- if err != nil {
- t.Errorf("Failed to create file")
- }
- _, err = fh.Write([]byte("This is a test"))
- if err != nil {
- t.Errorf("Failed to write file")
- }
-
- fh.Seek(0, os.SEEK_SET)
- buf := make([]byte, 4)
- _, err = fh.Read(buf)
- fh.Write([]byte(" IS A"))
- fh.Close()
-
- baseData, _ := ReadFile(base, "/data/file.txt")
- layerData, _ := ReadFile(layer, "/data/file.txt")
- if string(baseData) != string(layerData) {
- t.Errorf("Different data: %s <=> %s", baseData, layerData)
- }
-}
-
-func TestUnionCacheExpire(t *testing.T) {
- base := &MemMapFs{}
- layer := &MemMapFs{}
- ufs := &CacheOnReadFs{base: base, layer: layer, cacheTime: 1 * time.Second}
-
- base.Mkdir("/data", 0777)
-
- fh, err := ufs.Create("/data/file.txt")
- if err != nil {
- t.Errorf("Failed to create file")
- }
- _, err = fh.Write([]byte("This is a test"))
- if err != nil {
- t.Errorf("Failed to write file")
- }
- fh.Close()
-
- fh, _ = base.Create("/data/file.txt")
- // sleep some time, so we really get a different time.Now() on write...
- time.Sleep(2 * time.Second)
- fh.WriteString("Another test")
- fh.Close()
-
- data, _ := ReadFile(ufs, "/data/file.txt")
- if string(data) != "Another test" {
- t.Errorf("cache time failed: <%s>", data)
- }
-}
-
-func TestCacheOnReadFsNotInLayer(t *testing.T) {
- base := NewMemMapFs()
- layer := NewMemMapFs()
- fs := NewCacheOnReadFs(base, layer, 0)
-
- fh, err := base.Create("/file.txt")
- if err != nil {
- t.Fatal("unable to create file: ", err)
- }
-
- txt := []byte("This is a test")
- fh.Write(txt)
- fh.Close()
-
- fh, err = fs.Open("/file.txt")
- if err != nil {
- t.Fatal("could not open file: ", err)
- }
-
- b, err := ReadAll(fh)
- fh.Close()
-
- if err != nil {
- t.Fatal("could not read file: ", err)
- } else if !bytes.Equal(txt, b) {
- t.Fatalf("wanted file text %q, got %q", txt, b)
- }
-
- fh, err = layer.Open("/file.txt")
- if err != nil {
- t.Fatal("could not open file from layer: ", err)
- }
- fh.Close()
-}
diff --git a/vendor/github.com/spf13/afero/copyOnWriteFs.go b/vendor/github.com/spf13/afero/copyOnWriteFs.go
index f2ebcd226..9aef39794 100644
--- a/vendor/github.com/spf13/afero/copyOnWriteFs.go
+++ b/vendor/github.com/spf13/afero/copyOnWriteFs.go
@@ -8,6 +8,8 @@ import (
"time"
)
+var _ Lstater = (*CopyOnWriteFs)(nil)
+
// The CopyOnWriteFs is a union filesystem: a read only base file system with
// a possibly writeable layer on top. Changes to the file system will only
// be made in the overlay: Changing an existing file in the base layer which
@@ -76,18 +78,55 @@ func (u *CopyOnWriteFs) Chmod(name string, mode os.FileMode) error {
func (u *CopyOnWriteFs) Stat(name string) (os.FileInfo, error) {
fi, err := u.layer.Stat(name)
if err != nil {
- origErr := err
- if e, ok := err.(*os.PathError); ok {
- err = e.Err
- }
- if err == os.ErrNotExist || err == syscall.ENOENT || err == syscall.ENOTDIR {
+ isNotExist := u.isNotExist(err)
+ if isNotExist {
return u.base.Stat(name)
}
- return nil, origErr
+ return nil, err
}
return fi, nil
}
+func (u *CopyOnWriteFs) LstatIfPossible(name string) (os.FileInfo, bool, error) {
+ llayer, ok1 := u.layer.(Lstater)
+ lbase, ok2 := u.base.(Lstater)
+
+ if ok1 {
+ fi, b, err := llayer.LstatIfPossible(name)
+ if err == nil {
+ return fi, b, nil
+ }
+
+ if !u.isNotExist(err) {
+ return nil, b, err
+ }
+ }
+
+ if ok2 {
+ fi, b, err := lbase.LstatIfPossible(name)
+ if err == nil {
+ return fi, b, nil
+ }
+ if !u.isNotExist(err) {
+ return nil, b, err
+ }
+ }
+
+ fi, err := u.Stat(name)
+
+ return fi, false, err
+}
+
+func (u *CopyOnWriteFs) isNotExist(err error) bool {
+ if e, ok := err.(*os.PathError); ok {
+ err = e.Err
+ }
+ if err == os.ErrNotExist || err == syscall.ENOENT || err == syscall.ENOTDIR {
+ return true
+ }
+ return false
+}
+
// Renaming files present only in the base layer is not permitted
func (u *CopyOnWriteFs) Rename(oldname, newname string) error {
b, err := u.isBaseFile(oldname)
@@ -219,7 +258,7 @@ func (u *CopyOnWriteFs) Open(name string) (File, error) {
return nil, fmt.Errorf("BaseErr: %v\nOverlayErr: %v", bErr, lErr)
}
- return &UnionFile{base: bfile, layer: lfile}, nil
+ return &UnionFile{Base: bfile, Layer: lfile}, nil
}
func (u *CopyOnWriteFs) Mkdir(name string, perm os.FileMode) error {
diff --git a/vendor/github.com/spf13/afero/copyOnWriteFs_test.go b/vendor/github.com/spf13/afero/copyOnWriteFs_test.go
deleted file mode 100644
index c6f2c6d62..000000000
--- a/vendor/github.com/spf13/afero/copyOnWriteFs_test.go
+++ /dev/null
@@ -1,39 +0,0 @@
-package afero
-
-import "testing"
-
-func TestCopyOnWrite(t *testing.T) {
- var fs Fs
- var err error
- base := NewOsFs()
- roBase := NewReadOnlyFs(base)
- ufs := NewCopyOnWriteFs(roBase, NewMemMapFs())
- fs = ufs
- err = fs.MkdirAll("nonexistent/directory/", 0744)
- if err != nil {
- t.Error(err)
- return
- }
- _, err = fs.Create("nonexistent/directory/newfile")
- if err != nil {
- t.Error(err)
- return
- }
-
-}
-
-func TestCopyOnWriteFileInMemMapBase(t *testing.T) {
- base := &MemMapFs{}
- layer := &MemMapFs{}
-
- if err := WriteFile(base, "base.txt", []byte("base"), 0755); err != nil {
- t.Fatalf("Failed to write file: %s", err)
- }
-
- ufs := NewCopyOnWriteFs(base, layer)
-
- _, err := ufs.Stat("base.txt")
- if err != nil {
- t.Fatal(err)
- }
-}
diff --git a/vendor/github.com/spf13/afero/ioutil_test.go b/vendor/github.com/spf13/afero/ioutil_test.go
deleted file mode 100644
index e7c9f0698..000000000
--- a/vendor/github.com/spf13/afero/ioutil_test.go
+++ /dev/null
@@ -1,112 +0,0 @@
-// ©2015 The Go Authors
-// Copyright ©2015 Steve Francia <spf@spf13.com>
-//
-// 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 afero
-
-import "testing"
-
-func checkSizePath(t *testing.T, path string, size int64) {
- dir, err := testFS.Stat(path)
- if err != nil {
- t.Fatalf("Stat %q (looking for size %d): %s", path, size, err)
- }
- if dir.Size() != size {
- t.Errorf("Stat %q: size %d want %d", path, dir.Size(), size)
- }
-}
-
-func TestReadFile(t *testing.T) {
- testFS = &MemMapFs{}
- fsutil := &Afero{Fs: testFS}
-
- testFS.Create("this_exists.go")
- filename := "rumpelstilzchen"
- contents, err := fsutil.ReadFile(filename)
- if err == nil {
- t.Fatalf("ReadFile %s: error expected, none found", filename)
- }
-
- filename = "this_exists.go"
- contents, err = fsutil.ReadFile(filename)
- if err != nil {
- t.Fatalf("ReadFile %s: %v", filename, err)
- }
-
- checkSizePath(t, filename, int64(len(contents)))
-}
-
-func TestWriteFile(t *testing.T) {
- testFS = &MemMapFs{}
- fsutil := &Afero{Fs: testFS}
- f, err := fsutil.TempFile("", "ioutil-test")
- if err != nil {
- t.Fatal(err)
- }
- filename := f.Name()
- data := "Programming today is a race between software engineers striving to " +
- "build bigger and better idiot-proof programs, and the Universe trying " +
- "to produce bigger and better idiots. So far, the Universe is winning."
-
- if err := fsutil.WriteFile(filename, []byte(data), 0644); err != nil {
- t.Fatalf("WriteFile %s: %v", filename, err)
- }
-
- contents, err := fsutil.ReadFile(filename)
- if err != nil {
- t.Fatalf("ReadFile %s: %v", filename, err)
- }
-
- if string(contents) != data {
- t.Fatalf("contents = %q\nexpected = %q", string(contents), data)
- }
-
- // cleanup
- f.Close()
- testFS.Remove(filename) // ignore error
-}
-
-func TestReadDir(t *testing.T) {
- testFS = &MemMapFs{}
- testFS.Mkdir("/i-am-a-dir", 0777)
- testFS.Create("/this_exists.go")
- dirname := "rumpelstilzchen"
- _, err := ReadDir(testFS, dirname)
- if err == nil {
- t.Fatalf("ReadDir %s: error expected, none found", dirname)
- }
-
- dirname = ".."
- list, err := ReadDir(testFS, dirname)
- if err != nil {
- t.Fatalf("ReadDir %s: %v", dirname, err)
- }
-
- foundFile := false
- foundSubDir := false
- for _, dir := range list {
- switch {
- case !dir.IsDir() && dir.Name() == "this_exists.go":
- foundFile = true
- case dir.IsDir() && dir.Name() == "i-am-a-dir":
- foundSubDir = true
- }
- }
- if !foundFile {
- t.Fatalf("ReadDir %s: this_exists.go file not found", dirname)
- }
- if !foundSubDir {
- t.Fatalf("ReadDir %s: i-am-a-dir directory not found", dirname)
- }
-}
diff --git a/vendor/github.com/spf13/cobra/cobra/main.go b/vendor/github.com/spf13/afero/lstater.go
index c3a9d9cb0..89c1bfc0a 100644
--- a/vendor/github.com/spf13/cobra/cobra/main.go
+++ b/vendor/github.com/spf13/afero/lstater.go
@@ -1,4 +1,4 @@
-// Copyright © 2015 Steve Francia <spf@spf13.com>.
+// Copyright © 2018 Steve Francia <spf@spf13.com>.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
@@ -11,10 +11,17 @@
// See the License for the specific language governing permissions and
// limitations under the License.
-package main
+package afero
-import "github.com/spf13/cobra/cobra/cmd"
+import (
+ "os"
+)
-func main() {
- cmd.Execute()
+// Lstater is an optional interface in Afero. It is only implemented by the
+// filesystems saying so.
+// It will call Lstat if the filesystem iself is, or it delegates to, the os filesystem.
+// Else it will call Stat.
+// In addtion to the FileInfo, it will return a boolean telling whether Lstat was called or not.
+type Lstater interface {
+ LstatIfPossible(name string) (os.FileInfo, bool, error)
}
diff --git a/vendor/github.com/spf13/afero/match.go b/vendor/github.com/spf13/afero/match.go
index 08b3b7e01..c18a87fb7 100644
--- a/vendor/github.com/spf13/afero/match.go
+++ b/vendor/github.com/spf13/afero/match.go
@@ -33,8 +33,8 @@ import (
// built-ins from that package.
func Glob(fs Fs, pattern string) (matches []string, err error) {
if !hasMeta(pattern) {
- // afero does not support Lstat directly.
- if _, err = lstatIfOs(fs, pattern); err != nil {
+ // Lstat not supported by a ll filesystems.
+ if _, err = lstatIfPossible(fs, pattern); err != nil {
return nil, nil
}
return []string{pattern}, nil
diff --git a/vendor/github.com/spf13/afero/match_test.go b/vendor/github.com/spf13/afero/match_test.go
deleted file mode 100644
index 21e1faecd..000000000
--- a/vendor/github.com/spf13/afero/match_test.go
+++ /dev/null
@@ -1,183 +0,0 @@
-// Copyright © 2014 Steve Francia <spf@spf13.com>.
-// Copyright 2009 The Go Authors. All rights reserved.
-//
-// 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 afero
-
-import (
- "os"
- "path/filepath"
- "runtime"
- "testing"
-)
-
-// contains returns true if vector contains the string s.
-func contains(vector []string, s string) bool {
- for _, elem := range vector {
- if elem == s {
- return true
- }
- }
- return false
-}
-
-func setupGlobDirRoot(t *testing.T, fs Fs) string {
- path := testDir(fs)
- setupGlobFiles(t, fs, path)
- return path
-}
-
-func setupGlobDirReusePath(t *testing.T, fs Fs, path string) string {
- testRegistry[fs] = append(testRegistry[fs], path)
- return setupGlobFiles(t, fs, path)
-}
-
-func setupGlobFiles(t *testing.T, fs Fs, path string) string {
- testSubDir := filepath.Join(path, "globs", "bobs")
- err := fs.MkdirAll(testSubDir, 0700)
- if err != nil && !os.IsExist(err) {
- t.Fatal(err)
- }
-
- f, err := fs.Create(filepath.Join(testSubDir, "/matcher"))
- if err != nil {
- t.Fatal(err)
- }
- f.WriteString("Testfile 1 content")
- f.Close()
-
- f, err = fs.Create(filepath.Join(testSubDir, "/../submatcher"))
- if err != nil {
- t.Fatal(err)
- }
- f.WriteString("Testfile 2 content")
- f.Close()
-
- f, err = fs.Create(filepath.Join(testSubDir, "/../../match"))
- if err != nil {
- t.Fatal(err)
- }
- f.WriteString("Testfile 3 content")
- f.Close()
-
- return testSubDir
-}
-
-func TestGlob(t *testing.T) {
- defer removeAllTestFiles(t)
- var testDir string
- for i, fs := range Fss {
- if i == 0 {
- testDir = setupGlobDirRoot(t, fs)
- } else {
- setupGlobDirReusePath(t, fs, testDir)
- }
- }
-
- var globTests = []struct {
- pattern, result string
- }{
- {testDir + "/globs/bobs/matcher", testDir + "/globs/bobs/matcher"},
- {testDir + "/globs/*/mat?her", testDir + "/globs/bobs/matcher"},
- {testDir + "/globs/bobs/../*", testDir + "/globs/submatcher"},
- {testDir + "/match", testDir + "/match"},
- }
-
- for _, fs := range Fss {
-
- for _, tt := range globTests {
- pattern := tt.pattern
- result := tt.result
- if runtime.GOOS == "windows" {
- pattern = filepath.Clean(pattern)
- result = filepath.Clean(result)
- }
- matches, err := Glob(fs, pattern)
- if err != nil {
- t.Errorf("Glob error for %q: %s", pattern, err)
- continue
- }
- if !contains(matches, result) {
- t.Errorf("Glob(%#q) = %#v want %v", pattern, matches, result)
- }
- }
- for _, pattern := range []string{"no_match", "../*/no_match"} {
- matches, err := Glob(fs, pattern)
- if err != nil {
- t.Errorf("Glob error for %q: %s", pattern, err)
- continue
- }
- if len(matches) != 0 {
- t.Errorf("Glob(%#q) = %#v want []", pattern, matches)
- }
- }
-
- }
-}
-
-func TestGlobSymlink(t *testing.T) {
- defer removeAllTestFiles(t)
-
- fs := &OsFs{}
- testDir := setupGlobDirRoot(t, fs)
-
- err := os.Symlink("target", filepath.Join(testDir, "symlink"))
- if err != nil {
- t.Skipf("skipping on %s", runtime.GOOS)
- }
-
- var globSymlinkTests = []struct {
- path, dest string
- brokenLink bool
- }{
- {"test1", "link1", false},
- {"test2", "link2", true},
- }
-
- for _, tt := range globSymlinkTests {
- path := filepath.Join(testDir, tt.path)
- dest := filepath.Join(testDir, tt.dest)
- f, err := fs.Create(path)
- if err != nil {
- t.Fatal(err)
- }
- if err := f.Close(); err != nil {
- t.Fatal(err)
- }
- err = os.Symlink(path, dest)
- if err != nil {
- t.Fatal(err)
- }
- if tt.brokenLink {
- // Break the symlink.
- fs.Remove(path)
- }
- matches, err := Glob(fs, dest)
- if err != nil {
- t.Errorf("GlobSymlink error for %q: %s", dest, err)
- }
- if !contains(matches, dest) {
- t.Errorf("Glob(%#q) = %#v want %v", dest, matches, dest)
- }
- }
-}
-
-
-func TestGlobError(t *testing.T) {
- for _, fs := range Fss {
- _, err := Glob(fs, "[7]")
- if err != nil {
- t.Error("expected error for bad pattern; got none")
- }
- }
-}
diff --git a/vendor/github.com/spf13/afero/mem/file_test.go b/vendor/github.com/spf13/afero/mem/file_test.go
deleted file mode 100644
index 5769067a7..000000000
--- a/vendor/github.com/spf13/afero/mem/file_test.go
+++ /dev/null
@@ -1,154 +0,0 @@
-package mem
-
-import (
- "testing"
- "time"
-)
-
-func TestFileDataNameRace(t *testing.T) {
- t.Parallel()
- const someName = "someName"
- const someOtherName = "someOtherName"
- d := FileData{
- name: someName,
- }
-
- if d.Name() != someName {
- t.Errorf("Failed to read correct Name, was %v", d.Name())
- }
-
- ChangeFileName(&d, someOtherName)
- if d.Name() != someOtherName {
- t.Errorf("Failed to set Name, was %v", d.Name())
- }
-
- go func() {
- ChangeFileName(&d, someName)
- }()
-
- if d.Name() != someName && d.Name() != someOtherName {
- t.Errorf("Failed to read either Name, was %v", d.Name())
- }
-}
-
-func TestFileDataModTimeRace(t *testing.T) {
- t.Parallel()
- someTime := time.Now()
- someOtherTime := someTime.Add(1 * time.Minute)
-
- d := FileData{
- modtime: someTime,
- }
-
- s := FileInfo{
- FileData: &d,
- }
-
- if s.ModTime() != someTime {
- t.Errorf("Failed to read correct value, was %v", s.ModTime())
- }
-
- SetModTime(&d, someOtherTime)
- if s.ModTime() != someOtherTime {
- t.Errorf("Failed to set ModTime, was %v", s.ModTime())
- }
-
- go func() {
- SetModTime(&d, someTime)
- }()
-
- if s.ModTime() != someTime && s.ModTime() != someOtherTime {
- t.Errorf("Failed to read either modtime, was %v", s.ModTime())
- }
-}
-
-func TestFileDataModeRace(t *testing.T) {
- t.Parallel()
- const someMode = 0777
- const someOtherMode = 0660
-
- d := FileData{
- mode: someMode,
- }
-
- s := FileInfo{
- FileData: &d,
- }
-
- if s.Mode() != someMode {
- t.Errorf("Failed to read correct value, was %v", s.Mode())
- }
-
- SetMode(&d, someOtherMode)
- if s.Mode() != someOtherMode {
- t.Errorf("Failed to set Mode, was %v", s.Mode())
- }
-
- go func() {
- SetMode(&d, someMode)
- }()
-
- if s.Mode() != someMode && s.Mode() != someOtherMode {
- t.Errorf("Failed to read either mode, was %v", s.Mode())
- }
-}
-
-func TestFileDataIsDirRace(t *testing.T) {
- t.Parallel()
-
- d := FileData{
- dir: true,
- }
-
- s := FileInfo{
- FileData: &d,
- }
-
- if s.IsDir() != true {
- t.Errorf("Failed to read correct value, was %v", s.IsDir())
- }
-
- go func() {
- s.Lock()
- d.dir = false
- s.Unlock()
- }()
-
- //just logging the value to trigger a read:
- t.Logf("Value is %v", s.IsDir())
-}
-
-func TestFileDataSizeRace(t *testing.T) {
- t.Parallel()
-
- const someData = "Hello"
- const someOtherDataSize = "Hello World"
-
- d := FileData{
- data: []byte(someData),
- dir: false,
- }
-
- s := FileInfo{
- FileData: &d,
- }
-
- if s.Size() != int64(len(someData)) {
- t.Errorf("Failed to read correct value, was %v", s.Size())
- }
-
- go func() {
- s.Lock()
- d.data = []byte(someOtherDataSize)
- s.Unlock()
- }()
-
- //just logging the value to trigger a read:
- t.Logf("Value is %v", s.Size())
-
- //Testing the Dir size case
- d.dir = true
- if s.Size() != int64(42) {
- t.Errorf("Failed to read correct value for dir, was %v", s.Size())
- }
-}
diff --git a/vendor/github.com/spf13/afero/memmap_test.go b/vendor/github.com/spf13/afero/memmap_test.go
deleted file mode 100644
index 47414ab14..000000000
--- a/vendor/github.com/spf13/afero/memmap_test.go
+++ /dev/null
@@ -1,451 +0,0 @@
-package afero
-
-import (
- "fmt"
- "io"
- "os"
- "path/filepath"
- "runtime"
- "testing"
- "time"
-)
-
-func TestNormalizePath(t *testing.T) {
- type test struct {
- input string
- expected string
- }
-
- data := []test{
- {".", FilePathSeparator},
- {"./", FilePathSeparator},
- {"..", FilePathSeparator},
- {"../", FilePathSeparator},
- {"./..", FilePathSeparator},
- {"./../", FilePathSeparator},
- }
-
- for i, d := range data {
- cpath := normalizePath(d.input)
- if d.expected != cpath {
- t.Errorf("Test %d failed. Expected %q got %q", i, d.expected, cpath)
- }
- }
-}
-
-func TestPathErrors(t *testing.T) {
- path := filepath.Join(".", "some", "path")
- path2 := filepath.Join(".", "different", "path")
- fs := NewMemMapFs()
- perm := os.FileMode(0755)
-
- // relevant functions:
- // func (m *MemMapFs) Chmod(name string, mode os.FileMode) error
- // func (m *MemMapFs) Chtimes(name string, atime time.Time, mtime time.Time) error
- // func (m *MemMapFs) Create(name string) (File, error)
- // func (m *MemMapFs) Mkdir(name string, perm os.FileMode) error
- // func (m *MemMapFs) MkdirAll(path string, perm os.FileMode) error
- // func (m *MemMapFs) Open(name string) (File, error)
- // func (m *MemMapFs) OpenFile(name string, flag int, perm os.FileMode) (File, error)
- // func (m *MemMapFs) Remove(name string) error
- // func (m *MemMapFs) Rename(oldname, newname string) error
- // func (m *MemMapFs) Stat(name string) (os.FileInfo, error)
-
- err := fs.Chmod(path, perm)
- checkPathError(t, err, "Chmod")
-
- err = fs.Chtimes(path, time.Now(), time.Now())
- checkPathError(t, err, "Chtimes")
-
- // fs.Create doesn't return an error
-
- err = fs.Mkdir(path2, perm)
- if err != nil {
- t.Error(err)
- }
- err = fs.Mkdir(path2, perm)
- checkPathError(t, err, "Mkdir")
-
- err = fs.MkdirAll(path2, perm)
- if err != nil {
- t.Error("MkdirAll:", err)
- }
-
- _, err = fs.Open(path)
- checkPathError(t, err, "Open")
-
- _, err = fs.OpenFile(path, os.O_RDWR, perm)
- checkPathError(t, err, "OpenFile")
-
- err = fs.Remove(path)
- checkPathError(t, err, "Remove")
-
- err = fs.RemoveAll(path)
- if err != nil {
- t.Error("RemoveAll:", err)
- }
-
- err = fs.Rename(path, path2)
- checkPathError(t, err, "Rename")
-
- _, err = fs.Stat(path)
- checkPathError(t, err, "Stat")
-}
-
-func checkPathError(t *testing.T, err error, op string) {
- pathErr, ok := err.(*os.PathError)
- if !ok {
- t.Error(op+":", err, "is not a os.PathError")
- return
- }
- _, ok = pathErr.Err.(*os.PathError)
- if ok {
- t.Error(op+":", err, "contains another os.PathError")
- }
-}
-
-// Ensure Permissions are set on OpenFile/Mkdir/MkdirAll
-func TestPermSet(t *testing.T) {
- const fileName = "/myFileTest"
- const dirPath = "/myDirTest"
- const dirPathAll = "/my/path/to/dir"
-
- const fileMode = os.FileMode(0765)
- // directories will also have the directory bit set
- const dirMode = fileMode | os.ModeDir
-
- fs := NewMemMapFs()
-
- // Test Openfile
- f, err := fs.OpenFile(fileName, os.O_CREATE, fileMode)
- if err != nil {
- t.Errorf("OpenFile Create failed: %s", err)
- return
- }
- f.Close()
-
- s, err := fs.Stat(fileName)
- if err != nil {
- t.Errorf("Stat failed: %s", err)
- return
- }
- if s.Mode().String() != fileMode.String() {
- t.Errorf("Permissions Incorrect: %s != %s", s.Mode().String(), fileMode.String())
- return
- }
-
- // Test Mkdir
- err = fs.Mkdir(dirPath, dirMode)
- if err != nil {
- t.Errorf("MkDir Create failed: %s", err)
- return
- }
- s, err = fs.Stat(dirPath)
- if err != nil {
- t.Errorf("Stat failed: %s", err)
- return
- }
- // sets File
- if s.Mode().String() != dirMode.String() {
- t.Errorf("Permissions Incorrect: %s != %s", s.Mode().String(), dirMode.String())
- return
- }
-
- // Test MkdirAll
- err = fs.MkdirAll(dirPathAll, dirMode)
- if err != nil {
- t.Errorf("MkDir Create failed: %s", err)
- return
- }
- s, err = fs.Stat(dirPathAll)
- if err != nil {
- t.Errorf("Stat failed: %s", err)
- return
- }
- if s.Mode().String() != dirMode.String() {
- t.Errorf("Permissions Incorrect: %s != %s", s.Mode().String(), dirMode.String())
- return
- }
-}
-
-// Fails if multiple file objects use the same file.at counter in MemMapFs
-func TestMultipleOpenFiles(t *testing.T) {
- defer removeAllTestFiles(t)
- const fileName = "afero-demo2.txt"
-
- var data = make([][]byte, len(Fss))
-
- for i, fs := range Fss {
- dir := testDir(fs)
- path := filepath.Join(dir, fileName)
- fh1, err := fs.Create(path)
- if err != nil {
- t.Error("fs.Create failed: " + err.Error())
- }
- _, err = fh1.Write([]byte("test"))
- if err != nil {
- t.Error("fh.Write failed: " + err.Error())
- }
- _, err = fh1.Seek(0, os.SEEK_SET)
- if err != nil {
- t.Error(err)
- }
-
- fh2, err := fs.OpenFile(path, os.O_RDWR, 0777)
- if err != nil {
- t.Error("fs.OpenFile failed: " + err.Error())
- }
- _, err = fh2.Seek(0, os.SEEK_END)
- if err != nil {
- t.Error(err)
- }
- _, err = fh2.Write([]byte("data"))
- if err != nil {
- t.Error(err)
- }
- err = fh2.Close()
- if err != nil {
- t.Error(err)
- }
-
- _, err = fh1.Write([]byte("data"))
- if err != nil {
- t.Error(err)
- }
- err = fh1.Close()
- if err != nil {
- t.Error(err)
- }
- // the file now should contain "datadata"
- data[i], err = ReadFile(fs, path)
- if err != nil {
- t.Error(err)
- }
- }
-
- for i, fs := range Fss {
- if i == 0 {
- continue
- }
- if string(data[0]) != string(data[i]) {
- t.Errorf("%s and %s don't behave the same\n"+
- "%s: \"%s\"\n%s: \"%s\"\n",
- Fss[0].Name(), fs.Name(), Fss[0].Name(), data[0], fs.Name(), data[i])
- }
- }
-}
-
-// Test if file.Write() fails when opened as read only
-func TestReadOnly(t *testing.T) {
- defer removeAllTestFiles(t)
- const fileName = "afero-demo.txt"
-
- for _, fs := range Fss {
- dir := testDir(fs)
- path := filepath.Join(dir, fileName)
-
- f, err := fs.Create(path)
- if err != nil {
- t.Error(fs.Name()+":", "fs.Create failed: "+err.Error())
- }
- _, err = f.Write([]byte("test"))
- if err != nil {
- t.Error(fs.Name()+":", "Write failed: "+err.Error())
- }
- f.Close()
-
- f, err = fs.Open(path)
- if err != nil {
- t.Error("fs.Open failed: " + err.Error())
- }
- _, err = f.Write([]byte("data"))
- if err == nil {
- t.Error(fs.Name()+":", "No write error")
- }
- f.Close()
-
- f, err = fs.OpenFile(path, os.O_RDONLY, 0644)
- if err != nil {
- t.Error("fs.Open failed: " + err.Error())
- }
- _, err = f.Write([]byte("data"))
- if err == nil {
- t.Error(fs.Name()+":", "No write error")
- }
- f.Close()
- }
-}
-
-func TestWriteCloseTime(t *testing.T) {
- defer removeAllTestFiles(t)
- const fileName = "afero-demo.txt"
-
- for _, fs := range Fss {
- dir := testDir(fs)
- path := filepath.Join(dir, fileName)
-
- f, err := fs.Create(path)
- if err != nil {
- t.Error(fs.Name()+":", "fs.Create failed: "+err.Error())
- }
- f.Close()
-
- f, err = fs.Create(path)
- if err != nil {
- t.Error(fs.Name()+":", "fs.Create failed: "+err.Error())
- }
- fi, err := f.Stat()
- if err != nil {
- t.Error(fs.Name()+":", "Stat failed: "+err.Error())
- }
- timeBefore := fi.ModTime()
-
- // sorry for the delay, but we have to make sure time advances,
- // also on non Un*x systems...
- switch runtime.GOOS {
- case "windows":
- time.Sleep(2 * time.Second)
- case "darwin":
- time.Sleep(1 * time.Second)
- default: // depending on the FS, this may work with < 1 second, on my old ext3 it does not
- time.Sleep(1 * time.Second)
- }
-
- _, err = f.Write([]byte("test"))
- if err != nil {
- t.Error(fs.Name()+":", "Write failed: "+err.Error())
- }
- f.Close()
- fi, err = fs.Stat(path)
- if err != nil {
- t.Error(fs.Name()+":", "fs.Stat failed: "+err.Error())
- }
- if fi.ModTime().Equal(timeBefore) {
- t.Error(fs.Name()+":", "ModTime was not set on Close()")
- }
- }
-}
-
-// This test should be run with the race detector on:
-// go test -race -v -timeout 10s -run TestRacingDeleteAndClose
-func TestRacingDeleteAndClose(t *testing.T) {
- fs := NewMemMapFs()
- pathname := "testfile"
- f, err := fs.Create(pathname)
- if err != nil {
- t.Fatal(err)
- }
-
- in := make(chan bool)
-
- go func() {
- <-in
- f.Close()
- }()
- go func() {
- <-in
- fs.Remove(pathname)
- }()
- close(in)
-}
-
-// This test should be run with the race detector on:
-// go test -run TestMemFsDataRace -race
-func TestMemFsDataRace(t *testing.T) {
- const dir = "test_dir"
- fs := NewMemMapFs()
-
- if err := fs.MkdirAll(dir, 0777); err != nil {
- t.Fatal(err)
- }
-
- const n = 1000
- done := make(chan struct{})
-
- go func() {
- defer close(done)
- for i := 0; i < n; i++ {
- fname := filepath.Join(dir, fmt.Sprintf("%d.txt", i))
- if err := WriteFile(fs, fname, []byte(""), 0777); err != nil {
- panic(err)
- }
- if err := fs.Remove(fname); err != nil {
- panic(err)
- }
- }
- }()
-
-loop:
- for {
- select {
- case <-done:
- break loop
- default:
- _, err := ReadDir(fs, dir)
- if err != nil {
- t.Fatal(err)
- }
- }
- }
-}
-
-func TestMemFsDirMode(t *testing.T) {
- fs := NewMemMapFs()
- err := fs.Mkdir("/testDir1", 0644)
- if err != nil {
- t.Error(err)
- }
- err = fs.MkdirAll("/sub/testDir2", 0644)
- if err != nil {
- t.Error(err)
- }
- info, err := fs.Stat("/testDir1")
- if err != nil {
- t.Error(err)
- }
- if !info.IsDir() {
- t.Error("should be a directory")
- }
- if !info.Mode().IsDir() {
- t.Error("FileMode is not directory")
- }
- info, err = fs.Stat("/sub/testDir2")
- if err != nil {
- t.Error(err)
- }
- if !info.IsDir() {
- t.Error("should be a directory")
- }
- if !info.Mode().IsDir() {
- t.Error("FileMode is not directory")
- }
-}
-
-func TestMemFsUnexpectedEOF(t *testing.T) {
- t.Parallel()
-
- fs := NewMemMapFs()
-
- if err := WriteFile(fs, "file.txt", []byte("abc"), 0777); err != nil {
- t.Fatal(err)
- }
-
- f, err := fs.Open("file.txt")
- if err != nil {
- t.Fatal(err)
- }
- defer f.Close()
-
- // Seek beyond the end.
- _, err = f.Seek(512, 0)
- if err != nil {
- t.Fatal(err)
- }
-
- buff := make([]byte, 256)
- _, err = io.ReadAtLeast(f, buff, 256)
-
- if err != io.ErrUnexpectedEOF {
- t.Fatal("Expected ErrUnexpectedEOF")
- }
-}
diff --git a/vendor/github.com/spf13/afero/os.go b/vendor/github.com/spf13/afero/os.go
index 6b8bce1c5..13cc1b84c 100644
--- a/vendor/github.com/spf13/afero/os.go
+++ b/vendor/github.com/spf13/afero/os.go
@@ -19,6 +19,8 @@ import (
"time"
)
+var _ Lstater = (*OsFs)(nil)
+
// OsFs is a Fs implementation that uses functions provided by the os package.
//
// For details in any method, check the documentation of the os package
@@ -92,3 +94,8 @@ func (OsFs) Chmod(name string, mode os.FileMode) error {
func (OsFs) Chtimes(name string, atime time.Time, mtime time.Time) error {
return os.Chtimes(name, atime, mtime)
}
+
+func (OsFs) LstatIfPossible(name string) (os.FileInfo, bool, error) {
+ fi, err := os.Lstat(name)
+ return fi, true, err
+}
diff --git a/vendor/github.com/spf13/afero/path.go b/vendor/github.com/spf13/afero/path.go
index 1d90e46dd..18f60a0f6 100644
--- a/vendor/github.com/spf13/afero/path.go
+++ b/vendor/github.com/spf13/afero/path.go
@@ -60,7 +60,7 @@ func walk(fs Fs, path string, info os.FileInfo, walkFn filepath.WalkFunc) error
for _, name := range names {
filename := filepath.Join(path, name)
- fileInfo, err := lstatIfOs(fs, filename)
+ fileInfo, err := lstatIfPossible(fs, filename)
if err != nil {
if err := walkFn(filename, fileInfo, err); err != nil && err != filepath.SkipDir {
return err
@@ -77,15 +77,13 @@ func walk(fs Fs, path string, info os.FileInfo, walkFn filepath.WalkFunc) error
return nil
}
-// if the filesystem is OsFs use Lstat, else use fs.Stat
-func lstatIfOs(fs Fs, path string) (info os.FileInfo, err error) {
- _, ok := fs.(*OsFs)
- if ok {
- info, err = os.Lstat(path)
- } else {
- info, err = fs.Stat(path)
+// if the filesystem supports it, use Lstat, else use fs.Stat
+func lstatIfPossible(fs Fs, path string) (os.FileInfo, error) {
+ if lfs, ok := fs.(Lstater); ok {
+ fi, _, err := lfs.LstatIfPossible(path)
+ return fi, err
}
- return
+ return fs.Stat(path)
}
// Walk walks the file tree rooted at root, calling walkFn for each file or
@@ -100,7 +98,7 @@ func (a Afero) Walk(root string, walkFn filepath.WalkFunc) error {
}
func Walk(fs Fs, root string, walkFn filepath.WalkFunc) error {
- info, err := lstatIfOs(fs, root)
+ info, err := lstatIfPossible(fs, root)
if err != nil {
return walkFn(root, nil, err)
}
diff --git a/vendor/github.com/spf13/afero/path_test.go b/vendor/github.com/spf13/afero/path_test.go
deleted file mode 100644
index 104a6bcbe..000000000
--- a/vendor/github.com/spf13/afero/path_test.go
+++ /dev/null
@@ -1,69 +0,0 @@
-// Copyright © 2014 Steve Francia <spf@spf13.com>.
-// Copyright 2009 The Go Authors. All rights reserved.
-//
-// 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 afero
-
-import (
- "fmt"
- "os"
- "testing"
-)
-
-func TestWalk(t *testing.T) {
- defer removeAllTestFiles(t)
- var testDir string
- for i, fs := range Fss {
- if i == 0 {
- testDir = setupTestDirRoot(t, fs)
- } else {
- setupTestDirReusePath(t, fs, testDir)
- }
- }
-
- outputs := make([]string, len(Fss))
- for i, fs := range Fss {
- walkFn := func(path string, info os.FileInfo, err error) error {
- if err != nil {
- t.Error("walkFn err:", err)
- }
- var size int64
- if !info.IsDir() {
- size = info.Size()
- }
- outputs[i] += fmt.Sprintln(path, info.Name(), size, info.IsDir(), err)
- return nil
- }
- err := Walk(fs, testDir, walkFn)
- if err != nil {
- t.Error(err)
- }
- }
- fail := false
- for i, o := range outputs {
- if i == 0 {
- continue
- }
- if o != outputs[i-1] {
- fail = true
- break
- }
- }
- if fail {
- t.Log("Walk outputs not equal!")
- for i, o := range outputs {
- t.Log(Fss[i].Name() + "\n" + o)
- }
- t.Fail()
- }
-}
diff --git a/vendor/github.com/spf13/afero/readonlyfs.go b/vendor/github.com/spf13/afero/readonlyfs.go
index f1fa55bcf..c6376ec37 100644
--- a/vendor/github.com/spf13/afero/readonlyfs.go
+++ b/vendor/github.com/spf13/afero/readonlyfs.go
@@ -6,6 +6,8 @@ import (
"time"
)
+var _ Lstater = (*ReadOnlyFs)(nil)
+
type ReadOnlyFs struct {
source Fs
}
@@ -34,6 +36,14 @@ func (r *ReadOnlyFs) Stat(name string) (os.FileInfo, error) {
return r.source.Stat(name)
}
+func (r *ReadOnlyFs) LstatIfPossible(name string) (os.FileInfo, bool, error) {
+ if lsf, ok := r.source.(Lstater); ok {
+ return lsf.LstatIfPossible(name)
+ }
+ fi, err := r.Stat(name)
+ return fi, false, err
+}
+
func (r *ReadOnlyFs) Rename(o, n string) error {
return syscall.EPERM
}
diff --git a/vendor/github.com/spf13/afero/ro_regexp_test.go b/vendor/github.com/spf13/afero/ro_regexp_test.go
deleted file mode 100644
index ef8a35d0d..000000000
--- a/vendor/github.com/spf13/afero/ro_regexp_test.go
+++ /dev/null
@@ -1,96 +0,0 @@
-package afero
-
-import (
- "regexp"
- "testing"
-)
-
-func TestFilterReadOnly(t *testing.T) {
- fs := &ReadOnlyFs{source: &MemMapFs{}}
- _, err := fs.Create("/file.txt")
- if err == nil {
- t.Errorf("Did not fail to create file")
- }
- // t.Logf("ERR=%s", err)
-}
-
-func TestFilterReadonlyRemoveAndRead(t *testing.T) {
- mfs := &MemMapFs{}
- fh, err := mfs.Create("/file.txt")
- fh.Write([]byte("content here"))
- fh.Close()
-
- fs := NewReadOnlyFs(mfs)
- err = fs.Remove("/file.txt")
- if err == nil {
- t.Errorf("Did not fail to remove file")
- }
-
- fh, err = fs.Open("/file.txt")
- if err != nil {
- t.Errorf("Failed to open file: %s", err)
- }
-
- buf := make([]byte, len("content here"))
- _, err = fh.Read(buf)
- fh.Close()
- if string(buf) != "content here" {
- t.Errorf("Failed to read file: %s", err)
- }
-
- err = mfs.Remove("/file.txt")
- if err != nil {
- t.Errorf("Failed to remove file")
- }
-
- fh, err = fs.Open("/file.txt")
- if err == nil {
- fh.Close()
- t.Errorf("File still present")
- }
-}
-
-func TestFilterRegexp(t *testing.T) {
- fs := NewRegexpFs(&MemMapFs{}, regexp.MustCompile(`\.txt$`))
- _, err := fs.Create("/file.html")
- if err == nil {
-
- t.Errorf("Did not fail to create file")
- }
- // t.Logf("ERR=%s", err)
-}
-
-func TestFilterRORegexpChain(t *testing.T) {
- rofs := &ReadOnlyFs{source: &MemMapFs{}}
- fs := &RegexpFs{re: regexp.MustCompile(`\.txt$`), source: rofs}
- _, err := fs.Create("/file.txt")
- if err == nil {
- t.Errorf("Did not fail to create file")
- }
- // t.Logf("ERR=%s", err)
-}
-
-func TestFilterRegexReadDir(t *testing.T) {
- mfs := &MemMapFs{}
- fs1 := &RegexpFs{re: regexp.MustCompile(`\.txt$`), source: mfs}
- fs := &RegexpFs{re: regexp.MustCompile(`^a`), source: fs1}
-
- mfs.MkdirAll("/dir/sub", 0777)
- for _, name := range []string{"afile.txt", "afile.html", "bfile.txt"} {
- for _, dir := range []string{"/dir/", "/dir/sub/"} {
- fh, _ := mfs.Create(dir + name)
- fh.Close()
- }
- }
-
- files, _ := ReadDir(fs, "/dir")
- if len(files) != 2 { // afile.txt, sub
- t.Errorf("Got wrong number of files: %#v", files)
- }
-
- f, _ := fs.Open("/dir/sub")
- names, _ := f.Readdirnames(-1)
- if len(names) != 1 {
- t.Errorf("Got wrong number of names: %v", names)
- }
-}
diff --git a/vendor/github.com/spf13/afero/sftpfs/file.go b/vendor/github.com/spf13/afero/sftpfs/file.go
deleted file mode 100644
index e4ccb55c0..000000000
--- a/vendor/github.com/spf13/afero/sftpfs/file.go
+++ /dev/null
@@ -1,95 +0,0 @@
-// Copyright © 2015 Jerry Jacobs <jerry.jacobs@xor-gate.org>.
-//
-// 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 sftpfs
-
-import (
- "github.com/pkg/sftp"
- "os"
-)
-
-type File struct {
- fd *sftp.File
-}
-
-func FileOpen(s *sftp.Client, name string) (*File, error) {
- fd, err := s.Open(name)
- if err != nil {
- return &File{}, err
- }
- return &File{fd: fd}, nil
-}
-
-func FileCreate(s *sftp.Client, name string) (*File, error) {
- fd, err := s.Create(name)
- if err != nil {
- return &File{}, err
- }
- return &File{fd: fd}, nil
-}
-
-func (f *File) Close() error {
- return f.fd.Close()
-}
-
-func (f *File) Name() string {
- return f.fd.Name()
-}
-
-func (f *File) Stat() (os.FileInfo, error) {
- return f.fd.Stat()
-}
-
-func (f *File) Sync() error {
- return nil
-}
-
-func (f *File) Truncate(size int64) error {
- return f.fd.Truncate(size)
-}
-
-func (f *File) Read(b []byte) (n int, err error) {
- return f.fd.Read(b)
-}
-
-// TODO
-func (f *File) ReadAt(b []byte, off int64) (n int, err error) {
- return 0, nil
-}
-
-// TODO
-func (f *File) Readdir(count int) (res []os.FileInfo, err error) {
- return nil, nil
-}
-
-// TODO
-func (f *File) Readdirnames(n int) (names []string, err error) {
- return nil, nil
-}
-
-func (f *File) Seek(offset int64, whence int) (int64, error) {
- return f.fd.Seek(offset, whence)
-}
-
-func (f *File) Write(b []byte) (n int, err error) {
- return f.fd.Write(b)
-}
-
-// TODO
-func (f *File) WriteAt(b []byte, off int64) (n int, err error) {
- return 0, nil
-}
-
-func (f *File) WriteString(s string) (ret int, err error) {
- return f.fd.Write([]byte(s))
-}
diff --git a/vendor/github.com/spf13/afero/sftpfs/sftp.go b/vendor/github.com/spf13/afero/sftpfs/sftp.go
deleted file mode 100644
index 28721da76..000000000
--- a/vendor/github.com/spf13/afero/sftpfs/sftp.go
+++ /dev/null
@@ -1,129 +0,0 @@
-// Copyright © 2015 Jerry Jacobs <jerry.jacobs@xor-gate.org>.
-//
-// 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 sftpfs
-
-import (
- "os"
- "time"
-
- "github.com/pkg/sftp"
- "github.com/spf13/afero"
-)
-
-// Fs is a afero.Fs implementation that uses functions provided by the sftp package.
-//
-// For details in any method, check the documentation of the sftp package
-// (github.com/pkg/sftp).
-type Fs struct {
- client *sftp.Client
-}
-
-func New(client *sftp.Client) afero.Fs {
- return &Fs{client: client}
-}
-
-func (s Fs) Name() string { return "sftpfs" }
-
-func (s Fs) Create(name string) (afero.File, error) {
- return FileCreate(s.client, name)
-}
-
-func (s Fs) Mkdir(name string, perm os.FileMode) error {
- err := s.client.Mkdir(name)
- if err != nil {
- return err
- }
- return s.client.Chmod(name, perm)
-}
-
-func (s Fs) MkdirAll(path string, perm os.FileMode) error {
- // Fast path: if we can tell whether path is a directory or file, stop with success or error.
- dir, err := s.Stat(path)
- if err == nil {
- if dir.IsDir() {
- return nil
- }
- return err
- }
-
- // Slow path: make sure parent exists and then call Mkdir for path.
- i := len(path)
- for i > 0 && os.IsPathSeparator(path[i-1]) { // Skip trailing path separator.
- i--
- }
-
- j := i
- for j > 0 && !os.IsPathSeparator(path[j-1]) { // Scan backward over element.
- j--
- }
-
- if j > 1 {
- // Create parent
- err = s.MkdirAll(path[0:j-1], perm)
- if err != nil {
- return err
- }
- }
-
- // Parent now exists; invoke Mkdir and use its result.
- err = s.Mkdir(path, perm)
- if err != nil {
- // Handle arguments like "foo/." by
- // double-checking that directory doesn't exist.
- dir, err1 := s.Lstat(path)
- if err1 == nil && dir.IsDir() {
- return nil
- }
- return err
- }
- return nil
-}
-
-func (s Fs) Open(name string) (afero.File, error) {
- return FileOpen(s.client, name)
-}
-
-func (s Fs) OpenFile(name string, flag int, perm os.FileMode) (afero.File, error) {
- return nil, nil
-}
-
-func (s Fs) Remove(name string) error {
- return s.client.Remove(name)
-}
-
-func (s Fs) RemoveAll(path string) error {
- // TODO have a look at os.RemoveAll
- // https://github.com/golang/go/blob/master/src/os/path.go#L66
- return nil
-}
-
-func (s Fs) Rename(oldname, newname string) error {
- return s.client.Rename(oldname, newname)
-}
-
-func (s Fs) Stat(name string) (os.FileInfo, error) {
- return s.client.Stat(name)
-}
-
-func (s Fs) Lstat(p string) (os.FileInfo, error) {
- return s.client.Lstat(p)
-}
-
-func (s Fs) Chmod(name string, mode os.FileMode) error {
- return s.client.Chmod(name, mode)
-}
-
-func (s Fs) Chtimes(name string, atime time.Time, mtime time.Time) error {
- return s.client.Chtimes(name, atime, mtime)
-}
diff --git a/vendor/github.com/spf13/afero/sftpfs/sftp_test_go b/vendor/github.com/spf13/afero/sftpfs/sftp_test_go
deleted file mode 100644
index bb00535d8..000000000
--- a/vendor/github.com/spf13/afero/sftpfs/sftp_test_go
+++ /dev/null
@@ -1,286 +0,0 @@
-// Copyright © 2015 Jerry Jacobs <jerry.jacobs@xor-gate.org>.
-//
-// 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 afero
-
-import (
- "testing"
- "os"
- "log"
- "fmt"
- "net"
- "flag"
- "time"
- "io/ioutil"
- "crypto/rsa"
- _rand "crypto/rand"
- "encoding/pem"
- "crypto/x509"
-
- "golang.org/x/crypto/ssh"
- "github.com/pkg/sftp"
-)
-
-type SftpFsContext struct {
- sshc *ssh.Client
- sshcfg *ssh.ClientConfig
- sftpc *sftp.Client
-}
-
-// TODO we only connect with hardcoded user+pass for now
-// it should be possible to use $HOME/.ssh/id_rsa to login into the stub sftp server
-func SftpConnect(user, password, host string) (*SftpFsContext, error) {
-/*
- pemBytes, err := ioutil.ReadFile(os.Getenv("HOME") + "/.ssh/id_rsa")
- if err != nil {
- return nil,err
- }
-
- signer, err := ssh.ParsePrivateKey(pemBytes)
- if err != nil {
- return nil,err
- }
-
- sshcfg := &ssh.ClientConfig{
- User: user,
- Auth: []ssh.AuthMethod{
- ssh.Password(password),
- ssh.PublicKeys(signer),
- },
- }
-*/
-
- sshcfg := &ssh.ClientConfig{
- User: user,
- Auth: []ssh.AuthMethod{
- ssh.Password(password),
- },
- }
-
- sshc, err := ssh.Dial("tcp", host, sshcfg)
- if err != nil {
- return nil,err
- }
-
- sftpc, err := sftp.NewClient(sshc)
- if err != nil {
- return nil,err
- }
-
- ctx := &SftpFsContext{
- sshc: sshc,
- sshcfg: sshcfg,
- sftpc: sftpc,
- }
-
- return ctx,nil
-}
-
-func (ctx *SftpFsContext) Disconnect() error {
- ctx.sftpc.Close()
- ctx.sshc.Close()
- return nil
-}
-
-// TODO for such a weird reason rootpath is "." when writing "file1" with afero sftp backend
-func RunSftpServer(rootpath string) {
- var (
- readOnly bool
- debugLevelStr string
- debugLevel int
- debugStderr bool
- rootDir string
- )
-
- flag.BoolVar(&readOnly, "R", false, "read-only server")
- flag.BoolVar(&debugStderr, "e", true, "debug to stderr")
- flag.StringVar(&debugLevelStr, "l", "none", "debug level")
- flag.StringVar(&rootDir, "root", rootpath, "root directory")
- flag.Parse()
-
- debugStream := ioutil.Discard
- if debugStderr {
- debugStream = os.Stderr
- debugLevel = 1
- }
-
- // An SSH server is represented by a ServerConfig, which holds
- // certificate details and handles authentication of ServerConns.
- config := &ssh.ServerConfig{
- PasswordCallback: func(c ssh.ConnMetadata, pass []byte) (*ssh.Permissions, error) {
- // Should use constant-time compare (or better, salt+hash) in
- // a production setting.
- fmt.Fprintf(debugStream, "Login: %s\n", c.User())
- if c.User() == "test" && string(pass) == "test" {
- return nil, nil
- }
- return nil, fmt.Errorf("password rejected for %q", c.User())
- },
- }
-
- privateBytes, err := ioutil.ReadFile("./test/id_rsa")
- if err != nil {
- log.Fatal("Failed to load private key", err)
- }
-
- private, err := ssh.ParsePrivateKey(privateBytes)
- if err != nil {
- log.Fatal("Failed to parse private key", err)
- }
-
- config.AddHostKey(private)
-
- // Once a ServerConfig has been configured, connections can be
- // accepted.
- listener, err := net.Listen("tcp", "0.0.0.0:2022")
- if err != nil {
- log.Fatal("failed to listen for connection", err)
- }
- fmt.Printf("Listening on %v\n", listener.Addr())
-
- nConn, err := listener.Accept()
- if err != nil {
- log.Fatal("failed to accept incoming connection", err)
- }
-
- // Before use, a handshake must be performed on the incoming
- // net.Conn.
- _, chans, reqs, err := ssh.NewServerConn(nConn, config)
- if err != nil {
- log.Fatal("failed to handshake", err)
- }
- fmt.Fprintf(debugStream, "SSH server established\n")
-
- // The incoming Request channel must be serviced.
- go ssh.DiscardRequests(reqs)
-
- // Service the incoming Channel channel.
- for newChannel := range chans {
- // Channels have a type, depending on the application level
- // protocol intended. In the case of an SFTP session, this is "subsystem"
- // with a payload string of "<length=4>sftp"
- fmt.Fprintf(debugStream, "Incoming channel: %s\n", newChannel.ChannelType())
- if newChannel.ChannelType() != "session" {
- newChannel.Reject(ssh.UnknownChannelType, "unknown channel type")
- fmt.Fprintf(debugStream, "Unknown channel type: %s\n", newChannel.ChannelType())
- continue
- }
- channel, requests, err := newChannel.Accept()
- if err != nil {
- log.Fatal("could not accept channel.", err)
- }
- fmt.Fprintf(debugStream, "Channel accepted\n")
-
- // Sessions have out-of-band requests such as "shell",
- // "pty-req" and "env". Here we handle only the
- // "subsystem" request.
- go func(in <-chan *ssh.Request) {
- for req := range in {
- fmt.Fprintf(debugStream, "Request: %v\n", req.Type)
- ok := false
- switch req.Type {
- case "subsystem":
- fmt.Fprintf(debugStream, "Subsystem: %s\n", req.Payload[4:])
- if string(req.Payload[4:]) == "sftp" {
- ok = true
- }
- }
- fmt.Fprintf(debugStream, " - accepted: %v\n", ok)
- req.Reply(ok, nil)
- }
- }(requests)
-
- server, err := sftp.NewServer(channel, channel, debugStream, debugLevel, readOnly, rootpath)
- if err != nil {
- log.Fatal(err)
- }
- if err := server.Serve(); err != nil {
- log.Fatal("sftp server completed with error:", err)
- }
- }
-}
-
-// MakeSSHKeyPair make a pair of public and private keys for SSH access.
-// Public key is encoded in the format for inclusion in an OpenSSH authorized_keys file.
-// Private Key generated is PEM encoded
-func MakeSSHKeyPair(bits int, pubKeyPath, privateKeyPath string) error {
- privateKey, err := rsa.GenerateKey(_rand.Reader, bits)
- if err != nil {
- return err
- }
-
- // generate and write private key as PEM
- privateKeyFile, err := os.Create(privateKeyPath)
- defer privateKeyFile.Close()
- if err != nil {
- return err
- }
-
- privateKeyPEM := &pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(privateKey)}
- if err := pem.Encode(privateKeyFile, privateKeyPEM); err != nil {
- return err
- }
-
- // generate and write public key
- pub, err := ssh.NewPublicKey(&privateKey.PublicKey)
- if err != nil {
- return err
- }
-
- return ioutil.WriteFile(pubKeyPath, ssh.MarshalAuthorizedKey(pub), 0655)
-}
-
-func TestSftpCreate(t *testing.T) {
- os.Mkdir("./test", 0777)
- MakeSSHKeyPair(1024, "./test/id_rsa.pub", "./test/id_rsa")
-
- go RunSftpServer("./test/")
- time.Sleep(5 * time.Second)
-
- ctx, err := SftpConnect("test", "test", "localhost:2022")
- if err != nil {
- t.Fatal(err)
- }
- defer ctx.Disconnect()
-
- var AppFs Fs = SftpFs{
- SftpClient: ctx.sftpc,
- }
-
- AppFs.MkdirAll("test/dir1/dir2/dir3", os.FileMode(0777))
- AppFs.Mkdir("test/foo", os.FileMode(0000))
- AppFs.Chmod("test/foo", os.FileMode(0700))
- AppFs.Mkdir("test/bar", os.FileMode(0777))
-
- file, err := AppFs.Create("file1")
- if err != nil {
- t.Error(err)
- }
- defer file.Close()
-
- file.Write([]byte("hello\t"))
- file.WriteString("world!\n")
-
- f1, err := AppFs.Open("file1")
- if err != nil {
- log.Fatalf("open: %v", err)
- }
- defer f1.Close()
-
- b := make([]byte, 100)
-
- _, err = f1.Read(b)
- fmt.Println(string(b))
-
- // TODO check here if "hello\tworld\n" is in buffer b
-}
diff --git a/vendor/github.com/spf13/afero/unionFile.go b/vendor/github.com/spf13/afero/unionFile.go
index 99f9e5db2..1e78f7d1e 100644
--- a/vendor/github.com/spf13/afero/unionFile.go
+++ b/vendor/github.com/spf13/afero/unionFile.go
@@ -21,32 +21,33 @@ import (
// successful read in the overlay will move the cursor position in the base layer
// by the number of bytes read.
type UnionFile struct {
- base File
- layer File
- off int
- files []os.FileInfo
+ Base File
+ Layer File
+ Merger DirsMerger
+ off int
+ files []os.FileInfo
}
func (f *UnionFile) Close() error {
// first close base, so we have a newer timestamp in the overlay. If we'd close
// the overlay first, we'd get a cacheStale the next time we access this file
// -> cache would be useless ;-)
- if f.base != nil {
- f.base.Close()
+ if f.Base != nil {
+ f.Base.Close()
}
- if f.layer != nil {
- return f.layer.Close()
+ if f.Layer != nil {
+ return f.Layer.Close()
}
return BADFD
}
func (f *UnionFile) Read(s []byte) (int, error) {
- if f.layer != nil {
- n, err := f.layer.Read(s)
- if (err == nil || err == io.EOF) && f.base != nil {
+ if f.Layer != nil {
+ n, err := f.Layer.Read(s)
+ if (err == nil || err == io.EOF) && f.Base != nil {
// advance the file position also in the base file, the next
// call may be a write at this position (or a seek with SEEK_CUR)
- if _, seekErr := f.base.Seek(int64(n), os.SEEK_CUR); seekErr != nil {
+ if _, seekErr := f.Base.Seek(int64(n), os.SEEK_CUR); seekErr != nil {
// only overwrite err in case the seek fails: we need to
// report an eventual io.EOF to the caller
err = seekErr
@@ -54,105 +55,135 @@ func (f *UnionFile) Read(s []byte) (int, error) {
}
return n, err
}
- if f.base != nil {
- return f.base.Read(s)
+ if f.Base != nil {
+ return f.Base.Read(s)
}
return 0, BADFD
}
func (f *UnionFile) ReadAt(s []byte, o int64) (int, error) {
- if f.layer != nil {
- n, err := f.layer.ReadAt(s, o)
- if (err == nil || err == io.EOF) && f.base != nil {
- _, err = f.base.Seek(o+int64(n), os.SEEK_SET)
+ if f.Layer != nil {
+ n, err := f.Layer.ReadAt(s, o)
+ if (err == nil || err == io.EOF) && f.Base != nil {
+ _, err = f.Base.Seek(o+int64(n), os.SEEK_SET)
}
return n, err
}
- if f.base != nil {
- return f.base.ReadAt(s, o)
+ if f.Base != nil {
+ return f.Base.ReadAt(s, o)
}
return 0, BADFD
}
func (f *UnionFile) Seek(o int64, w int) (pos int64, err error) {
- if f.layer != nil {
- pos, err = f.layer.Seek(o, w)
- if (err == nil || err == io.EOF) && f.base != nil {
- _, err = f.base.Seek(o, w)
+ if f.Layer != nil {
+ pos, err = f.Layer.Seek(o, w)
+ if (err == nil || err == io.EOF) && f.Base != nil {
+ _, err = f.Base.Seek(o, w)
}
return pos, err
}
- if f.base != nil {
- return f.base.Seek(o, w)
+ if f.Base != nil {
+ return f.Base.Seek(o, w)
}
return 0, BADFD
}
func (f *UnionFile) Write(s []byte) (n int, err error) {
- if f.layer != nil {
- n, err = f.layer.Write(s)
- if err == nil && f.base != nil { // hmm, do we have fixed size files where a write may hit the EOF mark?
- _, err = f.base.Write(s)
+ if f.Layer != nil {
+ n, err = f.Layer.Write(s)
+ if err == nil && f.Base != nil { // hmm, do we have fixed size files where a write may hit the EOF mark?
+ _, err = f.Base.Write(s)
}
return n, err
}
- if f.base != nil {
- return f.base.Write(s)
+ if f.Base != nil {
+ return f.Base.Write(s)
}
return 0, BADFD
}
func (f *UnionFile) WriteAt(s []byte, o int64) (n int, err error) {
- if f.layer != nil {
- n, err = f.layer.WriteAt(s, o)
- if err == nil && f.base != nil {
- _, err = f.base.WriteAt(s, o)
+ if f.Layer != nil {
+ n, err = f.Layer.WriteAt(s, o)
+ if err == nil && f.Base != nil {
+ _, err = f.Base.WriteAt(s, o)
}
return n, err
}
- if f.base != nil {
- return f.base.WriteAt(s, o)
+ if f.Base != nil {
+ return f.Base.WriteAt(s, o)
}
return 0, BADFD
}
func (f *UnionFile) Name() string {
- if f.layer != nil {
- return f.layer.Name()
+ if f.Layer != nil {
+ return f.Layer.Name()
}
- return f.base.Name()
+ return f.Base.Name()
+}
+
+// DirsMerger is how UnionFile weaves two directories together.
+// It takes the FileInfo slices from the layer and the base and returns a
+// single view.
+type DirsMerger func(lofi, bofi []os.FileInfo) ([]os.FileInfo, error)
+
+var defaultUnionMergeDirsFn = func(lofi, bofi []os.FileInfo) ([]os.FileInfo, error) {
+ var files = make(map[string]os.FileInfo)
+
+ for _, fi := range lofi {
+ files[fi.Name()] = fi
+ }
+
+ for _, fi := range bofi {
+ if _, exists := files[fi.Name()]; !exists {
+ files[fi.Name()] = fi
+ }
+ }
+
+ rfi := make([]os.FileInfo, len(files))
+
+ i := 0
+ for _, fi := range files {
+ rfi[i] = fi
+ i++
+ }
+
+ return rfi, nil
+
}
// Readdir will weave the two directories together and
// return a single view of the overlayed directories
func (f *UnionFile) Readdir(c int) (ofi []os.FileInfo, err error) {
+ var merge DirsMerger = f.Merger
+ if merge == nil {
+ merge = defaultUnionMergeDirsFn
+ }
+
if f.off == 0 {
- var files = make(map[string]os.FileInfo)
- var rfi []os.FileInfo
- if f.layer != nil {
- rfi, err = f.layer.Readdir(-1)
+ var lfi []os.FileInfo
+ if f.Layer != nil {
+ lfi, err = f.Layer.Readdir(-1)
if err != nil {
return nil, err
}
- for _, fi := range rfi {
- files[fi.Name()] = fi
- }
}
- if f.base != nil {
- rfi, err = f.base.Readdir(-1)
+ var bfi []os.FileInfo
+ if f.Base != nil {
+ bfi, err = f.Base.Readdir(-1)
if err != nil {
return nil, err
}
- for _, fi := range rfi {
- if _, exists := files[fi.Name()]; !exists {
- files[fi.Name()] = fi
- }
- }
+
}
- for _, fi := range files {
- f.files = append(f.files, fi)
+ merged, err := merge(lfi, bfi)
+ if err != nil {
+ return nil, err
}
+ f.files = append(f.files, merged...)
}
if c == -1 {
return f.files[f.off:], nil
@@ -174,53 +205,53 @@ func (f *UnionFile) Readdirnames(c int) ([]string, error) {
}
func (f *UnionFile) Stat() (os.FileInfo, error) {
- if f.layer != nil {
- return f.layer.Stat()
+ if f.Layer != nil {
+ return f.Layer.Stat()
}
- if f.base != nil {
- return f.base.Stat()
+ if f.Base != nil {
+ return f.Base.Stat()
}
return nil, BADFD
}
func (f *UnionFile) Sync() (err error) {
- if f.layer != nil {
- err = f.layer.Sync()
- if err == nil && f.base != nil {
- err = f.base.Sync()
+ if f.Layer != nil {
+ err = f.Layer.Sync()
+ if err == nil && f.Base != nil {
+ err = f.Base.Sync()
}
return err
}
- if f.base != nil {
- return f.base.Sync()
+ if f.Base != nil {
+ return f.Base.Sync()
}
return BADFD
}
func (f *UnionFile) Truncate(s int64) (err error) {
- if f.layer != nil {
- err = f.layer.Truncate(s)
- if err == nil && f.base != nil {
- err = f.base.Truncate(s)
+ if f.Layer != nil {
+ err = f.Layer.Truncate(s)
+ if err == nil && f.Base != nil {
+ err = f.Base.Truncate(s)
}
return err
}
- if f.base != nil {
- return f.base.Truncate(s)
+ if f.Base != nil {
+ return f.Base.Truncate(s)
}
return BADFD
}
func (f *UnionFile) WriteString(s string) (n int, err error) {
- if f.layer != nil {
- n, err = f.layer.WriteString(s)
- if err == nil && f.base != nil {
- _, err = f.base.WriteString(s)
+ if f.Layer != nil {
+ n, err = f.Layer.WriteString(s)
+ if err == nil && f.Base != nil {
+ _, err = f.Base.WriteString(s)
}
return n, err
}
- if f.base != nil {
- return f.base.WriteString(s)
+ if f.Base != nil {
+ return f.Base.WriteString(s)
}
return 0, BADFD
}
diff --git a/vendor/github.com/spf13/afero/util_test.go b/vendor/github.com/spf13/afero/util_test.go
deleted file mode 100644
index b5852f184..000000000
--- a/vendor/github.com/spf13/afero/util_test.go
+++ /dev/null
@@ -1,450 +0,0 @@
-// Copyright ©2015 Steve Francia <spf@spf13.com>
-// Portions Copyright ©2015 The Hugo Authors
-//
-//
-// 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 afero
-
-import (
- "fmt"
- "os"
- "path/filepath"
- "strconv"
- "strings"
- "testing"
- "time"
-)
-
-var testFS = new(MemMapFs)
-
-func TestDirExists(t *testing.T) {
- type test struct {
- input string
- expected bool
- }
-
- // First create a couple directories so there is something in the filesystem
- //testFS := new(MemMapFs)
- testFS.MkdirAll("/foo/bar", 0777)
-
- data := []test{
- {".", true},
- {"./", true},
- {"..", true},
- {"../", true},
- {"./..", true},
- {"./../", true},
- {"/foo/", true},
- {"/foo", true},
- {"/foo/bar", true},
- {"/foo/bar/", true},
- {"/", true},
- {"/some-really-random-directory-name", false},
- {"/some/really/random/directory/name", false},
- {"./some-really-random-local-directory-name", false},
- {"./some/really/random/local/directory/name", false},
- }
-
- for i, d := range data {
- exists, _ := DirExists(testFS, filepath.FromSlash(d.input))
- if d.expected != exists {
- t.Errorf("Test %d %q failed. Expected %t got %t", i, d.input, d.expected, exists)
- }
- }
-}
-
-func TestIsDir(t *testing.T) {
- testFS = new(MemMapFs)
-
- type test struct {
- input string
- expected bool
- }
- data := []test{
- {"./", true},
- {"/", true},
- {"./this-directory-does-not-existi", false},
- {"/this-absolute-directory/does-not-exist", false},
- }
-
- for i, d := range data {
-
- exists, _ := IsDir(testFS, d.input)
- if d.expected != exists {
- t.Errorf("Test %d failed. Expected %t got %t", i, d.expected, exists)
- }
- }
-}
-
-func TestIsEmpty(t *testing.T) {
- testFS = new(MemMapFs)
-
- zeroSizedFile, _ := createZeroSizedFileInTempDir()
- defer deleteFileInTempDir(zeroSizedFile)
- nonZeroSizedFile, _ := createNonZeroSizedFileInTempDir()
- defer deleteFileInTempDir(nonZeroSizedFile)
- emptyDirectory, _ := createEmptyTempDir()
- defer deleteTempDir(emptyDirectory)
- nonEmptyZeroLengthFilesDirectory, _ := createTempDirWithZeroLengthFiles()
- defer deleteTempDir(nonEmptyZeroLengthFilesDirectory)
- nonEmptyNonZeroLengthFilesDirectory, _ := createTempDirWithNonZeroLengthFiles()
- defer deleteTempDir(nonEmptyNonZeroLengthFilesDirectory)
- nonExistentFile := os.TempDir() + "/this-file-does-not-exist.txt"
- nonExistentDir := os.TempDir() + "/this/direcotry/does/not/exist/"
-
- fileDoesNotExist := fmt.Errorf("%q path does not exist", nonExistentFile)
- dirDoesNotExist := fmt.Errorf("%q path does not exist", nonExistentDir)
-
- type test struct {
- input string
- expectedResult bool
- expectedErr error
- }
-
- data := []test{
- {zeroSizedFile.Name(), true, nil},
- {nonZeroSizedFile.Name(), false, nil},
- {emptyDirectory, true, nil},
- {nonEmptyZeroLengthFilesDirectory, false, nil},
- {nonEmptyNonZeroLengthFilesDirectory, false, nil},
- {nonExistentFile, false, fileDoesNotExist},
- {nonExistentDir, false, dirDoesNotExist},
- }
- for i, d := range data {
- exists, err := IsEmpty(testFS, d.input)
- if d.expectedResult != exists {
- t.Errorf("Test %d %q failed exists. Expected result %t got %t", i, d.input, d.expectedResult, exists)
- }
- if d.expectedErr != nil {
- if d.expectedErr.Error() != err.Error() {
- t.Errorf("Test %d failed with err. Expected %q(%#v) got %q(%#v)", i, d.expectedErr, d.expectedErr, err, err)
- }
- } else {
- if d.expectedErr != err {
- t.Errorf("Test %d failed. Expected error %q(%#v) got %q(%#v)", i, d.expectedErr, d.expectedErr, err, err)
- }
- }
- }
-}
-
-func TestReaderContains(t *testing.T) {
- for i, this := range []struct {
- v1 string
- v2 [][]byte
- expect bool
- }{
- {"abc", [][]byte{[]byte("a")}, true},
- {"abc", [][]byte{[]byte("b")}, true},
- {"abcdefg", [][]byte{[]byte("efg")}, true},
- {"abc", [][]byte{[]byte("d")}, false},
- {"abc", [][]byte{[]byte("d"), []byte("e")}, false},
- {"abc", [][]byte{[]byte("d"), []byte("a")}, true},
- {"abc", [][]byte{[]byte("b"), []byte("e")}, true},
- {"", nil, false},
- {"", [][]byte{[]byte("a")}, false},
- {"a", [][]byte{[]byte("")}, false},
- {"", [][]byte{[]byte("")}, false}} {
- result := readerContainsAny(strings.NewReader(this.v1), this.v2...)
- if result != this.expect {
- t.Errorf("[%d] readerContains: got %t but expected %t", i, result, this.expect)
- }
- }
-
- if readerContainsAny(nil, []byte("a")) {
- t.Error("readerContains with nil reader")
- }
-
- if readerContainsAny(nil, nil) {
- t.Error("readerContains with nil arguments")
- }
-}
-
-func createZeroSizedFileInTempDir() (File, error) {
- filePrefix := "_path_test_"
- f, e := TempFile(testFS, "", filePrefix) // dir is os.TempDir()
- if e != nil {
- // if there was an error no file was created.
- // => no requirement to delete the file
- return nil, e
- }
- return f, nil
-}
-
-func createNonZeroSizedFileInTempDir() (File, error) {
- f, err := createZeroSizedFileInTempDir()
- if err != nil {
- // no file ??
- }
- byteString := []byte("byteString")
- err = WriteFile(testFS, f.Name(), byteString, 0644)
- if err != nil {
- // delete the file
- deleteFileInTempDir(f)
- return nil, err
- }
- return f, nil
-}
-
-func deleteFileInTempDir(f File) {
- err := testFS.Remove(f.Name())
- if err != nil {
- // now what?
- }
-}
-
-func createEmptyTempDir() (string, error) {
- dirPrefix := "_dir_prefix_"
- d, e := TempDir(testFS, "", dirPrefix) // will be in os.TempDir()
- if e != nil {
- // no directory to delete - it was never created
- return "", e
- }
- return d, nil
-}
-
-func createTempDirWithZeroLengthFiles() (string, error) {
- d, dirErr := createEmptyTempDir()
- if dirErr != nil {
- //now what?
- }
- filePrefix := "_path_test_"
- _, fileErr := TempFile(testFS, d, filePrefix) // dir is os.TempDir()
- if fileErr != nil {
- // if there was an error no file was created.
- // but we need to remove the directory to clean-up
- deleteTempDir(d)
- return "", fileErr
- }
- // the dir now has one, zero length file in it
- return d, nil
-
-}
-
-func createTempDirWithNonZeroLengthFiles() (string, error) {
- d, dirErr := createEmptyTempDir()
- if dirErr != nil {
- //now what?
- }
- filePrefix := "_path_test_"
- f, fileErr := TempFile(testFS, d, filePrefix) // dir is os.TempDir()
- if fileErr != nil {
- // if there was an error no file was created.
- // but we need to remove the directory to clean-up
- deleteTempDir(d)
- return "", fileErr
- }
- byteString := []byte("byteString")
- fileErr = WriteFile(testFS, f.Name(), byteString, 0644)
- if fileErr != nil {
- // delete the file
- deleteFileInTempDir(f)
- // also delete the directory
- deleteTempDir(d)
- return "", fileErr
- }
-
- // the dir now has one, zero length file in it
- return d, nil
-
-}
-
-func TestExists(t *testing.T) {
- zeroSizedFile, _ := createZeroSizedFileInTempDir()
- defer deleteFileInTempDir(zeroSizedFile)
- nonZeroSizedFile, _ := createNonZeroSizedFileInTempDir()
- defer deleteFileInTempDir(nonZeroSizedFile)
- emptyDirectory, _ := createEmptyTempDir()
- defer deleteTempDir(emptyDirectory)
- nonExistentFile := os.TempDir() + "/this-file-does-not-exist.txt"
- nonExistentDir := os.TempDir() + "/this/direcotry/does/not/exist/"
-
- type test struct {
- input string
- expectedResult bool
- expectedErr error
- }
-
- data := []test{
- {zeroSizedFile.Name(), true, nil},
- {nonZeroSizedFile.Name(), true, nil},
- {emptyDirectory, true, nil},
- {nonExistentFile, false, nil},
- {nonExistentDir, false, nil},
- }
- for i, d := range data {
- exists, err := Exists(testFS, d.input)
- if d.expectedResult != exists {
- t.Errorf("Test %d failed. Expected result %t got %t", i, d.expectedResult, exists)
- }
- if d.expectedErr != err {
- t.Errorf("Test %d failed. Expected %q got %q", i, d.expectedErr, err)
- }
- }
-
-}
-
-func TestSafeWriteToDisk(t *testing.T) {
- emptyFile, _ := createZeroSizedFileInTempDir()
- defer deleteFileInTempDir(emptyFile)
- tmpDir, _ := createEmptyTempDir()
- defer deleteTempDir(tmpDir)
-
- randomString := "This is a random string!"
- reader := strings.NewReader(randomString)
-
- fileExists := fmt.Errorf("%v already exists", emptyFile.Name())
-
- type test struct {
- filename string
- expectedErr error
- }
-
- now := time.Now().Unix()
- nowStr := strconv.FormatInt(now, 10)
- data := []test{
- {emptyFile.Name(), fileExists},
- {tmpDir + "/" + nowStr, nil},
- }
-
- for i, d := range data {
- e := SafeWriteReader(testFS, d.filename, reader)
- if d.expectedErr != nil {
- if d.expectedErr.Error() != e.Error() {
- t.Errorf("Test %d failed. Expected error %q but got %q", i, d.expectedErr.Error(), e.Error())
- }
- } else {
- if d.expectedErr != e {
- t.Errorf("Test %d failed. Expected %q but got %q", i, d.expectedErr, e)
- }
- contents, _ := ReadFile(testFS, d.filename)
- if randomString != string(contents) {
- t.Errorf("Test %d failed. Expected contents %q but got %q", i, randomString, string(contents))
- }
- }
- reader.Seek(0, 0)
- }
-}
-
-func TestWriteToDisk(t *testing.T) {
- emptyFile, _ := createZeroSizedFileInTempDir()
- defer deleteFileInTempDir(emptyFile)
- tmpDir, _ := createEmptyTempDir()
- defer deleteTempDir(tmpDir)
-
- randomString := "This is a random string!"
- reader := strings.NewReader(randomString)
-
- type test struct {
- filename string
- expectedErr error
- }
-
- now := time.Now().Unix()
- nowStr := strconv.FormatInt(now, 10)
- data := []test{
- {emptyFile.Name(), nil},
- {tmpDir + "/" + nowStr, nil},
- }
-
- for i, d := range data {
- e := WriteReader(testFS, d.filename, reader)
- if d.expectedErr != e {
- t.Errorf("Test %d failed. WriteToDisk Error Expected %q but got %q", i, d.expectedErr, e)
- }
- contents, e := ReadFile(testFS, d.filename)
- if e != nil {
- t.Errorf("Test %d failed. Could not read file %s. Reason: %s\n", i, d.filename, e)
- }
- if randomString != string(contents) {
- t.Errorf("Test %d failed. Expected contents %q but got %q", i, randomString, string(contents))
- }
- reader.Seek(0, 0)
- }
-}
-
-func TestGetTempDir(t *testing.T) {
- dir := os.TempDir()
- if FilePathSeparator != dir[len(dir)-1:] {
- dir = dir + FilePathSeparator
- }
- testDir := "hugoTestFolder" + FilePathSeparator
- tests := []struct {
- input string
- expected string
- }{
- {"", dir},
- {testDir + " Foo bar ", dir + testDir + " Foo bar " + FilePathSeparator},
- {testDir + "Foo.Bar/foo_Bar-Foo", dir + testDir + "Foo.Bar/foo_Bar-Foo" + FilePathSeparator},
- {testDir + "fOO,bar:foo%bAR", dir + testDir + "fOObarfoo%bAR" + FilePathSeparator},
- {testDir + "FOo/BaR.html", dir + testDir + "FOo/BaR.html" + FilePathSeparator},
- {testDir + "трям/трям", dir + testDir + "трям/трям" + FilePathSeparator},
- {testDir + "은행", dir + testDir + "은행" + FilePathSeparator},
- {testDir + "Банковский кассир", dir + testDir + "Банковский кассир" + FilePathSeparator},
- }
-
- for _, test := range tests {
- output := GetTempDir(new(MemMapFs), test.input)
- if output != test.expected {
- t.Errorf("Expected %#v, got %#v\n", test.expected, output)
- }
- }
-}
-
-// This function is very dangerous. Don't use it.
-func deleteTempDir(d string) {
- err := os.RemoveAll(d)
- if err != nil {
- // now what?
- }
-}
-
-func TestFullBaseFsPath(t *testing.T) {
- type dirSpec struct {
- Dir1, Dir2, Dir3 string
- }
- dirSpecs := []dirSpec{
- dirSpec{Dir1: "/", Dir2: "/", Dir3: "/"},
- dirSpec{Dir1: "/", Dir2: "/path2", Dir3: "/"},
- dirSpec{Dir1: "/path1/dir", Dir2: "/path2/dir/", Dir3: "/path3/dir"},
- dirSpec{Dir1: "C:/path1", Dir2: "path2/dir", Dir3: "/path3/dir/"},
- }
-
- for _, ds := range dirSpecs {
- memFs := NewMemMapFs()
- level1Fs := NewBasePathFs(memFs, ds.Dir1)
- level2Fs := NewBasePathFs(level1Fs, ds.Dir2)
- level3Fs := NewBasePathFs(level2Fs, ds.Dir3)
-
- type spec struct {
- BaseFs Fs
- FileName string
- ExpectedPath string
- }
- specs := []spec{
- spec{BaseFs: level3Fs, FileName: "f.txt", ExpectedPath: filepath.Join(ds.Dir1, ds.Dir2, ds.Dir3, "f.txt")},
- spec{BaseFs: level3Fs, FileName: "", ExpectedPath: filepath.Join(ds.Dir1, ds.Dir2, ds.Dir3, "")},
- spec{BaseFs: level2Fs, FileName: "f.txt", ExpectedPath: filepath.Join(ds.Dir1, ds.Dir2, "f.txt")},
- spec{BaseFs: level2Fs, FileName: "", ExpectedPath: filepath.Join(ds.Dir1, ds.Dir2, "")},
- spec{BaseFs: level1Fs, FileName: "f.txt", ExpectedPath: filepath.Join(ds.Dir1, "f.txt")},
- spec{BaseFs: level1Fs, FileName: "", ExpectedPath: filepath.Join(ds.Dir1, "")},
- }
-
- for _, s := range specs {
- if actualPath := FullBaseFsPath(s.BaseFs.(*BasePathFs), s.FileName); actualPath != s.ExpectedPath {
- t.Errorf("Expected \n%s got \n%s", s.ExpectedPath, actualPath)
- }
- }
- }
-}
diff --git a/vendor/github.com/spf13/cast/cast_test.go b/vendor/github.com/spf13/cast/cast_test.go
deleted file mode 100644
index d9b0b013d..000000000
--- a/vendor/github.com/spf13/cast/cast_test.go
+++ /dev/null
@@ -1,1208 +0,0 @@
-// Copyright © 2014 Steve Francia <spf@spf13.com>.
-//
-// Use of this source code is governed by an MIT-style
-// license that can be found in the LICENSE file.
-
-package cast
-
-import (
- "fmt"
- "html/template"
- "testing"
- "time"
-
- "github.com/stretchr/testify/assert"
-)
-
-func TestToUintE(t *testing.T) {
- tests := []struct {
- input interface{}
- expect uint
- iserr bool
- }{
- {int(8), 8, false},
- {int8(8), 8, false},
- {int16(8), 8, false},
- {int32(8), 8, false},
- {int64(8), 8, false},
- {uint(8), 8, false},
- {uint8(8), 8, false},
- {uint16(8), 8, false},
- {uint32(8), 8, false},
- {uint64(8), 8, false},
- {float32(8.31), 8, false},
- {float64(8.31), 8, false},
- {true, 1, false},
- {false, 0, false},
- {"8", 8, false},
- {nil, 0, false},
- // errors
- {int(-8), 0, true},
- {int8(-8), 0, true},
- {int16(-8), 0, true},
- {int32(-8), 0, true},
- {int64(-8), 0, true},
- {float32(-8.31), 0, true},
- {float64(-8.31), 0, true},
- {"-8", 0, true},
- {"test", 0, true},
- {testing.T{}, 0, true},
- }
-
- for i, test := range tests {
- errmsg := fmt.Sprintf("i = %d", i) // assert helper message
-
- v, err := ToUintE(test.input)
- if test.iserr {
- assert.Error(t, err, errmsg)
- continue
- }
-
- assert.NoError(t, err, errmsg)
- assert.Equal(t, test.expect, v, errmsg)
-
- // Non-E test:
- v = ToUint(test.input)
- assert.Equal(t, test.expect, v, errmsg)
- }
-}
-
-func TestToUint64E(t *testing.T) {
- tests := []struct {
- input interface{}
- expect uint64
- iserr bool
- }{
- {int(8), 8, false},
- {int8(8), 8, false},
- {int16(8), 8, false},
- {int32(8), 8, false},
- {int64(8), 8, false},
- {uint(8), 8, false},
- {uint8(8), 8, false},
- {uint16(8), 8, false},
- {uint32(8), 8, false},
- {uint64(8), 8, false},
- {float32(8.31), 8, false},
- {float64(8.31), 8, false},
- {true, 1, false},
- {false, 0, false},
- {"8", 8, false},
- {nil, 0, false},
- // errors
- {int(-8), 0, true},
- {int8(-8), 0, true},
- {int16(-8), 0, true},
- {int32(-8), 0, true},
- {int64(-8), 0, true},
- {float32(-8.31), 0, true},
- {float64(-8.31), 0, true},
- {"-8", 0, true},
- {"test", 0, true},
- {testing.T{}, 0, true},
- }
-
- for i, test := range tests {
- errmsg := fmt.Sprintf("i = %d", i) // assert helper message
-
- v, err := ToUint64E(test.input)
- if test.iserr {
- assert.Error(t, err, errmsg)
- continue
- }
-
- assert.NoError(t, err, errmsg)
- assert.Equal(t, test.expect, v, errmsg)
-
- // Non-E test:
- v = ToUint64(test.input)
- assert.Equal(t, test.expect, v, errmsg)
- }
-}
-
-func TestToUint32E(t *testing.T) {
- tests := []struct {
- input interface{}
- expect uint32
- iserr bool
- }{
- {int(8), 8, false},
- {int8(8), 8, false},
- {int16(8), 8, false},
- {int32(8), 8, false},
- {int64(8), 8, false},
- {uint(8), 8, false},
- {uint8(8), 8, false},
- {uint16(8), 8, false},
- {uint32(8), 8, false},
- {uint64(8), 8, false},
- {float32(8.31), 8, false},
- {float64(8.31), 8, false},
- {true, 1, false},
- {false, 0, false},
- {"8", 8, false},
- {nil, 0, false},
- {int(-8), 0, true},
- {int8(-8), 0, true},
- {int16(-8), 0, true},
- {int32(-8), 0, true},
- {int64(-8), 0, true},
- {float32(-8.31), 0, true},
- {float64(-8.31), 0, true},
- {"-8", 0, true},
- // errors
- {"test", 0, true},
- {testing.T{}, 0, true},
- }
-
- for i, test := range tests {
- errmsg := fmt.Sprintf("i = %d", i) // assert helper message
-
- v, err := ToUint32E(test.input)
- if test.iserr {
- assert.Error(t, err, errmsg)
- continue
- }
-
- assert.NoError(t, err, errmsg)
- assert.Equal(t, test.expect, v, errmsg)
-
- // Non-E test:
- v = ToUint32(test.input)
- assert.Equal(t, test.expect, v, errmsg)
- }
-}
-
-func TestToUint16E(t *testing.T) {
- tests := []struct {
- input interface{}
- expect uint16
- iserr bool
- }{
- {int(8), 8, false},
- {int8(8), 8, false},
- {int16(8), 8, false},
- {int32(8), 8, false},
- {int64(8), 8, false},
- {uint(8), 8, false},
- {uint8(8), 8, false},
- {uint16(8), 8, false},
- {uint32(8), 8, false},
- {uint64(8), 8, false},
- {float32(8.31), 8, false},
- {float64(8.31), 8, false},
- {true, 1, false},
- {false, 0, false},
- {"8", 8, false},
- {nil, 0, false},
- // errors
- {int(-8), 0, true},
- {int8(-8), 0, true},
- {int16(-8), 0, true},
- {int32(-8), 0, true},
- {int64(-8), 0, true},
- {float32(-8.31), 0, true},
- {float64(-8.31), 0, true},
- {"-8", 0, true},
- {"test", 0, true},
- {testing.T{}, 0, true},
- }
-
- for i, test := range tests {
- errmsg := fmt.Sprintf("i = %d", i) // assert helper message
-
- v, err := ToUint16E(test.input)
- if test.iserr {
- assert.Error(t, err, errmsg)
- continue
- }
-
- assert.NoError(t, err, errmsg)
- assert.Equal(t, test.expect, v, errmsg)
-
- // Non-E test
- v = ToUint16(test.input)
- assert.Equal(t, test.expect, v, errmsg)
- }
-}
-
-func TestToUint8E(t *testing.T) {
- tests := []struct {
- input interface{}
- expect uint8
- iserr bool
- }{
- {int(8), 8, false},
- {int8(8), 8, false},
- {int16(8), 8, false},
- {int32(8), 8, false},
- {int64(8), 8, false},
- {uint(8), 8, false},
- {uint8(8), 8, false},
- {uint16(8), 8, false},
- {uint32(8), 8, false},
- {uint64(8), 8, false},
- {float32(8.31), 8, false},
- {float64(8.31), 8, false},
- {true, 1, false},
- {false, 0, false},
- {"8", 8, false},
- {nil, 0, false},
- // errors
- {int(-8), 0, true},
- {int8(-8), 0, true},
- {int16(-8), 0, true},
- {int32(-8), 0, true},
- {int64(-8), 0, true},
- {float32(-8.31), 0, true},
- {float64(-8.31), 0, true},
- {"-8", 0, true},
- {"test", 0, true},
- {testing.T{}, 0, true},
- }
-
- for i, test := range tests {
- errmsg := fmt.Sprintf("i = %d", i) // assert helper message
-
- v, err := ToUint8E(test.input)
- if test.iserr {
- assert.Error(t, err, errmsg)
- continue
- }
-
- assert.NoError(t, err, errmsg)
- assert.Equal(t, test.expect, v, errmsg)
-
- // Non-E test
- v = ToUint8(test.input)
- assert.Equal(t, test.expect, v, errmsg)
- }
-}
-
-func TestToIntE(t *testing.T) {
- tests := []struct {
- input interface{}
- expect int
- iserr bool
- }{
- {int(8), 8, false},
- {int8(8), 8, false},
- {int16(8), 8, false},
- {int32(8), 8, false},
- {int64(8), 8, false},
- {uint(8), 8, false},
- {uint8(8), 8, false},
- {uint16(8), 8, false},
- {uint32(8), 8, false},
- {uint64(8), 8, false},
- {float32(8.31), 8, false},
- {float64(8.31), 8, false},
- {true, 1, false},
- {false, 0, false},
- {"8", 8, false},
- {nil, 0, false},
- // errors
- {"test", 0, true},
- {testing.T{}, 0, true},
- }
-
- for i, test := range tests {
- errmsg := fmt.Sprintf("i = %d", i) // assert helper message
-
- v, err := ToIntE(test.input)
- if test.iserr {
- assert.Error(t, err, errmsg)
- continue
- }
-
- assert.NoError(t, err, errmsg)
- assert.Equal(t, test.expect, v, errmsg)
-
- // Non-E test
- v = ToInt(test.input)
- assert.Equal(t, test.expect, v, errmsg)
- }
-}
-
-func TestToInt64E(t *testing.T) {
- tests := []struct {
- input interface{}
- expect int64
- iserr bool
- }{
- {int(8), 8, false},
- {int8(8), 8, false},
- {int16(8), 8, false},
- {int32(8), 8, false},
- {int64(8), 8, false},
- {uint(8), 8, false},
- {uint8(8), 8, false},
- {uint16(8), 8, false},
- {uint32(8), 8, false},
- {uint64(8), 8, false},
- {float32(8.31), 8, false},
- {float64(8.31), 8, false},
- {true, 1, false},
- {false, 0, false},
- {"8", 8, false},
- {nil, 0, false},
- // errors
- {"test", 0, true},
- {testing.T{}, 0, true},
- }
-
- for i, test := range tests {
- errmsg := fmt.Sprintf("i = %d", i) // assert helper message
-
- v, err := ToInt64E(test.input)
- if test.iserr {
- assert.Error(t, err, errmsg)
- continue
- }
-
- assert.NoError(t, err, errmsg)
- assert.Equal(t, test.expect, v, errmsg)
-
- // Non-E test
- v = ToInt64(test.input)
- assert.Equal(t, test.expect, v, errmsg)
- }
-}
-
-func TestToInt32E(t *testing.T) {
- tests := []struct {
- input interface{}
- expect int32
- iserr bool
- }{
- {int(8), 8, false},
- {int8(8), 8, false},
- {int16(8), 8, false},
- {int32(8), 8, false},
- {int64(8), 8, false},
- {uint(8), 8, false},
- {uint8(8), 8, false},
- {uint16(8), 8, false},
- {uint32(8), 8, false},
- {uint64(8), 8, false},
- {float32(8.31), 8, false},
- {float64(8.31), 8, false},
- {true, 1, false},
- {false, 0, false},
- {"8", 8, false},
- {nil, 0, false},
- // errors
- {"test", 0, true},
- {testing.T{}, 0, true},
- }
-
- for i, test := range tests {
- errmsg := fmt.Sprintf("i = %d", i) // assert helper message
-
- v, err := ToInt32E(test.input)
- if test.iserr {
- assert.Error(t, err, errmsg)
- continue
- }
-
- assert.NoError(t, err, errmsg)
- assert.Equal(t, test.expect, v, errmsg)
-
- // Non-E test
- v = ToInt32(test.input)
- assert.Equal(t, test.expect, v, errmsg)
- }
-}
-
-func TestToInt16E(t *testing.T) {
- tests := []struct {
- input interface{}
- expect int16
- iserr bool
- }{
- {int(8), 8, false},
- {int8(8), 8, false},
- {int16(8), 8, false},
- {int32(8), 8, false},
- {int64(8), 8, false},
- {uint(8), 8, false},
- {uint8(8), 8, false},
- {uint16(8), 8, false},
- {uint32(8), 8, false},
- {uint64(8), 8, false},
- {float32(8.31), 8, false},
- {float64(8.31), 8, false},
- {true, 1, false},
- {false, 0, false},
- {"8", 8, false},
- {nil, 0, false},
- // errors
- {"test", 0, true},
- {testing.T{}, 0, true},
- }
-
- for i, test := range tests {
- errmsg := fmt.Sprintf("i = %d", i) // assert helper message
-
- v, err := ToInt16E(test.input)
- if test.iserr {
- assert.Error(t, err, errmsg)
- continue
- }
-
- assert.NoError(t, err, errmsg)
- assert.Equal(t, test.expect, v, errmsg)
-
- // Non-E test
- v = ToInt16(test.input)
- assert.Equal(t, test.expect, v, errmsg)
- }
-}
-
-func TestToInt8E(t *testing.T) {
- tests := []struct {
- input interface{}
- expect int8
- iserr bool
- }{
- {int(8), 8, false},
- {int8(8), 8, false},
- {int16(8), 8, false},
- {int32(8), 8, false},
- {int64(8), 8, false},
- {uint(8), 8, false},
- {uint8(8), 8, false},
- {uint16(8), 8, false},
- {uint32(8), 8, false},
- {uint64(8), 8, false},
- {float32(8.31), 8, false},
- {float64(8.31), 8, false},
- {true, 1, false},
- {false, 0, false},
- {"8", 8, false},
- {nil, 0, false},
- // errors
- {"test", 0, true},
- {testing.T{}, 0, true},
- }
-
- for i, test := range tests {
- errmsg := fmt.Sprintf("i = %d", i) // assert helper message
-
- v, err := ToInt8E(test.input)
- if test.iserr {
- assert.Error(t, err, errmsg)
- continue
- }
-
- assert.NoError(t, err, errmsg)
- assert.Equal(t, test.expect, v, errmsg)
-
- // Non-E test
- v = ToInt8(test.input)
- assert.Equal(t, test.expect, v, errmsg)
- }
-}
-
-func TestToFloat64E(t *testing.T) {
- tests := []struct {
- input interface{}
- expect float64
- iserr bool
- }{
- {int(8), 8, false},
- {int8(8), 8, false},
- {int16(8), 8, false},
- {int32(8), 8, false},
- {int64(8), 8, false},
- {uint(8), 8, false},
- {uint8(8), 8, false},
- {uint16(8), 8, false},
- {uint32(8), 8, false},
- {uint64(8), 8, false},
- {float32(8), 8, false},
- {float64(8.31), 8.31, false},
- {"8", 8, false},
- {true, 1, false},
- {false, 0, false},
- // errors
- {"test", 0, true},
- {testing.T{}, 0, true},
- }
-
- for i, test := range tests {
- errmsg := fmt.Sprintf("i = %d", i) // assert helper message
-
- v, err := ToFloat64E(test.input)
- if test.iserr {
- assert.Error(t, err, errmsg)
- continue
- }
-
- assert.NoError(t, err, errmsg)
- assert.Equal(t, test.expect, v, errmsg)
-
- // Non-E test
- v = ToFloat64(test.input)
- assert.Equal(t, test.expect, v, errmsg)
- }
-}
-
-func TestToFloat32E(t *testing.T) {
- tests := []struct {
- input interface{}
- expect float32
- iserr bool
- }{
- {int(8), 8, false},
- {int8(8), 8, false},
- {int16(8), 8, false},
- {int32(8), 8, false},
- {int64(8), 8, false},
- {uint(8), 8, false},
- {uint8(8), 8, false},
- {uint16(8), 8, false},
- {uint32(8), 8, false},
- {uint64(8), 8, false},
- {float32(8.31), 8.31, false},
- {float64(8.31), 8.31, false},
- {"8", 8, false},
- {true, 1, false},
- {false, 0, false},
- // errors
- {"test", 0, true},
- {testing.T{}, 0, true},
- }
-
- for i, test := range tests {
- errmsg := fmt.Sprintf("i = %d", i) // assert helper message
-
- v, err := ToFloat32E(test.input)
- if test.iserr {
- assert.Error(t, err, errmsg)
- continue
- }
-
- assert.NoError(t, err, errmsg)
- assert.Equal(t, test.expect, v, errmsg)
-
- // Non-E test
- v = ToFloat32(test.input)
- assert.Equal(t, test.expect, v, errmsg)
- }
-}
-
-func TestToStringE(t *testing.T) {
- type Key struct {
- k string
- }
- key := &Key{"foo"}
-
- tests := []struct {
- input interface{}
- expect string
- iserr bool
- }{
- {int(8), "8", false},
- {int8(8), "8", false},
- {int16(8), "8", false},
- {int32(8), "8", false},
- {int64(8), "8", false},
- {uint(8), "8", false},
- {uint8(8), "8", false},
- {uint16(8), "8", false},
- {uint32(8), "8", false},
- {uint64(8), "8", false},
- {float32(8.31), "8.31", false},
- {float64(8.31), "8.31", false},
- {true, "true", false},
- {false, "false", false},
- {nil, "", false},
- {[]byte("one time"), "one time", false},
- {"one more time", "one more time", false},
- {template.HTML("one time"), "one time", false},
- {template.URL("http://somehost.foo"), "http://somehost.foo", false},
- {template.JS("(1+2)"), "(1+2)", false},
- {template.CSS("a"), "a", false},
- {template.HTMLAttr("a"), "a", false},
- // errors
- {testing.T{}, "", true},
- {key, "", true},
- }
-
- for i, test := range tests {
- errmsg := fmt.Sprintf("i = %d", i) // assert helper message
-
- v, err := ToStringE(test.input)
- if test.iserr {
- assert.Error(t, err, errmsg)
- continue
- }
-
- assert.NoError(t, err, errmsg)
- assert.Equal(t, test.expect, v, errmsg)
-
- // Non-E test
- v = ToString(test.input)
- assert.Equal(t, test.expect, v, errmsg)
- }
-}
-
-type foo struct {
- val string
-}
-
-func (x foo) String() string {
- return x.val
-}
-
-func TestStringerToString(t *testing.T) {
- var x foo
- x.val = "bar"
- assert.Equal(t, "bar", ToString(x))
-}
-
-type fu struct {
- val string
-}
-
-func (x fu) Error() string {
- return x.val
-}
-
-func TestErrorToString(t *testing.T) {
- var x fu
- x.val = "bar"
- assert.Equal(t, "bar", ToString(x))
-}
-
-func TestStringMapStringSliceE(t *testing.T) {
- // ToStringMapString inputs/outputs
- var stringMapString = map[string]string{"key 1": "value 1", "key 2": "value 2", "key 3": "value 3"}
- var stringMapInterface = map[string]interface{}{"key 1": "value 1", "key 2": "value 2", "key 3": "value 3"}
- var interfaceMapString = map[interface{}]string{"key 1": "value 1", "key 2": "value 2", "key 3": "value 3"}
- var interfaceMapInterface = map[interface{}]interface{}{"key 1": "value 1", "key 2": "value 2", "key 3": "value 3"}
-
- // ToStringMapStringSlice inputs/outputs
- var stringMapStringSlice = map[string][]string{"key 1": {"value 1", "value 2", "value 3"}, "key 2": {"value 1", "value 2", "value 3"}, "key 3": {"value 1", "value 2", "value 3"}}
- var stringMapInterfaceSlice = map[string][]interface{}{"key 1": {"value 1", "value 2", "value 3"}, "key 2": {"value 1", "value 2", "value 3"}, "key 3": {"value 1", "value 2", "value 3"}}
- var stringMapInterfaceInterfaceSlice = map[string]interface{}{"key 1": []interface{}{"value 1", "value 2", "value 3"}, "key 2": []interface{}{"value 1", "value 2", "value 3"}, "key 3": []interface{}{"value 1", "value 2", "value 3"}}
- var stringMapStringSingleSliceFieldsResult = map[string][]string{"key 1": {"value", "1"}, "key 2": {"value", "2"}, "key 3": {"value", "3"}}
- var interfaceMapStringSlice = map[interface{}][]string{"key 1": {"value 1", "value 2", "value 3"}, "key 2": {"value 1", "value 2", "value 3"}, "key 3": {"value 1", "value 2", "value 3"}}
- var interfaceMapInterfaceSlice = map[interface{}][]interface{}{"key 1": {"value 1", "value 2", "value 3"}, "key 2": {"value 1", "value 2", "value 3"}, "key 3": {"value 1", "value 2", "value 3"}}
-
- var stringMapStringSliceMultiple = map[string][]string{"key 1": {"value 1", "value 2", "value 3"}, "key 2": {"value 1", "value 2", "value 3"}, "key 3": {"value 1", "value 2", "value 3"}}
- var stringMapStringSliceSingle = map[string][]string{"key 1": {"value 1"}, "key 2": {"value 2"}, "key 3": {"value 3"}}
-
- var stringMapInterface1 = map[string]interface{}{"key 1": []string{"value 1"}, "key 2": []string{"value 2"}}
- var stringMapInterfaceResult1 = map[string][]string{"key 1": {"value 1"}, "key 2": {"value 2"}}
-
- var jsonStringMapString = `{"key 1": "value 1", "key 2": "value 2"}`
- var jsonStringMapStringArray = `{"key 1": ["value 1"], "key 2": ["value 2", "value 3"]}`
- var jsonStringMapStringArrayResult = map[string][]string{"key 1": {"value 1"}, "key 2": {"value 2", "value 3"}}
-
- type Key struct {
- k string
- }
-
- tests := []struct {
- input interface{}
- expect map[string][]string
- iserr bool
- }{
- {stringMapStringSlice, stringMapStringSlice, false},
- {stringMapInterfaceSlice, stringMapStringSlice, false},
- {stringMapInterfaceInterfaceSlice, stringMapStringSlice, false},
- {stringMapStringSliceMultiple, stringMapStringSlice, false},
- {stringMapStringSliceMultiple, stringMapStringSlice, false},
- {stringMapString, stringMapStringSliceSingle, false},
- {stringMapInterface, stringMapStringSliceSingle, false},
- {stringMapInterface1, stringMapInterfaceResult1, false},
- {interfaceMapStringSlice, stringMapStringSlice, false},
- {interfaceMapInterfaceSlice, stringMapStringSlice, false},
- {interfaceMapString, stringMapStringSingleSliceFieldsResult, false},
- {interfaceMapInterface, stringMapStringSingleSliceFieldsResult, false},
- {jsonStringMapStringArray, jsonStringMapStringArrayResult, false},
-
- // errors
- {nil, nil, true},
- {testing.T{}, nil, true},
- {map[interface{}]interface{}{"foo": testing.T{}}, nil, true},
- {map[interface{}]interface{}{Key{"foo"}: "bar"}, nil, true}, // ToStringE(Key{"foo"}) should fail
- {jsonStringMapString, nil, true},
- {"", nil, true},
- }
-
- for i, test := range tests {
- errmsg := fmt.Sprintf("i = %d", i) // assert helper message
-
- v, err := ToStringMapStringSliceE(test.input)
- if test.iserr {
- assert.Error(t, err, errmsg)
- continue
- }
-
- assert.NoError(t, err, errmsg)
- assert.Equal(t, test.expect, v, errmsg)
-
- // Non-E test
- v = ToStringMapStringSlice(test.input)
- assert.Equal(t, test.expect, v, errmsg)
- }
-}
-
-func TestToStringMapE(t *testing.T) {
- tests := []struct {
- input interface{}
- expect map[string]interface{}
- iserr bool
- }{
- {map[interface{}]interface{}{"tag": "tags", "group": "groups"}, map[string]interface{}{"tag": "tags", "group": "groups"}, false},
- {map[string]interface{}{"tag": "tags", "group": "groups"}, map[string]interface{}{"tag": "tags", "group": "groups"}, false},
- {`{"tag": "tags", "group": "groups"}`, map[string]interface{}{"tag": "tags", "group": "groups"}, false},
- {`{"tag": "tags", "group": true}`, map[string]interface{}{"tag": "tags", "group": true}, false},
-
- // errors
- {nil, nil, true},
- {testing.T{}, nil, true},
- {"", nil, true},
- }
-
- for i, test := range tests {
- errmsg := fmt.Sprintf("i = %d", i) // assert helper message
-
- v, err := ToStringMapE(test.input)
- if test.iserr {
- assert.Error(t, err, errmsg)
- continue
- }
-
- assert.NoError(t, err, errmsg)
- assert.Equal(t, test.expect, v, errmsg)
-
- // Non-E test
- v = ToStringMap(test.input)
- assert.Equal(t, test.expect, v, errmsg)
- }
-}
-
-func TestToStringMapBoolE(t *testing.T) {
- tests := []struct {
- input interface{}
- expect map[string]bool
- iserr bool
- }{
- {map[interface{}]interface{}{"v1": true, "v2": false}, map[string]bool{"v1": true, "v2": false}, false},
- {map[string]interface{}{"v1": true, "v2": false}, map[string]bool{"v1": true, "v2": false}, false},
- {map[string]bool{"v1": true, "v2": false}, map[string]bool{"v1": true, "v2": false}, false},
- {`{"v1": true, "v2": false}`, map[string]bool{"v1": true, "v2": false}, false},
-
- // errors
- {nil, nil, true},
- {testing.T{}, nil, true},
- {"", nil, true},
- }
-
- for i, test := range tests {
- errmsg := fmt.Sprintf("i = %d", i) // assert helper message
-
- v, err := ToStringMapBoolE(test.input)
- if test.iserr {
- assert.Error(t, err, errmsg)
- continue
- }
-
- assert.NoError(t, err, errmsg)
- assert.Equal(t, test.expect, v, errmsg)
-
- // Non-E test
- v = ToStringMapBool(test.input)
- assert.Equal(t, test.expect, v, errmsg)
- }
-}
-
-func TestToStringMapStringE(t *testing.T) {
- var stringMapString = map[string]string{"key 1": "value 1", "key 2": "value 2", "key 3": "value 3"}
- var stringMapInterface = map[string]interface{}{"key 1": "value 1", "key 2": "value 2", "key 3": "value 3"}
- var interfaceMapString = map[interface{}]string{"key 1": "value 1", "key 2": "value 2", "key 3": "value 3"}
- var interfaceMapInterface = map[interface{}]interface{}{"key 1": "value 1", "key 2": "value 2", "key 3": "value 3"}
- var jsonString = `{"key 1": "value 1", "key 2": "value 2", "key 3": "value 3"}`
- var invalidJsonString = `{"key 1": "value 1", "key 2": "value 2", "key 3": "value 3"`
- var emptyString = ""
-
- tests := []struct {
- input interface{}
- expect map[string]string
- iserr bool
- }{
- {stringMapString, stringMapString, false},
- {stringMapInterface, stringMapString, false},
- {interfaceMapString, stringMapString, false},
- {interfaceMapInterface, stringMapString, false},
- {jsonString, stringMapString, false},
-
- // errors
- {nil, nil, true},
- {testing.T{}, nil, true},
- {invalidJsonString, nil, true},
- {emptyString, nil, true},
- }
-
- for i, test := range tests {
- errmsg := fmt.Sprintf("i = %d", i) // assert helper message
-
- v, err := ToStringMapStringE(test.input)
- if test.iserr {
- assert.Error(t, err, errmsg)
- continue
- }
-
- assert.NoError(t, err, errmsg)
- assert.Equal(t, test.expect, v, errmsg)
-
- // Non-E test
- v = ToStringMapString(test.input)
- assert.Equal(t, test.expect, v, errmsg)
- }
-}
-
-func TestToBoolSliceE(t *testing.T) {
- tests := []struct {
- input interface{}
- expect []bool
- iserr bool
- }{
- {[]bool{true, false, true}, []bool{true, false, true}, false},
- {[]interface{}{true, false, true}, []bool{true, false, true}, false},
- {[]int{1, 0, 1}, []bool{true, false, true}, false},
- {[]string{"true", "false", "true"}, []bool{true, false, true}, false},
- // errors
- {nil, nil, true},
- {testing.T{}, nil, true},
- {[]string{"foo", "bar"}, nil, true},
- }
-
- for i, test := range tests {
- errmsg := fmt.Sprintf("i = %d", i) // assert helper message
-
- v, err := ToBoolSliceE(test.input)
- if test.iserr {
- assert.Error(t, err, errmsg)
- continue
- }
-
- assert.NoError(t, err, errmsg)
- assert.Equal(t, test.expect, v, errmsg)
-
- // Non-E test
- v = ToBoolSlice(test.input)
- assert.Equal(t, test.expect, v, errmsg)
- }
-}
-
-func TestToIntSliceE(t *testing.T) {
- tests := []struct {
- input interface{}
- expect []int
- iserr bool
- }{
- {[]int{1, 3}, []int{1, 3}, false},
- {[]interface{}{1.2, 3.2}, []int{1, 3}, false},
- {[]string{"2", "3"}, []int{2, 3}, false},
- {[2]string{"2", "3"}, []int{2, 3}, false},
- // errors
- {nil, nil, true},
- {testing.T{}, nil, true},
- {[]string{"foo", "bar"}, nil, true},
- }
-
- for i, test := range tests {
- errmsg := fmt.Sprintf("i = %d", i) // assert helper message
-
- v, err := ToIntSliceE(test.input)
- if test.iserr {
- assert.Error(t, err, errmsg)
- continue
- }
-
- assert.NoError(t, err, errmsg)
- assert.Equal(t, test.expect, v, errmsg)
-
- // Non-E test
- v = ToIntSlice(test.input)
- assert.Equal(t, test.expect, v, errmsg)
- }
-}
-
-func TestToSliceE(t *testing.T) {
- tests := []struct {
- input interface{}
- expect []interface{}
- iserr bool
- }{
- {[]interface{}{1, 3}, []interface{}{1, 3}, false},
- {[]map[string]interface{}{{"k1": 1}, {"k2": 2}}, []interface{}{map[string]interface{}{"k1": 1}, map[string]interface{}{"k2": 2}}, false},
- // errors
- {nil, nil, true},
- {testing.T{}, nil, true},
- }
-
- for i, test := range tests {
- errmsg := fmt.Sprintf("i = %d", i) // assert helper message
-
- v, err := ToSliceE(test.input)
- if test.iserr {
- assert.Error(t, err, errmsg)
- continue
- }
-
- assert.NoError(t, err, errmsg)
- assert.Equal(t, test.expect, v, errmsg)
-
- // Non-E test
- v = ToSlice(test.input)
- assert.Equal(t, test.expect, v, errmsg)
- }
-}
-
-func TestToStringSliceE(t *testing.T) {
- tests := []struct {
- input interface{}
- expect []string
- iserr bool
- }{
- {[]string{"a", "b"}, []string{"a", "b"}, false},
- {[]interface{}{1, 3}, []string{"1", "3"}, false},
- {interface{}(1), []string{"1"}, false},
- // errors
- {nil, nil, true},
- {testing.T{}, nil, true},
- }
-
- for i, test := range tests {
- errmsg := fmt.Sprintf("i = %d", i) // assert helper message
-
- v, err := ToStringSliceE(test.input)
- if test.iserr {
- assert.Error(t, err, errmsg)
- continue
- }
-
- assert.NoError(t, err, errmsg)
- assert.Equal(t, test.expect, v, errmsg)
-
- // Non-E test
- v = ToStringSlice(test.input)
- assert.Equal(t, test.expect, v, errmsg)
- }
-}
-
-func TestToDurationSliceE(t *testing.T) {
- tests := []struct {
- input interface{}
- expect []time.Duration
- iserr bool
- }{
- {[]string{"1s", "1m"}, []time.Duration{time.Second, time.Minute}, false},
- {[]int{1, 2}, []time.Duration{1, 2}, false},
- {[]interface{}{1, 3}, []time.Duration{1, 3}, false},
- {[]time.Duration{1, 3}, []time.Duration{1, 3}, false},
-
- // errors
- {nil, nil, true},
- {testing.T{}, nil, true},
- {[]string{"invalid"}, nil, true},
- }
-
- for i, test := range tests {
- errmsg := fmt.Sprintf("i = %d", i) // assert helper message
-
- v, err := ToDurationSliceE(test.input)
- if test.iserr {
- assert.Error(t, err, errmsg)
- continue
- }
-
- assert.NoError(t, err, errmsg)
- assert.Equal(t, test.expect, v, errmsg)
-
- // Non-E test
- v = ToDurationSlice(test.input)
- assert.Equal(t, test.expect, v, errmsg)
- }
-}
-
-func TestToBoolE(t *testing.T) {
- tests := []struct {
- input interface{}
- expect bool
- iserr bool
- }{
- {0, false, false},
- {nil, false, false},
- {"false", false, false},
- {"FALSE", false, false},
- {"False", false, false},
- {"f", false, false},
- {"F", false, false},
- {false, false, false},
-
- {"true", true, false},
- {"TRUE", true, false},
- {"True", true, false},
- {"t", true, false},
- {"T", true, false},
- {1, true, false},
- {true, true, false},
- {-1, true, false},
-
- // errors
- {"test", false, true},
- {testing.T{}, false, true},
- }
-
- for i, test := range tests {
- errmsg := fmt.Sprintf("i = %d", i) // assert helper message
-
- v, err := ToBoolE(test.input)
- if test.iserr {
- assert.Error(t, err, errmsg)
- continue
- }
-
- assert.NoError(t, err, errmsg)
- assert.Equal(t, test.expect, v, errmsg)
-
- // Non-E test
- v = ToBool(test.input)
- assert.Equal(t, test.expect, v, errmsg)
- }
-}
-
-func BenchmarkTooBool(b *testing.B) {
- for i := 0; i < b.N; i++ {
- if !ToBool(true) {
- b.Fatal("ToBool returned false")
- }
- }
-}
-
-func TestIndirectPointers(t *testing.T) {
- x := 13
- y := &x
- z := &y
-
- assert.Equal(t, ToInt(y), 13)
- assert.Equal(t, ToInt(z), 13)
-}
-
-func TestToTimeEE(t *testing.T) {
- tests := []struct {
- input interface{}
- expect time.Time
- iserr bool
- }{
- {"2009-11-10 23:00:00 +0000 UTC", time.Date(2009, 11, 10, 23, 0, 0, 0, time.UTC), false}, // Time.String()
- {"Tue Nov 10 23:00:00 2009", time.Date(2009, 11, 10, 23, 0, 0, 0, time.UTC), false}, // ANSIC
- {"Tue Nov 10 23:00:00 UTC 2009", time.Date(2009, 11, 10, 23, 0, 0, 0, time.UTC), false}, // UnixDate
- {"Tue Nov 10 23:00:00 +0000 2009", time.Date(2009, 11, 10, 23, 0, 0, 0, time.UTC), false}, // RubyDate
- {"10 Nov 09 23:00 UTC", time.Date(2009, 11, 10, 23, 0, 0, 0, time.UTC), false}, // RFC822
- {"10 Nov 09 23:00 +0000", time.Date(2009, 11, 10, 23, 0, 0, 0, time.UTC), false}, // RFC822Z
- {"Tuesday, 10-Nov-09 23:00:00 UTC", time.Date(2009, 11, 10, 23, 0, 0, 0, time.UTC), false}, // RFC850
- {"Tue, 10 Nov 2009 23:00:00 UTC", time.Date(2009, 11, 10, 23, 0, 0, 0, time.UTC), false}, // RFC1123
- {"Tue, 10 Nov 2009 23:00:00 +0000", time.Date(2009, 11, 10, 23, 0, 0, 0, time.UTC), false}, // RFC1123Z
- {"2009-11-10T23:00:00Z", time.Date(2009, 11, 10, 23, 0, 0, 0, time.UTC), false}, // RFC3339
- {"2009-11-10T23:00:00Z", time.Date(2009, 11, 10, 23, 0, 0, 0, time.UTC), false}, // RFC3339Nano
- {"11:00PM", time.Date(0, 1, 1, 23, 0, 0, 0, time.UTC), false}, // Kitchen
- {"Nov 10 23:00:00", time.Date(0, 11, 10, 23, 0, 0, 0, time.UTC), false}, // Stamp
- {"Nov 10 23:00:00.000", time.Date(0, 11, 10, 23, 0, 0, 0, time.UTC), false}, // StampMilli
- {"Nov 10 23:00:00.000000", time.Date(0, 11, 10, 23, 0, 0, 0, time.UTC), false}, // StampMicro
- {"Nov 10 23:00:00.000000000", time.Date(0, 11, 10, 23, 0, 0, 0, time.UTC), false}, // StampNano
- {"2016-03-06 15:28:01-00:00", time.Date(2016, 3, 6, 15, 28, 1, 0, time.UTC), false}, // RFC3339 without T
- {"2016-03-06 15:28:01", time.Date(2016, 3, 6, 15, 28, 1, 0, time.UTC), false},
- {"2016-03-06 15:28:01 -0000", time.Date(2016, 3, 6, 15, 28, 1, 0, time.UTC), false},
- {"2016-03-06 15:28:01 -00:00", time.Date(2016, 3, 6, 15, 28, 1, 0, time.UTC), false},
- {"2006-01-02", time.Date(2006, 1, 2, 0, 0, 0, 0, time.UTC), false},
- {"02 Jan 2006", time.Date(2006, 1, 2, 0, 0, 0, 0, time.UTC), false},
- {1472574600, time.Date(2016, 8, 30, 16, 30, 0, 0, time.UTC), false},
- {int(1482597504), time.Date(2016, 12, 24, 16, 38, 24, 0, time.UTC), false},
- {int64(1234567890), time.Date(2009, 2, 13, 23, 31, 30, 0, time.UTC), false},
- {int32(1234567890), time.Date(2009, 2, 13, 23, 31, 30, 0, time.UTC), false},
- {uint(1482597504), time.Date(2016, 12, 24, 16, 38, 24, 0, time.UTC), false},
- {uint64(1234567890), time.Date(2009, 2, 13, 23, 31, 30, 0, time.UTC), false},
- {uint32(1234567890), time.Date(2009, 2, 13, 23, 31, 30, 0, time.UTC), false},
- {time.Date(2009, 2, 13, 23, 31, 30, 0, time.UTC), time.Date(2009, 2, 13, 23, 31, 30, 0, time.UTC), false},
- // errors
- {"2006", time.Time{}, true},
- {testing.T{}, time.Time{}, true},
- }
-
- for i, test := range tests {
- errmsg := fmt.Sprintf("i = %d", i) // assert helper message
-
- v, err := ToTimeE(test.input)
- if test.iserr {
- assert.Error(t, err, errmsg)
- continue
- }
-
- assert.NoError(t, err, errmsg)
- assert.Equal(t, test.expect, v.UTC(), errmsg)
-
- // Non-E test
- v = ToTime(test.input)
- assert.Equal(t, test.expect, v.UTC(), errmsg)
- }
-}
-
-func TestToDurationE(t *testing.T) {
- var td time.Duration = 5
-
- tests := []struct {
- input interface{}
- expect time.Duration
- iserr bool
- }{
- {time.Duration(5), td, false},
- {int(5), td, false},
- {int64(5), td, false},
- {int32(5), td, false},
- {int16(5), td, false},
- {int8(5), td, false},
- {uint(5), td, false},
- {uint64(5), td, false},
- {uint32(5), td, false},
- {uint16(5), td, false},
- {uint8(5), td, false},
- {float64(5), td, false},
- {float32(5), td, false},
- {string("5"), td, false},
- {string("5ns"), td, false},
- {string("5us"), time.Microsecond * td, false},
- {string("5µs"), time.Microsecond * td, false},
- {string("5ms"), time.Millisecond * td, false},
- {string("5s"), time.Second * td, false},
- {string("5m"), time.Minute * td, false},
- {string("5h"), time.Hour * td, false},
- // errors
- {"test", 0, true},
- {testing.T{}, 0, true},
- }
-
- for i, test := range tests {
- errmsg := fmt.Sprintf("i = %d", i) // assert helper message
-
- v, err := ToDurationE(test.input)
- if test.iserr {
- assert.Error(t, err, errmsg)
- continue
- }
-
- assert.NoError(t, err, errmsg)
- assert.Equal(t, test.expect, v, errmsg)
-
- // Non-E test
- v = ToDuration(test.input)
- assert.Equal(t, test.expect, v, errmsg)
- }
-}
diff --git a/vendor/github.com/spf13/cobra/.circleci/config.yml b/vendor/github.com/spf13/cobra/.circleci/config.yml
deleted file mode 100644
index 136e17f0e..000000000
--- a/vendor/github.com/spf13/cobra/.circleci/config.yml
+++ /dev/null
@@ -1,38 +0,0 @@
-workflows:
- version: 2
- main:
- jobs:
- - go-current
- - go-previous
- - go-latest
-base: &base
- working_directory: /go/src/github.com/spf13/cobra
- steps:
- - checkout
- - run:
- name: "All Commands"
- command: |
- mkdir -p bin
- curl -Lso bin/shellcheck https://github.com/caarlos0/shellcheck-docker/releases/download/v0.4.3/shellcheck
- chmod +x bin/shellcheck
- go get -t -v ./...
- PATH=$PATH:$PWD/bin go test -v ./...
- go build
- diff -u <(echo -n) <(gofmt -d -s .)
- if [ -z $NOVET ]; then
- diff -u <(echo -n) <(go tool vet . 2>&1 | grep -vE 'ExampleCommand|bash_completions.*Fprint');
- fi
-version: 2
-jobs:
- go-current:
- docker:
- - image: circleci/golang:1.8.3
- <<: *base
- go-previous:
- docker:
- - image: circleci/golang:1.7.6
- <<: *base
- go-latest:
- docker:
- - image: circleci/golang:latest
- <<: *base
diff --git a/vendor/github.com/spf13/cobra/.travis.yml b/vendor/github.com/spf13/cobra/.travis.yml
index 68efa1363..5afcb2096 100644
--- a/vendor/github.com/spf13/cobra/.travis.yml
+++ b/vendor/github.com/spf13/cobra/.travis.yml
@@ -2,8 +2,8 @@ language: go
matrix:
include:
- - go: 1.7.6
- - go: 1.8.3
+ - go: 1.9.4
+ - go: 1.10.0
- go: tip
allow_failures:
- go: tip
diff --git a/vendor/github.com/spf13/cobra/args_test.go b/vendor/github.com/spf13/cobra/args_test.go
deleted file mode 100644
index d797b6f58..000000000
--- a/vendor/github.com/spf13/cobra/args_test.go
+++ /dev/null
@@ -1,241 +0,0 @@
-package cobra
-
-import (
- "strings"
- "testing"
-)
-
-func TestNoArgs(t *testing.T) {
- c := &Command{Use: "c", Args: NoArgs, Run: emptyRun}
-
- output, err := executeCommand(c)
- if output != "" {
- t.Errorf("Unexpected string: %v", output)
- }
- if err != nil {
- t.Fatalf("Unexpected error: %v", err)
- }
-}
-
-func TestNoArgsWithArgs(t *testing.T) {
- c := &Command{Use: "c", Args: NoArgs, Run: emptyRun}
-
- _, err := executeCommand(c, "illegal")
- if err == nil {
- t.Fatal("Expected an error")
- }
-
- got := err.Error()
- expected := `unknown command "illegal" for "c"`
- if got != expected {
- t.Errorf("Expected: %q, got: %q", expected, got)
- }
-}
-
-func TestOnlyValidArgs(t *testing.T) {
- c := &Command{
- Use: "c",
- Args: OnlyValidArgs,
- ValidArgs: []string{"one", "two"},
- Run: emptyRun,
- }
-
- output, err := executeCommand(c, "one", "two")
- if output != "" {
- t.Errorf("Unexpected output: %v", output)
- }
- if err != nil {
- t.Fatalf("Unexpected error: %v", err)
- }
-}
-
-func TestOnlyValidArgsWithInvalidArgs(t *testing.T) {
- c := &Command{
- Use: "c",
- Args: OnlyValidArgs,
- ValidArgs: []string{"one", "two"},
- Run: emptyRun,
- }
-
- _, err := executeCommand(c, "three")
- if err == nil {
- t.Fatal("Expected an error")
- }
-
- got := err.Error()
- expected := `invalid argument "three" for "c"`
- if got != expected {
- t.Errorf("Expected: %q, got: %q", expected, got)
- }
-}
-
-func TestArbitraryArgs(t *testing.T) {
- c := &Command{Use: "c", Args: ArbitraryArgs, Run: emptyRun}
- output, err := executeCommand(c, "a", "b")
- if output != "" {
- t.Errorf("Unexpected output: %v", output)
- }
- if err != nil {
- t.Errorf("Unexpected error: %v", err)
- }
-}
-
-func TestMinimumNArgs(t *testing.T) {
- c := &Command{Use: "c", Args: MinimumNArgs(2), Run: emptyRun}
- output, err := executeCommand(c, "a", "b", "c")
- if output != "" {
- t.Errorf("Unexpected output: %v", output)
- }
- if err != nil {
- t.Errorf("Unexpected error: %v", err)
- }
-}
-
-func TestMinimumNArgsWithLessArgs(t *testing.T) {
- c := &Command{Use: "c", Args: MinimumNArgs(2), Run: emptyRun}
- _, err := executeCommand(c, "a")
-
- if err == nil {
- t.Fatal("Expected an error")
- }
-
- got := err.Error()
- expected := "requires at least 2 arg(s), only received 1"
- if got != expected {
- t.Fatalf("Expected %q, got %q", expected, got)
- }
-}
-
-func TestMaximumNArgs(t *testing.T) {
- c := &Command{Use: "c", Args: MaximumNArgs(3), Run: emptyRun}
- output, err := executeCommand(c, "a", "b")
- if output != "" {
- t.Errorf("Unexpected output: %v", output)
- }
- if err != nil {
- t.Errorf("Unexpected error: %v", err)
- }
-}
-
-func TestMaximumNArgsWithMoreArgs(t *testing.T) {
- c := &Command{Use: "c", Args: MaximumNArgs(2), Run: emptyRun}
- _, err := executeCommand(c, "a", "b", "c")
-
- if err == nil {
- t.Fatal("Expected an error")
- }
-
- got := err.Error()
- expected := "accepts at most 2 arg(s), received 3"
- if got != expected {
- t.Fatalf("Expected %q, got %q", expected, got)
- }
-}
-
-func TestExactArgs(t *testing.T) {
- c := &Command{Use: "c", Args: ExactArgs(3), Run: emptyRun}
- output, err := executeCommand(c, "a", "b", "c")
- if output != "" {
- t.Errorf("Unexpected output: %v", output)
- }
- if err != nil {
- t.Errorf("Unexpected error: %v", err)
- }
-}
-
-func TestExactArgsWithInvalidCount(t *testing.T) {
- c := &Command{Use: "c", Args: ExactArgs(2), Run: emptyRun}
- _, err := executeCommand(c, "a", "b", "c")
-
- if err == nil {
- t.Fatal("Expected an error")
- }
-
- got := err.Error()
- expected := "accepts 2 arg(s), received 3"
- if got != expected {
- t.Fatalf("Expected %q, got %q", expected, got)
- }
-}
-
-func TestRangeArgs(t *testing.T) {
- c := &Command{Use: "c", Args: RangeArgs(2, 4), Run: emptyRun}
- output, err := executeCommand(c, "a", "b", "c")
- if output != "" {
- t.Errorf("Unexpected output: %v", output)
- }
- if err != nil {
- t.Errorf("Unexpected error: %v", err)
- }
-}
-
-func TestRangeArgsWithInvalidCount(t *testing.T) {
- c := &Command{Use: "c", Args: RangeArgs(2, 4), Run: emptyRun}
- _, err := executeCommand(c, "a")
-
- if err == nil {
- t.Fatal("Expected an error")
- }
-
- got := err.Error()
- expected := "accepts between 2 and 4 arg(s), received 1"
- if got != expected {
- t.Fatalf("Expected %q, got %q", expected, got)
- }
-}
-
-func TestRootTakesNoArgs(t *testing.T) {
- rootCmd := &Command{Use: "root", Run: emptyRun}
- childCmd := &Command{Use: "child", Run: emptyRun}
- rootCmd.AddCommand(childCmd)
-
- _, err := executeCommand(rootCmd, "illegal", "args")
- if err == nil {
- t.Fatal("Expected an error")
- }
-
- got := err.Error()
- expected := `unknown command "illegal" for "root"`
- if !strings.Contains(got, expected) {
- t.Errorf("expected %q, got %q", expected, got)
- }
-}
-
-func TestRootTakesArgs(t *testing.T) {
- rootCmd := &Command{Use: "root", Args: ArbitraryArgs, Run: emptyRun}
- childCmd := &Command{Use: "child", Run: emptyRun}
- rootCmd.AddCommand(childCmd)
-
- _, err := executeCommand(rootCmd, "legal", "args")
- if err != nil {
- t.Errorf("Unexpected error: %v", err)
- }
-}
-
-func TestChildTakesNoArgs(t *testing.T) {
- rootCmd := &Command{Use: "root", Run: emptyRun}
- childCmd := &Command{Use: "child", Args: NoArgs, Run: emptyRun}
- rootCmd.AddCommand(childCmd)
-
- _, err := executeCommand(rootCmd, "child", "illegal", "args")
- if err == nil {
- t.Fatal("Expected an error")
- }
-
- got := err.Error()
- expected := `unknown command "illegal" for "root child"`
- if !strings.Contains(got, expected) {
- t.Errorf("expected %q, got %q", expected, got)
- }
-}
-
-func TestChildTakesArgs(t *testing.T) {
- rootCmd := &Command{Use: "root", Run: emptyRun}
- childCmd := &Command{Use: "child", Args: ArbitraryArgs, Run: emptyRun}
- rootCmd.AddCommand(childCmd)
-
- _, err := executeCommand(rootCmd, "child", "legal", "args")
- if err != nil {
- t.Fatalf("Unexpected error: %v", err)
- }
-}
diff --git a/vendor/github.com/spf13/cobra/bash_completions.go b/vendor/github.com/spf13/cobra/bash_completions.go
index 1d955ac25..291eae7d8 100644
--- a/vendor/github.com/spf13/cobra/bash_completions.go
+++ b/vendor/github.com/spf13/cobra/bash_completions.go
@@ -136,6 +136,12 @@ __%[1]s_handle_reply()
if declare -F __ltrim_colon_completions >/dev/null; then
__ltrim_colon_completions "$cur"
fi
+
+ # If there is only 1 completion and it is a flag with an = it will be completed
+ # but we don't want a space after the =
+ if [[ "${#COMPREPLY[@]}" -eq "1" ]] && [[ $(type -t compopt) = "builtin" ]] && [[ "${COMPREPLY[0]}" == --*= ]]; then
+ compopt -o nospace
+ fi
}
# The arguments should be in the form "ext1|ext2|extn"
@@ -222,7 +228,7 @@ __%[1]s_handle_command()
next_command="_${last_command}_${words[c]//:/__}"
else
if [[ $c -eq 0 ]]; then
- next_command="_$(basename "${words[c]//:/__}")"
+ next_command="_%[1]s_root_command"
else
next_command="_${words[c]//:/__}"
fi
@@ -243,7 +249,7 @@ __%[1]s_handle_word()
__%[1]s_handle_flag
elif __%[1]s_contains_word "${words[c]}" "${commands[@]}"; then
__%[1]s_handle_command
- elif [[ $c -eq 0 ]] && __%[1]s_contains_word "$(basename "${words[c]}")" "${commands[@]}"; then
+ elif [[ $c -eq 0 ]]; then
__%[1]s_handle_command
else
__%[1]s_handle_noun
@@ -311,7 +317,7 @@ func writeFlagHandler(buf *bytes.Buffer, name string, annotations map[string][]s
var ext string
if len(value) > 0 {
- ext = fmt.Sprintf("__%s_handle_filename_extension_flag ", cmd.Name()) + strings.Join(value, "|")
+ ext = fmt.Sprintf("__%s_handle_filename_extension_flag ", cmd.Root().Name()) + strings.Join(value, "|")
} else {
ext = "_filedir"
}
@@ -329,7 +335,7 @@ func writeFlagHandler(buf *bytes.Buffer, name string, annotations map[string][]s
var ext string
if len(value) == 1 {
- ext = fmt.Sprintf("__%s_handle_subdirs_in_dir_flag ", cmd.Name()) + value[0]
+ ext = fmt.Sprintf("__%s_handle_subdirs_in_dir_flag ", cmd.Root().Name()) + value[0]
} else {
ext = "_filedir -d"
}
@@ -455,7 +461,13 @@ func gen(buf *bytes.Buffer, cmd *Command) {
commandName := cmd.CommandPath()
commandName = strings.Replace(commandName, " ", "_", -1)
commandName = strings.Replace(commandName, ":", "__", -1)
- buf.WriteString(fmt.Sprintf("_%s()\n{\n", commandName))
+
+ if cmd.Root() == cmd {
+ buf.WriteString(fmt.Sprintf("_%s_root_command()\n{\n", commandName))
+ } else {
+ buf.WriteString(fmt.Sprintf("_%s()\n{\n", commandName))
+ }
+
buf.WriteString(fmt.Sprintf(" last_command=%q\n", commandName))
writeCommands(buf, cmd)
writeFlags(buf, cmd)
diff --git a/vendor/github.com/spf13/cobra/bash_completions.md b/vendor/github.com/spf13/cobra/bash_completions.md
index 44d777c18..8d01f456f 100644
--- a/vendor/github.com/spf13/cobra/bash_completions.md
+++ b/vendor/github.com/spf13/cobra/bash_completions.md
@@ -6,15 +6,16 @@ Generating bash completions from a cobra command is incredibly easy. An actual p
package main
import (
- "io/ioutil"
- "os"
+ "io/ioutil"
+ "os"
- "github.com/GoogleCloudPlatform/kubernetes/pkg/kubectl/cmd"
+ "k8s.io/kubernetes/pkg/kubectl/cmd"
+ "k8s.io/kubernetes/pkg/kubectl/cmd/util"
)
func main() {
- kubectl := cmd.NewFactory(nil).NewKubectlCommand(os.Stdin, ioutil.Discard, ioutil.Discard)
- kubectl.GenBashCompletionFile("out.sh")
+ kubectl := cmd.NewKubectlCommand(util.NewFactory(nil), os.Stdin, ioutil.Discard, ioutil.Discard)
+ kubectl.GenBashCompletionFile("out.sh")
}
```
@@ -204,3 +205,17 @@ __kubectl_get_namespaces()
fi
}
```
+# Using bash aliases for commands
+
+You can also configure the `bash aliases` for the commands and they will also support completions.
+
+```bash
+alias aliasname=origcommand
+complete -o default -F __start_origcommand aliasname
+
+# and now when you run `aliasname` completion will make
+# suggestions as it did for `origcommand`.
+
+$) aliasname <tab><tab>
+completion firstcommand secondcommand
+```
diff --git a/vendor/github.com/spf13/cobra/bash_completions_test.go b/vendor/github.com/spf13/cobra/bash_completions_test.go
deleted file mode 100644
index dd3a88efb..000000000
--- a/vendor/github.com/spf13/cobra/bash_completions_test.go
+++ /dev/null
@@ -1,197 +0,0 @@
-package cobra
-
-import (
- "bytes"
- "fmt"
- "os"
- "os/exec"
- "strings"
- "testing"
-)
-
-func checkOmit(t *testing.T, found, unexpected string) {
- if strings.Contains(found, unexpected) {
- t.Errorf("Got: %q\nBut should not have!\n", unexpected)
- }
-}
-
-func check(t *testing.T, found, expected string) {
- if !strings.Contains(found, expected) {
- t.Errorf("Expecting to contain: \n %q\nGot:\n %q\n", expected, found)
- }
-}
-
-func runShellCheck(s string) error {
- excluded := []string{
- "SC2034", // PREFIX appears unused. Verify it or export it.
- }
- cmd := exec.Command("shellcheck", "-s", "bash", "-", "-e", strings.Join(excluded, ","))
- cmd.Stderr = os.Stderr
- cmd.Stdout = os.Stdout
-
- stdin, err := cmd.StdinPipe()
- if err != nil {
- return err
- }
- go func() {
- stdin.Write([]byte(s))
- stdin.Close()
- }()
-
- return cmd.Run()
-}
-
-// World worst custom function, just keep telling you to enter hello!
-const bashCompletionFunc = `__custom_func() {
- COMPREPLY=( "hello" )
-}
-`
-
-func TestBashCompletions(t *testing.T) {
- rootCmd := &Command{
- Use: "root",
- ArgAliases: []string{"pods", "nodes", "services", "replicationcontrollers", "po", "no", "svc", "rc"},
- ValidArgs: []string{"pod", "node", "service", "replicationcontroller"},
- BashCompletionFunction: bashCompletionFunc,
- Run: emptyRun,
- }
- rootCmd.Flags().IntP("introot", "i", -1, "help message for flag introot")
- rootCmd.MarkFlagRequired("introot")
-
- // Filename.
- rootCmd.Flags().String("filename", "", "Enter a filename")
- rootCmd.MarkFlagFilename("filename", "json", "yaml", "yml")
-
- // Persistent filename.
- rootCmd.PersistentFlags().String("persistent-filename", "", "Enter a filename")
- rootCmd.MarkPersistentFlagFilename("persistent-filename")
- rootCmd.MarkPersistentFlagRequired("persistent-filename")
-
- // Filename extensions.
- rootCmd.Flags().String("filename-ext", "", "Enter a filename (extension limited)")
- rootCmd.MarkFlagFilename("filename-ext")
- rootCmd.Flags().String("custom", "", "Enter a filename (extension limited)")
- rootCmd.MarkFlagCustom("custom", "__complete_custom")
-
- // Subdirectories in a given directory.
- rootCmd.Flags().String("theme", "", "theme to use (located in /themes/THEMENAME/)")
- rootCmd.Flags().SetAnnotation("theme", BashCompSubdirsInDir, []string{"themes"})
-
- echoCmd := &Command{
- Use: "echo [string to echo]",
- Aliases: []string{"say"},
- Short: "Echo anything to the screen",
- Long: "an utterly useless command for testing.",
- Example: "Just run cobra-test echo",
- Run: emptyRun,
- }
-
- printCmd := &Command{
- Use: "print [string to print]",
- Args: MinimumNArgs(1),
- Short: "Print anything to the screen",
- Long: "an absolutely utterly useless command for testing.",
- Run: emptyRun,
- }
-
- deprecatedCmd := &Command{
- Use: "deprecated [can't do anything here]",
- Args: NoArgs,
- Short: "A command which is deprecated",
- Long: "an absolutely utterly useless command for testing deprecation!.",
- Deprecated: "Please use echo instead",
- Run: emptyRun,
- }
-
- colonCmd := &Command{
- Use: "cmd:colon",
- Run: emptyRun,
- }
-
- timesCmd := &Command{
- Use: "times [# times] [string to echo]",
- SuggestFor: []string{"counts"},
- Args: OnlyValidArgs,
- ValidArgs: []string{"one", "two", "three", "four"},
- Short: "Echo anything to the screen more times",
- Long: "a slightly useless command for testing.",
- Run: emptyRun,
- }
-
- echoCmd.AddCommand(timesCmd)
- rootCmd.AddCommand(echoCmd, printCmd, deprecatedCmd, colonCmd)
-
- buf := new(bytes.Buffer)
- rootCmd.GenBashCompletion(buf)
- output := buf.String()
-
- check(t, output, "_root")
- check(t, output, "_root_echo")
- check(t, output, "_root_echo_times")
- check(t, output, "_root_print")
- check(t, output, "_root_cmd__colon")
-
- // check for required flags
- check(t, output, `must_have_one_flag+=("--introot=")`)
- check(t, output, `must_have_one_flag+=("--persistent-filename=")`)
- // check for custom completion function
- check(t, output, `COMPREPLY=( "hello" )`)
- // check for required nouns
- check(t, output, `must_have_one_noun+=("pod")`)
- // check for noun aliases
- check(t, output, `noun_aliases+=("pods")`)
- check(t, output, `noun_aliases+=("rc")`)
- checkOmit(t, output, `must_have_one_noun+=("pods")`)
- // check for filename extension flags
- check(t, output, `flags_completion+=("_filedir")`)
- // check for filename extension flags
- check(t, output, `must_have_one_noun+=("three")`)
- // check for filename extension flags
- check(t, output, fmt.Sprintf(`flags_completion+=("__%s_handle_filename_extension_flag json|yaml|yml")`, rootCmd.Name()))
- // check for custom flags
- check(t, output, `flags_completion+=("__complete_custom")`)
- // check for subdirs_in_dir flags
- check(t, output, fmt.Sprintf(`flags_completion+=("__%s_handle_subdirs_in_dir_flag themes")`, rootCmd.Name()))
-
- checkOmit(t, output, deprecatedCmd.Name())
-
- // If available, run shellcheck against the script.
- if err := exec.Command("which", "shellcheck").Run(); err != nil {
- return
- }
- if err := runShellCheck(output); err != nil {
- t.Fatalf("shellcheck failed: %v", err)
- }
-}
-
-func TestBashCompletionHiddenFlag(t *testing.T) {
- c := &Command{Use: "c", Run: emptyRun}
-
- const flagName = "hiddenFlag"
- c.Flags().Bool(flagName, false, "")
- c.Flags().MarkHidden(flagName)
-
- buf := new(bytes.Buffer)
- c.GenBashCompletion(buf)
- output := buf.String()
-
- if strings.Contains(output, flagName) {
- t.Errorf("Expected completion to not include %q flag: Got %v", flagName, output)
- }
-}
-
-func TestBashCompletionDeprecatedFlag(t *testing.T) {
- c := &Command{Use: "c", Run: emptyRun}
-
- const flagName = "deprecated-flag"
- c.Flags().Bool(flagName, false, "")
- c.Flags().MarkDeprecated(flagName, "use --not-deprecated instead")
-
- buf := new(bytes.Buffer)
- c.GenBashCompletion(buf)
- output := buf.String()
-
- if strings.Contains(output, flagName) {
- t.Errorf("expected completion to not include %q flag: Got %v", flagName, output)
- }
-}
diff --git a/vendor/github.com/spf13/cobra/cobra/README.md b/vendor/github.com/spf13/cobra/cobra/README.md
deleted file mode 100644
index 6054f95c5..000000000
--- a/vendor/github.com/spf13/cobra/cobra/README.md
+++ /dev/null
@@ -1,94 +0,0 @@
-# Cobra Generator
-
-Cobra provides its own program that will create your application and add any
-commands you want. It's the easiest way to incorporate Cobra into your application.
-
-In order to use the cobra command, compile it using the following command:
-
- go get github.com/spf13/cobra/cobra
-
-This will create the cobra executable under your `$GOPATH/bin` directory.
-
-### cobra init
-
-The `cobra init [app]` command will create your initial application code
-for you. It is a very powerful application that will populate your program with
-the right structure so you can immediately enjoy all the benefits of Cobra. It
-will also automatically apply the license you specify to your application.
-
-Cobra init is pretty smart. You can provide it a full path, or simply a path
-similar to what is expected in the import.
-
-```
-cobra init github.com/spf13/newApp
-```
-
-### cobra add
-
-Once an application is initialized, Cobra can create additional commands for you.
-Let's say you created an app and you wanted the following commands for it:
-
-* app serve
-* app config
-* app config create
-
-In your project directory (where your main.go file is) you would run the following:
-
-```
-cobra add serve
-cobra add config
-cobra add create -p 'configCmd'
-```
-
-*Note: Use camelCase (not snake_case/snake-case) for command names.
-Otherwise, you will encounter errors.
-For example, `cobra add add-user` is incorrect, but `cobra add addUser` is valid.*
-
-Once you have run these three commands you would have an app structure similar to
-the following:
-
-```
- ▾ app/
- ▾ cmd/
- serve.go
- config.go
- create.go
- main.go
-```
-
-At this point you can run `go run main.go` and it would run your app. `go run
-main.go serve`, `go run main.go config`, `go run main.go config create` along
-with `go run main.go help serve`, etc. would all work.
-
-Obviously you haven't added your own code to these yet. The commands are ready
-for you to give them their tasks. Have fun!
-
-### Configuring the cobra generator
-
-The Cobra generator will be easier to use if you provide a simple configuration
-file which will help you eliminate providing a bunch of repeated information in
-flags over and over.
-
-An example ~/.cobra.yaml file:
-
-```yaml
-author: Steve Francia <spf@spf13.com>
-license: MIT
-```
-
-You can specify no license by setting `license` to `none` or you can specify
-a custom license:
-
-```yaml
-license:
- header: This file is part of {{ .appName }}.
- text: |
- {{ .copyright }}
-
- This is my license. There are many like it, but this one is mine.
- My license is my best friend. It is my life. I must master it as I must
- master my life.
-```
-
-You can also use built-in licenses. For example, **GPLv2**, **GPLv3**, **LGPL**,
-**AGPL**, **MIT**, **2-Clause BSD** or **3-Clause BSD**.
diff --git a/vendor/github.com/spf13/cobra/cobra/cmd/add.go b/vendor/github.com/spf13/cobra/cobra/cmd/add.go
deleted file mode 100644
index fb22096a3..000000000
--- a/vendor/github.com/spf13/cobra/cobra/cmd/add.go
+++ /dev/null
@@ -1,179 +0,0 @@
-// Copyright © 2015 Steve Francia <spf@spf13.com>.
-//
-// 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 cmd
-
-import (
- "fmt"
- "os"
- "path/filepath"
- "unicode"
-
- "github.com/spf13/cobra"
-)
-
-func init() {
- addCmd.Flags().StringVarP(&packageName, "package", "t", "", "target package name (e.g. github.com/spf13/hugo)")
- addCmd.Flags().StringVarP(&parentName, "parent", "p", "rootCmd", "variable name of parent command for this command")
-}
-
-var packageName, parentName string
-
-var addCmd = &cobra.Command{
- Use: "add [command name]",
- Aliases: []string{"command"},
- Short: "Add a command to a Cobra Application",
- Long: `Add (cobra add) will create a new command, with a license and
-the appropriate structure for a Cobra-based CLI application,
-and register it to its parent (default rootCmd).
-
-If you want your command to be public, pass in the command name
-with an initial uppercase letter.
-
-Example: cobra add server -> resulting in a new cmd/server.go`,
-
- Run: func(cmd *cobra.Command, args []string) {
- if len(args) < 1 {
- er("add needs a name for the command")
- }
-
- var project *Project
- if packageName != "" {
- project = NewProject(packageName)
- } else {
- wd, err := os.Getwd()
- if err != nil {
- er(err)
- }
- project = NewProjectFromPath(wd)
- }
-
- cmdName := validateCmdName(args[0])
- cmdPath := filepath.Join(project.CmdPath(), cmdName+".go")
- createCmdFile(project.License(), cmdPath, cmdName)
-
- fmt.Fprintln(cmd.OutOrStdout(), cmdName, "created at", cmdPath)
- },
-}
-
-// validateCmdName returns source without any dashes and underscore.
-// If there will be dash or underscore, next letter will be uppered.
-// It supports only ASCII (1-byte character) strings.
-// https://github.com/spf13/cobra/issues/269
-func validateCmdName(source string) string {
- i := 0
- l := len(source)
- // The output is initialized on demand, then first dash or underscore
- // occurs.
- var output string
-
- for i < l {
- if source[i] == '-' || source[i] == '_' {
- if output == "" {
- output = source[:i]
- }
-
- // If it's last rune and it's dash or underscore,
- // don't add it output and break the loop.
- if i == l-1 {
- break
- }
-
- // If next character is dash or underscore,
- // just skip the current character.
- if source[i+1] == '-' || source[i+1] == '_' {
- i++
- continue
- }
-
- // If the current character is dash or underscore,
- // upper next letter and add to output.
- output += string(unicode.ToUpper(rune(source[i+1])))
- // We know, what source[i] is dash or underscore and source[i+1] is
- // uppered character, so make i = i+2.
- i += 2
- continue
- }
-
- // If the current character isn't dash or underscore,
- // just add it.
- if output != "" {
- output += string(source[i])
- }
- i++
- }
-
- if output == "" {
- return source // source is initially valid name.
- }
- return output
-}
-
-func createCmdFile(license License, path, cmdName string) {
- template := `{{comment .copyright}}
-{{if .license}}{{comment .license}}{{end}}
-
-package {{.cmdPackage}}
-
-import (
- "fmt"
-
- "github.com/spf13/cobra"
-)
-
-// {{.cmdName}}Cmd represents the {{.cmdName}} command
-var {{.cmdName}}Cmd = &cobra.Command{
- Use: "{{.cmdName}}",
- Short: "A brief description of your command",
- Long: ` + "`" + `A longer description that spans multiple lines and likely contains examples
-and usage of using your command. For example:
-
-Cobra is a CLI library for Go that empowers applications.
-This application is a tool to generate the needed files
-to quickly create a Cobra application.` + "`" + `,
- Run: func(cmd *cobra.Command, args []string) {
- fmt.Println("{{.cmdName}} called")
- },
-}
-
-func init() {
- {{.parentName}}.AddCommand({{.cmdName}}Cmd)
-
- // Here you will define your flags and configuration settings.
-
- // Cobra supports Persistent Flags which will work for this command
- // and all subcommands, e.g.:
- // {{.cmdName}}Cmd.PersistentFlags().String("foo", "", "A help for foo")
-
- // Cobra supports local flags which will only run when this command
- // is called directly, e.g.:
- // {{.cmdName}}Cmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
-}
-`
-
- data := make(map[string]interface{})
- data["copyright"] = copyrightLine()
- data["license"] = license.Header
- data["cmdPackage"] = filepath.Base(filepath.Dir(path)) // last dir of path
- data["parentName"] = parentName
- data["cmdName"] = cmdName
-
- cmdScript, err := executeTemplate(template, data)
- if err != nil {
- er(err)
- }
- err = writeStringToFile(path, cmdScript)
- if err != nil {
- er(err)
- }
-}
diff --git a/vendor/github.com/spf13/cobra/cobra/cmd/add_test.go b/vendor/github.com/spf13/cobra/cobra/cmd/add_test.go
deleted file mode 100644
index b920e2b9d..000000000
--- a/vendor/github.com/spf13/cobra/cobra/cmd/add_test.go
+++ /dev/null
@@ -1,109 +0,0 @@
-package cmd
-
-import (
- "errors"
- "io/ioutil"
- "os"
- "path/filepath"
- "testing"
-
- "github.com/spf13/viper"
-)
-
-// TestGoldenAddCmd initializes the project "github.com/spf13/testproject"
-// in GOPATH, adds "test" command
-// and compares the content of all files in cmd directory of testproject
-// with appropriate golden files.
-// Use -update to update existing golden files.
-func TestGoldenAddCmd(t *testing.T) {
- projectName := "github.com/spf13/testproject"
- project := NewProject(projectName)
- defer os.RemoveAll(project.AbsPath())
-
- viper.Set("author", "NAME HERE <EMAIL ADDRESS>")
- viper.Set("license", "apache")
- viper.Set("year", 2017)
- defer viper.Set("author", nil)
- defer viper.Set("license", nil)
- defer viper.Set("year", nil)
-
- // Initialize the project first.
- initializeProject(project)
-
- // Then add the "test" command.
- cmdName := "test"
- cmdPath := filepath.Join(project.CmdPath(), cmdName+".go")
- createCmdFile(project.License(), cmdPath, cmdName)
-
- expectedFiles := []string{".", "root.go", "test.go"}
- gotFiles := []string{}
-
- // Check project file hierarchy and compare the content of every single file
- // with appropriate golden file.
- err := filepath.Walk(project.CmdPath(), func(path string, info os.FileInfo, err error) error {
- if err != nil {
- return err
- }
-
- // Make path relative to project.CmdPath().
- // E.g. path = "/home/user/go/src/github.com/spf13/testproject/cmd/root.go"
- // then it returns just "root.go".
- relPath, err := filepath.Rel(project.CmdPath(), path)
- if err != nil {
- return err
- }
- relPath = filepath.ToSlash(relPath)
- gotFiles = append(gotFiles, relPath)
- goldenPath := filepath.Join("testdata", filepath.Base(path)+".golden")
-
- switch relPath {
- // Known directories.
- case ".":
- return nil
- // Known files.
- case "root.go", "test.go":
- if *update {
- got, err := ioutil.ReadFile(path)
- if err != nil {
- return err
- }
- ioutil.WriteFile(goldenPath, got, 0644)
- }
- return compareFiles(path, goldenPath)
- }
- // Unknown file.
- return errors.New("unknown file: " + path)
- })
- if err != nil {
- t.Fatal(err)
- }
-
- // Check if some files lack.
- if err := checkLackFiles(expectedFiles, gotFiles); err != nil {
- t.Fatal(err)
- }
-}
-
-func TestValidateCmdName(t *testing.T) {
- testCases := []struct {
- input string
- expected string
- }{
- {"cmdName", "cmdName"},
- {"cmd_name", "cmdName"},
- {"cmd-name", "cmdName"},
- {"cmd______Name", "cmdName"},
- {"cmd------Name", "cmdName"},
- {"cmd______name", "cmdName"},
- {"cmd------name", "cmdName"},
- {"cmdName-----", "cmdName"},
- {"cmdname-", "cmdname"},
- }
-
- for _, testCase := range testCases {
- got := validateCmdName(testCase.input)
- if testCase.expected != got {
- t.Errorf("Expected %q, got %q", testCase.expected, got)
- }
- }
-}
diff --git a/vendor/github.com/spf13/cobra/cobra/cmd/golden_test.go b/vendor/github.com/spf13/cobra/cobra/cmd/golden_test.go
deleted file mode 100644
index 59a5a1c9f..000000000
--- a/vendor/github.com/spf13/cobra/cobra/cmd/golden_test.go
+++ /dev/null
@@ -1,77 +0,0 @@
-package cmd
-
-import (
- "bytes"
- "errors"
- "flag"
- "fmt"
- "io/ioutil"
- "os/exec"
-)
-
-var update = flag.Bool("update", false, "update .golden files")
-
-func init() {
- // Mute commands.
- addCmd.SetOutput(new(bytes.Buffer))
- initCmd.SetOutput(new(bytes.Buffer))
-}
-
-// compareFiles compares the content of files with pathA and pathB.
-// If contents are equal, it returns nil.
-// If not, it returns which files are not equal
-// and diff (if system has diff command) between these files.
-func compareFiles(pathA, pathB string) error {
- contentA, err := ioutil.ReadFile(pathA)
- if err != nil {
- return err
- }
- contentB, err := ioutil.ReadFile(pathB)
- if err != nil {
- return err
- }
- if !bytes.Equal(contentA, contentB) {
- output := new(bytes.Buffer)
- output.WriteString(fmt.Sprintf("%q and %q are not equal!\n\n", pathA, pathB))
-
- diffPath, err := exec.LookPath("diff")
- if err != nil {
- // Don't execute diff if it can't be found.
- return nil
- }
- diffCmd := exec.Command(diffPath, "-u", pathA, pathB)
- diffCmd.Stdout = output
- diffCmd.Stderr = output
-
- output.WriteString("$ diff -u " + pathA + " " + pathB + "\n")
- if err := diffCmd.Run(); err != nil {
- output.WriteString("\n" + err.Error())
- }
- return errors.New(output.String())
- }
- return nil
-}
-
-// checkLackFiles checks if all elements of expected are in got.
-func checkLackFiles(expected, got []string) error {
- lacks := make([]string, 0, len(expected))
- for _, ev := range expected {
- if !stringInStringSlice(ev, got) {
- lacks = append(lacks, ev)
- }
- }
- if len(lacks) > 0 {
- return fmt.Errorf("Lack %v file(s): %v", len(lacks), lacks)
- }
- return nil
-}
-
-// stringInStringSlice checks if s is an element of slice.
-func stringInStringSlice(s string, slice []string) bool {
- for _, v := range slice {
- if s == v {
- return true
- }
- }
- return false
-}
diff --git a/vendor/github.com/spf13/cobra/cobra/cmd/helpers.go b/vendor/github.com/spf13/cobra/cobra/cmd/helpers.go
deleted file mode 100644
index cd94b3e31..000000000
--- a/vendor/github.com/spf13/cobra/cobra/cmd/helpers.go
+++ /dev/null
@@ -1,168 +0,0 @@
-// Copyright © 2015 Steve Francia <spf@spf13.com>.
-//
-// 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 cmd
-
-import (
- "bytes"
- "fmt"
- "io"
- "os"
- "os/exec"
- "path/filepath"
- "strings"
- "text/template"
-)
-
-var srcPaths []string
-
-func init() {
- // Initialize srcPaths.
- envGoPath := os.Getenv("GOPATH")
- goPaths := filepath.SplitList(envGoPath)
- if len(goPaths) == 0 {
- // Adapted from https://github.com/Masterminds/glide/pull/798/files.
- // As of Go 1.8 the GOPATH is no longer required to be set. Instead there
- // is a default value. If there is no GOPATH check for the default value.
- // Note, checking the GOPATH first to avoid invoking the go toolchain if
- // possible.
-
- goExecutable := os.Getenv("COBRA_GO_EXECUTABLE")
- if len(goExecutable) <= 0 {
- goExecutable = "go"
- }
-
- out, err := exec.Command(goExecutable, "env", "GOPATH").Output()
- if err != nil {
- er(err)
- }
-
- toolchainGoPath := strings.TrimSpace(string(out))
- goPaths = filepath.SplitList(toolchainGoPath)
- if len(goPaths) == 0 {
- er("$GOPATH is not set")
- }
- }
- srcPaths = make([]string, 0, len(goPaths))
- for _, goPath := range goPaths {
- srcPaths = append(srcPaths, filepath.Join(goPath, "src"))
- }
-}
-
-func er(msg interface{}) {
- fmt.Println("Error:", msg)
- os.Exit(1)
-}
-
-// isEmpty checks if a given path is empty.
-// Hidden files in path are ignored.
-func isEmpty(path string) bool {
- fi, err := os.Stat(path)
- if err != nil {
- er(err)
- }
-
- if !fi.IsDir() {
- return fi.Size() == 0
- }
-
- f, err := os.Open(path)
- if err != nil {
- er(err)
- }
- defer f.Close()
-
- names, err := f.Readdirnames(-1)
- if err != nil && err != io.EOF {
- er(err)
- }
-
- for _, name := range names {
- if len(name) > 0 && name[0] != '.' {
- return false
- }
- }
- return true
-}
-
-// exists checks if a file or directory exists.
-func exists(path string) bool {
- if path == "" {
- return false
- }
- _, err := os.Stat(path)
- if err == nil {
- return true
- }
- if !os.IsNotExist(err) {
- er(err)
- }
- return false
-}
-
-func executeTemplate(tmplStr string, data interface{}) (string, error) {
- tmpl, err := template.New("").Funcs(template.FuncMap{"comment": commentifyString}).Parse(tmplStr)
- if err != nil {
- return "", err
- }
-
- buf := new(bytes.Buffer)
- err = tmpl.Execute(buf, data)
- return buf.String(), err
-}
-
-func writeStringToFile(path string, s string) error {
- return writeToFile(path, strings.NewReader(s))
-}
-
-// writeToFile writes r to file with path only
-// if file/directory on given path doesn't exist.
-func writeToFile(path string, r io.Reader) error {
- if exists(path) {
- return fmt.Errorf("%v already exists", path)
- }
-
- dir := filepath.Dir(path)
- if dir != "" {
- if err := os.MkdirAll(dir, 0777); err != nil {
- return err
- }
- }
-
- file, err := os.Create(path)
- if err != nil {
- return err
- }
- defer file.Close()
-
- _, err = io.Copy(file, r)
- return err
-}
-
-// commentfyString comments every line of in.
-func commentifyString(in string) string {
- var newlines []string
- lines := strings.Split(in, "\n")
- for _, line := range lines {
- if strings.HasPrefix(line, "//") {
- newlines = append(newlines, line)
- } else {
- if line == "" {
- newlines = append(newlines, "//")
- } else {
- newlines = append(newlines, "// "+line)
- }
- }
- }
- return strings.Join(newlines, "\n")
-}
diff --git a/vendor/github.com/spf13/cobra/cobra/cmd/init.go b/vendor/github.com/spf13/cobra/cobra/cmd/init.go
deleted file mode 100644
index 244137015..000000000
--- a/vendor/github.com/spf13/cobra/cobra/cmd/init.go
+++ /dev/null
@@ -1,234 +0,0 @@
-// Copyright © 2015 Steve Francia <spf@spf13.com>.
-//
-// 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 cmd
-
-import (
- "fmt"
- "os"
- "path"
- "path/filepath"
-
- "github.com/spf13/cobra"
- "github.com/spf13/viper"
-)
-
-var initCmd = &cobra.Command{
- Use: "init [name]",
- Aliases: []string{"initialize", "initialise", "create"},
- Short: "Initialize a Cobra Application",
- Long: `Initialize (cobra init) will create a new application, with a license
-and the appropriate structure for a Cobra-based CLI application.
-
- * If a name is provided, it will be created in the current directory;
- * If no name is provided, the current directory will be assumed;
- * If a relative path is provided, it will be created inside $GOPATH
- (e.g. github.com/spf13/hugo);
- * If an absolute path is provided, it will be created;
- * If the directory already exists but is empty, it will be used.
-
-Init will not use an existing directory with contents.`,
-
- Run: func(cmd *cobra.Command, args []string) {
- wd, err := os.Getwd()
- if err != nil {
- er(err)
- }
-
- var project *Project
- if len(args) == 0 {
- project = NewProjectFromPath(wd)
- } else if len(args) == 1 {
- arg := args[0]
- if arg[0] == '.' {
- arg = filepath.Join(wd, arg)
- }
- if filepath.IsAbs(arg) {
- project = NewProjectFromPath(arg)
- } else {
- project = NewProject(arg)
- }
- } else {
- er("please provide only one argument")
- }
-
- initializeProject(project)
-
- fmt.Fprintln(cmd.OutOrStdout(), `Your Cobra application is ready at
-`+project.AbsPath()+`.
-
-Give it a try by going there and running `+"`go run main.go`."+`
-Add commands to it by running `+"`cobra add [cmdname]`.")
- },
-}
-
-func initializeProject(project *Project) {
- if !exists(project.AbsPath()) { // If path doesn't yet exist, create it
- err := os.MkdirAll(project.AbsPath(), os.ModePerm)
- if err != nil {
- er(err)
- }
- } else if !isEmpty(project.AbsPath()) { // If path exists and is not empty don't use it
- er("Cobra will not create a new project in a non empty directory: " + project.AbsPath())
- }
-
- // We have a directory and it's empty. Time to initialize it.
- createLicenseFile(project.License(), project.AbsPath())
- createMainFile(project)
- createRootCmdFile(project)
-}
-
-func createLicenseFile(license License, path string) {
- data := make(map[string]interface{})
- data["copyright"] = copyrightLine()
-
- // Generate license template from text and data.
- text, err := executeTemplate(license.Text, data)
- if err != nil {
- er(err)
- }
-
- // Write license text to LICENSE file.
- err = writeStringToFile(filepath.Join(path, "LICENSE"), text)
- if err != nil {
- er(err)
- }
-}
-
-func createMainFile(project *Project) {
- mainTemplate := `{{ comment .copyright }}
-{{if .license}}{{ comment .license }}{{end}}
-
-package main
-
-import "{{ .importpath }}"
-
-func main() {
- cmd.Execute()
-}
-`
- data := make(map[string]interface{})
- data["copyright"] = copyrightLine()
- data["license"] = project.License().Header
- data["importpath"] = path.Join(project.Name(), filepath.Base(project.CmdPath()))
-
- mainScript, err := executeTemplate(mainTemplate, data)
- if err != nil {
- er(err)
- }
-
- err = writeStringToFile(filepath.Join(project.AbsPath(), "main.go"), mainScript)
- if err != nil {
- er(err)
- }
-}
-
-func createRootCmdFile(project *Project) {
- template := `{{comment .copyright}}
-{{if .license}}{{comment .license}}{{end}}
-
-package cmd
-
-import (
- "fmt"
- "os"
-{{if .viper}}
- homedir "github.com/mitchellh/go-homedir"{{end}}
- "github.com/spf13/cobra"{{if .viper}}
- "github.com/spf13/viper"{{end}}
-){{if .viper}}
-
-var cfgFile string{{end}}
-
-// rootCmd represents the base command when called without any subcommands
-var rootCmd = &cobra.Command{
- Use: "{{.appName}}",
- Short: "A brief description of your application",
- Long: ` + "`" + `A longer description that spans multiple lines and likely contains
-examples and usage of using your application. For example:
-
-Cobra is a CLI library for Go that empowers applications.
-This application is a tool to generate the needed files
-to quickly create a Cobra application.` + "`" + `,
- // Uncomment the following line if your bare application
- // has an action associated with it:
- // Run: func(cmd *cobra.Command, args []string) { },
-}
-
-// Execute adds all child commands to the root command and sets flags appropriately.
-// This is called by main.main(). It only needs to happen once to the rootCmd.
-func Execute() {
- if err := rootCmd.Execute(); err != nil {
- fmt.Println(err)
- os.Exit(1)
- }
-}
-
-func init() { {{- if .viper}}
- cobra.OnInitialize(initConfig)
-{{end}}
- // Here you will define your flags and configuration settings.
- // Cobra supports persistent flags, which, if defined here,
- // will be global for your application.{{ if .viper }}
- rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.{{ .appName }}.yaml)"){{ else }}
- // rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.{{ .appName }}.yaml)"){{ end }}
-
- // Cobra also supports local flags, which will only run
- // when this action is called directly.
- rootCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
-}{{ if .viper }}
-
-// initConfig reads in config file and ENV variables if set.
-func initConfig() {
- if cfgFile != "" {
- // Use config file from the flag.
- viper.SetConfigFile(cfgFile)
- } else {
- // Find home directory.
- home, err := homedir.Dir()
- if err != nil {
- fmt.Println(err)
- os.Exit(1)
- }
-
- // Search config in home directory with name ".{{ .appName }}" (without extension).
- viper.AddConfigPath(home)
- viper.SetConfigName(".{{ .appName }}")
- }
-
- viper.AutomaticEnv() // read in environment variables that match
-
- // If a config file is found, read it in.
- if err := viper.ReadInConfig(); err == nil {
- fmt.Println("Using config file:", viper.ConfigFileUsed())
- }
-}{{ end }}
-`
-
- data := make(map[string]interface{})
- data["copyright"] = copyrightLine()
- data["viper"] = viper.GetBool("useViper")
- data["license"] = project.License().Header
- data["appName"] = path.Base(project.Name())
-
- rootCmdScript, err := executeTemplate(template, data)
- if err != nil {
- er(err)
- }
-
- err = writeStringToFile(filepath.Join(project.CmdPath(), "root.go"), rootCmdScript)
- if err != nil {
- er(err)
- }
-
-}
diff --git a/vendor/github.com/spf13/cobra/cobra/cmd/init_test.go b/vendor/github.com/spf13/cobra/cobra/cmd/init_test.go
deleted file mode 100644
index 40eb4038e..000000000
--- a/vendor/github.com/spf13/cobra/cobra/cmd/init_test.go
+++ /dev/null
@@ -1,83 +0,0 @@
-package cmd
-
-import (
- "errors"
- "io/ioutil"
- "os"
- "path/filepath"
- "testing"
-
- "github.com/spf13/viper"
-)
-
-// TestGoldenInitCmd initializes the project "github.com/spf13/testproject"
-// in GOPATH and compares the content of files in initialized project with
-// appropriate golden files ("testdata/*.golden").
-// Use -update to update existing golden files.
-func TestGoldenInitCmd(t *testing.T) {
- projectName := "github.com/spf13/testproject"
- project := NewProject(projectName)
- defer os.RemoveAll(project.AbsPath())
-
- viper.Set("author", "NAME HERE <EMAIL ADDRESS>")
- viper.Set("license", "apache")
- viper.Set("year", 2017)
- defer viper.Set("author", nil)
- defer viper.Set("license", nil)
- defer viper.Set("year", nil)
-
- os.Args = []string{"cobra", "init", projectName}
- if err := rootCmd.Execute(); err != nil {
- t.Fatal("Error by execution:", err)
- }
-
- expectedFiles := []string{".", "cmd", "LICENSE", "main.go", "cmd/root.go"}
- gotFiles := []string{}
-
- // Check project file hierarchy and compare the content of every single file
- // with appropriate golden file.
- err := filepath.Walk(project.AbsPath(), func(path string, info os.FileInfo, err error) error {
- if err != nil {
- return err
- }
-
- // Make path relative to project.AbsPath().
- // E.g. path = "/home/user/go/src/github.com/spf13/testproject/cmd/root.go"
- // then it returns just "cmd/root.go".
- relPath, err := filepath.Rel(project.AbsPath(), path)
- if err != nil {
- return err
- }
- relPath = filepath.ToSlash(relPath)
- gotFiles = append(gotFiles, relPath)
- goldenPath := filepath.Join("testdata", filepath.Base(path)+".golden")
-
- switch relPath {
- // Known directories.
- case ".", "cmd":
- return nil
- // Known files.
- case "LICENSE", "main.go", "cmd/root.go":
- if *update {
- got, err := ioutil.ReadFile(path)
- if err != nil {
- return err
- }
- if err := ioutil.WriteFile(goldenPath, got, 0644); err != nil {
- t.Fatal("Error while updating file:", err)
- }
- }
- return compareFiles(path, goldenPath)
- }
- // Unknown file.
- return errors.New("unknown file: " + path)
- })
- if err != nil {
- t.Fatal(err)
- }
-
- // Check if some files lack.
- if err := checkLackFiles(expectedFiles, gotFiles); err != nil {
- t.Fatal(err)
- }
-}
diff --git a/vendor/github.com/spf13/cobra/cobra/cmd/project.go b/vendor/github.com/spf13/cobra/cobra/cmd/project.go
deleted file mode 100644
index 7ddb82585..000000000
--- a/vendor/github.com/spf13/cobra/cobra/cmd/project.go
+++ /dev/null
@@ -1,200 +0,0 @@
-package cmd
-
-import (
- "os"
- "path/filepath"
- "runtime"
- "strings"
-)
-
-// Project contains name, license and paths to projects.
-type Project struct {
- absPath string
- cmdPath string
- srcPath string
- license License
- name string
-}
-
-// NewProject returns Project with specified project name.
-func NewProject(projectName string) *Project {
- if projectName == "" {
- er("can't create project with blank name")
- }
-
- p := new(Project)
- p.name = projectName
-
- // 1. Find already created protect.
- p.absPath = findPackage(projectName)
-
- // 2. If there are no created project with this path, and user is in GOPATH,
- // then use GOPATH/src/projectName.
- if p.absPath == "" {
- wd, err := os.Getwd()
- if err != nil {
- er(err)
- }
- for _, srcPath := range srcPaths {
- goPath := filepath.Dir(srcPath)
- if filepathHasPrefix(wd, goPath) {
- p.absPath = filepath.Join(srcPath, projectName)
- break
- }
- }
- }
-
- // 3. If user is not in GOPATH, then use (first GOPATH)/src/projectName.
- if p.absPath == "" {
- p.absPath = filepath.Join(srcPaths[0], projectName)
- }
-
- return p
-}
-
-// findPackage returns full path to existing go package in GOPATHs.
-func findPackage(packageName string) string {
- if packageName == "" {
- return ""
- }
-
- for _, srcPath := range srcPaths {
- packagePath := filepath.Join(srcPath, packageName)
- if exists(packagePath) {
- return packagePath
- }
- }
-
- return ""
-}
-
-// NewProjectFromPath returns Project with specified absolute path to
-// package.
-func NewProjectFromPath(absPath string) *Project {
- if absPath == "" {
- er("can't create project: absPath can't be blank")
- }
- if !filepath.IsAbs(absPath) {
- er("can't create project: absPath is not absolute")
- }
-
- // If absPath is symlink, use its destination.
- fi, err := os.Lstat(absPath)
- if err != nil {
- er("can't read path info: " + err.Error())
- }
- if fi.Mode()&os.ModeSymlink != 0 {
- path, err := os.Readlink(absPath)
- if err != nil {
- er("can't read the destination of symlink: " + err.Error())
- }
- absPath = path
- }
-
- p := new(Project)
- p.absPath = strings.TrimSuffix(absPath, findCmdDir(absPath))
- p.name = filepath.ToSlash(trimSrcPath(p.absPath, p.SrcPath()))
- return p
-}
-
-// trimSrcPath trims at the beginning of absPath the srcPath.
-func trimSrcPath(absPath, srcPath string) string {
- relPath, err := filepath.Rel(srcPath, absPath)
- if err != nil {
- er(err)
- }
- return relPath
-}
-
-// License returns the License object of project.
-func (p *Project) License() License {
- if p.license.Text == "" && p.license.Name != "None" {
- p.license = getLicense()
- }
- return p.license
-}
-
-// Name returns the name of project, e.g. "github.com/spf13/cobra"
-func (p Project) Name() string {
- return p.name
-}
-
-// CmdPath returns absolute path to directory, where all commands are located.
-func (p *Project) CmdPath() string {
- if p.absPath == "" {
- return ""
- }
- if p.cmdPath == "" {
- p.cmdPath = filepath.Join(p.absPath, findCmdDir(p.absPath))
- }
- return p.cmdPath
-}
-
-// findCmdDir checks if base of absPath is cmd dir and returns it or
-// looks for existing cmd dir in absPath.
-func findCmdDir(absPath string) string {
- if !exists(absPath) || isEmpty(absPath) {
- return "cmd"
- }
-
- if isCmdDir(absPath) {
- return filepath.Base(absPath)
- }
-
- files, _ := filepath.Glob(filepath.Join(absPath, "c*"))
- for _, file := range files {
- if isCmdDir(file) {
- return filepath.Base(file)
- }
- }
-
- return "cmd"
-}
-
-// isCmdDir checks if base of name is one of cmdDir.
-func isCmdDir(name string) bool {
- name = filepath.Base(name)
- for _, cmdDir := range []string{"cmd", "cmds", "command", "commands"} {
- if name == cmdDir {
- return true
- }
- }
- return false
-}
-
-// AbsPath returns absolute path of project.
-func (p Project) AbsPath() string {
- return p.absPath
-}
-
-// SrcPath returns absolute path to $GOPATH/src where project is located.
-func (p *Project) SrcPath() string {
- if p.srcPath != "" {
- return p.srcPath
- }
- if p.absPath == "" {
- p.srcPath = srcPaths[0]
- return p.srcPath
- }
-
- for _, srcPath := range srcPaths {
- if filepathHasPrefix(p.absPath, srcPath) {
- p.srcPath = srcPath
- break
- }
- }
-
- return p.srcPath
-}
-
-func filepathHasPrefix(path string, prefix string) bool {
- if len(path) <= len(prefix) {
- return false
- }
- if runtime.GOOS == "windows" {
- // Paths in windows are case-insensitive.
- return strings.EqualFold(path[0:len(prefix)], prefix)
- }
- return path[0:len(prefix)] == prefix
-
-}
diff --git a/vendor/github.com/spf13/cobra/cobra/cmd/project_test.go b/vendor/github.com/spf13/cobra/cobra/cmd/project_test.go
deleted file mode 100644
index 037f7c554..000000000
--- a/vendor/github.com/spf13/cobra/cobra/cmd/project_test.go
+++ /dev/null
@@ -1,24 +0,0 @@
-package cmd
-
-import (
- "testing"
-)
-
-func TestFindExistingPackage(t *testing.T) {
- path := findPackage("github.com/spf13/cobra")
- if path == "" {
- t.Fatal("findPackage didn't find the existing package")
- }
- if !hasGoPathPrefix(path) {
- t.Fatalf("%q is not in GOPATH, but must be", path)
- }
-}
-
-func hasGoPathPrefix(path string) bool {
- for _, srcPath := range srcPaths {
- if filepathHasPrefix(path, srcPath) {
- return true
- }
- }
- return false
-}
diff --git a/vendor/github.com/spf13/cobra/cobra/cmd/root.go b/vendor/github.com/spf13/cobra/cobra/cmd/root.go
deleted file mode 100644
index 19568f980..000000000
--- a/vendor/github.com/spf13/cobra/cobra/cmd/root.go
+++ /dev/null
@@ -1,79 +0,0 @@
-// Copyright © 2015 Steve Francia <spf@spf13.com>.
-//
-// 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 cmd
-
-import (
- "fmt"
-
- homedir "github.com/mitchellh/go-homedir"
- "github.com/spf13/cobra"
- "github.com/spf13/viper"
-)
-
-var (
- // Used for flags.
- cfgFile, userLicense string
-
- rootCmd = &cobra.Command{
- Use: "cobra",
- Short: "A generator for Cobra based Applications",
- Long: `Cobra is a CLI library for Go that empowers applications.
-This application is a tool to generate the needed files
-to quickly create a Cobra application.`,
- }
-)
-
-// Execute executes the root command.
-func Execute() {
- rootCmd.Execute()
-}
-
-func init() {
- cobra.OnInitialize(initConfig)
-
- rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.cobra.yaml)")
- rootCmd.PersistentFlags().StringP("author", "a", "YOUR NAME", "author name for copyright attribution")
- rootCmd.PersistentFlags().StringVarP(&userLicense, "license", "l", "", "name of license for the project")
- rootCmd.PersistentFlags().Bool("viper", true, "use Viper for configuration")
- viper.BindPFlag("author", rootCmd.PersistentFlags().Lookup("author"))
- viper.BindPFlag("useViper", rootCmd.PersistentFlags().Lookup("viper"))
- viper.SetDefault("author", "NAME HERE <EMAIL ADDRESS>")
- viper.SetDefault("license", "apache")
-
- rootCmd.AddCommand(addCmd)
- rootCmd.AddCommand(initCmd)
-}
-
-func initConfig() {
- if cfgFile != "" {
- // Use config file from the flag.
- viper.SetConfigFile(cfgFile)
- } else {
- // Find home directory.
- home, err := homedir.Dir()
- if err != nil {
- er(err)
- }
-
- // Search config in home directory with name ".cobra" (without extension).
- viper.AddConfigPath(home)
- viper.SetConfigName(".cobra")
- }
-
- viper.AutomaticEnv()
-
- if err := viper.ReadInConfig(); err == nil {
- fmt.Println("Using config file:", viper.ConfigFileUsed())
- }
-}
diff --git a/vendor/github.com/spf13/cobra/cobra/cmd/testdata/main.go.golden b/vendor/github.com/spf13/cobra/cobra/cmd/testdata/main.go.golden
deleted file mode 100644
index cdbe38d70..000000000
--- a/vendor/github.com/spf13/cobra/cobra/cmd/testdata/main.go.golden
+++ /dev/null
@@ -1,21 +0,0 @@
-// Copyright © 2017 NAME HERE <EMAIL ADDRESS>
-//
-// 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 "github.com/spf13/testproject/cmd"
-
-func main() {
- cmd.Execute()
-}
diff --git a/vendor/github.com/spf13/cobra/cobra/cmd/testdata/root.go.golden b/vendor/github.com/spf13/cobra/cobra/cmd/testdata/root.go.golden
deleted file mode 100644
index d74f4cd45..000000000
--- a/vendor/github.com/spf13/cobra/cobra/cmd/testdata/root.go.golden
+++ /dev/null
@@ -1,89 +0,0 @@
-// Copyright © 2017 NAME HERE <EMAIL ADDRESS>
-//
-// 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 cmd
-
-import (
- "fmt"
- "os"
-
- homedir "github.com/mitchellh/go-homedir"
- "github.com/spf13/cobra"
- "github.com/spf13/viper"
-)
-
-var cfgFile string
-
-// rootCmd represents the base command when called without any subcommands
-var rootCmd = &cobra.Command{
- Use: "testproject",
- Short: "A brief description of your application",
- Long: `A longer description that spans multiple lines and likely contains
-examples and usage of using your application. For example:
-
-Cobra is a CLI library for Go that empowers applications.
-This application is a tool to generate the needed files
-to quickly create a Cobra application.`,
- // Uncomment the following line if your bare application
- // has an action associated with it:
- // Run: func(cmd *cobra.Command, args []string) { },
-}
-
-// Execute adds all child commands to the root command and sets flags appropriately.
-// This is called by main.main(). It only needs to happen once to the rootCmd.
-func Execute() {
- if err := rootCmd.Execute(); err != nil {
- fmt.Println(err)
- os.Exit(1)
- }
-}
-
-func init() {
- cobra.OnInitialize(initConfig)
-
- // Here you will define your flags and configuration settings.
- // Cobra supports persistent flags, which, if defined here,
- // will be global for your application.
- rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.testproject.yaml)")
-
- // Cobra also supports local flags, which will only run
- // when this action is called directly.
- rootCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
-}
-
-// initConfig reads in config file and ENV variables if set.
-func initConfig() {
- if cfgFile != "" {
- // Use config file from the flag.
- viper.SetConfigFile(cfgFile)
- } else {
- // Find home directory.
- home, err := homedir.Dir()
- if err != nil {
- fmt.Println(err)
- os.Exit(1)
- }
-
- // Search config in home directory with name ".testproject" (without extension).
- viper.AddConfigPath(home)
- viper.SetConfigName(".testproject")
- }
-
- viper.AutomaticEnv() // read in environment variables that match
-
- // If a config file is found, read it in.
- if err := viper.ReadInConfig(); err == nil {
- fmt.Println("Using config file:", viper.ConfigFileUsed())
- }
-}
diff --git a/vendor/github.com/spf13/cobra/cobra/cmd/testdata/test.go.golden b/vendor/github.com/spf13/cobra/cobra/cmd/testdata/test.go.golden
deleted file mode 100644
index ed6442755..000000000
--- a/vendor/github.com/spf13/cobra/cobra/cmd/testdata/test.go.golden
+++ /dev/null
@@ -1,50 +0,0 @@
-// Copyright © 2017 NAME HERE <EMAIL ADDRESS>
-//
-// 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 cmd
-
-import (
- "fmt"
-
- "github.com/spf13/cobra"
-)
-
-// testCmd represents the test command
-var testCmd = &cobra.Command{
- Use: "test",
- Short: "A brief description of your command",
- Long: `A longer description that spans multiple lines and likely contains examples
-and usage of using your command. For example:
-
-Cobra is a CLI library for Go that empowers applications.
-This application is a tool to generate the needed files
-to quickly create a Cobra application.`,
- Run: func(cmd *cobra.Command, args []string) {
- fmt.Println("test called")
- },
-}
-
-func init() {
- rootCmd.AddCommand(testCmd)
-
- // Here you will define your flags and configuration settings.
-
- // Cobra supports Persistent Flags which will work for this command
- // and all subcommands, e.g.:
- // testCmd.PersistentFlags().String("foo", "", "A help for foo")
-
- // Cobra supports local flags which will only run when this command
- // is called directly, e.g.:
- // testCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
-}
diff --git a/vendor/github.com/spf13/cobra/cobra_test.go b/vendor/github.com/spf13/cobra/cobra_test.go
deleted file mode 100644
index 0d1755bdb..000000000
--- a/vendor/github.com/spf13/cobra/cobra_test.go
+++ /dev/null
@@ -1,22 +0,0 @@
-package cobra
-
-import (
- "testing"
- "text/template"
-)
-
-func TestAddTemplateFunctions(t *testing.T) {
- AddTemplateFunc("t", func() bool { return true })
- AddTemplateFuncs(template.FuncMap{
- "f": func() bool { return false },
- "h": func() string { return "Hello," },
- "w": func() string { return "world." }})
-
- c := &Command{}
- c.SetUsageTemplate(`{{if t}}{{h}}{{end}}{{if f}}{{h}}{{end}} {{w}}`)
-
- const expected = "Hello, world."
- if got := c.UsageString(); got != expected {
- t.Errorf("Expected UsageString: %v\nGot: %v", expected, got)
- }
-}
diff --git a/vendor/github.com/spf13/cobra/command.go b/vendor/github.com/spf13/cobra/command.go
index 29675b336..15b811279 100644
--- a/vendor/github.com/spf13/cobra/command.go
+++ b/vendor/github.com/spf13/cobra/command.go
@@ -475,6 +475,9 @@ Loop:
s := args[0]
args = args[1:]
switch {
+ case s == "--":
+ // "--" terminates the flags
+ break Loop
case strings.HasPrefix(s, "--") && !strings.Contains(s, "=") && !hasNoOptDefVal(s[2:], flags):
// If '--flag arg' then
// delete arg from args.
diff --git a/vendor/github.com/spf13/cobra/command_test.go b/vendor/github.com/spf13/cobra/command_test.go
deleted file mode 100644
index d874a9a51..000000000
--- a/vendor/github.com/spf13/cobra/command_test.go
+++ /dev/null
@@ -1,1628 +0,0 @@
-package cobra
-
-import (
- "bytes"
- "fmt"
- "os"
- "reflect"
- "strings"
- "testing"
-
- "github.com/spf13/pflag"
-)
-
-func emptyRun(*Command, []string) {}
-
-func executeCommand(root *Command, args ...string) (output string, err error) {
- _, output, err = executeCommandC(root, args...)
- return output, err
-}
-
-func executeCommandC(root *Command, args ...string) (c *Command, output string, err error) {
- buf := new(bytes.Buffer)
- root.SetOutput(buf)
- root.SetArgs(args)
-
- c, err = root.ExecuteC()
-
- return c, buf.String(), err
-}
-
-func resetCommandLineFlagSet() {
- pflag.CommandLine = pflag.NewFlagSet(os.Args[0], pflag.ExitOnError)
-}
-
-func checkStringContains(t *testing.T, got, expected string) {
- if !strings.Contains(got, expected) {
- t.Errorf("Expected to contain: \n %v\nGot:\n %v\n", expected, got)
- }
-}
-
-func checkStringOmits(t *testing.T, got, expected string) {
- if strings.Contains(got, expected) {
- t.Errorf("Expected to not contain: \n %v\nGot: %v", expected, got)
- }
-}
-
-func TestSingleCommand(t *testing.T) {
- var rootCmdArgs []string
- rootCmd := &Command{
- Use: "root",
- Args: ExactArgs(2),
- Run: func(_ *Command, args []string) { rootCmdArgs = args },
- }
- aCmd := &Command{Use: "a", Args: NoArgs, Run: emptyRun}
- bCmd := &Command{Use: "b", Args: NoArgs, Run: emptyRun}
- rootCmd.AddCommand(aCmd, bCmd)
-
- output, err := executeCommand(rootCmd, "one", "two")
- if output != "" {
- t.Errorf("Unexpected output: %v", output)
- }
- if err != nil {
- t.Errorf("Unexpected error: %v", err)
- }
-
- got := strings.Join(rootCmdArgs, " ")
- expected := "one two"
- if got != expected {
- t.Errorf("rootCmdArgs expected: %q, got: %q", expected, got)
- }
-}
-
-func TestChildCommand(t *testing.T) {
- var child1CmdArgs []string
- rootCmd := &Command{Use: "root", Args: NoArgs, Run: emptyRun}
- child1Cmd := &Command{
- Use: "child1",
- Args: ExactArgs(2),
- Run: func(_ *Command, args []string) { child1CmdArgs = args },
- }
- child2Cmd := &Command{Use: "child2", Args: NoArgs, Run: emptyRun}
- rootCmd.AddCommand(child1Cmd, child2Cmd)
-
- output, err := executeCommand(rootCmd, "child1", "one", "two")
- if output != "" {
- t.Errorf("Unexpected output: %v", output)
- }
- if err != nil {
- t.Errorf("Unexpected error: %v", err)
- }
-
- got := strings.Join(child1CmdArgs, " ")
- expected := "one two"
- if got != expected {
- t.Errorf("child1CmdArgs expected: %q, got: %q", expected, got)
- }
-}
-
-func TestCallCommandWithoutSubcommands(t *testing.T) {
- rootCmd := &Command{Use: "root", Args: NoArgs, Run: emptyRun}
- _, err := executeCommand(rootCmd)
- if err != nil {
- t.Errorf("Calling command without subcommands should not have error: %v", err)
- }
-}
-
-func TestRootExecuteUnknownCommand(t *testing.T) {
- rootCmd := &Command{Use: "root", Run: emptyRun}
- rootCmd.AddCommand(&Command{Use: "child", Run: emptyRun})
-
- output, _ := executeCommand(rootCmd, "unknown")
-
- expected := "Error: unknown command \"unknown\" for \"root\"\nRun 'root --help' for usage.\n"
-
- if output != expected {
- t.Errorf("Expected:\n %q\nGot:\n %q\n", expected, output)
- }
-}
-
-func TestSubcommandExecuteC(t *testing.T) {
- rootCmd := &Command{Use: "root", Run: emptyRun}
- childCmd := &Command{Use: "child", Run: emptyRun}
- rootCmd.AddCommand(childCmd)
-
- c, output, err := executeCommandC(rootCmd, "child")
- if output != "" {
- t.Errorf("Unexpected output: %v", output)
- }
- if err != nil {
- t.Errorf("Unexpected error: %v", err)
- }
-
- if c.Name() != "child" {
- t.Errorf(`invalid command returned from ExecuteC: expected "child"', got %q`, c.Name())
- }
-}
-
-func TestRootUnknownCommandSilenced(t *testing.T) {
- rootCmd := &Command{Use: "root", Run: emptyRun}
- rootCmd.SilenceErrors = true
- rootCmd.SilenceUsage = true
- rootCmd.AddCommand(&Command{Use: "child", Run: emptyRun})
-
- output, _ := executeCommand(rootCmd, "unknown")
- if output != "" {
- t.Errorf("Expected blank output, because of silenced usage.\nGot:\n %q\n", output)
- }
-}
-
-func TestCommandAlias(t *testing.T) {
- var timesCmdArgs []string
- rootCmd := &Command{Use: "root", Args: NoArgs, Run: emptyRun}
- echoCmd := &Command{
- Use: "echo",
- Aliases: []string{"say", "tell"},
- Args: NoArgs,
- Run: emptyRun,
- }
- timesCmd := &Command{
- Use: "times",
- Args: ExactArgs(2),
- Run: func(_ *Command, args []string) { timesCmdArgs = args },
- }
- echoCmd.AddCommand(timesCmd)
- rootCmd.AddCommand(echoCmd)
-
- output, err := executeCommand(rootCmd, "tell", "times", "one", "two")
- if output != "" {
- t.Errorf("Unexpected output: %v", output)
- }
- if err != nil {
- t.Errorf("Unexpected error: %v", err)
- }
-
- got := strings.Join(timesCmdArgs, " ")
- expected := "one two"
- if got != expected {
- t.Errorf("timesCmdArgs expected: %v, got: %v", expected, got)
- }
-}
-
-func TestEnablePrefixMatching(t *testing.T) {
- EnablePrefixMatching = true
-
- var aCmdArgs []string
- rootCmd := &Command{Use: "root", Args: NoArgs, Run: emptyRun}
- aCmd := &Command{
- Use: "aCmd",
- Args: ExactArgs(2),
- Run: func(_ *Command, args []string) { aCmdArgs = args },
- }
- bCmd := &Command{Use: "bCmd", Args: NoArgs, Run: emptyRun}
- rootCmd.AddCommand(aCmd, bCmd)
-
- output, err := executeCommand(rootCmd, "a", "one", "two")
- if output != "" {
- t.Errorf("Unexpected output: %v", output)
- }
- if err != nil {
- t.Errorf("Unexpected error: %v", err)
- }
-
- got := strings.Join(aCmdArgs, " ")
- expected := "one two"
- if got != expected {
- t.Errorf("aCmdArgs expected: %q, got: %q", expected, got)
- }
-
- EnablePrefixMatching = false
-}
-
-func TestAliasPrefixMatching(t *testing.T) {
- EnablePrefixMatching = true
-
- var timesCmdArgs []string
- rootCmd := &Command{Use: "root", Args: NoArgs, Run: emptyRun}
- echoCmd := &Command{
- Use: "echo",
- Aliases: []string{"say", "tell"},
- Args: NoArgs,
- Run: emptyRun,
- }
- timesCmd := &Command{
- Use: "times",
- Args: ExactArgs(2),
- Run: func(_ *Command, args []string) { timesCmdArgs = args },
- }
- echoCmd.AddCommand(timesCmd)
- rootCmd.AddCommand(echoCmd)
-
- output, err := executeCommand(rootCmd, "sa", "times", "one", "two")
- if output != "" {
- t.Errorf("Unexpected output: %v", output)
- }
- if err != nil {
- t.Errorf("Unexpected error: %v", err)
- }
-
- got := strings.Join(timesCmdArgs, " ")
- expected := "one two"
- if got != expected {
- t.Errorf("timesCmdArgs expected: %v, got: %v", expected, got)
- }
-
- EnablePrefixMatching = false
-}
-
-// TestChildSameName checks the correct behaviour of cobra in cases,
-// when an application with name "foo" and with subcommand "foo"
-// is executed with args "foo foo".
-func TestChildSameName(t *testing.T) {
- var fooCmdArgs []string
- rootCmd := &Command{Use: "foo", Args: NoArgs, Run: emptyRun}
- fooCmd := &Command{
- Use: "foo",
- Args: ExactArgs(2),
- Run: func(_ *Command, args []string) { fooCmdArgs = args },
- }
- barCmd := &Command{Use: "bar", Args: NoArgs, Run: emptyRun}
- rootCmd.AddCommand(fooCmd, barCmd)
-
- output, err := executeCommand(rootCmd, "foo", "one", "two")
- if output != "" {
- t.Errorf("Unexpected output: %v", output)
- }
- if err != nil {
- t.Errorf("Unexpected error: %v", err)
- }
-
- got := strings.Join(fooCmdArgs, " ")
- expected := "one two"
- if got != expected {
- t.Errorf("fooCmdArgs expected: %v, got: %v", expected, got)
- }
-}
-
-// TestGrandChildSameName checks the correct behaviour of cobra in cases,
-// when user has a root command and a grand child
-// with the same name.
-func TestGrandChildSameName(t *testing.T) {
- var fooCmdArgs []string
- rootCmd := &Command{Use: "foo", Args: NoArgs, Run: emptyRun}
- barCmd := &Command{Use: "bar", Args: NoArgs, Run: emptyRun}
- fooCmd := &Command{
- Use: "foo",
- Args: ExactArgs(2),
- Run: func(_ *Command, args []string) { fooCmdArgs = args },
- }
- barCmd.AddCommand(fooCmd)
- rootCmd.AddCommand(barCmd)
-
- output, err := executeCommand(rootCmd, "bar", "foo", "one", "two")
- if output != "" {
- t.Errorf("Unexpected output: %v", output)
- }
- if err != nil {
- t.Errorf("Unexpected error: %v", err)
- }
-
- got := strings.Join(fooCmdArgs, " ")
- expected := "one two"
- if got != expected {
- t.Errorf("fooCmdArgs expected: %v, got: %v", expected, got)
- }
-}
-
-func TestFlagLong(t *testing.T) {
- var cArgs []string
- c := &Command{
- Use: "c",
- Args: ArbitraryArgs,
- Run: func(_ *Command, args []string) { cArgs = args },
- }
-
- var intFlagValue int
- var stringFlagValue string
- c.Flags().IntVar(&intFlagValue, "intf", -1, "")
- c.Flags().StringVar(&stringFlagValue, "sf", "", "")
-
- output, err := executeCommand(c, "--intf=7", "--sf=abc", "one", "--", "two")
- if output != "" {
- t.Errorf("Unexpected output: %v", err)
- }
- if err != nil {
- t.Errorf("Unexpected error: %v", err)
- }
-
- if c.ArgsLenAtDash() != 1 {
- t.Errorf("Expected ArgsLenAtDash: %v but got %v", 1, c.ArgsLenAtDash())
- }
- if intFlagValue != 7 {
- t.Errorf("Expected intFlagValue: %v, got %v", 7, intFlagValue)
- }
- if stringFlagValue != "abc" {
- t.Errorf("Expected stringFlagValue: %q, got %q", "abc", stringFlagValue)
- }
-
- got := strings.Join(cArgs, " ")
- expected := "one two"
- if got != expected {
- t.Errorf("Expected arguments: %q, got %q", expected, got)
- }
-}
-
-func TestFlagShort(t *testing.T) {
- var cArgs []string
- c := &Command{
- Use: "c",
- Args: ArbitraryArgs,
- Run: func(_ *Command, args []string) { cArgs = args },
- }
-
- var intFlagValue int
- var stringFlagValue string
- c.Flags().IntVarP(&intFlagValue, "intf", "i", -1, "")
- c.Flags().StringVarP(&stringFlagValue, "sf", "s", "", "")
-
- output, err := executeCommand(c, "-i", "7", "-sabc", "one", "two")
- if output != "" {
- t.Errorf("Unexpected output: %v", err)
- }
- if err != nil {
- t.Errorf("Unexpected error: %v", err)
- }
-
- if intFlagValue != 7 {
- t.Errorf("Expected flag value: %v, got %v", 7, intFlagValue)
- }
- if stringFlagValue != "abc" {
- t.Errorf("Expected stringFlagValue: %q, got %q", "abc", stringFlagValue)
- }
-
- got := strings.Join(cArgs, " ")
- expected := "one two"
- if got != expected {
- t.Errorf("Expected arguments: %q, got %q", expected, got)
- }
-}
-
-func TestChildFlag(t *testing.T) {
- rootCmd := &Command{Use: "root", Run: emptyRun}
- childCmd := &Command{Use: "child", Run: emptyRun}
- rootCmd.AddCommand(childCmd)
-
- var intFlagValue int
- childCmd.Flags().IntVarP(&intFlagValue, "intf", "i", -1, "")
-
- output, err := executeCommand(rootCmd, "child", "-i7")
- if output != "" {
- t.Errorf("Unexpected output: %v", err)
- }
- if err != nil {
- t.Errorf("Unexpected error: %v", err)
- }
-
- if intFlagValue != 7 {
- t.Errorf("Expected flag value: %v, got %v", 7, intFlagValue)
- }
-}
-
-func TestChildFlagWithParentLocalFlag(t *testing.T) {
- rootCmd := &Command{Use: "root", Run: emptyRun}
- childCmd := &Command{Use: "child", Run: emptyRun}
- rootCmd.AddCommand(childCmd)
-
- var intFlagValue int
- rootCmd.Flags().StringP("sf", "s", "", "")
- childCmd.Flags().IntVarP(&intFlagValue, "intf", "i", -1, "")
-
- _, err := executeCommand(rootCmd, "child", "-i7", "-sabc")
- if err == nil {
- t.Errorf("Invalid flag should generate error")
- }
-
- checkStringContains(t, err.Error(), "unknown shorthand")
-
- if intFlagValue != 7 {
- t.Errorf("Expected flag value: %v, got %v", 7, intFlagValue)
- }
-}
-
-func TestFlagInvalidInput(t *testing.T) {
- rootCmd := &Command{Use: "root", Run: emptyRun}
- rootCmd.Flags().IntP("intf", "i", -1, "")
-
- _, err := executeCommand(rootCmd, "-iabc")
- if err == nil {
- t.Errorf("Invalid flag value should generate error")
- }
-
- checkStringContains(t, err.Error(), "invalid syntax")
-}
-
-func TestFlagBeforeCommand(t *testing.T) {
- rootCmd := &Command{Use: "root", Run: emptyRun}
- childCmd := &Command{Use: "child", Run: emptyRun}
- rootCmd.AddCommand(childCmd)
-
- var flagValue int
- childCmd.Flags().IntVarP(&flagValue, "intf", "i", -1, "")
-
- // With short flag.
- _, err := executeCommand(rootCmd, "-i7", "child")
- if err != nil {
- t.Errorf("Unexpected error: %v", err)
- }
- if flagValue != 7 {
- t.Errorf("Expected flag value: %v, got %v", 7, flagValue)
- }
-
- // With long flag.
- _, err = executeCommand(rootCmd, "--intf=8", "child")
- if err != nil {
- t.Errorf("Unexpected error: %v", err)
- }
- if flagValue != 8 {
- t.Errorf("Expected flag value: %v, got %v", 9, flagValue)
- }
-}
-
-func TestStripFlags(t *testing.T) {
- tests := []struct {
- input []string
- output []string
- }{
- {
- []string{"foo", "bar"},
- []string{"foo", "bar"},
- },
- {
- []string{"foo", "--str", "-s"},
- []string{"foo"},
- },
- {
- []string{"-s", "foo", "--str", "bar"},
- []string{},
- },
- {
- []string{"-i10", "echo"},
- []string{"echo"},
- },
- {
- []string{"-i=10", "echo"},
- []string{"echo"},
- },
- {
- []string{"--int=100", "echo"},
- []string{"echo"},
- },
- {
- []string{"-ib", "echo", "-sfoo", "baz"},
- []string{"echo", "baz"},
- },
- {
- []string{"-i=baz", "bar", "-i", "foo", "blah"},
- []string{"bar", "blah"},
- },
- {
- []string{"--int=baz", "-sbar", "-i", "foo", "blah"},
- []string{"blah"},
- },
- {
- []string{"--bool", "bar", "-i", "foo", "blah"},
- []string{"bar", "blah"},
- },
- {
- []string{"-b", "bar", "-i", "foo", "blah"},
- []string{"bar", "blah"},
- },
- {
- []string{"--persist", "bar"},
- []string{"bar"},
- },
- {
- []string{"-p", "bar"},
- []string{"bar"},
- },
- }
-
- c := &Command{Use: "c", Run: emptyRun}
- c.PersistentFlags().BoolP("persist", "p", false, "")
- c.Flags().IntP("int", "i", -1, "")
- c.Flags().StringP("str", "s", "", "")
- c.Flags().BoolP("bool", "b", false, "")
-
- for i, test := range tests {
- got := stripFlags(test.input, c)
- if !reflect.DeepEqual(test.output, got) {
- t.Errorf("(%v) Expected: %v, got: %v", i, test.output, got)
- }
- }
-}
-
-func TestDisableFlagParsing(t *testing.T) {
- var cArgs []string
- c := &Command{
- Use: "c",
- DisableFlagParsing: true,
- Run: func(_ *Command, args []string) {
- cArgs = args
- },
- }
-
- args := []string{"cmd", "-v", "-race", "-file", "foo.go"}
- output, err := executeCommand(c, args...)
- if output != "" {
- t.Errorf("Unexpected output: %v", output)
- }
- if err != nil {
- t.Errorf("Unexpected error: %v", err)
- }
-
- if !reflect.DeepEqual(args, cArgs) {
- t.Errorf("Expected: %v, got: %v", args, cArgs)
- }
-}
-
-func TestPersistentFlagsOnSameCommand(t *testing.T) {
- var rootCmdArgs []string
- rootCmd := &Command{
- Use: "root",
- Args: ArbitraryArgs,
- Run: func(_ *Command, args []string) { rootCmdArgs = args },
- }
-
- var flagValue int
- rootCmd.PersistentFlags().IntVarP(&flagValue, "intf", "i", -1, "")
-
- output, err := executeCommand(rootCmd, "-i7", "one", "two")
- if output != "" {
- t.Errorf("Unexpected output: %v", output)
- }
- if err != nil {
- t.Errorf("Unexpected error: %v", err)
- }
-
- got := strings.Join(rootCmdArgs, " ")
- expected := "one two"
- if got != expected {
- t.Errorf("rootCmdArgs expected: %q, got %q", expected, got)
- }
- if flagValue != 7 {
- t.Errorf("flagValue expected: %v, got %v", 7, flagValue)
- }
-}
-
-// TestEmptyInputs checks,
-// if flags correctly parsed with blank strings in args.
-func TestEmptyInputs(t *testing.T) {
- c := &Command{Use: "c", Run: emptyRun}
-
- var flagValue int
- c.Flags().IntVarP(&flagValue, "intf", "i", -1, "")
-
- output, err := executeCommand(c, "", "-i7", "")
- if output != "" {
- t.Errorf("Unexpected output: %v", output)
- }
- if err != nil {
- t.Errorf("Unexpected error: %v", err)
- }
-
- if flagValue != 7 {
- t.Errorf("flagValue expected: %v, got %v", 7, flagValue)
- }
-}
-
-func TestOverwrittenFlag(t *testing.T) {
- // TODO: This test fails, but should work.
- t.Skip()
-
- parent := &Command{Use: "parent", Run: emptyRun}
- child := &Command{Use: "child", Run: emptyRun}
-
- parent.PersistentFlags().Bool("boolf", false, "")
- parent.PersistentFlags().Int("intf", -1, "")
- child.Flags().String("strf", "", "")
- child.Flags().Int("intf", -1, "")
-
- parent.AddCommand(child)
-
- childInherited := child.InheritedFlags()
- childLocal := child.LocalFlags()
-
- if childLocal.Lookup("strf") == nil {
- t.Error(`LocalFlags expected to contain "strf", got "nil"`)
- }
- if childInherited.Lookup("boolf") == nil {
- t.Error(`InheritedFlags expected to contain "boolf", got "nil"`)
- }
-
- if childInherited.Lookup("intf") != nil {
- t.Errorf(`InheritedFlags should not contain overwritten flag "intf"`)
- }
- if childLocal.Lookup("intf") == nil {
- t.Error(`LocalFlags expected to contain "intf", got "nil"`)
- }
-}
-
-func TestPersistentFlagsOnChild(t *testing.T) {
- var childCmdArgs []string
- rootCmd := &Command{Use: "root", Run: emptyRun}
- childCmd := &Command{
- Use: "child",
- Args: ArbitraryArgs,
- Run: func(_ *Command, args []string) { childCmdArgs = args },
- }
- rootCmd.AddCommand(childCmd)
-
- var parentFlagValue int
- var childFlagValue int
- rootCmd.PersistentFlags().IntVarP(&parentFlagValue, "parentf", "p", -1, "")
- childCmd.Flags().IntVarP(&childFlagValue, "childf", "c", -1, "")
-
- output, err := executeCommand(rootCmd, "child", "-c7", "-p8", "one", "two")
- if output != "" {
- t.Errorf("Unexpected output: %v", output)
- }
- if err != nil {
- t.Errorf("Unexpected error: %v", err)
- }
-
- got := strings.Join(childCmdArgs, " ")
- expected := "one two"
- if got != expected {
- t.Errorf("childCmdArgs expected: %q, got %q", expected, got)
- }
- if parentFlagValue != 8 {
- t.Errorf("parentFlagValue expected: %v, got %v", 8, parentFlagValue)
- }
- if childFlagValue != 7 {
- t.Errorf("childFlagValue expected: %v, got %v", 7, childFlagValue)
- }
-}
-
-func TestRequiredFlags(t *testing.T) {
- c := &Command{Use: "c", Run: emptyRun}
- c.Flags().String("foo1", "", "")
- c.MarkFlagRequired("foo1")
- c.Flags().String("foo2", "", "")
- c.MarkFlagRequired("foo2")
- c.Flags().String("bar", "", "")
-
- expected := fmt.Sprintf("required flag(s) %q, %q not set", "foo1", "foo2")
-
- _, err := executeCommand(c)
- got := err.Error()
-
- if got != expected {
- t.Errorf("Expected error: %q, got: %q", expected, got)
- }
-}
-
-func TestPersistentRequiredFlags(t *testing.T) {
- parent := &Command{Use: "parent", Run: emptyRun}
- parent.PersistentFlags().String("foo1", "", "")
- parent.MarkPersistentFlagRequired("foo1")
- parent.PersistentFlags().String("foo2", "", "")
- parent.MarkPersistentFlagRequired("foo2")
- parent.Flags().String("foo3", "", "")
-
- child := &Command{Use: "child", Run: emptyRun}
- child.Flags().String("bar1", "", "")
- child.MarkFlagRequired("bar1")
- child.Flags().String("bar2", "", "")
- child.MarkFlagRequired("bar2")
- child.Flags().String("bar3", "", "")
-
- parent.AddCommand(child)
-
- expected := fmt.Sprintf("required flag(s) %q, %q, %q, %q not set", "bar1", "bar2", "foo1", "foo2")
-
- _, err := executeCommand(parent, "child")
- if err.Error() != expected {
- t.Errorf("Expected %q, got %q", expected, err.Error())
- }
-}
-
-func TestInitHelpFlagMergesFlags(t *testing.T) {
- usage := "custom flag"
- rootCmd := &Command{Use: "root"}
- rootCmd.PersistentFlags().Bool("help", false, "custom flag")
- childCmd := &Command{Use: "child"}
- rootCmd.AddCommand(childCmd)
-
- childCmd.InitDefaultHelpFlag()
- got := childCmd.Flags().Lookup("help").Usage
- if got != usage {
- t.Errorf("Expected the help flag from the root command with usage: %v\nGot the default with usage: %v", usage, got)
- }
-}
-
-func TestHelpCommandExecuted(t *testing.T) {
- rootCmd := &Command{Use: "root", Long: "Long description", Run: emptyRun}
- rootCmd.AddCommand(&Command{Use: "child", Run: emptyRun})
-
- output, err := executeCommand(rootCmd, "help")
- if err != nil {
- t.Errorf("Unexpected error: %v", err)
- }
-
- checkStringContains(t, output, rootCmd.Long)
-}
-
-func TestHelpCommandExecutedOnChild(t *testing.T) {
- rootCmd := &Command{Use: "root", Run: emptyRun}
- childCmd := &Command{Use: "child", Long: "Long description", Run: emptyRun}
- rootCmd.AddCommand(childCmd)
-
- output, err := executeCommand(rootCmd, "help", "child")
- if err != nil {
- t.Errorf("Unexpected error: %v", err)
- }
-
- checkStringContains(t, output, childCmd.Long)
-}
-
-func TestSetHelpCommand(t *testing.T) {
- c := &Command{Use: "c", Run: emptyRun}
- c.AddCommand(&Command{Use: "empty", Run: emptyRun})
-
- expected := "WORKS"
- c.SetHelpCommand(&Command{
- Use: "help [command]",
- Short: "Help about any command",
- Long: `Help provides help for any command in the application.
- Simply type ` + c.Name() + ` help [path to command] for full details.`,
- Run: func(c *Command, _ []string) { c.Print(expected) },
- })
-
- got, err := executeCommand(c, "help")
- if err != nil {
- t.Errorf("Unexpected error: %v", err)
- }
-
- if got != expected {
- t.Errorf("Expected to contain %q, got %q", expected, got)
- }
-}
-
-func TestHelpFlagExecuted(t *testing.T) {
- rootCmd := &Command{Use: "root", Long: "Long description", Run: emptyRun}
-
- output, err := executeCommand(rootCmd, "--help")
- if err != nil {
- t.Errorf("Unexpected error: %v", err)
- }
-
- checkStringContains(t, output, rootCmd.Long)
-}
-
-func TestHelpFlagExecutedOnChild(t *testing.T) {
- rootCmd := &Command{Use: "root", Run: emptyRun}
- childCmd := &Command{Use: "child", Long: "Long description", Run: emptyRun}
- rootCmd.AddCommand(childCmd)
-
- output, err := executeCommand(rootCmd, "child", "--help")
- if err != nil {
- t.Errorf("Unexpected error: %v", err)
- }
-
- checkStringContains(t, output, childCmd.Long)
-}
-
-// TestHelpFlagInHelp checks,
-// if '--help' flag is shown in help for child (executing `parent help child`),
-// that has no other flags.
-// Related to https://github.com/spf13/cobra/issues/302.
-func TestHelpFlagInHelp(t *testing.T) {
- parentCmd := &Command{Use: "parent", Run: func(*Command, []string) {}}
-
- childCmd := &Command{Use: "child", Run: func(*Command, []string) {}}
- parentCmd.AddCommand(childCmd)
-
- output, err := executeCommand(parentCmd, "help", "child")
- if err != nil {
- t.Errorf("Unexpected error: %v", err)
- }
-
- checkStringContains(t, output, "[flags]")
-}
-
-func TestFlagsInUsage(t *testing.T) {
- rootCmd := &Command{Use: "root", Args: NoArgs, Run: func(*Command, []string) {}}
- output, err := executeCommand(rootCmd, "--help")
- if err != nil {
- t.Errorf("Unexpected error: %v", err)
- }
-
- checkStringContains(t, output, "[flags]")
-}
-
-func TestHelpExecutedOnNonRunnableChild(t *testing.T) {
- rootCmd := &Command{Use: "root", Run: emptyRun}
- childCmd := &Command{Use: "child", Long: "Long description"}
- rootCmd.AddCommand(childCmd)
-
- output, err := executeCommand(rootCmd, "child")
- if err != nil {
- t.Errorf("Unexpected error: %v", err)
- }
-
- checkStringContains(t, output, childCmd.Long)
-}
-
-func TestVersionFlagExecuted(t *testing.T) {
- rootCmd := &Command{Use: "root", Version: "1.0.0", Run: emptyRun}
-
- output, err := executeCommand(rootCmd, "--version", "arg1")
- if err != nil {
- t.Errorf("Unexpected error: %v", err)
- }
-
- checkStringContains(t, output, "root version 1.0.0")
-}
-
-func TestVersionTemplate(t *testing.T) {
- rootCmd := &Command{Use: "root", Version: "1.0.0", Run: emptyRun}
- rootCmd.SetVersionTemplate(`customized version: {{.Version}}`)
-
- output, err := executeCommand(rootCmd, "--version", "arg1")
- if err != nil {
- t.Errorf("Unexpected error: %v", err)
- }
-
- checkStringContains(t, output, "customized version: 1.0.0")
-}
-
-func TestVersionFlagExecutedOnSubcommand(t *testing.T) {
- rootCmd := &Command{Use: "root", Version: "1.0.0"}
- rootCmd.AddCommand(&Command{Use: "sub", Run: emptyRun})
-
- output, err := executeCommand(rootCmd, "--version", "sub")
- if err != nil {
- t.Errorf("Unexpected error: %v", err)
- }
-
- checkStringContains(t, output, "root version 1.0.0")
-}
-
-func TestVersionFlagOnlyAddedToRoot(t *testing.T) {
- rootCmd := &Command{Use: "root", Version: "1.0.0", Run: emptyRun}
- rootCmd.AddCommand(&Command{Use: "sub", Run: emptyRun})
-
- _, err := executeCommand(rootCmd, "sub", "--version")
- if err == nil {
- t.Errorf("Expected error")
- }
-
- checkStringContains(t, err.Error(), "unknown flag: --version")
-}
-
-func TestVersionFlagOnlyExistsIfVersionNonEmpty(t *testing.T) {
- rootCmd := &Command{Use: "root", Run: emptyRun}
-
- _, err := executeCommand(rootCmd, "--version")
- if err == nil {
- t.Errorf("Expected error")
- }
- checkStringContains(t, err.Error(), "unknown flag: --version")
-}
-
-func TestUsageIsNotPrintedTwice(t *testing.T) {
- var cmd = &Command{Use: "root"}
- var sub = &Command{Use: "sub"}
- cmd.AddCommand(sub)
-
- output, _ := executeCommand(cmd, "")
- if strings.Count(output, "Usage:") != 1 {
- t.Error("Usage output is not printed exactly once")
- }
-}
-
-func TestVisitParents(t *testing.T) {
- c := &Command{Use: "app"}
- sub := &Command{Use: "sub"}
- dsub := &Command{Use: "dsub"}
- sub.AddCommand(dsub)
- c.AddCommand(sub)
-
- total := 0
- add := func(x *Command) {
- total++
- }
- sub.VisitParents(add)
- if total != 1 {
- t.Errorf("Should have visited 1 parent but visited %d", total)
- }
-
- total = 0
- dsub.VisitParents(add)
- if total != 2 {
- t.Errorf("Should have visited 2 parents but visited %d", total)
- }
-
- total = 0
- c.VisitParents(add)
- if total != 0 {
- t.Errorf("Should have visited no parents but visited %d", total)
- }
-}
-
-func TestSuggestions(t *testing.T) {
- rootCmd := &Command{Use: "root", Run: emptyRun}
- timesCmd := &Command{
- Use: "times",
- SuggestFor: []string{"counts"},
- Run: emptyRun,
- }
- rootCmd.AddCommand(timesCmd)
-
- templateWithSuggestions := "Error: unknown command \"%s\" for \"root\"\n\nDid you mean this?\n\t%s\n\nRun 'root --help' for usage.\n"
- templateWithoutSuggestions := "Error: unknown command \"%s\" for \"root\"\nRun 'root --help' for usage.\n"
-
- tests := map[string]string{
- "time": "times",
- "tiems": "times",
- "tims": "times",
- "timeS": "times",
- "rimes": "times",
- "ti": "times",
- "t": "times",
- "timely": "times",
- "ri": "",
- "timezone": "",
- "foo": "",
- "counts": "times",
- }
-
- for typo, suggestion := range tests {
- for _, suggestionsDisabled := range []bool{true, false} {
- rootCmd.DisableSuggestions = suggestionsDisabled
-
- var expected string
- output, _ := executeCommand(rootCmd, typo)
-
- if suggestion == "" || suggestionsDisabled {
- expected = fmt.Sprintf(templateWithoutSuggestions, typo)
- } else {
- expected = fmt.Sprintf(templateWithSuggestions, typo, suggestion)
- }
-
- if output != expected {
- t.Errorf("Unexpected response.\nExpected:\n %q\nGot:\n %q\n", expected, output)
- }
- }
- }
-}
-
-func TestRemoveCommand(t *testing.T) {
- rootCmd := &Command{Use: "root", Args: NoArgs, Run: emptyRun}
- childCmd := &Command{Use: "child", Run: emptyRun}
- rootCmd.AddCommand(childCmd)
- rootCmd.RemoveCommand(childCmd)
-
- _, err := executeCommand(rootCmd, "child")
- if err == nil {
- t.Error("Expected error on calling removed command. Got nil.")
- }
-}
-
-func TestReplaceCommandWithRemove(t *testing.T) {
- childUsed := 0
- rootCmd := &Command{Use: "root", Run: emptyRun}
- child1Cmd := &Command{
- Use: "child",
- Run: func(*Command, []string) { childUsed = 1 },
- }
- child2Cmd := &Command{
- Use: "child",
- Run: func(*Command, []string) { childUsed = 2 },
- }
- rootCmd.AddCommand(child1Cmd)
- rootCmd.RemoveCommand(child1Cmd)
- rootCmd.AddCommand(child2Cmd)
-
- output, err := executeCommand(rootCmd, "child")
- if output != "" {
- t.Errorf("Unexpected output: %v", output)
- }
- if err != nil {
- t.Errorf("Unexpected error: %v", err)
- }
-
- if childUsed == 1 {
- t.Error("Removed command shouldn't be called")
- }
- if childUsed != 2 {
- t.Error("Replacing command should have been called but didn't")
- }
-}
-
-func TestDeprecatedCommand(t *testing.T) {
- rootCmd := &Command{Use: "root", Run: emptyRun}
- deprecatedCmd := &Command{
- Use: "deprecated",
- Deprecated: "This command is deprecated",
- Run: emptyRun,
- }
- rootCmd.AddCommand(deprecatedCmd)
-
- output, err := executeCommand(rootCmd, "deprecated")
- if err != nil {
- t.Errorf("Unexpected error: %v", err)
- }
-
- checkStringContains(t, output, deprecatedCmd.Deprecated)
-}
-
-func TestHooks(t *testing.T) {
- var (
- persPreArgs string
- preArgs string
- runArgs string
- postArgs string
- persPostArgs string
- )
-
- c := &Command{
- Use: "c",
- PersistentPreRun: func(_ *Command, args []string) {
- persPreArgs = strings.Join(args, " ")
- },
- PreRun: func(_ *Command, args []string) {
- preArgs = strings.Join(args, " ")
- },
- Run: func(_ *Command, args []string) {
- runArgs = strings.Join(args, " ")
- },
- PostRun: func(_ *Command, args []string) {
- postArgs = strings.Join(args, " ")
- },
- PersistentPostRun: func(_ *Command, args []string) {
- persPostArgs = strings.Join(args, " ")
- },
- }
-
- output, err := executeCommand(c, "one", "two")
- if output != "" {
- t.Errorf("Unexpected output: %v", output)
- }
- if err != nil {
- t.Errorf("Unexpected error: %v", err)
- }
-
- if persPreArgs != "one two" {
- t.Errorf("Expected persPreArgs %q, got %q", "one two", persPreArgs)
- }
- if preArgs != "one two" {
- t.Errorf("Expected preArgs %q, got %q", "one two", preArgs)
- }
- if runArgs != "one two" {
- t.Errorf("Expected runArgs %q, got %q", "one two", runArgs)
- }
- if postArgs != "one two" {
- t.Errorf("Expected postArgs %q, got %q", "one two", postArgs)
- }
- if persPostArgs != "one two" {
- t.Errorf("Expected persPostArgs %q, got %q", "one two", persPostArgs)
- }
-}
-
-func TestPersistentHooks(t *testing.T) {
- var (
- parentPersPreArgs string
- parentPreArgs string
- parentRunArgs string
- parentPostArgs string
- parentPersPostArgs string
- )
-
- var (
- childPersPreArgs string
- childPreArgs string
- childRunArgs string
- childPostArgs string
- childPersPostArgs string
- )
-
- parentCmd := &Command{
- Use: "parent",
- PersistentPreRun: func(_ *Command, args []string) {
- parentPersPreArgs = strings.Join(args, " ")
- },
- PreRun: func(_ *Command, args []string) {
- parentPreArgs = strings.Join(args, " ")
- },
- Run: func(_ *Command, args []string) {
- parentRunArgs = strings.Join(args, " ")
- },
- PostRun: func(_ *Command, args []string) {
- parentPostArgs = strings.Join(args, " ")
- },
- PersistentPostRun: func(_ *Command, args []string) {
- parentPersPostArgs = strings.Join(args, " ")
- },
- }
-
- childCmd := &Command{
- Use: "child",
- PersistentPreRun: func(_ *Command, args []string) {
- childPersPreArgs = strings.Join(args, " ")
- },
- PreRun: func(_ *Command, args []string) {
- childPreArgs = strings.Join(args, " ")
- },
- Run: func(_ *Command, args []string) {
- childRunArgs = strings.Join(args, " ")
- },
- PostRun: func(_ *Command, args []string) {
- childPostArgs = strings.Join(args, " ")
- },
- PersistentPostRun: func(_ *Command, args []string) {
- childPersPostArgs = strings.Join(args, " ")
- },
- }
- parentCmd.AddCommand(childCmd)
-
- output, err := executeCommand(parentCmd, "child", "one", "two")
- if output != "" {
- t.Errorf("Unexpected output: %v", output)
- }
- if err != nil {
- t.Errorf("Unexpected error: %v", err)
- }
-
- // TODO: This test fails, but should not.
- // Related to https://github.com/spf13/cobra/issues/252.
- //
- // if parentPersPreArgs != "one two" {
- // t.Errorf("Expected parentPersPreArgs %q, got %q", "one two", parentPersPreArgs)
- // }
- if parentPreArgs != "" {
- t.Errorf("Expected blank parentPreArgs, got %q", parentPreArgs)
- }
- if parentRunArgs != "" {
- t.Errorf("Expected blank parentRunArgs, got %q", parentRunArgs)
- }
- if parentPostArgs != "" {
- t.Errorf("Expected blank parentPostArgs, got %q", parentPostArgs)
- }
- // TODO: This test fails, but should not.
- // Related to https://github.com/spf13/cobra/issues/252.
- //
- // if parentPersPostArgs != "one two" {
- // t.Errorf("Expected parentPersPostArgs %q, got %q", "one two", parentPersPostArgs)
- // }
-
- if childPersPreArgs != "one two" {
- t.Errorf("Expected childPersPreArgs %q, got %q", "one two", childPersPreArgs)
- }
- if childPreArgs != "one two" {
- t.Errorf("Expected childPreArgs %q, got %q", "one two", childPreArgs)
- }
- if childRunArgs != "one two" {
- t.Errorf("Expected childRunArgs %q, got %q", "one two", childRunArgs)
- }
- if childPostArgs != "one two" {
- t.Errorf("Expected childPostArgs %q, got %q", "one two", childPostArgs)
- }
- if childPersPostArgs != "one two" {
- t.Errorf("Expected childPersPostArgs %q, got %q", "one two", childPersPostArgs)
- }
-}
-
-// Related to https://github.com/spf13/cobra/issues/521.
-func TestGlobalNormFuncPropagation(t *testing.T) {
- normFunc := func(f *pflag.FlagSet, name string) pflag.NormalizedName {
- return pflag.NormalizedName(name)
- }
-
- rootCmd := &Command{Use: "root", Run: emptyRun}
- childCmd := &Command{Use: "child", Run: emptyRun}
- rootCmd.AddCommand(childCmd)
-
- rootCmd.SetGlobalNormalizationFunc(normFunc)
- if reflect.ValueOf(normFunc).Pointer() != reflect.ValueOf(rootCmd.GlobalNormalizationFunc()).Pointer() {
- t.Error("rootCmd seems to have a wrong normalization function")
- }
-
- if reflect.ValueOf(normFunc).Pointer() != reflect.ValueOf(childCmd.GlobalNormalizationFunc()).Pointer() {
- t.Error("childCmd should have had the normalization function of rootCmd")
- }
-}
-
-// Related to https://github.com/spf13/cobra/issues/521.
-func TestNormPassedOnLocal(t *testing.T) {
- toUpper := func(f *pflag.FlagSet, name string) pflag.NormalizedName {
- return pflag.NormalizedName(strings.ToUpper(name))
- }
-
- c := &Command{}
- c.Flags().Bool("flagname", true, "this is a dummy flag")
- c.SetGlobalNormalizationFunc(toUpper)
- if c.LocalFlags().Lookup("flagname") != c.LocalFlags().Lookup("FLAGNAME") {
- t.Error("Normalization function should be passed on to Local flag set")
- }
-}
-
-// Related to https://github.com/spf13/cobra/issues/521.
-func TestNormPassedOnInherited(t *testing.T) {
- toUpper := func(f *pflag.FlagSet, name string) pflag.NormalizedName {
- return pflag.NormalizedName(strings.ToUpper(name))
- }
-
- c := &Command{}
- c.SetGlobalNormalizationFunc(toUpper)
-
- child1 := &Command{}
- c.AddCommand(child1)
-
- c.PersistentFlags().Bool("flagname", true, "")
-
- child2 := &Command{}
- c.AddCommand(child2)
-
- inherited := child1.InheritedFlags()
- if inherited.Lookup("flagname") == nil || inherited.Lookup("flagname") != inherited.Lookup("FLAGNAME") {
- t.Error("Normalization function should be passed on to inherited flag set in command added before flag")
- }
-
- inherited = child2.InheritedFlags()
- if inherited.Lookup("flagname") == nil || inherited.Lookup("flagname") != inherited.Lookup("FLAGNAME") {
- t.Error("Normalization function should be passed on to inherited flag set in command added after flag")
- }
-}
-
-// Related to https://github.com/spf13/cobra/issues/521.
-func TestConsistentNormalizedName(t *testing.T) {
- toUpper := func(f *pflag.FlagSet, name string) pflag.NormalizedName {
- return pflag.NormalizedName(strings.ToUpper(name))
- }
- n := func(f *pflag.FlagSet, name string) pflag.NormalizedName {
- return pflag.NormalizedName(name)
- }
-
- c := &Command{}
- c.Flags().Bool("flagname", true, "")
- c.SetGlobalNormalizationFunc(toUpper)
- c.SetGlobalNormalizationFunc(n)
-
- if c.LocalFlags().Lookup("flagname") == c.LocalFlags().Lookup("FLAGNAME") {
- t.Error("Normalizing flag names should not result in duplicate flags")
- }
-}
-
-func TestFlagOnPflagCommandLine(t *testing.T) {
- flagName := "flagOnCommandLine"
- pflag.String(flagName, "", "about my flag")
-
- c := &Command{Use: "c", Run: emptyRun}
- c.AddCommand(&Command{Use: "child", Run: emptyRun})
-
- output, _ := executeCommand(c, "--help")
- checkStringContains(t, output, flagName)
-
- resetCommandLineFlagSet()
-}
-
-// TestHiddenCommandExecutes checks,
-// if hidden commands run as intended.
-func TestHiddenCommandExecutes(t *testing.T) {
- executed := false
- c := &Command{
- Use: "c",
- Hidden: true,
- Run: func(*Command, []string) { executed = true },
- }
-
- output, err := executeCommand(c)
- if output != "" {
- t.Errorf("Unexpected output: %v", output)
- }
- if err != nil {
- t.Errorf("Unexpected error: %v", err)
- }
-
- if !executed {
- t.Error("Hidden command should have been executed")
- }
-}
-
-// test to ensure hidden commands do not show up in usage/help text
-func TestHiddenCommandIsHidden(t *testing.T) {
- c := &Command{Use: "c", Hidden: true, Run: emptyRun}
- if c.IsAvailableCommand() {
- t.Errorf("Hidden command should be unavailable")
- }
-}
-
-func TestCommandsAreSorted(t *testing.T) {
- EnableCommandSorting = true
-
- originalNames := []string{"middle", "zlast", "afirst"}
- expectedNames := []string{"afirst", "middle", "zlast"}
-
- var rootCmd = &Command{Use: "root"}
-
- for _, name := range originalNames {
- rootCmd.AddCommand(&Command{Use: name})
- }
-
- for i, c := range rootCmd.Commands() {
- got := c.Name()
- if expectedNames[i] != got {
- t.Errorf("Expected: %s, got: %s", expectedNames[i], got)
- }
- }
-
- EnableCommandSorting = true
-}
-
-func TestEnableCommandSortingIsDisabled(t *testing.T) {
- EnableCommandSorting = false
-
- originalNames := []string{"middle", "zlast", "afirst"}
-
- var rootCmd = &Command{Use: "root"}
-
- for _, name := range originalNames {
- rootCmd.AddCommand(&Command{Use: name})
- }
-
- for i, c := range rootCmd.Commands() {
- got := c.Name()
- if originalNames[i] != got {
- t.Errorf("expected: %s, got: %s", originalNames[i], got)
- }
- }
-
- EnableCommandSorting = true
-}
-
-func TestSetOutput(t *testing.T) {
- c := &Command{}
- c.SetOutput(nil)
- if out := c.OutOrStdout(); out != os.Stdout {
- t.Errorf("Expected setting output to nil to revert back to stdout")
- }
-}
-
-func TestFlagErrorFunc(t *testing.T) {
- c := &Command{Use: "c", Run: emptyRun}
-
- expectedFmt := "This is expected: %v"
- c.SetFlagErrorFunc(func(_ *Command, err error) error {
- return fmt.Errorf(expectedFmt, err)
- })
-
- _, err := executeCommand(c, "--unknown-flag")
-
- got := err.Error()
- expected := fmt.Sprintf(expectedFmt, "unknown flag: --unknown-flag")
- if got != expected {
- t.Errorf("Expected %v, got %v", expected, got)
- }
-}
-
-// TestSortedFlags checks,
-// if cmd.LocalFlags() is unsorted when cmd.Flags().SortFlags set to false.
-// Related to https://github.com/spf13/cobra/issues/404.
-func TestSortedFlags(t *testing.T) {
- c := &Command{}
- c.Flags().SortFlags = false
- names := []string{"C", "B", "A", "D"}
- for _, name := range names {
- c.Flags().Bool(name, false, "")
- }
-
- i := 0
- c.LocalFlags().VisitAll(func(f *pflag.Flag) {
- if i == len(names) {
- return
- }
- if stringInSlice(f.Name, names) {
- if names[i] != f.Name {
- t.Errorf("Incorrect order. Expected %v, got %v", names[i], f.Name)
- }
- i++
- }
- })
-}
-
-// TestMergeCommandLineToFlags checks,
-// if pflag.CommandLine is correctly merged to c.Flags() after first call
-// of c.mergePersistentFlags.
-// Related to https://github.com/spf13/cobra/issues/443.
-func TestMergeCommandLineToFlags(t *testing.T) {
- pflag.Bool("boolflag", false, "")
- c := &Command{Use: "c", Run: emptyRun}
- c.mergePersistentFlags()
- if c.Flags().Lookup("boolflag") == nil {
- t.Fatal("Expecting to have flag from CommandLine in c.Flags()")
- }
-
- resetCommandLineFlagSet()
-}
-
-// TestUseDeprecatedFlags checks,
-// if cobra.Execute() prints a message, if a deprecated flag is used.
-// Related to https://github.com/spf13/cobra/issues/463.
-func TestUseDeprecatedFlags(t *testing.T) {
- c := &Command{Use: "c", Run: emptyRun}
- c.Flags().BoolP("deprecated", "d", false, "deprecated flag")
- c.Flags().MarkDeprecated("deprecated", "This flag is deprecated")
-
- output, err := executeCommand(c, "c", "-d")
- if err != nil {
- t.Error("Unexpected error:", err)
- }
- checkStringContains(t, output, "This flag is deprecated")
-}
-
-func TestTraverseWithParentFlags(t *testing.T) {
- rootCmd := &Command{Use: "root", TraverseChildren: true}
- rootCmd.Flags().String("str", "", "")
- rootCmd.Flags().BoolP("bool", "b", false, "")
-
- childCmd := &Command{Use: "child"}
- childCmd.Flags().Int("int", -1, "")
-
- rootCmd.AddCommand(childCmd)
-
- c, args, err := rootCmd.Traverse([]string{"-b", "--str", "ok", "child", "--int"})
- if err != nil {
- t.Errorf("Unexpected error: %v", err)
- }
- if len(args) != 1 && args[0] != "--add" {
- t.Errorf("Wrong args: %v", args)
- }
- if c.Name() != childCmd.Name() {
- t.Errorf("Expected command: %q, got: %q", childCmd.Name(), c.Name())
- }
-}
-
-func TestTraverseNoParentFlags(t *testing.T) {
- rootCmd := &Command{Use: "root", TraverseChildren: true}
- rootCmd.Flags().String("foo", "", "foo things")
-
- childCmd := &Command{Use: "child"}
- childCmd.Flags().String("str", "", "")
- rootCmd.AddCommand(childCmd)
-
- c, args, err := rootCmd.Traverse([]string{"child"})
- if err != nil {
- t.Errorf("Unexpected error: %v", err)
- }
- if len(args) != 0 {
- t.Errorf("Wrong args %v", args)
- }
- if c.Name() != childCmd.Name() {
- t.Errorf("Expected command: %q, got: %q", childCmd.Name(), c.Name())
- }
-}
-
-func TestTraverseWithBadParentFlags(t *testing.T) {
- rootCmd := &Command{Use: "root", TraverseChildren: true}
-
- childCmd := &Command{Use: "child"}
- childCmd.Flags().String("str", "", "")
- rootCmd.AddCommand(childCmd)
-
- expected := "unknown flag: --str"
-
- c, _, err := rootCmd.Traverse([]string{"--str", "ok", "child"})
- if err == nil || !strings.Contains(err.Error(), expected) {
- t.Errorf("Expected error, %q, got %q", expected, err)
- }
- if c != nil {
- t.Errorf("Expected nil command")
- }
-}
-
-func TestTraverseWithBadChildFlag(t *testing.T) {
- rootCmd := &Command{Use: "root", TraverseChildren: true}
- rootCmd.Flags().String("str", "", "")
-
- childCmd := &Command{Use: "child"}
- rootCmd.AddCommand(childCmd)
-
- // Expect no error because the last commands args shouldn't be parsed in
- // Traverse.
- c, args, err := rootCmd.Traverse([]string{"child", "--str"})
- if err != nil {
- t.Errorf("Unexpected error: %v", err)
- }
- if len(args) != 1 && args[0] != "--str" {
- t.Errorf("Wrong args: %v", args)
- }
- if c.Name() != childCmd.Name() {
- t.Errorf("Expected command %q, got: %q", childCmd.Name(), c.Name())
- }
-}
-
-func TestTraverseWithTwoSubcommands(t *testing.T) {
- rootCmd := &Command{Use: "root", TraverseChildren: true}
-
- subCmd := &Command{Use: "sub", TraverseChildren: true}
- rootCmd.AddCommand(subCmd)
-
- subsubCmd := &Command{
- Use: "subsub",
- }
- subCmd.AddCommand(subsubCmd)
-
- c, _, err := rootCmd.Traverse([]string{"sub", "subsub"})
- if err != nil {
- t.Fatalf("Unexpected error: %v", err)
- }
- if c.Name() != subsubCmd.Name() {
- t.Fatalf("Expected command: %q, got %q", subsubCmd.Name(), c.Name())
- }
-}
-
-// TestUpdateName checks if c.Name() updates on changed c.Use.
-// Related to https://github.com/spf13/cobra/pull/422#discussion_r143918343.
-func TestUpdateName(t *testing.T) {
- c := &Command{Use: "name xyz"}
- originalName := c.Name()
-
- c.Use = "changedName abc"
- if originalName == c.Name() || c.Name() != "changedName" {
- t.Error("c.Name() should be updated on changed c.Use")
- }
-}
-
-type calledAsTestcase struct {
- args []string
- call string
- want string
- epm bool
- tc bool
-}
-
-func (tc *calledAsTestcase) test(t *testing.T) {
- defer func(ov bool) { EnablePrefixMatching = ov }(EnablePrefixMatching)
- EnablePrefixMatching = tc.epm
-
- var called *Command
- run := func(c *Command, _ []string) { t.Logf("called: %q", c.Name()); called = c }
-
- parent := &Command{Use: "parent", Run: run}
- child1 := &Command{Use: "child1", Run: run, Aliases: []string{"this"}}
- child2 := &Command{Use: "child2", Run: run, Aliases: []string{"that"}}
-
- parent.AddCommand(child1)
- parent.AddCommand(child2)
- parent.SetArgs(tc.args)
-
- output := new(bytes.Buffer)
- parent.SetOutput(output)
-
- parent.Execute()
-
- if called == nil {
- if tc.call != "" {
- t.Errorf("missing expected call to command: %s", tc.call)
- }
- return
- }
-
- if called.Name() != tc.call {
- t.Errorf("called command == %q; Wanted %q", called.Name(), tc.call)
- } else if got := called.CalledAs(); got != tc.want {
- t.Errorf("%s.CalledAs() == %q; Wanted: %q", tc.call, got, tc.want)
- }
-}
-
-func TestCalledAs(t *testing.T) {
- tests := map[string]calledAsTestcase{
- "find/no-args": {nil, "parent", "parent", false, false},
- "find/real-name": {[]string{"child1"}, "child1", "child1", false, false},
- "find/full-alias": {[]string{"that"}, "child2", "that", false, false},
- "find/part-no-prefix": {[]string{"thi"}, "", "", false, false},
- "find/part-alias": {[]string{"thi"}, "child1", "this", true, false},
- "find/conflict": {[]string{"th"}, "", "", true, false},
- "traverse/no-args": {nil, "parent", "parent", false, true},
- "traverse/real-name": {[]string{"child1"}, "child1", "child1", false, true},
- "traverse/full-alias": {[]string{"that"}, "child2", "that", false, true},
- "traverse/part-no-prefix": {[]string{"thi"}, "", "", false, true},
- "traverse/part-alias": {[]string{"thi"}, "child1", "this", true, true},
- "traverse/conflict": {[]string{"th"}, "", "", true, true},
- }
-
- for name, tc := range tests {
- t.Run(name, tc.test)
- }
-}
diff --git a/vendor/github.com/spf13/cobra/doc/cmd_test.go b/vendor/github.com/spf13/cobra/doc/cmd_test.go
deleted file mode 100644
index d29c577df..000000000
--- a/vendor/github.com/spf13/cobra/doc/cmd_test.go
+++ /dev/null
@@ -1,86 +0,0 @@
-package doc
-
-import (
- "strings"
- "testing"
-
- "github.com/spf13/cobra"
-)
-
-func emptyRun(*cobra.Command, []string) {}
-
-func init() {
- rootCmd.PersistentFlags().StringP("rootflag", "r", "two", "")
- rootCmd.PersistentFlags().StringP("strtwo", "t", "two", "help message for parent flag strtwo")
-
- echoCmd.PersistentFlags().StringP("strone", "s", "one", "help message for flag strone")
- echoCmd.PersistentFlags().BoolP("persistentbool", "p", false, "help message for flag persistentbool")
- echoCmd.Flags().IntP("intone", "i", 123, "help message for flag intone")
- echoCmd.Flags().BoolP("boolone", "b", true, "help message for flag boolone")
-
- timesCmd.PersistentFlags().StringP("strtwo", "t", "2", "help message for child flag strtwo")
- timesCmd.Flags().IntP("inttwo", "j", 234, "help message for flag inttwo")
- timesCmd.Flags().BoolP("booltwo", "c", false, "help message for flag booltwo")
-
- printCmd.PersistentFlags().StringP("strthree", "s", "three", "help message for flag strthree")
- printCmd.Flags().IntP("intthree", "i", 345, "help message for flag intthree")
- printCmd.Flags().BoolP("boolthree", "b", true, "help message for flag boolthree")
-
- echoCmd.AddCommand(timesCmd, echoSubCmd, deprecatedCmd)
- rootCmd.AddCommand(printCmd, echoCmd)
-}
-
-var rootCmd = &cobra.Command{
- Use: "root",
- Short: "Root short description",
- Long: "Root long description",
- Run: emptyRun,
-}
-
-var echoCmd = &cobra.Command{
- Use: "echo [string to echo]",
- Aliases: []string{"say"},
- Short: "Echo anything to the screen",
- Long: "an utterly useless command for testing",
- Example: "Just run cobra-test echo",
-}
-
-var echoSubCmd = &cobra.Command{
- Use: "echosub [string to print]",
- Short: "second sub command for echo",
- Long: "an absolutely utterly useless command for testing gendocs!.",
- Run: emptyRun,
-}
-
-var timesCmd = &cobra.Command{
- Use: "times [# times] [string to echo]",
- SuggestFor: []string{"counts"},
- Short: "Echo anything to the screen more times",
- Long: `a slightly useless command for testing.`,
- Run: emptyRun,
-}
-
-var deprecatedCmd = &cobra.Command{
- Use: "deprecated [can't do anything here]",
- Short: "A command which is deprecated",
- Long: `an absolutely utterly useless command for testing deprecation!.`,
- Deprecated: "Please use echo instead",
-}
-
-var printCmd = &cobra.Command{
- Use: "print [string to print]",
- Short: "Print anything to the screen",
- Long: `an absolutely utterly useless command for testing.`,
-}
-
-func checkStringContains(t *testing.T, got, expected string) {
- if !strings.Contains(got, expected) {
- t.Errorf("Expected to contain: \n %v\nGot:\n %v\n", expected, got)
- }
-}
-
-func checkStringOmits(t *testing.T, got, expected string) {
- if strings.Contains(got, expected) {
- t.Errorf("Expected to not contain: \n %v\nGot: %v", expected, got)
- }
-}
diff --git a/vendor/github.com/spf13/cobra/doc/man_docs.go b/vendor/github.com/spf13/cobra/doc/man_docs.go
deleted file mode 100644
index ce92332dd..000000000
--- a/vendor/github.com/spf13/cobra/doc/man_docs.go
+++ /dev/null
@@ -1,236 +0,0 @@
-// Copyright 2015 Red Hat Inc. All rights reserved.
-//
-// 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 doc
-
-import (
- "bytes"
- "fmt"
- "io"
- "os"
- "path/filepath"
- "sort"
- "strings"
- "time"
-
- "github.com/cpuguy83/go-md2man/md2man"
- "github.com/spf13/cobra"
- "github.com/spf13/pflag"
-)
-
-// GenManTree will generate a man page for this command and all descendants
-// in the directory given. The header may be nil. This function may not work
-// correctly if your command names have `-` in them. If you have `cmd` with two
-// subcmds, `sub` and `sub-third`, and `sub` has a subcommand called `third`
-// it is undefined which help output will be in the file `cmd-sub-third.1`.
-func GenManTree(cmd *cobra.Command, header *GenManHeader, dir string) error {
- return GenManTreeFromOpts(cmd, GenManTreeOptions{
- Header: header,
- Path: dir,
- CommandSeparator: "-",
- })
-}
-
-// GenManTreeFromOpts generates a man page for the command and all descendants.
-// The pages are written to the opts.Path directory.
-func GenManTreeFromOpts(cmd *cobra.Command, opts GenManTreeOptions) error {
- header := opts.Header
- if header == nil {
- header = &GenManHeader{}
- }
- for _, c := range cmd.Commands() {
- if !c.IsAvailableCommand() || c.IsAdditionalHelpTopicCommand() {
- continue
- }
- if err := GenManTreeFromOpts(c, opts); err != nil {
- return err
- }
- }
- section := "1"
- if header.Section != "" {
- section = header.Section
- }
-
- separator := "_"
- if opts.CommandSeparator != "" {
- separator = opts.CommandSeparator
- }
- basename := strings.Replace(cmd.CommandPath(), " ", separator, -1)
- filename := filepath.Join(opts.Path, basename+"."+section)
- f, err := os.Create(filename)
- if err != nil {
- return err
- }
- defer f.Close()
-
- headerCopy := *header
- return GenMan(cmd, &headerCopy, f)
-}
-
-// GenManTreeOptions is the options for generating the man pages.
-// Used only in GenManTreeFromOpts.
-type GenManTreeOptions struct {
- Header *GenManHeader
- Path string
- CommandSeparator string
-}
-
-// GenManHeader is a lot like the .TH header at the start of man pages. These
-// include the title, section, date, source, and manual. We will use the
-// current time if Date if unset and will use "Auto generated by spf13/cobra"
-// if the Source is unset.
-type GenManHeader struct {
- Title string
- Section string
- Date *time.Time
- date string
- Source string
- Manual string
-}
-
-// GenMan will generate a man page for the given command and write it to
-// w. The header argument may be nil, however obviously w may not.
-func GenMan(cmd *cobra.Command, header *GenManHeader, w io.Writer) error {
- if header == nil {
- header = &GenManHeader{}
- }
- fillHeader(header, cmd.CommandPath())
-
- b := genMan(cmd, header)
- _, err := w.Write(md2man.Render(b))
- return err
-}
-
-func fillHeader(header *GenManHeader, name string) {
- if header.Title == "" {
- header.Title = strings.ToUpper(strings.Replace(name, " ", "\\-", -1))
- }
- if header.Section == "" {
- header.Section = "1"
- }
- if header.Date == nil {
- now := time.Now()
- header.Date = &now
- }
- header.date = (*header.Date).Format("Jan 2006")
- if header.Source == "" {
- header.Source = "Auto generated by spf13/cobra"
- }
-}
-
-func manPreamble(buf *bytes.Buffer, header *GenManHeader, cmd *cobra.Command, dashedName string) {
- description := cmd.Long
- if len(description) == 0 {
- description = cmd.Short
- }
-
- buf.WriteString(fmt.Sprintf(`%% %s(%s)%s
-%% %s
-%% %s
-# NAME
-`, header.Title, header.Section, header.date, header.Source, header.Manual))
- buf.WriteString(fmt.Sprintf("%s \\- %s\n\n", dashedName, cmd.Short))
- buf.WriteString("# SYNOPSIS\n")
- buf.WriteString(fmt.Sprintf("**%s**\n\n", cmd.UseLine()))
- buf.WriteString("# DESCRIPTION\n")
- buf.WriteString(description + "\n\n")
-}
-
-func manPrintFlags(buf *bytes.Buffer, flags *pflag.FlagSet) {
- flags.VisitAll(func(flag *pflag.Flag) {
- if len(flag.Deprecated) > 0 || flag.Hidden {
- return
- }
- format := ""
- if len(flag.Shorthand) > 0 && len(flag.ShorthandDeprecated) == 0 {
- format = fmt.Sprintf("**-%s**, **--%s**", flag.Shorthand, flag.Name)
- } else {
- format = fmt.Sprintf("**--%s**", flag.Name)
- }
- if len(flag.NoOptDefVal) > 0 {
- format += "["
- }
- if flag.Value.Type() == "string" {
- // put quotes on the value
- format += "=%q"
- } else {
- format += "=%s"
- }
- if len(flag.NoOptDefVal) > 0 {
- format += "]"
- }
- format += "\n\t%s\n\n"
- buf.WriteString(fmt.Sprintf(format, flag.DefValue, flag.Usage))
- })
-}
-
-func manPrintOptions(buf *bytes.Buffer, command *cobra.Command) {
- flags := command.NonInheritedFlags()
- if flags.HasFlags() {
- buf.WriteString("# OPTIONS\n")
- manPrintFlags(buf, flags)
- buf.WriteString("\n")
- }
- flags = command.InheritedFlags()
- if flags.HasFlags() {
- buf.WriteString("# OPTIONS INHERITED FROM PARENT COMMANDS\n")
- manPrintFlags(buf, flags)
- buf.WriteString("\n")
- }
-}
-
-func genMan(cmd *cobra.Command, header *GenManHeader) []byte {
- cmd.InitDefaultHelpCmd()
- cmd.InitDefaultHelpFlag()
-
- // something like `rootcmd-subcmd1-subcmd2`
- dashCommandName := strings.Replace(cmd.CommandPath(), " ", "-", -1)
-
- buf := new(bytes.Buffer)
-
- manPreamble(buf, header, cmd, dashCommandName)
- manPrintOptions(buf, cmd)
- if len(cmd.Example) > 0 {
- buf.WriteString("# EXAMPLE\n")
- buf.WriteString(fmt.Sprintf("```\n%s\n```\n", cmd.Example))
- }
- if hasSeeAlso(cmd) {
- buf.WriteString("# SEE ALSO\n")
- seealsos := make([]string, 0)
- if cmd.HasParent() {
- parentPath := cmd.Parent().CommandPath()
- dashParentPath := strings.Replace(parentPath, " ", "-", -1)
- seealso := fmt.Sprintf("**%s(%s)**", dashParentPath, header.Section)
- seealsos = append(seealsos, seealso)
- cmd.VisitParents(func(c *cobra.Command) {
- if c.DisableAutoGenTag {
- cmd.DisableAutoGenTag = c.DisableAutoGenTag
- }
- })
- }
- children := cmd.Commands()
- sort.Sort(byName(children))
- for _, c := range children {
- if !c.IsAvailableCommand() || c.IsAdditionalHelpTopicCommand() {
- continue
- }
- seealso := fmt.Sprintf("**%s-%s(%s)**", dashCommandName, c.Name(), header.Section)
- seealsos = append(seealsos, seealso)
- }
- buf.WriteString(strings.Join(seealsos, ", ") + "\n")
- }
- if !cmd.DisableAutoGenTag {
- buf.WriteString(fmt.Sprintf("# HISTORY\n%s Auto generated by spf13/cobra\n", header.Date.Format("2-Jan-2006")))
- }
- return buf.Bytes()
-}
diff --git a/vendor/github.com/spf13/cobra/doc/man_docs.md b/vendor/github.com/spf13/cobra/doc/man_docs.md
deleted file mode 100644
index 3709160f3..000000000
--- a/vendor/github.com/spf13/cobra/doc/man_docs.md
+++ /dev/null
@@ -1,31 +0,0 @@
-# Generating Man Pages For Your Own cobra.Command
-
-Generating man pages from a cobra command is incredibly easy. An example is as follows:
-
-```go
-package main
-
-import (
- "log"
-
- "github.com/spf13/cobra"
- "github.com/spf13/cobra/doc"
-)
-
-func main() {
- cmd := &cobra.Command{
- Use: "test",
- Short: "my test program",
- }
- header := &doc.GenManHeader{
- Title: "MINE",
- Section: "3",
- }
- err := doc.GenManTree(cmd, header, "/tmp")
- if err != nil {
- log.Fatal(err)
- }
-}
-```
-
-That will get you a man page `/tmp/test.3`
diff --git a/vendor/github.com/spf13/cobra/doc/man_docs_test.go b/vendor/github.com/spf13/cobra/doc/man_docs_test.go
deleted file mode 100644
index 62f85e47f..000000000
--- a/vendor/github.com/spf13/cobra/doc/man_docs_test.go
+++ /dev/null
@@ -1,177 +0,0 @@
-package doc
-
-import (
- "bufio"
- "bytes"
- "fmt"
- "io/ioutil"
- "os"
- "path/filepath"
- "strings"
- "testing"
-
- "github.com/spf13/cobra"
-)
-
-func translate(in string) string {
- return strings.Replace(in, "-", "\\-", -1)
-}
-
-func TestGenManDoc(t *testing.T) {
- header := &GenManHeader{
- Title: "Project",
- Section: "2",
- }
-
- // We generate on a subcommand so we have both subcommands and parents
- buf := new(bytes.Buffer)
- if err := GenMan(echoCmd, header, buf); err != nil {
- t.Fatal(err)
- }
- output := buf.String()
-
- // Make sure parent has - in CommandPath() in SEE ALSO:
- parentPath := echoCmd.Parent().CommandPath()
- dashParentPath := strings.Replace(parentPath, " ", "-", -1)
- expected := translate(dashParentPath)
- expected = expected + "(" + header.Section + ")"
- checkStringContains(t, output, expected)
-
- checkStringContains(t, output, translate(echoCmd.Name()))
- checkStringContains(t, output, translate(echoCmd.Name()))
- checkStringContains(t, output, "boolone")
- checkStringContains(t, output, "rootflag")
- checkStringContains(t, output, translate(rootCmd.Name()))
- checkStringContains(t, output, translate(echoSubCmd.Name()))
- checkStringOmits(t, output, translate(deprecatedCmd.Name()))
- checkStringContains(t, output, translate("Auto generated"))
-}
-
-func TestGenManNoGenTag(t *testing.T) {
- echoCmd.DisableAutoGenTag = true
- defer func() { echoCmd.DisableAutoGenTag = false }()
-
- header := &GenManHeader{
- Title: "Project",
- Section: "2",
- }
-
- // We generate on a subcommand so we have both subcommands and parents
- buf := new(bytes.Buffer)
- if err := GenMan(echoCmd, header, buf); err != nil {
- t.Fatal(err)
- }
- output := buf.String()
-
- unexpected := translate("#HISTORY")
- checkStringOmits(t, output, unexpected)
-}
-
-func TestGenManSeeAlso(t *testing.T) {
- rootCmd := &cobra.Command{Use: "root", Run: emptyRun}
- aCmd := &cobra.Command{Use: "aaa", Run: emptyRun, Hidden: true} // #229
- bCmd := &cobra.Command{Use: "bbb", Run: emptyRun}
- cCmd := &cobra.Command{Use: "ccc", Run: emptyRun}
- rootCmd.AddCommand(aCmd, bCmd, cCmd)
-
- buf := new(bytes.Buffer)
- header := &GenManHeader{}
- if err := GenMan(rootCmd, header, buf); err != nil {
- t.Fatal(err)
- }
- scanner := bufio.NewScanner(buf)
-
- if err := assertLineFound(scanner, ".SH SEE ALSO"); err != nil {
- t.Fatalf("Couldn't find SEE ALSO section header: %v", err)
- }
- if err := assertNextLineEquals(scanner, ".PP"); err != nil {
- t.Fatalf("First line after SEE ALSO wasn't break-indent: %v", err)
- }
- if err := assertNextLineEquals(scanner, `\fBroot\-bbb(1)\fP, \fBroot\-ccc(1)\fP`); err != nil {
- t.Fatalf("Second line after SEE ALSO wasn't correct: %v", err)
- }
-}
-
-func TestManPrintFlagsHidesShortDeperecated(t *testing.T) {
- c := &cobra.Command{}
- c.Flags().StringP("foo", "f", "default", "Foo flag")
- c.Flags().MarkShorthandDeprecated("foo", "don't use it no more")
-
- buf := new(bytes.Buffer)
- manPrintFlags(buf, c.Flags())
-
- got := buf.String()
- expected := "**--foo**=\"default\"\n\tFoo flag\n\n"
- if got != expected {
- t.Errorf("Expected %v, got %v", expected, got)
- }
-}
-
-func TestGenManTree(t *testing.T) {
- c := &cobra.Command{Use: "do [OPTIONS] arg1 arg2"}
- header := &GenManHeader{Section: "2"}
- tmpdir, err := ioutil.TempDir("", "test-gen-man-tree")
- if err != nil {
- t.Fatalf("Failed to create tmpdir: %s", err.Error())
- }
- defer os.RemoveAll(tmpdir)
-
- if err := GenManTree(c, header, tmpdir); err != nil {
- t.Fatalf("GenManTree failed: %s", err.Error())
- }
-
- if _, err := os.Stat(filepath.Join(tmpdir, "do.2")); err != nil {
- t.Fatalf("Expected file 'do.2' to exist")
- }
-
- if header.Title != "" {
- t.Fatalf("Expected header.Title to be unmodified")
- }
-}
-
-func assertLineFound(scanner *bufio.Scanner, expectedLine string) error {
- for scanner.Scan() {
- line := scanner.Text()
- if line == expectedLine {
- return nil
- }
- }
-
- if err := scanner.Err(); err != nil {
- return fmt.Errorf("scan failed: %s", err)
- }
-
- return fmt.Errorf("hit EOF before finding %v", expectedLine)
-}
-
-func assertNextLineEquals(scanner *bufio.Scanner, expectedLine string) error {
- if scanner.Scan() {
- line := scanner.Text()
- if line == expectedLine {
- return nil
- }
- return fmt.Errorf("got %v, not %v", line, expectedLine)
- }
-
- if err := scanner.Err(); err != nil {
- return fmt.Errorf("scan failed: %v", err)
- }
-
- return fmt.Errorf("hit EOF before finding %v", expectedLine)
-}
-
-func BenchmarkGenManToFile(b *testing.B) {
- file, err := ioutil.TempFile("", "")
- if err != nil {
- b.Fatal(err)
- }
- defer os.Remove(file.Name())
- defer file.Close()
-
- b.ResetTimer()
- for i := 0; i < b.N; i++ {
- if err := GenMan(rootCmd, nil, file); err != nil {
- b.Fatal(err)
- }
- }
-}
diff --git a/vendor/github.com/spf13/cobra/doc/man_examples_test.go b/vendor/github.com/spf13/cobra/doc/man_examples_test.go
deleted file mode 100644
index db6604268..000000000
--- a/vendor/github.com/spf13/cobra/doc/man_examples_test.go
+++ /dev/null
@@ -1,35 +0,0 @@
-package doc_test
-
-import (
- "bytes"
- "fmt"
-
- "github.com/spf13/cobra"
- "github.com/spf13/cobra/doc"
-)
-
-func ExampleGenManTree() {
- cmd := &cobra.Command{
- Use: "test",
- Short: "my test program",
- }
- header := &doc.GenManHeader{
- Title: "MINE",
- Section: "3",
- }
- doc.GenManTree(cmd, header, "/tmp")
-}
-
-func ExampleGenMan() {
- cmd := &cobra.Command{
- Use: "test",
- Short: "my test program",
- }
- header := &doc.GenManHeader{
- Title: "MINE",
- Section: "3",
- }
- out := new(bytes.Buffer)
- doc.GenMan(cmd, header, out)
- fmt.Print(out.String())
-}
diff --git a/vendor/github.com/spf13/cobra/doc/md_docs.go b/vendor/github.com/spf13/cobra/doc/md_docs.go
deleted file mode 100644
index d7a2c2b62..000000000
--- a/vendor/github.com/spf13/cobra/doc/md_docs.go
+++ /dev/null
@@ -1,159 +0,0 @@
-//Copyright 2015 Red Hat Inc. All rights reserved.
-//
-// 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 doc
-
-import (
- "bytes"
- "fmt"
- "io"
- "os"
- "path/filepath"
- "sort"
- "strings"
- "time"
-
- "github.com/spf13/cobra"
-)
-
-func printOptions(buf *bytes.Buffer, cmd *cobra.Command, name string) error {
- flags := cmd.NonInheritedFlags()
- flags.SetOutput(buf)
- if flags.HasFlags() {
- buf.WriteString("### Options\n\n```\n")
- flags.PrintDefaults()
- buf.WriteString("```\n\n")
- }
-
- parentFlags := cmd.InheritedFlags()
- parentFlags.SetOutput(buf)
- if parentFlags.HasFlags() {
- buf.WriteString("### Options inherited from parent commands\n\n```\n")
- parentFlags.PrintDefaults()
- buf.WriteString("```\n\n")
- }
- return nil
-}
-
-// GenMarkdown creates markdown output.
-func GenMarkdown(cmd *cobra.Command, w io.Writer) error {
- return GenMarkdownCustom(cmd, w, func(s string) string { return s })
-}
-
-// GenMarkdownCustom creates custom markdown output.
-func GenMarkdownCustom(cmd *cobra.Command, w io.Writer, linkHandler func(string) string) error {
- cmd.InitDefaultHelpCmd()
- cmd.InitDefaultHelpFlag()
-
- buf := new(bytes.Buffer)
- name := cmd.CommandPath()
-
- short := cmd.Short
- long := cmd.Long
- if len(long) == 0 {
- long = short
- }
-
- buf.WriteString("## " + name + "\n\n")
- buf.WriteString(short + "\n\n")
- buf.WriteString("### Synopsis\n\n")
- buf.WriteString(long + "\n\n")
-
- if cmd.Runnable() {
- buf.WriteString(fmt.Sprintf("```\n%s\n```\n\n", cmd.UseLine()))
- }
-
- if len(cmd.Example) > 0 {
- buf.WriteString("### Examples\n\n")
- buf.WriteString(fmt.Sprintf("```\n%s\n```\n\n", cmd.Example))
- }
-
- if err := printOptions(buf, cmd, name); err != nil {
- return err
- }
- if hasSeeAlso(cmd) {
- buf.WriteString("### SEE ALSO\n\n")
- if cmd.HasParent() {
- parent := cmd.Parent()
- pname := parent.CommandPath()
- link := pname + ".md"
- link = strings.Replace(link, " ", "_", -1)
- buf.WriteString(fmt.Sprintf("* [%s](%s)\t - %s\n", pname, linkHandler(link), parent.Short))
- cmd.VisitParents(func(c *cobra.Command) {
- if c.DisableAutoGenTag {
- cmd.DisableAutoGenTag = c.DisableAutoGenTag
- }
- })
- }
-
- children := cmd.Commands()
- sort.Sort(byName(children))
-
- for _, child := range children {
- if !child.IsAvailableCommand() || child.IsAdditionalHelpTopicCommand() {
- continue
- }
- cname := name + " " + child.Name()
- link := cname + ".md"
- link = strings.Replace(link, " ", "_", -1)
- buf.WriteString(fmt.Sprintf("* [%s](%s)\t - %s\n", cname, linkHandler(link), child.Short))
- }
- buf.WriteString("\n")
- }
- if !cmd.DisableAutoGenTag {
- buf.WriteString("###### Auto generated by spf13/cobra on " + time.Now().Format("2-Jan-2006") + "\n")
- }
- _, err := buf.WriteTo(w)
- return err
-}
-
-// GenMarkdownTree will generate a markdown page for this command and all
-// descendants in the directory given. The header may be nil.
-// This function may not work correctly if your command names have `-` in them.
-// If you have `cmd` with two subcmds, `sub` and `sub-third`,
-// and `sub` has a subcommand called `third`, it is undefined which
-// help output will be in the file `cmd-sub-third.1`.
-func GenMarkdownTree(cmd *cobra.Command, dir string) error {
- identity := func(s string) string { return s }
- emptyStr := func(s string) string { return "" }
- return GenMarkdownTreeCustom(cmd, dir, emptyStr, identity)
-}
-
-// GenMarkdownTreeCustom is the the same as GenMarkdownTree, but
-// with custom filePrepender and linkHandler.
-func GenMarkdownTreeCustom(cmd *cobra.Command, dir string, filePrepender, linkHandler func(string) string) error {
- for _, c := range cmd.Commands() {
- if !c.IsAvailableCommand() || c.IsAdditionalHelpTopicCommand() {
- continue
- }
- if err := GenMarkdownTreeCustom(c, dir, filePrepender, linkHandler); err != nil {
- return err
- }
- }
-
- basename := strings.Replace(cmd.CommandPath(), " ", "_", -1) + ".md"
- filename := filepath.Join(dir, basename)
- f, err := os.Create(filename)
- if err != nil {
- return err
- }
- defer f.Close()
-
- if _, err := io.WriteString(f, filePrepender(filename)); err != nil {
- return err
- }
- if err := GenMarkdownCustom(cmd, f, linkHandler); err != nil {
- return err
- }
- return nil
-}
diff --git a/vendor/github.com/spf13/cobra/doc/md_docs.md b/vendor/github.com/spf13/cobra/doc/md_docs.md
deleted file mode 100644
index 56ce9fe81..000000000
--- a/vendor/github.com/spf13/cobra/doc/md_docs.md
+++ /dev/null
@@ -1,115 +0,0 @@
-# Generating Markdown Docs For Your Own cobra.Command
-
-Generating man pages from a cobra command is incredibly easy. An example is as follows:
-
-```go
-package main
-
-import (
- "log"
-
- "github.com/spf13/cobra"
- "github.com/spf13/cobra/doc"
-)
-
-func main() {
- cmd := &cobra.Command{
- Use: "test",
- Short: "my test program",
- }
- err := doc.GenMarkdownTree(cmd, "/tmp")
- if err != nil {
- log.Fatal(err)
- }
-}
-```
-
-That will get you a Markdown document `/tmp/test.md`
-
-## Generate markdown docs for the entire command tree
-
-This program can actually generate docs for the kubectl command in the kubernetes project
-
-```go
-package main
-
-import (
- "log"
- "io/ioutil"
- "os"
-
- "k8s.io/kubernetes/pkg/kubectl/cmd"
- cmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util"
-
- "github.com/spf13/cobra/doc"
-)
-
-func main() {
- kubectl := cmd.NewKubectlCommand(cmdutil.NewFactory(nil), os.Stdin, ioutil.Discard, ioutil.Discard)
- err := doc.GenMarkdownTree(kubectl, "./")
- if err != nil {
- log.Fatal(err)
- }
-}
-```
-
-This will generate a whole series of files, one for each command in the tree, in the directory specified (in this case "./")
-
-## Generate markdown docs for a single command
-
-You may wish to have more control over the output, or only generate for a single command, instead of the entire command tree. If this is the case you may prefer to `GenMarkdown` instead of `GenMarkdownTree`
-
-```go
- out := new(bytes.Buffer)
- err := doc.GenMarkdown(cmd, out)
- if err != nil {
- log.Fatal(err)
- }
-```
-
-This will write the markdown doc for ONLY "cmd" into the out, buffer.
-
-## Customize the output
-
-Both `GenMarkdown` and `GenMarkdownTree` have alternate versions with callbacks to get some control of the output:
-
-```go
-func GenMarkdownTreeCustom(cmd *Command, dir string, filePrepender, linkHandler func(string) string) error {
- //...
-}
-```
-
-```go
-func GenMarkdownCustom(cmd *Command, out *bytes.Buffer, linkHandler func(string) string) error {
- //...
-}
-```
-
-The `filePrepender` will prepend the return value given the full filepath to the rendered Markdown file. A common use case is to add front matter to use the generated documentation with [Hugo](http://gohugo.io/):
-
-```go
-const fmTemplate = `---
-date: %s
-title: "%s"
-slug: %s
-url: %s
----
-`
-
-filePrepender := func(filename string) string {
- now := time.Now().Format(time.RFC3339)
- name := filepath.Base(filename)
- base := strings.TrimSuffix(name, path.Ext(name))
- url := "/commands/" + strings.ToLower(base) + "/"
- return fmt.Sprintf(fmTemplate, now, strings.Replace(base, "_", " ", -1), base, url)
-}
-```
-
-The `linkHandler` can be used to customize the rendered internal links to the commands, given a filename:
-
-```go
-linkHandler := func(name string) string {
- base := strings.TrimSuffix(name, path.Ext(name))
- return "/commands/" + strings.ToLower(base) + "/"
-}
-```
diff --git a/vendor/github.com/spf13/cobra/doc/md_docs_test.go b/vendor/github.com/spf13/cobra/doc/md_docs_test.go
deleted file mode 100644
index b0fa68c0b..000000000
--- a/vendor/github.com/spf13/cobra/doc/md_docs_test.go
+++ /dev/null
@@ -1,74 +0,0 @@
-package doc
-
-import (
- "bytes"
- "io/ioutil"
- "os"
- "path/filepath"
- "testing"
-
- "github.com/spf13/cobra"
-)
-
-func TestGenMdDoc(t *testing.T) {
- // We generate on subcommand so we have both subcommands and parents.
- buf := new(bytes.Buffer)
- if err := GenMarkdown(echoCmd, buf); err != nil {
- t.Fatal(err)
- }
- output := buf.String()
-
- checkStringContains(t, output, echoCmd.Long)
- checkStringContains(t, output, echoCmd.Example)
- checkStringContains(t, output, "boolone")
- checkStringContains(t, output, "rootflag")
- checkStringContains(t, output, rootCmd.Short)
- checkStringContains(t, output, echoSubCmd.Short)
- checkStringOmits(t, output, deprecatedCmd.Short)
-}
-
-func TestGenMdNoTag(t *testing.T) {
- rootCmd.DisableAutoGenTag = true
- defer func() { rootCmd.DisableAutoGenTag = false }()
-
- buf := new(bytes.Buffer)
- if err := GenMarkdown(rootCmd, buf); err != nil {
- t.Fatal(err)
- }
- output := buf.String()
-
- checkStringOmits(t, output, "Auto generated")
-}
-
-func TestGenMdTree(t *testing.T) {
- c := &cobra.Command{Use: "do [OPTIONS] arg1 arg2"}
- tmpdir, err := ioutil.TempDir("", "test-gen-md-tree")
- if err != nil {
- t.Fatalf("Failed to create tmpdir: %v", err)
- }
- defer os.RemoveAll(tmpdir)
-
- if err := GenMarkdownTree(c, tmpdir); err != nil {
- t.Fatalf("GenMarkdownTree failed: %v", err)
- }
-
- if _, err := os.Stat(filepath.Join(tmpdir, "do.md")); err != nil {
- t.Fatalf("Expected file 'do.md' to exist")
- }
-}
-
-func BenchmarkGenMarkdownToFile(b *testing.B) {
- file, err := ioutil.TempFile("", "")
- if err != nil {
- b.Fatal(err)
- }
- defer os.Remove(file.Name())
- defer file.Close()
-
- b.ResetTimer()
- for i := 0; i < b.N; i++ {
- if err := GenMarkdown(rootCmd, file); err != nil {
- b.Fatal(err)
- }
- }
-}
diff --git a/vendor/github.com/spf13/cobra/doc/rest_docs.go b/vendor/github.com/spf13/cobra/doc/rest_docs.go
deleted file mode 100644
index 4913e3ee2..000000000
--- a/vendor/github.com/spf13/cobra/doc/rest_docs.go
+++ /dev/null
@@ -1,185 +0,0 @@
-//Copyright 2015 Red Hat Inc. All rights reserved.
-//
-// 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 doc
-
-import (
- "bytes"
- "fmt"
- "io"
- "os"
- "path/filepath"
- "sort"
- "strings"
- "time"
-
- "github.com/spf13/cobra"
-)
-
-func printOptionsReST(buf *bytes.Buffer, cmd *cobra.Command, name string) error {
- flags := cmd.NonInheritedFlags()
- flags.SetOutput(buf)
- if flags.HasFlags() {
- buf.WriteString("Options\n")
- buf.WriteString("~~~~~~~\n\n::\n\n")
- flags.PrintDefaults()
- buf.WriteString("\n")
- }
-
- parentFlags := cmd.InheritedFlags()
- parentFlags.SetOutput(buf)
- if parentFlags.HasFlags() {
- buf.WriteString("Options inherited from parent commands\n")
- buf.WriteString("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n::\n\n")
- parentFlags.PrintDefaults()
- buf.WriteString("\n")
- }
- return nil
-}
-
-// linkHandler for default ReST hyperlink markup
-func defaultLinkHandler(name, ref string) string {
- return fmt.Sprintf("`%s <%s.rst>`_", name, ref)
-}
-
-// GenReST creates reStructured Text output.
-func GenReST(cmd *cobra.Command, w io.Writer) error {
- return GenReSTCustom(cmd, w, defaultLinkHandler)
-}
-
-// GenReSTCustom creates custom reStructured Text output.
-func GenReSTCustom(cmd *cobra.Command, w io.Writer, linkHandler func(string, string) string) error {
- cmd.InitDefaultHelpCmd()
- cmd.InitDefaultHelpFlag()
-
- buf := new(bytes.Buffer)
- name := cmd.CommandPath()
-
- short := cmd.Short
- long := cmd.Long
- if len(long) == 0 {
- long = short
- }
- ref := strings.Replace(name, " ", "_", -1)
-
- buf.WriteString(".. _" + ref + ":\n\n")
- buf.WriteString(name + "\n")
- buf.WriteString(strings.Repeat("-", len(name)) + "\n\n")
- buf.WriteString(short + "\n\n")
- buf.WriteString("Synopsis\n")
- buf.WriteString("~~~~~~~~\n\n")
- buf.WriteString("\n" + long + "\n\n")
-
- if cmd.Runnable() {
- buf.WriteString(fmt.Sprintf("::\n\n %s\n\n", cmd.UseLine()))
- }
-
- if len(cmd.Example) > 0 {
- buf.WriteString("Examples\n")
- buf.WriteString("~~~~~~~~\n\n")
- buf.WriteString(fmt.Sprintf("::\n\n%s\n\n", indentString(cmd.Example, " ")))
- }
-
- if err := printOptionsReST(buf, cmd, name); err != nil {
- return err
- }
- if hasSeeAlso(cmd) {
- buf.WriteString("SEE ALSO\n")
- buf.WriteString("~~~~~~~~\n\n")
- if cmd.HasParent() {
- parent := cmd.Parent()
- pname := parent.CommandPath()
- ref = strings.Replace(pname, " ", "_", -1)
- buf.WriteString(fmt.Sprintf("* %s \t - %s\n", linkHandler(pname, ref), parent.Short))
- cmd.VisitParents(func(c *cobra.Command) {
- if c.DisableAutoGenTag {
- cmd.DisableAutoGenTag = c.DisableAutoGenTag
- }
- })
- }
-
- children := cmd.Commands()
- sort.Sort(byName(children))
-
- for _, child := range children {
- if !child.IsAvailableCommand() || child.IsAdditionalHelpTopicCommand() {
- continue
- }
- cname := name + " " + child.Name()
- ref = strings.Replace(cname, " ", "_", -1)
- buf.WriteString(fmt.Sprintf("* %s \t - %s\n", linkHandler(cname, ref), child.Short))
- }
- buf.WriteString("\n")
- }
- if !cmd.DisableAutoGenTag {
- buf.WriteString("*Auto generated by spf13/cobra on " + time.Now().Format("2-Jan-2006") + "*\n")
- }
- _, err := buf.WriteTo(w)
- return err
-}
-
-// GenReSTTree will generate a ReST page for this command and all
-// descendants in the directory given.
-// This function may not work correctly if your command names have `-` in them.
-// If you have `cmd` with two subcmds, `sub` and `sub-third`,
-// and `sub` has a subcommand called `third`, it is undefined which
-// help output will be in the file `cmd-sub-third.1`.
-func GenReSTTree(cmd *cobra.Command, dir string) error {
- emptyStr := func(s string) string { return "" }
- return GenReSTTreeCustom(cmd, dir, emptyStr, defaultLinkHandler)
-}
-
-// GenReSTTreeCustom is the the same as GenReSTTree, but
-// with custom filePrepender and linkHandler.
-func GenReSTTreeCustom(cmd *cobra.Command, dir string, filePrepender func(string) string, linkHandler func(string, string) string) error {
- for _, c := range cmd.Commands() {
- if !c.IsAvailableCommand() || c.IsAdditionalHelpTopicCommand() {
- continue
- }
- if err := GenReSTTreeCustom(c, dir, filePrepender, linkHandler); err != nil {
- return err
- }
- }
-
- basename := strings.Replace(cmd.CommandPath(), " ", "_", -1) + ".rst"
- filename := filepath.Join(dir, basename)
- f, err := os.Create(filename)
- if err != nil {
- return err
- }
- defer f.Close()
-
- if _, err := io.WriteString(f, filePrepender(filename)); err != nil {
- return err
- }
- if err := GenReSTCustom(cmd, f, linkHandler); err != nil {
- return err
- }
- return nil
-}
-
-// adapted from: https://github.com/kr/text/blob/main/indent.go
-func indentString(s, p string) string {
- var res []byte
- b := []byte(s)
- prefix := []byte(p)
- bol := true
- for _, c := range b {
- if bol && c != '\n' {
- res = append(res, prefix...)
- }
- res = append(res, c)
- bol = c == '\n'
- }
- return string(res)
-}
diff --git a/vendor/github.com/spf13/cobra/doc/rest_docs.md b/vendor/github.com/spf13/cobra/doc/rest_docs.md
deleted file mode 100644
index 6098430ef..000000000
--- a/vendor/github.com/spf13/cobra/doc/rest_docs.md
+++ /dev/null
@@ -1,114 +0,0 @@
-# Generating ReStructured Text Docs For Your Own cobra.Command
-
-Generating ReST pages from a cobra command is incredibly easy. An example is as follows:
-
-```go
-package main
-
-import (
- "log"
-
- "github.com/spf13/cobra"
- "github.com/spf13/cobra/doc"
-)
-
-func main() {
- cmd := &cobra.Command{
- Use: "test",
- Short: "my test program",
- }
- err := doc.GenReSTTree(cmd, "/tmp")
- if err != nil {
- log.Fatal(err)
- }
-}
-```
-
-That will get you a ReST document `/tmp/test.rst`
-
-## Generate ReST docs for the entire command tree
-
-This program can actually generate docs for the kubectl command in the kubernetes project
-
-```go
-package main
-
-import (
- "log"
- "io/ioutil"
- "os"
-
- "k8s.io/kubernetes/pkg/kubectl/cmd"
- cmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util"
-
- "github.com/spf13/cobra/doc"
-)
-
-func main() {
- kubectl := cmd.NewKubectlCommand(cmdutil.NewFactory(nil), os.Stdin, ioutil.Discard, ioutil.Discard)
- err := doc.GenReSTTree(kubectl, "./")
- if err != nil {
- log.Fatal(err)
- }
-}
-```
-
-This will generate a whole series of files, one for each command in the tree, in the directory specified (in this case "./")
-
-## Generate ReST docs for a single command
-
-You may wish to have more control over the output, or only generate for a single command, instead of the entire command tree. If this is the case you may prefer to `GenReST` instead of `GenReSTTree`
-
-```go
- out := new(bytes.Buffer)
- err := doc.GenReST(cmd, out)
- if err != nil {
- log.Fatal(err)
- }
-```
-
-This will write the ReST doc for ONLY "cmd" into the out, buffer.
-
-## Customize the output
-
-Both `GenReST` and `GenReSTTree` have alternate versions with callbacks to get some control of the output:
-
-```go
-func GenReSTTreeCustom(cmd *Command, dir string, filePrepender func(string) string, linkHandler func(string, string) string) error {
- //...
-}
-```
-
-```go
-func GenReSTCustom(cmd *Command, out *bytes.Buffer, linkHandler func(string, string) string) error {
- //...
-}
-```
-
-The `filePrepender` will prepend the return value given the full filepath to the rendered ReST file. A common use case is to add front matter to use the generated documentation with [Hugo](http://gohugo.io/):
-
-```go
-const fmTemplate = `---
-date: %s
-title: "%s"
-slug: %s
-url: %s
----
-`
-filePrepender := func(filename string) string {
- now := time.Now().Format(time.RFC3339)
- name := filepath.Base(filename)
- base := strings.TrimSuffix(name, path.Ext(name))
- url := "/commands/" + strings.ToLower(base) + "/"
- return fmt.Sprintf(fmTemplate, now, strings.Replace(base, "_", " ", -1), base, url)
-}
-```
-
-The `linkHandler` can be used to customize the rendered links to the commands, given a command name and reference. This is useful while converting rst to html or while generating documentation with tools like Sphinx where `:ref:` is used:
-
-```go
-// Sphinx cross-referencing format
-linkHandler := func(name, ref string) string {
- return fmt.Sprintf(":ref:`%s <%s>`", name, ref)
-}
-```
diff --git a/vendor/github.com/spf13/cobra/doc/rest_docs_test.go b/vendor/github.com/spf13/cobra/doc/rest_docs_test.go
deleted file mode 100644
index aa3186e8f..000000000
--- a/vendor/github.com/spf13/cobra/doc/rest_docs_test.go
+++ /dev/null
@@ -1,76 +0,0 @@
-package doc
-
-import (
- "bytes"
- "io/ioutil"
- "os"
- "path/filepath"
- "testing"
-
- "github.com/spf13/cobra"
-)
-
-func TestGenRSTDoc(t *testing.T) {
- // We generate on a subcommand so we have both subcommands and parents
- buf := new(bytes.Buffer)
- if err := GenReST(echoCmd, buf); err != nil {
- t.Fatal(err)
- }
- output := buf.String()
-
- checkStringContains(t, output, echoCmd.Long)
- checkStringContains(t, output, echoCmd.Example)
- checkStringContains(t, output, "boolone")
- checkStringContains(t, output, "rootflag")
- checkStringContains(t, output, rootCmd.Short)
- checkStringContains(t, output, echoSubCmd.Short)
- checkStringOmits(t, output, deprecatedCmd.Short)
-}
-
-func TestGenRSTNoTag(t *testing.T) {
- rootCmd.DisableAutoGenTag = true
- defer func() { rootCmd.DisableAutoGenTag = false }()
-
- buf := new(bytes.Buffer)
- if err := GenReST(rootCmd, buf); err != nil {
- t.Fatal(err)
- }
- output := buf.String()
-
- unexpected := "Auto generated"
- checkStringOmits(t, output, unexpected)
-}
-
-func TestGenRSTTree(t *testing.T) {
- c := &cobra.Command{Use: "do [OPTIONS] arg1 arg2"}
-
- tmpdir, err := ioutil.TempDir("", "test-gen-rst-tree")
- if err != nil {
- t.Fatalf("Failed to create tmpdir: %s", err.Error())
- }
- defer os.RemoveAll(tmpdir)
-
- if err := GenReSTTree(c, tmpdir); err != nil {
- t.Fatalf("GenReSTTree failed: %s", err.Error())
- }
-
- if _, err := os.Stat(filepath.Join(tmpdir, "do.rst")); err != nil {
- t.Fatalf("Expected file 'do.rst' to exist")
- }
-}
-
-func BenchmarkGenReSTToFile(b *testing.B) {
- file, err := ioutil.TempFile("", "")
- if err != nil {
- b.Fatal(err)
- }
- defer os.Remove(file.Name())
- defer file.Close()
-
- b.ResetTimer()
- for i := 0; i < b.N; i++ {
- if err := GenReST(rootCmd, file); err != nil {
- b.Fatal(err)
- }
- }
-}
diff --git a/vendor/github.com/spf13/cobra/doc/util.go b/vendor/github.com/spf13/cobra/doc/util.go
deleted file mode 100644
index 8d3dbecec..000000000
--- a/vendor/github.com/spf13/cobra/doc/util.go
+++ /dev/null
@@ -1,51 +0,0 @@
-// Copyright 2015 Red Hat Inc. All rights reserved.
-//
-// 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 doc
-
-import (
- "strings"
-
- "github.com/spf13/cobra"
-)
-
-// Test to see if we have a reason to print See Also information in docs
-// Basically this is a test for a parent commend or a subcommand which is
-// both not deprecated and not the autogenerated help command.
-func hasSeeAlso(cmd *cobra.Command) bool {
- if cmd.HasParent() {
- return true
- }
- for _, c := range cmd.Commands() {
- if !c.IsAvailableCommand() || c.IsAdditionalHelpTopicCommand() {
- continue
- }
- return true
- }
- return false
-}
-
-// Temporary workaround for yaml lib generating incorrect yaml with long strings
-// that do not contain \n.
-func forceMultiLine(s string) string {
- if len(s) > 60 && !strings.Contains(s, "\n") {
- s = s + "\n"
- }
- return s
-}
-
-type byName []*cobra.Command
-
-func (s byName) Len() int { return len(s) }
-func (s byName) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
-func (s byName) Less(i, j int) bool { return s[i].Name() < s[j].Name() }
diff --git a/vendor/github.com/spf13/cobra/doc/yaml_docs.go b/vendor/github.com/spf13/cobra/doc/yaml_docs.go
deleted file mode 100644
index ea00af07e..000000000
--- a/vendor/github.com/spf13/cobra/doc/yaml_docs.go
+++ /dev/null
@@ -1,169 +0,0 @@
-// Copyright 2016 French Ben. All rights reserved.
-//
-// 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 doc
-
-import (
- "fmt"
- "io"
- "os"
- "path/filepath"
- "sort"
- "strings"
-
- "github.com/spf13/cobra"
- "github.com/spf13/pflag"
- "gopkg.in/yaml.v2"
-)
-
-type cmdOption struct {
- Name string
- Shorthand string `yaml:",omitempty"`
- DefaultValue string `yaml:"default_value,omitempty"`
- Usage string `yaml:",omitempty"`
-}
-
-type cmdDoc struct {
- Name string
- Synopsis string `yaml:",omitempty"`
- Description string `yaml:",omitempty"`
- Options []cmdOption `yaml:",omitempty"`
- InheritedOptions []cmdOption `yaml:"inherited_options,omitempty"`
- Example string `yaml:",omitempty"`
- SeeAlso []string `yaml:"see_also,omitempty"`
-}
-
-// GenYamlTree creates yaml structured ref files for this command and all descendants
-// in the directory given. This function may not work
-// correctly if your command names have `-` in them. If you have `cmd` with two
-// subcmds, `sub` and `sub-third`, and `sub` has a subcommand called `third`
-// it is undefined which help output will be in the file `cmd-sub-third.1`.
-func GenYamlTree(cmd *cobra.Command, dir string) error {
- identity := func(s string) string { return s }
- emptyStr := func(s string) string { return "" }
- return GenYamlTreeCustom(cmd, dir, emptyStr, identity)
-}
-
-// GenYamlTreeCustom creates yaml structured ref files.
-func GenYamlTreeCustom(cmd *cobra.Command, dir string, filePrepender, linkHandler func(string) string) error {
- for _, c := range cmd.Commands() {
- if !c.IsAvailableCommand() || c.IsAdditionalHelpTopicCommand() {
- continue
- }
- if err := GenYamlTreeCustom(c, dir, filePrepender, linkHandler); err != nil {
- return err
- }
- }
-
- basename := strings.Replace(cmd.CommandPath(), " ", "_", -1) + ".yaml"
- filename := filepath.Join(dir, basename)
- f, err := os.Create(filename)
- if err != nil {
- return err
- }
- defer f.Close()
-
- if _, err := io.WriteString(f, filePrepender(filename)); err != nil {
- return err
- }
- if err := GenYamlCustom(cmd, f, linkHandler); err != nil {
- return err
- }
- return nil
-}
-
-// GenYaml creates yaml output.
-func GenYaml(cmd *cobra.Command, w io.Writer) error {
- return GenYamlCustom(cmd, w, func(s string) string { return s })
-}
-
-// GenYamlCustom creates custom yaml output.
-func GenYamlCustom(cmd *cobra.Command, w io.Writer, linkHandler func(string) string) error {
- cmd.InitDefaultHelpCmd()
- cmd.InitDefaultHelpFlag()
-
- yamlDoc := cmdDoc{}
- yamlDoc.Name = cmd.CommandPath()
-
- yamlDoc.Synopsis = forceMultiLine(cmd.Short)
- yamlDoc.Description = forceMultiLine(cmd.Long)
-
- if len(cmd.Example) > 0 {
- yamlDoc.Example = cmd.Example
- }
-
- flags := cmd.NonInheritedFlags()
- if flags.HasFlags() {
- yamlDoc.Options = genFlagResult(flags)
- }
- flags = cmd.InheritedFlags()
- if flags.HasFlags() {
- yamlDoc.InheritedOptions = genFlagResult(flags)
- }
-
- if hasSeeAlso(cmd) {
- result := []string{}
- if cmd.HasParent() {
- parent := cmd.Parent()
- result = append(result, parent.CommandPath()+" - "+parent.Short)
- }
- children := cmd.Commands()
- sort.Sort(byName(children))
- for _, child := range children {
- if !child.IsAvailableCommand() || child.IsAdditionalHelpTopicCommand() {
- continue
- }
- result = append(result, child.Name()+" - "+child.Short)
- }
- yamlDoc.SeeAlso = result
- }
-
- final, err := yaml.Marshal(&yamlDoc)
- if err != nil {
- fmt.Println(err)
- os.Exit(1)
- }
-
- if _, err := w.Write(final); err != nil {
- return err
- }
- return nil
-}
-
-func genFlagResult(flags *pflag.FlagSet) []cmdOption {
- var result []cmdOption
-
- flags.VisitAll(func(flag *pflag.Flag) {
- // Todo, when we mark a shorthand is deprecated, but specify an empty message.
- // The flag.ShorthandDeprecated is empty as the shorthand is deprecated.
- // Using len(flag.ShorthandDeprecated) > 0 can't handle this, others are ok.
- if !(len(flag.ShorthandDeprecated) > 0) && len(flag.Shorthand) > 0 {
- opt := cmdOption{
- flag.Name,
- flag.Shorthand,
- flag.DefValue,
- forceMultiLine(flag.Usage),
- }
- result = append(result, opt)
- } else {
- opt := cmdOption{
- Name: flag.Name,
- DefaultValue: forceMultiLine(flag.DefValue),
- Usage: forceMultiLine(flag.Usage),
- }
- result = append(result, opt)
- }
- })
-
- return result
-}
diff --git a/vendor/github.com/spf13/cobra/doc/yaml_docs.md b/vendor/github.com/spf13/cobra/doc/yaml_docs.md
deleted file mode 100644
index 1a9b7c6a3..000000000
--- a/vendor/github.com/spf13/cobra/doc/yaml_docs.md
+++ /dev/null
@@ -1,112 +0,0 @@
-# Generating Yaml Docs For Your Own cobra.Command
-
-Generating yaml files from a cobra command is incredibly easy. An example is as follows:
-
-```go
-package main
-
-import (
- "log"
-
- "github.com/spf13/cobra"
- "github.com/spf13/cobra/doc"
-)
-
-func main() {
- cmd := &cobra.Command{
- Use: "test",
- Short: "my test program",
- }
- err := doc.GenYamlTree(cmd, "/tmp")
- if err != nil {
- log.Fatal(err)
- }
-}
-```
-
-That will get you a Yaml document `/tmp/test.yaml`
-
-## Generate yaml docs for the entire command tree
-
-This program can actually generate docs for the kubectl command in the kubernetes project
-
-```go
-package main
-
-import (
- "io/ioutil"
- "log"
- "os"
-
- "k8s.io/kubernetes/pkg/kubectl/cmd"
- cmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util"
-
- "github.com/spf13/cobra/doc"
-)
-
-func main() {
- kubectl := cmd.NewKubectlCommand(cmdutil.NewFactory(nil), os.Stdin, ioutil.Discard, ioutil.Discard)
- err := doc.GenYamlTree(kubectl, "./")
- if err != nil {
- log.Fatal(err)
- }
-}
-```
-
-This will generate a whole series of files, one for each command in the tree, in the directory specified (in this case "./")
-
-## Generate yaml docs for a single command
-
-You may wish to have more control over the output, or only generate for a single command, instead of the entire command tree. If this is the case you may prefer to `GenYaml` instead of `GenYamlTree`
-
-```go
- out := new(bytes.Buffer)
- doc.GenYaml(cmd, out)
-```
-
-This will write the yaml doc for ONLY "cmd" into the out, buffer.
-
-## Customize the output
-
-Both `GenYaml` and `GenYamlTree` have alternate versions with callbacks to get some control of the output:
-
-```go
-func GenYamlTreeCustom(cmd *Command, dir string, filePrepender, linkHandler func(string) string) error {
- //...
-}
-```
-
-```go
-func GenYamlCustom(cmd *Command, out *bytes.Buffer, linkHandler func(string) string) error {
- //...
-}
-```
-
-The `filePrepender` will prepend the return value given the full filepath to the rendered Yaml file. A common use case is to add front matter to use the generated documentation with [Hugo](http://gohugo.io/):
-
-```go
-const fmTemplate = `---
-date: %s
-title: "%s"
-slug: %s
-url: %s
----
-`
-
-filePrepender := func(filename string) string {
- now := time.Now().Format(time.RFC3339)
- name := filepath.Base(filename)
- base := strings.TrimSuffix(name, path.Ext(name))
- url := "/commands/" + strings.ToLower(base) + "/"
- return fmt.Sprintf(fmTemplate, now, strings.Replace(base, "_", " ", -1), base, url)
-}
-```
-
-The `linkHandler` can be used to customize the rendered internal links to the commands, given a filename:
-
-```go
-linkHandler := func(name string) string {
- base := strings.TrimSuffix(name, path.Ext(name))
- return "/commands/" + strings.ToLower(base) + "/"
-}
-```
diff --git a/vendor/github.com/spf13/cobra/doc/yaml_docs_test.go b/vendor/github.com/spf13/cobra/doc/yaml_docs_test.go
deleted file mode 100644
index c5a63594f..000000000
--- a/vendor/github.com/spf13/cobra/doc/yaml_docs_test.go
+++ /dev/null
@@ -1,74 +0,0 @@
-package doc
-
-import (
- "bytes"
- "io/ioutil"
- "os"
- "path/filepath"
- "testing"
-
- "github.com/spf13/cobra"
-)
-
-func TestGenYamlDoc(t *testing.T) {
- // We generate on s subcommand so we have both subcommands and parents
- buf := new(bytes.Buffer)
- if err := GenYaml(echoCmd, buf); err != nil {
- t.Fatal(err)
- }
- output := buf.String()
-
- checkStringContains(t, output, echoCmd.Long)
- checkStringContains(t, output, echoCmd.Example)
- checkStringContains(t, output, "boolone")
- checkStringContains(t, output, "rootflag")
- checkStringContains(t, output, rootCmd.Short)
- checkStringContains(t, output, echoSubCmd.Short)
-}
-
-func TestGenYamlNoTag(t *testing.T) {
- rootCmd.DisableAutoGenTag = true
- defer func() { rootCmd.DisableAutoGenTag = false }()
-
- buf := new(bytes.Buffer)
- if err := GenYaml(rootCmd, buf); err != nil {
- t.Fatal(err)
- }
- output := buf.String()
-
- checkStringOmits(t, output, "Auto generated")
-}
-
-func TestGenYamlTree(t *testing.T) {
- c := &cobra.Command{Use: "do [OPTIONS] arg1 arg2"}
-
- tmpdir, err := ioutil.TempDir("", "test-gen-yaml-tree")
- if err != nil {
- t.Fatalf("Failed to create tmpdir: %s", err.Error())
- }
- defer os.RemoveAll(tmpdir)
-
- if err := GenYamlTree(c, tmpdir); err != nil {
- t.Fatalf("GenYamlTree failed: %s", err.Error())
- }
-
- if _, err := os.Stat(filepath.Join(tmpdir, "do.yaml")); err != nil {
- t.Fatalf("Expected file 'do.yaml' to exist")
- }
-}
-
-func BenchmarkGenYamlToFile(b *testing.B) {
- file, err := ioutil.TempFile("", "")
- if err != nil {
- b.Fatal(err)
- }
- defer os.Remove(file.Name())
- defer file.Close()
-
- b.ResetTimer()
- for i := 0; i < b.N; i++ {
- if err := GenYaml(rootCmd, file); err != nil {
- b.Fatal(err)
- }
- }
-}
diff --git a/vendor/github.com/spf13/cobra/zsh_completions_test.go b/vendor/github.com/spf13/cobra/zsh_completions_test.go
deleted file mode 100644
index 34e69496f..000000000
--- a/vendor/github.com/spf13/cobra/zsh_completions_test.go
+++ /dev/null
@@ -1,89 +0,0 @@
-package cobra
-
-import (
- "bytes"
- "strings"
- "testing"
-)
-
-func TestZshCompletion(t *testing.T) {
- tcs := []struct {
- name string
- root *Command
- expectedExpressions []string
- }{
- {
- name: "trivial",
- root: &Command{Use: "trivialapp"},
- expectedExpressions: []string{"#compdef trivial"},
- },
- {
- name: "linear",
- root: func() *Command {
- r := &Command{Use: "linear"}
-
- sub1 := &Command{Use: "sub1"}
- r.AddCommand(sub1)
-
- sub2 := &Command{Use: "sub2"}
- sub1.AddCommand(sub2)
-
- sub3 := &Command{Use: "sub3"}
- sub2.AddCommand(sub3)
- return r
- }(),
- expectedExpressions: []string{"sub1", "sub2", "sub3"},
- },
- {
- name: "flat",
- root: func() *Command {
- r := &Command{Use: "flat"}
- r.AddCommand(&Command{Use: "c1"})
- r.AddCommand(&Command{Use: "c2"})
- return r
- }(),
- expectedExpressions: []string{"(c1 c2)"},
- },
- {
- name: "tree",
- root: func() *Command {
- r := &Command{Use: "tree"}
-
- sub1 := &Command{Use: "sub1"}
- r.AddCommand(sub1)
-
- sub11 := &Command{Use: "sub11"}
- sub12 := &Command{Use: "sub12"}
-
- sub1.AddCommand(sub11)
- sub1.AddCommand(sub12)
-
- sub2 := &Command{Use: "sub2"}
- r.AddCommand(sub2)
-
- sub21 := &Command{Use: "sub21"}
- sub22 := &Command{Use: "sub22"}
-
- sub2.AddCommand(sub21)
- sub2.AddCommand(sub22)
-
- return r
- }(),
- expectedExpressions: []string{"(sub11 sub12)", "(sub21 sub22)"},
- },
- }
-
- for _, tc := range tcs {
- t.Run(tc.name, func(t *testing.T) {
- buf := new(bytes.Buffer)
- tc.root.GenZshCompletion(buf)
- output := buf.String()
-
- for _, expectedExpression := range tc.expectedExpressions {
- if !strings.Contains(output, expectedExpression) {
- t.Errorf("Expected completion to contain %q somewhere; got %q", expectedExpression, output)
- }
- }
- })
- }
-}
diff --git a/vendor/github.com/spf13/jwalterweatherman/default_notepad_test.go b/vendor/github.com/spf13/jwalterweatherman/default_notepad_test.go
deleted file mode 100644
index 2670c8d96..000000000
--- a/vendor/github.com/spf13/jwalterweatherman/default_notepad_test.go
+++ /dev/null
@@ -1,102 +0,0 @@
-// Copyright © 2016 Steve Francia <spf@spf13.com>.
-//
-// Use of this source code is governed by an MIT-style
-// license that can be found in the LICENSE file.
-
-package jwalterweatherman
-
-import (
- "bytes"
- "io/ioutil"
- "sync"
- "testing"
-
- "github.com/stretchr/testify/require"
-)
-
-func TestThresholds(t *testing.T) {
- SetStdoutThreshold(LevelError)
- require.Equal(t, StdoutThreshold(), LevelError)
- SetLogThreshold(LevelCritical)
- require.Equal(t, LogThreshold(), LevelCritical)
- require.NotEqual(t, StdoutThreshold(), LevelCritical)
- SetStdoutThreshold(LevelWarn)
- require.Equal(t, StdoutThreshold(), LevelWarn)
-}
-
-func TestDefaultLogging(t *testing.T) {
- var outputBuf, logBuf bytes.Buffer
-
- defaultNotepad.logHandle = &logBuf
- defaultNotepad.outHandle = &outputBuf
-
- SetLogThreshold(LevelWarn)
- SetStdoutThreshold(LevelError)
-
- FATAL.Println("fatal err")
- CRITICAL.Println("critical err")
- ERROR.Println("an error")
- WARN.Println("a warning")
- INFO.Println("information")
- DEBUG.Println("debugging info")
- TRACE.Println("trace")
-
- require.Contains(t, logBuf.String(), "fatal err")
- require.Contains(t, logBuf.String(), "critical err")
- require.Contains(t, logBuf.String(), "an error")
- require.Contains(t, logBuf.String(), "a warning")
- require.NotContains(t, logBuf.String(), "information")
- require.NotContains(t, logBuf.String(), "debugging info")
- require.NotContains(t, logBuf.String(), "trace")
-
- require.Contains(t, outputBuf.String(), "fatal err")
- require.Contains(t, outputBuf.String(), "critical err")
- require.Contains(t, outputBuf.String(), "an error")
- require.NotContains(t, outputBuf.String(), "a warning")
- require.NotContains(t, outputBuf.String(), "information")
- require.NotContains(t, outputBuf.String(), "debugging info")
- require.NotContains(t, outputBuf.String(), "trace")
-}
-
-func TestLogCounter(t *testing.T) {
- defaultNotepad.logHandle = ioutil.Discard
- defaultNotepad.outHandle = ioutil.Discard
-
- SetLogThreshold(LevelTrace)
- SetStdoutThreshold(LevelTrace)
-
- FATAL.Println("fatal err")
- CRITICAL.Println("critical err")
- WARN.Println("a warning")
- WARN.Println("another warning")
- INFO.Println("information")
- DEBUG.Println("debugging info")
- TRACE.Println("trace")
-
- wg := &sync.WaitGroup{}
-
- for i := 0; i < 10; i++ {
- wg.Add(1)
- go func() {
- defer wg.Done()
- for j := 0; j < 10; j++ {
- ERROR.Println("error", j)
- // check for data races
- require.True(t, LogCountForLevel(LevelError) > uint64(j))
- require.True(t, LogCountForLevelsGreaterThanorEqualTo(LevelError) > uint64(j))
- }
- }()
-
- }
-
- wg.Wait()
-
- require.Equal(t, uint64(1), LogCountForLevel(LevelFatal))
- require.Equal(t, uint64(1), LogCountForLevel(LevelCritical))
- require.Equal(t, uint64(2), LogCountForLevel(LevelWarn))
- require.Equal(t, uint64(1), LogCountForLevel(LevelInfo))
- require.Equal(t, uint64(1), LogCountForLevel(LevelDebug))
- require.Equal(t, uint64(1), LogCountForLevel(LevelTrace))
- require.Equal(t, uint64(100), LogCountForLevel(LevelError))
- require.Equal(t, uint64(102), LogCountForLevelsGreaterThanorEqualTo(LevelError))
-}
diff --git a/vendor/github.com/spf13/jwalterweatherman/notepad_test.go b/vendor/github.com/spf13/jwalterweatherman/notepad_test.go
deleted file mode 100644
index 69ad6f8fc..000000000
--- a/vendor/github.com/spf13/jwalterweatherman/notepad_test.go
+++ /dev/null
@@ -1,50 +0,0 @@
-// Copyright © 2016 Steve Francia <spf@spf13.com>.
-//
-// Use of this source code is governed by an MIT-style
-// license that can be found in the LICENSE file.
-
-package jwalterweatherman
-
-import (
- "bytes"
- "testing"
-
- "github.com/stretchr/testify/require"
-)
-
-func TestNotepad(t *testing.T) {
- var logHandle, outHandle bytes.Buffer
-
- n := NewNotepad(LevelCritical, LevelError, &outHandle, &logHandle, "TestNotePad", 0)
-
- require.Equal(t, LevelCritical, n.GetStdoutThreshold())
- require.Equal(t, LevelError, n.GetLogThreshold())
-
- n.DEBUG.Println("Some debug")
- n.ERROR.Println("Some error")
- n.CRITICAL.Println("Some critical error")
-
- require.Contains(t, logHandle.String(), "[TestNotePad] ERROR Some error")
- require.NotContains(t, logHandle.String(), "Some debug")
- require.NotContains(t, outHandle.String(), "Some error")
- require.Contains(t, outHandle.String(), "Some critical error")
-
- require.Equal(t, n.LogCountForLevel(LevelError), uint64(1))
- require.Equal(t, n.LogCountForLevel(LevelDebug), uint64(1))
- require.Equal(t, n.LogCountForLevel(LevelTrace), uint64(0))
-}
-
-func TestThresholdString(t *testing.T) {
- require.Equal(t, LevelError.String(), "ERROR")
- require.Equal(t, LevelTrace.String(), "TRACE")
-}
-
-func BenchmarkLogPrintOnlyToCounter(b *testing.B) {
- var logHandle, outHandle bytes.Buffer
- n := NewNotepad(LevelCritical, LevelCritical, &outHandle, &logHandle, "TestNotePad", 0)
-
- b.ResetTimer()
- for i := 0; i < b.N; i++ {
- n.INFO.Print("Test")
- }
-}
diff --git a/vendor/github.com/spf13/pflag/bool_slice_test.go b/vendor/github.com/spf13/pflag/bool_slice_test.go
deleted file mode 100644
index b617dd237..000000000
--- a/vendor/github.com/spf13/pflag/bool_slice_test.go
+++ /dev/null
@@ -1,215 +0,0 @@
-package pflag
-
-import (
- "fmt"
- "strconv"
- "strings"
- "testing"
-)
-
-func setUpBSFlagSet(bsp *[]bool) *FlagSet {
- f := NewFlagSet("test", ContinueOnError)
- f.BoolSliceVar(bsp, "bs", []bool{}, "Command separated list!")
- return f
-}
-
-func setUpBSFlagSetWithDefault(bsp *[]bool) *FlagSet {
- f := NewFlagSet("test", ContinueOnError)
- f.BoolSliceVar(bsp, "bs", []bool{false, true}, "Command separated list!")
- return f
-}
-
-func TestEmptyBS(t *testing.T) {
- var bs []bool
- f := setUpBSFlagSet(&bs)
- err := f.Parse([]string{})
- if err != nil {
- t.Fatal("expected no error; got", err)
- }
-
- getBS, err := f.GetBoolSlice("bs")
- if err != nil {
- t.Fatal("got an error from GetBoolSlice():", err)
- }
- if len(getBS) != 0 {
- t.Fatalf("got bs %v with len=%d but expected length=0", getBS, len(getBS))
- }
-}
-
-func TestBS(t *testing.T) {
- var bs []bool
- f := setUpBSFlagSet(&bs)
-
- vals := []string{"1", "F", "TRUE", "0"}
- arg := fmt.Sprintf("--bs=%s", strings.Join(vals, ","))
- err := f.Parse([]string{arg})
- if err != nil {
- t.Fatal("expected no error; got", err)
- }
- for i, v := range bs {
- b, err := strconv.ParseBool(vals[i])
- if err != nil {
- t.Fatalf("got error: %v", err)
- }
- if b != v {
- t.Fatalf("expected is[%d] to be %s but got: %t", i, vals[i], v)
- }
- }
- getBS, err := f.GetBoolSlice("bs")
- if err != nil {
- t.Fatalf("got error: %v", err)
- }
- for i, v := range getBS {
- b, err := strconv.ParseBool(vals[i])
- if err != nil {
- t.Fatalf("got error: %v", err)
- }
- if b != v {
- t.Fatalf("expected bs[%d] to be %s but got: %t from GetBoolSlice", i, vals[i], v)
- }
- }
-}
-
-func TestBSDefault(t *testing.T) {
- var bs []bool
- f := setUpBSFlagSetWithDefault(&bs)
-
- vals := []string{"false", "T"}
-
- err := f.Parse([]string{})
- if err != nil {
- t.Fatal("expected no error; got", err)
- }
- for i, v := range bs {
- b, err := strconv.ParseBool(vals[i])
- if err != nil {
- t.Fatalf("got error: %v", err)
- }
- if b != v {
- t.Fatalf("expected bs[%d] to be %t from GetBoolSlice but got: %t", i, b, v)
- }
- }
-
- getBS, err := f.GetBoolSlice("bs")
- if err != nil {
- t.Fatal("got an error from GetBoolSlice():", err)
- }
- for i, v := range getBS {
- b, err := strconv.ParseBool(vals[i])
- if err != nil {
- t.Fatal("got an error from GetBoolSlice():", err)
- }
- if b != v {
- t.Fatalf("expected bs[%d] to be %t from GetBoolSlice but got: %t", i, b, v)
- }
- }
-}
-
-func TestBSWithDefault(t *testing.T) {
- var bs []bool
- f := setUpBSFlagSetWithDefault(&bs)
-
- vals := []string{"FALSE", "1"}
- arg := fmt.Sprintf("--bs=%s", strings.Join(vals, ","))
- err := f.Parse([]string{arg})
- if err != nil {
- t.Fatal("expected no error; got", err)
- }
- for i, v := range bs {
- b, err := strconv.ParseBool(vals[i])
- if err != nil {
- t.Fatalf("got error: %v", err)
- }
- if b != v {
- t.Fatalf("expected bs[%d] to be %t but got: %t", i, b, v)
- }
- }
-
- getBS, err := f.GetBoolSlice("bs")
- if err != nil {
- t.Fatal("got an error from GetBoolSlice():", err)
- }
- for i, v := range getBS {
- b, err := strconv.ParseBool(vals[i])
- if err != nil {
- t.Fatalf("got error: %v", err)
- }
- if b != v {
- t.Fatalf("expected bs[%d] to be %t from GetBoolSlice but got: %t", i, b, v)
- }
- }
-}
-
-func TestBSCalledTwice(t *testing.T) {
- var bs []bool
- f := setUpBSFlagSet(&bs)
-
- in := []string{"T,F", "T"}
- expected := []bool{true, false, true}
- argfmt := "--bs=%s"
- arg1 := fmt.Sprintf(argfmt, in[0])
- arg2 := fmt.Sprintf(argfmt, in[1])
- err := f.Parse([]string{arg1, arg2})
- if err != nil {
- t.Fatal("expected no error; got", err)
- }
- for i, v := range bs {
- if expected[i] != v {
- t.Fatalf("expected bs[%d] to be %t but got %t", i, expected[i], v)
- }
- }
-}
-
-func TestBSBadQuoting(t *testing.T) {
-
- tests := []struct {
- Want []bool
- FlagArg []string
- }{
- {
- Want: []bool{true, false, true},
- FlagArg: []string{"1", "0", "true"},
- },
- {
- Want: []bool{true, false},
- FlagArg: []string{"True", "F"},
- },
- {
- Want: []bool{true, false},
- FlagArg: []string{"T", "0"},
- },
- {
- Want: []bool{true, false},
- FlagArg: []string{"1", "0"},
- },
- {
- Want: []bool{true, false, false},
- FlagArg: []string{"true,false", "false"},
- },
- {
- Want: []bool{true, false, false, true, false, true, false},
- FlagArg: []string{`"true,false,false,1,0, T"`, " false "},
- },
- {
- Want: []bool{false, false, true, false, true, false, true},
- FlagArg: []string{`"0, False, T,false , true,F"`, "true"},
- },
- }
-
- for i, test := range tests {
-
- var bs []bool
- f := setUpBSFlagSet(&bs)
-
- if err := f.Parse([]string{fmt.Sprintf("--bs=%s", strings.Join(test.FlagArg, ","))}); err != nil {
- t.Fatalf("flag parsing failed with error: %s\nparsing:\t%#v\nwant:\t\t%#v",
- err, test.FlagArg, test.Want[i])
- }
-
- for j, b := range bs {
- if b != test.Want[j] {
- t.Fatalf("bad value parsed for test %d on bool %d:\nwant:\t%t\ngot:\t%t", i, j, test.Want[j], b)
- }
- }
- }
-}
diff --git a/vendor/github.com/spf13/pflag/bool_test.go b/vendor/github.com/spf13/pflag/bool_test.go
deleted file mode 100644
index a4319e79f..000000000
--- a/vendor/github.com/spf13/pflag/bool_test.go
+++ /dev/null
@@ -1,179 +0,0 @@
-// Copyright 2009 The Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package pflag
-
-import (
- "bytes"
- "strconv"
- "testing"
-)
-
-// This value can be a boolean ("true", "false") or "maybe"
-type triStateValue int
-
-const (
- triStateFalse triStateValue = 0
- triStateTrue triStateValue = 1
- triStateMaybe triStateValue = 2
-)
-
-const strTriStateMaybe = "maybe"
-
-func (v *triStateValue) IsBoolFlag() bool {
- return true
-}
-
-func (v *triStateValue) Get() interface{} {
- return triStateValue(*v)
-}
-
-func (v *triStateValue) Set(s string) error {
- if s == strTriStateMaybe {
- *v = triStateMaybe
- return nil
- }
- boolVal, err := strconv.ParseBool(s)
- if boolVal {
- *v = triStateTrue
- } else {
- *v = triStateFalse
- }
- return err
-}
-
-func (v *triStateValue) String() string {
- if *v == triStateMaybe {
- return strTriStateMaybe
- }
- return strconv.FormatBool(*v == triStateTrue)
-}
-
-// The type of the flag as required by the pflag.Value interface
-func (v *triStateValue) Type() string {
- return "version"
-}
-
-func setUpFlagSet(tristate *triStateValue) *FlagSet {
- f := NewFlagSet("test", ContinueOnError)
- *tristate = triStateFalse
- flag := f.VarPF(tristate, "tristate", "t", "tristate value (true, maybe or false)")
- flag.NoOptDefVal = "true"
- return f
-}
-
-func TestExplicitTrue(t *testing.T) {
- var tristate triStateValue
- f := setUpFlagSet(&tristate)
- err := f.Parse([]string{"--tristate=true"})
- if err != nil {
- t.Fatal("expected no error; got", err)
- }
- if tristate != triStateTrue {
- t.Fatal("expected", triStateTrue, "(triStateTrue) but got", tristate, "instead")
- }
-}
-
-func TestImplicitTrue(t *testing.T) {
- var tristate triStateValue
- f := setUpFlagSet(&tristate)
- err := f.Parse([]string{"--tristate"})
- if err != nil {
- t.Fatal("expected no error; got", err)
- }
- if tristate != triStateTrue {
- t.Fatal("expected", triStateTrue, "(triStateTrue) but got", tristate, "instead")
- }
-}
-
-func TestShortFlag(t *testing.T) {
- var tristate triStateValue
- f := setUpFlagSet(&tristate)
- err := f.Parse([]string{"-t"})
- if err != nil {
- t.Fatal("expected no error; got", err)
- }
- if tristate != triStateTrue {
- t.Fatal("expected", triStateTrue, "(triStateTrue) but got", tristate, "instead")
- }
-}
-
-func TestShortFlagExtraArgument(t *testing.T) {
- var tristate triStateValue
- f := setUpFlagSet(&tristate)
- // The"maybe"turns into an arg, since short boolean options will only do true/false
- err := f.Parse([]string{"-t", "maybe"})
- if err != nil {
- t.Fatal("expected no error; got", err)
- }
- if tristate != triStateTrue {
- t.Fatal("expected", triStateTrue, "(triStateTrue) but got", tristate, "instead")
- }
- args := f.Args()
- if len(args) != 1 || args[0] != "maybe" {
- t.Fatal("expected an extra 'maybe' argument to stick around")
- }
-}
-
-func TestExplicitMaybe(t *testing.T) {
- var tristate triStateValue
- f := setUpFlagSet(&tristate)
- err := f.Parse([]string{"--tristate=maybe"})
- if err != nil {
- t.Fatal("expected no error; got", err)
- }
- if tristate != triStateMaybe {
- t.Fatal("expected", triStateMaybe, "(triStateMaybe) but got", tristate, "instead")
- }
-}
-
-func TestExplicitFalse(t *testing.T) {
- var tristate triStateValue
- f := setUpFlagSet(&tristate)
- err := f.Parse([]string{"--tristate=false"})
- if err != nil {
- t.Fatal("expected no error; got", err)
- }
- if tristate != triStateFalse {
- t.Fatal("expected", triStateFalse, "(triStateFalse) but got", tristate, "instead")
- }
-}
-
-func TestImplicitFalse(t *testing.T) {
- var tristate triStateValue
- f := setUpFlagSet(&tristate)
- err := f.Parse([]string{})
- if err != nil {
- t.Fatal("expected no error; got", err)
- }
- if tristate != triStateFalse {
- t.Fatal("expected", triStateFalse, "(triStateFalse) but got", tristate, "instead")
- }
-}
-
-func TestInvalidValue(t *testing.T) {
- var tristate triStateValue
- f := setUpFlagSet(&tristate)
- var buf bytes.Buffer
- f.SetOutput(&buf)
- err := f.Parse([]string{"--tristate=invalid"})
- if err == nil {
- t.Fatal("expected an error but did not get any, tristate has value", tristate)
- }
-}
-
-func TestBoolP(t *testing.T) {
- b := BoolP("bool", "b", false, "bool value in CommandLine")
- c := BoolP("c", "c", false, "other bool value")
- args := []string{"--bool"}
- if err := CommandLine.Parse(args); err != nil {
- t.Error("expected no error, got ", err)
- }
- if *b != true {
- t.Errorf("expected b=true got b=%v", *b)
- }
- if *c != false {
- t.Errorf("expect c=false got c=%v", *c)
- }
-}
diff --git a/vendor/github.com/spf13/pflag/bytes.go b/vendor/github.com/spf13/pflag/bytes.go
new file mode 100644
index 000000000..12c58db9f
--- /dev/null
+++ b/vendor/github.com/spf13/pflag/bytes.go
@@ -0,0 +1,105 @@
+package pflag
+
+import (
+ "encoding/hex"
+ "fmt"
+ "strings"
+)
+
+// BytesHex adapts []byte for use as a flag. Value of flag is HEX encoded
+type bytesHexValue []byte
+
+func (bytesHex bytesHexValue) String() string {
+ return fmt.Sprintf("%X", []byte(bytesHex))
+}
+
+func (bytesHex *bytesHexValue) Set(value string) error {
+ bin, err := hex.DecodeString(strings.TrimSpace(value))
+
+ if err != nil {
+ return err
+ }
+
+ *bytesHex = bin
+
+ return nil
+}
+
+func (*bytesHexValue) Type() string {
+ return "bytesHex"
+}
+
+func newBytesHexValue(val []byte, p *[]byte) *bytesHexValue {
+ *p = val
+ return (*bytesHexValue)(p)
+}
+
+func bytesHexConv(sval string) (interface{}, error) {
+
+ bin, err := hex.DecodeString(sval)
+
+ if err == nil {
+ return bin, nil
+ }
+
+ return nil, fmt.Errorf("invalid string being converted to Bytes: %s %s", sval, err)
+}
+
+// GetBytesHex return the []byte value of a flag with the given name
+func (f *FlagSet) GetBytesHex(name string) ([]byte, error) {
+ val, err := f.getFlagType(name, "bytesHex", bytesHexConv)
+
+ if err != nil {
+ return []byte{}, err
+ }
+
+ return val.([]byte), nil
+}
+
+// BytesHexVar defines an []byte flag with specified name, default value, and usage string.
+// The argument p points to an []byte variable in which to store the value of the flag.
+func (f *FlagSet) BytesHexVar(p *[]byte, name string, value []byte, usage string) {
+ f.VarP(newBytesHexValue(value, p), name, "", usage)
+}
+
+// BytesHexVarP is like BytesHexVar, but accepts a shorthand letter that can be used after a single dash.
+func (f *FlagSet) BytesHexVarP(p *[]byte, name, shorthand string, value []byte, usage string) {
+ f.VarP(newBytesHexValue(value, p), name, shorthand, usage)
+}
+
+// BytesHexVar defines an []byte flag with specified name, default value, and usage string.
+// The argument p points to an []byte variable in which to store the value of the flag.
+func BytesHexVar(p *[]byte, name string, value []byte, usage string) {
+ CommandLine.VarP(newBytesHexValue(value, p), name, "", usage)
+}
+
+// BytesHexVarP is like BytesHexVar, but accepts a shorthand letter that can be used after a single dash.
+func BytesHexVarP(p *[]byte, name, shorthand string, value []byte, usage string) {
+ CommandLine.VarP(newBytesHexValue(value, p), name, shorthand, usage)
+}
+
+// BytesHex defines an []byte flag with specified name, default value, and usage string.
+// The return value is the address of an []byte variable that stores the value of the flag.
+func (f *FlagSet) BytesHex(name string, value []byte, usage string) *[]byte {
+ p := new([]byte)
+ f.BytesHexVarP(p, name, "", value, usage)
+ return p
+}
+
+// BytesHexP is like BytesHex, but accepts a shorthand letter that can be used after a single dash.
+func (f *FlagSet) BytesHexP(name, shorthand string, value []byte, usage string) *[]byte {
+ p := new([]byte)
+ f.BytesHexVarP(p, name, shorthand, value, usage)
+ return p
+}
+
+// BytesHex defines an []byte flag with specified name, default value, and usage string.
+// The return value is the address of an []byte variable that stores the value of the flag.
+func BytesHex(name string, value []byte, usage string) *[]byte {
+ return CommandLine.BytesHexP(name, "", value, usage)
+}
+
+// BytesHexP is like BytesHex, but accepts a shorthand letter that can be used after a single dash.
+func BytesHexP(name, shorthand string, value []byte, usage string) *[]byte {
+ return CommandLine.BytesHexP(name, shorthand, value, usage)
+}
diff --git a/vendor/github.com/spf13/pflag/count_test.go b/vendor/github.com/spf13/pflag/count_test.go
deleted file mode 100644
index 3785d375a..000000000
--- a/vendor/github.com/spf13/pflag/count_test.go
+++ /dev/null
@@ -1,56 +0,0 @@
-package pflag
-
-import (
- "os"
- "testing"
-)
-
-func setUpCount(c *int) *FlagSet {
- f := NewFlagSet("test", ContinueOnError)
- f.CountVarP(c, "verbose", "v", "a counter")
- return f
-}
-
-func TestCount(t *testing.T) {
- testCases := []struct {
- input []string
- success bool
- expected int
- }{
- {[]string{}, true, 0},
- {[]string{"-v"}, true, 1},
- {[]string{"-vvv"}, true, 3},
- {[]string{"-v", "-v", "-v"}, true, 3},
- {[]string{"-v", "--verbose", "-v"}, true, 3},
- {[]string{"-v=3", "-v"}, true, 4},
- {[]string{"--verbose=0"}, true, 0},
- {[]string{"-v=0"}, true, 0},
- {[]string{"-v=a"}, false, 0},
- }
-
- devnull, _ := os.Open(os.DevNull)
- os.Stderr = devnull
- for i := range testCases {
- var count int
- f := setUpCount(&count)
-
- tc := &testCases[i]
-
- err := f.Parse(tc.input)
- if err != nil && tc.success == true {
- t.Errorf("expected success, got %q", err)
- continue
- } else if err == nil && tc.success == false {
- t.Errorf("expected failure, got success")
- continue
- } else if tc.success {
- c, err := f.GetCount("verbose")
- if err != nil {
- t.Errorf("Got error trying to fetch the counter flag")
- }
- if c != tc.expected {
- t.Errorf("expected %d, got %d", tc.expected, c)
- }
- }
- }
-}
diff --git a/vendor/github.com/spf13/pflag/duration_slice_test.go b/vendor/github.com/spf13/pflag/duration_slice_test.go
deleted file mode 100644
index 489b012ff..000000000
--- a/vendor/github.com/spf13/pflag/duration_slice_test.go
+++ /dev/null
@@ -1,165 +0,0 @@
-// Copyright 2009 The Go Authors. All rights reserved.
-// Use of this source code ds governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package pflag
-
-import (
- "fmt"
- "strings"
- "testing"
- "time"
-)
-
-func setUpDSFlagSet(dsp *[]time.Duration) *FlagSet {
- f := NewFlagSet("test", ContinueOnError)
- f.DurationSliceVar(dsp, "ds", []time.Duration{}, "Command separated list!")
- return f
-}
-
-func setUpDSFlagSetWithDefault(dsp *[]time.Duration) *FlagSet {
- f := NewFlagSet("test", ContinueOnError)
- f.DurationSliceVar(dsp, "ds", []time.Duration{0, 1}, "Command separated list!")
- return f
-}
-
-func TestEmptyDS(t *testing.T) {
- var ds []time.Duration
- f := setUpDSFlagSet(&ds)
- err := f.Parse([]string{})
- if err != nil {
- t.Fatal("expected no error; got", err)
- }
-
- getDS, err := f.GetDurationSlice("ds")
- if err != nil {
- t.Fatal("got an error from GetDurationSlice():", err)
- }
- if len(getDS) != 0 {
- t.Fatalf("got ds %v with len=%d but expected length=0", getDS, len(getDS))
- }
-}
-
-func TestDS(t *testing.T) {
- var ds []time.Duration
- f := setUpDSFlagSet(&ds)
-
- vals := []string{"1ns", "2ms", "3m", "4h"}
- arg := fmt.Sprintf("--ds=%s", strings.Join(vals, ","))
- err := f.Parse([]string{arg})
- if err != nil {
- t.Fatal("expected no error; got", err)
- }
- for i, v := range ds {
- d, err := time.ParseDuration(vals[i])
- if err != nil {
- t.Fatalf("got error: %v", err)
- }
- if d != v {
- t.Fatalf("expected ds[%d] to be %s but got: %d", i, vals[i], v)
- }
- }
- getDS, err := f.GetDurationSlice("ds")
- if err != nil {
- t.Fatalf("got error: %v", err)
- }
- for i, v := range getDS {
- d, err := time.ParseDuration(vals[i])
- if err != nil {
- t.Fatalf("got error: %v", err)
- }
- if d != v {
- t.Fatalf("expected ds[%d] to be %s but got: %d from GetDurationSlice", i, vals[i], v)
- }
- }
-}
-
-func TestDSDefault(t *testing.T) {
- var ds []time.Duration
- f := setUpDSFlagSetWithDefault(&ds)
-
- vals := []string{"0s", "1ns"}
-
- err := f.Parse([]string{})
- if err != nil {
- t.Fatal("expected no error; got", err)
- }
- for i, v := range ds {
- d, err := time.ParseDuration(vals[i])
- if err != nil {
- t.Fatalf("got error: %v", err)
- }
- if d != v {
- t.Fatalf("expected ds[%d] to be %d but got: %d", i, d, v)
- }
- }
-
- getDS, err := f.GetDurationSlice("ds")
- if err != nil {
- t.Fatal("got an error from GetDurationSlice():", err)
- }
- for i, v := range getDS {
- d, err := time.ParseDuration(vals[i])
- if err != nil {
- t.Fatal("got an error from GetDurationSlice():", err)
- }
- if d != v {
- t.Fatalf("expected ds[%d] to be %d from GetDurationSlice but got: %d", i, d, v)
- }
- }
-}
-
-func TestDSWithDefault(t *testing.T) {
- var ds []time.Duration
- f := setUpDSFlagSetWithDefault(&ds)
-
- vals := []string{"1ns", "2ns"}
- arg := fmt.Sprintf("--ds=%s", strings.Join(vals, ","))
- err := f.Parse([]string{arg})
- if err != nil {
- t.Fatal("expected no error; got", err)
- }
- for i, v := range ds {
- d, err := time.ParseDuration(vals[i])
- if err != nil {
- t.Fatalf("got error: %v", err)
- }
- if d != v {
- t.Fatalf("expected ds[%d] to be %d but got: %d", i, d, v)
- }
- }
-
- getDS, err := f.GetDurationSlice("ds")
- if err != nil {
- t.Fatal("got an error from GetDurationSlice():", err)
- }
- for i, v := range getDS {
- d, err := time.ParseDuration(vals[i])
- if err != nil {
- t.Fatalf("got error: %v", err)
- }
- if d != v {
- t.Fatalf("expected ds[%d] to be %d from GetDurationSlice but got: %d", i, d, v)
- }
- }
-}
-
-func TestDSCalledTwice(t *testing.T) {
- var ds []time.Duration
- f := setUpDSFlagSet(&ds)
-
- in := []string{"1ns,2ns", "3ns"}
- expected := []time.Duration{1, 2, 3}
- argfmt := "--ds=%s"
- arg1 := fmt.Sprintf(argfmt, in[0])
- arg2 := fmt.Sprintf(argfmt, in[1])
- err := f.Parse([]string{arg1, arg2})
- if err != nil {
- t.Fatal("expected no error; got", err)
- }
- for i, v := range ds {
- if expected[i] != v {
- t.Fatalf("expected ds[%d] to be %d but got: %d", i, expected[i], v)
- }
- }
-}
diff --git a/vendor/github.com/spf13/pflag/example_test.go b/vendor/github.com/spf13/pflag/example_test.go
deleted file mode 100644
index abd7806fa..000000000
--- a/vendor/github.com/spf13/pflag/example_test.go
+++ /dev/null
@@ -1,36 +0,0 @@
-// Copyright 2012 The Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package pflag_test
-
-import (
- "fmt"
-
- "github.com/spf13/pflag"
-)
-
-func ExampleShorthandLookup() {
- name := "verbose"
- short := name[:1]
-
- pflag.BoolP(name, short, false, "verbose output")
-
- // len(short) must be == 1
- flag := pflag.ShorthandLookup(short)
-
- fmt.Println(flag.Name)
-}
-
-func ExampleFlagSet_ShorthandLookup() {
- name := "verbose"
- short := name[:1]
-
- fs := pflag.NewFlagSet("Example", pflag.ContinueOnError)
- fs.BoolP(name, short, false, "verbose output")
-
- // len(short) must be == 1
- flag := fs.ShorthandLookup(short)
-
- fmt.Println(flag.Name)
-}
diff --git a/vendor/github.com/spf13/pflag/export_test.go b/vendor/github.com/spf13/pflag/export_test.go
deleted file mode 100644
index 9318fee00..000000000
--- a/vendor/github.com/spf13/pflag/export_test.go
+++ /dev/null
@@ -1,29 +0,0 @@
-// Copyright 2010 The Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package pflag
-
-import (
- "io/ioutil"
- "os"
-)
-
-// Additional routines compiled into the package only during testing.
-
-// ResetForTesting clears all flag state and sets the usage function as directed.
-// After calling ResetForTesting, parse errors in flag handling will not
-// exit the program.
-func ResetForTesting(usage func()) {
- CommandLine = &FlagSet{
- name: os.Args[0],
- errorHandling: ContinueOnError,
- output: ioutil.Discard,
- }
- Usage = usage
-}
-
-// GetCommandLine returns the default FlagSet.
-func GetCommandLine() *FlagSet {
- return CommandLine
-}
diff --git a/vendor/github.com/spf13/pflag/flag.go b/vendor/github.com/spf13/pflag/flag.go
index 28538c075..5eadc84e3 100644
--- a/vendor/github.com/spf13/pflag/flag.go
+++ b/vendor/github.com/spf13/pflag/flag.go
@@ -101,6 +101,7 @@ package pflag
import (
"bytes"
"errors"
+ goflag "flag"
"fmt"
"io"
"os"
@@ -123,6 +124,12 @@ const (
PanicOnError
)
+// ParseErrorsWhitelist defines the parsing errors that can be ignored
+type ParseErrorsWhitelist struct {
+ // UnknownFlags will ignore unknown flags errors and continue parsing rest of the flags
+ UnknownFlags bool
+}
+
// NormalizedName is a flag name that has been normalized according to rules
// for the FlagSet (e.g. making '-' and '_' equivalent).
type NormalizedName string
@@ -138,6 +145,9 @@ type FlagSet struct {
// help/usage messages.
SortFlags bool
+ // ParseErrorsWhitelist is used to configure a whitelist of errors
+ ParseErrorsWhitelist ParseErrorsWhitelist
+
name string
parsed bool
actual map[NormalizedName]*Flag
@@ -153,6 +163,8 @@ type FlagSet struct {
output io.Writer // nil means stderr; use out() accessor
interspersed bool // allow interspersed option/non-option args
normalizeNameFunc func(f *FlagSet, name string) NormalizedName
+
+ addedGoFlagSets []*goflag.FlagSet
}
// A Flag represents the state of a flag.
@@ -267,16 +279,16 @@ func (f *FlagSet) VisitAll(fn func(*Flag)) {
}
}
-// HasFlags returns a bool to indicate if the FlagSet has any flags definied.
+// HasFlags returns a bool to indicate if the FlagSet has any flags defined.
func (f *FlagSet) HasFlags() bool {
return len(f.formal) > 0
}
// HasAvailableFlags returns a bool to indicate if the FlagSet has any flags
-// definied that are not hidden or deprecated.
+// that are not hidden.
func (f *FlagSet) HasAvailableFlags() bool {
for _, flag := range f.formal {
- if !flag.Hidden && len(flag.Deprecated) == 0 {
+ if !flag.Hidden {
return true
}
}
@@ -386,6 +398,7 @@ func (f *FlagSet) MarkDeprecated(name string, usageMessage string) error {
return fmt.Errorf("deprecated message for flag %q must be set", name)
}
flag.Deprecated = usageMessage
+ flag.Hidden = true
return nil
}
@@ -586,11 +599,14 @@ func wrapN(i, slop int, s string) (string, string) {
return s, ""
}
- w := strings.LastIndexAny(s[:i], " \t")
+ w := strings.LastIndexAny(s[:i], " \t\n")
if w <= 0 {
return s, ""
}
-
+ nlPos := strings.LastIndex(s[:i], "\n")
+ if nlPos > 0 && nlPos < w {
+ return s[:nlPos], s[nlPos+1:]
+ }
return s[:w], s[w+1:]
}
@@ -599,7 +615,7 @@ func wrapN(i, slop int, s string) (string, string) {
// caller). Pass `w` == 0 to do no wrapping
func wrap(i, w int, s string) string {
if w == 0 {
- return s
+ return strings.Replace(s, "\n", "\n"+strings.Repeat(" ", i), -1)
}
// space between indent i and end of line width w into which
@@ -617,7 +633,7 @@ func wrap(i, w int, s string) string {
}
// If still not enough space then don't even try to wrap.
if wrap < 24 {
- return s
+ return strings.Replace(s, "\n", r, -1)
}
// Try to avoid short orphan words on the final line, by
@@ -629,14 +645,14 @@ func wrap(i, w int, s string) string {
// Handle first line, which is indented by the caller (or the
// special case above)
l, s = wrapN(wrap, slop, s)
- r = r + l
+ r = r + strings.Replace(l, "\n", "\n"+strings.Repeat(" ", i), -1)
// Now wrap the rest
for s != "" {
var t string
t, s = wrapN(wrap, slop, s)
- r = r + "\n" + strings.Repeat(" ", i) + t
+ r = r + "\n" + strings.Repeat(" ", i) + strings.Replace(t, "\n", "\n"+strings.Repeat(" ", i), -1)
}
return r
@@ -653,7 +669,7 @@ func (f *FlagSet) FlagUsagesWrapped(cols int) string {
maxlen := 0
f.VisitAll(func(flag *Flag) {
- if flag.Deprecated != "" || flag.Hidden {
+ if flag.Hidden {
return
}
@@ -700,6 +716,9 @@ func (f *FlagSet) FlagUsagesWrapped(cols int) string {
line += fmt.Sprintf(" (default %s)", flag.DefValue)
}
}
+ if len(flag.Deprecated) != 0 {
+ line += fmt.Sprintf(" (DEPRECATED: %s)", flag.Deprecated)
+ }
lines = append(lines, line)
})
@@ -896,6 +915,25 @@ func (f *FlagSet) usage() {
}
}
+//--unknown (args will be empty)
+//--unknown --next-flag ... (args will be --next-flag ...)
+//--unknown arg ... (args will be arg ...)
+func stripUnknownFlagValue(args []string) []string {
+ if len(args) == 0 {
+ //--unknown
+ return args
+ }
+
+ first := args[0]
+ if first[0] == '-' {
+ //--unknown --next-flag ...
+ return args
+ }
+
+ //--unknown arg ... (args will be arg ...)
+ return args[1:]
+}
+
func (f *FlagSet) parseLongArg(s string, args []string, fn parseFunc) (a []string, err error) {
a = args
name := s[2:]
@@ -907,13 +945,24 @@ func (f *FlagSet) parseLongArg(s string, args []string, fn parseFunc) (a []strin
split := strings.SplitN(name, "=", 2)
name = split[0]
flag, exists := f.formal[f.normalizeFlagName(name)]
+
if !exists {
- if name == "help" { // special case for nice help message.
+ switch {
+ case name == "help":
f.usage()
return a, ErrHelp
+ case f.ParseErrorsWhitelist.UnknownFlags:
+ // --unknown=unknownval arg ...
+ // we do not want to lose arg in this case
+ if len(split) >= 2 {
+ return a, nil
+ }
+
+ return stripUnknownFlagValue(a), nil
+ default:
+ err = f.failf("unknown flag: --%s", name)
+ return
}
- err = f.failf("unknown flag: --%s", name)
- return
}
var value string
@@ -951,13 +1000,25 @@ func (f *FlagSet) parseSingleShortArg(shorthands string, args []string, fn parse
flag, exists := f.shorthands[c]
if !exists {
- if c == 'h' { // special case for nice help message.
+ switch {
+ case c == 'h':
f.usage()
err = ErrHelp
return
+ case f.ParseErrorsWhitelist.UnknownFlags:
+ // '-f=arg arg ...'
+ // we do not want to lose arg in this case
+ if len(shorthands) > 2 && shorthands[1] == '=' {
+ outShorts = ""
+ return
+ }
+
+ outArgs = stripUnknownFlagValue(outArgs)
+ return
+ default:
+ err = f.failf("unknown shorthand flag: %q in -%s", c, shorthands)
+ return
}
- err = f.failf("unknown shorthand flag: %q in -%s", c, shorthands)
- return
}
var value string
@@ -1044,6 +1105,11 @@ func (f *FlagSet) parseArgs(args []string, fn parseFunc) (err error) {
// are defined and before flags are accessed by the program.
// The return value will be ErrHelp if -help was set but not defined.
func (f *FlagSet) Parse(arguments []string) error {
+ if f.addedGoFlagSets != nil {
+ for _, goFlagSet := range f.addedGoFlagSets {
+ goFlagSet.Parse(nil)
+ }
+ }
f.parsed = true
if len(arguments) < 0 {
diff --git a/vendor/github.com/spf13/pflag/flag_test.go b/vendor/github.com/spf13/pflag/flag_test.go
deleted file mode 100644
index d587752f3..000000000
--- a/vendor/github.com/spf13/pflag/flag_test.go
+++ /dev/null
@@ -1,1158 +0,0 @@
-// Copyright 2009 The Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package pflag
-
-import (
- "bytes"
- "fmt"
- "io"
- "io/ioutil"
- "net"
- "os"
- "reflect"
- "sort"
- "strconv"
- "strings"
- "testing"
- "time"
-)
-
-var (
- testBool = Bool("test_bool", false, "bool value")
- testInt = Int("test_int", 0, "int value")
- testInt64 = Int64("test_int64", 0, "int64 value")
- testUint = Uint("test_uint", 0, "uint value")
- testUint64 = Uint64("test_uint64", 0, "uint64 value")
- testString = String("test_string", "0", "string value")
- testFloat = Float64("test_float64", 0, "float64 value")
- testDuration = Duration("test_duration", 0, "time.Duration value")
- testOptionalInt = Int("test_optional_int", 0, "optional int value")
- normalizeFlagNameInvocations = 0
-)
-
-func boolString(s string) string {
- if s == "0" {
- return "false"
- }
- return "true"
-}
-
-func TestEverything(t *testing.T) {
- m := make(map[string]*Flag)
- desired := "0"
- visitor := func(f *Flag) {
- if len(f.Name) > 5 && f.Name[0:5] == "test_" {
- m[f.Name] = f
- ok := false
- switch {
- case f.Value.String() == desired:
- ok = true
- case f.Name == "test_bool" && f.Value.String() == boolString(desired):
- ok = true
- case f.Name == "test_duration" && f.Value.String() == desired+"s":
- ok = true
- }
- if !ok {
- t.Error("Visit: bad value", f.Value.String(), "for", f.Name)
- }
- }
- }
- VisitAll(visitor)
- if len(m) != 9 {
- t.Error("VisitAll misses some flags")
- for k, v := range m {
- t.Log(k, *v)
- }
- }
- m = make(map[string]*Flag)
- Visit(visitor)
- if len(m) != 0 {
- t.Errorf("Visit sees unset flags")
- for k, v := range m {
- t.Log(k, *v)
- }
- }
- // Now set all flags
- Set("test_bool", "true")
- Set("test_int", "1")
- Set("test_int64", "1")
- Set("test_uint", "1")
- Set("test_uint64", "1")
- Set("test_string", "1")
- Set("test_float64", "1")
- Set("test_duration", "1s")
- Set("test_optional_int", "1")
- desired = "1"
- Visit(visitor)
- if len(m) != 9 {
- t.Error("Visit fails after set")
- for k, v := range m {
- t.Log(k, *v)
- }
- }
- // Now test they're visited in sort order.
- var flagNames []string
- Visit(func(f *Flag) { flagNames = append(flagNames, f.Name) })
- if !sort.StringsAreSorted(flagNames) {
- t.Errorf("flag names not sorted: %v", flagNames)
- }
-}
-
-func TestUsage(t *testing.T) {
- called := false
- ResetForTesting(func() { called = true })
- if GetCommandLine().Parse([]string{"--x"}) == nil {
- t.Error("parse did not fail for unknown flag")
- }
- if called {
- t.Error("did call Usage while using ContinueOnError")
- }
-}
-
-func TestAddFlagSet(t *testing.T) {
- oldSet := NewFlagSet("old", ContinueOnError)
- newSet := NewFlagSet("new", ContinueOnError)
-
- oldSet.String("flag1", "flag1", "flag1")
- oldSet.String("flag2", "flag2", "flag2")
-
- newSet.String("flag2", "flag2", "flag2")
- newSet.String("flag3", "flag3", "flag3")
-
- oldSet.AddFlagSet(newSet)
-
- if len(oldSet.formal) != 3 {
- t.Errorf("Unexpected result adding a FlagSet to a FlagSet %v", oldSet)
- }
-}
-
-func TestAnnotation(t *testing.T) {
- f := NewFlagSet("shorthand", ContinueOnError)
-
- if err := f.SetAnnotation("missing-flag", "key", nil); err == nil {
- t.Errorf("Expected error setting annotation on non-existent flag")
- }
-
- f.StringP("stringa", "a", "", "string value")
- if err := f.SetAnnotation("stringa", "key", nil); err != nil {
- t.Errorf("Unexpected error setting new nil annotation: %v", err)
- }
- if annotation := f.Lookup("stringa").Annotations["key"]; annotation != nil {
- t.Errorf("Unexpected annotation: %v", annotation)
- }
-
- f.StringP("stringb", "b", "", "string2 value")
- if err := f.SetAnnotation("stringb", "key", []string{"value1"}); err != nil {
- t.Errorf("Unexpected error setting new annotation: %v", err)
- }
- if annotation := f.Lookup("stringb").Annotations["key"]; !reflect.DeepEqual(annotation, []string{"value1"}) {
- t.Errorf("Unexpected annotation: %v", annotation)
- }
-
- if err := f.SetAnnotation("stringb", "key", []string{"value2"}); err != nil {
- t.Errorf("Unexpected error updating annotation: %v", err)
- }
- if annotation := f.Lookup("stringb").Annotations["key"]; !reflect.DeepEqual(annotation, []string{"value2"}) {
- t.Errorf("Unexpected annotation: %v", annotation)
- }
-}
-
-func testParse(f *FlagSet, t *testing.T) {
- if f.Parsed() {
- t.Error("f.Parse() = true before Parse")
- }
- boolFlag := f.Bool("bool", false, "bool value")
- bool2Flag := f.Bool("bool2", false, "bool2 value")
- bool3Flag := f.Bool("bool3", false, "bool3 value")
- intFlag := f.Int("int", 0, "int value")
- int8Flag := f.Int8("int8", 0, "int value")
- int16Flag := f.Int16("int16", 0, "int value")
- int32Flag := f.Int32("int32", 0, "int value")
- int64Flag := f.Int64("int64", 0, "int64 value")
- uintFlag := f.Uint("uint", 0, "uint value")
- uint8Flag := f.Uint8("uint8", 0, "uint value")
- uint16Flag := f.Uint16("uint16", 0, "uint value")
- uint32Flag := f.Uint32("uint32", 0, "uint value")
- uint64Flag := f.Uint64("uint64", 0, "uint64 value")
- stringFlag := f.String("string", "0", "string value")
- float32Flag := f.Float32("float32", 0, "float32 value")
- float64Flag := f.Float64("float64", 0, "float64 value")
- ipFlag := f.IP("ip", net.ParseIP("127.0.0.1"), "ip value")
- maskFlag := f.IPMask("mask", ParseIPv4Mask("0.0.0.0"), "mask value")
- durationFlag := f.Duration("duration", 5*time.Second, "time.Duration value")
- optionalIntNoValueFlag := f.Int("optional-int-no-value", 0, "int value")
- f.Lookup("optional-int-no-value").NoOptDefVal = "9"
- optionalIntWithValueFlag := f.Int("optional-int-with-value", 0, "int value")
- f.Lookup("optional-int-no-value").NoOptDefVal = "9"
- extra := "one-extra-argument"
- args := []string{
- "--bool",
- "--bool2=true",
- "--bool3=false",
- "--int=22",
- "--int8=-8",
- "--int16=-16",
- "--int32=-32",
- "--int64=0x23",
- "--uint", "24",
- "--uint8=8",
- "--uint16=16",
- "--uint32=32",
- "--uint64=25",
- "--string=hello",
- "--float32=-172e12",
- "--float64=2718e28",
- "--ip=10.11.12.13",
- "--mask=255.255.255.0",
- "--duration=2m",
- "--optional-int-no-value",
- "--optional-int-with-value=42",
- extra,
- }
- if err := f.Parse(args); err != nil {
- t.Fatal(err)
- }
- if !f.Parsed() {
- t.Error("f.Parse() = false after Parse")
- }
- if *boolFlag != true {
- t.Error("bool flag should be true, is ", *boolFlag)
- }
- if v, err := f.GetBool("bool"); err != nil || v != *boolFlag {
- t.Error("GetBool does not work.")
- }
- if *bool2Flag != true {
- t.Error("bool2 flag should be true, is ", *bool2Flag)
- }
- if *bool3Flag != false {
- t.Error("bool3 flag should be false, is ", *bool2Flag)
- }
- if *intFlag != 22 {
- t.Error("int flag should be 22, is ", *intFlag)
- }
- if v, err := f.GetInt("int"); err != nil || v != *intFlag {
- t.Error("GetInt does not work.")
- }
- if *int8Flag != -8 {
- t.Error("int8 flag should be 0x23, is ", *int8Flag)
- }
- if *int16Flag != -16 {
- t.Error("int16 flag should be -16, is ", *int16Flag)
- }
- if v, err := f.GetInt8("int8"); err != nil || v != *int8Flag {
- t.Error("GetInt8 does not work.")
- }
- if v, err := f.GetInt16("int16"); err != nil || v != *int16Flag {
- t.Error("GetInt16 does not work.")
- }
- if *int32Flag != -32 {
- t.Error("int32 flag should be 0x23, is ", *int32Flag)
- }
- if v, err := f.GetInt32("int32"); err != nil || v != *int32Flag {
- t.Error("GetInt32 does not work.")
- }
- if *int64Flag != 0x23 {
- t.Error("int64 flag should be 0x23, is ", *int64Flag)
- }
- if v, err := f.GetInt64("int64"); err != nil || v != *int64Flag {
- t.Error("GetInt64 does not work.")
- }
- if *uintFlag != 24 {
- t.Error("uint flag should be 24, is ", *uintFlag)
- }
- if v, err := f.GetUint("uint"); err != nil || v != *uintFlag {
- t.Error("GetUint does not work.")
- }
- if *uint8Flag != 8 {
- t.Error("uint8 flag should be 8, is ", *uint8Flag)
- }
- if v, err := f.GetUint8("uint8"); err != nil || v != *uint8Flag {
- t.Error("GetUint8 does not work.")
- }
- if *uint16Flag != 16 {
- t.Error("uint16 flag should be 16, is ", *uint16Flag)
- }
- if v, err := f.GetUint16("uint16"); err != nil || v != *uint16Flag {
- t.Error("GetUint16 does not work.")
- }
- if *uint32Flag != 32 {
- t.Error("uint32 flag should be 32, is ", *uint32Flag)
- }
- if v, err := f.GetUint32("uint32"); err != nil || v != *uint32Flag {
- t.Error("GetUint32 does not work.")
- }
- if *uint64Flag != 25 {
- t.Error("uint64 flag should be 25, is ", *uint64Flag)
- }
- if v, err := f.GetUint64("uint64"); err != nil || v != *uint64Flag {
- t.Error("GetUint64 does not work.")
- }
- if *stringFlag != "hello" {
- t.Error("string flag should be `hello`, is ", *stringFlag)
- }
- if v, err := f.GetString("string"); err != nil || v != *stringFlag {
- t.Error("GetString does not work.")
- }
- if *float32Flag != -172e12 {
- t.Error("float32 flag should be -172e12, is ", *float32Flag)
- }
- if v, err := f.GetFloat32("float32"); err != nil || v != *float32Flag {
- t.Errorf("GetFloat32 returned %v but float32Flag was %v", v, *float32Flag)
- }
- if *float64Flag != 2718e28 {
- t.Error("float64 flag should be 2718e28, is ", *float64Flag)
- }
- if v, err := f.GetFloat64("float64"); err != nil || v != *float64Flag {
- t.Errorf("GetFloat64 returned %v but float64Flag was %v", v, *float64Flag)
- }
- if !(*ipFlag).Equal(net.ParseIP("10.11.12.13")) {
- t.Error("ip flag should be 10.11.12.13, is ", *ipFlag)
- }
- if v, err := f.GetIP("ip"); err != nil || !v.Equal(*ipFlag) {
- t.Errorf("GetIP returned %v but ipFlag was %v", v, *ipFlag)
- }
- if (*maskFlag).String() != ParseIPv4Mask("255.255.255.0").String() {
- t.Error("mask flag should be 255.255.255.0, is ", (*maskFlag).String())
- }
- if v, err := f.GetIPv4Mask("mask"); err != nil || v.String() != (*maskFlag).String() {
- t.Errorf("GetIP returned %v maskFlag was %v error was %v", v, *maskFlag, err)
- }
- if *durationFlag != 2*time.Minute {
- t.Error("duration flag should be 2m, is ", *durationFlag)
- }
- if v, err := f.GetDuration("duration"); err != nil || v != *durationFlag {
- t.Error("GetDuration does not work.")
- }
- if _, err := f.GetInt("duration"); err == nil {
- t.Error("GetInt parsed a time.Duration?!?!")
- }
- if *optionalIntNoValueFlag != 9 {
- t.Error("optional int flag should be the default value, is ", *optionalIntNoValueFlag)
- }
- if *optionalIntWithValueFlag != 42 {
- t.Error("optional int flag should be 42, is ", *optionalIntWithValueFlag)
- }
- if len(f.Args()) != 1 {
- t.Error("expected one argument, got", len(f.Args()))
- } else if f.Args()[0] != extra {
- t.Errorf("expected argument %q got %q", extra, f.Args()[0])
- }
-}
-
-func testParseAll(f *FlagSet, t *testing.T) {
- if f.Parsed() {
- t.Error("f.Parse() = true before Parse")
- }
- f.BoolP("boola", "a", false, "bool value")
- f.BoolP("boolb", "b", false, "bool2 value")
- f.BoolP("boolc", "c", false, "bool3 value")
- f.BoolP("boold", "d", false, "bool4 value")
- f.StringP("stringa", "s", "0", "string value")
- f.StringP("stringz", "z", "0", "string value")
- f.StringP("stringx", "x", "0", "string value")
- f.StringP("stringy", "y", "0", "string value")
- f.Lookup("stringx").NoOptDefVal = "1"
- args := []string{
- "-ab",
- "-cs=xx",
- "--stringz=something",
- "-d=true",
- "-x",
- "-y",
- "ee",
- }
- want := []string{
- "boola", "true",
- "boolb", "true",
- "boolc", "true",
- "stringa", "xx",
- "stringz", "something",
- "boold", "true",
- "stringx", "1",
- "stringy", "ee",
- }
- got := []string{}
- store := func(flag *Flag, value string) error {
- got = append(got, flag.Name)
- if len(value) > 0 {
- got = append(got, value)
- }
- return nil
- }
- if err := f.ParseAll(args, store); err != nil {
- t.Errorf("expected no error, got %s", err)
- }
- if !f.Parsed() {
- t.Errorf("f.Parse() = false after Parse")
- }
- if !reflect.DeepEqual(got, want) {
- t.Errorf("f.ParseAll() fail to restore the args")
- t.Errorf("Got: %v", got)
- t.Errorf("Want: %v", want)
- }
-}
-
-func TestShorthand(t *testing.T) {
- f := NewFlagSet("shorthand", ContinueOnError)
- if f.Parsed() {
- t.Error("f.Parse() = true before Parse")
- }
- boolaFlag := f.BoolP("boola", "a", false, "bool value")
- boolbFlag := f.BoolP("boolb", "b", false, "bool2 value")
- boolcFlag := f.BoolP("boolc", "c", false, "bool3 value")
- booldFlag := f.BoolP("boold", "d", false, "bool4 value")
- stringaFlag := f.StringP("stringa", "s", "0", "string value")
- stringzFlag := f.StringP("stringz", "z", "0", "string value")
- extra := "interspersed-argument"
- notaflag := "--i-look-like-a-flag"
- args := []string{
- "-ab",
- extra,
- "-cs",
- "hello",
- "-z=something",
- "-d=true",
- "--",
- notaflag,
- }
- f.SetOutput(ioutil.Discard)
- if err := f.Parse(args); err != nil {
- t.Error("expected no error, got ", err)
- }
- if !f.Parsed() {
- t.Error("f.Parse() = false after Parse")
- }
- if *boolaFlag != true {
- t.Error("boola flag should be true, is ", *boolaFlag)
- }
- if *boolbFlag != true {
- t.Error("boolb flag should be true, is ", *boolbFlag)
- }
- if *boolcFlag != true {
- t.Error("boolc flag should be true, is ", *boolcFlag)
- }
- if *booldFlag != true {
- t.Error("boold flag should be true, is ", *booldFlag)
- }
- if *stringaFlag != "hello" {
- t.Error("stringa flag should be `hello`, is ", *stringaFlag)
- }
- if *stringzFlag != "something" {
- t.Error("stringz flag should be `something`, is ", *stringzFlag)
- }
- if len(f.Args()) != 2 {
- t.Error("expected one argument, got", len(f.Args()))
- } else if f.Args()[0] != extra {
- t.Errorf("expected argument %q got %q", extra, f.Args()[0])
- } else if f.Args()[1] != notaflag {
- t.Errorf("expected argument %q got %q", notaflag, f.Args()[1])
- }
- if f.ArgsLenAtDash() != 1 {
- t.Errorf("expected argsLenAtDash %d got %d", f.ArgsLenAtDash(), 1)
- }
-}
-
-func TestShorthandLookup(t *testing.T) {
- f := NewFlagSet("shorthand", ContinueOnError)
- if f.Parsed() {
- t.Error("f.Parse() = true before Parse")
- }
- f.BoolP("boola", "a", false, "bool value")
- f.BoolP("boolb", "b", false, "bool2 value")
- args := []string{
- "-ab",
- }
- f.SetOutput(ioutil.Discard)
- if err := f.Parse(args); err != nil {
- t.Error("expected no error, got ", err)
- }
- if !f.Parsed() {
- t.Error("f.Parse() = false after Parse")
- }
- flag := f.ShorthandLookup("a")
- if flag == nil {
- t.Errorf("f.ShorthandLookup(\"a\") returned nil")
- }
- if flag.Name != "boola" {
- t.Errorf("f.ShorthandLookup(\"a\") found %q instead of \"boola\"", flag.Name)
- }
- flag = f.ShorthandLookup("")
- if flag != nil {
- t.Errorf("f.ShorthandLookup(\"\") did not return nil")
- }
- defer func() {
- recover()
- }()
- flag = f.ShorthandLookup("ab")
- // should NEVER get here. lookup should panic. defer'd func should recover it.
- t.Errorf("f.ShorthandLookup(\"ab\") did not panic")
-}
-
-func TestParse(t *testing.T) {
- ResetForTesting(func() { t.Error("bad parse") })
- testParse(GetCommandLine(), t)
-}
-
-func TestParseAll(t *testing.T) {
- ResetForTesting(func() { t.Error("bad parse") })
- testParseAll(GetCommandLine(), t)
-}
-
-func TestFlagSetParse(t *testing.T) {
- testParse(NewFlagSet("test", ContinueOnError), t)
-}
-
-func TestChangedHelper(t *testing.T) {
- f := NewFlagSet("changedtest", ContinueOnError)
- f.Bool("changed", false, "changed bool")
- f.Bool("settrue", true, "true to true")
- f.Bool("setfalse", false, "false to false")
- f.Bool("unchanged", false, "unchanged bool")
-
- args := []string{"--changed", "--settrue", "--setfalse=false"}
- if err := f.Parse(args); err != nil {
- t.Error("f.Parse() = false after Parse")
- }
- if !f.Changed("changed") {
- t.Errorf("--changed wasn't changed!")
- }
- if !f.Changed("settrue") {
- t.Errorf("--settrue wasn't changed!")
- }
- if !f.Changed("setfalse") {
- t.Errorf("--setfalse wasn't changed!")
- }
- if f.Changed("unchanged") {
- t.Errorf("--unchanged was changed!")
- }
- if f.Changed("invalid") {
- t.Errorf("--invalid was changed!")
- }
- if f.ArgsLenAtDash() != -1 {
- t.Errorf("Expected argsLenAtDash: %d but got %d", -1, f.ArgsLenAtDash())
- }
-}
-
-func replaceSeparators(name string, from []string, to string) string {
- result := name
- for _, sep := range from {
- result = strings.Replace(result, sep, to, -1)
- }
- // Type convert to indicate normalization has been done.
- return result
-}
-
-func wordSepNormalizeFunc(f *FlagSet, name string) NormalizedName {
- seps := []string{"-", "_"}
- name = replaceSeparators(name, seps, ".")
- normalizeFlagNameInvocations++
-
- return NormalizedName(name)
-}
-
-func testWordSepNormalizedNames(args []string, t *testing.T) {
- f := NewFlagSet("normalized", ContinueOnError)
- if f.Parsed() {
- t.Error("f.Parse() = true before Parse")
- }
- withDashFlag := f.Bool("with-dash-flag", false, "bool value")
- // Set this after some flags have been added and before others.
- f.SetNormalizeFunc(wordSepNormalizeFunc)
- withUnderFlag := f.Bool("with_under_flag", false, "bool value")
- withBothFlag := f.Bool("with-both_flag", false, "bool value")
- if err := f.Parse(args); err != nil {
- t.Fatal(err)
- }
- if !f.Parsed() {
- t.Error("f.Parse() = false after Parse")
- }
- if *withDashFlag != true {
- t.Error("withDashFlag flag should be true, is ", *withDashFlag)
- }
- if *withUnderFlag != true {
- t.Error("withUnderFlag flag should be true, is ", *withUnderFlag)
- }
- if *withBothFlag != true {
- t.Error("withBothFlag flag should be true, is ", *withBothFlag)
- }
-}
-
-func TestWordSepNormalizedNames(t *testing.T) {
- args := []string{
- "--with-dash-flag",
- "--with-under-flag",
- "--with-both-flag",
- }
- testWordSepNormalizedNames(args, t)
-
- args = []string{
- "--with_dash_flag",
- "--with_under_flag",
- "--with_both_flag",
- }
- testWordSepNormalizedNames(args, t)
-
- args = []string{
- "--with-dash_flag",
- "--with-under_flag",
- "--with-both_flag",
- }
- testWordSepNormalizedNames(args, t)
-}
-
-func aliasAndWordSepFlagNames(f *FlagSet, name string) NormalizedName {
- seps := []string{"-", "_"}
-
- oldName := replaceSeparators("old-valid_flag", seps, ".")
- newName := replaceSeparators("valid-flag", seps, ".")
-
- name = replaceSeparators(name, seps, ".")
- switch name {
- case oldName:
- name = newName
- }
-
- return NormalizedName(name)
-}
-
-func TestCustomNormalizedNames(t *testing.T) {
- f := NewFlagSet("normalized", ContinueOnError)
- if f.Parsed() {
- t.Error("f.Parse() = true before Parse")
- }
-
- validFlag := f.Bool("valid-flag", false, "bool value")
- f.SetNormalizeFunc(aliasAndWordSepFlagNames)
- someOtherFlag := f.Bool("some-other-flag", false, "bool value")
-
- args := []string{"--old_valid_flag", "--some-other_flag"}
- if err := f.Parse(args); err != nil {
- t.Fatal(err)
- }
-
- if *validFlag != true {
- t.Errorf("validFlag is %v even though we set the alias --old_valid_falg", *validFlag)
- }
- if *someOtherFlag != true {
- t.Error("someOtherFlag should be true, is ", *someOtherFlag)
- }
-}
-
-// Every flag we add, the name (displayed also in usage) should normalized
-func TestNormalizationFuncShouldChangeFlagName(t *testing.T) {
- // Test normalization after addition
- f := NewFlagSet("normalized", ContinueOnError)
-
- f.Bool("valid_flag", false, "bool value")
- if f.Lookup("valid_flag").Name != "valid_flag" {
- t.Error("The new flag should have the name 'valid_flag' instead of ", f.Lookup("valid_flag").Name)
- }
-
- f.SetNormalizeFunc(wordSepNormalizeFunc)
- if f.Lookup("valid_flag").Name != "valid.flag" {
- t.Error("The new flag should have the name 'valid.flag' instead of ", f.Lookup("valid_flag").Name)
- }
-
- // Test normalization before addition
- f = NewFlagSet("normalized", ContinueOnError)
- f.SetNormalizeFunc(wordSepNormalizeFunc)
-
- f.Bool("valid_flag", false, "bool value")
- if f.Lookup("valid_flag").Name != "valid.flag" {
- t.Error("The new flag should have the name 'valid.flag' instead of ", f.Lookup("valid_flag").Name)
- }
-}
-
-// Related to https://github.com/spf13/cobra/issues/521.
-func TestNormalizationSharedFlags(t *testing.T) {
- f := NewFlagSet("set f", ContinueOnError)
- g := NewFlagSet("set g", ContinueOnError)
- nfunc := wordSepNormalizeFunc
- testName := "valid_flag"
- normName := nfunc(nil, testName)
- if testName == string(normName) {
- t.Error("TestNormalizationSharedFlags meaningless: the original and normalized flag names are identical:", testName)
- }
-
- f.Bool(testName, false, "bool value")
- g.AddFlagSet(f)
-
- f.SetNormalizeFunc(nfunc)
- g.SetNormalizeFunc(nfunc)
-
- if len(f.formal) != 1 {
- t.Error("Normalizing flags should not result in duplications in the flag set:", f.formal)
- }
- if f.orderedFormal[0].Name != string(normName) {
- t.Error("Flag name not normalized")
- }
- for k := range f.formal {
- if k != "valid.flag" {
- t.Errorf("The key in the flag map should have been normalized: wanted \"%s\", got \"%s\" instead", normName, k)
- }
- }
-
- if !reflect.DeepEqual(f.formal, g.formal) || !reflect.DeepEqual(f.orderedFormal, g.orderedFormal) {
- t.Error("Two flag sets sharing the same flags should stay consistent after being normalized. Original set:", f.formal, "Duplicate set:", g.formal)
- }
-}
-
-func TestNormalizationSetFlags(t *testing.T) {
- f := NewFlagSet("normalized", ContinueOnError)
- nfunc := wordSepNormalizeFunc
- testName := "valid_flag"
- normName := nfunc(nil, testName)
- if testName == string(normName) {
- t.Error("TestNormalizationSetFlags meaningless: the original and normalized flag names are identical:", testName)
- }
-
- f.Bool(testName, false, "bool value")
- f.Set(testName, "true")
- f.SetNormalizeFunc(nfunc)
-
- if len(f.formal) != 1 {
- t.Error("Normalizing flags should not result in duplications in the flag set:", f.formal)
- }
- if f.orderedFormal[0].Name != string(normName) {
- t.Error("Flag name not normalized")
- }
- for k := range f.formal {
- if k != "valid.flag" {
- t.Errorf("The key in the flag map should have been normalized: wanted \"%s\", got \"%s\" instead", normName, k)
- }
- }
-
- if !reflect.DeepEqual(f.formal, f.actual) {
- t.Error("The map of set flags should get normalized. Formal:", f.formal, "Actual:", f.actual)
- }
-}
-
-// Declare a user-defined flag type.
-type flagVar []string
-
-func (f *flagVar) String() string {
- return fmt.Sprint([]string(*f))
-}
-
-func (f *flagVar) Set(value string) error {
- *f = append(*f, value)
- return nil
-}
-
-func (f *flagVar) Type() string {
- return "flagVar"
-}
-
-func TestUserDefined(t *testing.T) {
- var flags FlagSet
- flags.Init("test", ContinueOnError)
- var v flagVar
- flags.VarP(&v, "v", "v", "usage")
- if err := flags.Parse([]string{"--v=1", "-v2", "-v", "3"}); err != nil {
- t.Error(err)
- }
- if len(v) != 3 {
- t.Fatal("expected 3 args; got ", len(v))
- }
- expect := "[1 2 3]"
- if v.String() != expect {
- t.Errorf("expected value %q got %q", expect, v.String())
- }
-}
-
-func TestSetOutput(t *testing.T) {
- var flags FlagSet
- var buf bytes.Buffer
- flags.SetOutput(&buf)
- flags.Init("test", ContinueOnError)
- flags.Parse([]string{"--unknown"})
- if out := buf.String(); !strings.Contains(out, "--unknown") {
- t.Logf("expected output mentioning unknown; got %q", out)
- }
-}
-
-// This tests that one can reset the flags. This still works but not well, and is
-// superseded by FlagSet.
-func TestChangingArgs(t *testing.T) {
- ResetForTesting(func() { t.Fatal("bad parse") })
- oldArgs := os.Args
- defer func() { os.Args = oldArgs }()
- os.Args = []string{"cmd", "--before", "subcmd"}
- before := Bool("before", false, "")
- if err := GetCommandLine().Parse(os.Args[1:]); err != nil {
- t.Fatal(err)
- }
- cmd := Arg(0)
- os.Args = []string{"subcmd", "--after", "args"}
- after := Bool("after", false, "")
- Parse()
- args := Args()
-
- if !*before || cmd != "subcmd" || !*after || len(args) != 1 || args[0] != "args" {
- t.Fatalf("expected true subcmd true [args] got %v %v %v %v", *before, cmd, *after, args)
- }
-}
-
-// Test that -help invokes the usage message and returns ErrHelp.
-func TestHelp(t *testing.T) {
- var helpCalled = false
- fs := NewFlagSet("help test", ContinueOnError)
- fs.Usage = func() { helpCalled = true }
- var flag bool
- fs.BoolVar(&flag, "flag", false, "regular flag")
- // Regular flag invocation should work
- err := fs.Parse([]string{"--flag=true"})
- if err != nil {
- t.Fatal("expected no error; got ", err)
- }
- if !flag {
- t.Error("flag was not set by --flag")
- }
- if helpCalled {
- t.Error("help called for regular flag")
- helpCalled = false // reset for next test
- }
- // Help flag should work as expected.
- err = fs.Parse([]string{"--help"})
- if err == nil {
- t.Fatal("error expected")
- }
- if err != ErrHelp {
- t.Fatal("expected ErrHelp; got ", err)
- }
- if !helpCalled {
- t.Fatal("help was not called")
- }
- // If we define a help flag, that should override.
- var help bool
- fs.BoolVar(&help, "help", false, "help flag")
- helpCalled = false
- err = fs.Parse([]string{"--help"})
- if err != nil {
- t.Fatal("expected no error for defined --help; got ", err)
- }
- if helpCalled {
- t.Fatal("help was called; should not have been for defined help flag")
- }
-}
-
-func TestNoInterspersed(t *testing.T) {
- f := NewFlagSet("test", ContinueOnError)
- f.SetInterspersed(false)
- f.Bool("true", true, "always true")
- f.Bool("false", false, "always false")
- err := f.Parse([]string{"--true", "break", "--false"})
- if err != nil {
- t.Fatal("expected no error; got ", err)
- }
- args := f.Args()
- if len(args) != 2 || args[0] != "break" || args[1] != "--false" {
- t.Fatal("expected interspersed options/non-options to fail")
- }
-}
-
-func TestTermination(t *testing.T) {
- f := NewFlagSet("termination", ContinueOnError)
- boolFlag := f.BoolP("bool", "l", false, "bool value")
- if f.Parsed() {
- t.Error("f.Parse() = true before Parse")
- }
- arg1 := "ls"
- arg2 := "-l"
- args := []string{
- "--",
- arg1,
- arg2,
- }
- f.SetOutput(ioutil.Discard)
- if err := f.Parse(args); err != nil {
- t.Fatal("expected no error; got ", err)
- }
- if !f.Parsed() {
- t.Error("f.Parse() = false after Parse")
- }
- if *boolFlag {
- t.Error("expected boolFlag=false, got true")
- }
- if len(f.Args()) != 2 {
- t.Errorf("expected 2 arguments, got %d: %v", len(f.Args()), f.Args())
- }
- if f.Args()[0] != arg1 {
- t.Errorf("expected argument %q got %q", arg1, f.Args()[0])
- }
- if f.Args()[1] != arg2 {
- t.Errorf("expected argument %q got %q", arg2, f.Args()[1])
- }
- if f.ArgsLenAtDash() != 0 {
- t.Errorf("expected argsLenAtDash %d got %d", 0, f.ArgsLenAtDash())
- }
-}
-
-func TestDeprecatedFlagInDocs(t *testing.T) {
- f := NewFlagSet("bob", ContinueOnError)
- f.Bool("badflag", true, "always true")
- f.MarkDeprecated("badflag", "use --good-flag instead")
-
- out := new(bytes.Buffer)
- f.SetOutput(out)
- f.PrintDefaults()
-
- if strings.Contains(out.String(), "badflag") {
- t.Errorf("found deprecated flag in usage!")
- }
-}
-
-func TestDeprecatedFlagShorthandInDocs(t *testing.T) {
- f := NewFlagSet("bob", ContinueOnError)
- name := "noshorthandflag"
- f.BoolP(name, "n", true, "always true")
- f.MarkShorthandDeprecated("noshorthandflag", fmt.Sprintf("use --%s instead", name))
-
- out := new(bytes.Buffer)
- f.SetOutput(out)
- f.PrintDefaults()
-
- if strings.Contains(out.String(), "-n,") {
- t.Errorf("found deprecated flag shorthand in usage!")
- }
-}
-
-func parseReturnStderr(t *testing.T, f *FlagSet, args []string) (string, error) {
- oldStderr := os.Stderr
- r, w, _ := os.Pipe()
- os.Stderr = w
-
- err := f.Parse(args)
-
- outC := make(chan string)
- // copy the output in a separate goroutine so printing can't block indefinitely
- go func() {
- var buf bytes.Buffer
- io.Copy(&buf, r)
- outC <- buf.String()
- }()
-
- w.Close()
- os.Stderr = oldStderr
- out := <-outC
-
- return out, err
-}
-
-func TestDeprecatedFlagUsage(t *testing.T) {
- f := NewFlagSet("bob", ContinueOnError)
- f.Bool("badflag", true, "always true")
- usageMsg := "use --good-flag instead"
- f.MarkDeprecated("badflag", usageMsg)
-
- args := []string{"--badflag"}
- out, err := parseReturnStderr(t, f, args)
- if err != nil {
- t.Fatal("expected no error; got ", err)
- }
-
- if !strings.Contains(out, usageMsg) {
- t.Errorf("usageMsg not printed when using a deprecated flag!")
- }
-}
-
-func TestDeprecatedFlagShorthandUsage(t *testing.T) {
- f := NewFlagSet("bob", ContinueOnError)
- name := "noshorthandflag"
- f.BoolP(name, "n", true, "always true")
- usageMsg := fmt.Sprintf("use --%s instead", name)
- f.MarkShorthandDeprecated(name, usageMsg)
-
- args := []string{"-n"}
- out, err := parseReturnStderr(t, f, args)
- if err != nil {
- t.Fatal("expected no error; got ", err)
- }
-
- if !strings.Contains(out, usageMsg) {
- t.Errorf("usageMsg not printed when using a deprecated flag!")
- }
-}
-
-func TestDeprecatedFlagUsageNormalized(t *testing.T) {
- f := NewFlagSet("bob", ContinueOnError)
- f.Bool("bad-double_flag", true, "always true")
- f.SetNormalizeFunc(wordSepNormalizeFunc)
- usageMsg := "use --good-flag instead"
- f.MarkDeprecated("bad_double-flag", usageMsg)
-
- args := []string{"--bad_double_flag"}
- out, err := parseReturnStderr(t, f, args)
- if err != nil {
- t.Fatal("expected no error; got ", err)
- }
-
- if !strings.Contains(out, usageMsg) {
- t.Errorf("usageMsg not printed when using a deprecated flag!")
- }
-}
-
-// Name normalization function should be called only once on flag addition
-func TestMultipleNormalizeFlagNameInvocations(t *testing.T) {
- normalizeFlagNameInvocations = 0
-
- f := NewFlagSet("normalized", ContinueOnError)
- f.SetNormalizeFunc(wordSepNormalizeFunc)
- f.Bool("with_under_flag", false, "bool value")
-
- if normalizeFlagNameInvocations != 1 {
- t.Fatal("Expected normalizeFlagNameInvocations to be 1; got ", normalizeFlagNameInvocations)
- }
-}
-
-//
-func TestHiddenFlagInUsage(t *testing.T) {
- f := NewFlagSet("bob", ContinueOnError)
- f.Bool("secretFlag", true, "shhh")
- f.MarkHidden("secretFlag")
-
- out := new(bytes.Buffer)
- f.SetOutput(out)
- f.PrintDefaults()
-
- if strings.Contains(out.String(), "secretFlag") {
- t.Errorf("found hidden flag in usage!")
- }
-}
-
-//
-func TestHiddenFlagUsage(t *testing.T) {
- f := NewFlagSet("bob", ContinueOnError)
- f.Bool("secretFlag", true, "shhh")
- f.MarkHidden("secretFlag")
-
- args := []string{"--secretFlag"}
- out, err := parseReturnStderr(t, f, args)
- if err != nil {
- t.Fatal("expected no error; got ", err)
- }
-
- if strings.Contains(out, "shhh") {
- t.Errorf("usage message printed when using a hidden flag!")
- }
-}
-
-const defaultOutput = ` --A for bootstrapping, allow 'any' type
- --Alongflagname disable bounds checking
- -C, --CCC a boolean defaulting to true (default true)
- --D path set relative path for local imports
- -E, --EEE num[=1234] a num with NoOptDefVal (default 4321)
- --F number a non-zero number (default 2.7)
- --G float a float that defaults to zero
- --IP ip IP address with no default
- --IPMask ipMask Netmask address with no default
- --IPNet ipNet IP network with no default
- --Ints ints int slice with zero default
- --N int a non-zero int (default 27)
- --ND1 string[="bar"] a string with NoOptDefVal (default "foo")
- --ND2 num[=4321] a num with NoOptDefVal (default 1234)
- --StringArray stringArray string array with zero default
- --StringSlice strings string slice with zero default
- --Z int an int that defaults to zero
- --custom custom custom Value implementation
- --customP custom a VarP with default (default 10)
- --maxT timeout set timeout for dial
- -v, --verbose count verbosity
-`
-
-// Custom value that satisfies the Value interface.
-type customValue int
-
-func (cv *customValue) String() string { return fmt.Sprintf("%v", *cv) }
-
-func (cv *customValue) Set(s string) error {
- v, err := strconv.ParseInt(s, 0, 64)
- *cv = customValue(v)
- return err
-}
-
-func (cv *customValue) Type() string { return "custom" }
-
-func TestPrintDefaults(t *testing.T) {
- fs := NewFlagSet("print defaults test", ContinueOnError)
- var buf bytes.Buffer
- fs.SetOutput(&buf)
- fs.Bool("A", false, "for bootstrapping, allow 'any' type")
- fs.Bool("Alongflagname", false, "disable bounds checking")
- fs.BoolP("CCC", "C", true, "a boolean defaulting to true")
- fs.String("D", "", "set relative `path` for local imports")
- fs.Float64("F", 2.7, "a non-zero `number`")
- fs.Float64("G", 0, "a float that defaults to zero")
- fs.Int("N", 27, "a non-zero int")
- fs.IntSlice("Ints", []int{}, "int slice with zero default")
- fs.IP("IP", nil, "IP address with no default")
- fs.IPMask("IPMask", nil, "Netmask address with no default")
- fs.IPNet("IPNet", net.IPNet{}, "IP network with no default")
- fs.Int("Z", 0, "an int that defaults to zero")
- fs.Duration("maxT", 0, "set `timeout` for dial")
- fs.String("ND1", "foo", "a string with NoOptDefVal")
- fs.Lookup("ND1").NoOptDefVal = "bar"
- fs.Int("ND2", 1234, "a `num` with NoOptDefVal")
- fs.Lookup("ND2").NoOptDefVal = "4321"
- fs.IntP("EEE", "E", 4321, "a `num` with NoOptDefVal")
- fs.ShorthandLookup("E").NoOptDefVal = "1234"
- fs.StringSlice("StringSlice", []string{}, "string slice with zero default")
- fs.StringArray("StringArray", []string{}, "string array with zero default")
- fs.CountP("verbose", "v", "verbosity")
-
- var cv customValue
- fs.Var(&cv, "custom", "custom Value implementation")
-
- cv2 := customValue(10)
- fs.VarP(&cv2, "customP", "", "a VarP with default")
-
- fs.PrintDefaults()
- got := buf.String()
- if got != defaultOutput {
- fmt.Println("\n" + got)
- fmt.Println("\n" + defaultOutput)
- t.Errorf("got %q want %q\n", got, defaultOutput)
- }
-}
-
-func TestVisitAllFlagOrder(t *testing.T) {
- fs := NewFlagSet("TestVisitAllFlagOrder", ContinueOnError)
- fs.SortFlags = false
- // https://github.com/spf13/pflag/issues/120
- fs.SetNormalizeFunc(func(f *FlagSet, name string) NormalizedName {
- return NormalizedName(name)
- })
-
- names := []string{"C", "B", "A", "D"}
- for _, name := range names {
- fs.Bool(name, false, "")
- }
-
- i := 0
- fs.VisitAll(func(f *Flag) {
- if names[i] != f.Name {
- t.Errorf("Incorrect order. Expected %v, got %v", names[i], f.Name)
- }
- i++
- })
-}
-
-func TestVisitFlagOrder(t *testing.T) {
- fs := NewFlagSet("TestVisitFlagOrder", ContinueOnError)
- fs.SortFlags = false
- names := []string{"C", "B", "A", "D"}
- for _, name := range names {
- fs.Bool(name, false, "")
- fs.Set(name, "true")
- }
-
- i := 0
- fs.Visit(func(f *Flag) {
- if names[i] != f.Name {
- t.Errorf("Incorrect order. Expected %v, got %v", names[i], f.Name)
- }
- i++
- })
-}
diff --git a/vendor/github.com/spf13/pflag/golangflag.go b/vendor/github.com/spf13/pflag/golangflag.go
index c4f47ebe5..d3dd72b7f 100644
--- a/vendor/github.com/spf13/pflag/golangflag.go
+++ b/vendor/github.com/spf13/pflag/golangflag.go
@@ -98,4 +98,8 @@ func (f *FlagSet) AddGoFlagSet(newSet *goflag.FlagSet) {
newSet.VisitAll(func(goflag *goflag.Flag) {
f.AddGoFlag(goflag)
})
+ if f.addedGoFlagSets == nil {
+ f.addedGoFlagSets = make([]*goflag.FlagSet, 0)
+ }
+ f.addedGoFlagSets = append(f.addedGoFlagSets, newSet)
}
diff --git a/vendor/github.com/spf13/pflag/golangflag_test.go b/vendor/github.com/spf13/pflag/golangflag_test.go
deleted file mode 100644
index 77e2d7d80..000000000
--- a/vendor/github.com/spf13/pflag/golangflag_test.go
+++ /dev/null
@@ -1,39 +0,0 @@
-// Copyright 2009 The Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package pflag
-
-import (
- goflag "flag"
- "testing"
-)
-
-func TestGoflags(t *testing.T) {
- goflag.String("stringFlag", "stringFlag", "stringFlag")
- goflag.Bool("boolFlag", false, "boolFlag")
-
- f := NewFlagSet("test", ContinueOnError)
-
- f.AddGoFlagSet(goflag.CommandLine)
- err := f.Parse([]string{"--stringFlag=bob", "--boolFlag"})
- if err != nil {
- t.Fatal("expected no error; get", err)
- }
-
- getString, err := f.GetString("stringFlag")
- if err != nil {
- t.Fatal("expected no error; get", err)
- }
- if getString != "bob" {
- t.Fatalf("expected getString=bob but got getString=%s", getString)
- }
-
- getBool, err := f.GetBool("boolFlag")
- if err != nil {
- t.Fatal("expected no error; get", err)
- }
- if getBool != true {
- t.Fatalf("expected getBool=true but got getBool=%v", getBool)
- }
-}
diff --git a/vendor/github.com/spf13/pflag/int_slice_test.go b/vendor/github.com/spf13/pflag/int_slice_test.go
deleted file mode 100644
index 745aecb95..000000000
--- a/vendor/github.com/spf13/pflag/int_slice_test.go
+++ /dev/null
@@ -1,165 +0,0 @@
-// Copyright 2009 The Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package pflag
-
-import (
- "fmt"
- "strconv"
- "strings"
- "testing"
-)
-
-func setUpISFlagSet(isp *[]int) *FlagSet {
- f := NewFlagSet("test", ContinueOnError)
- f.IntSliceVar(isp, "is", []int{}, "Command separated list!")
- return f
-}
-
-func setUpISFlagSetWithDefault(isp *[]int) *FlagSet {
- f := NewFlagSet("test", ContinueOnError)
- f.IntSliceVar(isp, "is", []int{0, 1}, "Command separated list!")
- return f
-}
-
-func TestEmptyIS(t *testing.T) {
- var is []int
- f := setUpISFlagSet(&is)
- err := f.Parse([]string{})
- if err != nil {
- t.Fatal("expected no error; got", err)
- }
-
- getIS, err := f.GetIntSlice("is")
- if err != nil {
- t.Fatal("got an error from GetIntSlice():", err)
- }
- if len(getIS) != 0 {
- t.Fatalf("got is %v with len=%d but expected length=0", getIS, len(getIS))
- }
-}
-
-func TestIS(t *testing.T) {
- var is []int
- f := setUpISFlagSet(&is)
-
- vals := []string{"1", "2", "4", "3"}
- arg := fmt.Sprintf("--is=%s", strings.Join(vals, ","))
- err := f.Parse([]string{arg})
- if err != nil {
- t.Fatal("expected no error; got", err)
- }
- for i, v := range is {
- d, err := strconv.Atoi(vals[i])
- if err != nil {
- t.Fatalf("got error: %v", err)
- }
- if d != v {
- t.Fatalf("expected is[%d] to be %s but got: %d", i, vals[i], v)
- }
- }
- getIS, err := f.GetIntSlice("is")
- if err != nil {
- t.Fatalf("got error: %v", err)
- }
- for i, v := range getIS {
- d, err := strconv.Atoi(vals[i])
- if err != nil {
- t.Fatalf("got error: %v", err)
- }
- if d != v {
- t.Fatalf("expected is[%d] to be %s but got: %d from GetIntSlice", i, vals[i], v)
- }
- }
-}
-
-func TestISDefault(t *testing.T) {
- var is []int
- f := setUpISFlagSetWithDefault(&is)
-
- vals := []string{"0", "1"}
-
- err := f.Parse([]string{})
- if err != nil {
- t.Fatal("expected no error; got", err)
- }
- for i, v := range is {
- d, err := strconv.Atoi(vals[i])
- if err != nil {
- t.Fatalf("got error: %v", err)
- }
- if d != v {
- t.Fatalf("expected is[%d] to be %d but got: %d", i, d, v)
- }
- }
-
- getIS, err := f.GetIntSlice("is")
- if err != nil {
- t.Fatal("got an error from GetIntSlice():", err)
- }
- for i, v := range getIS {
- d, err := strconv.Atoi(vals[i])
- if err != nil {
- t.Fatal("got an error from GetIntSlice():", err)
- }
- if d != v {
- t.Fatalf("expected is[%d] to be %d from GetIntSlice but got: %d", i, d, v)
- }
- }
-}
-
-func TestISWithDefault(t *testing.T) {
- var is []int
- f := setUpISFlagSetWithDefault(&is)
-
- vals := []string{"1", "2"}
- arg := fmt.Sprintf("--is=%s", strings.Join(vals, ","))
- err := f.Parse([]string{arg})
- if err != nil {
- t.Fatal("expected no error; got", err)
- }
- for i, v := range is {
- d, err := strconv.Atoi(vals[i])
- if err != nil {
- t.Fatalf("got error: %v", err)
- }
- if d != v {
- t.Fatalf("expected is[%d] to be %d but got: %d", i, d, v)
- }
- }
-
- getIS, err := f.GetIntSlice("is")
- if err != nil {
- t.Fatal("got an error from GetIntSlice():", err)
- }
- for i, v := range getIS {
- d, err := strconv.Atoi(vals[i])
- if err != nil {
- t.Fatalf("got error: %v", err)
- }
- if d != v {
- t.Fatalf("expected is[%d] to be %d from GetIntSlice but got: %d", i, d, v)
- }
- }
-}
-
-func TestISCalledTwice(t *testing.T) {
- var is []int
- f := setUpISFlagSet(&is)
-
- in := []string{"1,2", "3"}
- expected := []int{1, 2, 3}
- argfmt := "--is=%s"
- arg1 := fmt.Sprintf(argfmt, in[0])
- arg2 := fmt.Sprintf(argfmt, in[1])
- err := f.Parse([]string{arg1, arg2})
- if err != nil {
- t.Fatal("expected no error; got", err)
- }
- for i, v := range is {
- if expected[i] != v {
- t.Fatalf("expected is[%d] to be %d but got: %d", i, expected[i], v)
- }
- }
-}
diff --git a/vendor/github.com/spf13/pflag/ip_slice_test.go b/vendor/github.com/spf13/pflag/ip_slice_test.go
deleted file mode 100644
index b0c681c5b..000000000
--- a/vendor/github.com/spf13/pflag/ip_slice_test.go
+++ /dev/null
@@ -1,222 +0,0 @@
-package pflag
-
-import (
- "fmt"
- "net"
- "strings"
- "testing"
-)
-
-func setUpIPSFlagSet(ipsp *[]net.IP) *FlagSet {
- f := NewFlagSet("test", ContinueOnError)
- f.IPSliceVar(ipsp, "ips", []net.IP{}, "Command separated list!")
- return f
-}
-
-func setUpIPSFlagSetWithDefault(ipsp *[]net.IP) *FlagSet {
- f := NewFlagSet("test", ContinueOnError)
- f.IPSliceVar(ipsp, "ips",
- []net.IP{
- net.ParseIP("192.168.1.1"),
- net.ParseIP("0:0:0:0:0:0:0:1"),
- },
- "Command separated list!")
- return f
-}
-
-func TestEmptyIP(t *testing.T) {
- var ips []net.IP
- f := setUpIPSFlagSet(&ips)
- err := f.Parse([]string{})
- if err != nil {
- t.Fatal("expected no error; got", err)
- }
-
- getIPS, err := f.GetIPSlice("ips")
- if err != nil {
- t.Fatal("got an error from GetIPSlice():", err)
- }
- if len(getIPS) != 0 {
- t.Fatalf("got ips %v with len=%d but expected length=0", getIPS, len(getIPS))
- }
-}
-
-func TestIPS(t *testing.T) {
- var ips []net.IP
- f := setUpIPSFlagSet(&ips)
-
- vals := []string{"192.168.1.1", "10.0.0.1", "0:0:0:0:0:0:0:2"}
- arg := fmt.Sprintf("--ips=%s", strings.Join(vals, ","))
- err := f.Parse([]string{arg})
- if err != nil {
- t.Fatal("expected no error; got", err)
- }
- for i, v := range ips {
- if ip := net.ParseIP(vals[i]); ip == nil {
- t.Fatalf("invalid string being converted to IP address: %s", vals[i])
- } else if !ip.Equal(v) {
- t.Fatalf("expected ips[%d] to be %s but got: %s from GetIPSlice", i, vals[i], v)
- }
- }
-}
-
-func TestIPSDefault(t *testing.T) {
- var ips []net.IP
- f := setUpIPSFlagSetWithDefault(&ips)
-
- vals := []string{"192.168.1.1", "0:0:0:0:0:0:0:1"}
- err := f.Parse([]string{})
- if err != nil {
- t.Fatal("expected no error; got", err)
- }
- for i, v := range ips {
- if ip := net.ParseIP(vals[i]); ip == nil {
- t.Fatalf("invalid string being converted to IP address: %s", vals[i])
- } else if !ip.Equal(v) {
- t.Fatalf("expected ips[%d] to be %s but got: %s", i, vals[i], v)
- }
- }
-
- getIPS, err := f.GetIPSlice("ips")
- if err != nil {
- t.Fatal("got an error from GetIPSlice")
- }
- for i, v := range getIPS {
- if ip := net.ParseIP(vals[i]); ip == nil {
- t.Fatalf("invalid string being converted to IP address: %s", vals[i])
- } else if !ip.Equal(v) {
- t.Fatalf("expected ips[%d] to be %s but got: %s", i, vals[i], v)
- }
- }
-}
-
-func TestIPSWithDefault(t *testing.T) {
- var ips []net.IP
- f := setUpIPSFlagSetWithDefault(&ips)
-
- vals := []string{"192.168.1.1", "0:0:0:0:0:0:0:1"}
- arg := fmt.Sprintf("--ips=%s", strings.Join(vals, ","))
- err := f.Parse([]string{arg})
- if err != nil {
- t.Fatal("expected no error; got", err)
- }
- for i, v := range ips {
- if ip := net.ParseIP(vals[i]); ip == nil {
- t.Fatalf("invalid string being converted to IP address: %s", vals[i])
- } else if !ip.Equal(v) {
- t.Fatalf("expected ips[%d] to be %s but got: %s", i, vals[i], v)
- }
- }
-
- getIPS, err := f.GetIPSlice("ips")
- if err != nil {
- t.Fatal("got an error from GetIPSlice")
- }
- for i, v := range getIPS {
- if ip := net.ParseIP(vals[i]); ip == nil {
- t.Fatalf("invalid string being converted to IP address: %s", vals[i])
- } else if !ip.Equal(v) {
- t.Fatalf("expected ips[%d] to be %s but got: %s", i, vals[i], v)
- }
- }
-}
-
-func TestIPSCalledTwice(t *testing.T) {
- var ips []net.IP
- f := setUpIPSFlagSet(&ips)
-
- in := []string{"192.168.1.2,0:0:0:0:0:0:0:1", "10.0.0.1"}
- expected := []net.IP{net.ParseIP("192.168.1.2"), net.ParseIP("0:0:0:0:0:0:0:1"), net.ParseIP("10.0.0.1")}
- argfmt := "ips=%s"
- arg1 := fmt.Sprintf(argfmt, in[0])
- arg2 := fmt.Sprintf(argfmt, in[1])
- err := f.Parse([]string{arg1, arg2})
- if err != nil {
- t.Fatal("expected no error; got", err)
- }
- for i, v := range ips {
- if !expected[i].Equal(v) {
- t.Fatalf("expected ips[%d] to be %s but got: %s", i, expected[i], v)
- }
- }
-}
-
-func TestIPSBadQuoting(t *testing.T) {
-
- tests := []struct {
- Want []net.IP
- FlagArg []string
- }{
- {
- Want: []net.IP{
- net.ParseIP("a4ab:61d:f03e:5d7d:fad7:d4c2:a1a5:568"),
- net.ParseIP("203.107.49.208"),
- net.ParseIP("14.57.204.90"),
- },
- FlagArg: []string{
- "a4ab:61d:f03e:5d7d:fad7:d4c2:a1a5:568",
- "203.107.49.208",
- "14.57.204.90",
- },
- },
- {
- Want: []net.IP{
- net.ParseIP("204.228.73.195"),
- net.ParseIP("86.141.15.94"),
- },
- FlagArg: []string{
- "204.228.73.195",
- "86.141.15.94",
- },
- },
- {
- Want: []net.IP{
- net.ParseIP("c70c:db36:3001:890f:c6ea:3f9b:7a39:cc3f"),
- net.ParseIP("4d17:1d6e:e699:bd7a:88c5:5e7e:ac6a:4472"),
- },
- FlagArg: []string{
- "c70c:db36:3001:890f:c6ea:3f9b:7a39:cc3f",
- "4d17:1d6e:e699:bd7a:88c5:5e7e:ac6a:4472",
- },
- },
- {
- Want: []net.IP{
- net.ParseIP("5170:f971:cfac:7be3:512a:af37:952c:bc33"),
- net.ParseIP("93.21.145.140"),
- net.ParseIP("2cac:61d3:c5ff:6caf:73e0:1b1a:c336:c1ca"),
- },
- FlagArg: []string{
- " 5170:f971:cfac:7be3:512a:af37:952c:bc33 , 93.21.145.140 ",
- "2cac:61d3:c5ff:6caf:73e0:1b1a:c336:c1ca",
- },
- },
- {
- Want: []net.IP{
- net.ParseIP("2e5e:66b2:6441:848:5b74:76ea:574c:3a7b"),
- net.ParseIP("2e5e:66b2:6441:848:5b74:76ea:574c:3a7b"),
- net.ParseIP("2e5e:66b2:6441:848:5b74:76ea:574c:3a7b"),
- net.ParseIP("2e5e:66b2:6441:848:5b74:76ea:574c:3a7b"),
- },
- FlagArg: []string{
- `"2e5e:66b2:6441:848:5b74:76ea:574c:3a7b, 2e5e:66b2:6441:848:5b74:76ea:574c:3a7b,2e5e:66b2:6441:848:5b74:76ea:574c:3a7b "`,
- " 2e5e:66b2:6441:848:5b74:76ea:574c:3a7b"},
- },
- }
-
- for i, test := range tests {
-
- var ips []net.IP
- f := setUpIPSFlagSet(&ips)
-
- if err := f.Parse([]string{fmt.Sprintf("--ips=%s", strings.Join(test.FlagArg, ","))}); err != nil {
- t.Fatalf("flag parsing failed with error: %s\nparsing:\t%#v\nwant:\t\t%s",
- err, test.FlagArg, test.Want[i])
- }
-
- for j, b := range ips {
- if !b.Equal(test.Want[j]) {
- t.Fatalf("bad value parsed for test %d on net.IP %d:\nwant:\t%s\ngot:\t%s", i, j, test.Want[j], b)
- }
- }
- }
-}
diff --git a/vendor/github.com/spf13/pflag/ip_test.go b/vendor/github.com/spf13/pflag/ip_test.go
deleted file mode 100644
index 1fec50e42..000000000
--- a/vendor/github.com/spf13/pflag/ip_test.go
+++ /dev/null
@@ -1,63 +0,0 @@
-package pflag
-
-import (
- "fmt"
- "net"
- "os"
- "testing"
-)
-
-func setUpIP(ip *net.IP) *FlagSet {
- f := NewFlagSet("test", ContinueOnError)
- f.IPVar(ip, "address", net.ParseIP("0.0.0.0"), "IP Address")
- return f
-}
-
-func TestIP(t *testing.T) {
- testCases := []struct {
- input string
- success bool
- expected string
- }{
- {"0.0.0.0", true, "0.0.0.0"},
- {" 0.0.0.0 ", true, "0.0.0.0"},
- {"1.2.3.4", true, "1.2.3.4"},
- {"127.0.0.1", true, "127.0.0.1"},
- {"255.255.255.255", true, "255.255.255.255"},
- {"", false, ""},
- {"0", false, ""},
- {"localhost", false, ""},
- {"0.0.0", false, ""},
- {"0.0.0.", false, ""},
- {"0.0.0.0.", false, ""},
- {"0.0.0.256", false, ""},
- {"0 . 0 . 0 . 0", false, ""},
- }
-
- devnull, _ := os.Open(os.DevNull)
- os.Stderr = devnull
- for i := range testCases {
- var addr net.IP
- f := setUpIP(&addr)
-
- tc := &testCases[i]
-
- arg := fmt.Sprintf("--address=%s", tc.input)
- err := f.Parse([]string{arg})
- if err != nil && tc.success == true {
- t.Errorf("expected success, got %q", err)
- continue
- } else if err == nil && tc.success == false {
- t.Errorf("expected failure")
- continue
- } else if tc.success {
- ip, err := f.GetIP("address")
- if err != nil {
- t.Errorf("Got error trying to fetch the IP flag: %v", err)
- }
- if ip.String() != tc.expected {
- t.Errorf("expected %q, got %q", tc.expected, ip.String())
- }
- }
- }
-}
diff --git a/vendor/github.com/spf13/pflag/ipnet_test.go b/vendor/github.com/spf13/pflag/ipnet_test.go
deleted file mode 100644
index 335b6fa15..000000000
--- a/vendor/github.com/spf13/pflag/ipnet_test.go
+++ /dev/null
@@ -1,70 +0,0 @@
-package pflag
-
-import (
- "fmt"
- "net"
- "os"
- "testing"
-)
-
-func setUpIPNet(ip *net.IPNet) *FlagSet {
- f := NewFlagSet("test", ContinueOnError)
- _, def, _ := net.ParseCIDR("0.0.0.0/0")
- f.IPNetVar(ip, "address", *def, "IP Address")
- return f
-}
-
-func TestIPNet(t *testing.T) {
- testCases := []struct {
- input string
- success bool
- expected string
- }{
- {"0.0.0.0/0", true, "0.0.0.0/0"},
- {" 0.0.0.0/0 ", true, "0.0.0.0/0"},
- {"1.2.3.4/8", true, "1.0.0.0/8"},
- {"127.0.0.1/16", true, "127.0.0.0/16"},
- {"255.255.255.255/19", true, "255.255.224.0/19"},
- {"255.255.255.255/32", true, "255.255.255.255/32"},
- {"", false, ""},
- {"/0", false, ""},
- {"0", false, ""},
- {"0/0", false, ""},
- {"localhost/0", false, ""},
- {"0.0.0/4", false, ""},
- {"0.0.0./8", false, ""},
- {"0.0.0.0./12", false, ""},
- {"0.0.0.256/16", false, ""},
- {"0.0.0.0 /20", false, ""},
- {"0.0.0.0/ 24", false, ""},
- {"0 . 0 . 0 . 0 / 28", false, ""},
- {"0.0.0.0/33", false, ""},
- }
-
- devnull, _ := os.Open(os.DevNull)
- os.Stderr = devnull
- for i := range testCases {
- var addr net.IPNet
- f := setUpIPNet(&addr)
-
- tc := &testCases[i]
-
- arg := fmt.Sprintf("--address=%s", tc.input)
- err := f.Parse([]string{arg})
- if err != nil && tc.success == true {
- t.Errorf("expected success, got %q", err)
- continue
- } else if err == nil && tc.success == false {
- t.Errorf("expected failure")
- continue
- } else if tc.success {
- ip, err := f.GetIPNet("address")
- if err != nil {
- t.Errorf("Got error trying to fetch the IP flag: %v", err)
- }
- if ip.String() != tc.expected {
- t.Errorf("expected %q, got %q", tc.expected, ip.String())
- }
- }
- }
-}
diff --git a/vendor/github.com/spf13/pflag/string_array.go b/vendor/github.com/spf13/pflag/string_array.go
index 276b7ed49..fa7bc6018 100644
--- a/vendor/github.com/spf13/pflag/string_array.go
+++ b/vendor/github.com/spf13/pflag/string_array.go
@@ -52,7 +52,7 @@ func (f *FlagSet) GetStringArray(name string) ([]string, error) {
// StringArrayVar defines a string flag with specified name, default value, and usage string.
// The argument p points to a []string variable in which to store the values of the multiple flags.
-// The value of each argument will not try to be separated by comma
+// The value of each argument will not try to be separated by comma. Use a StringSlice for that.
func (f *FlagSet) StringArrayVar(p *[]string, name string, value []string, usage string) {
f.VarP(newStringArrayValue(value, p), name, "", usage)
}
@@ -64,7 +64,7 @@ func (f *FlagSet) StringArrayVarP(p *[]string, name, shorthand string, value []s
// StringArrayVar defines a string flag with specified name, default value, and usage string.
// The argument p points to a []string variable in which to store the value of the flag.
-// The value of each argument will not try to be separated by comma
+// The value of each argument will not try to be separated by comma. Use a StringSlice for that.
func StringArrayVar(p *[]string, name string, value []string, usage string) {
CommandLine.VarP(newStringArrayValue(value, p), name, "", usage)
}
@@ -76,7 +76,7 @@ func StringArrayVarP(p *[]string, name, shorthand string, value []string, usage
// StringArray defines a string flag with specified name, default value, and usage string.
// The return value is the address of a []string variable that stores the value of the flag.
-// The value of each argument will not try to be separated by comma
+// The value of each argument will not try to be separated by comma. Use a StringSlice for that.
func (f *FlagSet) StringArray(name string, value []string, usage string) *[]string {
p := []string{}
f.StringArrayVarP(&p, name, "", value, usage)
@@ -92,7 +92,7 @@ func (f *FlagSet) StringArrayP(name, shorthand string, value []string, usage str
// StringArray defines a string flag with specified name, default value, and usage string.
// The return value is the address of a []string variable that stores the value of the flag.
-// The value of each argument will not try to be separated by comma
+// The value of each argument will not try to be separated by comma. Use a StringSlice for that.
func StringArray(name string, value []string, usage string) *[]string {
return CommandLine.StringArrayP(name, "", value, usage)
}
diff --git a/vendor/github.com/spf13/pflag/string_array_test.go b/vendor/github.com/spf13/pflag/string_array_test.go
deleted file mode 100644
index 1ceac8c6c..000000000
--- a/vendor/github.com/spf13/pflag/string_array_test.go
+++ /dev/null
@@ -1,233 +0,0 @@
-// Copyright 2009 The Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package pflag
-
-import (
- "fmt"
- "testing"
-)
-
-func setUpSAFlagSet(sap *[]string) *FlagSet {
- f := NewFlagSet("test", ContinueOnError)
- f.StringArrayVar(sap, "sa", []string{}, "Command separated list!")
- return f
-}
-
-func setUpSAFlagSetWithDefault(sap *[]string) *FlagSet {
- f := NewFlagSet("test", ContinueOnError)
- f.StringArrayVar(sap, "sa", []string{"default", "values"}, "Command separated list!")
- return f
-}
-
-func TestEmptySA(t *testing.T) {
- var sa []string
- f := setUpSAFlagSet(&sa)
- err := f.Parse([]string{})
- if err != nil {
- t.Fatal("expected no error; got", err)
- }
-
- getSA, err := f.GetStringArray("sa")
- if err != nil {
- t.Fatal("got an error from GetStringArray():", err)
- }
- if len(getSA) != 0 {
- t.Fatalf("got sa %v with len=%d but expected length=0", getSA, len(getSA))
- }
-}
-
-func TestEmptySAValue(t *testing.T) {
- var sa []string
- f := setUpSAFlagSet(&sa)
- err := f.Parse([]string{"--sa="})
- if err != nil {
- t.Fatal("expected no error; got", err)
- }
-
- getSA, err := f.GetStringArray("sa")
- if err != nil {
- t.Fatal("got an error from GetStringArray():", err)
- }
- if len(getSA) != 0 {
- t.Fatalf("got sa %v with len=%d but expected length=0", getSA, len(getSA))
- }
-}
-
-func TestSADefault(t *testing.T) {
- var sa []string
- f := setUpSAFlagSetWithDefault(&sa)
-
- vals := []string{"default", "values"}
-
- err := f.Parse([]string{})
- if err != nil {
- t.Fatal("expected no error; got", err)
- }
- for i, v := range sa {
- if vals[i] != v {
- t.Fatalf("expected sa[%d] to be %s but got: %s", i, vals[i], v)
- }
- }
-
- getSA, err := f.GetStringArray("sa")
- if err != nil {
- t.Fatal("got an error from GetStringArray():", err)
- }
- for i, v := range getSA {
- if vals[i] != v {
- t.Fatalf("expected sa[%d] to be %s from GetStringArray but got: %s", i, vals[i], v)
- }
- }
-}
-
-func TestSAWithDefault(t *testing.T) {
- var sa []string
- f := setUpSAFlagSetWithDefault(&sa)
-
- val := "one"
- arg := fmt.Sprintf("--sa=%s", val)
- err := f.Parse([]string{arg})
- if err != nil {
- t.Fatal("expected no error; got", err)
- }
-
- if len(sa) != 1 {
- t.Fatalf("expected number of values to be %d but %d", 1, len(sa))
- }
-
- if sa[0] != val {
- t.Fatalf("expected value to be %s but got: %s", sa[0], val)
- }
-
- getSA, err := f.GetStringArray("sa")
- if err != nil {
- t.Fatal("got an error from GetStringArray():", err)
- }
-
- if len(getSA) != 1 {
- t.Fatalf("expected number of values to be %d but %d", 1, len(getSA))
- }
-
- if getSA[0] != val {
- t.Fatalf("expected value to be %s but got: %s", getSA[0], val)
- }
-}
-
-func TestSACalledTwice(t *testing.T) {
- var sa []string
- f := setUpSAFlagSet(&sa)
-
- in := []string{"one", "two"}
- expected := []string{"one", "two"}
- argfmt := "--sa=%s"
- arg1 := fmt.Sprintf(argfmt, in[0])
- arg2 := fmt.Sprintf(argfmt, in[1])
- err := f.Parse([]string{arg1, arg2})
- if err != nil {
- t.Fatal("expected no error; got", err)
- }
-
- if len(expected) != len(sa) {
- t.Fatalf("expected number of sa to be %d but got: %d", len(expected), len(sa))
- }
- for i, v := range sa {
- if expected[i] != v {
- t.Fatalf("expected sa[%d] to be %s but got: %s", i, expected[i], v)
- }
- }
-
- values, err := f.GetStringArray("sa")
- if err != nil {
- t.Fatal("expected no error; got", err)
- }
-
- if len(expected) != len(values) {
- t.Fatalf("expected number of values to be %d but got: %d", len(expected), len(sa))
- }
- for i, v := range values {
- if expected[i] != v {
- t.Fatalf("expected got sa[%d] to be %s but got: %s", i, expected[i], v)
- }
- }
-}
-
-func TestSAWithSpecialChar(t *testing.T) {
- var sa []string
- f := setUpSAFlagSet(&sa)
-
- in := []string{"one,two", `"three"`, `"four,five",six`, "seven eight"}
- expected := []string{"one,two", `"three"`, `"four,five",six`, "seven eight"}
- argfmt := "--sa=%s"
- arg1 := fmt.Sprintf(argfmt, in[0])
- arg2 := fmt.Sprintf(argfmt, in[1])
- arg3 := fmt.Sprintf(argfmt, in[2])
- arg4 := fmt.Sprintf(argfmt, in[3])
- err := f.Parse([]string{arg1, arg2, arg3, arg4})
- if err != nil {
- t.Fatal("expected no error; got", err)
- }
-
- if len(expected) != len(sa) {
- t.Fatalf("expected number of sa to be %d but got: %d", len(expected), len(sa))
- }
- for i, v := range sa {
- if expected[i] != v {
- t.Fatalf("expected sa[%d] to be %s but got: %s", i, expected[i], v)
- }
- }
-
- values, err := f.GetStringArray("sa")
- if err != nil {
- t.Fatal("expected no error; got", err)
- }
-
- if len(expected) != len(values) {
- t.Fatalf("expected number of values to be %d but got: %d", len(expected), len(values))
- }
- for i, v := range values {
- if expected[i] != v {
- t.Fatalf("expected got sa[%d] to be %s but got: %s", i, expected[i], v)
- }
- }
-}
-
-func TestSAWithSquareBrackets(t *testing.T) {
- var sa []string
- f := setUpSAFlagSet(&sa)
-
- in := []string{"][]-[", "[a-z]", "[a-z]+"}
- expected := []string{"][]-[", "[a-z]", "[a-z]+"}
- argfmt := "--sa=%s"
- arg1 := fmt.Sprintf(argfmt, in[0])
- arg2 := fmt.Sprintf(argfmt, in[1])
- arg3 := fmt.Sprintf(argfmt, in[2])
- err := f.Parse([]string{arg1, arg2, arg3})
- if err != nil {
- t.Fatal("expected no error; got", err)
- }
-
- if len(expected) != len(sa) {
- t.Fatalf("expected number of sa to be %d but got: %d", len(expected), len(sa))
- }
- for i, v := range sa {
- if expected[i] != v {
- t.Fatalf("expected sa[%d] to be %s but got: %s", i, expected[i], v)
- }
- }
-
- values, err := f.GetStringArray("sa")
- if err != nil {
- t.Fatal("expected no error; got", err)
- }
-
- if len(expected) != len(values) {
- t.Fatalf("expected number of values to be %d but got: %d", len(expected), len(values))
- }
- for i, v := range values {
- if expected[i] != v {
- t.Fatalf("expected got sa[%d] to be %s but got: %s", i, expected[i], v)
- }
- }
-}
diff --git a/vendor/github.com/spf13/pflag/string_slice.go b/vendor/github.com/spf13/pflag/string_slice.go
index 05eee7543..0cd3ccc08 100644
--- a/vendor/github.com/spf13/pflag/string_slice.go
+++ b/vendor/github.com/spf13/pflag/string_slice.go
@@ -82,6 +82,11 @@ func (f *FlagSet) GetStringSlice(name string) ([]string, error) {
// StringSliceVar defines a string flag with specified name, default value, and usage string.
// The argument p points to a []string variable in which to store the value of the flag.
+// Compared to StringArray flags, StringSlice flags take comma-separated value as arguments and split them accordingly.
+// For example:
+// --ss="v1,v2" -ss="v3"
+// will result in
+// []string{"v1", "v2", "v3"}
func (f *FlagSet) StringSliceVar(p *[]string, name string, value []string, usage string) {
f.VarP(newStringSliceValue(value, p), name, "", usage)
}
@@ -93,6 +98,11 @@ func (f *FlagSet) StringSliceVarP(p *[]string, name, shorthand string, value []s
// StringSliceVar defines a string flag with specified name, default value, and usage string.
// The argument p points to a []string variable in which to store the value of the flag.
+// Compared to StringArray flags, StringSlice flags take comma-separated value as arguments and split them accordingly.
+// For example:
+// --ss="v1,v2" -ss="v3"
+// will result in
+// []string{"v1", "v2", "v3"}
func StringSliceVar(p *[]string, name string, value []string, usage string) {
CommandLine.VarP(newStringSliceValue(value, p), name, "", usage)
}
@@ -104,6 +114,11 @@ func StringSliceVarP(p *[]string, name, shorthand string, value []string, usage
// StringSlice defines a string flag with specified name, default value, and usage string.
// The return value is the address of a []string variable that stores the value of the flag.
+// Compared to StringArray flags, StringSlice flags take comma-separated value as arguments and split them accordingly.
+// For example:
+// --ss="v1,v2" -ss="v3"
+// will result in
+// []string{"v1", "v2", "v3"}
func (f *FlagSet) StringSlice(name string, value []string, usage string) *[]string {
p := []string{}
f.StringSliceVarP(&p, name, "", value, usage)
@@ -119,6 +134,11 @@ func (f *FlagSet) StringSliceP(name, shorthand string, value []string, usage str
// StringSlice defines a string flag with specified name, default value, and usage string.
// The return value is the address of a []string variable that stores the value of the flag.
+// Compared to StringArray flags, StringSlice flags take comma-separated value as arguments and split them accordingly.
+// For example:
+// --ss="v1,v2" -ss="v3"
+// will result in
+// []string{"v1", "v2", "v3"}
func StringSlice(name string, value []string, usage string) *[]string {
return CommandLine.StringSliceP(name, "", value, usage)
}
diff --git a/vendor/github.com/spf13/pflag/string_slice_test.go b/vendor/github.com/spf13/pflag/string_slice_test.go
deleted file mode 100644
index c41f3bd66..000000000
--- a/vendor/github.com/spf13/pflag/string_slice_test.go
+++ /dev/null
@@ -1,253 +0,0 @@
-// Copyright 2009 The Go Authors. All rights reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-package pflag
-
-import (
- "fmt"
- "strings"
- "testing"
-)
-
-func setUpSSFlagSet(ssp *[]string) *FlagSet {
- f := NewFlagSet("test", ContinueOnError)
- f.StringSliceVar(ssp, "ss", []string{}, "Command separated list!")
- return f
-}
-
-func setUpSSFlagSetWithDefault(ssp *[]string) *FlagSet {
- f := NewFlagSet("test", ContinueOnError)
- f.StringSliceVar(ssp, "ss", []string{"default", "values"}, "Command separated list!")
- return f
-}
-
-func TestEmptySS(t *testing.T) {
- var ss []string
- f := setUpSSFlagSet(&ss)
- err := f.Parse([]string{})
- if err != nil {
- t.Fatal("expected no error; got", err)
- }
-
- getSS, err := f.GetStringSlice("ss")
- if err != nil {
- t.Fatal("got an error from GetStringSlice():", err)
- }
- if len(getSS) != 0 {
- t.Fatalf("got ss %v with len=%d but expected length=0", getSS, len(getSS))
- }
-}
-
-func TestEmptySSValue(t *testing.T) {
- var ss []string
- f := setUpSSFlagSet(&ss)
- err := f.Parse([]string{"--ss="})
- if err != nil {
- t.Fatal("expected no error; got", err)
- }
-
- getSS, err := f.GetStringSlice("ss")
- if err != nil {
- t.Fatal("got an error from GetStringSlice():", err)
- }
- if len(getSS) != 0 {
- t.Fatalf("got ss %v with len=%d but expected length=0", getSS, len(getSS))
- }
-}
-
-func TestSS(t *testing.T) {
- var ss []string
- f := setUpSSFlagSet(&ss)
-
- vals := []string{"one", "two", "4", "3"}
- arg := fmt.Sprintf("--ss=%s", strings.Join(vals, ","))
- err := f.Parse([]string{arg})
- if err != nil {
- t.Fatal("expected no error; got", err)
- }
- for i, v := range ss {
- if vals[i] != v {
- t.Fatalf("expected ss[%d] to be %s but got: %s", i, vals[i], v)
- }
- }
-
- getSS, err := f.GetStringSlice("ss")
- if err != nil {
- t.Fatal("got an error from GetStringSlice():", err)
- }
- for i, v := range getSS {
- if vals[i] != v {
- t.Fatalf("expected ss[%d] to be %s from GetStringSlice but got: %s", i, vals[i], v)
- }
- }
-}
-
-func TestSSDefault(t *testing.T) {
- var ss []string
- f := setUpSSFlagSetWithDefault(&ss)
-
- vals := []string{"default", "values"}
-
- err := f.Parse([]string{})
- if err != nil {
- t.Fatal("expected no error; got", err)
- }
- for i, v := range ss {
- if vals[i] != v {
- t.Fatalf("expected ss[%d] to be %s but got: %s", i, vals[i], v)
- }
- }
-
- getSS, err := f.GetStringSlice("ss")
- if err != nil {
- t.Fatal("got an error from GetStringSlice():", err)
- }
- for i, v := range getSS {
- if vals[i] != v {
- t.Fatalf("expected ss[%d] to be %s from GetStringSlice but got: %s", i, vals[i], v)
- }
- }
-}
-
-func TestSSWithDefault(t *testing.T) {
- var ss []string
- f := setUpSSFlagSetWithDefault(&ss)
-
- vals := []string{"one", "two", "4", "3"}
- arg := fmt.Sprintf("--ss=%s", strings.Join(vals, ","))
- err := f.Parse([]string{arg})
- if err != nil {
- t.Fatal("expected no error; got", err)
- }
- for i, v := range ss {
- if vals[i] != v {
- t.Fatalf("expected ss[%d] to be %s but got: %s", i, vals[i], v)
- }
- }
-
- getSS, err := f.GetStringSlice("ss")
- if err != nil {
- t.Fatal("got an error from GetStringSlice():", err)
- }
- for i, v := range getSS {
- if vals[i] != v {
- t.Fatalf("expected ss[%d] to be %s from GetStringSlice but got: %s", i, vals[i], v)
- }
- }
-}
-
-func TestSSCalledTwice(t *testing.T) {
- var ss []string
- f := setUpSSFlagSet(&ss)
-
- in := []string{"one,two", "three"}
- expected := []string{"one", "two", "three"}
- argfmt := "--ss=%s"
- arg1 := fmt.Sprintf(argfmt, in[0])
- arg2 := fmt.Sprintf(argfmt, in[1])
- err := f.Parse([]string{arg1, arg2})
- if err != nil {
- t.Fatal("expected no error; got", err)
- }
-
- if len(expected) != len(ss) {
- t.Fatalf("expected number of ss to be %d but got: %d", len(expected), len(ss))
- }
- for i, v := range ss {
- if expected[i] != v {
- t.Fatalf("expected ss[%d] to be %s but got: %s", i, expected[i], v)
- }
- }
-
- values, err := f.GetStringSlice("ss")
- if err != nil {
- t.Fatal("expected no error; got", err)
- }
-
- if len(expected) != len(values) {
- t.Fatalf("expected number of values to be %d but got: %d", len(expected), len(ss))
- }
- for i, v := range values {
- if expected[i] != v {
- t.Fatalf("expected got ss[%d] to be %s but got: %s", i, expected[i], v)
- }
- }
-}
-
-func TestSSWithComma(t *testing.T) {
- var ss []string
- f := setUpSSFlagSet(&ss)
-
- in := []string{`"one,two"`, `"three"`, `"four,five",six`}
- expected := []string{"one,two", "three", "four,five", "six"}
- argfmt := "--ss=%s"
- arg1 := fmt.Sprintf(argfmt, in[0])
- arg2 := fmt.Sprintf(argfmt, in[1])
- arg3 := fmt.Sprintf(argfmt, in[2])
- err := f.Parse([]string{arg1, arg2, arg3})
- if err != nil {
- t.Fatal("expected no error; got", err)
- }
-
- if len(expected) != len(ss) {
- t.Fatalf("expected number of ss to be %d but got: %d", len(expected), len(ss))
- }
- for i, v := range ss {
- if expected[i] != v {
- t.Fatalf("expected ss[%d] to be %s but got: %s", i, expected[i], v)
- }
- }
-
- values, err := f.GetStringSlice("ss")
- if err != nil {
- t.Fatal("expected no error; got", err)
- }
-
- if len(expected) != len(values) {
- t.Fatalf("expected number of values to be %d but got: %d", len(expected), len(values))
- }
- for i, v := range values {
- if expected[i] != v {
- t.Fatalf("expected got ss[%d] to be %s but got: %s", i, expected[i], v)
- }
- }
-}
-
-func TestSSWithSquareBrackets(t *testing.T) {
- var ss []string
- f := setUpSSFlagSet(&ss)
-
- in := []string{`"[a-z]"`, `"[a-z]+"`}
- expected := []string{"[a-z]", "[a-z]+"}
- argfmt := "--ss=%s"
- arg1 := fmt.Sprintf(argfmt, in[0])
- arg2 := fmt.Sprintf(argfmt, in[1])
- err := f.Parse([]string{arg1, arg2})
- if err != nil {
- t.Fatal("expected no error; got", err)
- }
-
- if len(expected) != len(ss) {
- t.Fatalf("expected number of ss to be %d but got: %d", len(expected), len(ss))
- }
- for i, v := range ss {
- if expected[i] != v {
- t.Fatalf("expected ss[%d] to be %s but got: %s", i, expected[i], v)
- }
- }
-
- values, err := f.GetStringSlice("ss")
- if err != nil {
- t.Fatal("expected no error; got", err)
- }
-
- if len(expected) != len(values) {
- t.Fatalf("expected number of values to be %d but got: %d", len(expected), len(values))
- }
- for i, v := range values {
- if expected[i] != v {
- t.Fatalf("expected got ss[%d] to be %s but got: %s", i, expected[i], v)
- }
- }
-}
diff --git a/vendor/github.com/spf13/pflag/uint_slice_test.go b/vendor/github.com/spf13/pflag/uint_slice_test.go
deleted file mode 100644
index db1a19dc2..000000000
--- a/vendor/github.com/spf13/pflag/uint_slice_test.go
+++ /dev/null
@@ -1,161 +0,0 @@
-package pflag
-
-import (
- "fmt"
- "strconv"
- "strings"
- "testing"
-)
-
-func setUpUISFlagSet(uisp *[]uint) *FlagSet {
- f := NewFlagSet("test", ContinueOnError)
- f.UintSliceVar(uisp, "uis", []uint{}, "Command separated list!")
- return f
-}
-
-func setUpUISFlagSetWithDefault(uisp *[]uint) *FlagSet {
- f := NewFlagSet("test", ContinueOnError)
- f.UintSliceVar(uisp, "uis", []uint{0, 1}, "Command separated list!")
- return f
-}
-
-func TestEmptyUIS(t *testing.T) {
- var uis []uint
- f := setUpUISFlagSet(&uis)
- err := f.Parse([]string{})
- if err != nil {
- t.Fatal("expected no error; got", err)
- }
-
- getUIS, err := f.GetUintSlice("uis")
- if err != nil {
- t.Fatal("got an error from GetUintSlice():", err)
- }
- if len(getUIS) != 0 {
- t.Fatalf("got is %v with len=%d but expected length=0", getUIS, len(getUIS))
- }
-}
-
-func TestUIS(t *testing.T) {
- var uis []uint
- f := setUpUISFlagSet(&uis)
-
- vals := []string{"1", "2", "4", "3"}
- arg := fmt.Sprintf("--uis=%s", strings.Join(vals, ","))
- err := f.Parse([]string{arg})
- if err != nil {
- t.Fatal("expected no error; got", err)
- }
- for i, v := range uis {
- u, err := strconv.ParseUint(vals[i], 10, 0)
- if err != nil {
- t.Fatalf("got error: %v", err)
- }
- if uint(u) != v {
- t.Fatalf("expected uis[%d] to be %s but got %d", i, vals[i], v)
- }
- }
- getUIS, err := f.GetUintSlice("uis")
- if err != nil {
- t.Fatalf("got error: %v", err)
- }
- for i, v := range getUIS {
- u, err := strconv.ParseUint(vals[i], 10, 0)
- if err != nil {
- t.Fatalf("got error: %v", err)
- }
- if uint(u) != v {
- t.Fatalf("expected uis[%d] to be %s but got: %d from GetUintSlice", i, vals[i], v)
- }
- }
-}
-
-func TestUISDefault(t *testing.T) {
- var uis []uint
- f := setUpUISFlagSetWithDefault(&uis)
-
- vals := []string{"0", "1"}
-
- err := f.Parse([]string{})
- if err != nil {
- t.Fatal("expected no error; got", err)
- }
- for i, v := range uis {
- u, err := strconv.ParseUint(vals[i], 10, 0)
- if err != nil {
- t.Fatalf("got error: %v", err)
- }
- if uint(u) != v {
- t.Fatalf("expect uis[%d] to be %d but got: %d", i, u, v)
- }
- }
-
- getUIS, err := f.GetUintSlice("uis")
- if err != nil {
- t.Fatal("got an error from GetUintSlice():", err)
- }
- for i, v := range getUIS {
- u, err := strconv.ParseUint(vals[i], 10, 0)
- if err != nil {
- t.Fatal("got an error from GetIntSlice():", err)
- }
- if uint(u) != v {
- t.Fatalf("expected uis[%d] to be %d from GetUintSlice but got: %d", i, u, v)
- }
- }
-}
-
-func TestUISWithDefault(t *testing.T) {
- var uis []uint
- f := setUpUISFlagSetWithDefault(&uis)
-
- vals := []string{"1", "2"}
- arg := fmt.Sprintf("--uis=%s", strings.Join(vals, ","))
- err := f.Parse([]string{arg})
- if err != nil {
- t.Fatal("expected no error; got", err)
- }
- for i, v := range uis {
- u, err := strconv.ParseUint(vals[i], 10, 0)
- if err != nil {
- t.Fatalf("got error: %v", err)
- }
- if uint(u) != v {
- t.Fatalf("expected uis[%d] to be %d from GetUintSlice but got: %d", i, u, v)
- }
- }
-
- getUIS, err := f.GetUintSlice("uis")
- if err != nil {
- t.Fatal("got an error from GetUintSlice():", err)
- }
- for i, v := range getUIS {
- u, err := strconv.ParseUint(vals[i], 10, 0)
- if err != nil {
- t.Fatalf("got error: %v", err)
- }
- if uint(u) != v {
- t.Fatalf("expected uis[%d] to be %d from GetUintSlice but got: %d", i, u, v)
- }
- }
-}
-
-func TestUISCalledTwice(t *testing.T) {
- var uis []uint
- f := setUpUISFlagSet(&uis)
-
- in := []string{"1,2", "3"}
- expected := []int{1, 2, 3}
- argfmt := "--uis=%s"
- arg1 := fmt.Sprintf(argfmt, in[0])
- arg2 := fmt.Sprintf(argfmt, in[1])
- err := f.Parse([]string{arg1, arg2})
- if err != nil {
- t.Fatal("expected no error; got", err)
- }
- for i, v := range uis {
- if uint(expected[i]) != v {
- t.Fatalf("expected uis[%d] to be %d but got: %d", i, expected[i], v)
- }
- }
-}
diff --git a/vendor/github.com/spf13/pflag/verify/all.sh b/vendor/github.com/spf13/pflag/verify/all.sh
deleted file mode 100755
index 739f89c0b..000000000
--- a/vendor/github.com/spf13/pflag/verify/all.sh
+++ /dev/null
@@ -1,69 +0,0 @@
-#!/bin/bash
-
-set -o errexit
-set -o nounset
-set -o pipefail
-
-ROOT=$(dirname "${BASH_SOURCE}")/..
-
-# Some useful colors.
-if [[ -z "${color_start-}" ]]; then
- declare -r color_start="\033["
- declare -r color_red="${color_start}0;31m"
- declare -r color_yellow="${color_start}0;33m"
- declare -r color_green="${color_start}0;32m"
- declare -r color_norm="${color_start}0m"
-fi
-
-SILENT=true
-
-function is-excluded {
- for e in $EXCLUDE; do
- if [[ $1 -ef ${BASH_SOURCE} ]]; then
- return
- fi
- if [[ $1 -ef "$ROOT/hack/$e" ]]; then
- return
- fi
- done
- return 1
-}
-
-while getopts ":v" opt; do
- case $opt in
- v)
- SILENT=false
- ;;
- \?)
- echo "Invalid flag: -$OPTARG" >&2
- exit 1
- ;;
- esac
-done
-
-if $SILENT ; then
- echo "Running in the silent mode, run with -v if you want to see script logs."
-fi
-
-EXCLUDE="all.sh"
-
-ret=0
-for t in `ls $ROOT/verify/*.sh`
-do
- if is-excluded $t ; then
- echo "Skipping $t"
- continue
- fi
- if $SILENT ; then
- echo -e "Verifying $t"
- if bash "$t" &> /dev/null; then
- echo -e "${color_green}SUCCESS${color_norm}"
- else
- echo -e "${color_red}FAILED${color_norm}"
- ret=1
- fi
- else
- bash "$t" || ret=1
- fi
-done
-exit $ret
diff --git a/vendor/github.com/spf13/pflag/verify/gofmt.sh b/vendor/github.com/spf13/pflag/verify/gofmt.sh
deleted file mode 100755
index f66acf803..000000000
--- a/vendor/github.com/spf13/pflag/verify/gofmt.sh
+++ /dev/null
@@ -1,19 +0,0 @@
-#!/bin/bash
-
-set -o errexit
-set -o nounset
-set -o pipefail
-
-ROOT=$(dirname "${BASH_SOURCE}")/..
-
-pushd "${ROOT}" > /dev/null
-
-GOFMT=${GOFMT:-"gofmt"}
-bad_files=$(find . -name '*.go' | xargs $GOFMT -s -l)
-if [[ -n "${bad_files}" ]]; then
- echo "!!! '$GOFMT' needs to be run on the following files: "
- echo "${bad_files}"
- exit 1
-fi
-
-# ex: ts=2 sw=2 et filetype=sh
diff --git a/vendor/github.com/spf13/pflag/verify/golint.sh b/vendor/github.com/spf13/pflag/verify/golint.sh
deleted file mode 100755
index 685c1778e..000000000
--- a/vendor/github.com/spf13/pflag/verify/golint.sh
+++ /dev/null
@@ -1,15 +0,0 @@
-#!/bin/bash
-
-ROOT=$(dirname "${BASH_SOURCE}")/..
-GOLINT=${GOLINT:-"golint"}
-
-pushd "${ROOT}" > /dev/null
- bad_files=$($GOLINT -min_confidence=0.9 ./...)
- if [[ -n "${bad_files}" ]]; then
- echo "!!! '$GOLINT' problems: "
- echo "${bad_files}"
- exit 1
- fi
-popd > /dev/null
-
-# ex: ts=2 sw=2 et filetype=sh
diff --git a/vendor/github.com/spf13/viper/flags_test.go b/vendor/github.com/spf13/viper/flags_test.go
deleted file mode 100644
index 0b976b605..000000000
--- a/vendor/github.com/spf13/viper/flags_test.go
+++ /dev/null
@@ -1,65 +0,0 @@
-package viper
-
-import (
- "testing"
-
- "github.com/spf13/pflag"
- "github.com/stretchr/testify/assert"
-)
-
-func TestBindFlagValueSet(t *testing.T) {
- flagSet := pflag.NewFlagSet("test", pflag.ContinueOnError)
-
- var testValues = map[string]*string{
- "host": nil,
- "port": nil,
- "endpoint": nil,
- }
-
- var mutatedTestValues = map[string]string{
- "host": "localhost",
- "port": "6060",
- "endpoint": "/public",
- }
-
- for name := range testValues {
- testValues[name] = flagSet.String(name, "", "test")
- }
-
- flagValueSet := pflagValueSet{flagSet}
-
- err := BindFlagValues(flagValueSet)
- if err != nil {
- t.Fatalf("error binding flag set, %v", err)
- }
-
- flagSet.VisitAll(func(flag *pflag.Flag) {
- flag.Value.Set(mutatedTestValues[flag.Name])
- flag.Changed = true
- })
-
- for name, expected := range mutatedTestValues {
- assert.Equal(t, Get(name), expected)
- }
-}
-
-func TestBindFlagValue(t *testing.T) {
- var testString = "testing"
- var testValue = newStringValue(testString, &testString)
-
- flag := &pflag.Flag{
- Name: "testflag",
- Value: testValue,
- Changed: false,
- }
-
- flagValue := pflagValue{flag}
- BindFlagValue("testvalue", flagValue)
-
- assert.Equal(t, testString, Get("testvalue"))
-
- flag.Value.Set("testing_mutate")
- flag.Changed = true //hack for pflag usage
-
- assert.Equal(t, "testing_mutate", Get("testvalue"))
-}
diff --git a/vendor/github.com/spf13/viper/overrides_test.go b/vendor/github.com/spf13/viper/overrides_test.go
deleted file mode 100644
index dd2aa9b0d..000000000
--- a/vendor/github.com/spf13/viper/overrides_test.go
+++ /dev/null
@@ -1,173 +0,0 @@
-package viper
-
-import (
- "fmt"
- "strings"
- "testing"
-
- "github.com/spf13/cast"
- "github.com/stretchr/testify/assert"
-)
-
-type layer int
-
-const (
- defaultLayer layer = iota + 1
- overrideLayer
-)
-
-func TestNestedOverrides(t *testing.T) {
- assert := assert.New(t)
- var v *Viper
-
- // Case 0: value overridden by a value
- overrideDefault(assert, "tom", 10, "tom", 20) // "tom" is first given 10 as default value, then overridden by 20
- override(assert, "tom", 10, "tom", 20) // "tom" is first given value 10, then overridden by 20
- overrideDefault(assert, "tom.age", 10, "tom.age", 20)
- override(assert, "tom.age", 10, "tom.age", 20)
- overrideDefault(assert, "sawyer.tom.age", 10, "sawyer.tom.age", 20)
- override(assert, "sawyer.tom.age", 10, "sawyer.tom.age", 20)
-
- // Case 1: key:value overridden by a value
- v = overrideDefault(assert, "tom.age", 10, "tom", "boy") // "tom.age" is first given 10 as default value, then "tom" is overridden by "boy"
- assert.Nil(v.Get("tom.age")) // "tom.age" should not exist anymore
- v = override(assert, "tom.age", 10, "tom", "boy")
- assert.Nil(v.Get("tom.age"))
-
- // Case 2: value overridden by a key:value
- overrideDefault(assert, "tom", "boy", "tom.age", 10) // "tom" is first given "boy" as default value, then "tom" is overridden by map{"age":10}
- override(assert, "tom.age", 10, "tom", "boy")
-
- // Case 3: key:value overridden by a key:value
- v = overrideDefault(assert, "tom.size", 4, "tom.age", 10)
- assert.Equal(4, v.Get("tom.size")) // value should still be reachable
- v = override(assert, "tom.size", 4, "tom.age", 10)
- assert.Equal(4, v.Get("tom.size"))
- deepCheckValue(assert, v, overrideLayer, []string{"tom", "size"}, 4)
-
- // Case 4: key:value overridden by a map
- v = overrideDefault(assert, "tom.size", 4, "tom", map[string]interface{}{"age": 10}) // "tom.size" is first given "4" as default value, then "tom" is overridden by map{"age":10}
- assert.Equal(4, v.Get("tom.size")) // "tom.size" should still be reachable
- assert.Equal(10, v.Get("tom.age")) // new value should be there
- deepCheckValue(assert, v, overrideLayer, []string{"tom", "age"}, 10) // new value should be there
- v = override(assert, "tom.size", 4, "tom", map[string]interface{}{"age": 10})
- assert.Nil(v.Get("tom.size"))
- assert.Equal(10, v.Get("tom.age"))
- deepCheckValue(assert, v, overrideLayer, []string{"tom", "age"}, 10)
-
- // Case 5: array overridden by a value
- overrideDefault(assert, "tom", []int{10, 20}, "tom", 30)
- override(assert, "tom", []int{10, 20}, "tom", 30)
- overrideDefault(assert, "tom.age", []int{10, 20}, "tom.age", 30)
- override(assert, "tom.age", []int{10, 20}, "tom.age", 30)
-
- // Case 6: array overridden by an array
- overrideDefault(assert, "tom", []int{10, 20}, "tom", []int{30, 40})
- override(assert, "tom", []int{10, 20}, "tom", []int{30, 40})
- overrideDefault(assert, "tom.age", []int{10, 20}, "tom.age", []int{30, 40})
- v = override(assert, "tom.age", []int{10, 20}, "tom.age", []int{30, 40})
- // explicit array merge:
- s, ok := v.Get("tom.age").([]int)
- if assert.True(ok, "tom[\"age\"] is not a slice") {
- v.Set("tom.age", append(s, []int{50, 60}...))
- assert.Equal([]int{30, 40, 50, 60}, v.Get("tom.age"))
- deepCheckValue(assert, v, overrideLayer, []string{"tom", "age"}, []int{30, 40, 50, 60})
- }
-}
-
-func overrideDefault(assert *assert.Assertions, firstPath string, firstValue interface{}, secondPath string, secondValue interface{}) *Viper {
- return overrideFromLayer(defaultLayer, assert, firstPath, firstValue, secondPath, secondValue)
-}
-func override(assert *assert.Assertions, firstPath string, firstValue interface{}, secondPath string, secondValue interface{}) *Viper {
- return overrideFromLayer(overrideLayer, assert, firstPath, firstValue, secondPath, secondValue)
-}
-
-// overrideFromLayer performs the sequential override and low-level checks.
-//
-// First assignment is made on layer l for path firstPath with value firstValue,
-// the second one on the override layer (i.e., with the Set() function)
-// for path secondPath with value secondValue.
-//
-// firstPath and secondPath can include an arbitrary number of dots to indicate
-// a nested element.
-//
-// After each assignment, the value is checked, retrieved both by its full path
-// and by its key sequence (successive maps).
-func overrideFromLayer(l layer, assert *assert.Assertions, firstPath string, firstValue interface{}, secondPath string, secondValue interface{}) *Viper {
- v := New()
- firstKeys := strings.Split(firstPath, v.keyDelim)
- if assert == nil ||
- len(firstKeys) == 0 || len(firstKeys[0]) == 0 {
- return v
- }
-
- // Set and check first value
- switch l {
- case defaultLayer:
- v.SetDefault(firstPath, firstValue)
- case overrideLayer:
- v.Set(firstPath, firstValue)
- default:
- return v
- }
- assert.Equal(firstValue, v.Get(firstPath))
- deepCheckValue(assert, v, l, firstKeys, firstValue)
-
- // Override and check new value
- secondKeys := strings.Split(secondPath, v.keyDelim)
- if len(secondKeys) == 0 || len(secondKeys[0]) == 0 {
- return v
- }
- v.Set(secondPath, secondValue)
- assert.Equal(secondValue, v.Get(secondPath))
- deepCheckValue(assert, v, overrideLayer, secondKeys, secondValue)
-
- return v
-}
-
-// deepCheckValue checks that all given keys correspond to a valid path in the
-// configuration map of the given layer, and that the final value equals the one given
-func deepCheckValue(assert *assert.Assertions, v *Viper, l layer, keys []string, value interface{}) {
- if assert == nil || v == nil ||
- len(keys) == 0 || len(keys[0]) == 0 {
- return
- }
-
- // init
- var val interface{}
- var ms string
- switch l {
- case defaultLayer:
- val = v.defaults
- ms = "v.defaults"
- case overrideLayer:
- val = v.override
- ms = "v.override"
- }
-
- // loop through map
- var m map[string]interface{}
- err := false
- for _, k := range keys {
- if val == nil {
- assert.Fail(fmt.Sprintf("%s is not a map[string]interface{}", ms))
- return
- }
-
- // deep scan of the map to get the final value
- switch val.(type) {
- case map[interface{}]interface{}:
- m = cast.ToStringMap(val)
- case map[string]interface{}:
- m = val.(map[string]interface{})
- default:
- assert.Fail(fmt.Sprintf("%s is not a map[string]interface{}", ms))
- return
- }
- ms = ms + "[\"" + k + "\"]"
- val = m[k]
- }
- if !err {
- assert.Equal(value, val)
- }
-}
diff --git a/vendor/github.com/spf13/viper/remote/remote.go b/vendor/github.com/spf13/viper/remote/remote.go
deleted file mode 100644
index 810d0702e..000000000
--- a/vendor/github.com/spf13/viper/remote/remote.go
+++ /dev/null
@@ -1,105 +0,0 @@
-// Copyright © 2015 Steve Francia <spf@spf13.com>.
-//
-// Use of this source code is governed by an MIT-style
-// license that can be found in the LICENSE file.
-
-// Package remote integrates the remote features of Viper.
-package remote
-
-import (
- "bytes"
- "io"
- "os"
-
- "github.com/spf13/viper"
- crypt "github.com/xordataexchange/crypt/config"
-)
-
-type remoteConfigProvider struct{}
-
-func (rc remoteConfigProvider) Get(rp viper.RemoteProvider) (io.Reader, error) {
- cm, err := getConfigManager(rp)
- if err != nil {
- return nil, err
- }
- b, err := cm.Get(rp.Path())
- if err != nil {
- return nil, err
- }
- return bytes.NewReader(b), nil
-}
-
-func (rc remoteConfigProvider) Watch(rp viper.RemoteProvider) (io.Reader, error) {
- cm, err := getConfigManager(rp)
- if err != nil {
- return nil, err
- }
- resp, err := cm.Get(rp.Path())
- if err != nil {
- return nil, err
- }
-
- return bytes.NewReader(resp), nil
-}
-
-func (rc remoteConfigProvider) WatchChannel(rp viper.RemoteProvider) (<-chan *viper.RemoteResponse, chan bool) {
- cm, err := getConfigManager(rp)
- if err != nil {
- return nil, nil
- }
- quit := make(chan bool)
- quitwc := make(chan bool)
- viperResponsCh := make(chan *viper.RemoteResponse)
- cryptoResponseCh := cm.Watch(rp.Path(), quit)
- // need this function to convert the Channel response form crypt.Response to viper.Response
- go func(cr <-chan *crypt.Response, vr chan<- *viper.RemoteResponse, quitwc <-chan bool, quit chan<- bool) {
- for {
- select {
- case <-quitwc:
- quit <- true
- return
- case resp := <-cr:
- vr <- &viper.RemoteResponse{
- Error: resp.Error,
- Value: resp.Value,
- }
-
- }
-
- }
- }(cryptoResponseCh, viperResponsCh, quitwc, quit)
-
- return viperResponsCh, quitwc
-}
-
-func getConfigManager(rp viper.RemoteProvider) (crypt.ConfigManager, error) {
- var cm crypt.ConfigManager
- var err error
-
- if rp.SecretKeyring() != "" {
- kr, err := os.Open(rp.SecretKeyring())
- defer kr.Close()
- if err != nil {
- return nil, err
- }
- if rp.Provider() == "etcd" {
- cm, err = crypt.NewEtcdConfigManager([]string{rp.Endpoint()}, kr)
- } else {
- cm, err = crypt.NewConsulConfigManager([]string{rp.Endpoint()}, kr)
- }
- } else {
- if rp.Provider() == "etcd" {
- cm, err = crypt.NewStandardEtcdConfigManager([]string{rp.Endpoint()})
- } else {
- cm, err = crypt.NewStandardConsulConfigManager([]string{rp.Endpoint()})
- }
- }
- if err != nil {
- return nil, err
- }
- return cm, nil
-}
-
-func init() {
- viper.RemoteConfig = &remoteConfigProvider{}
-}
diff --git a/vendor/github.com/spf13/viper/util_test.go b/vendor/github.com/spf13/viper/util_test.go
deleted file mode 100644
index 0af80bb63..000000000
--- a/vendor/github.com/spf13/viper/util_test.go
+++ /dev/null
@@ -1,54 +0,0 @@
-// Copyright © 2016 Steve Francia <spf@spf13.com>.
-//
-// Use of this source code is governed by an MIT-style
-// license that can be found in the LICENSE file.
-
-// Viper is a application configuration system.
-// It believes that applications can be configured a variety of ways
-// via flags, ENVIRONMENT variables, configuration files retrieved
-// from the file system, or a remote key/value store.
-
-package viper
-
-import (
- "reflect"
- "testing"
-)
-
-func TestCopyAndInsensitiviseMap(t *testing.T) {
- var (
- given = map[string]interface{}{
- "Foo": 32,
- "Bar": map[interface{}]interface {
- }{
- "ABc": "A",
- "cDE": "B"},
- }
- expected = map[string]interface{}{
- "foo": 32,
- "bar": map[string]interface {
- }{
- "abc": "A",
- "cde": "B"},
- }
- )
-
- got := copyAndInsensitiviseMap(given)
-
- if !reflect.DeepEqual(got, expected) {
- t.Fatalf("Got %q\nexpected\n%q", got, expected)
- }
-
- if _, ok := given["foo"]; ok {
- t.Fatal("Input map changed")
- }
-
- if _, ok := given["bar"]; ok {
- t.Fatal("Input map changed")
- }
-
- m := given["Bar"].(map[interface{}]interface{})
- if _, ok := m["ABc"]; !ok {
- t.Fatal("Input map changed")
- }
-}
diff --git a/vendor/github.com/spf13/viper/viper_test.go b/vendor/github.com/spf13/viper/viper_test.go
deleted file mode 100644
index c93480eab..000000000
--- a/vendor/github.com/spf13/viper/viper_test.go
+++ /dev/null
@@ -1,1406 +0,0 @@
-// Copyright © 2014 Steve Francia <spf@spf13.com>.
-//
-// Use of this source code is governed by an MIT-style
-// license that can be found in the LICENSE file.
-
-package viper
-
-import (
- "bytes"
- "fmt"
- "io"
- "io/ioutil"
- "os"
- "path"
- "reflect"
- "sort"
- "strings"
- "testing"
- "time"
-
- "github.com/spf13/afero"
- "github.com/spf13/cast"
-
- "github.com/spf13/pflag"
- "github.com/stretchr/testify/assert"
-)
-
-var yamlExample = []byte(`Hacker: true
-name: steve
-hobbies:
-- skateboarding
-- snowboarding
-- go
-clothing:
- jacket: leather
- trousers: denim
- pants:
- size: large
-age: 35
-eyes : brown
-beard: true
-`)
-
-var yamlExampleWithExtras = []byte(`Existing: true
-Bogus: true
-`)
-
-type testUnmarshalExtra struct {
- Existing bool
-}
-
-var tomlExample = []byte(`
-title = "TOML Example"
-
-[owner]
-organization = "MongoDB"
-Bio = "MongoDB Chief Developer Advocate & Hacker at Large"
-dob = 1979-05-27T07:32:00Z # First class dates? Why not?`)
-
-var jsonExample = []byte(`{
-"id": "0001",
-"type": "donut",
-"name": "Cake",
-"ppu": 0.55,
-"batters": {
- "batter": [
- { "type": "Regular" },
- { "type": "Chocolate" },
- { "type": "Blueberry" },
- { "type": "Devil's Food" }
- ]
- }
-}`)
-
-var hclExample = []byte(`
-id = "0001"
-type = "donut"
-name = "Cake"
-ppu = 0.55
-foos {
- foo {
- key = 1
- }
- foo {
- key = 2
- }
- foo {
- key = 3
- }
- foo {
- key = 4
- }
-}`)
-
-var propertiesExample = []byte(`
-p_id: 0001
-p_type: donut
-p_name: Cake
-p_ppu: 0.55
-p_batters.batter.type: Regular
-`)
-
-var remoteExample = []byte(`{
-"id":"0002",
-"type":"cronut",
-"newkey":"remote"
-}`)
-
-func initConfigs() {
- Reset()
- var r io.Reader
- SetConfigType("yaml")
- r = bytes.NewReader(yamlExample)
- unmarshalReader(r, v.config)
-
- SetConfigType("json")
- r = bytes.NewReader(jsonExample)
- unmarshalReader(r, v.config)
-
- SetConfigType("hcl")
- r = bytes.NewReader(hclExample)
- unmarshalReader(r, v.config)
-
- SetConfigType("properties")
- r = bytes.NewReader(propertiesExample)
- unmarshalReader(r, v.config)
-
- SetConfigType("toml")
- r = bytes.NewReader(tomlExample)
- unmarshalReader(r, v.config)
-
- SetConfigType("json")
- remote := bytes.NewReader(remoteExample)
- unmarshalReader(remote, v.kvstore)
-}
-
-func initConfig(typ, config string) {
- Reset()
- SetConfigType(typ)
- r := strings.NewReader(config)
-
- if err := unmarshalReader(r, v.config); err != nil {
- panic(err)
- }
-}
-
-func initYAML() {
- initConfig("yaml", string(yamlExample))
-}
-
-func initJSON() {
- Reset()
- SetConfigType("json")
- r := bytes.NewReader(jsonExample)
-
- unmarshalReader(r, v.config)
-}
-
-func initProperties() {
- Reset()
- SetConfigType("properties")
- r := bytes.NewReader(propertiesExample)
-
- unmarshalReader(r, v.config)
-}
-
-func initTOML() {
- Reset()
- SetConfigType("toml")
- r := bytes.NewReader(tomlExample)
-
- unmarshalReader(r, v.config)
-}
-
-func initHcl() {
- Reset()
- SetConfigType("hcl")
- r := bytes.NewReader(hclExample)
-
- unmarshalReader(r, v.config)
-}
-
-// make directories for testing
-func initDirs(t *testing.T) (string, string, func()) {
-
- var (
- testDirs = []string{`a a`, `b`, `c\c`, `D_`}
- config = `improbable`
- )
-
- root, err := ioutil.TempDir("", "")
-
- cleanup := true
- defer func() {
- if cleanup {
- os.Chdir("..")
- os.RemoveAll(root)
- }
- }()
-
- assert.Nil(t, err)
-
- err = os.Chdir(root)
- assert.Nil(t, err)
-
- for _, dir := range testDirs {
- err = os.Mkdir(dir, 0750)
- assert.Nil(t, err)
-
- err = ioutil.WriteFile(
- path.Join(dir, config+".toml"),
- []byte("key = \"value is "+dir+"\"\n"),
- 0640)
- assert.Nil(t, err)
- }
-
- cleanup = false
- return root, config, func() {
- os.Chdir("..")
- os.RemoveAll(root)
- }
-}
-
-//stubs for PFlag Values
-type stringValue string
-
-func newStringValue(val string, p *string) *stringValue {
- *p = val
- return (*stringValue)(p)
-}
-
-func (s *stringValue) Set(val string) error {
- *s = stringValue(val)
- return nil
-}
-
-func (s *stringValue) Type() string {
- return "string"
-}
-
-func (s *stringValue) String() string {
- return fmt.Sprintf("%s", *s)
-}
-
-func TestBasics(t *testing.T) {
- SetConfigFile("/tmp/config.yaml")
- filename, err := v.getConfigFile()
- assert.Equal(t, "/tmp/config.yaml", filename)
- assert.NoError(t, err)
-}
-
-func TestDefault(t *testing.T) {
- SetDefault("age", 45)
- assert.Equal(t, 45, Get("age"))
-
- SetDefault("clothing.jacket", "slacks")
- assert.Equal(t, "slacks", Get("clothing.jacket"))
-
- SetConfigType("yaml")
- err := ReadConfig(bytes.NewBuffer(yamlExample))
-
- assert.NoError(t, err)
- assert.Equal(t, "leather", Get("clothing.jacket"))
-}
-
-func TestUnmarshaling(t *testing.T) {
- SetConfigType("yaml")
- r := bytes.NewReader(yamlExample)
-
- unmarshalReader(r, v.config)
- assert.True(t, InConfig("name"))
- assert.False(t, InConfig("state"))
- assert.Equal(t, "steve", Get("name"))
- assert.Equal(t, []interface{}{"skateboarding", "snowboarding", "go"}, Get("hobbies"))
- assert.Equal(t, map[string]interface{}{"jacket": "leather", "trousers": "denim", "pants": map[string]interface{}{"size": "large"}}, Get("clothing"))
- assert.Equal(t, 35, Get("age"))
-}
-
-func TestUnmarshalExact(t *testing.T) {
- vip := New()
- target := &testUnmarshalExtra{}
- vip.SetConfigType("yaml")
- r := bytes.NewReader(yamlExampleWithExtras)
- vip.ReadConfig(r)
- err := vip.UnmarshalExact(target)
- if err == nil {
- t.Fatal("UnmarshalExact should error when populating a struct from a conf that contains unused fields")
- }
-}
-
-func TestOverrides(t *testing.T) {
- Set("age", 40)
- assert.Equal(t, 40, Get("age"))
-}
-
-func TestDefaultPost(t *testing.T) {
- assert.NotEqual(t, "NYC", Get("state"))
- SetDefault("state", "NYC")
- assert.Equal(t, "NYC", Get("state"))
-}
-
-func TestAliases(t *testing.T) {
- RegisterAlias("years", "age")
- assert.Equal(t, 40, Get("years"))
- Set("years", 45)
- assert.Equal(t, 45, Get("age"))
-}
-
-func TestAliasInConfigFile(t *testing.T) {
- // the config file specifies "beard". If we make this an alias for
- // "hasbeard", we still want the old config file to work with beard.
- RegisterAlias("beard", "hasbeard")
- assert.Equal(t, true, Get("hasbeard"))
- Set("hasbeard", false)
- assert.Equal(t, false, Get("beard"))
-}
-
-func TestYML(t *testing.T) {
- initYAML()
- assert.Equal(t, "steve", Get("name"))
-}
-
-func TestJSON(t *testing.T) {
- initJSON()
- assert.Equal(t, "0001", Get("id"))
-}
-
-func TestProperties(t *testing.T) {
- initProperties()
- assert.Equal(t, "0001", Get("p_id"))
-}
-
-func TestTOML(t *testing.T) {
- initTOML()
- assert.Equal(t, "TOML Example", Get("title"))
-}
-
-func TestHCL(t *testing.T) {
- initHcl()
- assert.Equal(t, "0001", Get("id"))
- assert.Equal(t, 0.55, Get("ppu"))
- assert.Equal(t, "donut", Get("type"))
- assert.Equal(t, "Cake", Get("name"))
- Set("id", "0002")
- assert.Equal(t, "0002", Get("id"))
- assert.NotEqual(t, "cronut", Get("type"))
-}
-
-func TestRemotePrecedence(t *testing.T) {
- initJSON()
-
- remote := bytes.NewReader(remoteExample)
- assert.Equal(t, "0001", Get("id"))
- unmarshalReader(remote, v.kvstore)
- assert.Equal(t, "0001", Get("id"))
- assert.NotEqual(t, "cronut", Get("type"))
- assert.Equal(t, "remote", Get("newkey"))
- Set("newkey", "newvalue")
- assert.NotEqual(t, "remote", Get("newkey"))
- assert.Equal(t, "newvalue", Get("newkey"))
- Set("newkey", "remote")
-}
-
-func TestEnv(t *testing.T) {
- initJSON()
-
- BindEnv("id")
- BindEnv("f", "FOOD")
-
- os.Setenv("ID", "13")
- os.Setenv("FOOD", "apple")
- os.Setenv("NAME", "crunk")
-
- assert.Equal(t, "13", Get("id"))
- assert.Equal(t, "apple", Get("f"))
- assert.Equal(t, "Cake", Get("name"))
-
- AutomaticEnv()
-
- assert.Equal(t, "crunk", Get("name"))
-
-}
-
-func TestEnvPrefix(t *testing.T) {
- initJSON()
-
- SetEnvPrefix("foo") // will be uppercased automatically
- BindEnv("id")
- BindEnv("f", "FOOD") // not using prefix
-
- os.Setenv("FOO_ID", "13")
- os.Setenv("FOOD", "apple")
- os.Setenv("FOO_NAME", "crunk")
-
- assert.Equal(t, "13", Get("id"))
- assert.Equal(t, "apple", Get("f"))
- assert.Equal(t, "Cake", Get("name"))
-
- AutomaticEnv()
-
- assert.Equal(t, "crunk", Get("name"))
-}
-
-func TestAutoEnv(t *testing.T) {
- Reset()
-
- AutomaticEnv()
- os.Setenv("FOO_BAR", "13")
- assert.Equal(t, "13", Get("foo_bar"))
-}
-
-func TestAutoEnvWithPrefix(t *testing.T) {
- Reset()
-
- AutomaticEnv()
- SetEnvPrefix("Baz")
- os.Setenv("BAZ_BAR", "13")
- assert.Equal(t, "13", Get("bar"))
-}
-
-func TestSetEnvKeyReplacer(t *testing.T) {
- Reset()
-
- AutomaticEnv()
- os.Setenv("REFRESH_INTERVAL", "30s")
-
- replacer := strings.NewReplacer("-", "_")
- SetEnvKeyReplacer(replacer)
-
- assert.Equal(t, "30s", Get("refresh-interval"))
-}
-
-func TestAllKeys(t *testing.T) {
- initConfigs()
-
- ks := sort.StringSlice{"title", "newkey", "owner.organization", "owner.dob", "owner.bio", "name", "beard", "ppu", "batters.batter", "hobbies", "clothing.jacket", "clothing.trousers", "clothing.pants.size", "age", "hacker", "id", "type", "eyes", "p_id", "p_ppu", "p_batters.batter.type", "p_type", "p_name", "foos"}
- dob, _ := time.Parse(time.RFC3339, "1979-05-27T07:32:00Z")
- all := map[string]interface{}{"owner": map[string]interface{}{"organization": "MongoDB", "bio": "MongoDB Chief Developer Advocate & Hacker at Large", "dob": dob}, "title": "TOML Example", "ppu": 0.55, "eyes": "brown", "clothing": map[string]interface{}{"trousers": "denim", "jacket": "leather", "pants": map[string]interface{}{"size": "large"}}, "id": "0001", "batters": map[string]interface{}{"batter": []interface{}{map[string]interface{}{"type": "Regular"}, map[string]interface{}{"type": "Chocolate"}, map[string]interface{}{"type": "Blueberry"}, map[string]interface{}{"type": "Devil's Food"}}}, "hacker": true, "beard": true, "hobbies": []interface{}{"skateboarding", "snowboarding", "go"}, "age": 35, "type": "donut", "newkey": "remote", "name": "Cake", "p_id": "0001", "p_ppu": "0.55", "p_name": "Cake", "p_batters": map[string]interface{}{"batter": map[string]interface{}{"type": "Regular"}}, "p_type": "donut", "foos": []map[string]interface{}{map[string]interface{}{"foo": []map[string]interface{}{map[string]interface{}{"key": 1}, map[string]interface{}{"key": 2}, map[string]interface{}{"key": 3}, map[string]interface{}{"key": 4}}}}}
-
- var allkeys sort.StringSlice
- allkeys = AllKeys()
- allkeys.Sort()
- ks.Sort()
-
- assert.Equal(t, ks, allkeys)
- assert.Equal(t, all, AllSettings())
-}
-
-func TestAllKeysWithEnv(t *testing.T) {
- v := New()
-
- // bind and define environment variables (including a nested one)
- v.BindEnv("id")
- v.BindEnv("foo.bar")
- v.SetEnvKeyReplacer(strings.NewReplacer(".", "_"))
- os.Setenv("ID", "13")
- os.Setenv("FOO_BAR", "baz")
-
- expectedKeys := sort.StringSlice{"id", "foo.bar"}
- expectedKeys.Sort()
- keys := sort.StringSlice(v.AllKeys())
- keys.Sort()
- assert.Equal(t, expectedKeys, keys)
-}
-
-func TestAliasesOfAliases(t *testing.T) {
- Set("Title", "Checking Case")
- RegisterAlias("Foo", "Bar")
- RegisterAlias("Bar", "Title")
- assert.Equal(t, "Checking Case", Get("FOO"))
-}
-
-func TestRecursiveAliases(t *testing.T) {
- RegisterAlias("Baz", "Roo")
- RegisterAlias("Roo", "baz")
-}
-
-func TestUnmarshal(t *testing.T) {
- SetDefault("port", 1313)
- Set("name", "Steve")
- Set("duration", "1s1ms")
-
- type config struct {
- Port int
- Name string
- Duration time.Duration
- }
-
- var C config
-
- err := Unmarshal(&C)
- if err != nil {
- t.Fatalf("unable to decode into struct, %v", err)
- }
-
- assert.Equal(t, &config{Name: "Steve", Port: 1313, Duration: time.Second + time.Millisecond}, &C)
-
- Set("port", 1234)
- err = Unmarshal(&C)
- if err != nil {
- t.Fatalf("unable to decode into struct, %v", err)
- }
- assert.Equal(t, &config{Name: "Steve", Port: 1234, Duration: time.Second + time.Millisecond}, &C)
-}
-
-func TestBindPFlags(t *testing.T) {
- v := New() // create independent Viper object
- flagSet := pflag.NewFlagSet("test", pflag.ContinueOnError)
-
- var testValues = map[string]*string{
- "host": nil,
- "port": nil,
- "endpoint": nil,
- }
-
- var mutatedTestValues = map[string]string{
- "host": "localhost",
- "port": "6060",
- "endpoint": "/public",
- }
-
- for name := range testValues {
- testValues[name] = flagSet.String(name, "", "test")
- }
-
- err := v.BindPFlags(flagSet)
- if err != nil {
- t.Fatalf("error binding flag set, %v", err)
- }
-
- flagSet.VisitAll(func(flag *pflag.Flag) {
- flag.Value.Set(mutatedTestValues[flag.Name])
- flag.Changed = true
- })
-
- for name, expected := range mutatedTestValues {
- assert.Equal(t, expected, v.Get(name))
- }
-
-}
-
-func TestBindPFlagsStringSlice(t *testing.T) {
- for _, testValue := range []struct {
- Expected []string
- Value string
- }{
- {[]string{}, ""},
- {[]string{"jeden"}, "jeden"},
- {[]string{"dwa", "trzy"}, "dwa,trzy"},
- {[]string{"cztery", "piec , szesc"}, "cztery,\"piec , szesc\""}} {
-
- for _, changed := range []bool{true, false} {
- v := New() // create independent Viper object
- flagSet := pflag.NewFlagSet("test", pflag.ContinueOnError)
- flagSet.StringSlice("stringslice", testValue.Expected, "test")
- flagSet.Visit(func(f *pflag.Flag) {
- if len(testValue.Value) > 0 {
- f.Value.Set(testValue.Value)
- f.Changed = changed
- }
- })
-
- err := v.BindPFlags(flagSet)
- if err != nil {
- t.Fatalf("error binding flag set, %v", err)
- }
-
- type TestStr struct {
- StringSlice []string
- }
- val := &TestStr{}
- if err := v.Unmarshal(val); err != nil {
- t.Fatalf("%+#v cannot unmarshal: %s", testValue.Value, err)
- }
- assert.Equal(t, testValue.Expected, val.StringSlice)
- }
- }
-}
-
-func TestBindPFlag(t *testing.T) {
- var testString = "testing"
- var testValue = newStringValue(testString, &testString)
-
- flag := &pflag.Flag{
- Name: "testflag",
- Value: testValue,
- Changed: false,
- }
-
- BindPFlag("testvalue", flag)
-
- assert.Equal(t, testString, Get("testvalue"))
-
- flag.Value.Set("testing_mutate")
- flag.Changed = true //hack for pflag usage
-
- assert.Equal(t, "testing_mutate", Get("testvalue"))
-
-}
-
-func TestBoundCaseSensitivity(t *testing.T) {
- assert.Equal(t, "brown", Get("eyes"))
-
- BindEnv("eYEs", "TURTLE_EYES")
- os.Setenv("TURTLE_EYES", "blue")
-
- assert.Equal(t, "blue", Get("eyes"))
-
- var testString = "green"
- var testValue = newStringValue(testString, &testString)
-
- flag := &pflag.Flag{
- Name: "eyeballs",
- Value: testValue,
- Changed: true,
- }
-
- BindPFlag("eYEs", flag)
- assert.Equal(t, "green", Get("eyes"))
-
-}
-
-func TestSizeInBytes(t *testing.T) {
- input := map[string]uint{
- "": 0,
- "b": 0,
- "12 bytes": 0,
- "200000000000gb": 0,
- "12 b": 12,
- "43 MB": 43 * (1 << 20),
- "10mb": 10 * (1 << 20),
- "1gb": 1 << 30,
- }
-
- for str, expected := range input {
- assert.Equal(t, expected, parseSizeInBytes(str), str)
- }
-}
-
-func TestFindsNestedKeys(t *testing.T) {
- initConfigs()
- dob, _ := time.Parse(time.RFC3339, "1979-05-27T07:32:00Z")
-
- Set("super", map[string]interface{}{
- "deep": map[string]interface{}{
- "nested": "value",
- },
- })
-
- expected := map[string]interface{}{
- "super": map[string]interface{}{
- "deep": map[string]interface{}{
- "nested": "value",
- },
- },
- "super.deep": map[string]interface{}{
- "nested": "value",
- },
- "super.deep.nested": "value",
- "owner.organization": "MongoDB",
- "batters.batter": []interface{}{
- map[string]interface{}{
- "type": "Regular",
- },
- map[string]interface{}{
- "type": "Chocolate",
- },
- map[string]interface{}{
- "type": "Blueberry",
- },
- map[string]interface{}{
- "type": "Devil's Food",
- },
- },
- "hobbies": []interface{}{
- "skateboarding", "snowboarding", "go",
- },
- "title": "TOML Example",
- "newkey": "remote",
- "batters": map[string]interface{}{
- "batter": []interface{}{
- map[string]interface{}{
- "type": "Regular",
- },
- map[string]interface{}{
- "type": "Chocolate",
- }, map[string]interface{}{
- "type": "Blueberry",
- }, map[string]interface{}{
- "type": "Devil's Food",
- },
- },
- },
- "eyes": "brown",
- "age": 35,
- "owner": map[string]interface{}{
- "organization": "MongoDB",
- "bio": "MongoDB Chief Developer Advocate & Hacker at Large",
- "dob": dob,
- },
- "owner.bio": "MongoDB Chief Developer Advocate & Hacker at Large",
- "type": "donut",
- "id": "0001",
- "name": "Cake",
- "hacker": true,
- "ppu": 0.55,
- "clothing": map[string]interface{}{
- "jacket": "leather",
- "trousers": "denim",
- "pants": map[string]interface{}{
- "size": "large",
- },
- },
- "clothing.jacket": "leather",
- "clothing.pants.size": "large",
- "clothing.trousers": "denim",
- "owner.dob": dob,
- "beard": true,
- "foos": []map[string]interface{}{
- map[string]interface{}{
- "foo": []map[string]interface{}{
- map[string]interface{}{
- "key": 1,
- },
- map[string]interface{}{
- "key": 2,
- },
- map[string]interface{}{
- "key": 3,
- },
- map[string]interface{}{
- "key": 4,
- },
- },
- },
- },
- }
-
- for key, expectedValue := range expected {
-
- assert.Equal(t, expectedValue, v.Get(key))
- }
-
-}
-
-func TestReadBufConfig(t *testing.T) {
- v := New()
- v.SetConfigType("yaml")
- v.ReadConfig(bytes.NewBuffer(yamlExample))
- t.Log(v.AllKeys())
-
- assert.True(t, v.InConfig("name"))
- assert.False(t, v.InConfig("state"))
- assert.Equal(t, "steve", v.Get("name"))
- assert.Equal(t, []interface{}{"skateboarding", "snowboarding", "go"}, v.Get("hobbies"))
- assert.Equal(t, map[string]interface{}{"jacket": "leather", "trousers": "denim", "pants": map[string]interface{}{"size": "large"}}, v.Get("clothing"))
- assert.Equal(t, 35, v.Get("age"))
-}
-
-func TestIsSet(t *testing.T) {
- v := New()
- v.SetConfigType("yaml")
- v.ReadConfig(bytes.NewBuffer(yamlExample))
- assert.True(t, v.IsSet("clothing.jacket"))
- assert.False(t, v.IsSet("clothing.jackets"))
- assert.False(t, v.IsSet("helloworld"))
- v.Set("helloworld", "fubar")
- assert.True(t, v.IsSet("helloworld"))
-}
-
-func TestDirsSearch(t *testing.T) {
-
- root, config, cleanup := initDirs(t)
- defer cleanup()
-
- v := New()
- v.SetConfigName(config)
- v.SetDefault(`key`, `default`)
-
- entries, err := ioutil.ReadDir(root)
- for _, e := range entries {
- if e.IsDir() {
- v.AddConfigPath(e.Name())
- }
- }
-
- err = v.ReadInConfig()
- assert.Nil(t, err)
-
- assert.Equal(t, `value is `+path.Base(v.configPaths[0]), v.GetString(`key`))
-}
-
-func TestWrongDirsSearchNotFound(t *testing.T) {
-
- _, config, cleanup := initDirs(t)
- defer cleanup()
-
- v := New()
- v.SetConfigName(config)
- v.SetDefault(`key`, `default`)
-
- v.AddConfigPath(`whattayoutalkingbout`)
- v.AddConfigPath(`thispathaintthere`)
-
- err := v.ReadInConfig()
- assert.Equal(t, reflect.TypeOf(ConfigFileNotFoundError{"", ""}), reflect.TypeOf(err))
-
- // Even though config did not load and the error might have
- // been ignored by the client, the default still loads
- assert.Equal(t, `default`, v.GetString(`key`))
-}
-
-func TestWrongDirsSearchNotFoundForMerge(t *testing.T) {
-
- _, config, cleanup := initDirs(t)
- defer cleanup()
-
- v := New()
- v.SetConfigName(config)
- v.SetDefault(`key`, `default`)
-
- v.AddConfigPath(`whattayoutalkingbout`)
- v.AddConfigPath(`thispathaintthere`)
-
- err := v.MergeInConfig()
- assert.Equal(t, reflect.TypeOf(ConfigFileNotFoundError{"", ""}), reflect.TypeOf(err))
-
- // Even though config did not load and the error might have
- // been ignored by the client, the default still loads
- assert.Equal(t, `default`, v.GetString(`key`))
-}
-
-func TestSub(t *testing.T) {
- v := New()
- v.SetConfigType("yaml")
- v.ReadConfig(bytes.NewBuffer(yamlExample))
-
- subv := v.Sub("clothing")
- assert.Equal(t, v.Get("clothing.pants.size"), subv.Get("pants.size"))
-
- subv = v.Sub("clothing.pants")
- assert.Equal(t, v.Get("clothing.pants.size"), subv.Get("size"))
-
- subv = v.Sub("clothing.pants.size")
- assert.Equal(t, (*Viper)(nil), subv)
-
- subv = v.Sub("missing.key")
- assert.Equal(t, (*Viper)(nil), subv)
-}
-
-var hclWriteExpected = []byte(`"foos" = {
- "foo" = {
- "key" = 1
- }
-
- "foo" = {
- "key" = 2
- }
-
- "foo" = {
- "key" = 3
- }
-
- "foo" = {
- "key" = 4
- }
-}
-
-"id" = "0001"
-
-"name" = "Cake"
-
-"ppu" = 0.55
-
-"type" = "donut"`)
-
-func TestWriteConfigHCL(t *testing.T) {
- v := New()
- fs := afero.NewMemMapFs()
- v.SetFs(fs)
- v.SetConfigName("c")
- v.SetConfigType("hcl")
- err := v.ReadConfig(bytes.NewBuffer(hclExample))
- if err != nil {
- t.Fatal(err)
- }
- if err := v.WriteConfigAs("c.hcl"); err != nil {
- t.Fatal(err)
- }
- read, err := afero.ReadFile(fs, "c.hcl")
- if err != nil {
- t.Fatal(err)
- }
- assert.Equal(t, hclWriteExpected, read)
-}
-
-var jsonWriteExpected = []byte(`{
- "batters": {
- "batter": [
- {
- "type": "Regular"
- },
- {
- "type": "Chocolate"
- },
- {
- "type": "Blueberry"
- },
- {
- "type": "Devil's Food"
- }
- ]
- },
- "id": "0001",
- "name": "Cake",
- "ppu": 0.55,
- "type": "donut"
-}`)
-
-func TestWriteConfigJson(t *testing.T) {
- v := New()
- fs := afero.NewMemMapFs()
- v.SetFs(fs)
- v.SetConfigName("c")
- v.SetConfigType("json")
- err := v.ReadConfig(bytes.NewBuffer(jsonExample))
- if err != nil {
- t.Fatal(err)
- }
- if err := v.WriteConfigAs("c.json"); err != nil {
- t.Fatal(err)
- }
- read, err := afero.ReadFile(fs, "c.json")
- if err != nil {
- t.Fatal(err)
- }
- assert.Equal(t, jsonWriteExpected, read)
-}
-
-var propertiesWriteExpected = []byte(`p_id = 0001
-p_type = donut
-p_name = Cake
-p_ppu = 0.55
-p_batters.batter.type = Regular
-`)
-
-func TestWriteConfigProperties(t *testing.T) {
- v := New()
- fs := afero.NewMemMapFs()
- v.SetFs(fs)
- v.SetConfigName("c")
- v.SetConfigType("properties")
- err := v.ReadConfig(bytes.NewBuffer(propertiesExample))
- if err != nil {
- t.Fatal(err)
- }
- if err := v.WriteConfigAs("c.properties"); err != nil {
- t.Fatal(err)
- }
- read, err := afero.ReadFile(fs, "c.properties")
- if err != nil {
- t.Fatal(err)
- }
- assert.Equal(t, propertiesWriteExpected, read)
-}
-
-func TestWriteConfigTOML(t *testing.T) {
- fs := afero.NewMemMapFs()
- v := New()
- v.SetFs(fs)
- v.SetConfigName("c")
- v.SetConfigType("toml")
- err := v.ReadConfig(bytes.NewBuffer(tomlExample))
- if err != nil {
- t.Fatal(err)
- }
- if err := v.WriteConfigAs("c.toml"); err != nil {
- t.Fatal(err)
- }
-
- // The TOML String method does not order the contents.
- // Therefore, we must read the generated file and compare the data.
- v2 := New()
- v2.SetFs(fs)
- v2.SetConfigName("c")
- v2.SetConfigType("toml")
- v2.SetConfigFile("c.toml")
- err = v2.ReadInConfig()
- if err != nil {
- t.Fatal(err)
- }
-
- assert.Equal(t, v.GetString("title"), v2.GetString("title"))
- assert.Equal(t, v.GetString("owner.bio"), v2.GetString("owner.bio"))
- assert.Equal(t, v.GetString("owner.dob"), v2.GetString("owner.dob"))
- assert.Equal(t, v.GetString("owner.organization"), v2.GetString("owner.organization"))
-}
-
-var yamlWriteExpected = []byte(`age: 35
-beard: true
-clothing:
- jacket: leather
- pants:
- size: large
- trousers: denim
-eyes: brown
-hacker: true
-hobbies:
-- skateboarding
-- snowboarding
-- go
-name: steve
-`)
-
-func TestWriteConfigYAML(t *testing.T) {
- v := New()
- fs := afero.NewMemMapFs()
- v.SetFs(fs)
- v.SetConfigName("c")
- v.SetConfigType("yaml")
- err := v.ReadConfig(bytes.NewBuffer(yamlExample))
- if err != nil {
- t.Fatal(err)
- }
- if err := v.WriteConfigAs("c.yaml"); err != nil {
- t.Fatal(err)
- }
- read, err := afero.ReadFile(fs, "c.yaml")
- if err != nil {
- t.Fatal(err)
- }
- assert.Equal(t, yamlWriteExpected, read)
-}
-
-var yamlMergeExampleTgt = []byte(`
-hello:
- pop: 37890
- lagrenum: 765432101234567
- world:
- - us
- - uk
- - fr
- - de
-`)
-
-var yamlMergeExampleSrc = []byte(`
-hello:
- pop: 45000
- lagrenum: 7654321001234567
- universe:
- - mw
- - ad
-fu: bar
-`)
-
-func TestMergeConfig(t *testing.T) {
- v := New()
- v.SetConfigType("yml")
- if err := v.ReadConfig(bytes.NewBuffer(yamlMergeExampleTgt)); err != nil {
- t.Fatal(err)
- }
-
- if pop := v.GetInt("hello.pop"); pop != 37890 {
- t.Fatalf("pop != 37890, = %d", pop)
- }
-
- if pop := v.GetInt("hello.lagrenum"); pop != 765432101234567 {
- t.Fatalf("lagrenum != 765432101234567, = %d", pop)
- }
-
- if pop := v.GetInt64("hello.lagrenum"); pop != int64(765432101234567) {
- t.Fatalf("int64 lagrenum != 765432101234567, = %d", pop)
- }
-
- if world := v.GetStringSlice("hello.world"); len(world) != 4 {
- t.Fatalf("len(world) != 4, = %d", len(world))
- }
-
- if fu := v.GetString("fu"); fu != "" {
- t.Fatalf("fu != \"\", = %s", fu)
- }
-
- if err := v.MergeConfig(bytes.NewBuffer(yamlMergeExampleSrc)); err != nil {
- t.Fatal(err)
- }
-
- if pop := v.GetInt("hello.pop"); pop != 45000 {
- t.Fatalf("pop != 45000, = %d", pop)
- }
-
- if pop := v.GetInt("hello.lagrenum"); pop != 7654321001234567 {
- t.Fatalf("lagrenum != 7654321001234567, = %d", pop)
- }
-
- if pop := v.GetInt64("hello.lagrenum"); pop != int64(7654321001234567) {
- t.Fatalf("int64 lagrenum != 7654321001234567, = %d", pop)
- }
-
- if world := v.GetStringSlice("hello.world"); len(world) != 4 {
- t.Fatalf("len(world) != 4, = %d", len(world))
- }
-
- if universe := v.GetStringSlice("hello.universe"); len(universe) != 2 {
- t.Fatalf("len(universe) != 2, = %d", len(universe))
- }
-
- if fu := v.GetString("fu"); fu != "bar" {
- t.Fatalf("fu != \"bar\", = %s", fu)
- }
-}
-
-func TestMergeConfigNoMerge(t *testing.T) {
- v := New()
- v.SetConfigType("yml")
- if err := v.ReadConfig(bytes.NewBuffer(yamlMergeExampleTgt)); err != nil {
- t.Fatal(err)
- }
-
- if pop := v.GetInt("hello.pop"); pop != 37890 {
- t.Fatalf("pop != 37890, = %d", pop)
- }
-
- if world := v.GetStringSlice("hello.world"); len(world) != 4 {
- t.Fatalf("len(world) != 4, = %d", len(world))
- }
-
- if fu := v.GetString("fu"); fu != "" {
- t.Fatalf("fu != \"\", = %s", fu)
- }
-
- if err := v.ReadConfig(bytes.NewBuffer(yamlMergeExampleSrc)); err != nil {
- t.Fatal(err)
- }
-
- if pop := v.GetInt("hello.pop"); pop != 45000 {
- t.Fatalf("pop != 45000, = %d", pop)
- }
-
- if world := v.GetStringSlice("hello.world"); len(world) != 0 {
- t.Fatalf("len(world) != 0, = %d", len(world))
- }
-
- if universe := v.GetStringSlice("hello.universe"); len(universe) != 2 {
- t.Fatalf("len(universe) != 2, = %d", len(universe))
- }
-
- if fu := v.GetString("fu"); fu != "bar" {
- t.Fatalf("fu != \"bar\", = %s", fu)
- }
-}
-
-func TestUnmarshalingWithAliases(t *testing.T) {
- v := New()
- v.SetDefault("ID", 1)
- v.Set("name", "Steve")
- v.Set("lastname", "Owen")
-
- v.RegisterAlias("UserID", "ID")
- v.RegisterAlias("Firstname", "name")
- v.RegisterAlias("Surname", "lastname")
-
- type config struct {
- ID int
- FirstName string
- Surname string
- }
-
- var C config
- err := v.Unmarshal(&C)
- if err != nil {
- t.Fatalf("unable to decode into struct, %v", err)
- }
-
- assert.Equal(t, &config{ID: 1, FirstName: "Steve", Surname: "Owen"}, &C)
-}
-
-func TestSetConfigNameClearsFileCache(t *testing.T) {
- SetConfigFile("/tmp/config.yaml")
- SetConfigName("default")
- f, err := v.getConfigFile()
- if err == nil {
- t.Fatalf("config file cache should have been cleared")
- }
- assert.Empty(t, f)
-}
-
-func TestShadowedNestedValue(t *testing.T) {
-
- config := `name: steve
-clothing:
- jacket: leather
- trousers: denim
- pants:
- size: large
-`
- initConfig("yaml", config)
-
- assert.Equal(t, "steve", GetString("name"))
-
- polyester := "polyester"
- SetDefault("clothing.shirt", polyester)
- SetDefault("clothing.jacket.price", 100)
-
- assert.Equal(t, "leather", GetString("clothing.jacket"))
- assert.Nil(t, Get("clothing.jacket.price"))
- assert.Equal(t, polyester, GetString("clothing.shirt"))
-
- clothingSettings := AllSettings()["clothing"].(map[string]interface{})
- assert.Equal(t, "leather", clothingSettings["jacket"])
- assert.Equal(t, polyester, clothingSettings["shirt"])
-}
-
-func TestDotParameter(t *testing.T) {
- initJSON()
- // shoud take precedence over batters defined in jsonExample
- r := bytes.NewReader([]byte(`{ "batters.batter": [ { "type": "Small" } ] }`))
- unmarshalReader(r, v.config)
-
- actual := Get("batters.batter")
- expected := []interface{}{map[string]interface{}{"type": "Small"}}
- assert.Equal(t, expected, actual)
-}
-
-func TestCaseInsensitive(t *testing.T) {
- for _, config := range []struct {
- typ string
- content string
- }{
- {"yaml", `
-aBcD: 1
-eF:
- gH: 2
- iJk: 3
- Lm:
- nO: 4
- P:
- Q: 5
- R: 6
-`},
- {"json", `{
- "aBcD": 1,
- "eF": {
- "iJk": 3,
- "Lm": {
- "P": {
- "Q": 5,
- "R": 6
- },
- "nO": 4
- },
- "gH": 2
- }
-}`},
- {"toml", `aBcD = 1
-[eF]
-gH = 2
-iJk = 3
-[eF.Lm]
-nO = 4
-[eF.Lm.P]
-Q = 5
-R = 6
-`},
- } {
- doTestCaseInsensitive(t, config.typ, config.content)
- }
-}
-
-func TestCaseInsensitiveSet(t *testing.T) {
- Reset()
- m1 := map[string]interface{}{
- "Foo": 32,
- "Bar": map[interface{}]interface {
- }{
- "ABc": "A",
- "cDE": "B"},
- }
-
- m2 := map[string]interface{}{
- "Foo": 52,
- "Bar": map[interface{}]interface {
- }{
- "bCd": "A",
- "eFG": "B"},
- }
-
- Set("Given1", m1)
- Set("Number1", 42)
-
- SetDefault("Given2", m2)
- SetDefault("Number2", 52)
-
- // Verify SetDefault
- if v := Get("number2"); v != 52 {
- t.Fatalf("Expected 52 got %q", v)
- }
-
- if v := Get("given2.foo"); v != 52 {
- t.Fatalf("Expected 52 got %q", v)
- }
-
- if v := Get("given2.bar.bcd"); v != "A" {
- t.Fatalf("Expected A got %q", v)
- }
-
- if _, ok := m2["Foo"]; !ok {
- t.Fatal("Input map changed")
- }
-
- // Verify Set
- if v := Get("number1"); v != 42 {
- t.Fatalf("Expected 42 got %q", v)
- }
-
- if v := Get("given1.foo"); v != 32 {
- t.Fatalf("Expected 32 got %q", v)
- }
-
- if v := Get("given1.bar.abc"); v != "A" {
- t.Fatalf("Expected A got %q", v)
- }
-
- if _, ok := m1["Foo"]; !ok {
- t.Fatal("Input map changed")
- }
-}
-
-func TestParseNested(t *testing.T) {
- type duration struct {
- Delay time.Duration
- }
-
- type item struct {
- Name string
- Delay time.Duration
- Nested duration
- }
-
- config := `[[parent]]
- delay="100ms"
- [parent.nested]
- delay="200ms"
-`
- initConfig("toml", config)
-
- var items []item
- err := v.UnmarshalKey("parent", &items)
- if err != nil {
- t.Fatalf("unable to decode into struct, %v", err)
- }
-
- assert.Equal(t, 1, len(items))
- assert.Equal(t, 100*time.Millisecond, items[0].Delay)
- assert.Equal(t, 200*time.Millisecond, items[0].Nested.Delay)
-}
-
-func doTestCaseInsensitive(t *testing.T, typ, config string) {
- initConfig(typ, config)
- Set("RfD", true)
- assert.Equal(t, true, Get("rfd"))
- assert.Equal(t, true, Get("rFD"))
- assert.Equal(t, 1, cast.ToInt(Get("abcd")))
- assert.Equal(t, 1, cast.ToInt(Get("Abcd")))
- assert.Equal(t, 2, cast.ToInt(Get("ef.gh")))
- assert.Equal(t, 3, cast.ToInt(Get("ef.ijk")))
- assert.Equal(t, 4, cast.ToInt(Get("ef.lm.no")))
- assert.Equal(t, 5, cast.ToInt(Get("ef.lm.p.q")))
-
-}
-
-func BenchmarkGetBool(b *testing.B) {
- key := "BenchmarkGetBool"
- v = New()
- v.Set(key, true)
-
- for i := 0; i < b.N; i++ {
- if !v.GetBool(key) {
- b.Fatal("GetBool returned false")
- }
- }
-}
-
-func BenchmarkGet(b *testing.B) {
- key := "BenchmarkGet"
- v = New()
- v.Set(key, true)
-
- for i := 0; i < b.N; i++ {
- if !v.Get(key).(bool) {
- b.Fatal("Get returned false")
- }
- }
-}
-
-// This is the "perfect result" for the above.
-func BenchmarkGetBoolFromMap(b *testing.B) {
- m := make(map[string]bool)
- key := "BenchmarkGetBool"
- m[key] = true
-
- for i := 0; i < b.N; i++ {
- if !m[key] {
- b.Fatal("Map value was false")
- }
- }
-}