cmd/viewcore/vendor: remove files and packages for tests
Change-Id: I63eddc16cc3d3e248e933dc23034a5ebf9e69e1a
Reviewed-on: https://go-review.googlesource.com/121435
Reviewed-by: Heschi Kreinick <heschi@google.com>
Run-TryBot: Heschi Kreinick <heschi@google.com>
TryBot-Result: Gobot Gobot <gobot@golang.org>
diff --git a/cmd/viewcore/vendor/README b/cmd/viewcore/vendor/README
index 0c0ddc8..d430a13 100644
--- a/cmd/viewcore/vendor/README
+++ b/cmd/viewcore/vendor/README
@@ -8,6 +8,7 @@
$ cd `go env GOPATH`/src/golang.org/x/debug/cmd/viewcore
$ govendor fetch github.com/spf13/cobra
+ $ govendor fetch github.com/chzyer/readline
Check the updated vendor.json file carefully and
create a review request.
diff --git a/cmd/viewcore/vendor/github.com/chzyer/logex/LICENSE b/cmd/viewcore/vendor/github.com/chzyer/logex/LICENSE
deleted file mode 100644
index c9afab3..0000000
--- a/cmd/viewcore/vendor/github.com/chzyer/logex/LICENSE
+++ /dev/null
@@ -1,22 +0,0 @@
-The MIT License (MIT)
-
-Copyright (c) 2015 Chzyer
-
-Permission is hereby granted, free of charge, to any person obtaining a copy
-of this software and associated documentation files (the "Software"), to deal
-in the Software without restriction, including without limitation the rights
-to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-copies of the Software, and to permit persons to whom the Software is
-furnished to do so, subject to the following conditions:
-
-The above copyright notice and this permission notice shall be included in all
-copies or substantial portions of the Software.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
-SOFTWARE.
-
diff --git a/cmd/viewcore/vendor/github.com/chzyer/logex/Makefile b/cmd/viewcore/vendor/github.com/chzyer/logex/Makefile
deleted file mode 100644
index 8dc10bf..0000000
--- a/cmd/viewcore/vendor/github.com/chzyer/logex/Makefile
+++ /dev/null
@@ -1,5 +0,0 @@
-test:
- go test -v ./...
-
-install:
- go install ./...
diff --git a/cmd/viewcore/vendor/github.com/chzyer/logex/README.md b/cmd/viewcore/vendor/github.com/chzyer/logex/README.md
deleted file mode 100644
index 668d0eb..0000000
--- a/cmd/viewcore/vendor/github.com/chzyer/logex/README.md
+++ /dev/null
@@ -1,133 +0,0 @@
-Logex
-=======
-[![Build Status](https://travis-ci.org/chzyer/logex.svg?branch=master)](https://travis-ci.org/chzyer/logex)
-[![GoDoc](https://godoc.org/gopkg.in/logex.v1?status.svg)](https://godoc.org/gopkg.in/logex.v1)
-[![Join the chat at https://gitter.im/go-logex/logex](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/go-logex/logex?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
-
-An golang log lib, supports tracing and level, wrap by standard log lib
-
-How To Get
-=======
-shell
-```
-go get gopkg.in/logex.v1
-```
-
-source code
-```{go}
-import "gopkg.in/logex.v1" // package name is logex
-
-func main() {
- logex.Info("Hello!")
-}
-```
-
-Level
-=======
-
-```{go}
-import "gopkg.in/logex.v1"
-
-func main() {
- logex.Println("")
- logex.Debug("debug staff.") // Only show if has an "DEBUG" named env variable(whatever value).
- logex.Info("info")
- logex.Warn("")
- logex.Fatal("") // also trigger exec "os.Exit(1)"
- logex.Error(err) // print error
- logex.Struct(obj) // print objs follow such layout "%T(%+v)"
- logex.Pretty(obj) // print objs as JSON-style, more readable and hide non-publish properties, just JSON
-}
-```
-
-Extendability
-======
-
-source code
-```{go}
-type MyStruct struct {
- BiteMe bool
-}
-```
-
-may change to
-
-```{go}
-type MyStruct struct {
- BiteMe bool
- logex.Logger // just this
-}
-
-func main() {
- ms := new(MyStruct)
- ms.Info("woo!")
-}
-```
-
-Runtime Tracing
-======
-All log will attach theirs stack info. Stack Info will shown by an layout, `{packageName}.{FuncName}:{FileName}:{FileLine}`
-
-```{go}
-package main
-
-import "gopkg.in/logex.v1"
-
-func test() {
- logex.Pretty("hello")
-}
-
-func main() {
- test()
-}
-```
-
-response
-```
-2014/10/10 15:17:14 [main.test:testlog.go:6][PRETTY] "hello"
-```
-
-Error Tracing
-======
-You can trace an error if you want.
-
-```{go}
-package main
-
-import (
- "gopkg.in/logex.v1"
- "os"
-)
-
-func openfile() (*os.File, error) {
- f, err := os.Open("xxx")
- if err != nil {
- err = logex.Trace(err)
- }
- return f, err
-}
-
-func test() error {
- f, err := openfile()
- if err != nil {
- return logex.Trace(err)
- }
- f.Close()
- return nil
-}
-
-func main() {
- err := test()
- if err != nil {
- logex.Error(err)
- return
- }
- logex.Info("test success")
-}
-```
-
-
-response
-```
-2014/10/10 15:22:29 [main.main:testlog.go:28][ERROR] [main.openfile:11;main.test:19] open xxx: no such file or directory
-```
diff --git a/cmd/viewcore/vendor/github.com/chzyer/logex/err.go b/cmd/viewcore/vendor/github.com/chzyer/logex/err.go
deleted file mode 100644
index 8bd69c7..0000000
--- a/cmd/viewcore/vendor/github.com/chzyer/logex/err.go
+++ /dev/null
@@ -1,182 +0,0 @@
-package logex
-
-import (
- "bytes"
- "errors"
- "fmt"
- "path"
- "runtime"
- "strconv"
- "strings"
-)
-
-func Define(info string) *traceError {
- return &traceError{
- error: errors.New(info),
- }
-}
-
-func NewError(info ...interface{}) *traceError {
- return TraceEx(1, errors.New(sprint(info)))
-}
-
-func NewErrorf(format string, info ...interface{}) *traceError {
- return TraceEx(1, errors.New(sprintf(format, info)))
-}
-
-func EqualAny(e error, es []error) bool {
- for i := 0; i < len(es); i++ {
- if Equal(e, es[i]) {
- return true
- }
- }
- return false
-}
-
-func Equal(e1, e2 error) bool {
- if e, ok := e1.(*traceError); ok {
- e1 = e.error
- }
- if e, ok := e2.(*traceError); ok {
- e2 = e.error
- }
- return e1 == e2
-}
-
-type traceError struct {
- error
- format []interface{}
- stack []string
- code *int
-}
-
-func (t *traceError) SetCode(code int) *traceError {
- if t.stack == nil {
- t = TraceEx(1, t)
- }
- t.code = &code
- return t
-}
-
-func (t *traceError) GetCode() int {
- if t.code == nil {
- return 500
- }
- return *t.code
-}
-
-func (t *traceError) Error() string {
- if t == nil {
- return "<nil>"
- }
- if t.format == nil {
- if t.error == nil {
- panic(t.stack)
- }
- return t.error.Error()
- }
- return fmt.Sprintf(t.error.Error(), t.format...)
-}
-
-func (t *traceError) Trace(info ...interface{}) *traceError {
- return TraceEx(1, t, info...)
-}
-
-func (t *traceError) Follow(err error) *traceError {
- if t == nil {
- return nil
- }
- if te, ok := err.(*traceError); ok {
- if len(te.stack) > 0 {
- te.stack[len(te.stack)-1] += ":" + err.Error()
- }
- t.stack = append(te.stack, t.stack...)
- }
- return t
-}
-
-func (t *traceError) Format(obj ...interface{}) *traceError {
- if t.stack == nil {
- t = TraceEx(1, t)
- }
- t.format = obj
- return t
-}
-
-func (t *traceError) StackError() string {
- if t == nil {
- return t.Error()
- }
- if len(t.stack) == 0 {
- return t.Error()
- }
- return fmt.Sprintf("[%s] %s", strings.Join(t.stack, ";"), t.Error())
-}
-
-func Tracefmt(layout string, objs ...interface{}) error {
- var teInfo *traceError
- for idx, obj := range objs {
- if te, ok := obj.(*traceError); ok {
- teInfo = te
- objs[idx] = te.Error()
- }
- }
- return &traceError{
- error: fmt.Errorf(layout, objs...),
- format: teInfo.format,
- stack: teInfo.stack,
- code: teInfo.code,
- }
-}
-
-func Tracef(err error, obj ...interface{}) *traceError {
- e := TraceEx(1, err).Format(obj...)
- return e
-}
-
-// set runtime info to error
-func TraceError(err error, info ...interface{}) *traceError {
- return TraceEx(1, err, info...)
-}
-
-func Trace(err error, info ...interface{}) error {
- if err == nil {
- return nil
- }
- return TraceEx(1, err, info...)
-}
-
-func joinInterface(info []interface{}, ch string) string {
- ret := bytes.NewBuffer(make([]byte, 0, 512))
- for idx, o := range info {
- if idx > 0 {
- ret.WriteString(ch)
- }
- ret.WriteString(fmt.Sprint(o))
- }
- return ret.String()
-}
-
-func TraceEx(depth int, err error, info ...interface{}) *traceError {
- if err == nil {
- return nil
- }
- pc, _, line, _ := runtime.Caller(1 + depth)
- name := runtime.FuncForPC(pc).Name()
- name = path.Base(name)
- stack := name + ":" + strconv.Itoa(line)
- if len(info) > 0 {
- stack += "(" + joinInterface(info, ",") + ")"
- }
- if te, ok := err.(*traceError); ok {
- if te.stack == nil { // define
- return &traceError{
- error: te.error,
- stack: []string{stack},
- }
- }
- te.stack = append(te.stack, stack)
- return te
- }
- return &traceError{err, nil, []string{stack}, nil}
-}
diff --git a/cmd/viewcore/vendor/github.com/chzyer/logex/err_test.go b/cmd/viewcore/vendor/github.com/chzyer/logex/err_test.go
deleted file mode 100644
index 376a08a..0000000
--- a/cmd/viewcore/vendor/github.com/chzyer/logex/err_test.go
+++ /dev/null
@@ -1,31 +0,0 @@
-package logex
-
-import (
- "os"
- "strings"
- "testing"
-)
-
-func b() error {
- _, err := os.Open("dflkjasldfkas")
- return Trace(err)
-}
-
-func a() error {
- return Trace(b())
-}
-
-func TestError(t *testing.T) {
- te := TraceError(a())
- errInfo := te.StackError()
- prefixes := []string{"logex%2ev1", "logex"}
- for _, p := range prefixes {
- if strings.Contains(errInfo, p+".b:11") &&
- strings.Contains(errInfo, p+".a:15") &&
- strings.Contains(errInfo, p+".TestError:19") {
- return
- }
- }
-
- t.Error("fail", te.StackError())
-}
diff --git a/cmd/viewcore/vendor/github.com/chzyer/logex/logex.go b/cmd/viewcore/vendor/github.com/chzyer/logex/logex.go
deleted file mode 100644
index 9ab5079..0000000
--- a/cmd/viewcore/vendor/github.com/chzyer/logex/logex.go
+++ /dev/null
@@ -1,287 +0,0 @@
-package logex
-
-import (
- "encoding/json"
- "fmt"
- "io"
- goLog "log"
- "os"
- "path"
- "runtime"
- "strconv"
- "strings"
-)
-
-var DebugLevel = 1
-
-type Logger struct {
- depth int
- reqid string
- Logger *goLog.Logger
-}
-
-func NewLogger(l int) *Logger {
- return &Logger{l, "", goLogStd}
-}
-
-func NewLoggerEx(w io.Writer) *Logger {
- return &Logger{0, "", NewGoLog(w)}
-}
-
-func NewGoLog(w io.Writer) *goLog.Logger {
- return goLog.New(w, "", goLog.LstdFlags)
-}
-
-var goLogStd = goLog.New(os.Stderr, "", goLog.LstdFlags)
-var std = NewLogger(1)
-var ShowCode = true
-var (
- Println = std.Println
- Infof = std.Infof
- Info = std.Info
- Debug = std.Debug
- Debugf = std.Debugf
- Error = std.Error
- Errorf = std.Errorf
- Warn = std.Warn
- PrintStack = std.PrintStack
- Stack = std.Stack
- Panic = std.Panic
- Fatal = std.Fatal
- Struct = std.Struct
- Pretty = std.Pretty
- Todo = std.Todo
-)
-
-func SetStd(l *Logger) {
- std = l
- Println = std.Println
- Infof = std.Infof
- Info = std.Info
- Debug = std.Debug
- Error = std.Error
- Warn = std.Warn
- PrintStack = std.PrintStack
- Stack = std.Stack
- Panic = std.Panic
- Fatal = std.Fatal
- Struct = std.Struct
- Pretty = std.Pretty
- Todo = std.Todo
-}
-
-var (
- INFO = "[INFO] "
- ERROR = "[ERROR] "
- PANIC = "[PANIC] "
- DEBUG = "[DEBUG] "
- WARN = "[WARN] "
- FATAL = "[FATAL] "
- STRUCT = "[STRUCT] "
- PRETTY = "[PRETTY] "
- TODO = "[TODO] "
-)
-
-func color(col, s string) string {
- if col == "" {
- return s
- }
- return "\x1b[0;" + col + "m" + s + "\x1b[0m"
-}
-
-func init() {
- if os.Getenv("DEBUG") != "" {
- DebugLevel = 0
- ERROR = color("32", ERROR)
- }
-}
-
-func DownLevel(i int) Logger {
- return std.DownLevel(i - 1)
-}
-
-// decide to show which level's stack
-func (l Logger) DownLevel(i int) Logger {
- return Logger{l.depth + i, l.reqid, l.Logger}
-}
-
-// output objects to json format
-func (l Logger) Pretty(os ...interface{}) {
- content := ""
- for i := range os {
- if ret, err := json.MarshalIndent(os[i], "", "\t"); err == nil {
- content += string(ret) + "\n"
- }
- }
- l.Output(2, PRETTY+content)
-}
-
-// just print
-func (l Logger) Print(o ...interface{}) {
- l.Output(2, sprint(o))
-}
-
-// just print by format
-func (l Logger) Printf(layout string, o ...interface{}) {
- l.Output(2, sprintf(layout, o))
-}
-
-// just println
-func (l Logger) Println(o ...interface{}) {
- l.Output(2, " "+sprint(o))
-}
-
-func (l Logger) Info(o ...interface{}) {
- if DebugLevel > 1 {
- return
- }
-
- l.Output(2, INFO+sprint(o))
-}
-func (l Logger) Infof(f string, o ...interface{}) {
- if DebugLevel > 1 {
- return
- }
-
- l.Output(2, INFO+sprintf(f, o))
-}
-
-func (l Logger) Debug(o ...interface{}) {
- if DebugLevel > 0 {
- return
- }
- l.Output(2, DEBUG+sprint(o))
-}
-
-func (l Logger) Debugf(f string, o ...interface{}) {
- if DebugLevel > 0 {
- return
- }
- l.Output(2, DEBUG+sprintf(f, o))
-}
-
-func (l Logger) Todo(o ...interface{}) {
- l.Output(2, TODO+sprint(o))
-}
-
-func (l Logger) Error(o ...interface{}) {
- l.Output(2, ERROR+sprint(o))
-}
-
-func (l Logger) Errorf(f string, o ...interface{}) {
- l.Output(2, ERROR+sprintf(f, o))
-}
-
-func (l Logger) Warn(o ...interface{}) {
- l.Output(2, WARN+sprint(o))
-}
-func (l Logger) Warnf(f string, o ...interface{}) {
- l.Output(2, WARN+sprintf(f, o))
-}
-
-func (l Logger) Panic(o ...interface{}) {
- l.Output(2, PANIC+sprint(o))
- panic(o)
-}
-func (l Logger) Panicf(f string, o ...interface{}) {
- info := sprintf(f, o)
- l.Output(2, PANIC+info)
- panic(info)
-}
-
-func (l Logger) Fatal(o ...interface{}) {
- l.Output(2, FATAL+sprint(o))
- os.Exit(1)
-}
-
-func (l Logger) Fatalf(f string, o ...interface{}) {
- l.Output(2, FATAL+sprintf(f, o))
- os.Exit(1)
-}
-
-func (l Logger) Struct(o ...interface{}) {
- items := make([]interface{}, 0, len(o)*2)
- for _, item := range o {
- items = append(items, item, item)
- }
- layout := strings.Repeat(", %T(%+v)", len(o))
- if len(layout) > 0 {
- layout = layout[2:]
- }
- l.Output(2, STRUCT+sprintf(layout, items))
-}
-
-func (l Logger) PrintStack() {
- Info(string(l.Stack()))
-}
-
-func (l Logger) Stack() []byte {
- a := make([]byte, 1024*1024)
- n := runtime.Stack(a, true)
- return a[:n]
-}
-
-func (l Logger) Output(calldepth int, s string) error {
- calldepth += l.depth + 1
- if l.Logger == nil {
- l.Logger = goLogStd
- }
- return l.Logger.Output(calldepth, l.makePrefix(calldepth)+s)
-}
-
-func (l Logger) makePrefix(calldepth int) string {
- if !ShowCode {
- return ""
- }
- pc, f, line, _ := runtime.Caller(calldepth)
- name := runtime.FuncForPC(pc).Name()
- name = path.Base(name) // only use package.funcname
- f = path.Base(f) // only use filename
-
- tags := make([]string, 0, 3)
-
- pos := name + ":" + f + ":" + strconv.Itoa(line)
- tags = append(tags, pos)
- if l.reqid != "" {
- tags = append(tags, l.reqid)
- }
- return "[" + strings.Join(tags, "][") + "]"
-}
-
-func Sprint(o ...interface{}) string {
- return sprint(o)
-}
-
-func Sprintf(f string, o ...interface{}) string {
- return sprintf(f, o)
-}
-
-func sprint(o []interface{}) string {
- decodeTraceError(o)
- return joinInterface(o, " ")
-}
-func sprintf(f string, o []interface{}) string {
- decodeTraceError(o)
- return fmt.Sprintf(f, o...)
-}
-
-func DecodeError(e error) string {
- if e == nil {
- return ""
- }
- if e1, ok := e.(*traceError); ok {
- return e1.StackError()
- }
- return e.Error()
-}
-
-func decodeTraceError(o []interface{}) {
- if !ShowCode {
- return
- }
- for idx, obj := range o {
- if te, ok := obj.(*traceError); ok {
- o[idx] = te.StackError()
- }
- }
-}
diff --git a/cmd/viewcore/vendor/github.com/chzyer/logex/logex_test.go b/cmd/viewcore/vendor/github.com/chzyer/logex/logex_test.go
deleted file mode 100644
index e6027f2..0000000
--- a/cmd/viewcore/vendor/github.com/chzyer/logex/logex_test.go
+++ /dev/null
@@ -1,62 +0,0 @@
-package logex
-
-import (
- "bytes"
- "io"
- "strings"
- "testing"
-)
-
-func (s *S) hello() {
- s.Warn("warn in hello")
-}
-
-func log(buf io.Writer, s string) {
- Logger{Logger: NewGoLog(buf)}.Output(2, s)
-}
-
-func test(buf io.Writer) {
- log(buf, "aa")
- Info("b")
- NewLoggerEx(buf).Info("c")
- Error("ec")
- s.hello()
- Struct(&s, 1, "", false)
-}
-
-// -------------------------------------------------------------------
-
-type S struct {
- Logger
-}
-
-var s = S{}
-
-func TestLogex(t *testing.T) {
- buf := bytes.NewBuffer(nil)
- logger := NewLoggerEx(buf)
- logger.depth = 1
- goLogStd = logger.Logger
- SetStd(logger)
-
- test(buf)
- ret := buf.String()
-
- println("--------\n", ret)
-
- except := []string{
- ".test:logex_test.go:19]aa",
- ".test:logex_test.go:20][INFO] b",
- ".test:logex_test.go:21][INFO] c",
- ".test:logex_test.go:22][ERROR] ec",
- ".(*S).hello:logex_test.go:11][WARN] warn in hello",
- }
-
- for _, e := range except {
- idx := strings.Index(ret, e)
- if idx < 0 {
- t.Fatal("except", e, "not found")
- }
- ret = ret[idx+len(e):]
- }
-}
diff --git a/cmd/viewcore/vendor/github.com/chzyer/readline/complete_segment_test.go b/cmd/viewcore/vendor/github.com/chzyer/readline/complete_segment_test.go
deleted file mode 100644
index 73a828a..0000000
--- a/cmd/viewcore/vendor/github.com/chzyer/readline/complete_segment_test.go
+++ /dev/null
@@ -1,167 +0,0 @@
-package readline
-
-import (
- "fmt"
- "testing"
-
- "github.com/chzyer/test"
-)
-
-func rs(s [][]rune) []string {
- ret := make([]string, len(s))
- for idx, ss := range s {
- ret[idx] = string(ss)
- }
- return ret
-}
-
-func sr(s ...string) [][]rune {
- ret := make([][]rune, len(s))
- for idx, ss := range s {
- ret[idx] = []rune(ss)
- }
- return ret
-}
-
-func TestRetSegment(t *testing.T) {
- defer test.New(t)
- // a
- // |- a1
- // |--- a11
- // |--- a12
- // |- a2
- // |--- a21
- // b
- // add
- // adddomain
- ret := []struct {
- Segments [][]rune
- Cands [][]rune
- idx int
- Ret [][]rune
- pos int
- }{
- {sr(""), sr("a", "b", "add", "adddomain"), 0, sr("a", "b", "add", "adddomain"), 0},
- {sr("a"), sr("a", "add", "adddomain"), 1, sr("", "dd", "dddomain"), 1},
- {sr("a", ""), sr("a1", "a2"), 0, sr("a1", "a2"), 0},
- {sr("a", "a"), sr("a1", "a2"), 1, sr("1", "2"), 1},
- {sr("a", "a1"), sr("a1"), 2, sr(""), 2},
- {sr("add"), sr("add", "adddomain"), 2, sr("", "domain"), 2},
- }
- for idx, r := range ret {
- ret, pos := RetSegment(r.Segments, r.Cands, r.idx)
- test.Equal(ret, r.Ret, fmt.Errorf("%v", idx))
- test.Equal(pos, r.pos, fmt.Errorf("%v", idx))
- }
-}
-
-func TestSplitSegment(t *testing.T) {
- defer test.New(t)
- // a
- // |- a1
- // |--- a11
- // |--- a12
- // |- a2
- // |--- a21
- // b
- ret := []struct {
- Line string
- Pos int
- Segments [][]rune
- Idx int
- }{
- {"", 0, sr(""), 0},
- {"a", 1, sr("a"), 1},
- {"a ", 2, sr("a", ""), 0},
- {"a a", 3, sr("a", "a"), 1},
- {"a a1", 4, sr("a", "a1"), 2},
- {"a a1 ", 5, sr("a", "a1", ""), 0},
- }
-
- for i, r := range ret {
- ret, idx := SplitSegment([]rune(r.Line), r.Pos)
- test.Equal(rs(ret), rs(r.Segments), fmt.Errorf("%v", i))
- test.Equal(idx, r.Idx, fmt.Errorf("%v", i))
- }
-}
-
-type Tree struct {
- Name string
- Children []Tree
-}
-
-func TestSegmentCompleter(t *testing.T) {
- defer test.New(t)
-
- tree := Tree{"", []Tree{
- {"a", []Tree{
- {"a1", []Tree{
- {"a11", nil},
- {"a12", nil},
- }},
- {"a2", []Tree{
- {"a21", nil},
- }},
- }},
- {"b", nil},
- {"route", []Tree{
- {"add", nil},
- {"adddomain", nil},
- }},
- }}
- s := SegmentFunc(func(ret [][]rune, n int) [][]rune {
- tree := tree
- main:
- for level := 0; level < len(ret)-1; {
- name := string(ret[level])
- for _, t := range tree.Children {
- if t.Name == name {
- tree = t
- level++
- continue main
- }
- }
- }
-
- ret = make([][]rune, len(tree.Children))
- for idx, r := range tree.Children {
- ret[idx] = []rune(r.Name)
- }
- return ret
- })
-
- // a
- // |- a1
- // |--- a11
- // |--- a12
- // |- a2
- // |--- a21
- // b
- ret := []struct {
- Line string
- Pos int
- Ret [][]rune
- Share int
- }{
- {"", 0, sr("a", "b", "route"), 0},
- {"a", 1, sr(""), 1},
- {"a ", 2, sr("a1", "a2"), 0},
- {"a a", 3, sr("1", "2"), 1},
- {"a a1", 4, sr(""), 2},
- {"a a1 ", 5, sr("a11", "a12"), 0},
- {"a a1 a", 6, sr("11", "12"), 1},
- {"a a1 a1", 7, sr("1", "2"), 2},
- {"a a1 a11", 8, sr(""), 3},
- {"route add", 9, sr("", "domain"), 3},
- }
- for _, r := range ret {
- for idx, rr := range r.Ret {
- r.Ret[idx] = append(rr, ' ')
- }
- }
- for i, r := range ret {
- newLine, length := s.Do([]rune(r.Line), r.Pos)
- test.Equal(rs(newLine), rs(r.Ret), fmt.Errorf("%v", i))
- test.Equal(length, r.Share, fmt.Errorf("%v", i))
- }
-}
diff --git a/cmd/viewcore/vendor/github.com/chzyer/readline/readline_test.go b/cmd/viewcore/vendor/github.com/chzyer/readline/readline_test.go
deleted file mode 100644
index 34a5a3b..0000000
--- a/cmd/viewcore/vendor/github.com/chzyer/readline/readline_test.go
+++ /dev/null
@@ -1,27 +0,0 @@
-package readline
-
-import (
- "testing"
- "time"
-)
-
-func TestRace(t *testing.T) {
- rl, err := NewEx(&Config{})
- if err != nil {
- t.Fatal(err)
- return
- }
-
- go func() {
- for range time.Tick(time.Millisecond) {
- rl.SetPrompt("hello")
- }
- }()
-
- go func() {
- time.Sleep(100 * time.Millisecond)
- rl.Close()
- }()
-
- rl.Readline()
-}
diff --git a/cmd/viewcore/vendor/github.com/chzyer/readline/runes_test.go b/cmd/viewcore/vendor/github.com/chzyer/readline/runes_test.go
deleted file mode 100644
index 9c56d79..0000000
--- a/cmd/viewcore/vendor/github.com/chzyer/readline/runes_test.go
+++ /dev/null
@@ -1,68 +0,0 @@
-package readline
-
-import (
- "reflect"
- "testing"
-)
-
-type twidth struct {
- r []rune
- length int
-}
-
-func TestRuneWidth(t *testing.T) {
- rs := []twidth{
- {[]rune("☭"), 1},
- {[]rune("a"), 1},
- {[]rune("你"), 2},
- {runes.ColorFilter([]rune("☭\033[13;1m你")), 3},
- }
- for _, r := range rs {
- if w := runes.WidthAll(r.r); w != r.length {
- t.Fatal("result not expect", r.r, r.length, w)
- }
- }
-}
-
-type tagg struct {
- r [][]rune
- e [][]rune
- length int
-}
-
-func TestAggRunes(t *testing.T) {
- rs := []tagg{
- {
- [][]rune{[]rune("ab"), []rune("a"), []rune("abc")},
- [][]rune{[]rune("b"), []rune(""), []rune("bc")},
- 1,
- },
- {
- [][]rune{[]rune("addb"), []rune("ajkajsdf"), []rune("aasdfkc")},
- [][]rune{[]rune("ddb"), []rune("jkajsdf"), []rune("asdfkc")},
- 1,
- },
- {
- [][]rune{[]rune("ddb"), []rune("ajksdf"), []rune("aasdfkc")},
- [][]rune{[]rune("ddb"), []rune("ajksdf"), []rune("aasdfkc")},
- 0,
- },
- {
- [][]rune{[]rune("ddb"), []rune("ddajksdf"), []rune("ddaasdfkc")},
- [][]rune{[]rune("b"), []rune("ajksdf"), []rune("aasdfkc")},
- 2,
- },
- }
- for _, r := range rs {
- same, off := runes.Aggregate(r.r)
- if off != r.length {
- t.Fatal("result not expect", off)
- }
- if len(same) != off {
- t.Fatal("result not expect", same)
- }
- if !reflect.DeepEqual(r.r, r.e) {
- t.Fatal("result not expect")
- }
- }
-}
diff --git a/cmd/viewcore/vendor/github.com/chzyer/readline/utils_test.go b/cmd/viewcore/vendor/github.com/chzyer/readline/utils_test.go
deleted file mode 100644
index 96037df..0000000
--- a/cmd/viewcore/vendor/github.com/chzyer/readline/utils_test.go
+++ /dev/null
@@ -1 +0,0 @@
-package readline
diff --git a/cmd/viewcore/vendor/github.com/chzyer/test/LICENSE b/cmd/viewcore/vendor/github.com/chzyer/test/LICENSE
deleted file mode 100644
index 96c44aa..0000000
--- a/cmd/viewcore/vendor/github.com/chzyer/test/LICENSE
+++ /dev/null
@@ -1,21 +0,0 @@
-The MIT License (MIT)
-
-Copyright (c) 2016 chzyer
-
-Permission is hereby granted, free of charge, to any person obtaining a copy
-of this software and associated documentation files (the "Software"), to deal
-in the Software without restriction, including without limitation the rights
-to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-copies of the Software, and to permit persons to whom the Software is
-furnished to do so, subject to the following conditions:
-
-The above copyright notice and this permission notice shall be included in all
-copies or substantial portions of the Software.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
-SOFTWARE.
diff --git a/cmd/viewcore/vendor/github.com/chzyer/test/README.md b/cmd/viewcore/vendor/github.com/chzyer/test/README.md
deleted file mode 100644
index 00bcb6e..0000000
--- a/cmd/viewcore/vendor/github.com/chzyer/test/README.md
+++ /dev/null
@@ -1 +0,0 @@
-# test
\ No newline at end of file
diff --git a/cmd/viewcore/vendor/github.com/chzyer/test/disk.go b/cmd/viewcore/vendor/github.com/chzyer/test/disk.go
deleted file mode 100644
index 417d2f5..0000000
--- a/cmd/viewcore/vendor/github.com/chzyer/test/disk.go
+++ /dev/null
@@ -1,106 +0,0 @@
-package test
-
-import (
- "encoding/hex"
- "io"
-)
-
-type MemDisk struct {
- data [][]byte
- size int64
- woff, roff int
-}
-
-func NewMemDisk() *MemDisk {
- return &MemDisk{}
-}
-
-func (w *MemDisk) Write(b []byte) (int, error) {
- n, err := w.WriteAt(b, int64(w.woff))
- w.woff += n
- return n, err
-}
-
-func (w *MemDisk) getData(off int64) []byte {
- idx := int(off >> 20)
- if idx >= cap(w.data) {
- newdata := make([][]byte, idx+1)
- copy(newdata, w.data)
- w.data = newdata
- }
- if len(w.data[idx]) == 0 {
- w.data[idx] = make([]byte, 1<<20)
- }
-
- return w.data[idx][off&((1<<20)-1):]
-}
-
-func (w *MemDisk) WriteAt(b []byte, off int64) (int, error) {
- n := len(b)
- for len(b) > 0 {
- buf := w.getData(off)
- m := copy(buf, b)
- if off+int64(m) > w.size {
- w.size = off + int64(m)
- }
- b = b[m:]
- off += int64(m)
- }
- return n, nil
-}
-
-func (w *MemDisk) ReadAt(b []byte, off int64) (int, error) {
- byteRead := 0
- for byteRead < len(b) {
- if off >= w.size {
- return 0, io.EOF
- }
- buf := w.getData(off)
- if int64(len(buf))+off > w.size {
- buf = buf[:w.size-off]
- }
- if len(buf) == 0 {
- return byteRead, io.EOF
- }
- n := copy(b[byteRead:], buf)
- off += int64(n)
- byteRead += n
- }
- return byteRead, nil
-}
-
-func (w *MemDisk) Dump() string {
- return hex.Dump(w.getData(0))
-}
-
-func (w *MemDisk) SeekRead(offset int64, whence int) (ret int64) {
- switch whence {
- case 0:
- w.roff += int(offset)
- case 1:
- w.roff = int(offset)
- default:
- }
- return int64(w.roff)
-}
-
-func (w *MemDisk) SeekWrite(offset int64, whence int) (ret int64) {
- switch whence {
- case 0:
- w.woff += int(offset)
- case 1:
- w.woff = int(offset)
- default:
- }
- return int64(w.woff)
-}
-
-func (w *MemDisk) Read(b []byte) (int, error) {
- n, err := w.ReadAt(b, int64(w.roff))
- w.roff += n
- return n, err
-}
-
-func (w *MemDisk) Close() error {
- return nil
-}
diff --git a/cmd/viewcore/vendor/github.com/chzyer/test/disk_test.go b/cmd/viewcore/vendor/github.com/chzyer/test/disk_test.go
deleted file mode 100644
index 3b6988c..0000000
--- a/cmd/viewcore/vendor/github.com/chzyer/test/disk_test.go
+++ /dev/null
@@ -1,20 +0,0 @@
-package test
-
-import (
- "io"
- "testing"
-)
-
-func TestMemDisk(t *testing.T) {
- defer New(t)
- md := NewMemDisk()
- WriteAt(md, []byte("hello"), 4)
- h := make([]byte, 5)
- n, err := md.ReadAt(h, 3)
- Equals(n, 5, err, nil, h, []byte("\x00hell"))
-
- {
- n, err := md.ReadAt(h, 10)
- Equals(n, 0, err, io.EOF)
- }
-}
diff --git a/cmd/viewcore/vendor/github.com/chzyer/test/test.go b/cmd/viewcore/vendor/github.com/chzyer/test/test.go
deleted file mode 100644
index aef573a..0000000
--- a/cmd/viewcore/vendor/github.com/chzyer/test/test.go
+++ /dev/null
@@ -1,420 +0,0 @@
-package test
-
-import (
- "bytes"
- "crypto/rand"
- "fmt"
- "io"
- "io/ioutil"
- "os"
- "path/filepath"
- "reflect"
- "runtime"
- "strconv"
- "strings"
-
- "github.com/chzyer/logex"
-)
-
-var (
- mainRoot = ""
- RootPath = os.TempDir()
- ErrNotExcept = logex.Define("result not expect")
- ErrNotEqual = logex.Define("result not equals")
- ErrRequireNotEqual = logex.Define("result require not equals")
- StrNotSuchFile = "no such file or directory"
-)
-
-func init() {
- println("tmpdir:", RootPath)
-}
-
-type testException struct {
- depth int
- info string
-}
-
-func getMainRoot() string {
- if mainRoot != "" {
- return mainRoot
- }
-
- cwd, err := os.Getwd()
- if err != nil {
- return ""
- }
-
- for len(cwd) > 1 {
- _, err := os.Stat(filepath.Join(cwd, ".git"))
- if err == nil {
- mainRoot = cwd + string([]rune{filepath.Separator})
- break
- }
- cwd = filepath.Dir(cwd)
- }
- return mainRoot
-}
-
-func Skip() {
- panic(nil)
-}
-
-type Failer interface {
- FailNow()
-}
-
-func New(t Failer) {
- err := recover()
- if err == nil {
- return
- }
- te, ok := err.(*testException)
- if !ok {
- panic(err)
- }
-
- _, file, line, _ := runtime.Caller(5 + te.depth)
- if strings.HasPrefix(file, getMainRoot()) {
- file = file[len(getMainRoot()):]
- }
- println(fmt.Sprintf("%s:%d: %s", file, line, te.info))
- t.FailNow()
-}
-
-func getErr(def error, e []error) error {
- if len(e) == 0 {
- return def
- }
- return e[0]
-}
-
-func ReadAt(r io.ReaderAt, b []byte, at int64) {
- n, err := r.ReadAt(b, at)
- if err != nil {
- Panic(0, fmt.Errorf("ReadAt error: %v", err))
- }
- if n != len(b) {
- Panic(0, fmt.Errorf("ReadAt short read: %v, want: %v", n, len(b)))
- }
-}
-
-func ReadAndCheck(r io.Reader, b []byte) {
- buf := make([]byte, len(b))
- Read(r, buf)
- equalBytes(1, buf, b)
-}
-
-func Read(r io.Reader, b []byte) {
- n, err := r.Read(b)
- if err != nil && !logex.Equal(err, io.EOF) {
- Panic(0, fmt.Errorf("Read error: %v", err))
- }
- if n != len(b) {
- Panic(0, fmt.Errorf("Read: %v, want: %v", n, len(b)))
- }
-}
-
-func ReadStringAt(r io.ReaderAt, off int64, s string) {
- buf := make([]byte, len(s))
- n, err := r.ReadAt(buf, off)
- buf = buf[:n]
- if err != nil {
- Panic(0, fmt.Errorf("ReadStringAt: %v", err))
- }
- if string(buf) != s {
- Panic(0, fmt.Errorf(
- "ReadStringAt not match: %v, got: %v",
- strconv.Quote(s),
- strconv.Quote(string(buf)),
- ))
- }
-}
-
-func ReadString(r io.Reader, s string) {
- buf := make([]byte, len(s))
- n, err := r.Read(buf)
- if err != nil && !logex.Equal(err, io.EOF) {
- Panic(0, fmt.Errorf("ReadString: %v, got: %v", strconv.Quote(s), err))
- }
- if n != len(buf) {
- Panic(0, fmt.Errorf("ReadString: %v, got: %v", strconv.Quote(s), n))
- }
- if string(buf) != s {
- Panic(0, fmt.Errorf(
- "ReadString not match: %v, got: %v",
- strconv.Quote(s),
- strconv.Quote(string(buf)),
- ))
- }
-}
-
-func WriteAt(w io.WriterAt, b []byte, at int64) {
- n, err := w.WriteAt(b, at)
- if err != nil {
- Panic(0, err)
- }
- if n != len(b) {
- Panic(0, "short write")
- }
-}
-
-func Write(w io.Writer, b []byte) {
- n, err := w.Write(b)
- if err != nil {
- Panic(0, err)
- }
- if n != len(b) {
- Panic(0, "short write")
- }
-}
-
-func WriteString(w io.Writer, s string) {
- n, err := w.Write([]byte(s))
- if err != nil {
- Panic(0, err)
- }
- if n != len(s) {
- Panic(0, "short write")
- }
-}
-
-func Equals(o ...interface{}) {
- if len(o)%2 != 0 {
- Panic(0, "invalid Equals arguments")
- }
- for i := 0; i < len(o); i += 2 {
- equal(1, o[i], o[i+1], nil)
- }
-}
-
-func NotEqual(a, b interface{}, e ...error) {
- notEqual(1, a, b, e)
-}
-
-func toInt(a interface{}) (int64, bool) {
- switch n := a.(type) {
- case int:
- return int64(n), true
- case int8:
- return int64(n), true
- case int16:
- return int64(n), true
- case int32:
- return int64(n), true
- case int64:
- return int64(n), true
- case uintptr:
- return int64(n), true
- default:
- return -1, false
- }
-}
-
-func MarkLine() {
- r := strings.Repeat("-", 20)
- println(r)
-}
-
-var globalMarkInfo string
-
-func Mark(obj ...interface{}) {
- globalMarkInfo = fmt.Sprint(obj...)
-}
-
-func EqualBytes(got, want []byte) {
- equalBytes(0, got, want)
-}
-
-func equalBytes(n int, got, want []byte) {
- a := got
- b := want
- size := 16
- if len(a) != len(b) {
- Panic(n, fmt.Sprintf("equal bytes, %v != %v", len(a), len(b)))
- }
- if bytes.Equal(a, b) {
- return
- }
-
- for off := 0; off < len(a); off += size {
- end := off + size
- if end > len(a) {
- end = len(a)
- }
- if !bytes.Equal(a[off:end], b[off:end]) {
- Panic(n, fmt.Sprintf(
- "equal [%v]byte in [%v, %v]:\n\tgot: %v\n\twant: %v",
- len(a),
- off, off+size,
- a[off:end], b[off:end],
- ))
- }
- }
-}
-
-func Equal(a, b interface{}, e ...error) {
- if ai, ok := toInt(a); ok {
- if bi, ok := toInt(b); ok {
- equal(1, ai, bi, e)
- return
- }
- }
- equal(1, a, b, e)
-}
-
-func CheckError(e error, s string) {
- if e == nil {
- Panic(0, ErrNotExcept)
- }
- if !strings.Contains(e.Error(), s) {
- Panic(0, fmt.Errorf(
- "want: %s, got %s",
- strconv.Quote(s),
- strconv.Quote(e.Error()),
- ))
- }
-}
-
-func formatMax(o interface{}, max int) string {
- aStr := fmt.Sprint(o)
- if len(aStr) > max {
- aStr = aStr[:max] + " ..."
- }
- return aStr
-}
-
-func notEqual(d int, a, b interface{}, e []error) {
- _, oka := a.(error)
- _, okb := b.(error)
- if oka && okb {
- if logex.Equal(a.(error), b.(error)) {
- Panic(d, fmt.Sprintf("%v: %v",
- getErr(ErrRequireNotEqual, e),
- a,
- ))
- }
- return
- }
- if reflect.DeepEqual(a, b) {
- Panic(d, fmt.Sprintf("%v: (%v, %v)",
- getErr(ErrRequireNotEqual, e),
- formatMax(a, 100),
- formatMax(b, 100),
- ))
- }
-}
-
-func equal(d int, a, b interface{}, e []error) {
- _, oka := a.(error)
- _, okb := b.(error)
- if oka && okb {
- if !logex.Equal(a.(error), b.(error)) {
- Panic(d, fmt.Sprintf("%v: (%v, %v)",
- getErr(ErrNotEqual, e),
- formatMax(a, 100), formatMax(b, 100),
- ))
- }
- return
- }
- if !reflect.DeepEqual(a, b) {
- Panic(d, fmt.Sprintf("%v: (%+v, %+v)", getErr(ErrNotEqual, e), a, b))
- }
-}
-
-func Should(b bool, e ...error) {
- if !b {
- Panic(0, getErr(ErrNotExcept, e))
- }
-}
-
-func NotNil(obj interface{}) {
- if obj == nil {
- Panic(0, "should not nil")
- }
-}
-
-func False(obj bool) {
- if obj {
- Panic(0, "should false")
- }
-}
-
-func True(obj bool) {
- if !obj {
- Panic(0, "should true")
- }
-}
-
-func Nil(obj interface{}) {
- if obj != nil {
- // double check, incase different type with nil value
- if !reflect.ValueOf(obj).IsNil() {
- str := fmt.Sprint(obj)
- if err, ok := obj.(error); ok {
- str = logex.DecodeError(err)
- }
- Panic(0, fmt.Sprintf("should nil: %v", str))
- }
- }
-}
-
-func Panic(depth int, obj interface{}) {
- t := &testException{
- depth: depth,
- }
- if err, ok := obj.(error); ok {
- t.info = logex.DecodeError(err)
- } else {
- t.info = fmt.Sprint(obj)
- }
- if globalMarkInfo != "" {
- t.info = "[info:" + globalMarkInfo + "] " + t.info
- }
- panic(t)
-}
-
-func CleanTmp() {
- os.RemoveAll(root(2))
-}
-
-func TmpFile() (*os.File, error) {
- dir := root(2)
- if err := os.MkdirAll(dir, 0744); err != nil {
- return nil, err
- }
- return ioutil.TempFile(dir, "")
-}
-
-func Root() string {
- p := root(2)
- os.RemoveAll(root(2))
- return p
-}
-
-func root(n int) string {
- pc, _, _, _ := runtime.Caller(n)
- name := runtime.FuncForPC(pc).Name()
- if idx := strings.LastIndex(name, "."); idx > 0 {
- name = name[:idx] + "/" + name[idx+1:]
- }
-
- root := os.Getenv("TEST_ROOT")
- if root == "" {
- root = RootPath
- }
- return filepath.Join(root, name)
-}
-
-func RandBytes(n int) []byte {
- buf := make([]byte, n)
- rand.Read(buf)
- return buf
-}
-
-func SeqBytes(n int) []byte {
- buf := make([]byte, n)
- for idx := range buf {
- buf[idx] = byte(idx)
- }
- return buf
-}
diff --git a/cmd/viewcore/vendor/github.com/spf13/cobra/args_test.go b/cmd/viewcore/vendor/github.com/spf13/cobra/args_test.go
deleted file mode 100644
index d797b6f..0000000
--- a/cmd/viewcore/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/cmd/viewcore/vendor/github.com/spf13/cobra/bash_completions.md b/cmd/viewcore/vendor/github.com/spf13/cobra/bash_completions.md
index e79d476..49d0680 100644
--- a/cmd/viewcore/vendor/github.com/spf13/cobra/bash_completions.md
+++ b/cmd/viewcore/vendor/github.com/spf13/cobra/bash_completions.md
@@ -1,5 +1,40 @@
# Generating Bash Completions For Your Own cobra.Command
+If you are using the generator you can create a completion command by running
+
+```bash
+cobra add completion
+```
+
+Update the help text show how to install the bash_completion Linux show here [Kubectl docs show mac options](https://kubernetes.io/docs/tasks/tools/install-kubectl/#enabling-shell-autocompletion)
+
+Writing the shell script to stdout allows the most flexible use.
+
+```go
+// completionCmd represents the completion command
+var completionCmd = &cobra.Command{
+ Use: "completion",
+ Short: "Generates bash completion scripts",
+ Long: `To load completion run
+
+. <(bitbucket completion)
+
+To configure your bash shell to load completions for each session add to your bashrc
+
+# ~/.bashrc or ~/.profile
+. <(bitbucket completion)
+`,
+ Run: func(cmd *cobra.Command, args []string) {
+ rootCmd.GenBashCompletion(os.Stdout);
+ },
+}
+```
+
+**Note:** The cobra generator may include messages printed to stdout for example if the config file is loaded, this will break the auto complete script
+
+
+## Example from kubectl
+
Generating bash completions from a cobra command is incredibly easy. An actual program which does so for the kubernetes kubectl binary is as follows:
```go
diff --git a/cmd/viewcore/vendor/github.com/spf13/cobra/bash_completions_test.go b/cmd/viewcore/vendor/github.com/spf13/cobra/bash_completions_test.go
deleted file mode 100644
index 859f1ac..0000000
--- a/cmd/viewcore/vendor/github.com/spf13/cobra/bash_completions_test.go
+++ /dev/null
@@ -1,217 +0,0 @@
-package cobra
-
-import (
- "bytes"
- "fmt"
- "os"
- "os/exec"
- "regexp"
- "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 checkRegex(t *testing.T, found, pattern string) {
- matched, err := regexp.MatchString(pattern, found)
- if err != nil {
- t.Errorf("Error thrown performing MatchString: \n %s\n", err)
- }
- if !matched {
- t.Errorf("Expecting to match: \n %q\nGot:\n %q\n", pattern, 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,
- }
-
- echoCmd.Flags().String("filename", "", "Enter a filename")
- echoCmd.MarkFlagFilename("filename", "json", "yaml", "yml")
- echoCmd.Flags().String("config", "", "config to use (located in /config/PROFILE/)")
- echoCmd.Flags().SetAnnotation("config", BashCompSubdirsInDir, []string{"config"})
-
- 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 filename extension flags in a subcommand
- checkRegex(t, output, fmt.Sprintf(`_root_echo\(\)\n{[^}]*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()))
- // check for subdirs_in_dir flags in a subcommand
- checkRegex(t, output, fmt.Sprintf(`_root_echo\(\)\n{[^}]*flags_completion\+=\("__%s_handle_subdirs_in_dir_flag config"\)`, 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/cmd/viewcore/vendor/github.com/spf13/cobra/cobra_test.go b/cmd/viewcore/vendor/github.com/spf13/cobra/cobra_test.go
deleted file mode 100644
index 0d1755b..0000000
--- a/cmd/viewcore/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/cmd/viewcore/vendor/github.com/spf13/cobra/command_test.go b/cmd/viewcore/vendor/github.com/spf13/cobra/command_test.go
deleted file mode 100644
index ccee031..0000000
--- a/cmd/viewcore/vendor/github.com/spf13/cobra/command_test.go
+++ /dev/null
@@ -1,1733 +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)
- }
-}
-
-func TestFParseErrWhitelistBackwardCompatibility(t *testing.T) {
- c := &Command{Use: "c", Run: emptyRun}
- c.Flags().BoolP("boola", "a", false, "a boolean flag")
-
- output, err := executeCommand(c, "c", "-a", "--unknown", "flag")
- if err == nil {
- t.Error("expected unknown flag error")
- }
- checkStringContains(t, output, "unknown flag: --unknown")
-}
-
-func TestFParseErrWhitelistSameCommand(t *testing.T) {
- c := &Command{
- Use: "c",
- Run: emptyRun,
- FParseErrWhitelist: FParseErrWhitelist{
- UnknownFlags: true,
- },
- }
- c.Flags().BoolP("boola", "a", false, "a boolean flag")
-
- _, err := executeCommand(c, "c", "-a", "--unknown", "flag")
- if err != nil {
- t.Error("unexpected error: ", err)
- }
-}
-
-func TestFParseErrWhitelistParentCommand(t *testing.T) {
- root := &Command{
- Use: "root",
- Run: emptyRun,
- FParseErrWhitelist: FParseErrWhitelist{
- UnknownFlags: true,
- },
- }
-
- c := &Command{
- Use: "child",
- Run: emptyRun,
- }
- c.Flags().BoolP("boola", "a", false, "a boolean flag")
-
- root.AddCommand(c)
-
- output, err := executeCommand(root, "child", "-a", "--unknown", "flag")
- if err == nil {
- t.Error("expected unknown flag error")
- }
- checkStringContains(t, output, "unknown flag: --unknown")
-}
-
-func TestFParseErrWhitelistChildCommand(t *testing.T) {
- root := &Command{
- Use: "root",
- Run: emptyRun,
- }
-
- c := &Command{
- Use: "child",
- Run: emptyRun,
- FParseErrWhitelist: FParseErrWhitelist{
- UnknownFlags: true,
- },
- }
- c.Flags().BoolP("boola", "a", false, "a boolean flag")
-
- root.AddCommand(c)
-
- _, err := executeCommand(root, "child", "-a", "--unknown", "flag")
- if err != nil {
- t.Error("unexpected error: ", err.Error())
- }
-}
-
-func TestFParseErrWhitelistSiblingCommand(t *testing.T) {
- root := &Command{
- Use: "root",
- Run: emptyRun,
- }
-
- c := &Command{
- Use: "child",
- Run: emptyRun,
- FParseErrWhitelist: FParseErrWhitelist{
- UnknownFlags: true,
- },
- }
- c.Flags().BoolP("boola", "a", false, "a boolean flag")
-
- s := &Command{
- Use: "sibling",
- Run: emptyRun,
- }
- s.Flags().BoolP("boolb", "b", false, "a boolean flag")
-
- root.AddCommand(c)
- root.AddCommand(s)
-
- output, err := executeCommand(root, "sibling", "-b", "--unknown", "flag")
- if err == nil {
- t.Error("expected unknown flag error")
- }
- checkStringContains(t, output, "unknown flag: --unknown")
-}
diff --git a/cmd/viewcore/vendor/github.com/spf13/cobra/zsh_completions_test.go b/cmd/viewcore/vendor/github.com/spf13/cobra/zsh_completions_test.go
deleted file mode 100644
index 34e6949..0000000
--- a/cmd/viewcore/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/cmd/viewcore/vendor/github.com/spf13/pflag/bool_slice_test.go b/cmd/viewcore/vendor/github.com/spf13/pflag/bool_slice_test.go
deleted file mode 100644
index b617dd2..0000000
--- a/cmd/viewcore/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/cmd/viewcore/vendor/github.com/spf13/pflag/bool_test.go b/cmd/viewcore/vendor/github.com/spf13/pflag/bool_test.go
deleted file mode 100644
index a4319e7..0000000
--- a/cmd/viewcore/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/cmd/viewcore/vendor/github.com/spf13/pflag/bytes_test.go b/cmd/viewcore/vendor/github.com/spf13/pflag/bytes_test.go
deleted file mode 100644
index cc4a769..0000000
--- a/cmd/viewcore/vendor/github.com/spf13/pflag/bytes_test.go
+++ /dev/null
@@ -1,72 +0,0 @@
-package pflag
-
-import (
- "fmt"
- "os"
- "testing"
-)
-
-func setUpBytesHex(bytesHex *[]byte) *FlagSet {
- f := NewFlagSet("test", ContinueOnError)
- f.BytesHexVar(bytesHex, "bytes", []byte{1, 2, 3, 4, 5, 6, 7, 8, 9, 0}, "Some bytes in HEX")
- f.BytesHexVarP(bytesHex, "bytes2", "B", []byte{1, 2, 3, 4, 5, 6, 7, 8, 9, 0}, "Some bytes in HEX")
- return f
-}
-
-func TestBytesHex(t *testing.T) {
- testCases := []struct {
- input string
- success bool
- expected string
- }{
- /// Positive cases
- {"", true, ""}, // Is empty string OK ?
- {"01", true, "01"},
- {"0101", true, "0101"},
- {"1234567890abcdef", true, "1234567890ABCDEF"},
- {"1234567890ABCDEF", true, "1234567890ABCDEF"},
-
- // Negative cases
- {"0", false, ""}, // Short string
- {"000", false, ""}, /// Odd-length string
- {"qq", false, ""}, /// non-hex character
- }
-
- devnull, _ := os.Open(os.DevNull)
- os.Stderr = devnull
-
- for i := range testCases {
- var bytesHex []byte
- f := setUpBytesHex(&bytesHex)
-
- tc := &testCases[i]
-
- // --bytes
- args := []string{
- fmt.Sprintf("--bytes=%s", tc.input),
- fmt.Sprintf("-B %s", tc.input),
- fmt.Sprintf("--bytes2=%s", tc.input),
- }
-
- for _, arg := range args {
- 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 {
- // bytesHex, err := f.GetBytesHex("bytes")
- t.Errorf("expected failure while processing %q", tc.input)
- continue
- } else if tc.success {
- bytesHex, err := f.GetBytesHex("bytes")
- if err != nil {
- t.Errorf("Got error trying to fetch the IP flag: %v", err)
- }
- if fmt.Sprintf("%X", bytesHex) != tc.expected {
- t.Errorf("expected %q, got '%X'", tc.expected, bytesHex)
- }
- }
- }
- }
-}
diff --git a/cmd/viewcore/vendor/github.com/spf13/pflag/count_test.go b/cmd/viewcore/vendor/github.com/spf13/pflag/count_test.go
deleted file mode 100644
index 3785d37..0000000
--- a/cmd/viewcore/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/cmd/viewcore/vendor/github.com/spf13/pflag/duration_slice_test.go b/cmd/viewcore/vendor/github.com/spf13/pflag/duration_slice_test.go
deleted file mode 100644
index 489b012..0000000
--- a/cmd/viewcore/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/cmd/viewcore/vendor/github.com/spf13/pflag/example_test.go b/cmd/viewcore/vendor/github.com/spf13/pflag/example_test.go
deleted file mode 100644
index abd7806..0000000
--- a/cmd/viewcore/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/cmd/viewcore/vendor/github.com/spf13/pflag/export_test.go b/cmd/viewcore/vendor/github.com/spf13/pflag/export_test.go
deleted file mode 100644
index 9318fee..0000000
--- a/cmd/viewcore/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/cmd/viewcore/vendor/github.com/spf13/pflag/flag.go b/cmd/viewcore/vendor/github.com/spf13/pflag/flag.go
index 5eadc84..5cc710c 100644
--- a/cmd/viewcore/vendor/github.com/spf13/pflag/flag.go
+++ b/cmd/viewcore/vendor/github.com/spf13/pflag/flag.go
@@ -990,11 +990,12 @@
}
func (f *FlagSet) parseSingleShortArg(shorthands string, args []string, fn parseFunc) (outShorts string, outArgs []string, err error) {
+ outArgs = args
+
if strings.HasPrefix(shorthands, "test.") {
return
}
- outArgs = args
outShorts = shorthands[1:]
c := shorthands[0]
diff --git a/cmd/viewcore/vendor/github.com/spf13/pflag/flag_test.go b/cmd/viewcore/vendor/github.com/spf13/pflag/flag_test.go
deleted file mode 100644
index f600f0a..0000000
--- a/cmd/viewcore/vendor/github.com/spf13/pflag/flag_test.go
+++ /dev/null
@@ -1,1259 +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 testParseWithUnknownFlags(f *FlagSet, t *testing.T) {
- if f.Parsed() {
- t.Error("f.Parse() = true before Parse")
- }
- f.ParseErrorsWhitelist.UnknownFlags = true
-
- 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.BoolP("boole", "e", 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.StringP("stringo", "o", "0", "string value")
- f.Lookup("stringx").NoOptDefVal = "1"
- args := []string{
- "-ab",
- "-cs=xx",
- "--stringz=something",
- "--unknown1",
- "unknown1Value",
- "-d=true",
- "-x",
- "--unknown2=unknown2Value",
- "-u=unknown3Value",
- "-p",
- "unknown4Value",
- "-q", //another unknown with bool value
- "-y",
- "ee",
- "--unknown7=unknown7value",
- "--stringo=ovalue",
- "--unknown8=unknown8value",
- "--boole",
- "--unknown6",
- }
- want := []string{
- "boola", "true",
- "boolb", "true",
- "boolc", "true",
- "stringa", "xx",
- "stringz", "something",
- "boold", "true",
- "stringx", "1",
- "stringy", "ee",
- "stringo", "ovalue",
- "boole", "true",
- }
- 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 TestIgnoreUnknownFlags(t *testing.T) {
- ResetForTesting(func() { t.Error("bad parse") })
- testParseWithUnknownFlags(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 getDeprecatedFlagSet() *FlagSet {
- f := NewFlagSet("bob", ContinueOnError)
- f.Bool("badflag", true, "always true")
- f.MarkDeprecated("badflag", "use --good-flag instead")
- return f
-}
-func TestDeprecatedFlagInDocs(t *testing.T) {
- f := getDeprecatedFlagSet()
-
- out := new(bytes.Buffer)
- f.SetOutput(out)
- f.PrintDefaults()
-
- if strings.Contains(out.String(), "badflag") {
- t.Errorf("found deprecated flag in usage!")
- }
-}
-
-func TestUnHiddenDeprecatedFlagInDocs(t *testing.T) {
- f := getDeprecatedFlagSet()
- flg := f.Lookup("badflag")
- if flg == nil {
- t.Fatalf("Unable to lookup 'bob' in TestUnHiddenDeprecatedFlagInDocs")
- }
- flg.Hidden = false
-
- out := new(bytes.Buffer)
- f.SetOutput(out)
- f.PrintDefaults()
-
- defaults := out.String()
- if !strings.Contains(defaults, "badflag") {
- t.Errorf("Did not find deprecated flag in usage!")
- }
- if !strings.Contains(defaults, "use --good-flag instead") {
- t.Errorf("Did not find 'use --good-flag instead' in defaults")
- }
-}
-
-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/cmd/viewcore/vendor/github.com/spf13/pflag/golangflag_test.go b/cmd/viewcore/vendor/github.com/spf13/pflag/golangflag_test.go
deleted file mode 100644
index 5bd831b..0000000
--- a/cmd/viewcore/vendor/github.com/spf13/pflag/golangflag_test.go
+++ /dev/null
@@ -1,47 +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)
- }
- if !f.Parsed() {
- t.Fatal("f.Parsed() return false after f.Parse() called")
- }
-
- // in fact it is useless. because `go test` called flag.Parse()
- if !goflag.CommandLine.Parsed() {
- t.Fatal("goflag.CommandLine.Parsed() return false after f.Parse() called")
- }
-}
diff --git a/cmd/viewcore/vendor/github.com/spf13/pflag/int_slice_test.go b/cmd/viewcore/vendor/github.com/spf13/pflag/int_slice_test.go
deleted file mode 100644
index 745aecb..0000000
--- a/cmd/viewcore/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/cmd/viewcore/vendor/github.com/spf13/pflag/ip_slice_test.go b/cmd/viewcore/vendor/github.com/spf13/pflag/ip_slice_test.go
deleted file mode 100644
index b0c681c..0000000
--- a/cmd/viewcore/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/cmd/viewcore/vendor/github.com/spf13/pflag/ip_test.go b/cmd/viewcore/vendor/github.com/spf13/pflag/ip_test.go
deleted file mode 100644
index 1fec50e..0000000
--- a/cmd/viewcore/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/cmd/viewcore/vendor/github.com/spf13/pflag/ipnet_test.go b/cmd/viewcore/vendor/github.com/spf13/pflag/ipnet_test.go
deleted file mode 100644
index 335b6fa..0000000
--- a/cmd/viewcore/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/cmd/viewcore/vendor/github.com/spf13/pflag/printusage_test.go b/cmd/viewcore/vendor/github.com/spf13/pflag/printusage_test.go
deleted file mode 100644
index df982aa..0000000
--- a/cmd/viewcore/vendor/github.com/spf13/pflag/printusage_test.go
+++ /dev/null
@@ -1,74 +0,0 @@
-package pflag
-
-import (
- "bytes"
- "io"
- "testing"
-)
-
-const expectedOutput = ` --long-form Some description
- --long-form2 Some description
- with multiline
- -s, --long-name Some description
- -t, --long-name2 Some description with
- multiline
-`
-
-func setUpPFlagSet(buf io.Writer) *FlagSet {
- f := NewFlagSet("test", ExitOnError)
- f.Bool("long-form", false, "Some description")
- f.Bool("long-form2", false, "Some description\n with multiline")
- f.BoolP("long-name", "s", false, "Some description")
- f.BoolP("long-name2", "t", false, "Some description with\n multiline")
- f.SetOutput(buf)
- return f
-}
-
-func TestPrintUsage(t *testing.T) {
- buf := bytes.Buffer{}
- f := setUpPFlagSet(&buf)
- f.PrintDefaults()
- res := buf.String()
- if res != expectedOutput {
- t.Errorf("Expected \n%s \nActual \n%s", expectedOutput, res)
- }
-}
-
-func setUpPFlagSet2(buf io.Writer) *FlagSet {
- f := NewFlagSet("test", ExitOnError)
- f.Bool("long-form", false, "Some description")
- f.Bool("long-form2", false, "Some description\n with multiline")
- f.BoolP("long-name", "s", false, "Some description")
- f.BoolP("long-name2", "t", false, "Some description with\n multiline")
- f.StringP("some-very-long-arg", "l", "test", "Some very long description having break the limit")
- f.StringP("other-very-long-arg", "o", "long-default-value", "Some very long description having break the limit")
- f.String("some-very-long-arg2", "very long default value", "Some very long description\nwith line break\nmultiple")
- f.SetOutput(buf)
- return f
-}
-
-const expectedOutput2 = ` --long-form Some description
- --long-form2 Some description
- with multiline
- -s, --long-name Some description
- -t, --long-name2 Some description with
- multiline
- -o, --other-very-long-arg string Some very long description having
- break the limit (default
- "long-default-value")
- -l, --some-very-long-arg string Some very long description having
- break the limit (default "test")
- --some-very-long-arg2 string Some very long description
- with line break
- multiple (default "very long default
- value")
-`
-
-func TestPrintUsage_2(t *testing.T) {
- buf := bytes.Buffer{}
- f := setUpPFlagSet2(&buf)
- res := f.FlagUsagesWrapped(80)
- if res != expectedOutput2 {
- t.Errorf("Expected \n%q \nActual \n%q", expectedOutput2, res)
- }
-}
diff --git a/cmd/viewcore/vendor/github.com/spf13/pflag/string_array_test.go b/cmd/viewcore/vendor/github.com/spf13/pflag/string_array_test.go
deleted file mode 100644
index 1ceac8c..0000000
--- a/cmd/viewcore/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/cmd/viewcore/vendor/github.com/spf13/pflag/string_slice_test.go b/cmd/viewcore/vendor/github.com/spf13/pflag/string_slice_test.go
deleted file mode 100644
index c41f3bd..0000000
--- a/cmd/viewcore/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/cmd/viewcore/vendor/github.com/spf13/pflag/uint_slice_test.go b/cmd/viewcore/vendor/github.com/spf13/pflag/uint_slice_test.go
deleted file mode 100644
index db1a19d..0000000
--- a/cmd/viewcore/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/cmd/viewcore/vendor/golang.org/x/sys/unix/creds_test.go b/cmd/viewcore/vendor/golang.org/x/sys/unix/creds_test.go
deleted file mode 100644
index 1b50831..0000000
--- a/cmd/viewcore/vendor/golang.org/x/sys/unix/creds_test.go
+++ /dev/null
@@ -1,134 +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.
-
-// +build linux
-
-package unix_test
-
-import (
- "bytes"
- "go/build"
- "net"
- "os"
- "testing"
-
- "golang.org/x/sys/unix"
-)
-
-// TestSCMCredentials tests the sending and receiving of credentials
-// (PID, UID, GID) in an ancillary message between two UNIX
-// sockets. The SO_PASSCRED socket option is enabled on the sending
-// socket for this to work.
-func TestSCMCredentials(t *testing.T) {
- socketTypeTests := []struct {
- socketType int
- dataLen int
- }{
- {
- unix.SOCK_STREAM,
- 1,
- }, {
- unix.SOCK_DGRAM,
- 0,
- },
- }
-
- for _, tt := range socketTypeTests {
- if tt.socketType == unix.SOCK_DGRAM && !atLeast1p10() {
- t.Log("skipping DGRAM test on pre-1.10")
- continue
- }
-
- fds, err := unix.Socketpair(unix.AF_LOCAL, tt.socketType, 0)
- if err != nil {
- t.Fatalf("Socketpair: %v", err)
- }
- defer unix.Close(fds[0])
- defer unix.Close(fds[1])
-
- err = unix.SetsockoptInt(fds[0], unix.SOL_SOCKET, unix.SO_PASSCRED, 1)
- if err != nil {
- t.Fatalf("SetsockoptInt: %v", err)
- }
-
- srvFile := os.NewFile(uintptr(fds[0]), "server")
- defer srvFile.Close()
- srv, err := net.FileConn(srvFile)
- if err != nil {
- t.Errorf("FileConn: %v", err)
- return
- }
- defer srv.Close()
-
- cliFile := os.NewFile(uintptr(fds[1]), "client")
- defer cliFile.Close()
- cli, err := net.FileConn(cliFile)
- if err != nil {
- t.Errorf("FileConn: %v", err)
- return
- }
- defer cli.Close()
-
- var ucred unix.Ucred
- ucred.Pid = int32(os.Getpid())
- ucred.Uid = uint32(os.Getuid())
- ucred.Gid = uint32(os.Getgid())
- oob := unix.UnixCredentials(&ucred)
-
- // On SOCK_STREAM, this is internally going to send a dummy byte
- n, oobn, err := cli.(*net.UnixConn).WriteMsgUnix(nil, oob, nil)
- if err != nil {
- t.Fatalf("WriteMsgUnix: %v", err)
- }
- if n != 0 {
- t.Fatalf("WriteMsgUnix n = %d, want 0", n)
- }
- if oobn != len(oob) {
- t.Fatalf("WriteMsgUnix oobn = %d, want %d", oobn, len(oob))
- }
-
- oob2 := make([]byte, 10*len(oob))
- n, oobn2, flags, _, err := srv.(*net.UnixConn).ReadMsgUnix(nil, oob2)
- if err != nil {
- t.Fatalf("ReadMsgUnix: %v", err)
- }
- if flags != 0 {
- t.Fatalf("ReadMsgUnix flags = 0x%x, want 0", flags)
- }
- if n != tt.dataLen {
- t.Fatalf("ReadMsgUnix n = %d, want %d", n, tt.dataLen)
- }
- if oobn2 != oobn {
- // without SO_PASSCRED set on the socket, ReadMsgUnix will
- // return zero oob bytes
- t.Fatalf("ReadMsgUnix oobn = %d, want %d", oobn2, oobn)
- }
- oob2 = oob2[:oobn2]
- if !bytes.Equal(oob, oob2) {
- t.Fatal("ReadMsgUnix oob bytes don't match")
- }
-
- scm, err := unix.ParseSocketControlMessage(oob2)
- if err != nil {
- t.Fatalf("ParseSocketControlMessage: %v", err)
- }
- newUcred, err := unix.ParseUnixCredentials(&scm[0])
- if err != nil {
- t.Fatalf("ParseUnixCredentials: %v", err)
- }
- if *newUcred != ucred {
- t.Fatalf("ParseUnixCredentials = %+v, want %+v", newUcred, ucred)
- }
- }
-}
-
-// atLeast1p10 reports whether we are running on Go 1.10 or later.
-func atLeast1p10() bool {
- for _, ver := range build.Default.ReleaseTags {
- if ver == "go1.10" {
- return true
- }
- }
- return false
-}
diff --git a/cmd/viewcore/vendor/golang.org/x/sys/unix/dev_linux_test.go b/cmd/viewcore/vendor/golang.org/x/sys/unix/dev_linux_test.go
deleted file mode 100644
index 5164528..0000000
--- a/cmd/viewcore/vendor/golang.org/x/sys/unix/dev_linux_test.go
+++ /dev/null
@@ -1,56 +0,0 @@
-// Copyright 2017 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.
-
-// +build go1.7
-
-package unix_test
-
-import (
- "fmt"
- "testing"
-
- "golang.org/x/sys/unix"
-)
-
-func TestDevices(t *testing.T) {
- testCases := []struct {
- path string
- major uint32
- minor uint32
- }{
- // well known major/minor numbers according to
- // https://git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git/tree/Documentation/admin-guide/devices.txt
- {"/dev/null", 1, 3},
- {"/dev/zero", 1, 5},
- {"/dev/random", 1, 8},
- {"/dev/full", 1, 7},
- {"/dev/urandom", 1, 9},
- {"/dev/tty", 5, 0},
- }
- for _, tc := range testCases {
- t.Run(fmt.Sprintf("%s %v:%v", tc.path, tc.major, tc.minor), func(t *testing.T) {
- var stat unix.Stat_t
- err := unix.Stat(tc.path, &stat)
- if err != nil {
- if err == unix.EACCES {
- t.Skip("no permission to stat device, skipping test")
- }
- t.Errorf("failed to stat device: %v", err)
- return
- }
-
- dev := uint64(stat.Rdev)
- if unix.Major(dev) != tc.major {
- t.Errorf("for %s Major(%#x) == %d, want %d", tc.path, dev, unix.Major(dev), tc.major)
- }
- if unix.Minor(dev) != tc.minor {
- t.Errorf("for %s Minor(%#x) == %d, want %d", tc.path, dev, unix.Minor(dev), tc.minor)
- }
- if unix.Mkdev(tc.major, tc.minor) != dev {
- t.Errorf("for %s Mkdev(%d, %d) == %#x, want %#x", tc.path, tc.major, tc.minor, unix.Mkdev(tc.major, tc.minor), dev)
- }
- })
-
- }
-}
diff --git a/cmd/viewcore/vendor/golang.org/x/sys/unix/example_test.go b/cmd/viewcore/vendor/golang.org/x/sys/unix/example_test.go
deleted file mode 100644
index 10619af..0000000
--- a/cmd/viewcore/vendor/golang.org/x/sys/unix/example_test.go
+++ /dev/null
@@ -1,19 +0,0 @@
-// Copyright 2018 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.
-
-// +build darwin dragonfly freebsd linux netbsd openbsd solaris
-
-package unix_test
-
-import (
- "log"
- "os"
-
- "golang.org/x/sys/unix"
-)
-
-func ExampleExec() {
- err := unix.Exec("/bin/ls", []string{"ls", "-al"}, os.Environ())
- log.Fatal(err)
-}
diff --git a/cmd/viewcore/vendor/golang.org/x/sys/unix/export_test.go b/cmd/viewcore/vendor/golang.org/x/sys/unix/export_test.go
deleted file mode 100644
index e802469..0000000
--- a/cmd/viewcore/vendor/golang.org/x/sys/unix/export_test.go
+++ /dev/null
@@ -1,9 +0,0 @@
-// Copyright 2015 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.
-
-// +build darwin dragonfly freebsd linux netbsd openbsd solaris
-
-package unix
-
-var Itoa = itoa
diff --git a/cmd/viewcore/vendor/golang.org/x/sys/unix/fcntl.go b/cmd/viewcore/vendor/golang.org/x/sys/unix/fcntl.go
index 0c58c7e..9379ba9 100644
--- a/cmd/viewcore/vendor/golang.org/x/sys/unix/fcntl.go
+++ b/cmd/viewcore/vendor/golang.org/x/sys/unix/fcntl.go
@@ -14,7 +14,11 @@
// FcntlInt performs a fcntl syscall on fd with the provided command and argument.
func FcntlInt(fd uintptr, cmd, arg int) (int, error) {
- valptr, _, err := Syscall(fcntl64Syscall, fd, uintptr(cmd), uintptr(arg))
+ valptr, _, errno := Syscall(fcntl64Syscall, fd, uintptr(cmd), uintptr(arg))
+ var err error
+ if errno != 0 {
+ err = errno
+ }
return int(valptr), err
}
diff --git a/cmd/viewcore/vendor/golang.org/x/sys/unix/mmap_unix_test.go b/cmd/viewcore/vendor/golang.org/x/sys/unix/mmap_unix_test.go
deleted file mode 100644
index 3258ca3..0000000
--- a/cmd/viewcore/vendor/golang.org/x/sys/unix/mmap_unix_test.go
+++ /dev/null
@@ -1,35 +0,0 @@
-// Copyright 2014 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.
-
-// +build darwin dragonfly freebsd linux netbsd openbsd solaris
-
-package unix_test
-
-import (
- "testing"
-
- "golang.org/x/sys/unix"
-)
-
-func TestMmap(t *testing.T) {
- b, err := unix.Mmap(-1, 0, unix.Getpagesize(), unix.PROT_NONE, unix.MAP_ANON|unix.MAP_PRIVATE)
- if err != nil {
- t.Fatalf("Mmap: %v", err)
- }
- if err := unix.Mprotect(b, unix.PROT_READ|unix.PROT_WRITE); err != nil {
- t.Fatalf("Mprotect: %v", err)
- }
-
- b[0] = 42
-
- if err := unix.Msync(b, unix.MS_SYNC); err != nil {
- t.Fatalf("Msync: %v", err)
- }
- if err := unix.Madvise(b, unix.MADV_DONTNEED); err != nil {
- t.Fatalf("Madvise: %v", err)
- }
- if err := unix.Munmap(b); err != nil {
- t.Fatalf("Munmap: %v", err)
- }
-}
diff --git a/cmd/viewcore/vendor/golang.org/x/sys/unix/openbsd_test.go b/cmd/viewcore/vendor/golang.org/x/sys/unix/openbsd_test.go
deleted file mode 100644
index 734d765..0000000
--- a/cmd/viewcore/vendor/golang.org/x/sys/unix/openbsd_test.go
+++ /dev/null
@@ -1,113 +0,0 @@
-// Copyright 2016 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.
-
-// +build openbsd
-
-// This, on the face of it, bizarre testing mechanism is necessary because
-// the only reliable way to gauge whether or not a pledge(2) call has succeeded
-// is that the program has been killed as a result of breaking its pledge.
-
-package unix_test
-
-import (
- "flag"
- "fmt"
- "io/ioutil"
- "os"
- "os/exec"
- "path/filepath"
- "testing"
-
- "golang.org/x/sys/unix"
-)
-
-type testProc struct {
- fn func() // should always exit instead of returning
- cleanup func() error // for instance, delete coredumps from testing pledge
- success bool // whether zero-exit means success or failure
-}
-
-var (
- testProcs = map[string]testProc{}
- procName = ""
-)
-
-const (
- optName = "sys-unix-internal-procname"
-)
-
-func init() {
- flag.StringVar(&procName, optName, "", "internal use only")
-}
-
-// testCmd generates a proper command that, when executed, runs the test
-// corresponding to the given key.
-func testCmd(procName string) (*exec.Cmd, error) {
- exe, err := filepath.Abs(os.Args[0])
- if err != nil {
- return nil, err
- }
- cmd := exec.Command(exe, "-"+optName+"="+procName)
- cmd.Stdout, cmd.Stderr = os.Stdout, os.Stderr
- return cmd, nil
-}
-
-// ExitsCorrectly is a comprehensive, one-line-of-use wrapper for testing
-// a testProc with a key.
-func ExitsCorrectly(procName string, t *testing.T) {
- s := testProcs[procName]
- c, err := testCmd(procName)
- defer func() {
- if s.cleanup() != nil {
- t.Fatalf("Failed to run cleanup for %s", procName)
- }
- }()
- if err != nil {
- t.Fatalf("Failed to construct command for %s", procName)
- }
- if (c.Run() == nil) != s.success {
- result := "succeed"
- if !s.success {
- result = "fail"
- }
- t.Fatalf("Process did not %s when it was supposed to", result)
- }
-}
-
-func TestMain(m *testing.M) {
- flag.Parse()
- if procName != "" {
- testProcs[procName].fn()
- }
- os.Exit(m.Run())
-}
-
-// For example, add a test for pledge.
-func init() {
- testProcs["pledge"] = testProc{
- func() {
- fmt.Println(unix.Pledge("", nil))
- os.Exit(0)
- },
- func() error {
- files, err := ioutil.ReadDir(".")
- if err != nil {
- return err
- }
- for _, file := range files {
- if filepath.Ext(file.Name()) == ".core" {
- if err := os.Remove(file.Name()); err != nil {
- return err
- }
- }
- }
- return nil
- },
- false,
- }
-}
-
-func TestPledge(t *testing.T) {
- ExitsCorrectly("pledge", t)
-}
diff --git a/cmd/viewcore/vendor/golang.org/x/sys/unix/syscall_bsd_test.go b/cmd/viewcore/vendor/golang.org/x/sys/unix/syscall_bsd_test.go
deleted file mode 100644
index 6c4e2ac..0000000
--- a/cmd/viewcore/vendor/golang.org/x/sys/unix/syscall_bsd_test.go
+++ /dev/null
@@ -1,93 +0,0 @@
-// Copyright 2014 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.
-
-// +build darwin dragonfly freebsd openbsd
-
-package unix_test
-
-import (
- "os/exec"
- "runtime"
- "testing"
- "time"
-
- "golang.org/x/sys/unix"
-)
-
-const MNT_WAIT = 1
-const MNT_NOWAIT = 2
-
-func TestGetfsstat(t *testing.T) {
- const flags = MNT_NOWAIT // see golang.org/issue/16937
- n, err := unix.Getfsstat(nil, flags)
- if err != nil {
- t.Fatal(err)
- }
-
- data := make([]unix.Statfs_t, n)
- n2, err := unix.Getfsstat(data, flags)
- if err != nil {
- t.Fatal(err)
- }
- if n != n2 {
- t.Errorf("Getfsstat(nil) = %d, but subsequent Getfsstat(slice) = %d", n, n2)
- }
- for i, stat := range data {
- if stat == (unix.Statfs_t{}) {
- t.Errorf("index %v is an empty Statfs_t struct", i)
- }
- }
- if t.Failed() {
- for i, stat := range data[:n2] {
- t.Logf("data[%v] = %+v", i, stat)
- }
- mount, err := exec.Command("mount").CombinedOutput()
- if err != nil {
- t.Logf("mount: %v\n%s", err, mount)
- } else {
- t.Logf("mount: %s", mount)
- }
- }
-}
-
-func TestSelect(t *testing.T) {
- err := unix.Select(0, nil, nil, nil, &unix.Timeval{Sec: 0, Usec: 0})
- if err != nil {
- t.Fatalf("Select: %v", err)
- }
-
- dur := 250 * time.Millisecond
- tv := unix.NsecToTimeval(int64(dur))
- start := time.Now()
- err = unix.Select(0, nil, nil, nil, &tv)
- took := time.Since(start)
- if err != nil {
- t.Fatalf("Select: %v", err)
- }
-
- // On some BSDs the actual timeout might also be slightly less than the requested.
- // Add an acceptable margin to avoid flaky tests.
- if took < dur*2/3 {
- t.Errorf("Select: timeout should have been at least %v, got %v", dur, took)
- }
-}
-
-func TestSysctlRaw(t *testing.T) {
- if runtime.GOOS == "openbsd" {
- t.Skip("kern.proc.pid does not exist on OpenBSD")
- }
-
- _, err := unix.SysctlRaw("kern.proc.pid", unix.Getpid())
- if err != nil {
- t.Fatal(err)
- }
-}
-
-func TestSysctlUint32(t *testing.T) {
- maxproc, err := unix.SysctlUint32("kern.maxproc")
- if err != nil {
- t.Fatal(err)
- }
- t.Logf("kern.maxproc: %v", maxproc)
-}
diff --git a/cmd/viewcore/vendor/golang.org/x/sys/unix/syscall_darwin_test.go b/cmd/viewcore/vendor/golang.org/x/sys/unix/syscall_darwin_test.go
deleted file mode 100644
index 65691d5..0000000
--- a/cmd/viewcore/vendor/golang.org/x/sys/unix/syscall_darwin_test.go
+++ /dev/null
@@ -1,19 +0,0 @@
-// Copyright 2018 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 unix_test
-
-// stringsFromByteSlice converts a sequence of attributes to a []string.
-// On Darwin, each entry is a NULL-terminated string.
-func stringsFromByteSlice(buf []byte) []string {
- var result []string
- off := 0
- for i, b := range buf {
- if b == 0 {
- result = append(result, string(buf[off:i]))
- off = i + 1
- }
- }
- return result
-}
diff --git a/cmd/viewcore/vendor/golang.org/x/sys/unix/syscall_freebsd_test.go b/cmd/viewcore/vendor/golang.org/x/sys/unix/syscall_freebsd_test.go
deleted file mode 100644
index 0fec1a8..0000000
--- a/cmd/viewcore/vendor/golang.org/x/sys/unix/syscall_freebsd_test.go
+++ /dev/null
@@ -1,312 +0,0 @@
-// Copyright 2014 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.
-
-// +build freebsd
-
-package unix_test
-
-import (
- "flag"
- "fmt"
- "io/ioutil"
- "os"
- "os/exec"
- "path"
- "path/filepath"
- "runtime"
- "testing"
-
- "golang.org/x/sys/unix"
-)
-
-func TestSysctlUint64(t *testing.T) {
- _, err := unix.SysctlUint64("vm.swap_total")
- if err != nil {
- t.Fatal(err)
- }
-}
-
-// FIXME: Infrastructure for launching tests in subprocesses stolen from openbsd_test.go - refactor?
-// testCmd generates a proper command that, when executed, runs the test
-// corresponding to the given key.
-
-type testProc struct {
- fn func() // should always exit instead of returning
- arg func(t *testing.T) string // generate argument for test
- cleanup func(arg string) error // for instance, delete coredumps from testing pledge
- success bool // whether zero-exit means success or failure
-}
-
-var (
- testProcs = map[string]testProc{}
- procName = ""
- procArg = ""
-)
-
-const (
- optName = "sys-unix-internal-procname"
- optArg = "sys-unix-internal-arg"
-)
-
-func init() {
- flag.StringVar(&procName, optName, "", "internal use only")
- flag.StringVar(&procArg, optArg, "", "internal use only")
-
-}
-
-func testCmd(procName string, procArg string) (*exec.Cmd, error) {
- exe, err := filepath.Abs(os.Args[0])
- if err != nil {
- return nil, err
- }
- cmd := exec.Command(exe, "-"+optName+"="+procName, "-"+optArg+"="+procArg)
- cmd.Stdout, cmd.Stderr = os.Stdout, os.Stderr
- return cmd, nil
-}
-
-// ExitsCorrectly is a comprehensive, one-line-of-use wrapper for testing
-// a testProc with a key.
-func ExitsCorrectly(t *testing.T, procName string) {
- s := testProcs[procName]
- arg := "-"
- if s.arg != nil {
- arg = s.arg(t)
- }
- c, err := testCmd(procName, arg)
- defer func(arg string) {
- if err := s.cleanup(arg); err != nil {
- t.Fatalf("Failed to run cleanup for %s %s %#v", procName, err, err)
- }
- }(arg)
- if err != nil {
- t.Fatalf("Failed to construct command for %s", procName)
- }
- if (c.Run() == nil) != s.success {
- result := "succeed"
- if !s.success {
- result = "fail"
- }
- t.Fatalf("Process did not %s when it was supposed to", result)
- }
-}
-
-func TestMain(m *testing.M) {
- flag.Parse()
- if procName != "" {
- t := testProcs[procName]
- t.fn()
- os.Stderr.WriteString("test function did not exit\n")
- if t.success {
- os.Exit(1)
- } else {
- os.Exit(0)
- }
- }
- os.Exit(m.Run())
-}
-
-// end of infrastructure
-
-const testfile = "gocapmodetest"
-const testfile2 = testfile + "2"
-
-func CapEnterTest() {
- _, err := os.OpenFile(path.Join(procArg, testfile), os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0666)
- if err != nil {
- panic(fmt.Sprintf("OpenFile: %s", err))
- }
-
- err = unix.CapEnter()
- if err != nil {
- panic(fmt.Sprintf("CapEnter: %s", err))
- }
-
- _, err = os.OpenFile(path.Join(procArg, testfile2), os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0666)
- if err == nil {
- panic("OpenFile works!")
- }
- if err.(*os.PathError).Err != unix.ECAPMODE {
- panic(fmt.Sprintf("OpenFile failed wrong: %s %#v", err, err))
- }
- os.Exit(0)
-}
-
-func makeTempDir(t *testing.T) string {
- d, err := ioutil.TempDir("", "go_openat_test")
- if err != nil {
- t.Fatalf("TempDir failed: %s", err)
- }
- return d
-}
-
-func removeTempDir(arg string) error {
- err := os.RemoveAll(arg)
- if err != nil && err.(*os.PathError).Err == unix.ENOENT {
- return nil
- }
- return err
-}
-
-func init() {
- testProcs["cap_enter"] = testProc{
- CapEnterTest,
- makeTempDir,
- removeTempDir,
- true,
- }
-}
-
-func TestCapEnter(t *testing.T) {
- if runtime.GOARCH != "amd64" {
- t.Skipf("skipping test on %s", runtime.GOARCH)
- }
- ExitsCorrectly(t, "cap_enter")
-}
-
-func OpenatTest() {
- f, err := os.Open(procArg)
- if err != nil {
- panic(err)
- }
-
- err = unix.CapEnter()
- if err != nil {
- panic(fmt.Sprintf("CapEnter: %s", err))
- }
-
- fxx, err := unix.Openat(int(f.Fd()), "xx", os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0666)
- if err != nil {
- panic(err)
- }
- unix.Close(fxx)
-
- // The right to open BASE/xx is not ambient
- _, err = os.OpenFile(procArg+"/xx", os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0666)
- if err == nil {
- panic("OpenFile succeeded")
- }
- if err.(*os.PathError).Err != unix.ECAPMODE {
- panic(fmt.Sprintf("OpenFile failed wrong: %s %#v", err, err))
- }
-
- // Can't make a new directory either
- err = os.Mkdir(procArg+"2", 0777)
- if err == nil {
- panic("MKdir succeeded")
- }
- if err.(*os.PathError).Err != unix.ECAPMODE {
- panic(fmt.Sprintf("Mkdir failed wrong: %s %#v", err, err))
- }
-
- // Remove all caps except read and lookup.
- r, err := unix.CapRightsInit([]uint64{unix.CAP_READ, unix.CAP_LOOKUP})
- if err != nil {
- panic(fmt.Sprintf("CapRightsInit failed: %s %#v", err, err))
- }
- err = unix.CapRightsLimit(f.Fd(), r)
- if err != nil {
- panic(fmt.Sprintf("CapRightsLimit failed: %s %#v", err, err))
- }
-
- // Check we can get the rights back again
- r, err = unix.CapRightsGet(f.Fd())
- if err != nil {
- panic(fmt.Sprintf("CapRightsGet failed: %s %#v", err, err))
- }
- b, err := unix.CapRightsIsSet(r, []uint64{unix.CAP_READ, unix.CAP_LOOKUP})
- if err != nil {
- panic(fmt.Sprintf("CapRightsIsSet failed: %s %#v", err, err))
- }
- if !b {
- panic(fmt.Sprintf("Unexpected rights"))
- }
- b, err = unix.CapRightsIsSet(r, []uint64{unix.CAP_READ, unix.CAP_LOOKUP, unix.CAP_WRITE})
- if err != nil {
- panic(fmt.Sprintf("CapRightsIsSet failed: %s %#v", err, err))
- }
- if b {
- panic(fmt.Sprintf("Unexpected rights (2)"))
- }
-
- // Can no longer create a file
- _, err = unix.Openat(int(f.Fd()), "xx2", os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0666)
- if err == nil {
- panic("Openat succeeded")
- }
- if err != unix.ENOTCAPABLE {
- panic(fmt.Sprintf("OpenFileAt failed wrong: %s %#v", err, err))
- }
-
- // But can read an existing one
- _, err = unix.Openat(int(f.Fd()), "xx", os.O_RDONLY, 0666)
- if err != nil {
- panic(fmt.Sprintf("Openat failed: %s %#v", err, err))
- }
-
- os.Exit(0)
-}
-
-func init() {
- testProcs["openat"] = testProc{
- OpenatTest,
- makeTempDir,
- removeTempDir,
- true,
- }
-}
-
-func TestOpenat(t *testing.T) {
- if runtime.GOARCH != "amd64" {
- t.Skipf("skipping test on %s", runtime.GOARCH)
- }
- ExitsCorrectly(t, "openat")
-}
-
-func TestCapRightsSetAndClear(t *testing.T) {
- r, err := unix.CapRightsInit([]uint64{unix.CAP_READ, unix.CAP_WRITE, unix.CAP_PDWAIT})
- if err != nil {
- t.Fatalf("CapRightsInit failed: %s", err)
- }
-
- err = unix.CapRightsSet(r, []uint64{unix.CAP_EVENT, unix.CAP_LISTEN})
- if err != nil {
- t.Fatalf("CapRightsSet failed: %s", err)
- }
-
- b, err := unix.CapRightsIsSet(r, []uint64{unix.CAP_READ, unix.CAP_WRITE, unix.CAP_PDWAIT, unix.CAP_EVENT, unix.CAP_LISTEN})
- if err != nil {
- t.Fatalf("CapRightsIsSet failed: %s", err)
- }
- if !b {
- t.Fatalf("Wrong rights set")
- }
-
- err = unix.CapRightsClear(r, []uint64{unix.CAP_READ, unix.CAP_PDWAIT})
- if err != nil {
- t.Fatalf("CapRightsClear failed: %s", err)
- }
-
- b, err = unix.CapRightsIsSet(r, []uint64{unix.CAP_WRITE, unix.CAP_EVENT, unix.CAP_LISTEN})
- if err != nil {
- t.Fatalf("CapRightsIsSet failed: %s", err)
- }
- if !b {
- t.Fatalf("Wrong rights set")
- }
-}
-
-// stringsFromByteSlice converts a sequence of attributes to a []string.
-// On FreeBSD, each entry consists of a single byte containing the length
-// of the attribute name, followed by the attribute name.
-// The name is _not_ NULL-terminated.
-func stringsFromByteSlice(buf []byte) []string {
- var result []string
- i := 0
- for i < len(buf) {
- next := i + 1 + int(buf[i])
- result = append(result, string(buf[i+1:next]))
- i = next
- }
- return result
-}
diff --git a/cmd/viewcore/vendor/golang.org/x/sys/unix/syscall_linux_test.go b/cmd/viewcore/vendor/golang.org/x/sys/unix/syscall_linux_test.go
deleted file mode 100644
index eed1726..0000000
--- a/cmd/viewcore/vendor/golang.org/x/sys/unix/syscall_linux_test.go
+++ /dev/null
@@ -1,421 +0,0 @@
-// Copyright 2016 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.
-
-// +build linux
-
-package unix_test
-
-import (
- "os"
- "runtime"
- "runtime/debug"
- "testing"
- "time"
-
- "golang.org/x/sys/unix"
-)
-
-func TestIoctlGetInt(t *testing.T) {
- f, err := os.Open("/dev/random")
- if err != nil {
- t.Fatalf("failed to open device: %v", err)
- }
- defer f.Close()
-
- v, err := unix.IoctlGetInt(int(f.Fd()), unix.RNDGETENTCNT)
- if err != nil {
- t.Fatalf("failed to perform ioctl: %v", err)
- }
-
- t.Logf("%d bits of entropy available", v)
-}
-
-func TestPpoll(t *testing.T) {
- if runtime.GOOS == "android" {
- t.Skip("mkfifo syscall is not available on android, skipping test")
- }
-
- f, cleanup := mktmpfifo(t)
- defer cleanup()
-
- const timeout = 100 * time.Millisecond
-
- ok := make(chan bool, 1)
- go func() {
- select {
- case <-time.After(10 * timeout):
- t.Errorf("Ppoll: failed to timeout after %d", 10*timeout)
- case <-ok:
- }
- }()
-
- fds := []unix.PollFd{{Fd: int32(f.Fd()), Events: unix.POLLIN}}
- timeoutTs := unix.NsecToTimespec(int64(timeout))
- n, err := unix.Ppoll(fds, &timeoutTs, nil)
- ok <- true
- if err != nil {
- t.Errorf("Ppoll: unexpected error: %v", err)
- return
- }
- if n != 0 {
- t.Errorf("Ppoll: wrong number of events: got %v, expected %v", n, 0)
- return
- }
-}
-
-func TestTime(t *testing.T) {
- var ut unix.Time_t
- ut2, err := unix.Time(&ut)
- if err != nil {
- t.Fatalf("Time: %v", err)
- }
- if ut != ut2 {
- t.Errorf("Time: return value %v should be equal to argument %v", ut2, ut)
- }
-
- var now time.Time
-
- for i := 0; i < 10; i++ {
- ut, err = unix.Time(nil)
- if err != nil {
- t.Fatalf("Time: %v", err)
- }
-
- now = time.Now()
-
- if int64(ut) == now.Unix() {
- return
- }
- }
-
- t.Errorf("Time: return value %v should be nearly equal to time.Now().Unix() %v", ut, now.Unix())
-}
-
-func TestUtime(t *testing.T) {
- defer chtmpdir(t)()
-
- touch(t, "file1")
-
- buf := &unix.Utimbuf{
- Modtime: 12345,
- }
-
- err := unix.Utime("file1", buf)
- if err != nil {
- t.Fatalf("Utime: %v", err)
- }
-
- fi, err := os.Stat("file1")
- if err != nil {
- t.Fatal(err)
- }
-
- if fi.ModTime().Unix() != 12345 {
- t.Errorf("Utime: failed to change modtime: expected %v, got %v", 12345, fi.ModTime().Unix())
- }
-}
-
-func TestUtimesNanoAt(t *testing.T) {
- defer chtmpdir(t)()
-
- symlink := "symlink1"
- os.Remove(symlink)
- err := os.Symlink("nonexisting", symlink)
- if err != nil {
- t.Fatal(err)
- }
-
- ts := []unix.Timespec{
- {Sec: 1111, Nsec: 2222},
- {Sec: 3333, Nsec: 4444},
- }
- err = unix.UtimesNanoAt(unix.AT_FDCWD, symlink, ts, unix.AT_SYMLINK_NOFOLLOW)
- if err != nil {
- t.Fatalf("UtimesNanoAt: %v", err)
- }
-
- var st unix.Stat_t
- err = unix.Lstat(symlink, &st)
- if err != nil {
- t.Fatalf("Lstat: %v", err)
- }
-
- // Only check Mtim, Atim might not be supported by the underlying filesystem
- expected := ts[1]
- if st.Mtim.Nsec == 0 {
- // Some filesystems only support 1-second time stamp resolution
- // and will always set Nsec to 0.
- expected.Nsec = 0
- }
- if st.Mtim != expected {
- t.Errorf("UtimesNanoAt: wrong mtime: expected %v, got %v", expected, st.Mtim)
- }
-}
-
-func TestRlimitAs(t *testing.T) {
- // disable GC during to avoid flaky test
- defer debug.SetGCPercent(debug.SetGCPercent(-1))
-
- var rlim unix.Rlimit
- err := unix.Getrlimit(unix.RLIMIT_AS, &rlim)
- if err != nil {
- t.Fatalf("Getrlimit: %v", err)
- }
- var zero unix.Rlimit
- if zero == rlim {
- t.Fatalf("Getrlimit: got zero value %#v", rlim)
- }
- set := rlim
- set.Cur = uint64(unix.Getpagesize())
- err = unix.Setrlimit(unix.RLIMIT_AS, &set)
- if err != nil {
- t.Fatalf("Setrlimit: set failed: %#v %v", set, err)
- }
-
- // RLIMIT_AS was set to the page size, so mmap()'ing twice the page size
- // should fail. See 'man 2 getrlimit'.
- _, err = unix.Mmap(-1, 0, 2*unix.Getpagesize(), unix.PROT_NONE, unix.MAP_ANON|unix.MAP_PRIVATE)
- if err == nil {
- t.Fatal("Mmap: unexpectedly suceeded after setting RLIMIT_AS")
- }
-
- err = unix.Setrlimit(unix.RLIMIT_AS, &rlim)
- if err != nil {
- t.Fatalf("Setrlimit: restore failed: %#v %v", rlim, err)
- }
-
- b, err := unix.Mmap(-1, 0, 2*unix.Getpagesize(), unix.PROT_NONE, unix.MAP_ANON|unix.MAP_PRIVATE)
- if err != nil {
- t.Fatalf("Mmap: %v", err)
- }
- err = unix.Munmap(b)
- if err != nil {
- t.Fatalf("Munmap: %v", err)
- }
-}
-
-func TestSelect(t *testing.T) {
- _, err := unix.Select(0, nil, nil, nil, &unix.Timeval{Sec: 0, Usec: 0})
- if err != nil {
- t.Fatalf("Select: %v", err)
- }
-
- dur := 150 * time.Millisecond
- tv := unix.NsecToTimeval(int64(dur))
- start := time.Now()
- _, err = unix.Select(0, nil, nil, nil, &tv)
- took := time.Since(start)
- if err != nil {
- t.Fatalf("Select: %v", err)
- }
-
- if took < dur {
- t.Errorf("Select: timeout should have been at least %v, got %v", dur, took)
- }
-}
-
-func TestPselect(t *testing.T) {
- _, err := unix.Pselect(0, nil, nil, nil, &unix.Timespec{Sec: 0, Nsec: 0}, nil)
- if err != nil {
- t.Fatalf("Pselect: %v", err)
- }
-
- dur := 2500 * time.Microsecond
- ts := unix.NsecToTimespec(int64(dur))
- start := time.Now()
- _, err = unix.Pselect(0, nil, nil, nil, &ts, nil)
- took := time.Since(start)
- if err != nil {
- t.Fatalf("Pselect: %v", err)
- }
-
- if took < dur {
- t.Errorf("Pselect: timeout should have been at least %v, got %v", dur, took)
- }
-}
-
-func TestSchedSetaffinity(t *testing.T) {
- runtime.LockOSThread()
- defer runtime.UnlockOSThread()
-
- var oldMask unix.CPUSet
- err := unix.SchedGetaffinity(0, &oldMask)
- if err != nil {
- t.Fatalf("SchedGetaffinity: %v", err)
- }
-
- var newMask unix.CPUSet
- newMask.Zero()
- if newMask.Count() != 0 {
- t.Errorf("CpuZero: didn't zero CPU set: %v", newMask)
- }
- cpu := 1
- newMask.Set(cpu)
- if newMask.Count() != 1 || !newMask.IsSet(cpu) {
- t.Errorf("CpuSet: didn't set CPU %d in set: %v", cpu, newMask)
- }
- cpu = 5
- newMask.Set(cpu)
- if newMask.Count() != 2 || !newMask.IsSet(cpu) {
- t.Errorf("CpuSet: didn't set CPU %d in set: %v", cpu, newMask)
- }
- newMask.Clear(cpu)
- if newMask.Count() != 1 || newMask.IsSet(cpu) {
- t.Errorf("CpuClr: didn't clear CPU %d in set: %v", cpu, newMask)
- }
-
- if runtime.NumCPU() < 2 {
- t.Skip("skipping setaffinity tests on single CPU system")
- }
- if runtime.GOOS == "android" {
- t.Skip("skipping setaffinity tests on android")
- }
-
- err = unix.SchedSetaffinity(0, &newMask)
- if err != nil {
- t.Fatalf("SchedSetaffinity: %v", err)
- }
-
- var gotMask unix.CPUSet
- err = unix.SchedGetaffinity(0, &gotMask)
- if err != nil {
- t.Fatalf("SchedGetaffinity: %v", err)
- }
-
- if gotMask != newMask {
- t.Errorf("SchedSetaffinity: returned affinity mask does not match set affinity mask")
- }
-
- // Restore old mask so it doesn't affect successive tests
- err = unix.SchedSetaffinity(0, &oldMask)
- if err != nil {
- t.Fatalf("SchedSetaffinity: %v", err)
- }
-}
-
-func TestStatx(t *testing.T) {
- var stx unix.Statx_t
- err := unix.Statx(unix.AT_FDCWD, ".", 0, 0, &stx)
- if err == unix.ENOSYS || err == unix.EPERM {
- t.Skip("statx syscall is not available, skipping test")
- } else if err != nil {
- t.Fatalf("Statx: %v", err)
- }
-
- defer chtmpdir(t)()
- touch(t, "file1")
-
- var st unix.Stat_t
- err = unix.Stat("file1", &st)
- if err != nil {
- t.Fatalf("Stat: %v", err)
- }
-
- flags := unix.AT_STATX_SYNC_AS_STAT
- err = unix.Statx(unix.AT_FDCWD, "file1", flags, unix.STATX_ALL, &stx)
- if err != nil {
- t.Fatalf("Statx: %v", err)
- }
-
- if uint32(stx.Mode) != st.Mode {
- t.Errorf("Statx: returned stat mode does not match Stat")
- }
-
- ctime := unix.StatxTimestamp{Sec: int64(st.Ctim.Sec), Nsec: uint32(st.Ctim.Nsec)}
- mtime := unix.StatxTimestamp{Sec: int64(st.Mtim.Sec), Nsec: uint32(st.Mtim.Nsec)}
-
- if stx.Ctime != ctime {
- t.Errorf("Statx: returned stat ctime does not match Stat")
- }
- if stx.Mtime != mtime {
- t.Errorf("Statx: returned stat mtime does not match Stat")
- }
-
- err = os.Symlink("file1", "symlink1")
- if err != nil {
- t.Fatal(err)
- }
-
- err = unix.Lstat("symlink1", &st)
- if err != nil {
- t.Fatalf("Lstat: %v", err)
- }
-
- err = unix.Statx(unix.AT_FDCWD, "symlink1", flags, unix.STATX_BASIC_STATS, &stx)
- if err != nil {
- t.Fatalf("Statx: %v", err)
- }
-
- // follow symlink, expect a regulat file
- if stx.Mode&unix.S_IFREG == 0 {
- t.Errorf("Statx: didn't follow symlink")
- }
-
- err = unix.Statx(unix.AT_FDCWD, "symlink1", flags|unix.AT_SYMLINK_NOFOLLOW, unix.STATX_ALL, &stx)
- if err != nil {
- t.Fatalf("Statx: %v", err)
- }
-
- // follow symlink, expect a symlink
- if stx.Mode&unix.S_IFLNK == 0 {
- t.Errorf("Statx: unexpectedly followed symlink")
- }
- if uint32(stx.Mode) != st.Mode {
- t.Errorf("Statx: returned stat mode does not match Lstat")
- }
-
- ctime = unix.StatxTimestamp{Sec: int64(st.Ctim.Sec), Nsec: uint32(st.Ctim.Nsec)}
- mtime = unix.StatxTimestamp{Sec: int64(st.Mtim.Sec), Nsec: uint32(st.Mtim.Nsec)}
-
- if stx.Ctime != ctime {
- t.Errorf("Statx: returned stat ctime does not match Lstat")
- }
- if stx.Mtime != mtime {
- t.Errorf("Statx: returned stat mtime does not match Lstat")
- }
-}
-
-// stringsFromByteSlice converts a sequence of attributes to a []string.
-// On Linux, each entry is a NULL-terminated string.
-func stringsFromByteSlice(buf []byte) []string {
- var result []string
- off := 0
- for i, b := range buf {
- if b == 0 {
- result = append(result, string(buf[off:i]))
- off = i + 1
- }
- }
- return result
-}
-
-func TestFaccessat(t *testing.T) {
- defer chtmpdir(t)()
- touch(t, "file1")
-
- err := unix.Faccessat(unix.AT_FDCWD, "file1", unix.O_RDONLY, 0)
- if err != nil {
- t.Errorf("Faccessat: unexpected error: %v", err)
- }
-
- err = unix.Faccessat(unix.AT_FDCWD, "file1", unix.O_RDONLY, 2)
- if err != unix.EINVAL {
- t.Errorf("Faccessat: unexpected error: %v, want EINVAL", err)
- }
-
- err = unix.Faccessat(unix.AT_FDCWD, "file1", unix.O_RDONLY, unix.AT_EACCESS)
- if err != unix.EOPNOTSUPP {
- t.Errorf("Faccessat: unexpected error: %v, want EOPNOTSUPP", err)
- }
-
- err = os.Symlink("file1", "symlink1")
- if err != nil {
- t.Fatal(err)
- }
-
- err = unix.Faccessat(unix.AT_FDCWD, "symlink1", unix.O_RDONLY, unix.AT_SYMLINK_NOFOLLOW)
- if err != unix.EOPNOTSUPP {
- t.Errorf("Faccessat: unexpected error: %v, want EOPNOTSUPP", err)
- }
-}
diff --git a/cmd/viewcore/vendor/golang.org/x/sys/unix/syscall_solaris.go b/cmd/viewcore/vendor/golang.org/x/sys/unix/syscall_solaris.go
index 4d7efbc..820ef77 100644
--- a/cmd/viewcore/vendor/golang.org/x/sys/unix/syscall_solaris.go
+++ b/cmd/viewcore/vendor/golang.org/x/sys/unix/syscall_solaris.go
@@ -314,7 +314,11 @@
// FcntlInt performs a fcntl syscall on fd with the provided command and argument.
func FcntlInt(fd uintptr, cmd, arg int) (int, error) {
- valptr, _, err := sysvicall6(uintptr(unsafe.Pointer(&procfcntl)), 3, uintptr(fd), uintptr(cmd), uintptr(arg), 0, 0, 0)
+ valptr, _, errno := sysvicall6(uintptr(unsafe.Pointer(&procfcntl)), 3, uintptr(fd), uintptr(cmd), uintptr(arg), 0, 0, 0)
+ var err error
+ if errno != 0 {
+ err = errno
+ }
return int(valptr), err
}
diff --git a/cmd/viewcore/vendor/golang.org/x/sys/unix/syscall_solaris_test.go b/cmd/viewcore/vendor/golang.org/x/sys/unix/syscall_solaris_test.go
deleted file mode 100644
index 57dba88..0000000
--- a/cmd/viewcore/vendor/golang.org/x/sys/unix/syscall_solaris_test.go
+++ /dev/null
@@ -1,55 +0,0 @@
-// Copyright 2017 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.
-
-// +build solaris
-
-package unix_test
-
-import (
- "os/exec"
- "testing"
- "time"
-
- "golang.org/x/sys/unix"
-)
-
-func TestSelect(t *testing.T) {
- err := unix.Select(0, nil, nil, nil, &unix.Timeval{Sec: 0, Usec: 0})
- if err != nil {
- t.Fatalf("Select: %v", err)
- }
-
- dur := 150 * time.Millisecond
- tv := unix.NsecToTimeval(int64(dur))
- start := time.Now()
- err = unix.Select(0, nil, nil, nil, &tv)
- took := time.Since(start)
- if err != nil {
- t.Fatalf("Select: %v", err)
- }
-
- if took < dur {
- t.Errorf("Select: timeout should have been at least %v, got %v", dur, took)
- }
-}
-
-func TestStatvfs(t *testing.T) {
- if err := unix.Statvfs("", nil); err == nil {
- t.Fatal(`Statvfs("") expected failure`)
- }
-
- statvfs := unix.Statvfs_t{}
- if err := unix.Statvfs("/", &statvfs); err != nil {
- t.Errorf(`Statvfs("/") failed: %v`, err)
- }
-
- if t.Failed() {
- mount, err := exec.Command("mount").CombinedOutput()
- if err != nil {
- t.Logf("mount: %v\n%s", err, mount)
- } else {
- t.Logf("mount: %s", mount)
- }
- }
-}
diff --git a/cmd/viewcore/vendor/golang.org/x/sys/unix/syscall_test.go b/cmd/viewcore/vendor/golang.org/x/sys/unix/syscall_test.go
deleted file mode 100644
index a8eef7c..0000000
--- a/cmd/viewcore/vendor/golang.org/x/sys/unix/syscall_test.go
+++ /dev/null
@@ -1,60 +0,0 @@
-// Copyright 2013 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.
-
-// +build darwin dragonfly freebsd linux netbsd openbsd solaris
-
-package unix_test
-
-import (
- "fmt"
- "testing"
-
- "golang.org/x/sys/unix"
-)
-
-func testSetGetenv(t *testing.T, key, value string) {
- err := unix.Setenv(key, value)
- if err != nil {
- t.Fatalf("Setenv failed to set %q: %v", value, err)
- }
- newvalue, found := unix.Getenv(key)
- if !found {
- t.Fatalf("Getenv failed to find %v variable (want value %q)", key, value)
- }
- if newvalue != value {
- t.Fatalf("Getenv(%v) = %q; want %q", key, newvalue, value)
- }
-}
-
-func TestEnv(t *testing.T) {
- testSetGetenv(t, "TESTENV", "AVALUE")
- // make sure TESTENV gets set to "", not deleted
- testSetGetenv(t, "TESTENV", "")
-}
-
-func TestItoa(t *testing.T) {
- // Make most negative integer: 0x8000...
- i := 1
- for i<<1 != 0 {
- i <<= 1
- }
- if i >= 0 {
- t.Fatal("bad math")
- }
- s := unix.Itoa(i)
- f := fmt.Sprint(i)
- if s != f {
- t.Fatalf("itoa(%d) = %s, want %s", i, s, f)
- }
-}
-
-func TestUname(t *testing.T) {
- var utsname unix.Utsname
- err := unix.Uname(&utsname)
- if err != nil {
- t.Fatalf("Uname: %v", err)
- }
-
- t.Logf("OS: %s/%s %s", utsname.Sysname[:], utsname.Machine[:], utsname.Release[:])
-}
diff --git a/cmd/viewcore/vendor/golang.org/x/sys/unix/syscall_unix_test.go b/cmd/viewcore/vendor/golang.org/x/sys/unix/syscall_unix_test.go
deleted file mode 100644
index ad09716..0000000
--- a/cmd/viewcore/vendor/golang.org/x/sys/unix/syscall_unix_test.go
+++ /dev/null
@@ -1,639 +0,0 @@
-// Copyright 2013 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.
-
-// +build darwin dragonfly freebsd linux netbsd openbsd solaris
-
-package unix_test
-
-import (
- "flag"
- "fmt"
- "io/ioutil"
- "net"
- "os"
- "os/exec"
- "path/filepath"
- "runtime"
- "syscall"
- "testing"
- "time"
-
- "golang.org/x/sys/unix"
-)
-
-// Tests that below functions, structures and constants are consistent
-// on all Unix-like systems.
-func _() {
- // program scheduling priority functions and constants
- var (
- _ func(int, int, int) error = unix.Setpriority
- _ func(int, int) (int, error) = unix.Getpriority
- )
- const (
- _ int = unix.PRIO_USER
- _ int = unix.PRIO_PROCESS
- _ int = unix.PRIO_PGRP
- )
-
- // termios constants
- const (
- _ int = unix.TCIFLUSH
- _ int = unix.TCIOFLUSH
- _ int = unix.TCOFLUSH
- )
-
- // fcntl file locking structure and constants
- var (
- _ = unix.Flock_t{
- Type: int16(0),
- Whence: int16(0),
- Start: int64(0),
- Len: int64(0),
- Pid: int32(0),
- }
- )
- const (
- _ = unix.F_GETLK
- _ = unix.F_SETLK
- _ = unix.F_SETLKW
- )
-}
-
-func TestErrnoSignalName(t *testing.T) {
- testErrors := []struct {
- num syscall.Errno
- name string
- }{
- {syscall.EPERM, "EPERM"},
- {syscall.EINVAL, "EINVAL"},
- {syscall.ENOENT, "ENOENT"},
- }
-
- for _, te := range testErrors {
- t.Run(fmt.Sprintf("%d/%s", te.num, te.name), func(t *testing.T) {
- e := unix.ErrnoName(te.num)
- if e != te.name {
- t.Errorf("ErrnoName(%d) returned %s, want %s", te.num, e, te.name)
- }
- })
- }
-
- testSignals := []struct {
- num syscall.Signal
- name string
- }{
- {syscall.SIGHUP, "SIGHUP"},
- {syscall.SIGPIPE, "SIGPIPE"},
- {syscall.SIGSEGV, "SIGSEGV"},
- }
-
- for _, ts := range testSignals {
- t.Run(fmt.Sprintf("%d/%s", ts.num, ts.name), func(t *testing.T) {
- s := unix.SignalName(ts.num)
- if s != ts.name {
- t.Errorf("SignalName(%d) returned %s, want %s", ts.num, s, ts.name)
- }
- })
- }
-}
-
-// TestFcntlFlock tests whether the file locking structure matches
-// the calling convention of each kernel.
-func TestFcntlFlock(t *testing.T) {
- name := filepath.Join(os.TempDir(), "TestFcntlFlock")
- fd, err := unix.Open(name, unix.O_CREAT|unix.O_RDWR|unix.O_CLOEXEC, 0)
- if err != nil {
- t.Fatalf("Open failed: %v", err)
- }
- defer unix.Unlink(name)
- defer unix.Close(fd)
- flock := unix.Flock_t{
- Type: unix.F_RDLCK,
- Start: 0, Len: 0, Whence: 1,
- }
- if err := unix.FcntlFlock(uintptr(fd), unix.F_GETLK, &flock); err != nil {
- t.Fatalf("FcntlFlock failed: %v", err)
- }
-}
-
-// TestPassFD tests passing a file descriptor over a Unix socket.
-//
-// This test involved both a parent and child process. The parent
-// process is invoked as a normal test, with "go test", which then
-// runs the child process by running the current test binary with args
-// "-test.run=^TestPassFD$" and an environment variable used to signal
-// that the test should become the child process instead.
-func TestPassFD(t *testing.T) {
- if runtime.GOOS == "darwin" && (runtime.GOARCH == "arm" || runtime.GOARCH == "arm64") {
- t.Skip("cannot exec subprocess on iOS, skipping test")
- }
-
- if os.Getenv("GO_WANT_HELPER_PROCESS") == "1" {
- passFDChild()
- return
- }
-
- tempDir, err := ioutil.TempDir("", "TestPassFD")
- if err != nil {
- t.Fatal(err)
- }
- defer os.RemoveAll(tempDir)
-
- fds, err := unix.Socketpair(unix.AF_LOCAL, unix.SOCK_STREAM, 0)
- if err != nil {
- t.Fatalf("Socketpair: %v", err)
- }
- defer unix.Close(fds[0])
- defer unix.Close(fds[1])
- writeFile := os.NewFile(uintptr(fds[0]), "child-writes")
- readFile := os.NewFile(uintptr(fds[1]), "parent-reads")
- defer writeFile.Close()
- defer readFile.Close()
-
- cmd := exec.Command(os.Args[0], "-test.run=^TestPassFD$", "--", tempDir)
- cmd.Env = []string{"GO_WANT_HELPER_PROCESS=1"}
- if lp := os.Getenv("LD_LIBRARY_PATH"); lp != "" {
- cmd.Env = append(cmd.Env, "LD_LIBRARY_PATH="+lp)
- }
- cmd.ExtraFiles = []*os.File{writeFile}
-
- out, err := cmd.CombinedOutput()
- if len(out) > 0 || err != nil {
- t.Fatalf("child process: %q, %v", out, err)
- }
-
- c, err := net.FileConn(readFile)
- if err != nil {
- t.Fatalf("FileConn: %v", err)
- }
- defer c.Close()
-
- uc, ok := c.(*net.UnixConn)
- if !ok {
- t.Fatalf("unexpected FileConn type; expected UnixConn, got %T", c)
- }
-
- buf := make([]byte, 32) // expect 1 byte
- oob := make([]byte, 32) // expect 24 bytes
- closeUnix := time.AfterFunc(5*time.Second, func() {
- t.Logf("timeout reading from unix socket")
- uc.Close()
- })
- _, oobn, _, _, err := uc.ReadMsgUnix(buf, oob)
- if err != nil {
- t.Fatalf("ReadMsgUnix: %v", err)
- }
- closeUnix.Stop()
-
- scms, err := unix.ParseSocketControlMessage(oob[:oobn])
- if err != nil {
- t.Fatalf("ParseSocketControlMessage: %v", err)
- }
- if len(scms) != 1 {
- t.Fatalf("expected 1 SocketControlMessage; got scms = %#v", scms)
- }
- scm := scms[0]
- gotFds, err := unix.ParseUnixRights(&scm)
- if err != nil {
- t.Fatalf("unix.ParseUnixRights: %v", err)
- }
- if len(gotFds) != 1 {
- t.Fatalf("wanted 1 fd; got %#v", gotFds)
- }
-
- f := os.NewFile(uintptr(gotFds[0]), "fd-from-child")
- defer f.Close()
-
- got, err := ioutil.ReadAll(f)
- want := "Hello from child process!\n"
- if string(got) != want {
- t.Errorf("child process ReadAll: %q, %v; want %q", got, err, want)
- }
-}
-
-// passFDChild is the child process used by TestPassFD.
-func passFDChild() {
- defer os.Exit(0)
-
- // Look for our fd. It should be fd 3, but we work around an fd leak
- // bug here (http://golang.org/issue/2603) to let it be elsewhere.
- var uc *net.UnixConn
- for fd := uintptr(3); fd <= 10; fd++ {
- f := os.NewFile(fd, "unix-conn")
- var ok bool
- netc, _ := net.FileConn(f)
- uc, ok = netc.(*net.UnixConn)
- if ok {
- break
- }
- }
- if uc == nil {
- fmt.Println("failed to find unix fd")
- return
- }
-
- // Make a file f to send to our parent process on uc.
- // We make it in tempDir, which our parent will clean up.
- flag.Parse()
- tempDir := flag.Arg(0)
- f, err := ioutil.TempFile(tempDir, "")
- if err != nil {
- fmt.Printf("TempFile: %v", err)
- return
- }
-
- f.Write([]byte("Hello from child process!\n"))
- f.Seek(0, 0)
-
- rights := unix.UnixRights(int(f.Fd()))
- dummyByte := []byte("x")
- n, oobn, err := uc.WriteMsgUnix(dummyByte, rights, nil)
- if err != nil {
- fmt.Printf("WriteMsgUnix: %v", err)
- return
- }
- if n != 1 || oobn != len(rights) {
- fmt.Printf("WriteMsgUnix = %d, %d; want 1, %d", n, oobn, len(rights))
- return
- }
-}
-
-// TestUnixRightsRoundtrip tests that UnixRights, ParseSocketControlMessage,
-// and ParseUnixRights are able to successfully round-trip lists of file descriptors.
-func TestUnixRightsRoundtrip(t *testing.T) {
- testCases := [...][][]int{
- {{42}},
- {{1, 2}},
- {{3, 4, 5}},
- {{}},
- {{1, 2}, {3, 4, 5}, {}, {7}},
- }
- for _, testCase := range testCases {
- b := []byte{}
- var n int
- for _, fds := range testCase {
- // Last assignment to n wins
- n = len(b) + unix.CmsgLen(4*len(fds))
- b = append(b, unix.UnixRights(fds...)...)
- }
- // Truncate b
- b = b[:n]
-
- scms, err := unix.ParseSocketControlMessage(b)
- if err != nil {
- t.Fatalf("ParseSocketControlMessage: %v", err)
- }
- if len(scms) != len(testCase) {
- t.Fatalf("expected %v SocketControlMessage; got scms = %#v", len(testCase), scms)
- }
- for i, scm := range scms {
- gotFds, err := unix.ParseUnixRights(&scm)
- if err != nil {
- t.Fatalf("ParseUnixRights: %v", err)
- }
- wantFds := testCase[i]
- if len(gotFds) != len(wantFds) {
- t.Fatalf("expected %v fds, got %#v", len(wantFds), gotFds)
- }
- for j, fd := range gotFds {
- if fd != wantFds[j] {
- t.Fatalf("expected fd %v, got %v", wantFds[j], fd)
- }
- }
- }
- }
-}
-
-func TestRlimit(t *testing.T) {
- var rlimit, zero unix.Rlimit
- err := unix.Getrlimit(unix.RLIMIT_NOFILE, &rlimit)
- if err != nil {
- t.Fatalf("Getrlimit: save failed: %v", err)
- }
- if zero == rlimit {
- t.Fatalf("Getrlimit: save failed: got zero value %#v", rlimit)
- }
- set := rlimit
- set.Cur = set.Max - 1
- err = unix.Setrlimit(unix.RLIMIT_NOFILE, &set)
- if err != nil {
- t.Fatalf("Setrlimit: set failed: %#v %v", set, err)
- }
- var get unix.Rlimit
- err = unix.Getrlimit(unix.RLIMIT_NOFILE, &get)
- if err != nil {
- t.Fatalf("Getrlimit: get failed: %v", err)
- }
- set = rlimit
- set.Cur = set.Max - 1
- if set != get {
- // Seems like Darwin requires some privilege to
- // increase the soft limit of rlimit sandbox, though
- // Setrlimit never reports an error.
- switch runtime.GOOS {
- case "darwin":
- default:
- t.Fatalf("Rlimit: change failed: wanted %#v got %#v", set, get)
- }
- }
- err = unix.Setrlimit(unix.RLIMIT_NOFILE, &rlimit)
- if err != nil {
- t.Fatalf("Setrlimit: restore failed: %#v %v", rlimit, err)
- }
-}
-
-func TestSeekFailure(t *testing.T) {
- _, err := unix.Seek(-1, 0, 0)
- if err == nil {
- t.Fatalf("Seek(-1, 0, 0) did not fail")
- }
- str := err.Error() // used to crash on Linux
- t.Logf("Seek: %v", str)
- if str == "" {
- t.Fatalf("Seek(-1, 0, 0) return error with empty message")
- }
-}
-
-func TestDup(t *testing.T) {
- file, err := ioutil.TempFile("", "TestDup")
- if err != nil {
- t.Fatalf("Tempfile failed: %v", err)
- }
- defer os.Remove(file.Name())
- defer file.Close()
- f := int(file.Fd())
-
- newFd, err := unix.Dup(f)
- if err != nil {
- t.Fatalf("Dup: %v", err)
- }
-
- err = unix.Dup2(newFd, newFd+1)
- if err != nil {
- t.Fatalf("Dup2: %v", err)
- }
-
- b1 := []byte("Test123")
- b2 := make([]byte, 7)
- _, err = unix.Write(newFd+1, b1)
- if err != nil {
- t.Fatalf("Write to dup2 fd failed: %v", err)
- }
- _, err = unix.Seek(f, 0, 0)
- if err != nil {
- t.Fatalf("Seek failed: %v", err)
- }
- _, err = unix.Read(f, b2)
- if err != nil {
- t.Fatalf("Read back failed: %v", err)
- }
- if string(b1) != string(b2) {
- t.Errorf("Dup: stdout write not in file, expected %v, got %v", string(b1), string(b2))
- }
-}
-
-func TestPoll(t *testing.T) {
- if runtime.GOOS == "android" ||
- (runtime.GOOS == "darwin" && (runtime.GOARCH == "arm" || runtime.GOARCH == "arm64")) {
- t.Skip("mkfifo syscall is not available on android and iOS, skipping test")
- }
-
- f, cleanup := mktmpfifo(t)
- defer cleanup()
-
- const timeout = 100
-
- ok := make(chan bool, 1)
- go func() {
- select {
- case <-time.After(10 * timeout * time.Millisecond):
- t.Errorf("Poll: failed to timeout after %d milliseconds", 10*timeout)
- case <-ok:
- }
- }()
-
- fds := []unix.PollFd{{Fd: int32(f.Fd()), Events: unix.POLLIN}}
- n, err := unix.Poll(fds, timeout)
- ok <- true
- if err != nil {
- t.Errorf("Poll: unexpected error: %v", err)
- return
- }
- if n != 0 {
- t.Errorf("Poll: wrong number of events: got %v, expected %v", n, 0)
- return
- }
-}
-
-func TestGetwd(t *testing.T) {
- fd, err := os.Open(".")
- if err != nil {
- t.Fatalf("Open .: %s", err)
- }
- defer fd.Close()
- // These are chosen carefully not to be symlinks on a Mac
- // (unlike, say, /var, /etc)
- dirs := []string{"/", "/usr/bin"}
- switch runtime.GOOS {
- case "android":
- dirs = []string{"/", "/system/bin"}
- case "darwin":
- switch runtime.GOARCH {
- case "arm", "arm64":
- d1, err := ioutil.TempDir("", "d1")
- if err != nil {
- t.Fatalf("TempDir: %v", err)
- }
- d2, err := ioutil.TempDir("", "d2")
- if err != nil {
- t.Fatalf("TempDir: %v", err)
- }
- dirs = []string{d1, d2}
- }
- }
- oldwd := os.Getenv("PWD")
- for _, d := range dirs {
- err = os.Chdir(d)
- if err != nil {
- t.Fatalf("Chdir: %v", err)
- }
- pwd, err := unix.Getwd()
- if err != nil {
- t.Fatalf("Getwd in %s: %s", d, err)
- }
- os.Setenv("PWD", oldwd)
- err = fd.Chdir()
- if err != nil {
- // We changed the current directory and cannot go back.
- // Don't let the tests continue; they'll scribble
- // all over some other directory.
- fmt.Fprintf(os.Stderr, "fchdir back to dot failed: %s\n", err)
- os.Exit(1)
- }
- if pwd != d {
- t.Fatalf("Getwd returned %q want %q", pwd, d)
- }
- }
-}
-
-func TestFstatat(t *testing.T) {
- defer chtmpdir(t)()
-
- touch(t, "file1")
-
- var st1 unix.Stat_t
- err := unix.Stat("file1", &st1)
- if err != nil {
- t.Fatalf("Stat: %v", err)
- }
-
- var st2 unix.Stat_t
- err = unix.Fstatat(unix.AT_FDCWD, "file1", &st2, 0)
- if err != nil {
- t.Fatalf("Fstatat: %v", err)
- }
-
- if st1 != st2 {
- t.Errorf("Fstatat: returned stat does not match Stat")
- }
-
- err = os.Symlink("file1", "symlink1")
- if err != nil {
- t.Fatal(err)
- }
-
- err = unix.Lstat("symlink1", &st1)
- if err != nil {
- t.Fatalf("Lstat: %v", err)
- }
-
- err = unix.Fstatat(unix.AT_FDCWD, "symlink1", &st2, unix.AT_SYMLINK_NOFOLLOW)
- if err != nil {
- t.Fatalf("Fstatat: %v", err)
- }
-
- if st1 != st2 {
- t.Errorf("Fstatat: returned stat does not match Lstat")
- }
-}
-
-func TestFchmodat(t *testing.T) {
- defer chtmpdir(t)()
-
- touch(t, "file1")
- err := os.Symlink("file1", "symlink1")
- if err != nil {
- t.Fatal(err)
- }
-
- mode := os.FileMode(0444)
- err = unix.Fchmodat(unix.AT_FDCWD, "symlink1", uint32(mode), 0)
- if err != nil {
- t.Fatalf("Fchmodat: unexpected error: %v", err)
- }
-
- fi, err := os.Stat("file1")
- if err != nil {
- t.Fatal(err)
- }
-
- if fi.Mode() != mode {
- t.Errorf("Fchmodat: failed to change file mode: expected %v, got %v", mode, fi.Mode())
- }
-
- mode = os.FileMode(0644)
- didChmodSymlink := true
- err = unix.Fchmodat(unix.AT_FDCWD, "symlink1", uint32(mode), unix.AT_SYMLINK_NOFOLLOW)
- if err != nil {
- if (runtime.GOOS == "android" || runtime.GOOS == "linux" || runtime.GOOS == "solaris") && err == unix.EOPNOTSUPP {
- // Linux and Illumos don't support flags != 0
- didChmodSymlink = false
- } else {
- t.Fatalf("Fchmodat: unexpected error: %v", err)
- }
- }
-
- if !didChmodSymlink {
- // Didn't change mode of the symlink. On Linux, the permissions
- // of a symbolic link are always 0777 according to symlink(7)
- mode = os.FileMode(0777)
- }
-
- var st unix.Stat_t
- err = unix.Lstat("symlink1", &st)
- if err != nil {
- t.Fatal(err)
- }
-
- got := os.FileMode(st.Mode & 0777)
- if got != mode {
- t.Errorf("Fchmodat: failed to change symlink mode: expected %v, got %v", mode, got)
- }
-}
-
-func TestMkdev(t *testing.T) {
- major := uint32(42)
- minor := uint32(7)
- dev := unix.Mkdev(major, minor)
-
- if unix.Major(dev) != major {
- t.Errorf("Major(%#x) == %d, want %d", dev, unix.Major(dev), major)
- }
- if unix.Minor(dev) != minor {
- t.Errorf("Minor(%#x) == %d, want %d", dev, unix.Minor(dev), minor)
- }
-}
-
-// mktmpfifo creates a temporary FIFO and provides a cleanup function.
-func mktmpfifo(t *testing.T) (*os.File, func()) {
- err := unix.Mkfifo("fifo", 0666)
- if err != nil {
- t.Fatalf("mktmpfifo: failed to create FIFO: %v", err)
- }
-
- f, err := os.OpenFile("fifo", os.O_RDWR, 0666)
- if err != nil {
- os.Remove("fifo")
- t.Fatalf("mktmpfifo: failed to open FIFO: %v", err)
- }
-
- return f, func() {
- f.Close()
- os.Remove("fifo")
- }
-}
-
-// utilities taken from os/os_test.go
-
-func touch(t *testing.T, name string) {
- f, err := os.Create(name)
- if err != nil {
- t.Fatal(err)
- }
- if err := f.Close(); err != nil {
- t.Fatal(err)
- }
-}
-
-// chtmpdir changes the working directory to a new temporary directory and
-// provides a cleanup function. Used when PWD is read-only.
-func chtmpdir(t *testing.T) func() {
- oldwd, err := os.Getwd()
- if err != nil {
- t.Fatalf("chtmpdir: %v", err)
- }
- d, err := ioutil.TempDir("", "test")
- if err != nil {
- t.Fatalf("chtmpdir: %v", err)
- }
- if err := os.Chdir(d); err != nil {
- t.Fatalf("chtmpdir: %v", err)
- }
- return func() {
- if err := os.Chdir(oldwd); err != nil {
- t.Fatalf("chtmpdir: %v", err)
- }
- os.RemoveAll(d)
- }
-}
diff --git a/cmd/viewcore/vendor/golang.org/x/sys/unix/timestruct_test.go b/cmd/viewcore/vendor/golang.org/x/sys/unix/timestruct_test.go
deleted file mode 100644
index 4215f46..0000000
--- a/cmd/viewcore/vendor/golang.org/x/sys/unix/timestruct_test.go
+++ /dev/null
@@ -1,54 +0,0 @@
-// Copyright 2017 The Go Authors. All right reserved.
-// Use of this source code is governed by a BSD-style
-// license that can be found in the LICENSE file.
-
-// +build darwin dragonfly freebsd linux netbsd openbsd solaris
-
-package unix_test
-
-import (
- "testing"
- "time"
- "unsafe"
-
- "golang.org/x/sys/unix"
-)
-
-func TestTimeToTimespec(t *testing.T) {
- timeTests := []struct {
- time time.Time
- valid bool
- }{
- {time.Unix(0, 0), true},
- {time.Date(2009, time.November, 10, 23, 0, 0, 0, time.UTC), true},
- {time.Date(2262, time.December, 31, 23, 0, 0, 0, time.UTC), false},
- {time.Unix(0x7FFFFFFF, 0), true},
- {time.Unix(0x80000000, 0), false},
- {time.Unix(0x7FFFFFFF, 1000000000), false},
- {time.Unix(0x7FFFFFFF, 999999999), true},
- {time.Unix(-0x80000000, 0), true},
- {time.Unix(-0x80000001, 0), false},
- {time.Date(2038, time.January, 19, 3, 14, 7, 0, time.UTC), true},
- {time.Date(2038, time.January, 19, 3, 14, 8, 0, time.UTC), false},
- {time.Date(1901, time.December, 13, 20, 45, 52, 0, time.UTC), true},
- {time.Date(1901, time.December, 13, 20, 45, 51, 0, time.UTC), false},
- }
-
- // Currently all targets have either int32 or int64 for Timespec.Sec.
- // If there were a new target with unsigned or floating point type for
- // it, this test must be adjusted.
- have64BitTime := (unsafe.Sizeof(unix.Timespec{}.Sec) == 8)
- for _, tt := range timeTests {
- ts, err := unix.TimeToTimespec(tt.time)
- tt.valid = tt.valid || have64BitTime
- if tt.valid && err != nil {
- t.Errorf("TimeToTimespec(%v): %v", tt.time, err)
- }
- if err == nil {
- tstime := time.Unix(int64(ts.Sec), int64(ts.Nsec))
- if !tstime.Equal(tt.time) {
- t.Errorf("TimeToTimespec(%v) is the time %v", tt.time, tstime)
- }
- }
- }
-}
diff --git a/cmd/viewcore/vendor/golang.org/x/sys/unix/xattr_test.go b/cmd/viewcore/vendor/golang.org/x/sys/unix/xattr_test.go
deleted file mode 100644
index b8b28d0..0000000
--- a/cmd/viewcore/vendor/golang.org/x/sys/unix/xattr_test.go
+++ /dev/null
@@ -1,119 +0,0 @@
-// Copyright 2018 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.
-
-// +build darwin freebsd linux
-
-package unix_test
-
-import (
- "os"
- "runtime"
- "strings"
- "testing"
-
- "golang.org/x/sys/unix"
-)
-
-func TestXattr(t *testing.T) {
- defer chtmpdir(t)()
-
- f := "xattr1"
- touch(t, f)
-
- xattrName := "user.test"
- xattrDataSet := "gopher"
- err := unix.Setxattr(f, xattrName, []byte(xattrDataSet), 0)
- if err == unix.ENOTSUP || err == unix.EOPNOTSUPP {
- t.Skip("filesystem does not support extended attributes, skipping test")
- } else if err != nil {
- t.Fatalf("Setxattr: %v", err)
- }
-
- // find size
- size, err := unix.Listxattr(f, nil)
- if err != nil {
- t.Fatalf("Listxattr: %v", err)
- }
-
- if size <= 0 {
- t.Fatalf("Listxattr returned an empty list of attributes")
- }
-
- buf := make([]byte, size)
- read, err := unix.Listxattr(f, buf)
- if err != nil {
- t.Fatalf("Listxattr: %v", err)
- }
-
- xattrs := stringsFromByteSlice(buf[:read])
-
- xattrWant := xattrName
- if runtime.GOOS == "freebsd" {
- // On FreeBSD, the namespace is stored separately from the xattr
- // name and Listxattr doesn't return the namespace prefix.
- xattrWant = strings.TrimPrefix(xattrWant, "user.")
- }
- found := false
- for _, name := range xattrs {
- if name == xattrWant {
- found = true
- }
- }
-
- if !found {
- t.Errorf("Listxattr did not return previously set attribute '%s'", xattrName)
- }
-
- // find size
- size, err = unix.Getxattr(f, xattrName, nil)
- if err != nil {
- t.Fatalf("Getxattr: %v", err)
- }
-
- if size <= 0 {
- t.Fatalf("Getxattr returned an empty attribute")
- }
-
- xattrDataGet := make([]byte, size)
- _, err = unix.Getxattr(f, xattrName, xattrDataGet)
- if err != nil {
- t.Fatalf("Getxattr: %v", err)
- }
-
- got := string(xattrDataGet)
- if got != xattrDataSet {
- t.Errorf("Getxattr: expected attribute value %s, got %s", xattrDataSet, got)
- }
-
- err = unix.Removexattr(f, xattrName)
- if err != nil {
- t.Fatalf("Removexattr: %v", err)
- }
-
- n := "nonexistent"
- err = unix.Lsetxattr(n, xattrName, []byte(xattrDataSet), 0)
- if err != unix.ENOENT {
- t.Errorf("Lsetxattr: expected %v on non-existent file, got %v", unix.ENOENT, err)
- }
-
- _, err = unix.Lgetxattr(n, xattrName, nil)
- if err != unix.ENOENT {
- t.Errorf("Lgetxattr: %v", err)
- }
-
- s := "symlink1"
- err = os.Symlink(n, s)
- if err != nil {
- t.Fatal(err)
- }
-
- err = unix.Lsetxattr(s, xattrName, []byte(xattrDataSet), 0)
- if err != nil {
- // Linux and Android doen't support xattrs on symlinks according
- // to xattr(7), so just test that we get the proper error.
- if (runtime.GOOS != "linux" && runtime.GOOS != "android") || err != unix.EPERM {
- t.Fatalf("Lsetxattr: %v", err)
- }
- }
-}
diff --git a/cmd/viewcore/vendor/vendor.json b/cmd/viewcore/vendor/vendor.json
index 229db5a..f42e20c 100644
--- a/cmd/viewcore/vendor/vendor.json
+++ b/cmd/viewcore/vendor/vendor.json
@@ -1,48 +1,36 @@
{
"comment": "",
- "ignore": "",
+ "ignore": "test",
"package": [
{
- "checksumSHA1": "pccX+tLMoPXwqW6wFXOHQxq23eU=",
- "path": "github.com/chzyer/logex",
- "revision": "445be9e134b204a8c920a30fedad02b2f2ab1efd",
- "revisionTime": "2017-03-29T06:48:20Z"
- },
- {
- "checksumSHA1": "R/zioKKcEGi2axgzZMdBhWugP+E=",
+ "checksumSHA1": "cJ/yTXO11AXO9FJaVKcL78x6LyU=",
"path": "github.com/chzyer/readline",
"revision": "2972be24d48e78746da79ba8e24e8b488c9880de",
"revisionTime": "2018-06-03T13:26:55Z"
},
{
- "checksumSHA1": "dFr+xfpmqeLbtAbZUGxIpPuo7Kc=",
- "path": "github.com/chzyer/test",
- "revision": "a1ea475d72b168a29f44221e0ad031a842642302",
- "revisionTime": "2018-02-12T23:58:34Z"
- },
- {
"checksumSHA1": "40vJyUB4ezQSn/NSadsKEOrudMc=",
"path": "github.com/inconshreveable/mousetrap",
"revision": "76626ae9c91c4f2a10f34cad8ce83ea42c93bb75",
"revisionTime": "2014-10-17T20:07:13Z"
},
{
- "checksumSHA1": "D7hWCay3XKO5RjeVj7C1ACkHk6s=",
+ "checksumSHA1": "Xnlls27MEcxIHhpRdsiUa2BqcFk=",
"path": "github.com/spf13/cobra",
- "revision": "ef82de70bb3f60c65fb8eebacbb2d122ef517385",
- "revisionTime": "2018-04-27T13:45:50Z"
+ "revision": "1e58aa3361fd650121dceeedc399e7189c05674a",
+ "revisionTime": "2018-05-31T18:03:38Z"
},
{
- "checksumSHA1": "fTUB2LRINzrW2q0Wp5h9VILSu6A=",
+ "checksumSHA1": "OJI0OgC5V8gZtfS1e0CDYMhkDNc=",
"path": "github.com/spf13/pflag",
- "revision": "583c0c0531f06d5278b7d917446061adc344b5cd",
- "revisionTime": "2018-04-12T12:09:13Z"
+ "revision": "3ebe029320b2676d667ae88da602a5f854788a8a",
+ "revisionTime": "2018-06-01T13:25:42Z"
},
{
- "checksumSHA1": "fQRmHeOLiQ/Lbklrl9BfevodvEM=",
+ "checksumSHA1": "e66DmNWQKgI97tvj4BH7rHYnyJs=",
"path": "golang.org/x/sys/unix",
- "revision": "c4afb3effaa53fd9a06ca61262dc7ce8df4c081b",
- "revisionTime": "2018-06-26T06:41:42Z"
+ "revision": "7138fd3d9dc8335c567ca206f4333fb75eb05d56",
+ "revisionTime": "2018-06-27T13:57:12Z"
}
],
"rootPath": "golang.org/x/debug/cmd/viewcore"