Depenancy upgrades and movign to dep. (#8630)
Этот коммит содержится в:
коммит произвёл
Joram Wilander
родитель
bf24f51c4e
Коммит
6e2cb00008
2
vendor/github.com/spf13/afero/.travis.yml
сгенерированный
поставляемый
2
vendor/github.com/spf13/afero/.travis.yml
сгенерированный
поставляемый
@@ -2,8 +2,8 @@ sudo: false
|
||||
language: go
|
||||
|
||||
go:
|
||||
- 1.8
|
||||
- 1.9
|
||||
- "1.10"
|
||||
- tip
|
||||
|
||||
os:
|
||||
|
||||
699
vendor/github.com/spf13/afero/afero_test.go
сгенерированный
поставляемый
699
vendor/github.com/spf13/afero/afero_test.go
сгенерированный
поставляемый
@@ -1,699 +0,0 @@
|
||||
// Copyright © 2014 Steve Francia <spf@spf13.com>.
|
||||
// Copyright 2009 The Go Authors. All rights reserved.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package afero
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"io"
|
||||
"io/ioutil"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"strings"
|
||||
"syscall"
|
||||
"testing"
|
||||
)
|
||||
|
||||
var testName = "test.txt"
|
||||
var Fss = []Fs{&MemMapFs{}, &OsFs{}}
|
||||
|
||||
var testRegistry map[Fs][]string = make(map[Fs][]string)
|
||||
|
||||
func testDir(fs Fs) string {
|
||||
name, err := TempDir(fs, "", "afero")
|
||||
if err != nil {
|
||||
panic(fmt.Sprint("unable to work with test dir", err))
|
||||
}
|
||||
testRegistry[fs] = append(testRegistry[fs], name)
|
||||
|
||||
return name
|
||||
}
|
||||
|
||||
func tmpFile(fs Fs) File {
|
||||
x, err := TempFile(fs, "", "afero")
|
||||
|
||||
if err != nil {
|
||||
panic(fmt.Sprint("unable to work with temp file", err))
|
||||
}
|
||||
|
||||
testRegistry[fs] = append(testRegistry[fs], x.Name())
|
||||
|
||||
return x
|
||||
}
|
||||
|
||||
//Read with length 0 should not return EOF.
|
||||
func TestRead0(t *testing.T) {
|
||||
for _, fs := range Fss {
|
||||
f := tmpFile(fs)
|
||||
defer f.Close()
|
||||
f.WriteString("Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.")
|
||||
|
||||
var b []byte
|
||||
// b := make([]byte, 0)
|
||||
n, err := f.Read(b)
|
||||
if n != 0 || err != nil {
|
||||
t.Errorf("%v: Read(0) = %d, %v, want 0, nil", fs.Name(), n, err)
|
||||
}
|
||||
f.Seek(0, 0)
|
||||
b = make([]byte, 100)
|
||||
n, err = f.Read(b)
|
||||
if n <= 0 || err != nil {
|
||||
t.Errorf("%v: Read(100) = %d, %v, want >0, nil", fs.Name(), n, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestOpenFile(t *testing.T) {
|
||||
defer removeAllTestFiles(t)
|
||||
for _, fs := range Fss {
|
||||
tmp := testDir(fs)
|
||||
path := filepath.Join(tmp, testName)
|
||||
|
||||
f, err := fs.OpenFile(path, os.O_RDWR|os.O_CREATE, 0600)
|
||||
if err != nil {
|
||||
t.Error(fs.Name(), "OpenFile (O_CREATE) failed:", err)
|
||||
continue
|
||||
}
|
||||
io.WriteString(f, "initial")
|
||||
f.Close()
|
||||
|
||||
f, err = fs.OpenFile(path, os.O_WRONLY|os.O_APPEND, 0600)
|
||||
if err != nil {
|
||||
t.Error(fs.Name(), "OpenFile (O_APPEND) failed:", err)
|
||||
continue
|
||||
}
|
||||
io.WriteString(f, "|append")
|
||||
f.Close()
|
||||
|
||||
f, err = fs.OpenFile(path, os.O_RDONLY, 0600)
|
||||
contents, _ := ioutil.ReadAll(f)
|
||||
expectedContents := "initial|append"
|
||||
if string(contents) != expectedContents {
|
||||
t.Errorf("%v: appending, expected '%v', got: '%v'", fs.Name(), expectedContents, string(contents))
|
||||
}
|
||||
f.Close()
|
||||
|
||||
f, err = fs.OpenFile(path, os.O_RDWR|os.O_TRUNC, 0600)
|
||||
if err != nil {
|
||||
t.Error(fs.Name(), "OpenFile (O_TRUNC) failed:", err)
|
||||
continue
|
||||
}
|
||||
contents, _ = ioutil.ReadAll(f)
|
||||
if string(contents) != "" {
|
||||
t.Errorf("%v: expected truncated file, got: '%v'", fs.Name(), string(contents))
|
||||
}
|
||||
f.Close()
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreate(t *testing.T) {
|
||||
defer removeAllTestFiles(t)
|
||||
for _, fs := range Fss {
|
||||
tmp := testDir(fs)
|
||||
path := filepath.Join(tmp, testName)
|
||||
|
||||
f, err := fs.Create(path)
|
||||
if err != nil {
|
||||
t.Error(fs.Name(), "Create failed:", err)
|
||||
f.Close()
|
||||
continue
|
||||
}
|
||||
io.WriteString(f, "initial")
|
||||
f.Close()
|
||||
|
||||
f, err = fs.Create(path)
|
||||
if err != nil {
|
||||
t.Error(fs.Name(), "Create failed:", err)
|
||||
f.Close()
|
||||
continue
|
||||
}
|
||||
secondContent := "second create"
|
||||
io.WriteString(f, secondContent)
|
||||
f.Close()
|
||||
|
||||
f, err = fs.Open(path)
|
||||
if err != nil {
|
||||
t.Error(fs.Name(), "Open failed:", err)
|
||||
f.Close()
|
||||
continue
|
||||
}
|
||||
buf, err := ReadAll(f)
|
||||
if err != nil {
|
||||
t.Error(fs.Name(), "ReadAll failed:", err)
|
||||
f.Close()
|
||||
continue
|
||||
}
|
||||
if string(buf) != secondContent {
|
||||
t.Error(fs.Name(), "Content should be", "\""+secondContent+"\" but is \""+string(buf)+"\"")
|
||||
f.Close()
|
||||
continue
|
||||
}
|
||||
f.Close()
|
||||
}
|
||||
}
|
||||
|
||||
func TestMemFileRead(t *testing.T) {
|
||||
f := tmpFile(new(MemMapFs))
|
||||
// f := MemFileCreate("testfile")
|
||||
f.WriteString("abcd")
|
||||
f.Seek(0, 0)
|
||||
b := make([]byte, 8)
|
||||
n, err := f.Read(b)
|
||||
if n != 4 {
|
||||
t.Errorf("didn't read all bytes: %v %v %v", n, err, b)
|
||||
}
|
||||
if err != nil {
|
||||
t.Errorf("err is not nil: %v %v %v", n, err, b)
|
||||
}
|
||||
n, err = f.Read(b)
|
||||
if n != 0 {
|
||||
t.Errorf("read more bytes: %v %v %v", n, err, b)
|
||||
}
|
||||
if err != io.EOF {
|
||||
t.Errorf("error is not EOF: %v %v %v", n, err, b)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRename(t *testing.T) {
|
||||
defer removeAllTestFiles(t)
|
||||
for _, fs := range Fss {
|
||||
tDir := testDir(fs)
|
||||
from := filepath.Join(tDir, "/renamefrom")
|
||||
to := filepath.Join(tDir, "/renameto")
|
||||
exists := filepath.Join(tDir, "/renameexists")
|
||||
file, err := fs.Create(from)
|
||||
if err != nil {
|
||||
t.Fatalf("%s: open %q failed: %v", fs.Name(), to, err)
|
||||
}
|
||||
if err = file.Close(); err != nil {
|
||||
t.Errorf("%s: close %q failed: %v", fs.Name(), to, err)
|
||||
}
|
||||
file, err = fs.Create(exists)
|
||||
if err != nil {
|
||||
t.Fatalf("%s: open %q failed: %v", fs.Name(), to, err)
|
||||
}
|
||||
if err = file.Close(); err != nil {
|
||||
t.Errorf("%s: close %q failed: %v", fs.Name(), to, err)
|
||||
}
|
||||
err = fs.Rename(from, to)
|
||||
if err != nil {
|
||||
t.Fatalf("%s: rename %q, %q failed: %v", fs.Name(), to, from, err)
|
||||
}
|
||||
file, err = fs.Create(from)
|
||||
if err != nil {
|
||||
t.Fatalf("%s: open %q failed: %v", fs.Name(), to, err)
|
||||
}
|
||||
if err = file.Close(); err != nil {
|
||||
t.Errorf("%s: close %q failed: %v", fs.Name(), to, err)
|
||||
}
|
||||
err = fs.Rename(from, exists)
|
||||
if err != nil {
|
||||
t.Errorf("%s: rename %q, %q failed: %v", fs.Name(), exists, from, err)
|
||||
}
|
||||
names, err := readDirNames(fs, tDir)
|
||||
if err != nil {
|
||||
t.Errorf("%s: readDirNames error: %v", fs.Name(), err)
|
||||
}
|
||||
found := false
|
||||
for _, e := range names {
|
||||
if e == "renamefrom" {
|
||||
t.Error("File is still called renamefrom")
|
||||
}
|
||||
if e == "renameto" {
|
||||
found = true
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
t.Error("File was not renamed to renameto")
|
||||
}
|
||||
|
||||
_, err = fs.Stat(to)
|
||||
if err != nil {
|
||||
t.Errorf("%s: stat %q failed: %v", fs.Name(), to, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestRemove(t *testing.T) {
|
||||
for _, fs := range Fss {
|
||||
|
||||
x, err := TempFile(fs, "", "afero")
|
||||
if err != nil {
|
||||
t.Error(fmt.Sprint("unable to work with temp file", err))
|
||||
}
|
||||
|
||||
path := x.Name()
|
||||
x.Close()
|
||||
|
||||
tDir := filepath.Dir(path)
|
||||
|
||||
err = fs.Remove(path)
|
||||
if err != nil {
|
||||
t.Errorf("%v: Remove() failed: %v", fs.Name(), err)
|
||||
continue
|
||||
}
|
||||
|
||||
_, err = fs.Stat(path)
|
||||
if !os.IsNotExist(err) {
|
||||
t.Errorf("%v: Remove() didn't remove file", fs.Name())
|
||||
continue
|
||||
}
|
||||
|
||||
// Deleting non-existent file should raise error
|
||||
err = fs.Remove(path)
|
||||
if !os.IsNotExist(err) {
|
||||
t.Errorf("%v: Remove() didn't raise error for non-existent file", fs.Name())
|
||||
}
|
||||
|
||||
f, err := fs.Open(tDir)
|
||||
if err != nil {
|
||||
t.Error("TestDir should still exist:", err)
|
||||
}
|
||||
|
||||
names, err := f.Readdirnames(-1)
|
||||
if err != nil {
|
||||
t.Error("Readdirnames failed:", err)
|
||||
}
|
||||
|
||||
for _, e := range names {
|
||||
if e == testName {
|
||||
t.Error("File was not removed from parent directory")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestTruncate(t *testing.T) {
|
||||
defer removeAllTestFiles(t)
|
||||
for _, fs := range Fss {
|
||||
f := tmpFile(fs)
|
||||
defer f.Close()
|
||||
|
||||
checkSize(t, f, 0)
|
||||
f.Write([]byte("hello, world\n"))
|
||||
checkSize(t, f, 13)
|
||||
f.Truncate(10)
|
||||
checkSize(t, f, 10)
|
||||
f.Truncate(1024)
|
||||
checkSize(t, f, 1024)
|
||||
f.Truncate(0)
|
||||
checkSize(t, f, 0)
|
||||
_, err := f.Write([]byte("surprise!"))
|
||||
if err == nil {
|
||||
checkSize(t, f, 13+9) // wrote at offset past where hello, world was.
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestSeek(t *testing.T) {
|
||||
defer removeAllTestFiles(t)
|
||||
for _, fs := range Fss {
|
||||
f := tmpFile(fs)
|
||||
defer f.Close()
|
||||
|
||||
const data = "hello, world\n"
|
||||
io.WriteString(f, data)
|
||||
|
||||
type test struct {
|
||||
in int64
|
||||
whence int
|
||||
out int64
|
||||
}
|
||||
var tests = []test{
|
||||
{0, 1, int64(len(data))},
|
||||
{0, 0, 0},
|
||||
{5, 0, 5},
|
||||
{0, 2, int64(len(data))},
|
||||
{0, 0, 0},
|
||||
{-1, 2, int64(len(data)) - 1},
|
||||
{1 << 33, 0, 1 << 33},
|
||||
{1 << 33, 2, 1<<33 + int64(len(data))},
|
||||
}
|
||||
for i, tt := range tests {
|
||||
off, err := f.Seek(tt.in, tt.whence)
|
||||
if off != tt.out || err != nil {
|
||||
if e, ok := err.(*os.PathError); ok && e.Err == syscall.EINVAL && tt.out > 1<<32 {
|
||||
// Reiserfs rejects the big seeks.
|
||||
// http://code.google.com/p/go/issues/detail?id=91
|
||||
break
|
||||
}
|
||||
t.Errorf("#%d: Seek(%v, %v) = %v, %v want %v, nil", i, tt.in, tt.whence, off, err, tt.out)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestReadAt(t *testing.T) {
|
||||
defer removeAllTestFiles(t)
|
||||
for _, fs := range Fss {
|
||||
f := tmpFile(fs)
|
||||
defer f.Close()
|
||||
|
||||
const data = "hello, world\n"
|
||||
io.WriteString(f, data)
|
||||
|
||||
b := make([]byte, 5)
|
||||
n, err := f.ReadAt(b, 7)
|
||||
if err != nil || n != len(b) {
|
||||
t.Fatalf("ReadAt 7: %d, %v", n, err)
|
||||
}
|
||||
if string(b) != "world" {
|
||||
t.Fatalf("ReadAt 7: have %q want %q", string(b), "world")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestWriteAt(t *testing.T) {
|
||||
defer removeAllTestFiles(t)
|
||||
for _, fs := range Fss {
|
||||
f := tmpFile(fs)
|
||||
defer f.Close()
|
||||
|
||||
const data = "hello, world\n"
|
||||
io.WriteString(f, data)
|
||||
|
||||
n, err := f.WriteAt([]byte("WORLD"), 7)
|
||||
if err != nil || n != 5 {
|
||||
t.Fatalf("WriteAt 7: %d, %v", n, err)
|
||||
}
|
||||
|
||||
f2, err := fs.Open(f.Name())
|
||||
if err != nil {
|
||||
t.Fatalf("%v: ReadFile %s: %v", fs.Name(), f.Name(), err)
|
||||
}
|
||||
defer f2.Close()
|
||||
buf := new(bytes.Buffer)
|
||||
buf.ReadFrom(f2)
|
||||
b := buf.Bytes()
|
||||
if string(b) != "hello, WORLD\n" {
|
||||
t.Fatalf("after write: have %q want %q", string(b), "hello, WORLD\n")
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
func setupTestDir(t *testing.T, fs Fs) string {
|
||||
path := testDir(fs)
|
||||
return setupTestFiles(t, fs, path)
|
||||
}
|
||||
|
||||
func setupTestDirRoot(t *testing.T, fs Fs) string {
|
||||
path := testDir(fs)
|
||||
setupTestFiles(t, fs, path)
|
||||
return path
|
||||
}
|
||||
|
||||
func setupTestDirReusePath(t *testing.T, fs Fs, path string) string {
|
||||
testRegistry[fs] = append(testRegistry[fs], path)
|
||||
return setupTestFiles(t, fs, path)
|
||||
}
|
||||
|
||||
func setupTestFiles(t *testing.T, fs Fs, path string) string {
|
||||
testSubDir := filepath.Join(path, "more", "subdirectories", "for", "testing", "we")
|
||||
err := fs.MkdirAll(testSubDir, 0700)
|
||||
if err != nil && !os.IsExist(err) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
f, err := fs.Create(filepath.Join(testSubDir, "testfile1"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
f.WriteString("Testfile 1 content")
|
||||
f.Close()
|
||||
|
||||
f, err = fs.Create(filepath.Join(testSubDir, "testfile2"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
f.WriteString("Testfile 2 content")
|
||||
f.Close()
|
||||
|
||||
f, err = fs.Create(filepath.Join(testSubDir, "testfile3"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
f.WriteString("Testfile 3 content")
|
||||
f.Close()
|
||||
|
||||
f, err = fs.Create(filepath.Join(testSubDir, "testfile4"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
f.WriteString("Testfile 4 content")
|
||||
f.Close()
|
||||
return testSubDir
|
||||
}
|
||||
|
||||
func TestReaddirnames(t *testing.T) {
|
||||
defer removeAllTestFiles(t)
|
||||
for _, fs := range Fss {
|
||||
testSubDir := setupTestDir(t, fs)
|
||||
tDir := filepath.Dir(testSubDir)
|
||||
|
||||
root, err := fs.Open(tDir)
|
||||
if err != nil {
|
||||
t.Fatal(fs.Name(), tDir, err)
|
||||
}
|
||||
defer root.Close()
|
||||
|
||||
namesRoot, err := root.Readdirnames(-1)
|
||||
if err != nil {
|
||||
t.Fatal(fs.Name(), namesRoot, err)
|
||||
}
|
||||
|
||||
sub, err := fs.Open(testSubDir)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer sub.Close()
|
||||
|
||||
namesSub, err := sub.Readdirnames(-1)
|
||||
if err != nil {
|
||||
t.Fatal(fs.Name(), namesSub, err)
|
||||
}
|
||||
|
||||
findNames(fs, t, tDir, testSubDir, namesRoot, namesSub)
|
||||
}
|
||||
}
|
||||
|
||||
func TestReaddirSimple(t *testing.T) {
|
||||
defer removeAllTestFiles(t)
|
||||
for _, fs := range Fss {
|
||||
testSubDir := setupTestDir(t, fs)
|
||||
tDir := filepath.Dir(testSubDir)
|
||||
|
||||
root, err := fs.Open(tDir)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer root.Close()
|
||||
|
||||
rootInfo, err := root.Readdir(1)
|
||||
if err != nil {
|
||||
t.Log(myFileInfo(rootInfo))
|
||||
t.Error(err)
|
||||
}
|
||||
|
||||
rootInfo, err = root.Readdir(5)
|
||||
if err != io.EOF {
|
||||
t.Log(myFileInfo(rootInfo))
|
||||
t.Error(err)
|
||||
}
|
||||
|
||||
sub, err := fs.Open(testSubDir)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer sub.Close()
|
||||
|
||||
subInfo, err := sub.Readdir(5)
|
||||
if err != nil {
|
||||
t.Log(myFileInfo(subInfo))
|
||||
t.Error(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestReaddir(t *testing.T) {
|
||||
defer removeAllTestFiles(t)
|
||||
for num := 0; num < 6; num++ {
|
||||
outputs := make([]string, len(Fss))
|
||||
infos := make([]string, len(Fss))
|
||||
for i, fs := range Fss {
|
||||
testSubDir := setupTestDir(t, fs)
|
||||
//tDir := filepath.Dir(testSubDir)
|
||||
root, err := fs.Open(testSubDir)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer root.Close()
|
||||
|
||||
for j := 0; j < 6; j++ {
|
||||
info, err := root.Readdir(num)
|
||||
outputs[i] += fmt.Sprintf("%v Error: %v\n", myFileInfo(info), err)
|
||||
infos[i] += fmt.Sprintln(len(info), err)
|
||||
}
|
||||
}
|
||||
|
||||
fail := false
|
||||
for i, o := range infos {
|
||||
if i == 0 {
|
||||
continue
|
||||
}
|
||||
if o != infos[i-1] {
|
||||
fail = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if fail {
|
||||
t.Log("Readdir outputs not equal for Readdir(", num, ")")
|
||||
for i, o := range outputs {
|
||||
t.Log(Fss[i].Name())
|
||||
t.Log(o)
|
||||
}
|
||||
t.Fail()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
type myFileInfo []os.FileInfo
|
||||
|
||||
func (m myFileInfo) String() string {
|
||||
out := "Fileinfos:\n"
|
||||
for _, e := range m {
|
||||
out += " " + e.Name() + "\n"
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func TestReaddirAll(t *testing.T) {
|
||||
defer removeAllTestFiles(t)
|
||||
for _, fs := range Fss {
|
||||
testSubDir := setupTestDir(t, fs)
|
||||
tDir := filepath.Dir(testSubDir)
|
||||
|
||||
root, err := fs.Open(tDir)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer root.Close()
|
||||
|
||||
rootInfo, err := root.Readdir(-1)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var namesRoot = []string{}
|
||||
for _, e := range rootInfo {
|
||||
namesRoot = append(namesRoot, e.Name())
|
||||
}
|
||||
|
||||
sub, err := fs.Open(testSubDir)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer sub.Close()
|
||||
|
||||
subInfo, err := sub.Readdir(-1)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var namesSub = []string{}
|
||||
for _, e := range subInfo {
|
||||
namesSub = append(namesSub, e.Name())
|
||||
}
|
||||
|
||||
findNames(fs, t, tDir, testSubDir, namesRoot, namesSub)
|
||||
}
|
||||
}
|
||||
|
||||
func findNames(fs Fs, t *testing.T, tDir, testSubDir string, root, sub []string) {
|
||||
var foundRoot bool
|
||||
for _, e := range root {
|
||||
f, err := fs.Open(filepath.Join(tDir, e))
|
||||
if err != nil {
|
||||
t.Error("Open", filepath.Join(tDir, e), ":", err)
|
||||
}
|
||||
defer f.Close()
|
||||
|
||||
if equal(e, "we") {
|
||||
foundRoot = true
|
||||
}
|
||||
}
|
||||
if !foundRoot {
|
||||
t.Logf("Names root: %v", root)
|
||||
t.Logf("Names sub: %v", sub)
|
||||
t.Error("Didn't find subdirectory we")
|
||||
}
|
||||
|
||||
var found1, found2 bool
|
||||
for _, e := range sub {
|
||||
f, err := fs.Open(filepath.Join(testSubDir, e))
|
||||
if err != nil {
|
||||
t.Error("Open", filepath.Join(testSubDir, e), ":", err)
|
||||
}
|
||||
defer f.Close()
|
||||
|
||||
if equal(e, "testfile1") {
|
||||
found1 = true
|
||||
}
|
||||
if equal(e, "testfile2") {
|
||||
found2 = true
|
||||
}
|
||||
}
|
||||
|
||||
if !found1 {
|
||||
t.Logf("Names root: %v", root)
|
||||
t.Logf("Names sub: %v", sub)
|
||||
t.Error("Didn't find testfile1")
|
||||
}
|
||||
if !found2 {
|
||||
t.Logf("Names root: %v", root)
|
||||
t.Logf("Names sub: %v", sub)
|
||||
t.Error("Didn't find testfile2")
|
||||
}
|
||||
}
|
||||
|
||||
func removeAllTestFiles(t *testing.T) {
|
||||
for fs, list := range testRegistry {
|
||||
for _, path := range list {
|
||||
if err := fs.RemoveAll(path); err != nil {
|
||||
t.Error(fs.Name(), err)
|
||||
}
|
||||
}
|
||||
}
|
||||
testRegistry = make(map[Fs][]string)
|
||||
}
|
||||
|
||||
func equal(name1, name2 string) (r bool) {
|
||||
switch runtime.GOOS {
|
||||
case "windows":
|
||||
r = strings.ToLower(name1) == strings.ToLower(name2)
|
||||
default:
|
||||
r = name1 == name2
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func checkSize(t *testing.T, f File, size int64) {
|
||||
dir, err := f.Stat()
|
||||
if err != nil {
|
||||
t.Fatalf("Stat %q (looking for size %d): %s", f.Name(), size, err)
|
||||
}
|
||||
if dir.Size() != size {
|
||||
t.Errorf("Stat %q: size %d want %d", f.Name(), dir.Size(), size)
|
||||
}
|
||||
}
|
||||
47
vendor/github.com/spf13/afero/basepath.go
сгенерированный
поставляемый
47
vendor/github.com/spf13/afero/basepath.go
сгенерированный
поставляемый
@@ -1,7 +1,6 @@
|
||||
package afero
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
@@ -9,6 +8,8 @@ import (
|
||||
"time"
|
||||
)
|
||||
|
||||
var _ Lstater = (*BasePathFs)(nil)
|
||||
|
||||
// The BasePathFs restricts all operations to a given path within an Fs.
|
||||
// The given file name to the operations on this Fs will be prepended with
|
||||
// the base path before calling the base Fs.
|
||||
@@ -22,6 +23,16 @@ type BasePathFs struct {
|
||||
path string
|
||||
}
|
||||
|
||||
type BasePathFile struct {
|
||||
File
|
||||
path string
|
||||
}
|
||||
|
||||
func (f *BasePathFile) Name() string {
|
||||
sourcename := f.File.Name()
|
||||
return strings.TrimPrefix(sourcename, filepath.Clean(f.path))
|
||||
}
|
||||
|
||||
func NewBasePathFs(source Fs, path string) Fs {
|
||||
return &BasePathFs{source: source, path: path}
|
||||
}
|
||||
@@ -30,7 +41,7 @@ func NewBasePathFs(source Fs, path string) Fs {
|
||||
// else the given file with the base path prepended
|
||||
func (b *BasePathFs) RealPath(name string) (path string, err error) {
|
||||
if err := validateBasePathName(name); err != nil {
|
||||
return "", err
|
||||
return name, err
|
||||
}
|
||||
|
||||
bpath := filepath.Clean(b.path)
|
||||
@@ -52,7 +63,7 @@ func validateBasePathName(name string) error {
|
||||
// On Windows a common mistake would be to provide an absolute OS path
|
||||
// We could strip out the base part, but that would not be very portable.
|
||||
if filepath.IsAbs(name) {
|
||||
return &os.PathError{Op: "realPath", Path: name, Err: errors.New("got a real OS path instead of a virtual")}
|
||||
return os.ErrNotExist
|
||||
}
|
||||
|
||||
return nil
|
||||
@@ -111,14 +122,22 @@ func (b *BasePathFs) OpenFile(name string, flag int, mode os.FileMode) (f File,
|
||||
if name, err = b.RealPath(name); err != nil {
|
||||
return nil, &os.PathError{Op: "openfile", Path: name, Err: err}
|
||||
}
|
||||
return b.source.OpenFile(name, flag, mode)
|
||||
sourcef, err := b.source.OpenFile(name, flag, mode)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &BasePathFile{sourcef, b.path}, nil
|
||||
}
|
||||
|
||||
func (b *BasePathFs) Open(name string) (f File, err error) {
|
||||
if name, err = b.RealPath(name); err != nil {
|
||||
return nil, &os.PathError{Op: "open", Path: name, Err: err}
|
||||
}
|
||||
return b.source.Open(name)
|
||||
sourcef, err := b.source.Open(name)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &BasePathFile{File: sourcef, path: b.path}, nil
|
||||
}
|
||||
|
||||
func (b *BasePathFs) Mkdir(name string, mode os.FileMode) (err error) {
|
||||
@@ -139,7 +158,23 @@ func (b *BasePathFs) Create(name string) (f File, err error) {
|
||||
if name, err = b.RealPath(name); err != nil {
|
||||
return nil, &os.PathError{Op: "create", Path: name, Err: err}
|
||||
}
|
||||
return b.source.Create(name)
|
||||
sourcef, err := b.source.Create(name)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &BasePathFile{File: sourcef, path: b.path}, nil
|
||||
}
|
||||
|
||||
func (b *BasePathFs) LstatIfPossible(name string) (os.FileInfo, bool, error) {
|
||||
name, err := b.RealPath(name)
|
||||
if err != nil {
|
||||
return nil, false, &os.PathError{Op: "lstat", Path: name, Err: err}
|
||||
}
|
||||
if lstater, ok := b.source.(Lstater); ok {
|
||||
return lstater.LstatIfPossible(name)
|
||||
}
|
||||
fi, err := b.source.Stat(name)
|
||||
return fi, false, err
|
||||
}
|
||||
|
||||
// vim: ts=4 sw=4 noexpandtab nolist syn=go
|
||||
|
||||
142
vendor/github.com/spf13/afero/basepath_test.go
сгенерированный
поставляемый
142
vendor/github.com/spf13/afero/basepath_test.go
сгенерированный
поставляемый
@@ -1,142 +0,0 @@
|
||||
package afero
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestBasePath(t *testing.T) {
|
||||
baseFs := &MemMapFs{}
|
||||
baseFs.MkdirAll("/base/path/tmp", 0777)
|
||||
bp := NewBasePathFs(baseFs, "/base/path")
|
||||
|
||||
if _, err := bp.Create("/tmp/foo"); err != nil {
|
||||
t.Errorf("Failed to set real path")
|
||||
}
|
||||
|
||||
if fh, err := bp.Create("../tmp/bar"); err == nil {
|
||||
t.Errorf("succeeded in creating %s ...", fh.Name())
|
||||
}
|
||||
}
|
||||
|
||||
func TestBasePathRoot(t *testing.T) {
|
||||
baseFs := &MemMapFs{}
|
||||
baseFs.MkdirAll("/base/path/foo/baz", 0777)
|
||||
baseFs.MkdirAll("/base/path/boo/", 0777)
|
||||
bp := NewBasePathFs(baseFs, "/base/path")
|
||||
|
||||
rd, err := ReadDir(bp, string(os.PathSeparator))
|
||||
|
||||
if len(rd) != 2 {
|
||||
t.Errorf("base path doesn't respect root")
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRealPath(t *testing.T) {
|
||||
fs := NewOsFs()
|
||||
baseDir, err := TempDir(fs, "", "base")
|
||||
if err != nil {
|
||||
t.Fatal("error creating tempDir", err)
|
||||
}
|
||||
defer fs.RemoveAll(baseDir)
|
||||
anotherDir, err := TempDir(fs, "", "another")
|
||||
if err != nil {
|
||||
t.Fatal("error creating tempDir", err)
|
||||
}
|
||||
defer fs.RemoveAll(anotherDir)
|
||||
|
||||
bp := NewBasePathFs(fs, baseDir).(*BasePathFs)
|
||||
|
||||
subDir := filepath.Join(baseDir, "s1")
|
||||
|
||||
realPath, err := bp.RealPath("/s1")
|
||||
|
||||
if err != nil {
|
||||
t.Errorf("Got error %s", err)
|
||||
}
|
||||
|
||||
if realPath != subDir {
|
||||
t.Errorf("Expected \n%s got \n%s", subDir, realPath)
|
||||
}
|
||||
|
||||
if runtime.GOOS == "windows" {
|
||||
_, err = bp.RealPath(anotherDir)
|
||||
|
||||
if err == nil {
|
||||
t.Errorf("Expected error")
|
||||
}
|
||||
|
||||
} else {
|
||||
// on *nix we have no way of just looking at the path and tell that anotherDir
|
||||
// is not inside the base file system.
|
||||
// The user will receive an os.ErrNotExist later.
|
||||
surrealPath, err := bp.RealPath(anotherDir)
|
||||
|
||||
if err != nil {
|
||||
t.Errorf("Got error %s", err)
|
||||
}
|
||||
|
||||
excpected := filepath.Join(baseDir, anotherDir)
|
||||
|
||||
if surrealPath != excpected {
|
||||
t.Errorf("Expected \n%s got \n%s", excpected, surrealPath)
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
func TestNestedBasePaths(t *testing.T) {
|
||||
type dirSpec struct {
|
||||
Dir1, Dir2, Dir3 string
|
||||
}
|
||||
dirSpecs := []dirSpec{
|
||||
dirSpec{Dir1: "/", Dir2: "/", Dir3: "/"},
|
||||
dirSpec{Dir1: "/", Dir2: "/path2", Dir3: "/"},
|
||||
dirSpec{Dir1: "/path1/dir", Dir2: "/path2/dir/", Dir3: "/path3/dir"},
|
||||
dirSpec{Dir1: "C:/path1", Dir2: "path2/dir", Dir3: "/path3/dir/"},
|
||||
}
|
||||
|
||||
for _, ds := range dirSpecs {
|
||||
memFs := NewMemMapFs()
|
||||
level1Fs := NewBasePathFs(memFs, ds.Dir1)
|
||||
level2Fs := NewBasePathFs(level1Fs, ds.Dir2)
|
||||
level3Fs := NewBasePathFs(level2Fs, ds.Dir3)
|
||||
|
||||
type spec struct {
|
||||
BaseFs Fs
|
||||
FileName string
|
||||
}
|
||||
specs := []spec{
|
||||
spec{BaseFs: level3Fs, FileName: "f.txt"},
|
||||
spec{BaseFs: level2Fs, FileName: "f.txt"},
|
||||
spec{BaseFs: level1Fs, FileName: "f.txt"},
|
||||
}
|
||||
|
||||
for _, s := range specs {
|
||||
if err := s.BaseFs.MkdirAll(s.FileName, 0755); err != nil {
|
||||
t.Errorf("Got error %s", err.Error())
|
||||
}
|
||||
if _, err := s.BaseFs.Stat(s.FileName); err != nil {
|
||||
t.Errorf("Got error %s", err.Error())
|
||||
}
|
||||
|
||||
if s.BaseFs == level3Fs {
|
||||
pathToExist := filepath.Join(ds.Dir3, s.FileName)
|
||||
if _, err := level2Fs.Stat(pathToExist); err != nil {
|
||||
t.Errorf("Got error %s (path %s)", err.Error(), pathToExist)
|
||||
}
|
||||
} else if s.BaseFs == level2Fs {
|
||||
pathToExist := filepath.Join(ds.Dir2, ds.Dir3, s.FileName)
|
||||
if _, err := level1Fs.Stat(pathToExist); err != nil {
|
||||
t.Errorf("Got error %s (path %s)", err.Error(), pathToExist)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
6
vendor/github.com/spf13/afero/cacheOnReadFs.go
сгенерированный
поставляемый
6
vendor/github.com/spf13/afero/cacheOnReadFs.go
сгенерированный
поставляемый
@@ -205,7 +205,7 @@ func (u *CacheOnReadFs) OpenFile(name string, flag int, perm os.FileMode) (File,
|
||||
bfi.Close() // oops, what if O_TRUNC was set and file opening in the layer failed...?
|
||||
return nil, err
|
||||
}
|
||||
return &UnionFile{base: bfi, layer: lfi}, nil
|
||||
return &UnionFile{Base: bfi, Layer: lfi}, nil
|
||||
}
|
||||
return u.layer.OpenFile(name, flag, perm)
|
||||
}
|
||||
@@ -251,7 +251,7 @@ func (u *CacheOnReadFs) Open(name string) (File, error) {
|
||||
if err != nil && bfile == nil {
|
||||
return nil, err
|
||||
}
|
||||
return &UnionFile{base: bfile, layer: lfile}, nil
|
||||
return &UnionFile{Base: bfile, Layer: lfile}, nil
|
||||
}
|
||||
|
||||
func (u *CacheOnReadFs) Mkdir(name string, perm os.FileMode) error {
|
||||
@@ -286,5 +286,5 @@ func (u *CacheOnReadFs) Create(name string) (File, error) {
|
||||
bfh.Close()
|
||||
return nil, err
|
||||
}
|
||||
return &UnionFile{base: bfh, layer: lfh}, nil
|
||||
return &UnionFile{Base: bfh, Layer: lfh}, nil
|
||||
}
|
||||
|
||||
404
vendor/github.com/spf13/afero/composite_test.go
сгенерированный
поставляемый
404
vendor/github.com/spf13/afero/composite_test.go
сгенерированный
поставляемый
@@ -1,404 +0,0 @@
|
||||
package afero
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"io/ioutil"
|
||||
"os"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
var tempDirs []string
|
||||
|
||||
func NewTempOsBaseFs(t *testing.T) Fs {
|
||||
name, err := TempDir(NewOsFs(), "", "")
|
||||
if err != nil {
|
||||
t.Error("error creating tempDir", err)
|
||||
}
|
||||
|
||||
tempDirs = append(tempDirs, name)
|
||||
|
||||
return NewBasePathFs(NewOsFs(), name)
|
||||
}
|
||||
|
||||
func CleanupTempDirs(t *testing.T) {
|
||||
osfs := NewOsFs()
|
||||
type ev struct {
|
||||
path string
|
||||
e error
|
||||
}
|
||||
|
||||
errs := []ev{}
|
||||
|
||||
for _, x := range tempDirs {
|
||||
err := osfs.RemoveAll(x)
|
||||
if err != nil {
|
||||
errs = append(errs, ev{path: x, e: err})
|
||||
}
|
||||
}
|
||||
|
||||
for _, e := range errs {
|
||||
fmt.Println("error removing tempDir", e.path, e.e)
|
||||
}
|
||||
|
||||
if len(errs) > 0 {
|
||||
t.Error("error cleaning up tempDirs")
|
||||
}
|
||||
tempDirs = []string{}
|
||||
}
|
||||
|
||||
func TestUnionCreateExisting(t *testing.T) {
|
||||
base := &MemMapFs{}
|
||||
roBase := &ReadOnlyFs{source: base}
|
||||
|
||||
ufs := NewCopyOnWriteFs(roBase, &MemMapFs{})
|
||||
|
||||
base.MkdirAll("/home/test", 0777)
|
||||
fh, _ := base.Create("/home/test/file.txt")
|
||||
fh.WriteString("This is a test")
|
||||
fh.Close()
|
||||
|
||||
fh, err := ufs.OpenFile("/home/test/file.txt", os.O_RDWR, 0666)
|
||||
if err != nil {
|
||||
t.Errorf("Failed to open file r/w: %s", err)
|
||||
}
|
||||
|
||||
_, err = fh.Write([]byte("####"))
|
||||
if err != nil {
|
||||
t.Errorf("Failed to write file: %s", err)
|
||||
}
|
||||
fh.Seek(0, 0)
|
||||
data, err := ioutil.ReadAll(fh)
|
||||
if err != nil {
|
||||
t.Errorf("Failed to read file: %s", err)
|
||||
}
|
||||
if string(data) != "#### is a test" {
|
||||
t.Errorf("Got wrong data")
|
||||
}
|
||||
fh.Close()
|
||||
|
||||
fh, _ = base.Open("/home/test/file.txt")
|
||||
data, err = ioutil.ReadAll(fh)
|
||||
if string(data) != "This is a test" {
|
||||
t.Errorf("Got wrong data in base file")
|
||||
}
|
||||
fh.Close()
|
||||
|
||||
fh, err = ufs.Create("/home/test/file.txt")
|
||||
switch err {
|
||||
case nil:
|
||||
if fi, _ := fh.Stat(); fi.Size() != 0 {
|
||||
t.Errorf("Create did not truncate file")
|
||||
}
|
||||
fh.Close()
|
||||
default:
|
||||
t.Errorf("Create failed on existing file")
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
func TestUnionMergeReaddir(t *testing.T) {
|
||||
base := &MemMapFs{}
|
||||
roBase := &ReadOnlyFs{source: base}
|
||||
|
||||
ufs := &CopyOnWriteFs{base: roBase, layer: &MemMapFs{}}
|
||||
|
||||
base.MkdirAll("/home/test", 0777)
|
||||
fh, _ := base.Create("/home/test/file.txt")
|
||||
fh.WriteString("This is a test")
|
||||
fh.Close()
|
||||
|
||||
fh, _ = ufs.Create("/home/test/file2.txt")
|
||||
fh.WriteString("This is a test")
|
||||
fh.Close()
|
||||
|
||||
fh, _ = ufs.Open("/home/test")
|
||||
files, err := fh.Readdirnames(-1)
|
||||
if err != nil {
|
||||
t.Errorf("Readdirnames failed")
|
||||
}
|
||||
if len(files) != 2 {
|
||||
t.Errorf("Got wrong number of files: %v", files)
|
||||
}
|
||||
}
|
||||
|
||||
func TestExistingDirectoryCollisionReaddir(t *testing.T) {
|
||||
base := &MemMapFs{}
|
||||
roBase := &ReadOnlyFs{source: base}
|
||||
overlay := &MemMapFs{}
|
||||
|
||||
ufs := &CopyOnWriteFs{base: roBase, layer: overlay}
|
||||
|
||||
base.MkdirAll("/home/test", 0777)
|
||||
fh, _ := base.Create("/home/test/file.txt")
|
||||
fh.WriteString("This is a test")
|
||||
fh.Close()
|
||||
|
||||
overlay.MkdirAll("home/test", 0777)
|
||||
fh, _ = overlay.Create("/home/test/file2.txt")
|
||||
fh.WriteString("This is a test")
|
||||
fh.Close()
|
||||
|
||||
fh, _ = ufs.Create("/home/test/file3.txt")
|
||||
fh.WriteString("This is a test")
|
||||
fh.Close()
|
||||
|
||||
fh, _ = ufs.Open("/home/test")
|
||||
files, err := fh.Readdirnames(-1)
|
||||
if err != nil {
|
||||
t.Errorf("Readdirnames failed")
|
||||
}
|
||||
if len(files) != 3 {
|
||||
t.Errorf("Got wrong number of files in union: %v", files)
|
||||
}
|
||||
|
||||
fh, _ = overlay.Open("/home/test")
|
||||
files, err = fh.Readdirnames(-1)
|
||||
if err != nil {
|
||||
t.Errorf("Readdirnames failed")
|
||||
}
|
||||
if len(files) != 2 {
|
||||
t.Errorf("Got wrong number of files in overlay: %v", files)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNestedDirBaseReaddir(t *testing.T) {
|
||||
base := &MemMapFs{}
|
||||
roBase := &ReadOnlyFs{source: base}
|
||||
overlay := &MemMapFs{}
|
||||
|
||||
ufs := &CopyOnWriteFs{base: roBase, layer: overlay}
|
||||
|
||||
base.MkdirAll("/home/test/foo/bar", 0777)
|
||||
fh, _ := base.Create("/home/test/file.txt")
|
||||
fh.WriteString("This is a test")
|
||||
fh.Close()
|
||||
|
||||
fh, _ = base.Create("/home/test/foo/file2.txt")
|
||||
fh.WriteString("This is a test")
|
||||
fh.Close()
|
||||
fh, _ = base.Create("/home/test/foo/bar/file3.txt")
|
||||
fh.WriteString("This is a test")
|
||||
fh.Close()
|
||||
|
||||
overlay.MkdirAll("/", 0777)
|
||||
|
||||
// Opening something only in the base
|
||||
fh, _ = ufs.Open("/home/test/foo")
|
||||
list, err := fh.Readdir(-1)
|
||||
if err != nil {
|
||||
t.Errorf("Readdir failed %s", err)
|
||||
}
|
||||
if len(list) != 2 {
|
||||
for _, x := range list {
|
||||
fmt.Println(x.Name())
|
||||
}
|
||||
t.Errorf("Got wrong number of files in union: %v", len(list))
|
||||
}
|
||||
}
|
||||
|
||||
func TestNestedDirOverlayReaddir(t *testing.T) {
|
||||
base := &MemMapFs{}
|
||||
roBase := &ReadOnlyFs{source: base}
|
||||
overlay := &MemMapFs{}
|
||||
|
||||
ufs := &CopyOnWriteFs{base: roBase, layer: overlay}
|
||||
|
||||
base.MkdirAll("/", 0777)
|
||||
overlay.MkdirAll("/home/test/foo/bar", 0777)
|
||||
fh, _ := overlay.Create("/home/test/file.txt")
|
||||
fh.WriteString("This is a test")
|
||||
fh.Close()
|
||||
fh, _ = overlay.Create("/home/test/foo/file2.txt")
|
||||
fh.WriteString("This is a test")
|
||||
fh.Close()
|
||||
fh, _ = overlay.Create("/home/test/foo/bar/file3.txt")
|
||||
fh.WriteString("This is a test")
|
||||
fh.Close()
|
||||
|
||||
// Opening nested dir only in the overlay
|
||||
fh, _ = ufs.Open("/home/test/foo")
|
||||
list, err := fh.Readdir(-1)
|
||||
if err != nil {
|
||||
t.Errorf("Readdir failed %s", err)
|
||||
}
|
||||
if len(list) != 2 {
|
||||
for _, x := range list {
|
||||
fmt.Println(x.Name())
|
||||
}
|
||||
t.Errorf("Got wrong number of files in union: %v", len(list))
|
||||
}
|
||||
}
|
||||
|
||||
func TestNestedDirOverlayOsFsReaddir(t *testing.T) {
|
||||
defer CleanupTempDirs(t)
|
||||
base := NewTempOsBaseFs(t)
|
||||
roBase := &ReadOnlyFs{source: base}
|
||||
overlay := NewTempOsBaseFs(t)
|
||||
|
||||
ufs := &CopyOnWriteFs{base: roBase, layer: overlay}
|
||||
|
||||
base.MkdirAll("/", 0777)
|
||||
overlay.MkdirAll("/home/test/foo/bar", 0777)
|
||||
fh, _ := overlay.Create("/home/test/file.txt")
|
||||
fh.WriteString("This is a test")
|
||||
fh.Close()
|
||||
fh, _ = overlay.Create("/home/test/foo/file2.txt")
|
||||
fh.WriteString("This is a test")
|
||||
fh.Close()
|
||||
fh, _ = overlay.Create("/home/test/foo/bar/file3.txt")
|
||||
fh.WriteString("This is a test")
|
||||
fh.Close()
|
||||
|
||||
// Opening nested dir only in the overlay
|
||||
fh, _ = ufs.Open("/home/test/foo")
|
||||
list, err := fh.Readdir(-1)
|
||||
fh.Close()
|
||||
if err != nil {
|
||||
t.Errorf("Readdir failed %s", err)
|
||||
}
|
||||
if len(list) != 2 {
|
||||
for _, x := range list {
|
||||
fmt.Println(x.Name())
|
||||
}
|
||||
t.Errorf("Got wrong number of files in union: %v", len(list))
|
||||
}
|
||||
}
|
||||
|
||||
func TestCopyOnWriteFsWithOsFs(t *testing.T) {
|
||||
defer CleanupTempDirs(t)
|
||||
base := NewTempOsBaseFs(t)
|
||||
roBase := &ReadOnlyFs{source: base}
|
||||
overlay := NewTempOsBaseFs(t)
|
||||
|
||||
ufs := &CopyOnWriteFs{base: roBase, layer: overlay}
|
||||
|
||||
base.MkdirAll("/home/test", 0777)
|
||||
fh, _ := base.Create("/home/test/file.txt")
|
||||
fh.WriteString("This is a test")
|
||||
fh.Close()
|
||||
|
||||
overlay.MkdirAll("home/test", 0777)
|
||||
fh, _ = overlay.Create("/home/test/file2.txt")
|
||||
fh.WriteString("This is a test")
|
||||
fh.Close()
|
||||
|
||||
fh, _ = ufs.Create("/home/test/file3.txt")
|
||||
fh.WriteString("This is a test")
|
||||
fh.Close()
|
||||
|
||||
fh, _ = ufs.Open("/home/test")
|
||||
files, err := fh.Readdirnames(-1)
|
||||
fh.Close()
|
||||
if err != nil {
|
||||
t.Errorf("Readdirnames failed")
|
||||
}
|
||||
if len(files) != 3 {
|
||||
t.Errorf("Got wrong number of files in union: %v", files)
|
||||
}
|
||||
|
||||
fh, _ = overlay.Open("/home/test")
|
||||
files, err = fh.Readdirnames(-1)
|
||||
fh.Close()
|
||||
if err != nil {
|
||||
t.Errorf("Readdirnames failed")
|
||||
}
|
||||
if len(files) != 2 {
|
||||
t.Errorf("Got wrong number of files in overlay: %v", files)
|
||||
}
|
||||
}
|
||||
|
||||
func TestUnionCacheWrite(t *testing.T) {
|
||||
base := &MemMapFs{}
|
||||
layer := &MemMapFs{}
|
||||
|
||||
ufs := NewCacheOnReadFs(base, layer, 0)
|
||||
|
||||
base.Mkdir("/data", 0777)
|
||||
|
||||
fh, err := ufs.Create("/data/file.txt")
|
||||
if err != nil {
|
||||
t.Errorf("Failed to create file")
|
||||
}
|
||||
_, err = fh.Write([]byte("This is a test"))
|
||||
if err != nil {
|
||||
t.Errorf("Failed to write file")
|
||||
}
|
||||
|
||||
fh.Seek(0, os.SEEK_SET)
|
||||
buf := make([]byte, 4)
|
||||
_, err = fh.Read(buf)
|
||||
fh.Write([]byte(" IS A"))
|
||||
fh.Close()
|
||||
|
||||
baseData, _ := ReadFile(base, "/data/file.txt")
|
||||
layerData, _ := ReadFile(layer, "/data/file.txt")
|
||||
if string(baseData) != string(layerData) {
|
||||
t.Errorf("Different data: %s <=> %s", baseData, layerData)
|
||||
}
|
||||
}
|
||||
|
||||
func TestUnionCacheExpire(t *testing.T) {
|
||||
base := &MemMapFs{}
|
||||
layer := &MemMapFs{}
|
||||
ufs := &CacheOnReadFs{base: base, layer: layer, cacheTime: 1 * time.Second}
|
||||
|
||||
base.Mkdir("/data", 0777)
|
||||
|
||||
fh, err := ufs.Create("/data/file.txt")
|
||||
if err != nil {
|
||||
t.Errorf("Failed to create file")
|
||||
}
|
||||
_, err = fh.Write([]byte("This is a test"))
|
||||
if err != nil {
|
||||
t.Errorf("Failed to write file")
|
||||
}
|
||||
fh.Close()
|
||||
|
||||
fh, _ = base.Create("/data/file.txt")
|
||||
// sleep some time, so we really get a different time.Now() on write...
|
||||
time.Sleep(2 * time.Second)
|
||||
fh.WriteString("Another test")
|
||||
fh.Close()
|
||||
|
||||
data, _ := ReadFile(ufs, "/data/file.txt")
|
||||
if string(data) != "Another test" {
|
||||
t.Errorf("cache time failed: <%s>", data)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCacheOnReadFsNotInLayer(t *testing.T) {
|
||||
base := NewMemMapFs()
|
||||
layer := NewMemMapFs()
|
||||
fs := NewCacheOnReadFs(base, layer, 0)
|
||||
|
||||
fh, err := base.Create("/file.txt")
|
||||
if err != nil {
|
||||
t.Fatal("unable to create file: ", err)
|
||||
}
|
||||
|
||||
txt := []byte("This is a test")
|
||||
fh.Write(txt)
|
||||
fh.Close()
|
||||
|
||||
fh, err = fs.Open("/file.txt")
|
||||
if err != nil {
|
||||
t.Fatal("could not open file: ", err)
|
||||
}
|
||||
|
||||
b, err := ReadAll(fh)
|
||||
fh.Close()
|
||||
|
||||
if err != nil {
|
||||
t.Fatal("could not read file: ", err)
|
||||
} else if !bytes.Equal(txt, b) {
|
||||
t.Fatalf("wanted file text %q, got %q", txt, b)
|
||||
}
|
||||
|
||||
fh, err = layer.Open("/file.txt")
|
||||
if err != nil {
|
||||
t.Fatal("could not open file from layer: ", err)
|
||||
}
|
||||
fh.Close()
|
||||
}
|
||||
53
vendor/github.com/spf13/afero/copyOnWriteFs.go
сгенерированный
поставляемый
53
vendor/github.com/spf13/afero/copyOnWriteFs.go
сгенерированный
поставляемый
@@ -8,6 +8,8 @@ import (
|
||||
"time"
|
||||
)
|
||||
|
||||
var _ Lstater = (*CopyOnWriteFs)(nil)
|
||||
|
||||
// The CopyOnWriteFs is a union filesystem: a read only base file system with
|
||||
// a possibly writeable layer on top. Changes to the file system will only
|
||||
// be made in the overlay: Changing an existing file in the base layer which
|
||||
@@ -76,18 +78,55 @@ func (u *CopyOnWriteFs) Chmod(name string, mode os.FileMode) error {
|
||||
func (u *CopyOnWriteFs) Stat(name string) (os.FileInfo, error) {
|
||||
fi, err := u.layer.Stat(name)
|
||||
if err != nil {
|
||||
origErr := err
|
||||
if e, ok := err.(*os.PathError); ok {
|
||||
err = e.Err
|
||||
}
|
||||
if err == os.ErrNotExist || err == syscall.ENOENT || err == syscall.ENOTDIR {
|
||||
isNotExist := u.isNotExist(err)
|
||||
if isNotExist {
|
||||
return u.base.Stat(name)
|
||||
}
|
||||
return nil, origErr
|
||||
return nil, err
|
||||
}
|
||||
return fi, nil
|
||||
}
|
||||
|
||||
func (u *CopyOnWriteFs) LstatIfPossible(name string) (os.FileInfo, bool, error) {
|
||||
llayer, ok1 := u.layer.(Lstater)
|
||||
lbase, ok2 := u.base.(Lstater)
|
||||
|
||||
if ok1 {
|
||||
fi, b, err := llayer.LstatIfPossible(name)
|
||||
if err == nil {
|
||||
return fi, b, nil
|
||||
}
|
||||
|
||||
if !u.isNotExist(err) {
|
||||
return nil, b, err
|
||||
}
|
||||
}
|
||||
|
||||
if ok2 {
|
||||
fi, b, err := lbase.LstatIfPossible(name)
|
||||
if err == nil {
|
||||
return fi, b, nil
|
||||
}
|
||||
if !u.isNotExist(err) {
|
||||
return nil, b, err
|
||||
}
|
||||
}
|
||||
|
||||
fi, err := u.Stat(name)
|
||||
|
||||
return fi, false, err
|
||||
}
|
||||
|
||||
func (u *CopyOnWriteFs) isNotExist(err error) bool {
|
||||
if e, ok := err.(*os.PathError); ok {
|
||||
err = e.Err
|
||||
}
|
||||
if err == os.ErrNotExist || err == syscall.ENOENT || err == syscall.ENOTDIR {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// Renaming files present only in the base layer is not permitted
|
||||
func (u *CopyOnWriteFs) Rename(oldname, newname string) error {
|
||||
b, err := u.isBaseFile(oldname)
|
||||
@@ -219,7 +258,7 @@ func (u *CopyOnWriteFs) Open(name string) (File, error) {
|
||||
return nil, fmt.Errorf("BaseErr: %v\nOverlayErr: %v", bErr, lErr)
|
||||
}
|
||||
|
||||
return &UnionFile{base: bfile, layer: lfile}, nil
|
||||
return &UnionFile{Base: bfile, Layer: lfile}, nil
|
||||
}
|
||||
|
||||
func (u *CopyOnWriteFs) Mkdir(name string, perm os.FileMode) error {
|
||||
|
||||
39
vendor/github.com/spf13/afero/copyOnWriteFs_test.go
сгенерированный
поставляемый
39
vendor/github.com/spf13/afero/copyOnWriteFs_test.go
сгенерированный
поставляемый
@@ -1,39 +0,0 @@
|
||||
package afero
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestCopyOnWrite(t *testing.T) {
|
||||
var fs Fs
|
||||
var err error
|
||||
base := NewOsFs()
|
||||
roBase := NewReadOnlyFs(base)
|
||||
ufs := NewCopyOnWriteFs(roBase, NewMemMapFs())
|
||||
fs = ufs
|
||||
err = fs.MkdirAll("nonexistent/directory/", 0744)
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
return
|
||||
}
|
||||
_, err = fs.Create("nonexistent/directory/newfile")
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
return
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
func TestCopyOnWriteFileInMemMapBase(t *testing.T) {
|
||||
base := &MemMapFs{}
|
||||
layer := &MemMapFs{}
|
||||
|
||||
if err := WriteFile(base, "base.txt", []byte("base"), 0755); err != nil {
|
||||
t.Fatalf("Failed to write file: %s", err)
|
||||
}
|
||||
|
||||
ufs := NewCopyOnWriteFs(base, layer)
|
||||
|
||||
_, err := ufs.Stat("base.txt")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
112
vendor/github.com/spf13/afero/ioutil_test.go
сгенерированный
поставляемый
112
vendor/github.com/spf13/afero/ioutil_test.go
сгенерированный
поставляемый
@@ -1,112 +0,0 @@
|
||||
// ©2015 The Go Authors
|
||||
// Copyright ©2015 Steve Francia <spf@spf13.com>
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package afero
|
||||
|
||||
import "testing"
|
||||
|
||||
func checkSizePath(t *testing.T, path string, size int64) {
|
||||
dir, err := testFS.Stat(path)
|
||||
if err != nil {
|
||||
t.Fatalf("Stat %q (looking for size %d): %s", path, size, err)
|
||||
}
|
||||
if dir.Size() != size {
|
||||
t.Errorf("Stat %q: size %d want %d", path, dir.Size(), size)
|
||||
}
|
||||
}
|
||||
|
||||
func TestReadFile(t *testing.T) {
|
||||
testFS = &MemMapFs{}
|
||||
fsutil := &Afero{Fs: testFS}
|
||||
|
||||
testFS.Create("this_exists.go")
|
||||
filename := "rumpelstilzchen"
|
||||
contents, err := fsutil.ReadFile(filename)
|
||||
if err == nil {
|
||||
t.Fatalf("ReadFile %s: error expected, none found", filename)
|
||||
}
|
||||
|
||||
filename = "this_exists.go"
|
||||
contents, err = fsutil.ReadFile(filename)
|
||||
if err != nil {
|
||||
t.Fatalf("ReadFile %s: %v", filename, err)
|
||||
}
|
||||
|
||||
checkSizePath(t, filename, int64(len(contents)))
|
||||
}
|
||||
|
||||
func TestWriteFile(t *testing.T) {
|
||||
testFS = &MemMapFs{}
|
||||
fsutil := &Afero{Fs: testFS}
|
||||
f, err := fsutil.TempFile("", "ioutil-test")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
filename := f.Name()
|
||||
data := "Programming today is a race between software engineers striving to " +
|
||||
"build bigger and better idiot-proof programs, and the Universe trying " +
|
||||
"to produce bigger and better idiots. So far, the Universe is winning."
|
||||
|
||||
if err := fsutil.WriteFile(filename, []byte(data), 0644); err != nil {
|
||||
t.Fatalf("WriteFile %s: %v", filename, err)
|
||||
}
|
||||
|
||||
contents, err := fsutil.ReadFile(filename)
|
||||
if err != nil {
|
||||
t.Fatalf("ReadFile %s: %v", filename, err)
|
||||
}
|
||||
|
||||
if string(contents) != data {
|
||||
t.Fatalf("contents = %q\nexpected = %q", string(contents), data)
|
||||
}
|
||||
|
||||
// cleanup
|
||||
f.Close()
|
||||
testFS.Remove(filename) // ignore error
|
||||
}
|
||||
|
||||
func TestReadDir(t *testing.T) {
|
||||
testFS = &MemMapFs{}
|
||||
testFS.Mkdir("/i-am-a-dir", 0777)
|
||||
testFS.Create("/this_exists.go")
|
||||
dirname := "rumpelstilzchen"
|
||||
_, err := ReadDir(testFS, dirname)
|
||||
if err == nil {
|
||||
t.Fatalf("ReadDir %s: error expected, none found", dirname)
|
||||
}
|
||||
|
||||
dirname = ".."
|
||||
list, err := ReadDir(testFS, dirname)
|
||||
if err != nil {
|
||||
t.Fatalf("ReadDir %s: %v", dirname, err)
|
||||
}
|
||||
|
||||
foundFile := false
|
||||
foundSubDir := false
|
||||
for _, dir := range list {
|
||||
switch {
|
||||
case !dir.IsDir() && dir.Name() == "this_exists.go":
|
||||
foundFile = true
|
||||
case dir.IsDir() && dir.Name() == "i-am-a-dir":
|
||||
foundSubDir = true
|
||||
}
|
||||
}
|
||||
if !foundFile {
|
||||
t.Fatalf("ReadDir %s: this_exists.go file not found", dirname)
|
||||
}
|
||||
if !foundSubDir {
|
||||
t.Fatalf("ReadDir %s: i-am-a-dir directory not found", dirname)
|
||||
}
|
||||
}
|
||||
17
vendor/github.com/spf13/cobra/cobra/main.go → vendor/github.com/spf13/afero/lstater.go
сгенерированный
поставляемый
17
vendor/github.com/spf13/cobra/cobra/main.go → vendor/github.com/spf13/afero/lstater.go
сгенерированный
поставляемый
@@ -1,4 +1,4 @@
|
||||
// Copyright © 2015 Steve Francia <spf@spf13.com>.
|
||||
// Copyright © 2018 Steve Francia <spf@spf13.com>.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
@@ -11,10 +11,17 @@
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package main
|
||||
package afero
|
||||
|
||||
import "github.com/spf13/cobra/cobra/cmd"
|
||||
import (
|
||||
"os"
|
||||
)
|
||||
|
||||
func main() {
|
||||
cmd.Execute()
|
||||
// Lstater is an optional interface in Afero. It is only implemented by the
|
||||
// filesystems saying so.
|
||||
// It will call Lstat if the filesystem iself is, or it delegates to, the os filesystem.
|
||||
// Else it will call Stat.
|
||||
// In addtion to the FileInfo, it will return a boolean telling whether Lstat was called or not.
|
||||
type Lstater interface {
|
||||
LstatIfPossible(name string) (os.FileInfo, bool, error)
|
||||
}
|
||||
4
vendor/github.com/spf13/afero/match.go
сгенерированный
поставляемый
4
vendor/github.com/spf13/afero/match.go
сгенерированный
поставляемый
@@ -33,8 +33,8 @@ import (
|
||||
// built-ins from that package.
|
||||
func Glob(fs Fs, pattern string) (matches []string, err error) {
|
||||
if !hasMeta(pattern) {
|
||||
// afero does not support Lstat directly.
|
||||
if _, err = lstatIfOs(fs, pattern); err != nil {
|
||||
// Lstat not supported by a ll filesystems.
|
||||
if _, err = lstatIfPossible(fs, pattern); err != nil {
|
||||
return nil, nil
|
||||
}
|
||||
return []string{pattern}, nil
|
||||
|
||||
183
vendor/github.com/spf13/afero/match_test.go
сгенерированный
поставляемый
183
vendor/github.com/spf13/afero/match_test.go
сгенерированный
поставляемый
@@ -1,183 +0,0 @@
|
||||
// Copyright © 2014 Steve Francia <spf@spf13.com>.
|
||||
// Copyright 2009 The Go Authors. All rights reserved.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package afero
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// contains returns true if vector contains the string s.
|
||||
func contains(vector []string, s string) bool {
|
||||
for _, elem := range vector {
|
||||
if elem == s {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func setupGlobDirRoot(t *testing.T, fs Fs) string {
|
||||
path := testDir(fs)
|
||||
setupGlobFiles(t, fs, path)
|
||||
return path
|
||||
}
|
||||
|
||||
func setupGlobDirReusePath(t *testing.T, fs Fs, path string) string {
|
||||
testRegistry[fs] = append(testRegistry[fs], path)
|
||||
return setupGlobFiles(t, fs, path)
|
||||
}
|
||||
|
||||
func setupGlobFiles(t *testing.T, fs Fs, path string) string {
|
||||
testSubDir := filepath.Join(path, "globs", "bobs")
|
||||
err := fs.MkdirAll(testSubDir, 0700)
|
||||
if err != nil && !os.IsExist(err) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
f, err := fs.Create(filepath.Join(testSubDir, "/matcher"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
f.WriteString("Testfile 1 content")
|
||||
f.Close()
|
||||
|
||||
f, err = fs.Create(filepath.Join(testSubDir, "/../submatcher"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
f.WriteString("Testfile 2 content")
|
||||
f.Close()
|
||||
|
||||
f, err = fs.Create(filepath.Join(testSubDir, "/../../match"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
f.WriteString("Testfile 3 content")
|
||||
f.Close()
|
||||
|
||||
return testSubDir
|
||||
}
|
||||
|
||||
func TestGlob(t *testing.T) {
|
||||
defer removeAllTestFiles(t)
|
||||
var testDir string
|
||||
for i, fs := range Fss {
|
||||
if i == 0 {
|
||||
testDir = setupGlobDirRoot(t, fs)
|
||||
} else {
|
||||
setupGlobDirReusePath(t, fs, testDir)
|
||||
}
|
||||
}
|
||||
|
||||
var globTests = []struct {
|
||||
pattern, result string
|
||||
}{
|
||||
{testDir + "/globs/bobs/matcher", testDir + "/globs/bobs/matcher"},
|
||||
{testDir + "/globs/*/mat?her", testDir + "/globs/bobs/matcher"},
|
||||
{testDir + "/globs/bobs/../*", testDir + "/globs/submatcher"},
|
||||
{testDir + "/match", testDir + "/match"},
|
||||
}
|
||||
|
||||
for _, fs := range Fss {
|
||||
|
||||
for _, tt := range globTests {
|
||||
pattern := tt.pattern
|
||||
result := tt.result
|
||||
if runtime.GOOS == "windows" {
|
||||
pattern = filepath.Clean(pattern)
|
||||
result = filepath.Clean(result)
|
||||
}
|
||||
matches, err := Glob(fs, pattern)
|
||||
if err != nil {
|
||||
t.Errorf("Glob error for %q: %s", pattern, err)
|
||||
continue
|
||||
}
|
||||
if !contains(matches, result) {
|
||||
t.Errorf("Glob(%#q) = %#v want %v", pattern, matches, result)
|
||||
}
|
||||
}
|
||||
for _, pattern := range []string{"no_match", "../*/no_match"} {
|
||||
matches, err := Glob(fs, pattern)
|
||||
if err != nil {
|
||||
t.Errorf("Glob error for %q: %s", pattern, err)
|
||||
continue
|
||||
}
|
||||
if len(matches) != 0 {
|
||||
t.Errorf("Glob(%#q) = %#v want []", pattern, matches)
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
func TestGlobSymlink(t *testing.T) {
|
||||
defer removeAllTestFiles(t)
|
||||
|
||||
fs := &OsFs{}
|
||||
testDir := setupGlobDirRoot(t, fs)
|
||||
|
||||
err := os.Symlink("target", filepath.Join(testDir, "symlink"))
|
||||
if err != nil {
|
||||
t.Skipf("skipping on %s", runtime.GOOS)
|
||||
}
|
||||
|
||||
var globSymlinkTests = []struct {
|
||||
path, dest string
|
||||
brokenLink bool
|
||||
}{
|
||||
{"test1", "link1", false},
|
||||
{"test2", "link2", true},
|
||||
}
|
||||
|
||||
for _, tt := range globSymlinkTests {
|
||||
path := filepath.Join(testDir, tt.path)
|
||||
dest := filepath.Join(testDir, tt.dest)
|
||||
f, err := fs.Create(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := f.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
err = os.Symlink(path, dest)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if tt.brokenLink {
|
||||
// Break the symlink.
|
||||
fs.Remove(path)
|
||||
}
|
||||
matches, err := Glob(fs, dest)
|
||||
if err != nil {
|
||||
t.Errorf("GlobSymlink error for %q: %s", dest, err)
|
||||
}
|
||||
if !contains(matches, dest) {
|
||||
t.Errorf("Glob(%#q) = %#v want %v", dest, matches, dest)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
func TestGlobError(t *testing.T) {
|
||||
for _, fs := range Fss {
|
||||
_, err := Glob(fs, "[7]")
|
||||
if err != nil {
|
||||
t.Error("expected error for bad pattern; got none")
|
||||
}
|
||||
}
|
||||
}
|
||||
154
vendor/github.com/spf13/afero/mem/file_test.go
сгенерированный
поставляемый
154
vendor/github.com/spf13/afero/mem/file_test.go
сгенерированный
поставляемый
@@ -1,154 +0,0 @@
|
||||
package mem
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestFileDataNameRace(t *testing.T) {
|
||||
t.Parallel()
|
||||
const someName = "someName"
|
||||
const someOtherName = "someOtherName"
|
||||
d := FileData{
|
||||
name: someName,
|
||||
}
|
||||
|
||||
if d.Name() != someName {
|
||||
t.Errorf("Failed to read correct Name, was %v", d.Name())
|
||||
}
|
||||
|
||||
ChangeFileName(&d, someOtherName)
|
||||
if d.Name() != someOtherName {
|
||||
t.Errorf("Failed to set Name, was %v", d.Name())
|
||||
}
|
||||
|
||||
go func() {
|
||||
ChangeFileName(&d, someName)
|
||||
}()
|
||||
|
||||
if d.Name() != someName && d.Name() != someOtherName {
|
||||
t.Errorf("Failed to read either Name, was %v", d.Name())
|
||||
}
|
||||
}
|
||||
|
||||
func TestFileDataModTimeRace(t *testing.T) {
|
||||
t.Parallel()
|
||||
someTime := time.Now()
|
||||
someOtherTime := someTime.Add(1 * time.Minute)
|
||||
|
||||
d := FileData{
|
||||
modtime: someTime,
|
||||
}
|
||||
|
||||
s := FileInfo{
|
||||
FileData: &d,
|
||||
}
|
||||
|
||||
if s.ModTime() != someTime {
|
||||
t.Errorf("Failed to read correct value, was %v", s.ModTime())
|
||||
}
|
||||
|
||||
SetModTime(&d, someOtherTime)
|
||||
if s.ModTime() != someOtherTime {
|
||||
t.Errorf("Failed to set ModTime, was %v", s.ModTime())
|
||||
}
|
||||
|
||||
go func() {
|
||||
SetModTime(&d, someTime)
|
||||
}()
|
||||
|
||||
if s.ModTime() != someTime && s.ModTime() != someOtherTime {
|
||||
t.Errorf("Failed to read either modtime, was %v", s.ModTime())
|
||||
}
|
||||
}
|
||||
|
||||
func TestFileDataModeRace(t *testing.T) {
|
||||
t.Parallel()
|
||||
const someMode = 0777
|
||||
const someOtherMode = 0660
|
||||
|
||||
d := FileData{
|
||||
mode: someMode,
|
||||
}
|
||||
|
||||
s := FileInfo{
|
||||
FileData: &d,
|
||||
}
|
||||
|
||||
if s.Mode() != someMode {
|
||||
t.Errorf("Failed to read correct value, was %v", s.Mode())
|
||||
}
|
||||
|
||||
SetMode(&d, someOtherMode)
|
||||
if s.Mode() != someOtherMode {
|
||||
t.Errorf("Failed to set Mode, was %v", s.Mode())
|
||||
}
|
||||
|
||||
go func() {
|
||||
SetMode(&d, someMode)
|
||||
}()
|
||||
|
||||
if s.Mode() != someMode && s.Mode() != someOtherMode {
|
||||
t.Errorf("Failed to read either mode, was %v", s.Mode())
|
||||
}
|
||||
}
|
||||
|
||||
func TestFileDataIsDirRace(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
d := FileData{
|
||||
dir: true,
|
||||
}
|
||||
|
||||
s := FileInfo{
|
||||
FileData: &d,
|
||||
}
|
||||
|
||||
if s.IsDir() != true {
|
||||
t.Errorf("Failed to read correct value, was %v", s.IsDir())
|
||||
}
|
||||
|
||||
go func() {
|
||||
s.Lock()
|
||||
d.dir = false
|
||||
s.Unlock()
|
||||
}()
|
||||
|
||||
//just logging the value to trigger a read:
|
||||
t.Logf("Value is %v", s.IsDir())
|
||||
}
|
||||
|
||||
func TestFileDataSizeRace(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
const someData = "Hello"
|
||||
const someOtherDataSize = "Hello World"
|
||||
|
||||
d := FileData{
|
||||
data: []byte(someData),
|
||||
dir: false,
|
||||
}
|
||||
|
||||
s := FileInfo{
|
||||
FileData: &d,
|
||||
}
|
||||
|
||||
if s.Size() != int64(len(someData)) {
|
||||
t.Errorf("Failed to read correct value, was %v", s.Size())
|
||||
}
|
||||
|
||||
go func() {
|
||||
s.Lock()
|
||||
d.data = []byte(someOtherDataSize)
|
||||
s.Unlock()
|
||||
}()
|
||||
|
||||
//just logging the value to trigger a read:
|
||||
t.Logf("Value is %v", s.Size())
|
||||
|
||||
//Testing the Dir size case
|
||||
d.dir = true
|
||||
if s.Size() != int64(42) {
|
||||
t.Errorf("Failed to read correct value for dir, was %v", s.Size())
|
||||
}
|
||||
}
|
||||
451
vendor/github.com/spf13/afero/memmap_test.go
сгенерированный
поставляемый
451
vendor/github.com/spf13/afero/memmap_test.go
сгенерированный
поставляемый
@@ -1,451 +0,0 @@
|
||||
package afero
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestNormalizePath(t *testing.T) {
|
||||
type test struct {
|
||||
input string
|
||||
expected string
|
||||
}
|
||||
|
||||
data := []test{
|
||||
{".", FilePathSeparator},
|
||||
{"./", FilePathSeparator},
|
||||
{"..", FilePathSeparator},
|
||||
{"../", FilePathSeparator},
|
||||
{"./..", FilePathSeparator},
|
||||
{"./../", FilePathSeparator},
|
||||
}
|
||||
|
||||
for i, d := range data {
|
||||
cpath := normalizePath(d.input)
|
||||
if d.expected != cpath {
|
||||
t.Errorf("Test %d failed. Expected %q got %q", i, d.expected, cpath)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestPathErrors(t *testing.T) {
|
||||
path := filepath.Join(".", "some", "path")
|
||||
path2 := filepath.Join(".", "different", "path")
|
||||
fs := NewMemMapFs()
|
||||
perm := os.FileMode(0755)
|
||||
|
||||
// relevant functions:
|
||||
// func (m *MemMapFs) Chmod(name string, mode os.FileMode) error
|
||||
// func (m *MemMapFs) Chtimes(name string, atime time.Time, mtime time.Time) error
|
||||
// func (m *MemMapFs) Create(name string) (File, error)
|
||||
// func (m *MemMapFs) Mkdir(name string, perm os.FileMode) error
|
||||
// func (m *MemMapFs) MkdirAll(path string, perm os.FileMode) error
|
||||
// func (m *MemMapFs) Open(name string) (File, error)
|
||||
// func (m *MemMapFs) OpenFile(name string, flag int, perm os.FileMode) (File, error)
|
||||
// func (m *MemMapFs) Remove(name string) error
|
||||
// func (m *MemMapFs) Rename(oldname, newname string) error
|
||||
// func (m *MemMapFs) Stat(name string) (os.FileInfo, error)
|
||||
|
||||
err := fs.Chmod(path, perm)
|
||||
checkPathError(t, err, "Chmod")
|
||||
|
||||
err = fs.Chtimes(path, time.Now(), time.Now())
|
||||
checkPathError(t, err, "Chtimes")
|
||||
|
||||
// fs.Create doesn't return an error
|
||||
|
||||
err = fs.Mkdir(path2, perm)
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
err = fs.Mkdir(path2, perm)
|
||||
checkPathError(t, err, "Mkdir")
|
||||
|
||||
err = fs.MkdirAll(path2, perm)
|
||||
if err != nil {
|
||||
t.Error("MkdirAll:", err)
|
||||
}
|
||||
|
||||
_, err = fs.Open(path)
|
||||
checkPathError(t, err, "Open")
|
||||
|
||||
_, err = fs.OpenFile(path, os.O_RDWR, perm)
|
||||
checkPathError(t, err, "OpenFile")
|
||||
|
||||
err = fs.Remove(path)
|
||||
checkPathError(t, err, "Remove")
|
||||
|
||||
err = fs.RemoveAll(path)
|
||||
if err != nil {
|
||||
t.Error("RemoveAll:", err)
|
||||
}
|
||||
|
||||
err = fs.Rename(path, path2)
|
||||
checkPathError(t, err, "Rename")
|
||||
|
||||
_, err = fs.Stat(path)
|
||||
checkPathError(t, err, "Stat")
|
||||
}
|
||||
|
||||
func checkPathError(t *testing.T, err error, op string) {
|
||||
pathErr, ok := err.(*os.PathError)
|
||||
if !ok {
|
||||
t.Error(op+":", err, "is not a os.PathError")
|
||||
return
|
||||
}
|
||||
_, ok = pathErr.Err.(*os.PathError)
|
||||
if ok {
|
||||
t.Error(op+":", err, "contains another os.PathError")
|
||||
}
|
||||
}
|
||||
|
||||
// Ensure Permissions are set on OpenFile/Mkdir/MkdirAll
|
||||
func TestPermSet(t *testing.T) {
|
||||
const fileName = "/myFileTest"
|
||||
const dirPath = "/myDirTest"
|
||||
const dirPathAll = "/my/path/to/dir"
|
||||
|
||||
const fileMode = os.FileMode(0765)
|
||||
// directories will also have the directory bit set
|
||||
const dirMode = fileMode | os.ModeDir
|
||||
|
||||
fs := NewMemMapFs()
|
||||
|
||||
// Test Openfile
|
||||
f, err := fs.OpenFile(fileName, os.O_CREATE, fileMode)
|
||||
if err != nil {
|
||||
t.Errorf("OpenFile Create failed: %s", err)
|
||||
return
|
||||
}
|
||||
f.Close()
|
||||
|
||||
s, err := fs.Stat(fileName)
|
||||
if err != nil {
|
||||
t.Errorf("Stat failed: %s", err)
|
||||
return
|
||||
}
|
||||
if s.Mode().String() != fileMode.String() {
|
||||
t.Errorf("Permissions Incorrect: %s != %s", s.Mode().String(), fileMode.String())
|
||||
return
|
||||
}
|
||||
|
||||
// Test Mkdir
|
||||
err = fs.Mkdir(dirPath, dirMode)
|
||||
if err != nil {
|
||||
t.Errorf("MkDir Create failed: %s", err)
|
||||
return
|
||||
}
|
||||
s, err = fs.Stat(dirPath)
|
||||
if err != nil {
|
||||
t.Errorf("Stat failed: %s", err)
|
||||
return
|
||||
}
|
||||
// sets File
|
||||
if s.Mode().String() != dirMode.String() {
|
||||
t.Errorf("Permissions Incorrect: %s != %s", s.Mode().String(), dirMode.String())
|
||||
return
|
||||
}
|
||||
|
||||
// Test MkdirAll
|
||||
err = fs.MkdirAll(dirPathAll, dirMode)
|
||||
if err != nil {
|
||||
t.Errorf("MkDir Create failed: %s", err)
|
||||
return
|
||||
}
|
||||
s, err = fs.Stat(dirPathAll)
|
||||
if err != nil {
|
||||
t.Errorf("Stat failed: %s", err)
|
||||
return
|
||||
}
|
||||
if s.Mode().String() != dirMode.String() {
|
||||
t.Errorf("Permissions Incorrect: %s != %s", s.Mode().String(), dirMode.String())
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// Fails if multiple file objects use the same file.at counter in MemMapFs
|
||||
func TestMultipleOpenFiles(t *testing.T) {
|
||||
defer removeAllTestFiles(t)
|
||||
const fileName = "afero-demo2.txt"
|
||||
|
||||
var data = make([][]byte, len(Fss))
|
||||
|
||||
for i, fs := range Fss {
|
||||
dir := testDir(fs)
|
||||
path := filepath.Join(dir, fileName)
|
||||
fh1, err := fs.Create(path)
|
||||
if err != nil {
|
||||
t.Error("fs.Create failed: " + err.Error())
|
||||
}
|
||||
_, err = fh1.Write([]byte("test"))
|
||||
if err != nil {
|
||||
t.Error("fh.Write failed: " + err.Error())
|
||||
}
|
||||
_, err = fh1.Seek(0, os.SEEK_SET)
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
|
||||
fh2, err := fs.OpenFile(path, os.O_RDWR, 0777)
|
||||
if err != nil {
|
||||
t.Error("fs.OpenFile failed: " + err.Error())
|
||||
}
|
||||
_, err = fh2.Seek(0, os.SEEK_END)
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
_, err = fh2.Write([]byte("data"))
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
err = fh2.Close()
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
|
||||
_, err = fh1.Write([]byte("data"))
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
err = fh1.Close()
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
// the file now should contain "datadata"
|
||||
data[i], err = ReadFile(fs, path)
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
}
|
||||
|
||||
for i, fs := range Fss {
|
||||
if i == 0 {
|
||||
continue
|
||||
}
|
||||
if string(data[0]) != string(data[i]) {
|
||||
t.Errorf("%s and %s don't behave the same\n"+
|
||||
"%s: \"%s\"\n%s: \"%s\"\n",
|
||||
Fss[0].Name(), fs.Name(), Fss[0].Name(), data[0], fs.Name(), data[i])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Test if file.Write() fails when opened as read only
|
||||
func TestReadOnly(t *testing.T) {
|
||||
defer removeAllTestFiles(t)
|
||||
const fileName = "afero-demo.txt"
|
||||
|
||||
for _, fs := range Fss {
|
||||
dir := testDir(fs)
|
||||
path := filepath.Join(dir, fileName)
|
||||
|
||||
f, err := fs.Create(path)
|
||||
if err != nil {
|
||||
t.Error(fs.Name()+":", "fs.Create failed: "+err.Error())
|
||||
}
|
||||
_, err = f.Write([]byte("test"))
|
||||
if err != nil {
|
||||
t.Error(fs.Name()+":", "Write failed: "+err.Error())
|
||||
}
|
||||
f.Close()
|
||||
|
||||
f, err = fs.Open(path)
|
||||
if err != nil {
|
||||
t.Error("fs.Open failed: " + err.Error())
|
||||
}
|
||||
_, err = f.Write([]byte("data"))
|
||||
if err == nil {
|
||||
t.Error(fs.Name()+":", "No write error")
|
||||
}
|
||||
f.Close()
|
||||
|
||||
f, err = fs.OpenFile(path, os.O_RDONLY, 0644)
|
||||
if err != nil {
|
||||
t.Error("fs.Open failed: " + err.Error())
|
||||
}
|
||||
_, err = f.Write([]byte("data"))
|
||||
if err == nil {
|
||||
t.Error(fs.Name()+":", "No write error")
|
||||
}
|
||||
f.Close()
|
||||
}
|
||||
}
|
||||
|
||||
func TestWriteCloseTime(t *testing.T) {
|
||||
defer removeAllTestFiles(t)
|
||||
const fileName = "afero-demo.txt"
|
||||
|
||||
for _, fs := range Fss {
|
||||
dir := testDir(fs)
|
||||
path := filepath.Join(dir, fileName)
|
||||
|
||||
f, err := fs.Create(path)
|
||||
if err != nil {
|
||||
t.Error(fs.Name()+":", "fs.Create failed: "+err.Error())
|
||||
}
|
||||
f.Close()
|
||||
|
||||
f, err = fs.Create(path)
|
||||
if err != nil {
|
||||
t.Error(fs.Name()+":", "fs.Create failed: "+err.Error())
|
||||
}
|
||||
fi, err := f.Stat()
|
||||
if err != nil {
|
||||
t.Error(fs.Name()+":", "Stat failed: "+err.Error())
|
||||
}
|
||||
timeBefore := fi.ModTime()
|
||||
|
||||
// sorry for the delay, but we have to make sure time advances,
|
||||
// also on non Un*x systems...
|
||||
switch runtime.GOOS {
|
||||
case "windows":
|
||||
time.Sleep(2 * time.Second)
|
||||
case "darwin":
|
||||
time.Sleep(1 * time.Second)
|
||||
default: // depending on the FS, this may work with < 1 second, on my old ext3 it does not
|
||||
time.Sleep(1 * time.Second)
|
||||
}
|
||||
|
||||
_, err = f.Write([]byte("test"))
|
||||
if err != nil {
|
||||
t.Error(fs.Name()+":", "Write failed: "+err.Error())
|
||||
}
|
||||
f.Close()
|
||||
fi, err = fs.Stat(path)
|
||||
if err != nil {
|
||||
t.Error(fs.Name()+":", "fs.Stat failed: "+err.Error())
|
||||
}
|
||||
if fi.ModTime().Equal(timeBefore) {
|
||||
t.Error(fs.Name()+":", "ModTime was not set on Close()")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// This test should be run with the race detector on:
|
||||
// go test -race -v -timeout 10s -run TestRacingDeleteAndClose
|
||||
func TestRacingDeleteAndClose(t *testing.T) {
|
||||
fs := NewMemMapFs()
|
||||
pathname := "testfile"
|
||||
f, err := fs.Create(pathname)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
in := make(chan bool)
|
||||
|
||||
go func() {
|
||||
<-in
|
||||
f.Close()
|
||||
}()
|
||||
go func() {
|
||||
<-in
|
||||
fs.Remove(pathname)
|
||||
}()
|
||||
close(in)
|
||||
}
|
||||
|
||||
// This test should be run with the race detector on:
|
||||
// go test -run TestMemFsDataRace -race
|
||||
func TestMemFsDataRace(t *testing.T) {
|
||||
const dir = "test_dir"
|
||||
fs := NewMemMapFs()
|
||||
|
||||
if err := fs.MkdirAll(dir, 0777); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
const n = 1000
|
||||
done := make(chan struct{})
|
||||
|
||||
go func() {
|
||||
defer close(done)
|
||||
for i := 0; i < n; i++ {
|
||||
fname := filepath.Join(dir, fmt.Sprintf("%d.txt", i))
|
||||
if err := WriteFile(fs, fname, []byte(""), 0777); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
if err := fs.Remove(fname); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
||||
loop:
|
||||
for {
|
||||
select {
|
||||
case <-done:
|
||||
break loop
|
||||
default:
|
||||
_, err := ReadDir(fs, dir)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestMemFsDirMode(t *testing.T) {
|
||||
fs := NewMemMapFs()
|
||||
err := fs.Mkdir("/testDir1", 0644)
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
err = fs.MkdirAll("/sub/testDir2", 0644)
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
info, err := fs.Stat("/testDir1")
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
if !info.IsDir() {
|
||||
t.Error("should be a directory")
|
||||
}
|
||||
if !info.Mode().IsDir() {
|
||||
t.Error("FileMode is not directory")
|
||||
}
|
||||
info, err = fs.Stat("/sub/testDir2")
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
if !info.IsDir() {
|
||||
t.Error("should be a directory")
|
||||
}
|
||||
if !info.Mode().IsDir() {
|
||||
t.Error("FileMode is not directory")
|
||||
}
|
||||
}
|
||||
|
||||
func TestMemFsUnexpectedEOF(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
fs := NewMemMapFs()
|
||||
|
||||
if err := WriteFile(fs, "file.txt", []byte("abc"), 0777); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
f, err := fs.Open("file.txt")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer f.Close()
|
||||
|
||||
// Seek beyond the end.
|
||||
_, err = f.Seek(512, 0)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
buff := make([]byte, 256)
|
||||
_, err = io.ReadAtLeast(f, buff, 256)
|
||||
|
||||
if err != io.ErrUnexpectedEOF {
|
||||
t.Fatal("Expected ErrUnexpectedEOF")
|
||||
}
|
||||
}
|
||||
7
vendor/github.com/spf13/afero/os.go
сгенерированный
поставляемый
7
vendor/github.com/spf13/afero/os.go
сгенерированный
поставляемый
@@ -19,6 +19,8 @@ import (
|
||||
"time"
|
||||
)
|
||||
|
||||
var _ Lstater = (*OsFs)(nil)
|
||||
|
||||
// OsFs is a Fs implementation that uses functions provided by the os package.
|
||||
//
|
||||
// For details in any method, check the documentation of the os package
|
||||
@@ -92,3 +94,8 @@ func (OsFs) Chmod(name string, mode os.FileMode) error {
|
||||
func (OsFs) Chtimes(name string, atime time.Time, mtime time.Time) error {
|
||||
return os.Chtimes(name, atime, mtime)
|
||||
}
|
||||
|
||||
func (OsFs) LstatIfPossible(name string) (os.FileInfo, bool, error) {
|
||||
fi, err := os.Lstat(name)
|
||||
return fi, true, err
|
||||
}
|
||||
|
||||
18
vendor/github.com/spf13/afero/path.go
сгенерированный
поставляемый
18
vendor/github.com/spf13/afero/path.go
сгенерированный
поставляемый
@@ -60,7 +60,7 @@ func walk(fs Fs, path string, info os.FileInfo, walkFn filepath.WalkFunc) error
|
||||
|
||||
for _, name := range names {
|
||||
filename := filepath.Join(path, name)
|
||||
fileInfo, err := lstatIfOs(fs, filename)
|
||||
fileInfo, err := lstatIfPossible(fs, filename)
|
||||
if err != nil {
|
||||
if err := walkFn(filename, fileInfo, err); err != nil && err != filepath.SkipDir {
|
||||
return err
|
||||
@@ -77,15 +77,13 @@ func walk(fs Fs, path string, info os.FileInfo, walkFn filepath.WalkFunc) error
|
||||
return nil
|
||||
}
|
||||
|
||||
// if the filesystem is OsFs use Lstat, else use fs.Stat
|
||||
func lstatIfOs(fs Fs, path string) (info os.FileInfo, err error) {
|
||||
_, ok := fs.(*OsFs)
|
||||
if ok {
|
||||
info, err = os.Lstat(path)
|
||||
} else {
|
||||
info, err = fs.Stat(path)
|
||||
// if the filesystem supports it, use Lstat, else use fs.Stat
|
||||
func lstatIfPossible(fs Fs, path string) (os.FileInfo, error) {
|
||||
if lfs, ok := fs.(Lstater); ok {
|
||||
fi, _, err := lfs.LstatIfPossible(path)
|
||||
return fi, err
|
||||
}
|
||||
return
|
||||
return fs.Stat(path)
|
||||
}
|
||||
|
||||
// Walk walks the file tree rooted at root, calling walkFn for each file or
|
||||
@@ -100,7 +98,7 @@ func (a Afero) Walk(root string, walkFn filepath.WalkFunc) error {
|
||||
}
|
||||
|
||||
func Walk(fs Fs, root string, walkFn filepath.WalkFunc) error {
|
||||
info, err := lstatIfOs(fs, root)
|
||||
info, err := lstatIfPossible(fs, root)
|
||||
if err != nil {
|
||||
return walkFn(root, nil, err)
|
||||
}
|
||||
|
||||
69
vendor/github.com/spf13/afero/path_test.go
сгенерированный
поставляемый
69
vendor/github.com/spf13/afero/path_test.go
сгенерированный
поставляемый
@@ -1,69 +0,0 @@
|
||||
// Copyright © 2014 Steve Francia <spf@spf13.com>.
|
||||
// Copyright 2009 The Go Authors. All rights reserved.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package afero
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestWalk(t *testing.T) {
|
||||
defer removeAllTestFiles(t)
|
||||
var testDir string
|
||||
for i, fs := range Fss {
|
||||
if i == 0 {
|
||||
testDir = setupTestDirRoot(t, fs)
|
||||
} else {
|
||||
setupTestDirReusePath(t, fs, testDir)
|
||||
}
|
||||
}
|
||||
|
||||
outputs := make([]string, len(Fss))
|
||||
for i, fs := range Fss {
|
||||
walkFn := func(path string, info os.FileInfo, err error) error {
|
||||
if err != nil {
|
||||
t.Error("walkFn err:", err)
|
||||
}
|
||||
var size int64
|
||||
if !info.IsDir() {
|
||||
size = info.Size()
|
||||
}
|
||||
outputs[i] += fmt.Sprintln(path, info.Name(), size, info.IsDir(), err)
|
||||
return nil
|
||||
}
|
||||
err := Walk(fs, testDir, walkFn)
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
}
|
||||
fail := false
|
||||
for i, o := range outputs {
|
||||
if i == 0 {
|
||||
continue
|
||||
}
|
||||
if o != outputs[i-1] {
|
||||
fail = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if fail {
|
||||
t.Log("Walk outputs not equal!")
|
||||
for i, o := range outputs {
|
||||
t.Log(Fss[i].Name() + "\n" + o)
|
||||
}
|
||||
t.Fail()
|
||||
}
|
||||
}
|
||||
10
vendor/github.com/spf13/afero/readonlyfs.go
сгенерированный
поставляемый
10
vendor/github.com/spf13/afero/readonlyfs.go
сгенерированный
поставляемый
@@ -6,6 +6,8 @@ import (
|
||||
"time"
|
||||
)
|
||||
|
||||
var _ Lstater = (*ReadOnlyFs)(nil)
|
||||
|
||||
type ReadOnlyFs struct {
|
||||
source Fs
|
||||
}
|
||||
@@ -34,6 +36,14 @@ func (r *ReadOnlyFs) Stat(name string) (os.FileInfo, error) {
|
||||
return r.source.Stat(name)
|
||||
}
|
||||
|
||||
func (r *ReadOnlyFs) LstatIfPossible(name string) (os.FileInfo, bool, error) {
|
||||
if lsf, ok := r.source.(Lstater); ok {
|
||||
return lsf.LstatIfPossible(name)
|
||||
}
|
||||
fi, err := r.Stat(name)
|
||||
return fi, false, err
|
||||
}
|
||||
|
||||
func (r *ReadOnlyFs) Rename(o, n string) error {
|
||||
return syscall.EPERM
|
||||
}
|
||||
|
||||
96
vendor/github.com/spf13/afero/ro_regexp_test.go
сгенерированный
поставляемый
96
vendor/github.com/spf13/afero/ro_regexp_test.go
сгенерированный
поставляемый
@@ -1,96 +0,0 @@
|
||||
package afero
|
||||
|
||||
import (
|
||||
"regexp"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestFilterReadOnly(t *testing.T) {
|
||||
fs := &ReadOnlyFs{source: &MemMapFs{}}
|
||||
_, err := fs.Create("/file.txt")
|
||||
if err == nil {
|
||||
t.Errorf("Did not fail to create file")
|
||||
}
|
||||
// t.Logf("ERR=%s", err)
|
||||
}
|
||||
|
||||
func TestFilterReadonlyRemoveAndRead(t *testing.T) {
|
||||
mfs := &MemMapFs{}
|
||||
fh, err := mfs.Create("/file.txt")
|
||||
fh.Write([]byte("content here"))
|
||||
fh.Close()
|
||||
|
||||
fs := NewReadOnlyFs(mfs)
|
||||
err = fs.Remove("/file.txt")
|
||||
if err == nil {
|
||||
t.Errorf("Did not fail to remove file")
|
||||
}
|
||||
|
||||
fh, err = fs.Open("/file.txt")
|
||||
if err != nil {
|
||||
t.Errorf("Failed to open file: %s", err)
|
||||
}
|
||||
|
||||
buf := make([]byte, len("content here"))
|
||||
_, err = fh.Read(buf)
|
||||
fh.Close()
|
||||
if string(buf) != "content here" {
|
||||
t.Errorf("Failed to read file: %s", err)
|
||||
}
|
||||
|
||||
err = mfs.Remove("/file.txt")
|
||||
if err != nil {
|
||||
t.Errorf("Failed to remove file")
|
||||
}
|
||||
|
||||
fh, err = fs.Open("/file.txt")
|
||||
if err == nil {
|
||||
fh.Close()
|
||||
t.Errorf("File still present")
|
||||
}
|
||||
}
|
||||
|
||||
func TestFilterRegexp(t *testing.T) {
|
||||
fs := NewRegexpFs(&MemMapFs{}, regexp.MustCompile(`\.txt$`))
|
||||
_, err := fs.Create("/file.html")
|
||||
if err == nil {
|
||||
|
||||
t.Errorf("Did not fail to create file")
|
||||
}
|
||||
// t.Logf("ERR=%s", err)
|
||||
}
|
||||
|
||||
func TestFilterRORegexpChain(t *testing.T) {
|
||||
rofs := &ReadOnlyFs{source: &MemMapFs{}}
|
||||
fs := &RegexpFs{re: regexp.MustCompile(`\.txt$`), source: rofs}
|
||||
_, err := fs.Create("/file.txt")
|
||||
if err == nil {
|
||||
t.Errorf("Did not fail to create file")
|
||||
}
|
||||
// t.Logf("ERR=%s", err)
|
||||
}
|
||||
|
||||
func TestFilterRegexReadDir(t *testing.T) {
|
||||
mfs := &MemMapFs{}
|
||||
fs1 := &RegexpFs{re: regexp.MustCompile(`\.txt$`), source: mfs}
|
||||
fs := &RegexpFs{re: regexp.MustCompile(`^a`), source: fs1}
|
||||
|
||||
mfs.MkdirAll("/dir/sub", 0777)
|
||||
for _, name := range []string{"afile.txt", "afile.html", "bfile.txt"} {
|
||||
for _, dir := range []string{"/dir/", "/dir/sub/"} {
|
||||
fh, _ := mfs.Create(dir + name)
|
||||
fh.Close()
|
||||
}
|
||||
}
|
||||
|
||||
files, _ := ReadDir(fs, "/dir")
|
||||
if len(files) != 2 { // afile.txt, sub
|
||||
t.Errorf("Got wrong number of files: %#v", files)
|
||||
}
|
||||
|
||||
f, _ := fs.Open("/dir/sub")
|
||||
names, _ := f.Readdirnames(-1)
|
||||
if len(names) != 1 {
|
||||
t.Errorf("Got wrong number of names: %v", names)
|
||||
}
|
||||
}
|
||||
95
vendor/github.com/spf13/afero/sftpfs/file.go
сгенерированный
поставляемый
95
vendor/github.com/spf13/afero/sftpfs/file.go
сгенерированный
поставляемый
@@ -1,95 +0,0 @@
|
||||
// Copyright © 2015 Jerry Jacobs <jerry.jacobs@xor-gate.org>.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package sftpfs
|
||||
|
||||
import (
|
||||
"github.com/pkg/sftp"
|
||||
"os"
|
||||
)
|
||||
|
||||
type File struct {
|
||||
fd *sftp.File
|
||||
}
|
||||
|
||||
func FileOpen(s *sftp.Client, name string) (*File, error) {
|
||||
fd, err := s.Open(name)
|
||||
if err != nil {
|
||||
return &File{}, err
|
||||
}
|
||||
return &File{fd: fd}, nil
|
||||
}
|
||||
|
||||
func FileCreate(s *sftp.Client, name string) (*File, error) {
|
||||
fd, err := s.Create(name)
|
||||
if err != nil {
|
||||
return &File{}, err
|
||||
}
|
||||
return &File{fd: fd}, nil
|
||||
}
|
||||
|
||||
func (f *File) Close() error {
|
||||
return f.fd.Close()
|
||||
}
|
||||
|
||||
func (f *File) Name() string {
|
||||
return f.fd.Name()
|
||||
}
|
||||
|
||||
func (f *File) Stat() (os.FileInfo, error) {
|
||||
return f.fd.Stat()
|
||||
}
|
||||
|
||||
func (f *File) Sync() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (f *File) Truncate(size int64) error {
|
||||
return f.fd.Truncate(size)
|
||||
}
|
||||
|
||||
func (f *File) Read(b []byte) (n int, err error) {
|
||||
return f.fd.Read(b)
|
||||
}
|
||||
|
||||
// TODO
|
||||
func (f *File) ReadAt(b []byte, off int64) (n int, err error) {
|
||||
return 0, nil
|
||||
}
|
||||
|
||||
// TODO
|
||||
func (f *File) Readdir(count int) (res []os.FileInfo, err error) {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
// TODO
|
||||
func (f *File) Readdirnames(n int) (names []string, err error) {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func (f *File) Seek(offset int64, whence int) (int64, error) {
|
||||
return f.fd.Seek(offset, whence)
|
||||
}
|
||||
|
||||
func (f *File) Write(b []byte) (n int, err error) {
|
||||
return f.fd.Write(b)
|
||||
}
|
||||
|
||||
// TODO
|
||||
func (f *File) WriteAt(b []byte, off int64) (n int, err error) {
|
||||
return 0, nil
|
||||
}
|
||||
|
||||
func (f *File) WriteString(s string) (ret int, err error) {
|
||||
return f.fd.Write([]byte(s))
|
||||
}
|
||||
129
vendor/github.com/spf13/afero/sftpfs/sftp.go
сгенерированный
поставляемый
129
vendor/github.com/spf13/afero/sftpfs/sftp.go
сгенерированный
поставляемый
@@ -1,129 +0,0 @@
|
||||
// Copyright © 2015 Jerry Jacobs <jerry.jacobs@xor-gate.org>.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package sftpfs
|
||||
|
||||
import (
|
||||
"os"
|
||||
"time"
|
||||
|
||||
"github.com/pkg/sftp"
|
||||
"github.com/spf13/afero"
|
||||
)
|
||||
|
||||
// Fs is a afero.Fs implementation that uses functions provided by the sftp package.
|
||||
//
|
||||
// For details in any method, check the documentation of the sftp package
|
||||
// (github.com/pkg/sftp).
|
||||
type Fs struct {
|
||||
client *sftp.Client
|
||||
}
|
||||
|
||||
func New(client *sftp.Client) afero.Fs {
|
||||
return &Fs{client: client}
|
||||
}
|
||||
|
||||
func (s Fs) Name() string { return "sftpfs" }
|
||||
|
||||
func (s Fs) Create(name string) (afero.File, error) {
|
||||
return FileCreate(s.client, name)
|
||||
}
|
||||
|
||||
func (s Fs) Mkdir(name string, perm os.FileMode) error {
|
||||
err := s.client.Mkdir(name)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return s.client.Chmod(name, perm)
|
||||
}
|
||||
|
||||
func (s Fs) MkdirAll(path string, perm os.FileMode) error {
|
||||
// Fast path: if we can tell whether path is a directory or file, stop with success or error.
|
||||
dir, err := s.Stat(path)
|
||||
if err == nil {
|
||||
if dir.IsDir() {
|
||||
return nil
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
// Slow path: make sure parent exists and then call Mkdir for path.
|
||||
i := len(path)
|
||||
for i > 0 && os.IsPathSeparator(path[i-1]) { // Skip trailing path separator.
|
||||
i--
|
||||
}
|
||||
|
||||
j := i
|
||||
for j > 0 && !os.IsPathSeparator(path[j-1]) { // Scan backward over element.
|
||||
j--
|
||||
}
|
||||
|
||||
if j > 1 {
|
||||
// Create parent
|
||||
err = s.MkdirAll(path[0:j-1], perm)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
// Parent now exists; invoke Mkdir and use its result.
|
||||
err = s.Mkdir(path, perm)
|
||||
if err != nil {
|
||||
// Handle arguments like "foo/." by
|
||||
// double-checking that directory doesn't exist.
|
||||
dir, err1 := s.Lstat(path)
|
||||
if err1 == nil && dir.IsDir() {
|
||||
return nil
|
||||
}
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s Fs) Open(name string) (afero.File, error) {
|
||||
return FileOpen(s.client, name)
|
||||
}
|
||||
|
||||
func (s Fs) OpenFile(name string, flag int, perm os.FileMode) (afero.File, error) {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func (s Fs) Remove(name string) error {
|
||||
return s.client.Remove(name)
|
||||
}
|
||||
|
||||
func (s Fs) RemoveAll(path string) error {
|
||||
// TODO have a look at os.RemoveAll
|
||||
// https://github.com/golang/go/blob/master/src/os/path.go#L66
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s Fs) Rename(oldname, newname string) error {
|
||||
return s.client.Rename(oldname, newname)
|
||||
}
|
||||
|
||||
func (s Fs) Stat(name string) (os.FileInfo, error) {
|
||||
return s.client.Stat(name)
|
||||
}
|
||||
|
||||
func (s Fs) Lstat(p string) (os.FileInfo, error) {
|
||||
return s.client.Lstat(p)
|
||||
}
|
||||
|
||||
func (s Fs) Chmod(name string, mode os.FileMode) error {
|
||||
return s.client.Chmod(name, mode)
|
||||
}
|
||||
|
||||
func (s Fs) Chtimes(name string, atime time.Time, mtime time.Time) error {
|
||||
return s.client.Chtimes(name, atime, mtime)
|
||||
}
|
||||
286
vendor/github.com/spf13/afero/sftpfs/sftp_test_go
сгенерированный
поставляемый
286
vendor/github.com/spf13/afero/sftpfs/sftp_test_go
сгенерированный
поставляемый
@@ -1,286 +0,0 @@
|
||||
// Copyright © 2015 Jerry Jacobs <jerry.jacobs@xor-gate.org>.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package afero
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"os"
|
||||
"log"
|
||||
"fmt"
|
||||
"net"
|
||||
"flag"
|
||||
"time"
|
||||
"io/ioutil"
|
||||
"crypto/rsa"
|
||||
_rand "crypto/rand"
|
||||
"encoding/pem"
|
||||
"crypto/x509"
|
||||
|
||||
"golang.org/x/crypto/ssh"
|
||||
"github.com/pkg/sftp"
|
||||
)
|
||||
|
||||
type SftpFsContext struct {
|
||||
sshc *ssh.Client
|
||||
sshcfg *ssh.ClientConfig
|
||||
sftpc *sftp.Client
|
||||
}
|
||||
|
||||
// TODO we only connect with hardcoded user+pass for now
|
||||
// it should be possible to use $HOME/.ssh/id_rsa to login into the stub sftp server
|
||||
func SftpConnect(user, password, host string) (*SftpFsContext, error) {
|
||||
/*
|
||||
pemBytes, err := ioutil.ReadFile(os.Getenv("HOME") + "/.ssh/id_rsa")
|
||||
if err != nil {
|
||||
return nil,err
|
||||
}
|
||||
|
||||
signer, err := ssh.ParsePrivateKey(pemBytes)
|
||||
if err != nil {
|
||||
return nil,err
|
||||
}
|
||||
|
||||
sshcfg := &ssh.ClientConfig{
|
||||
User: user,
|
||||
Auth: []ssh.AuthMethod{
|
||||
ssh.Password(password),
|
||||
ssh.PublicKeys(signer),
|
||||
},
|
||||
}
|
||||
*/
|
||||
|
||||
sshcfg := &ssh.ClientConfig{
|
||||
User: user,
|
||||
Auth: []ssh.AuthMethod{
|
||||
ssh.Password(password),
|
||||
},
|
||||
}
|
||||
|
||||
sshc, err := ssh.Dial("tcp", host, sshcfg)
|
||||
if err != nil {
|
||||
return nil,err
|
||||
}
|
||||
|
||||
sftpc, err := sftp.NewClient(sshc)
|
||||
if err != nil {
|
||||
return nil,err
|
||||
}
|
||||
|
||||
ctx := &SftpFsContext{
|
||||
sshc: sshc,
|
||||
sshcfg: sshcfg,
|
||||
sftpc: sftpc,
|
||||
}
|
||||
|
||||
return ctx,nil
|
||||
}
|
||||
|
||||
func (ctx *SftpFsContext) Disconnect() error {
|
||||
ctx.sftpc.Close()
|
||||
ctx.sshc.Close()
|
||||
return nil
|
||||
}
|
||||
|
||||
// TODO for such a weird reason rootpath is "." when writing "file1" with afero sftp backend
|
||||
func RunSftpServer(rootpath string) {
|
||||
var (
|
||||
readOnly bool
|
||||
debugLevelStr string
|
||||
debugLevel int
|
||||
debugStderr bool
|
||||
rootDir string
|
||||
)
|
||||
|
||||
flag.BoolVar(&readOnly, "R", false, "read-only server")
|
||||
flag.BoolVar(&debugStderr, "e", true, "debug to stderr")
|
||||
flag.StringVar(&debugLevelStr, "l", "none", "debug level")
|
||||
flag.StringVar(&rootDir, "root", rootpath, "root directory")
|
||||
flag.Parse()
|
||||
|
||||
debugStream := ioutil.Discard
|
||||
if debugStderr {
|
||||
debugStream = os.Stderr
|
||||
debugLevel = 1
|
||||
}
|
||||
|
||||
// An SSH server is represented by a ServerConfig, which holds
|
||||
// certificate details and handles authentication of ServerConns.
|
||||
config := &ssh.ServerConfig{
|
||||
PasswordCallback: func(c ssh.ConnMetadata, pass []byte) (*ssh.Permissions, error) {
|
||||
// Should use constant-time compare (or better, salt+hash) in
|
||||
// a production setting.
|
||||
fmt.Fprintf(debugStream, "Login: %s\n", c.User())
|
||||
if c.User() == "test" && string(pass) == "test" {
|
||||
return nil, nil
|
||||
}
|
||||
return nil, fmt.Errorf("password rejected for %q", c.User())
|
||||
},
|
||||
}
|
||||
|
||||
privateBytes, err := ioutil.ReadFile("./test/id_rsa")
|
||||
if err != nil {
|
||||
log.Fatal("Failed to load private key", err)
|
||||
}
|
||||
|
||||
private, err := ssh.ParsePrivateKey(privateBytes)
|
||||
if err != nil {
|
||||
log.Fatal("Failed to parse private key", err)
|
||||
}
|
||||
|
||||
config.AddHostKey(private)
|
||||
|
||||
// Once a ServerConfig has been configured, connections can be
|
||||
// accepted.
|
||||
listener, err := net.Listen("tcp", "0.0.0.0:2022")
|
||||
if err != nil {
|
||||
log.Fatal("failed to listen for connection", err)
|
||||
}
|
||||
fmt.Printf("Listening on %v\n", listener.Addr())
|
||||
|
||||
nConn, err := listener.Accept()
|
||||
if err != nil {
|
||||
log.Fatal("failed to accept incoming connection", err)
|
||||
}
|
||||
|
||||
// Before use, a handshake must be performed on the incoming
|
||||
// net.Conn.
|
||||
_, chans, reqs, err := ssh.NewServerConn(nConn, config)
|
||||
if err != nil {
|
||||
log.Fatal("failed to handshake", err)
|
||||
}
|
||||
fmt.Fprintf(debugStream, "SSH server established\n")
|
||||
|
||||
// The incoming Request channel must be serviced.
|
||||
go ssh.DiscardRequests(reqs)
|
||||
|
||||
// Service the incoming Channel channel.
|
||||
for newChannel := range chans {
|
||||
// Channels have a type, depending on the application level
|
||||
// protocol intended. In the case of an SFTP session, this is "subsystem"
|
||||
// with a payload string of "<length=4>sftp"
|
||||
fmt.Fprintf(debugStream, "Incoming channel: %s\n", newChannel.ChannelType())
|
||||
if newChannel.ChannelType() != "session" {
|
||||
newChannel.Reject(ssh.UnknownChannelType, "unknown channel type")
|
||||
fmt.Fprintf(debugStream, "Unknown channel type: %s\n", newChannel.ChannelType())
|
||||
continue
|
||||
}
|
||||
channel, requests, err := newChannel.Accept()
|
||||
if err != nil {
|
||||
log.Fatal("could not accept channel.", err)
|
||||
}
|
||||
fmt.Fprintf(debugStream, "Channel accepted\n")
|
||||
|
||||
// Sessions have out-of-band requests such as "shell",
|
||||
// "pty-req" and "env". Here we handle only the
|
||||
// "subsystem" request.
|
||||
go func(in <-chan *ssh.Request) {
|
||||
for req := range in {
|
||||
fmt.Fprintf(debugStream, "Request: %v\n", req.Type)
|
||||
ok := false
|
||||
switch req.Type {
|
||||
case "subsystem":
|
||||
fmt.Fprintf(debugStream, "Subsystem: %s\n", req.Payload[4:])
|
||||
if string(req.Payload[4:]) == "sftp" {
|
||||
ok = true
|
||||
}
|
||||
}
|
||||
fmt.Fprintf(debugStream, " - accepted: %v\n", ok)
|
||||
req.Reply(ok, nil)
|
||||
}
|
||||
}(requests)
|
||||
|
||||
server, err := sftp.NewServer(channel, channel, debugStream, debugLevel, readOnly, rootpath)
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
if err := server.Serve(); err != nil {
|
||||
log.Fatal("sftp server completed with error:", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MakeSSHKeyPair make a pair of public and private keys for SSH access.
|
||||
// Public key is encoded in the format for inclusion in an OpenSSH authorized_keys file.
|
||||
// Private Key generated is PEM encoded
|
||||
func MakeSSHKeyPair(bits int, pubKeyPath, privateKeyPath string) error {
|
||||
privateKey, err := rsa.GenerateKey(_rand.Reader, bits)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// generate and write private key as PEM
|
||||
privateKeyFile, err := os.Create(privateKeyPath)
|
||||
defer privateKeyFile.Close()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
privateKeyPEM := &pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(privateKey)}
|
||||
if err := pem.Encode(privateKeyFile, privateKeyPEM); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// generate and write public key
|
||||
pub, err := ssh.NewPublicKey(&privateKey.PublicKey)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return ioutil.WriteFile(pubKeyPath, ssh.MarshalAuthorizedKey(pub), 0655)
|
||||
}
|
||||
|
||||
func TestSftpCreate(t *testing.T) {
|
||||
os.Mkdir("./test", 0777)
|
||||
MakeSSHKeyPair(1024, "./test/id_rsa.pub", "./test/id_rsa")
|
||||
|
||||
go RunSftpServer("./test/")
|
||||
time.Sleep(5 * time.Second)
|
||||
|
||||
ctx, err := SftpConnect("test", "test", "localhost:2022")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer ctx.Disconnect()
|
||||
|
||||
var AppFs Fs = SftpFs{
|
||||
SftpClient: ctx.sftpc,
|
||||
}
|
||||
|
||||
AppFs.MkdirAll("test/dir1/dir2/dir3", os.FileMode(0777))
|
||||
AppFs.Mkdir("test/foo", os.FileMode(0000))
|
||||
AppFs.Chmod("test/foo", os.FileMode(0700))
|
||||
AppFs.Mkdir("test/bar", os.FileMode(0777))
|
||||
|
||||
file, err := AppFs.Create("file1")
|
||||
if err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
defer file.Close()
|
||||
|
||||
file.Write([]byte("hello\t"))
|
||||
file.WriteString("world!\n")
|
||||
|
||||
f1, err := AppFs.Open("file1")
|
||||
if err != nil {
|
||||
log.Fatalf("open: %v", err)
|
||||
}
|
||||
defer f1.Close()
|
||||
|
||||
b := make([]byte, 100)
|
||||
|
||||
_, err = f1.Read(b)
|
||||
fmt.Println(string(b))
|
||||
|
||||
// TODO check here if "hello\tworld\n" is in buffer b
|
||||
}
|
||||
189
vendor/github.com/spf13/afero/unionFile.go
сгенерированный
поставляемый
189
vendor/github.com/spf13/afero/unionFile.go
сгенерированный
поставляемый
@@ -21,32 +21,33 @@ import (
|
||||
// successful read in the overlay will move the cursor position in the base layer
|
||||
// by the number of bytes read.
|
||||
type UnionFile struct {
|
||||
base File
|
||||
layer File
|
||||
off int
|
||||
files []os.FileInfo
|
||||
Base File
|
||||
Layer File
|
||||
Merger DirsMerger
|
||||
off int
|
||||
files []os.FileInfo
|
||||
}
|
||||
|
||||
func (f *UnionFile) Close() error {
|
||||
// first close base, so we have a newer timestamp in the overlay. If we'd close
|
||||
// the overlay first, we'd get a cacheStale the next time we access this file
|
||||
// -> cache would be useless ;-)
|
||||
if f.base != nil {
|
||||
f.base.Close()
|
||||
if f.Base != nil {
|
||||
f.Base.Close()
|
||||
}
|
||||
if f.layer != nil {
|
||||
return f.layer.Close()
|
||||
if f.Layer != nil {
|
||||
return f.Layer.Close()
|
||||
}
|
||||
return BADFD
|
||||
}
|
||||
|
||||
func (f *UnionFile) Read(s []byte) (int, error) {
|
||||
if f.layer != nil {
|
||||
n, err := f.layer.Read(s)
|
||||
if (err == nil || err == io.EOF) && f.base != nil {
|
||||
if f.Layer != nil {
|
||||
n, err := f.Layer.Read(s)
|
||||
if (err == nil || err == io.EOF) && f.Base != nil {
|
||||
// advance the file position also in the base file, the next
|
||||
// call may be a write at this position (or a seek with SEEK_CUR)
|
||||
if _, seekErr := f.base.Seek(int64(n), os.SEEK_CUR); seekErr != nil {
|
||||
if _, seekErr := f.Base.Seek(int64(n), os.SEEK_CUR); seekErr != nil {
|
||||
// only overwrite err in case the seek fails: we need to
|
||||
// report an eventual io.EOF to the caller
|
||||
err = seekErr
|
||||
@@ -54,105 +55,135 @@ func (f *UnionFile) Read(s []byte) (int, error) {
|
||||
}
|
||||
return n, err
|
||||
}
|
||||
if f.base != nil {
|
||||
return f.base.Read(s)
|
||||
if f.Base != nil {
|
||||
return f.Base.Read(s)
|
||||
}
|
||||
return 0, BADFD
|
||||
}
|
||||
|
||||
func (f *UnionFile) ReadAt(s []byte, o int64) (int, error) {
|
||||
if f.layer != nil {
|
||||
n, err := f.layer.ReadAt(s, o)
|
||||
if (err == nil || err == io.EOF) && f.base != nil {
|
||||
_, err = f.base.Seek(o+int64(n), os.SEEK_SET)
|
||||
if f.Layer != nil {
|
||||
n, err := f.Layer.ReadAt(s, o)
|
||||
if (err == nil || err == io.EOF) && f.Base != nil {
|
||||
_, err = f.Base.Seek(o+int64(n), os.SEEK_SET)
|
||||
}
|
||||
return n, err
|
||||
}
|
||||
if f.base != nil {
|
||||
return f.base.ReadAt(s, o)
|
||||
if f.Base != nil {
|
||||
return f.Base.ReadAt(s, o)
|
||||
}
|
||||
return 0, BADFD
|
||||
}
|
||||
|
||||
func (f *UnionFile) Seek(o int64, w int) (pos int64, err error) {
|
||||
if f.layer != nil {
|
||||
pos, err = f.layer.Seek(o, w)
|
||||
if (err == nil || err == io.EOF) && f.base != nil {
|
||||
_, err = f.base.Seek(o, w)
|
||||
if f.Layer != nil {
|
||||
pos, err = f.Layer.Seek(o, w)
|
||||
if (err == nil || err == io.EOF) && f.Base != nil {
|
||||
_, err = f.Base.Seek(o, w)
|
||||
}
|
||||
return pos, err
|
||||
}
|
||||
if f.base != nil {
|
||||
return f.base.Seek(o, w)
|
||||
if f.Base != nil {
|
||||
return f.Base.Seek(o, w)
|
||||
}
|
||||
return 0, BADFD
|
||||
}
|
||||
|
||||
func (f *UnionFile) Write(s []byte) (n int, err error) {
|
||||
if f.layer != nil {
|
||||
n, err = f.layer.Write(s)
|
||||
if err == nil && f.base != nil { // hmm, do we have fixed size files where a write may hit the EOF mark?
|
||||
_, err = f.base.Write(s)
|
||||
if f.Layer != nil {
|
||||
n, err = f.Layer.Write(s)
|
||||
if err == nil && f.Base != nil { // hmm, do we have fixed size files where a write may hit the EOF mark?
|
||||
_, err = f.Base.Write(s)
|
||||
}
|
||||
return n, err
|
||||
}
|
||||
if f.base != nil {
|
||||
return f.base.Write(s)
|
||||
if f.Base != nil {
|
||||
return f.Base.Write(s)
|
||||
}
|
||||
return 0, BADFD
|
||||
}
|
||||
|
||||
func (f *UnionFile) WriteAt(s []byte, o int64) (n int, err error) {
|
||||
if f.layer != nil {
|
||||
n, err = f.layer.WriteAt(s, o)
|
||||
if err == nil && f.base != nil {
|
||||
_, err = f.base.WriteAt(s, o)
|
||||
if f.Layer != nil {
|
||||
n, err = f.Layer.WriteAt(s, o)
|
||||
if err == nil && f.Base != nil {
|
||||
_, err = f.Base.WriteAt(s, o)
|
||||
}
|
||||
return n, err
|
||||
}
|
||||
if f.base != nil {
|
||||
return f.base.WriteAt(s, o)
|
||||
if f.Base != nil {
|
||||
return f.Base.WriteAt(s, o)
|
||||
}
|
||||
return 0, BADFD
|
||||
}
|
||||
|
||||
func (f *UnionFile) Name() string {
|
||||
if f.layer != nil {
|
||||
return f.layer.Name()
|
||||
if f.Layer != nil {
|
||||
return f.Layer.Name()
|
||||
}
|
||||
return f.base.Name()
|
||||
return f.Base.Name()
|
||||
}
|
||||
|
||||
// DirsMerger is how UnionFile weaves two directories together.
|
||||
// It takes the FileInfo slices from the layer and the base and returns a
|
||||
// single view.
|
||||
type DirsMerger func(lofi, bofi []os.FileInfo) ([]os.FileInfo, error)
|
||||
|
||||
var defaultUnionMergeDirsFn = func(lofi, bofi []os.FileInfo) ([]os.FileInfo, error) {
|
||||
var files = make(map[string]os.FileInfo)
|
||||
|
||||
for _, fi := range lofi {
|
||||
files[fi.Name()] = fi
|
||||
}
|
||||
|
||||
for _, fi := range bofi {
|
||||
if _, exists := files[fi.Name()]; !exists {
|
||||
files[fi.Name()] = fi
|
||||
}
|
||||
}
|
||||
|
||||
rfi := make([]os.FileInfo, len(files))
|
||||
|
||||
i := 0
|
||||
for _, fi := range files {
|
||||
rfi[i] = fi
|
||||
i++
|
||||
}
|
||||
|
||||
return rfi, nil
|
||||
|
||||
}
|
||||
|
||||
// Readdir will weave the two directories together and
|
||||
// return a single view of the overlayed directories
|
||||
func (f *UnionFile) Readdir(c int) (ofi []os.FileInfo, err error) {
|
||||
var merge DirsMerger = f.Merger
|
||||
if merge == nil {
|
||||
merge = defaultUnionMergeDirsFn
|
||||
}
|
||||
|
||||
if f.off == 0 {
|
||||
var files = make(map[string]os.FileInfo)
|
||||
var rfi []os.FileInfo
|
||||
if f.layer != nil {
|
||||
rfi, err = f.layer.Readdir(-1)
|
||||
var lfi []os.FileInfo
|
||||
if f.Layer != nil {
|
||||
lfi, err = f.Layer.Readdir(-1)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, fi := range rfi {
|
||||
files[fi.Name()] = fi
|
||||
}
|
||||
}
|
||||
|
||||
if f.base != nil {
|
||||
rfi, err = f.base.Readdir(-1)
|
||||
var bfi []os.FileInfo
|
||||
if f.Base != nil {
|
||||
bfi, err = f.Base.Readdir(-1)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, fi := range rfi {
|
||||
if _, exists := files[fi.Name()]; !exists {
|
||||
files[fi.Name()] = fi
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
for _, fi := range files {
|
||||
f.files = append(f.files, fi)
|
||||
merged, err := merge(lfi, bfi)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
f.files = append(f.files, merged...)
|
||||
}
|
||||
if c == -1 {
|
||||
return f.files[f.off:], nil
|
||||
@@ -174,53 +205,53 @@ func (f *UnionFile) Readdirnames(c int) ([]string, error) {
|
||||
}
|
||||
|
||||
func (f *UnionFile) Stat() (os.FileInfo, error) {
|
||||
if f.layer != nil {
|
||||
return f.layer.Stat()
|
||||
if f.Layer != nil {
|
||||
return f.Layer.Stat()
|
||||
}
|
||||
if f.base != nil {
|
||||
return f.base.Stat()
|
||||
if f.Base != nil {
|
||||
return f.Base.Stat()
|
||||
}
|
||||
return nil, BADFD
|
||||
}
|
||||
|
||||
func (f *UnionFile) Sync() (err error) {
|
||||
if f.layer != nil {
|
||||
err = f.layer.Sync()
|
||||
if err == nil && f.base != nil {
|
||||
err = f.base.Sync()
|
||||
if f.Layer != nil {
|
||||
err = f.Layer.Sync()
|
||||
if err == nil && f.Base != nil {
|
||||
err = f.Base.Sync()
|
||||
}
|
||||
return err
|
||||
}
|
||||
if f.base != nil {
|
||||
return f.base.Sync()
|
||||
if f.Base != nil {
|
||||
return f.Base.Sync()
|
||||
}
|
||||
return BADFD
|
||||
}
|
||||
|
||||
func (f *UnionFile) Truncate(s int64) (err error) {
|
||||
if f.layer != nil {
|
||||
err = f.layer.Truncate(s)
|
||||
if err == nil && f.base != nil {
|
||||
err = f.base.Truncate(s)
|
||||
if f.Layer != nil {
|
||||
err = f.Layer.Truncate(s)
|
||||
if err == nil && f.Base != nil {
|
||||
err = f.Base.Truncate(s)
|
||||
}
|
||||
return err
|
||||
}
|
||||
if f.base != nil {
|
||||
return f.base.Truncate(s)
|
||||
if f.Base != nil {
|
||||
return f.Base.Truncate(s)
|
||||
}
|
||||
return BADFD
|
||||
}
|
||||
|
||||
func (f *UnionFile) WriteString(s string) (n int, err error) {
|
||||
if f.layer != nil {
|
||||
n, err = f.layer.WriteString(s)
|
||||
if err == nil && f.base != nil {
|
||||
_, err = f.base.WriteString(s)
|
||||
if f.Layer != nil {
|
||||
n, err = f.Layer.WriteString(s)
|
||||
if err == nil && f.Base != nil {
|
||||
_, err = f.Base.WriteString(s)
|
||||
}
|
||||
return n, err
|
||||
}
|
||||
if f.base != nil {
|
||||
return f.base.WriteString(s)
|
||||
if f.Base != nil {
|
||||
return f.Base.WriteString(s)
|
||||
}
|
||||
return 0, BADFD
|
||||
}
|
||||
|
||||
450
vendor/github.com/spf13/afero/util_test.go
сгенерированный
поставляемый
450
vendor/github.com/spf13/afero/util_test.go
сгенерированный
поставляемый
@@ -1,450 +0,0 @@
|
||||
// Copyright ©2015 Steve Francia <spf@spf13.com>
|
||||
// Portions Copyright ©2015 The Hugo Authors
|
||||
//
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
//
|
||||
|
||||
package afero
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
var testFS = new(MemMapFs)
|
||||
|
||||
func TestDirExists(t *testing.T) {
|
||||
type test struct {
|
||||
input string
|
||||
expected bool
|
||||
}
|
||||
|
||||
// First create a couple directories so there is something in the filesystem
|
||||
//testFS := new(MemMapFs)
|
||||
testFS.MkdirAll("/foo/bar", 0777)
|
||||
|
||||
data := []test{
|
||||
{".", true},
|
||||
{"./", true},
|
||||
{"..", true},
|
||||
{"../", true},
|
||||
{"./..", true},
|
||||
{"./../", true},
|
||||
{"/foo/", true},
|
||||
{"/foo", true},
|
||||
{"/foo/bar", true},
|
||||
{"/foo/bar/", true},
|
||||
{"/", true},
|
||||
{"/some-really-random-directory-name", false},
|
||||
{"/some/really/random/directory/name", false},
|
||||
{"./some-really-random-local-directory-name", false},
|
||||
{"./some/really/random/local/directory/name", false},
|
||||
}
|
||||
|
||||
for i, d := range data {
|
||||
exists, _ := DirExists(testFS, filepath.FromSlash(d.input))
|
||||
if d.expected != exists {
|
||||
t.Errorf("Test %d %q failed. Expected %t got %t", i, d.input, d.expected, exists)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestIsDir(t *testing.T) {
|
||||
testFS = new(MemMapFs)
|
||||
|
||||
type test struct {
|
||||
input string
|
||||
expected bool
|
||||
}
|
||||
data := []test{
|
||||
{"./", true},
|
||||
{"/", true},
|
||||
{"./this-directory-does-not-existi", false},
|
||||
{"/this-absolute-directory/does-not-exist", false},
|
||||
}
|
||||
|
||||
for i, d := range data {
|
||||
|
||||
exists, _ := IsDir(testFS, d.input)
|
||||
if d.expected != exists {
|
||||
t.Errorf("Test %d failed. Expected %t got %t", i, d.expected, exists)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestIsEmpty(t *testing.T) {
|
||||
testFS = new(MemMapFs)
|
||||
|
||||
zeroSizedFile, _ := createZeroSizedFileInTempDir()
|
||||
defer deleteFileInTempDir(zeroSizedFile)
|
||||
nonZeroSizedFile, _ := createNonZeroSizedFileInTempDir()
|
||||
defer deleteFileInTempDir(nonZeroSizedFile)
|
||||
emptyDirectory, _ := createEmptyTempDir()
|
||||
defer deleteTempDir(emptyDirectory)
|
||||
nonEmptyZeroLengthFilesDirectory, _ := createTempDirWithZeroLengthFiles()
|
||||
defer deleteTempDir(nonEmptyZeroLengthFilesDirectory)
|
||||
nonEmptyNonZeroLengthFilesDirectory, _ := createTempDirWithNonZeroLengthFiles()
|
||||
defer deleteTempDir(nonEmptyNonZeroLengthFilesDirectory)
|
||||
nonExistentFile := os.TempDir() + "/this-file-does-not-exist.txt"
|
||||
nonExistentDir := os.TempDir() + "/this/direcotry/does/not/exist/"
|
||||
|
||||
fileDoesNotExist := fmt.Errorf("%q path does not exist", nonExistentFile)
|
||||
dirDoesNotExist := fmt.Errorf("%q path does not exist", nonExistentDir)
|
||||
|
||||
type test struct {
|
||||
input string
|
||||
expectedResult bool
|
||||
expectedErr error
|
||||
}
|
||||
|
||||
data := []test{
|
||||
{zeroSizedFile.Name(), true, nil},
|
||||
{nonZeroSizedFile.Name(), false, nil},
|
||||
{emptyDirectory, true, nil},
|
||||
{nonEmptyZeroLengthFilesDirectory, false, nil},
|
||||
{nonEmptyNonZeroLengthFilesDirectory, false, nil},
|
||||
{nonExistentFile, false, fileDoesNotExist},
|
||||
{nonExistentDir, false, dirDoesNotExist},
|
||||
}
|
||||
for i, d := range data {
|
||||
exists, err := IsEmpty(testFS, d.input)
|
||||
if d.expectedResult != exists {
|
||||
t.Errorf("Test %d %q failed exists. Expected result %t got %t", i, d.input, d.expectedResult, exists)
|
||||
}
|
||||
if d.expectedErr != nil {
|
||||
if d.expectedErr.Error() != err.Error() {
|
||||
t.Errorf("Test %d failed with err. Expected %q(%#v) got %q(%#v)", i, d.expectedErr, d.expectedErr, err, err)
|
||||
}
|
||||
} else {
|
||||
if d.expectedErr != err {
|
||||
t.Errorf("Test %d failed. Expected error %q(%#v) got %q(%#v)", i, d.expectedErr, d.expectedErr, err, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestReaderContains(t *testing.T) {
|
||||
for i, this := range []struct {
|
||||
v1 string
|
||||
v2 [][]byte
|
||||
expect bool
|
||||
}{
|
||||
{"abc", [][]byte{[]byte("a")}, true},
|
||||
{"abc", [][]byte{[]byte("b")}, true},
|
||||
{"abcdefg", [][]byte{[]byte("efg")}, true},
|
||||
{"abc", [][]byte{[]byte("d")}, false},
|
||||
{"abc", [][]byte{[]byte("d"), []byte("e")}, false},
|
||||
{"abc", [][]byte{[]byte("d"), []byte("a")}, true},
|
||||
{"abc", [][]byte{[]byte("b"), []byte("e")}, true},
|
||||
{"", nil, false},
|
||||
{"", [][]byte{[]byte("a")}, false},
|
||||
{"a", [][]byte{[]byte("")}, false},
|
||||
{"", [][]byte{[]byte("")}, false}} {
|
||||
result := readerContainsAny(strings.NewReader(this.v1), this.v2...)
|
||||
if result != this.expect {
|
||||
t.Errorf("[%d] readerContains: got %t but expected %t", i, result, this.expect)
|
||||
}
|
||||
}
|
||||
|
||||
if readerContainsAny(nil, []byte("a")) {
|
||||
t.Error("readerContains with nil reader")
|
||||
}
|
||||
|
||||
if readerContainsAny(nil, nil) {
|
||||
t.Error("readerContains with nil arguments")
|
||||
}
|
||||
}
|
||||
|
||||
func createZeroSizedFileInTempDir() (File, error) {
|
||||
filePrefix := "_path_test_"
|
||||
f, e := TempFile(testFS, "", filePrefix) // dir is os.TempDir()
|
||||
if e != nil {
|
||||
// if there was an error no file was created.
|
||||
// => no requirement to delete the file
|
||||
return nil, e
|
||||
}
|
||||
return f, nil
|
||||
}
|
||||
|
||||
func createNonZeroSizedFileInTempDir() (File, error) {
|
||||
f, err := createZeroSizedFileInTempDir()
|
||||
if err != nil {
|
||||
// no file ??
|
||||
}
|
||||
byteString := []byte("byteString")
|
||||
err = WriteFile(testFS, f.Name(), byteString, 0644)
|
||||
if err != nil {
|
||||
// delete the file
|
||||
deleteFileInTempDir(f)
|
||||
return nil, err
|
||||
}
|
||||
return f, nil
|
||||
}
|
||||
|
||||
func deleteFileInTempDir(f File) {
|
||||
err := testFS.Remove(f.Name())
|
||||
if err != nil {
|
||||
// now what?
|
||||
}
|
||||
}
|
||||
|
||||
func createEmptyTempDir() (string, error) {
|
||||
dirPrefix := "_dir_prefix_"
|
||||
d, e := TempDir(testFS, "", dirPrefix) // will be in os.TempDir()
|
||||
if e != nil {
|
||||
// no directory to delete - it was never created
|
||||
return "", e
|
||||
}
|
||||
return d, nil
|
||||
}
|
||||
|
||||
func createTempDirWithZeroLengthFiles() (string, error) {
|
||||
d, dirErr := createEmptyTempDir()
|
||||
if dirErr != nil {
|
||||
//now what?
|
||||
}
|
||||
filePrefix := "_path_test_"
|
||||
_, fileErr := TempFile(testFS, d, filePrefix) // dir is os.TempDir()
|
||||
if fileErr != nil {
|
||||
// if there was an error no file was created.
|
||||
// but we need to remove the directory to clean-up
|
||||
deleteTempDir(d)
|
||||
return "", fileErr
|
||||
}
|
||||
// the dir now has one, zero length file in it
|
||||
return d, nil
|
||||
|
||||
}
|
||||
|
||||
func createTempDirWithNonZeroLengthFiles() (string, error) {
|
||||
d, dirErr := createEmptyTempDir()
|
||||
if dirErr != nil {
|
||||
//now what?
|
||||
}
|
||||
filePrefix := "_path_test_"
|
||||
f, fileErr := TempFile(testFS, d, filePrefix) // dir is os.TempDir()
|
||||
if fileErr != nil {
|
||||
// if there was an error no file was created.
|
||||
// but we need to remove the directory to clean-up
|
||||
deleteTempDir(d)
|
||||
return "", fileErr
|
||||
}
|
||||
byteString := []byte("byteString")
|
||||
fileErr = WriteFile(testFS, f.Name(), byteString, 0644)
|
||||
if fileErr != nil {
|
||||
// delete the file
|
||||
deleteFileInTempDir(f)
|
||||
// also delete the directory
|
||||
deleteTempDir(d)
|
||||
return "", fileErr
|
||||
}
|
||||
|
||||
// the dir now has one, zero length file in it
|
||||
return d, nil
|
||||
|
||||
}
|
||||
|
||||
func TestExists(t *testing.T) {
|
||||
zeroSizedFile, _ := createZeroSizedFileInTempDir()
|
||||
defer deleteFileInTempDir(zeroSizedFile)
|
||||
nonZeroSizedFile, _ := createNonZeroSizedFileInTempDir()
|
||||
defer deleteFileInTempDir(nonZeroSizedFile)
|
||||
emptyDirectory, _ := createEmptyTempDir()
|
||||
defer deleteTempDir(emptyDirectory)
|
||||
nonExistentFile := os.TempDir() + "/this-file-does-not-exist.txt"
|
||||
nonExistentDir := os.TempDir() + "/this/direcotry/does/not/exist/"
|
||||
|
||||
type test struct {
|
||||
input string
|
||||
expectedResult bool
|
||||
expectedErr error
|
||||
}
|
||||
|
||||
data := []test{
|
||||
{zeroSizedFile.Name(), true, nil},
|
||||
{nonZeroSizedFile.Name(), true, nil},
|
||||
{emptyDirectory, true, nil},
|
||||
{nonExistentFile, false, nil},
|
||||
{nonExistentDir, false, nil},
|
||||
}
|
||||
for i, d := range data {
|
||||
exists, err := Exists(testFS, d.input)
|
||||
if d.expectedResult != exists {
|
||||
t.Errorf("Test %d failed. Expected result %t got %t", i, d.expectedResult, exists)
|
||||
}
|
||||
if d.expectedErr != err {
|
||||
t.Errorf("Test %d failed. Expected %q got %q", i, d.expectedErr, err)
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
func TestSafeWriteToDisk(t *testing.T) {
|
||||
emptyFile, _ := createZeroSizedFileInTempDir()
|
||||
defer deleteFileInTempDir(emptyFile)
|
||||
tmpDir, _ := createEmptyTempDir()
|
||||
defer deleteTempDir(tmpDir)
|
||||
|
||||
randomString := "This is a random string!"
|
||||
reader := strings.NewReader(randomString)
|
||||
|
||||
fileExists := fmt.Errorf("%v already exists", emptyFile.Name())
|
||||
|
||||
type test struct {
|
||||
filename string
|
||||
expectedErr error
|
||||
}
|
||||
|
||||
now := time.Now().Unix()
|
||||
nowStr := strconv.FormatInt(now, 10)
|
||||
data := []test{
|
||||
{emptyFile.Name(), fileExists},
|
||||
{tmpDir + "/" + nowStr, nil},
|
||||
}
|
||||
|
||||
for i, d := range data {
|
||||
e := SafeWriteReader(testFS, d.filename, reader)
|
||||
if d.expectedErr != nil {
|
||||
if d.expectedErr.Error() != e.Error() {
|
||||
t.Errorf("Test %d failed. Expected error %q but got %q", i, d.expectedErr.Error(), e.Error())
|
||||
}
|
||||
} else {
|
||||
if d.expectedErr != e {
|
||||
t.Errorf("Test %d failed. Expected %q but got %q", i, d.expectedErr, e)
|
||||
}
|
||||
contents, _ := ReadFile(testFS, d.filename)
|
||||
if randomString != string(contents) {
|
||||
t.Errorf("Test %d failed. Expected contents %q but got %q", i, randomString, string(contents))
|
||||
}
|
||||
}
|
||||
reader.Seek(0, 0)
|
||||
}
|
||||
}
|
||||
|
||||
func TestWriteToDisk(t *testing.T) {
|
||||
emptyFile, _ := createZeroSizedFileInTempDir()
|
||||
defer deleteFileInTempDir(emptyFile)
|
||||
tmpDir, _ := createEmptyTempDir()
|
||||
defer deleteTempDir(tmpDir)
|
||||
|
||||
randomString := "This is a random string!"
|
||||
reader := strings.NewReader(randomString)
|
||||
|
||||
type test struct {
|
||||
filename string
|
||||
expectedErr error
|
||||
}
|
||||
|
||||
now := time.Now().Unix()
|
||||
nowStr := strconv.FormatInt(now, 10)
|
||||
data := []test{
|
||||
{emptyFile.Name(), nil},
|
||||
{tmpDir + "/" + nowStr, nil},
|
||||
}
|
||||
|
||||
for i, d := range data {
|
||||
e := WriteReader(testFS, d.filename, reader)
|
||||
if d.expectedErr != e {
|
||||
t.Errorf("Test %d failed. WriteToDisk Error Expected %q but got %q", i, d.expectedErr, e)
|
||||
}
|
||||
contents, e := ReadFile(testFS, d.filename)
|
||||
if e != nil {
|
||||
t.Errorf("Test %d failed. Could not read file %s. Reason: %s\n", i, d.filename, e)
|
||||
}
|
||||
if randomString != string(contents) {
|
||||
t.Errorf("Test %d failed. Expected contents %q but got %q", i, randomString, string(contents))
|
||||
}
|
||||
reader.Seek(0, 0)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetTempDir(t *testing.T) {
|
||||
dir := os.TempDir()
|
||||
if FilePathSeparator != dir[len(dir)-1:] {
|
||||
dir = dir + FilePathSeparator
|
||||
}
|
||||
testDir := "hugoTestFolder" + FilePathSeparator
|
||||
tests := []struct {
|
||||
input string
|
||||
expected string
|
||||
}{
|
||||
{"", dir},
|
||||
{testDir + " Foo bar ", dir + testDir + " Foo bar " + FilePathSeparator},
|
||||
{testDir + "Foo.Bar/foo_Bar-Foo", dir + testDir + "Foo.Bar/foo_Bar-Foo" + FilePathSeparator},
|
||||
{testDir + "fOO,bar:foo%bAR", dir + testDir + "fOObarfoo%bAR" + FilePathSeparator},
|
||||
{testDir + "FOo/BaR.html", dir + testDir + "FOo/BaR.html" + FilePathSeparator},
|
||||
{testDir + "трям/трям", dir + testDir + "трям/трям" + FilePathSeparator},
|
||||
{testDir + "은행", dir + testDir + "은행" + FilePathSeparator},
|
||||
{testDir + "Банковский кассир", dir + testDir + "Банковский кассир" + FilePathSeparator},
|
||||
}
|
||||
|
||||
for _, test := range tests {
|
||||
output := GetTempDir(new(MemMapFs), test.input)
|
||||
if output != test.expected {
|
||||
t.Errorf("Expected %#v, got %#v\n", test.expected, output)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// This function is very dangerous. Don't use it.
|
||||
func deleteTempDir(d string) {
|
||||
err := os.RemoveAll(d)
|
||||
if err != nil {
|
||||
// now what?
|
||||
}
|
||||
}
|
||||
|
||||
func TestFullBaseFsPath(t *testing.T) {
|
||||
type dirSpec struct {
|
||||
Dir1, Dir2, Dir3 string
|
||||
}
|
||||
dirSpecs := []dirSpec{
|
||||
dirSpec{Dir1: "/", Dir2: "/", Dir3: "/"},
|
||||
dirSpec{Dir1: "/", Dir2: "/path2", Dir3: "/"},
|
||||
dirSpec{Dir1: "/path1/dir", Dir2: "/path2/dir/", Dir3: "/path3/dir"},
|
||||
dirSpec{Dir1: "C:/path1", Dir2: "path2/dir", Dir3: "/path3/dir/"},
|
||||
}
|
||||
|
||||
for _, ds := range dirSpecs {
|
||||
memFs := NewMemMapFs()
|
||||
level1Fs := NewBasePathFs(memFs, ds.Dir1)
|
||||
level2Fs := NewBasePathFs(level1Fs, ds.Dir2)
|
||||
level3Fs := NewBasePathFs(level2Fs, ds.Dir3)
|
||||
|
||||
type spec struct {
|
||||
BaseFs Fs
|
||||
FileName string
|
||||
ExpectedPath string
|
||||
}
|
||||
specs := []spec{
|
||||
spec{BaseFs: level3Fs, FileName: "f.txt", ExpectedPath: filepath.Join(ds.Dir1, ds.Dir2, ds.Dir3, "f.txt")},
|
||||
spec{BaseFs: level3Fs, FileName: "", ExpectedPath: filepath.Join(ds.Dir1, ds.Dir2, ds.Dir3, "")},
|
||||
spec{BaseFs: level2Fs, FileName: "f.txt", ExpectedPath: filepath.Join(ds.Dir1, ds.Dir2, "f.txt")},
|
||||
spec{BaseFs: level2Fs, FileName: "", ExpectedPath: filepath.Join(ds.Dir1, ds.Dir2, "")},
|
||||
spec{BaseFs: level1Fs, FileName: "f.txt", ExpectedPath: filepath.Join(ds.Dir1, "f.txt")},
|
||||
spec{BaseFs: level1Fs, FileName: "", ExpectedPath: filepath.Join(ds.Dir1, "")},
|
||||
}
|
||||
|
||||
for _, s := range specs {
|
||||
if actualPath := FullBaseFsPath(s.BaseFs.(*BasePathFs), s.FileName); actualPath != s.ExpectedPath {
|
||||
t.Errorf("Expected \n%s got \n%s", s.ExpectedPath, actualPath)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
1208
vendor/github.com/spf13/cast/cast_test.go
сгенерированный
поставляемый
1208
vendor/github.com/spf13/cast/cast_test.go
сгенерированный
поставляемый
Разница между файлами не показана из-за своего большого размера
Загрузить разницу
38
vendor/github.com/spf13/cobra/.circleci/config.yml
сгенерированный
поставляемый
38
vendor/github.com/spf13/cobra/.circleci/config.yml
сгенерированный
поставляемый
@@ -1,38 +0,0 @@
|
||||
workflows:
|
||||
version: 2
|
||||
main:
|
||||
jobs:
|
||||
- go-current
|
||||
- go-previous
|
||||
- go-latest
|
||||
base: &base
|
||||
working_directory: /go/src/github.com/spf13/cobra
|
||||
steps:
|
||||
- checkout
|
||||
- run:
|
||||
name: "All Commands"
|
||||
command: |
|
||||
mkdir -p bin
|
||||
curl -Lso bin/shellcheck https://github.com/caarlos0/shellcheck-docker/releases/download/v0.4.3/shellcheck
|
||||
chmod +x bin/shellcheck
|
||||
go get -t -v ./...
|
||||
PATH=$PATH:$PWD/bin go test -v ./...
|
||||
go build
|
||||
diff -u <(echo -n) <(gofmt -d -s .)
|
||||
if [ -z $NOVET ]; then
|
||||
diff -u <(echo -n) <(go tool vet . 2>&1 | grep -vE 'ExampleCommand|bash_completions.*Fprint');
|
||||
fi
|
||||
version: 2
|
||||
jobs:
|
||||
go-current:
|
||||
docker:
|
||||
- image: circleci/golang:1.8.3
|
||||
<<: *base
|
||||
go-previous:
|
||||
docker:
|
||||
- image: circleci/golang:1.7.6
|
||||
<<: *base
|
||||
go-latest:
|
||||
docker:
|
||||
- image: circleci/golang:latest
|
||||
<<: *base
|
||||
4
vendor/github.com/spf13/cobra/.travis.yml
сгенерированный
поставляемый
4
vendor/github.com/spf13/cobra/.travis.yml
сгенерированный
поставляемый
@@ -2,8 +2,8 @@ language: go
|
||||
|
||||
matrix:
|
||||
include:
|
||||
- go: 1.7.6
|
||||
- go: 1.8.3
|
||||
- go: 1.9.4
|
||||
- go: 1.10.0
|
||||
- go: tip
|
||||
allow_failures:
|
||||
- go: tip
|
||||
|
||||
241
vendor/github.com/spf13/cobra/args_test.go
сгенерированный
поставляемый
241
vendor/github.com/spf13/cobra/args_test.go
сгенерированный
поставляемый
@@ -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)
|
||||
}
|
||||
}
|
||||
22
vendor/github.com/spf13/cobra/bash_completions.go
сгенерированный
поставляемый
22
vendor/github.com/spf13/cobra/bash_completions.go
сгенерированный
поставляемый
@@ -136,6 +136,12 @@ __%[1]s_handle_reply()
|
||||
if declare -F __ltrim_colon_completions >/dev/null; then
|
||||
__ltrim_colon_completions "$cur"
|
||||
fi
|
||||
|
||||
# If there is only 1 completion and it is a flag with an = it will be completed
|
||||
# but we don't want a space after the =
|
||||
if [[ "${#COMPREPLY[@]}" -eq "1" ]] && [[ $(type -t compopt) = "builtin" ]] && [[ "${COMPREPLY[0]}" == --*= ]]; then
|
||||
compopt -o nospace
|
||||
fi
|
||||
}
|
||||
|
||||
# The arguments should be in the form "ext1|ext2|extn"
|
||||
@@ -222,7 +228,7 @@ __%[1]s_handle_command()
|
||||
next_command="_${last_command}_${words[c]//:/__}"
|
||||
else
|
||||
if [[ $c -eq 0 ]]; then
|
||||
next_command="_$(basename "${words[c]//:/__}")"
|
||||
next_command="_%[1]s_root_command"
|
||||
else
|
||||
next_command="_${words[c]//:/__}"
|
||||
fi
|
||||
@@ -243,7 +249,7 @@ __%[1]s_handle_word()
|
||||
__%[1]s_handle_flag
|
||||
elif __%[1]s_contains_word "${words[c]}" "${commands[@]}"; then
|
||||
__%[1]s_handle_command
|
||||
elif [[ $c -eq 0 ]] && __%[1]s_contains_word "$(basename "${words[c]}")" "${commands[@]}"; then
|
||||
elif [[ $c -eq 0 ]]; then
|
||||
__%[1]s_handle_command
|
||||
else
|
||||
__%[1]s_handle_noun
|
||||
@@ -311,7 +317,7 @@ func writeFlagHandler(buf *bytes.Buffer, name string, annotations map[string][]s
|
||||
|
||||
var ext string
|
||||
if len(value) > 0 {
|
||||
ext = fmt.Sprintf("__%s_handle_filename_extension_flag ", cmd.Name()) + strings.Join(value, "|")
|
||||
ext = fmt.Sprintf("__%s_handle_filename_extension_flag ", cmd.Root().Name()) + strings.Join(value, "|")
|
||||
} else {
|
||||
ext = "_filedir"
|
||||
}
|
||||
@@ -329,7 +335,7 @@ func writeFlagHandler(buf *bytes.Buffer, name string, annotations map[string][]s
|
||||
|
||||
var ext string
|
||||
if len(value) == 1 {
|
||||
ext = fmt.Sprintf("__%s_handle_subdirs_in_dir_flag ", cmd.Name()) + value[0]
|
||||
ext = fmt.Sprintf("__%s_handle_subdirs_in_dir_flag ", cmd.Root().Name()) + value[0]
|
||||
} else {
|
||||
ext = "_filedir -d"
|
||||
}
|
||||
@@ -455,7 +461,13 @@ func gen(buf *bytes.Buffer, cmd *Command) {
|
||||
commandName := cmd.CommandPath()
|
||||
commandName = strings.Replace(commandName, " ", "_", -1)
|
||||
commandName = strings.Replace(commandName, ":", "__", -1)
|
||||
buf.WriteString(fmt.Sprintf("_%s()\n{\n", commandName))
|
||||
|
||||
if cmd.Root() == cmd {
|
||||
buf.WriteString(fmt.Sprintf("_%s_root_command()\n{\n", commandName))
|
||||
} else {
|
||||
buf.WriteString(fmt.Sprintf("_%s()\n{\n", commandName))
|
||||
}
|
||||
|
||||
buf.WriteString(fmt.Sprintf(" last_command=%q\n", commandName))
|
||||
writeCommands(buf, cmd)
|
||||
writeFlags(buf, cmd)
|
||||
|
||||
25
vendor/github.com/spf13/cobra/bash_completions.md
сгенерированный
поставляемый
25
vendor/github.com/spf13/cobra/bash_completions.md
сгенерированный
поставляемый
@@ -6,15 +6,16 @@ Generating bash completions from a cobra command is incredibly easy. An actual p
|
||||
package main
|
||||
|
||||
import (
|
||||
"io/ioutil"
|
||||
"os"
|
||||
"io/ioutil"
|
||||
"os"
|
||||
|
||||
"github.com/GoogleCloudPlatform/kubernetes/pkg/kubectl/cmd"
|
||||
"k8s.io/kubernetes/pkg/kubectl/cmd"
|
||||
"k8s.io/kubernetes/pkg/kubectl/cmd/util"
|
||||
)
|
||||
|
||||
func main() {
|
||||
kubectl := cmd.NewFactory(nil).NewKubectlCommand(os.Stdin, ioutil.Discard, ioutil.Discard)
|
||||
kubectl.GenBashCompletionFile("out.sh")
|
||||
kubectl := cmd.NewKubectlCommand(util.NewFactory(nil), os.Stdin, ioutil.Discard, ioutil.Discard)
|
||||
kubectl.GenBashCompletionFile("out.sh")
|
||||
}
|
||||
```
|
||||
|
||||
@@ -204,3 +205,17 @@ __kubectl_get_namespaces()
|
||||
fi
|
||||
}
|
||||
```
|
||||
# Using bash aliases for commands
|
||||
|
||||
You can also configure the `bash aliases` for the commands and they will also support completions.
|
||||
|
||||
```bash
|
||||
alias aliasname=origcommand
|
||||
complete -o default -F __start_origcommand aliasname
|
||||
|
||||
# and now when you run `aliasname` completion will make
|
||||
# suggestions as it did for `origcommand`.
|
||||
|
||||
$) aliasname <tab><tab>
|
||||
completion firstcommand secondcommand
|
||||
```
|
||||
|
||||
197
vendor/github.com/spf13/cobra/bash_completions_test.go
сгенерированный
поставляемый
197
vendor/github.com/spf13/cobra/bash_completions_test.go
сгенерированный
поставляемый
@@ -1,197 +0,0 @@
|
||||
package cobra
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"os"
|
||||
"os/exec"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func checkOmit(t *testing.T, found, unexpected string) {
|
||||
if strings.Contains(found, unexpected) {
|
||||
t.Errorf("Got: %q\nBut should not have!\n", unexpected)
|
||||
}
|
||||
}
|
||||
|
||||
func check(t *testing.T, found, expected string) {
|
||||
if !strings.Contains(found, expected) {
|
||||
t.Errorf("Expecting to contain: \n %q\nGot:\n %q\n", expected, found)
|
||||
}
|
||||
}
|
||||
|
||||
func runShellCheck(s string) error {
|
||||
excluded := []string{
|
||||
"SC2034", // PREFIX appears unused. Verify it or export it.
|
||||
}
|
||||
cmd := exec.Command("shellcheck", "-s", "bash", "-", "-e", strings.Join(excluded, ","))
|
||||
cmd.Stderr = os.Stderr
|
||||
cmd.Stdout = os.Stdout
|
||||
|
||||
stdin, err := cmd.StdinPipe()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
go func() {
|
||||
stdin.Write([]byte(s))
|
||||
stdin.Close()
|
||||
}()
|
||||
|
||||
return cmd.Run()
|
||||
}
|
||||
|
||||
// World worst custom function, just keep telling you to enter hello!
|
||||
const bashCompletionFunc = `__custom_func() {
|
||||
COMPREPLY=( "hello" )
|
||||
}
|
||||
`
|
||||
|
||||
func TestBashCompletions(t *testing.T) {
|
||||
rootCmd := &Command{
|
||||
Use: "root",
|
||||
ArgAliases: []string{"pods", "nodes", "services", "replicationcontrollers", "po", "no", "svc", "rc"},
|
||||
ValidArgs: []string{"pod", "node", "service", "replicationcontroller"},
|
||||
BashCompletionFunction: bashCompletionFunc,
|
||||
Run: emptyRun,
|
||||
}
|
||||
rootCmd.Flags().IntP("introot", "i", -1, "help message for flag introot")
|
||||
rootCmd.MarkFlagRequired("introot")
|
||||
|
||||
// Filename.
|
||||
rootCmd.Flags().String("filename", "", "Enter a filename")
|
||||
rootCmd.MarkFlagFilename("filename", "json", "yaml", "yml")
|
||||
|
||||
// Persistent filename.
|
||||
rootCmd.PersistentFlags().String("persistent-filename", "", "Enter a filename")
|
||||
rootCmd.MarkPersistentFlagFilename("persistent-filename")
|
||||
rootCmd.MarkPersistentFlagRequired("persistent-filename")
|
||||
|
||||
// Filename extensions.
|
||||
rootCmd.Flags().String("filename-ext", "", "Enter a filename (extension limited)")
|
||||
rootCmd.MarkFlagFilename("filename-ext")
|
||||
rootCmd.Flags().String("custom", "", "Enter a filename (extension limited)")
|
||||
rootCmd.MarkFlagCustom("custom", "__complete_custom")
|
||||
|
||||
// Subdirectories in a given directory.
|
||||
rootCmd.Flags().String("theme", "", "theme to use (located in /themes/THEMENAME/)")
|
||||
rootCmd.Flags().SetAnnotation("theme", BashCompSubdirsInDir, []string{"themes"})
|
||||
|
||||
echoCmd := &Command{
|
||||
Use: "echo [string to echo]",
|
||||
Aliases: []string{"say"},
|
||||
Short: "Echo anything to the screen",
|
||||
Long: "an utterly useless command for testing.",
|
||||
Example: "Just run cobra-test echo",
|
||||
Run: emptyRun,
|
||||
}
|
||||
|
||||
printCmd := &Command{
|
||||
Use: "print [string to print]",
|
||||
Args: MinimumNArgs(1),
|
||||
Short: "Print anything to the screen",
|
||||
Long: "an absolutely utterly useless command for testing.",
|
||||
Run: emptyRun,
|
||||
}
|
||||
|
||||
deprecatedCmd := &Command{
|
||||
Use: "deprecated [can't do anything here]",
|
||||
Args: NoArgs,
|
||||
Short: "A command which is deprecated",
|
||||
Long: "an absolutely utterly useless command for testing deprecation!.",
|
||||
Deprecated: "Please use echo instead",
|
||||
Run: emptyRun,
|
||||
}
|
||||
|
||||
colonCmd := &Command{
|
||||
Use: "cmd:colon",
|
||||
Run: emptyRun,
|
||||
}
|
||||
|
||||
timesCmd := &Command{
|
||||
Use: "times [# times] [string to echo]",
|
||||
SuggestFor: []string{"counts"},
|
||||
Args: OnlyValidArgs,
|
||||
ValidArgs: []string{"one", "two", "three", "four"},
|
||||
Short: "Echo anything to the screen more times",
|
||||
Long: "a slightly useless command for testing.",
|
||||
Run: emptyRun,
|
||||
}
|
||||
|
||||
echoCmd.AddCommand(timesCmd)
|
||||
rootCmd.AddCommand(echoCmd, printCmd, deprecatedCmd, colonCmd)
|
||||
|
||||
buf := new(bytes.Buffer)
|
||||
rootCmd.GenBashCompletion(buf)
|
||||
output := buf.String()
|
||||
|
||||
check(t, output, "_root")
|
||||
check(t, output, "_root_echo")
|
||||
check(t, output, "_root_echo_times")
|
||||
check(t, output, "_root_print")
|
||||
check(t, output, "_root_cmd__colon")
|
||||
|
||||
// check for required flags
|
||||
check(t, output, `must_have_one_flag+=("--introot=")`)
|
||||
check(t, output, `must_have_one_flag+=("--persistent-filename=")`)
|
||||
// check for custom completion function
|
||||
check(t, output, `COMPREPLY=( "hello" )`)
|
||||
// check for required nouns
|
||||
check(t, output, `must_have_one_noun+=("pod")`)
|
||||
// check for noun aliases
|
||||
check(t, output, `noun_aliases+=("pods")`)
|
||||
check(t, output, `noun_aliases+=("rc")`)
|
||||
checkOmit(t, output, `must_have_one_noun+=("pods")`)
|
||||
// check for filename extension flags
|
||||
check(t, output, `flags_completion+=("_filedir")`)
|
||||
// check for filename extension flags
|
||||
check(t, output, `must_have_one_noun+=("three")`)
|
||||
// check for filename extension flags
|
||||
check(t, output, fmt.Sprintf(`flags_completion+=("__%s_handle_filename_extension_flag json|yaml|yml")`, rootCmd.Name()))
|
||||
// check for custom flags
|
||||
check(t, output, `flags_completion+=("__complete_custom")`)
|
||||
// check for subdirs_in_dir flags
|
||||
check(t, output, fmt.Sprintf(`flags_completion+=("__%s_handle_subdirs_in_dir_flag themes")`, rootCmd.Name()))
|
||||
|
||||
checkOmit(t, output, deprecatedCmd.Name())
|
||||
|
||||
// If available, run shellcheck against the script.
|
||||
if err := exec.Command("which", "shellcheck").Run(); err != nil {
|
||||
return
|
||||
}
|
||||
if err := runShellCheck(output); err != nil {
|
||||
t.Fatalf("shellcheck failed: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBashCompletionHiddenFlag(t *testing.T) {
|
||||
c := &Command{Use: "c", Run: emptyRun}
|
||||
|
||||
const flagName = "hiddenFlag"
|
||||
c.Flags().Bool(flagName, false, "")
|
||||
c.Flags().MarkHidden(flagName)
|
||||
|
||||
buf := new(bytes.Buffer)
|
||||
c.GenBashCompletion(buf)
|
||||
output := buf.String()
|
||||
|
||||
if strings.Contains(output, flagName) {
|
||||
t.Errorf("Expected completion to not include %q flag: Got %v", flagName, output)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBashCompletionDeprecatedFlag(t *testing.T) {
|
||||
c := &Command{Use: "c", Run: emptyRun}
|
||||
|
||||
const flagName = "deprecated-flag"
|
||||
c.Flags().Bool(flagName, false, "")
|
||||
c.Flags().MarkDeprecated(flagName, "use --not-deprecated instead")
|
||||
|
||||
buf := new(bytes.Buffer)
|
||||
c.GenBashCompletion(buf)
|
||||
output := buf.String()
|
||||
|
||||
if strings.Contains(output, flagName) {
|
||||
t.Errorf("expected completion to not include %q flag: Got %v", flagName, output)
|
||||
}
|
||||
}
|
||||
94
vendor/github.com/spf13/cobra/cobra/README.md
сгенерированный
поставляемый
94
vendor/github.com/spf13/cobra/cobra/README.md
сгенерированный
поставляемый
@@ -1,94 +0,0 @@
|
||||
# Cobra Generator
|
||||
|
||||
Cobra provides its own program that will create your application and add any
|
||||
commands you want. It's the easiest way to incorporate Cobra into your application.
|
||||
|
||||
In order to use the cobra command, compile it using the following command:
|
||||
|
||||
go get github.com/spf13/cobra/cobra
|
||||
|
||||
This will create the cobra executable under your `$GOPATH/bin` directory.
|
||||
|
||||
### cobra init
|
||||
|
||||
The `cobra init [app]` command will create your initial application code
|
||||
for you. It is a very powerful application that will populate your program with
|
||||
the right structure so you can immediately enjoy all the benefits of Cobra. It
|
||||
will also automatically apply the license you specify to your application.
|
||||
|
||||
Cobra init is pretty smart. You can provide it a full path, or simply a path
|
||||
similar to what is expected in the import.
|
||||
|
||||
```
|
||||
cobra init github.com/spf13/newApp
|
||||
```
|
||||
|
||||
### cobra add
|
||||
|
||||
Once an application is initialized, Cobra can create additional commands for you.
|
||||
Let's say you created an app and you wanted the following commands for it:
|
||||
|
||||
* app serve
|
||||
* app config
|
||||
* app config create
|
||||
|
||||
In your project directory (where your main.go file is) you would run the following:
|
||||
|
||||
```
|
||||
cobra add serve
|
||||
cobra add config
|
||||
cobra add create -p 'configCmd'
|
||||
```
|
||||
|
||||
*Note: Use camelCase (not snake_case/snake-case) for command names.
|
||||
Otherwise, you will encounter errors.
|
||||
For example, `cobra add add-user` is incorrect, but `cobra add addUser` is valid.*
|
||||
|
||||
Once you have run these three commands you would have an app structure similar to
|
||||
the following:
|
||||
|
||||
```
|
||||
▾ app/
|
||||
▾ cmd/
|
||||
serve.go
|
||||
config.go
|
||||
create.go
|
||||
main.go
|
||||
```
|
||||
|
||||
At this point you can run `go run main.go` and it would run your app. `go run
|
||||
main.go serve`, `go run main.go config`, `go run main.go config create` along
|
||||
with `go run main.go help serve`, etc. would all work.
|
||||
|
||||
Obviously you haven't added your own code to these yet. The commands are ready
|
||||
for you to give them their tasks. Have fun!
|
||||
|
||||
### Configuring the cobra generator
|
||||
|
||||
The Cobra generator will be easier to use if you provide a simple configuration
|
||||
file which will help you eliminate providing a bunch of repeated information in
|
||||
flags over and over.
|
||||
|
||||
An example ~/.cobra.yaml file:
|
||||
|
||||
```yaml
|
||||
author: Steve Francia <spf@spf13.com>
|
||||
license: MIT
|
||||
```
|
||||
|
||||
You can specify no license by setting `license` to `none` or you can specify
|
||||
a custom license:
|
||||
|
||||
```yaml
|
||||
license:
|
||||
header: This file is part of {{ .appName }}.
|
||||
text: |
|
||||
{{ .copyright }}
|
||||
|
||||
This is my license. There are many like it, but this one is mine.
|
||||
My license is my best friend. It is my life. I must master it as I must
|
||||
master my life.
|
||||
```
|
||||
|
||||
You can also use built-in licenses. For example, **GPLv2**, **GPLv3**, **LGPL**,
|
||||
**AGPL**, **MIT**, **2-Clause BSD** or **3-Clause BSD**.
|
||||
179
vendor/github.com/spf13/cobra/cobra/cmd/add.go
сгенерированный
поставляемый
179
vendor/github.com/spf13/cobra/cobra/cmd/add.go
сгенерированный
поставляемый
@@ -1,179 +0,0 @@
|
||||
// Copyright © 2015 Steve Francia <spf@spf13.com>.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"unicode"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
func init() {
|
||||
addCmd.Flags().StringVarP(&packageName, "package", "t", "", "target package name (e.g. github.com/spf13/hugo)")
|
||||
addCmd.Flags().StringVarP(&parentName, "parent", "p", "rootCmd", "variable name of parent command for this command")
|
||||
}
|
||||
|
||||
var packageName, parentName string
|
||||
|
||||
var addCmd = &cobra.Command{
|
||||
Use: "add [command name]",
|
||||
Aliases: []string{"command"},
|
||||
Short: "Add a command to a Cobra Application",
|
||||
Long: `Add (cobra add) will create a new command, with a license and
|
||||
the appropriate structure for a Cobra-based CLI application,
|
||||
and register it to its parent (default rootCmd).
|
||||
|
||||
If you want your command to be public, pass in the command name
|
||||
with an initial uppercase letter.
|
||||
|
||||
Example: cobra add server -> resulting in a new cmd/server.go`,
|
||||
|
||||
Run: func(cmd *cobra.Command, args []string) {
|
||||
if len(args) < 1 {
|
||||
er("add needs a name for the command")
|
||||
}
|
||||
|
||||
var project *Project
|
||||
if packageName != "" {
|
||||
project = NewProject(packageName)
|
||||
} else {
|
||||
wd, err := os.Getwd()
|
||||
if err != nil {
|
||||
er(err)
|
||||
}
|
||||
project = NewProjectFromPath(wd)
|
||||
}
|
||||
|
||||
cmdName := validateCmdName(args[0])
|
||||
cmdPath := filepath.Join(project.CmdPath(), cmdName+".go")
|
||||
createCmdFile(project.License(), cmdPath, cmdName)
|
||||
|
||||
fmt.Fprintln(cmd.OutOrStdout(), cmdName, "created at", cmdPath)
|
||||
},
|
||||
}
|
||||
|
||||
// validateCmdName returns source without any dashes and underscore.
|
||||
// If there will be dash or underscore, next letter will be uppered.
|
||||
// It supports only ASCII (1-byte character) strings.
|
||||
// https://github.com/spf13/cobra/issues/269
|
||||
func validateCmdName(source string) string {
|
||||
i := 0
|
||||
l := len(source)
|
||||
// The output is initialized on demand, then first dash or underscore
|
||||
// occurs.
|
||||
var output string
|
||||
|
||||
for i < l {
|
||||
if source[i] == '-' || source[i] == '_' {
|
||||
if output == "" {
|
||||
output = source[:i]
|
||||
}
|
||||
|
||||
// If it's last rune and it's dash or underscore,
|
||||
// don't add it output and break the loop.
|
||||
if i == l-1 {
|
||||
break
|
||||
}
|
||||
|
||||
// If next character is dash or underscore,
|
||||
// just skip the current character.
|
||||
if source[i+1] == '-' || source[i+1] == '_' {
|
||||
i++
|
||||
continue
|
||||
}
|
||||
|
||||
// If the current character is dash or underscore,
|
||||
// upper next letter and add to output.
|
||||
output += string(unicode.ToUpper(rune(source[i+1])))
|
||||
// We know, what source[i] is dash or underscore and source[i+1] is
|
||||
// uppered character, so make i = i+2.
|
||||
i += 2
|
||||
continue
|
||||
}
|
||||
|
||||
// If the current character isn't dash or underscore,
|
||||
// just add it.
|
||||
if output != "" {
|
||||
output += string(source[i])
|
||||
}
|
||||
i++
|
||||
}
|
||||
|
||||
if output == "" {
|
||||
return source // source is initially valid name.
|
||||
}
|
||||
return output
|
||||
}
|
||||
|
||||
func createCmdFile(license License, path, cmdName string) {
|
||||
template := `{{comment .copyright}}
|
||||
{{if .license}}{{comment .license}}{{end}}
|
||||
|
||||
package {{.cmdPackage}}
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
// {{.cmdName}}Cmd represents the {{.cmdName}} command
|
||||
var {{.cmdName}}Cmd = &cobra.Command{
|
||||
Use: "{{.cmdName}}",
|
||||
Short: "A brief description of your command",
|
||||
Long: ` + "`" + `A longer description that spans multiple lines and likely contains examples
|
||||
and usage of using your command. For example:
|
||||
|
||||
Cobra is a CLI library for Go that empowers applications.
|
||||
This application is a tool to generate the needed files
|
||||
to quickly create a Cobra application.` + "`" + `,
|
||||
Run: func(cmd *cobra.Command, args []string) {
|
||||
fmt.Println("{{.cmdName}} called")
|
||||
},
|
||||
}
|
||||
|
||||
func init() {
|
||||
{{.parentName}}.AddCommand({{.cmdName}}Cmd)
|
||||
|
||||
// Here you will define your flags and configuration settings.
|
||||
|
||||
// Cobra supports Persistent Flags which will work for this command
|
||||
// and all subcommands, e.g.:
|
||||
// {{.cmdName}}Cmd.PersistentFlags().String("foo", "", "A help for foo")
|
||||
|
||||
// Cobra supports local flags which will only run when this command
|
||||
// is called directly, e.g.:
|
||||
// {{.cmdName}}Cmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
|
||||
}
|
||||
`
|
||||
|
||||
data := make(map[string]interface{})
|
||||
data["copyright"] = copyrightLine()
|
||||
data["license"] = license.Header
|
||||
data["cmdPackage"] = filepath.Base(filepath.Dir(path)) // last dir of path
|
||||
data["parentName"] = parentName
|
||||
data["cmdName"] = cmdName
|
||||
|
||||
cmdScript, err := executeTemplate(template, data)
|
||||
if err != nil {
|
||||
er(err)
|
||||
}
|
||||
err = writeStringToFile(path, cmdScript)
|
||||
if err != nil {
|
||||
er(err)
|
||||
}
|
||||
}
|
||||
109
vendor/github.com/spf13/cobra/cobra/cmd/add_test.go
сгенерированный
поставляемый
109
vendor/github.com/spf13/cobra/cobra/cmd/add_test.go
сгенерированный
поставляемый
@@ -1,109 +0,0 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"io/ioutil"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"github.com/spf13/viper"
|
||||
)
|
||||
|
||||
// TestGoldenAddCmd initializes the project "github.com/spf13/testproject"
|
||||
// in GOPATH, adds "test" command
|
||||
// and compares the content of all files in cmd directory of testproject
|
||||
// with appropriate golden files.
|
||||
// Use -update to update existing golden files.
|
||||
func TestGoldenAddCmd(t *testing.T) {
|
||||
projectName := "github.com/spf13/testproject"
|
||||
project := NewProject(projectName)
|
||||
defer os.RemoveAll(project.AbsPath())
|
||||
|
||||
viper.Set("author", "NAME HERE <EMAIL ADDRESS>")
|
||||
viper.Set("license", "apache")
|
||||
viper.Set("year", 2017)
|
||||
defer viper.Set("author", nil)
|
||||
defer viper.Set("license", nil)
|
||||
defer viper.Set("year", nil)
|
||||
|
||||
// Initialize the project first.
|
||||
initializeProject(project)
|
||||
|
||||
// Then add the "test" command.
|
||||
cmdName := "test"
|
||||
cmdPath := filepath.Join(project.CmdPath(), cmdName+".go")
|
||||
createCmdFile(project.License(), cmdPath, cmdName)
|
||||
|
||||
expectedFiles := []string{".", "root.go", "test.go"}
|
||||
gotFiles := []string{}
|
||||
|
||||
// Check project file hierarchy and compare the content of every single file
|
||||
// with appropriate golden file.
|
||||
err := filepath.Walk(project.CmdPath(), func(path string, info os.FileInfo, err error) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Make path relative to project.CmdPath().
|
||||
// E.g. path = "/home/user/go/src/github.com/spf13/testproject/cmd/root.go"
|
||||
// then it returns just "root.go".
|
||||
relPath, err := filepath.Rel(project.CmdPath(), path)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
relPath = filepath.ToSlash(relPath)
|
||||
gotFiles = append(gotFiles, relPath)
|
||||
goldenPath := filepath.Join("testdata", filepath.Base(path)+".golden")
|
||||
|
||||
switch relPath {
|
||||
// Known directories.
|
||||
case ".":
|
||||
return nil
|
||||
// Known files.
|
||||
case "root.go", "test.go":
|
||||
if *update {
|
||||
got, err := ioutil.ReadFile(path)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
ioutil.WriteFile(goldenPath, got, 0644)
|
||||
}
|
||||
return compareFiles(path, goldenPath)
|
||||
}
|
||||
// Unknown file.
|
||||
return errors.New("unknown file: " + path)
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// Check if some files lack.
|
||||
if err := checkLackFiles(expectedFiles, gotFiles); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateCmdName(t *testing.T) {
|
||||
testCases := []struct {
|
||||
input string
|
||||
expected string
|
||||
}{
|
||||
{"cmdName", "cmdName"},
|
||||
{"cmd_name", "cmdName"},
|
||||
{"cmd-name", "cmdName"},
|
||||
{"cmd______Name", "cmdName"},
|
||||
{"cmd------Name", "cmdName"},
|
||||
{"cmd______name", "cmdName"},
|
||||
{"cmd------name", "cmdName"},
|
||||
{"cmdName-----", "cmdName"},
|
||||
{"cmdname-", "cmdname"},
|
||||
}
|
||||
|
||||
for _, testCase := range testCases {
|
||||
got := validateCmdName(testCase.input)
|
||||
if testCase.expected != got {
|
||||
t.Errorf("Expected %q, got %q", testCase.expected, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
77
vendor/github.com/spf13/cobra/cobra/cmd/golden_test.go
сгенерированный
поставляемый
77
vendor/github.com/spf13/cobra/cobra/cmd/golden_test.go
сгенерированный
поставляемый
@@ -1,77 +0,0 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"errors"
|
||||
"flag"
|
||||
"fmt"
|
||||
"io/ioutil"
|
||||
"os/exec"
|
||||
)
|
||||
|
||||
var update = flag.Bool("update", false, "update .golden files")
|
||||
|
||||
func init() {
|
||||
// Mute commands.
|
||||
addCmd.SetOutput(new(bytes.Buffer))
|
||||
initCmd.SetOutput(new(bytes.Buffer))
|
||||
}
|
||||
|
||||
// compareFiles compares the content of files with pathA and pathB.
|
||||
// If contents are equal, it returns nil.
|
||||
// If not, it returns which files are not equal
|
||||
// and diff (if system has diff command) between these files.
|
||||
func compareFiles(pathA, pathB string) error {
|
||||
contentA, err := ioutil.ReadFile(pathA)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
contentB, err := ioutil.ReadFile(pathB)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !bytes.Equal(contentA, contentB) {
|
||||
output := new(bytes.Buffer)
|
||||
output.WriteString(fmt.Sprintf("%q and %q are not equal!\n\n", pathA, pathB))
|
||||
|
||||
diffPath, err := exec.LookPath("diff")
|
||||
if err != nil {
|
||||
// Don't execute diff if it can't be found.
|
||||
return nil
|
||||
}
|
||||
diffCmd := exec.Command(diffPath, "-u", pathA, pathB)
|
||||
diffCmd.Stdout = output
|
||||
diffCmd.Stderr = output
|
||||
|
||||
output.WriteString("$ diff -u " + pathA + " " + pathB + "\n")
|
||||
if err := diffCmd.Run(); err != nil {
|
||||
output.WriteString("\n" + err.Error())
|
||||
}
|
||||
return errors.New(output.String())
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// checkLackFiles checks if all elements of expected are in got.
|
||||
func checkLackFiles(expected, got []string) error {
|
||||
lacks := make([]string, 0, len(expected))
|
||||
for _, ev := range expected {
|
||||
if !stringInStringSlice(ev, got) {
|
||||
lacks = append(lacks, ev)
|
||||
}
|
||||
}
|
||||
if len(lacks) > 0 {
|
||||
return fmt.Errorf("Lack %v file(s): %v", len(lacks), lacks)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// stringInStringSlice checks if s is an element of slice.
|
||||
func stringInStringSlice(s string, slice []string) bool {
|
||||
for _, v := range slice {
|
||||
if s == v {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
168
vendor/github.com/spf13/cobra/cobra/cmd/helpers.go
сгенерированный
поставляемый
168
vendor/github.com/spf13/cobra/cobra/cmd/helpers.go
сгенерированный
поставляемый
@@ -1,168 +0,0 @@
|
||||
// Copyright © 2015 Steve Francia <spf@spf13.com>.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"text/template"
|
||||
)
|
||||
|
||||
var srcPaths []string
|
||||
|
||||
func init() {
|
||||
// Initialize srcPaths.
|
||||
envGoPath := os.Getenv("GOPATH")
|
||||
goPaths := filepath.SplitList(envGoPath)
|
||||
if len(goPaths) == 0 {
|
||||
// Adapted from https://github.com/Masterminds/glide/pull/798/files.
|
||||
// As of Go 1.8 the GOPATH is no longer required to be set. Instead there
|
||||
// is a default value. If there is no GOPATH check for the default value.
|
||||
// Note, checking the GOPATH first to avoid invoking the go toolchain if
|
||||
// possible.
|
||||
|
||||
goExecutable := os.Getenv("COBRA_GO_EXECUTABLE")
|
||||
if len(goExecutable) <= 0 {
|
||||
goExecutable = "go"
|
||||
}
|
||||
|
||||
out, err := exec.Command(goExecutable, "env", "GOPATH").Output()
|
||||
if err != nil {
|
||||
er(err)
|
||||
}
|
||||
|
||||
toolchainGoPath := strings.TrimSpace(string(out))
|
||||
goPaths = filepath.SplitList(toolchainGoPath)
|
||||
if len(goPaths) == 0 {
|
||||
er("$GOPATH is not set")
|
||||
}
|
||||
}
|
||||
srcPaths = make([]string, 0, len(goPaths))
|
||||
for _, goPath := range goPaths {
|
||||
srcPaths = append(srcPaths, filepath.Join(goPath, "src"))
|
||||
}
|
||||
}
|
||||
|
||||
func er(msg interface{}) {
|
||||
fmt.Println("Error:", msg)
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
// isEmpty checks if a given path is empty.
|
||||
// Hidden files in path are ignored.
|
||||
func isEmpty(path string) bool {
|
||||
fi, err := os.Stat(path)
|
||||
if err != nil {
|
||||
er(err)
|
||||
}
|
||||
|
||||
if !fi.IsDir() {
|
||||
return fi.Size() == 0
|
||||
}
|
||||
|
||||
f, err := os.Open(path)
|
||||
if err != nil {
|
||||
er(err)
|
||||
}
|
||||
defer f.Close()
|
||||
|
||||
names, err := f.Readdirnames(-1)
|
||||
if err != nil && err != io.EOF {
|
||||
er(err)
|
||||
}
|
||||
|
||||
for _, name := range names {
|
||||
if len(name) > 0 && name[0] != '.' {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// exists checks if a file or directory exists.
|
||||
func exists(path string) bool {
|
||||
if path == "" {
|
||||
return false
|
||||
}
|
||||
_, err := os.Stat(path)
|
||||
if err == nil {
|
||||
return true
|
||||
}
|
||||
if !os.IsNotExist(err) {
|
||||
er(err)
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func executeTemplate(tmplStr string, data interface{}) (string, error) {
|
||||
tmpl, err := template.New("").Funcs(template.FuncMap{"comment": commentifyString}).Parse(tmplStr)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
buf := new(bytes.Buffer)
|
||||
err = tmpl.Execute(buf, data)
|
||||
return buf.String(), err
|
||||
}
|
||||
|
||||
func writeStringToFile(path string, s string) error {
|
||||
return writeToFile(path, strings.NewReader(s))
|
||||
}
|
||||
|
||||
// writeToFile writes r to file with path only
|
||||
// if file/directory on given path doesn't exist.
|
||||
func writeToFile(path string, r io.Reader) error {
|
||||
if exists(path) {
|
||||
return fmt.Errorf("%v already exists", path)
|
||||
}
|
||||
|
||||
dir := filepath.Dir(path)
|
||||
if dir != "" {
|
||||
if err := os.MkdirAll(dir, 0777); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
file, err := os.Create(path)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer file.Close()
|
||||
|
||||
_, err = io.Copy(file, r)
|
||||
return err
|
||||
}
|
||||
|
||||
// commentfyString comments every line of in.
|
||||
func commentifyString(in string) string {
|
||||
var newlines []string
|
||||
lines := strings.Split(in, "\n")
|
||||
for _, line := range lines {
|
||||
if strings.HasPrefix(line, "//") {
|
||||
newlines = append(newlines, line)
|
||||
} else {
|
||||
if line == "" {
|
||||
newlines = append(newlines, "//")
|
||||
} else {
|
||||
newlines = append(newlines, "// "+line)
|
||||
}
|
||||
}
|
||||
}
|
||||
return strings.Join(newlines, "\n")
|
||||
}
|
||||
234
vendor/github.com/spf13/cobra/cobra/cmd/init.go
сгенерированный
поставляемый
234
vendor/github.com/spf13/cobra/cobra/cmd/init.go
сгенерированный
поставляемый
@@ -1,234 +0,0 @@
|
||||
// Copyright © 2015 Steve Francia <spf@spf13.com>.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"path"
|
||||
"path/filepath"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
"github.com/spf13/viper"
|
||||
)
|
||||
|
||||
var initCmd = &cobra.Command{
|
||||
Use: "init [name]",
|
||||
Aliases: []string{"initialize", "initialise", "create"},
|
||||
Short: "Initialize a Cobra Application",
|
||||
Long: `Initialize (cobra init) will create a new application, with a license
|
||||
and the appropriate structure for a Cobra-based CLI application.
|
||||
|
||||
* If a name is provided, it will be created in the current directory;
|
||||
* If no name is provided, the current directory will be assumed;
|
||||
* If a relative path is provided, it will be created inside $GOPATH
|
||||
(e.g. github.com/spf13/hugo);
|
||||
* If an absolute path is provided, it will be created;
|
||||
* If the directory already exists but is empty, it will be used.
|
||||
|
||||
Init will not use an existing directory with contents.`,
|
||||
|
||||
Run: func(cmd *cobra.Command, args []string) {
|
||||
wd, err := os.Getwd()
|
||||
if err != nil {
|
||||
er(err)
|
||||
}
|
||||
|
||||
var project *Project
|
||||
if len(args) == 0 {
|
||||
project = NewProjectFromPath(wd)
|
||||
} else if len(args) == 1 {
|
||||
arg := args[0]
|
||||
if arg[0] == '.' {
|
||||
arg = filepath.Join(wd, arg)
|
||||
}
|
||||
if filepath.IsAbs(arg) {
|
||||
project = NewProjectFromPath(arg)
|
||||
} else {
|
||||
project = NewProject(arg)
|
||||
}
|
||||
} else {
|
||||
er("please provide only one argument")
|
||||
}
|
||||
|
||||
initializeProject(project)
|
||||
|
||||
fmt.Fprintln(cmd.OutOrStdout(), `Your Cobra application is ready at
|
||||
`+project.AbsPath()+`.
|
||||
|
||||
Give it a try by going there and running `+"`go run main.go`."+`
|
||||
Add commands to it by running `+"`cobra add [cmdname]`.")
|
||||
},
|
||||
}
|
||||
|
||||
func initializeProject(project *Project) {
|
||||
if !exists(project.AbsPath()) { // If path doesn't yet exist, create it
|
||||
err := os.MkdirAll(project.AbsPath(), os.ModePerm)
|
||||
if err != nil {
|
||||
er(err)
|
||||
}
|
||||
} else if !isEmpty(project.AbsPath()) { // If path exists and is not empty don't use it
|
||||
er("Cobra will not create a new project in a non empty directory: " + project.AbsPath())
|
||||
}
|
||||
|
||||
// We have a directory and it's empty. Time to initialize it.
|
||||
createLicenseFile(project.License(), project.AbsPath())
|
||||
createMainFile(project)
|
||||
createRootCmdFile(project)
|
||||
}
|
||||
|
||||
func createLicenseFile(license License, path string) {
|
||||
data := make(map[string]interface{})
|
||||
data["copyright"] = copyrightLine()
|
||||
|
||||
// Generate license template from text and data.
|
||||
text, err := executeTemplate(license.Text, data)
|
||||
if err != nil {
|
||||
er(err)
|
||||
}
|
||||
|
||||
// Write license text to LICENSE file.
|
||||
err = writeStringToFile(filepath.Join(path, "LICENSE"), text)
|
||||
if err != nil {
|
||||
er(err)
|
||||
}
|
||||
}
|
||||
|
||||
func createMainFile(project *Project) {
|
||||
mainTemplate := `{{ comment .copyright }}
|
||||
{{if .license}}{{ comment .license }}{{end}}
|
||||
|
||||
package main
|
||||
|
||||
import "{{ .importpath }}"
|
||||
|
||||
func main() {
|
||||
cmd.Execute()
|
||||
}
|
||||
`
|
||||
data := make(map[string]interface{})
|
||||
data["copyright"] = copyrightLine()
|
||||
data["license"] = project.License().Header
|
||||
data["importpath"] = path.Join(project.Name(), filepath.Base(project.CmdPath()))
|
||||
|
||||
mainScript, err := executeTemplate(mainTemplate, data)
|
||||
if err != nil {
|
||||
er(err)
|
||||
}
|
||||
|
||||
err = writeStringToFile(filepath.Join(project.AbsPath(), "main.go"), mainScript)
|
||||
if err != nil {
|
||||
er(err)
|
||||
}
|
||||
}
|
||||
|
||||
func createRootCmdFile(project *Project) {
|
||||
template := `{{comment .copyright}}
|
||||
{{if .license}}{{comment .license}}{{end}}
|
||||
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
{{if .viper}}
|
||||
homedir "github.com/mitchellh/go-homedir"{{end}}
|
||||
"github.com/spf13/cobra"{{if .viper}}
|
||||
"github.com/spf13/viper"{{end}}
|
||||
){{if .viper}}
|
||||
|
||||
var cfgFile string{{end}}
|
||||
|
||||
// rootCmd represents the base command when called without any subcommands
|
||||
var rootCmd = &cobra.Command{
|
||||
Use: "{{.appName}}",
|
||||
Short: "A brief description of your application",
|
||||
Long: ` + "`" + `A longer description that spans multiple lines and likely contains
|
||||
examples and usage of using your application. For example:
|
||||
|
||||
Cobra is a CLI library for Go that empowers applications.
|
||||
This application is a tool to generate the needed files
|
||||
to quickly create a Cobra application.` + "`" + `,
|
||||
// Uncomment the following line if your bare application
|
||||
// has an action associated with it:
|
||||
// Run: func(cmd *cobra.Command, args []string) { },
|
||||
}
|
||||
|
||||
// Execute adds all child commands to the root command and sets flags appropriately.
|
||||
// This is called by main.main(). It only needs to happen once to the rootCmd.
|
||||
func Execute() {
|
||||
if err := rootCmd.Execute(); err != nil {
|
||||
fmt.Println(err)
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
|
||||
func init() { {{- if .viper}}
|
||||
cobra.OnInitialize(initConfig)
|
||||
{{end}}
|
||||
// Here you will define your flags and configuration settings.
|
||||
// Cobra supports persistent flags, which, if defined here,
|
||||
// will be global for your application.{{ if .viper }}
|
||||
rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.{{ .appName }}.yaml)"){{ else }}
|
||||
// rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.{{ .appName }}.yaml)"){{ end }}
|
||||
|
||||
// Cobra also supports local flags, which will only run
|
||||
// when this action is called directly.
|
||||
rootCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
|
||||
}{{ if .viper }}
|
||||
|
||||
// initConfig reads in config file and ENV variables if set.
|
||||
func initConfig() {
|
||||
if cfgFile != "" {
|
||||
// Use config file from the flag.
|
||||
viper.SetConfigFile(cfgFile)
|
||||
} else {
|
||||
// Find home directory.
|
||||
home, err := homedir.Dir()
|
||||
if err != nil {
|
||||
fmt.Println(err)
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
// Search config in home directory with name ".{{ .appName }}" (without extension).
|
||||
viper.AddConfigPath(home)
|
||||
viper.SetConfigName(".{{ .appName }}")
|
||||
}
|
||||
|
||||
viper.AutomaticEnv() // read in environment variables that match
|
||||
|
||||
// If a config file is found, read it in.
|
||||
if err := viper.ReadInConfig(); err == nil {
|
||||
fmt.Println("Using config file:", viper.ConfigFileUsed())
|
||||
}
|
||||
}{{ end }}
|
||||
`
|
||||
|
||||
data := make(map[string]interface{})
|
||||
data["copyright"] = copyrightLine()
|
||||
data["viper"] = viper.GetBool("useViper")
|
||||
data["license"] = project.License().Header
|
||||
data["appName"] = path.Base(project.Name())
|
||||
|
||||
rootCmdScript, err := executeTemplate(template, data)
|
||||
if err != nil {
|
||||
er(err)
|
||||
}
|
||||
|
||||
err = writeStringToFile(filepath.Join(project.CmdPath(), "root.go"), rootCmdScript)
|
||||
if err != nil {
|
||||
er(err)
|
||||
}
|
||||
|
||||
}
|
||||
83
vendor/github.com/spf13/cobra/cobra/cmd/init_test.go
сгенерированный
поставляемый
83
vendor/github.com/spf13/cobra/cobra/cmd/init_test.go
сгенерированный
поставляемый
@@ -1,83 +0,0 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"io/ioutil"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"github.com/spf13/viper"
|
||||
)
|
||||
|
||||
// TestGoldenInitCmd initializes the project "github.com/spf13/testproject"
|
||||
// in GOPATH and compares the content of files in initialized project with
|
||||
// appropriate golden files ("testdata/*.golden").
|
||||
// Use -update to update existing golden files.
|
||||
func TestGoldenInitCmd(t *testing.T) {
|
||||
projectName := "github.com/spf13/testproject"
|
||||
project := NewProject(projectName)
|
||||
defer os.RemoveAll(project.AbsPath())
|
||||
|
||||
viper.Set("author", "NAME HERE <EMAIL ADDRESS>")
|
||||
viper.Set("license", "apache")
|
||||
viper.Set("year", 2017)
|
||||
defer viper.Set("author", nil)
|
||||
defer viper.Set("license", nil)
|
||||
defer viper.Set("year", nil)
|
||||
|
||||
os.Args = []string{"cobra", "init", projectName}
|
||||
if err := rootCmd.Execute(); err != nil {
|
||||
t.Fatal("Error by execution:", err)
|
||||
}
|
||||
|
||||
expectedFiles := []string{".", "cmd", "LICENSE", "main.go", "cmd/root.go"}
|
||||
gotFiles := []string{}
|
||||
|
||||
// Check project file hierarchy and compare the content of every single file
|
||||
// with appropriate golden file.
|
||||
err := filepath.Walk(project.AbsPath(), func(path string, info os.FileInfo, err error) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Make path relative to project.AbsPath().
|
||||
// E.g. path = "/home/user/go/src/github.com/spf13/testproject/cmd/root.go"
|
||||
// then it returns just "cmd/root.go".
|
||||
relPath, err := filepath.Rel(project.AbsPath(), path)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
relPath = filepath.ToSlash(relPath)
|
||||
gotFiles = append(gotFiles, relPath)
|
||||
goldenPath := filepath.Join("testdata", filepath.Base(path)+".golden")
|
||||
|
||||
switch relPath {
|
||||
// Known directories.
|
||||
case ".", "cmd":
|
||||
return nil
|
||||
// Known files.
|
||||
case "LICENSE", "main.go", "cmd/root.go":
|
||||
if *update {
|
||||
got, err := ioutil.ReadFile(path)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := ioutil.WriteFile(goldenPath, got, 0644); err != nil {
|
||||
t.Fatal("Error while updating file:", err)
|
||||
}
|
||||
}
|
||||
return compareFiles(path, goldenPath)
|
||||
}
|
||||
// Unknown file.
|
||||
return errors.New("unknown file: " + path)
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// Check if some files lack.
|
||||
if err := checkLackFiles(expectedFiles, gotFiles); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
200
vendor/github.com/spf13/cobra/cobra/cmd/project.go
сгенерированный
поставляемый
200
vendor/github.com/spf13/cobra/cobra/cmd/project.go
сгенерированный
поставляемый
@@ -1,200 +0,0 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// Project contains name, license and paths to projects.
|
||||
type Project struct {
|
||||
absPath string
|
||||
cmdPath string
|
||||
srcPath string
|
||||
license License
|
||||
name string
|
||||
}
|
||||
|
||||
// NewProject returns Project with specified project name.
|
||||
func NewProject(projectName string) *Project {
|
||||
if projectName == "" {
|
||||
er("can't create project with blank name")
|
||||
}
|
||||
|
||||
p := new(Project)
|
||||
p.name = projectName
|
||||
|
||||
// 1. Find already created protect.
|
||||
p.absPath = findPackage(projectName)
|
||||
|
||||
// 2. If there are no created project with this path, and user is in GOPATH,
|
||||
// then use GOPATH/src/projectName.
|
||||
if p.absPath == "" {
|
||||
wd, err := os.Getwd()
|
||||
if err != nil {
|
||||
er(err)
|
||||
}
|
||||
for _, srcPath := range srcPaths {
|
||||
goPath := filepath.Dir(srcPath)
|
||||
if filepathHasPrefix(wd, goPath) {
|
||||
p.absPath = filepath.Join(srcPath, projectName)
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 3. If user is not in GOPATH, then use (first GOPATH)/src/projectName.
|
||||
if p.absPath == "" {
|
||||
p.absPath = filepath.Join(srcPaths[0], projectName)
|
||||
}
|
||||
|
||||
return p
|
||||
}
|
||||
|
||||
// findPackage returns full path to existing go package in GOPATHs.
|
||||
func findPackage(packageName string) string {
|
||||
if packageName == "" {
|
||||
return ""
|
||||
}
|
||||
|
||||
for _, srcPath := range srcPaths {
|
||||
packagePath := filepath.Join(srcPath, packageName)
|
||||
if exists(packagePath) {
|
||||
return packagePath
|
||||
}
|
||||
}
|
||||
|
||||
return ""
|
||||
}
|
||||
|
||||
// NewProjectFromPath returns Project with specified absolute path to
|
||||
// package.
|
||||
func NewProjectFromPath(absPath string) *Project {
|
||||
if absPath == "" {
|
||||
er("can't create project: absPath can't be blank")
|
||||
}
|
||||
if !filepath.IsAbs(absPath) {
|
||||
er("can't create project: absPath is not absolute")
|
||||
}
|
||||
|
||||
// If absPath is symlink, use its destination.
|
||||
fi, err := os.Lstat(absPath)
|
||||
if err != nil {
|
||||
er("can't read path info: " + err.Error())
|
||||
}
|
||||
if fi.Mode()&os.ModeSymlink != 0 {
|
||||
path, err := os.Readlink(absPath)
|
||||
if err != nil {
|
||||
er("can't read the destination of symlink: " + err.Error())
|
||||
}
|
||||
absPath = path
|
||||
}
|
||||
|
||||
p := new(Project)
|
||||
p.absPath = strings.TrimSuffix(absPath, findCmdDir(absPath))
|
||||
p.name = filepath.ToSlash(trimSrcPath(p.absPath, p.SrcPath()))
|
||||
return p
|
||||
}
|
||||
|
||||
// trimSrcPath trims at the beginning of absPath the srcPath.
|
||||
func trimSrcPath(absPath, srcPath string) string {
|
||||
relPath, err := filepath.Rel(srcPath, absPath)
|
||||
if err != nil {
|
||||
er(err)
|
||||
}
|
||||
return relPath
|
||||
}
|
||||
|
||||
// License returns the License object of project.
|
||||
func (p *Project) License() License {
|
||||
if p.license.Text == "" && p.license.Name != "None" {
|
||||
p.license = getLicense()
|
||||
}
|
||||
return p.license
|
||||
}
|
||||
|
||||
// Name returns the name of project, e.g. "github.com/spf13/cobra"
|
||||
func (p Project) Name() string {
|
||||
return p.name
|
||||
}
|
||||
|
||||
// CmdPath returns absolute path to directory, where all commands are located.
|
||||
func (p *Project) CmdPath() string {
|
||||
if p.absPath == "" {
|
||||
return ""
|
||||
}
|
||||
if p.cmdPath == "" {
|
||||
p.cmdPath = filepath.Join(p.absPath, findCmdDir(p.absPath))
|
||||
}
|
||||
return p.cmdPath
|
||||
}
|
||||
|
||||
// findCmdDir checks if base of absPath is cmd dir and returns it or
|
||||
// looks for existing cmd dir in absPath.
|
||||
func findCmdDir(absPath string) string {
|
||||
if !exists(absPath) || isEmpty(absPath) {
|
||||
return "cmd"
|
||||
}
|
||||
|
||||
if isCmdDir(absPath) {
|
||||
return filepath.Base(absPath)
|
||||
}
|
||||
|
||||
files, _ := filepath.Glob(filepath.Join(absPath, "c*"))
|
||||
for _, file := range files {
|
||||
if isCmdDir(file) {
|
||||
return filepath.Base(file)
|
||||
}
|
||||
}
|
||||
|
||||
return "cmd"
|
||||
}
|
||||
|
||||
// isCmdDir checks if base of name is one of cmdDir.
|
||||
func isCmdDir(name string) bool {
|
||||
name = filepath.Base(name)
|
||||
for _, cmdDir := range []string{"cmd", "cmds", "command", "commands"} {
|
||||
if name == cmdDir {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// AbsPath returns absolute path of project.
|
||||
func (p Project) AbsPath() string {
|
||||
return p.absPath
|
||||
}
|
||||
|
||||
// SrcPath returns absolute path to $GOPATH/src where project is located.
|
||||
func (p *Project) SrcPath() string {
|
||||
if p.srcPath != "" {
|
||||
return p.srcPath
|
||||
}
|
||||
if p.absPath == "" {
|
||||
p.srcPath = srcPaths[0]
|
||||
return p.srcPath
|
||||
}
|
||||
|
||||
for _, srcPath := range srcPaths {
|
||||
if filepathHasPrefix(p.absPath, srcPath) {
|
||||
p.srcPath = srcPath
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
return p.srcPath
|
||||
}
|
||||
|
||||
func filepathHasPrefix(path string, prefix string) bool {
|
||||
if len(path) <= len(prefix) {
|
||||
return false
|
||||
}
|
||||
if runtime.GOOS == "windows" {
|
||||
// Paths in windows are case-insensitive.
|
||||
return strings.EqualFold(path[0:len(prefix)], prefix)
|
||||
}
|
||||
return path[0:len(prefix)] == prefix
|
||||
|
||||
}
|
||||
24
vendor/github.com/spf13/cobra/cobra/cmd/project_test.go
сгенерированный
поставляемый
24
vendor/github.com/spf13/cobra/cobra/cmd/project_test.go
сгенерированный
поставляемый
@@ -1,24 +0,0 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestFindExistingPackage(t *testing.T) {
|
||||
path := findPackage("github.com/spf13/cobra")
|
||||
if path == "" {
|
||||
t.Fatal("findPackage didn't find the existing package")
|
||||
}
|
||||
if !hasGoPathPrefix(path) {
|
||||
t.Fatalf("%q is not in GOPATH, but must be", path)
|
||||
}
|
||||
}
|
||||
|
||||
func hasGoPathPrefix(path string) bool {
|
||||
for _, srcPath := range srcPaths {
|
||||
if filepathHasPrefix(path, srcPath) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
79
vendor/github.com/spf13/cobra/cobra/cmd/root.go
сгенерированный
поставляемый
79
vendor/github.com/spf13/cobra/cobra/cmd/root.go
сгенерированный
поставляемый
@@ -1,79 +0,0 @@
|
||||
// Copyright © 2015 Steve Francia <spf@spf13.com>.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
homedir "github.com/mitchellh/go-homedir"
|
||||
"github.com/spf13/cobra"
|
||||
"github.com/spf13/viper"
|
||||
)
|
||||
|
||||
var (
|
||||
// Used for flags.
|
||||
cfgFile, userLicense string
|
||||
|
||||
rootCmd = &cobra.Command{
|
||||
Use: "cobra",
|
||||
Short: "A generator for Cobra based Applications",
|
||||
Long: `Cobra is a CLI library for Go that empowers applications.
|
||||
This application is a tool to generate the needed files
|
||||
to quickly create a Cobra application.`,
|
||||
}
|
||||
)
|
||||
|
||||
// Execute executes the root command.
|
||||
func Execute() {
|
||||
rootCmd.Execute()
|
||||
}
|
||||
|
||||
func init() {
|
||||
cobra.OnInitialize(initConfig)
|
||||
|
||||
rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.cobra.yaml)")
|
||||
rootCmd.PersistentFlags().StringP("author", "a", "YOUR NAME", "author name for copyright attribution")
|
||||
rootCmd.PersistentFlags().StringVarP(&userLicense, "license", "l", "", "name of license for the project")
|
||||
rootCmd.PersistentFlags().Bool("viper", true, "use Viper for configuration")
|
||||
viper.BindPFlag("author", rootCmd.PersistentFlags().Lookup("author"))
|
||||
viper.BindPFlag("useViper", rootCmd.PersistentFlags().Lookup("viper"))
|
||||
viper.SetDefault("author", "NAME HERE <EMAIL ADDRESS>")
|
||||
viper.SetDefault("license", "apache")
|
||||
|
||||
rootCmd.AddCommand(addCmd)
|
||||
rootCmd.AddCommand(initCmd)
|
||||
}
|
||||
|
||||
func initConfig() {
|
||||
if cfgFile != "" {
|
||||
// Use config file from the flag.
|
||||
viper.SetConfigFile(cfgFile)
|
||||
} else {
|
||||
// Find home directory.
|
||||
home, err := homedir.Dir()
|
||||
if err != nil {
|
||||
er(err)
|
||||
}
|
||||
|
||||
// Search config in home directory with name ".cobra" (without extension).
|
||||
viper.AddConfigPath(home)
|
||||
viper.SetConfigName(".cobra")
|
||||
}
|
||||
|
||||
viper.AutomaticEnv()
|
||||
|
||||
if err := viper.ReadInConfig(); err == nil {
|
||||
fmt.Println("Using config file:", viper.ConfigFileUsed())
|
||||
}
|
||||
}
|
||||
21
vendor/github.com/spf13/cobra/cobra/cmd/testdata/main.go.golden
сгенерированный
поставляемый
21
vendor/github.com/spf13/cobra/cobra/cmd/testdata/main.go.golden
сгенерированный
поставляемый
@@ -1,21 +0,0 @@
|
||||
// Copyright © 2017 NAME HERE <EMAIL ADDRESS>
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package main
|
||||
|
||||
import "github.com/spf13/testproject/cmd"
|
||||
|
||||
func main() {
|
||||
cmd.Execute()
|
||||
}
|
||||
89
vendor/github.com/spf13/cobra/cobra/cmd/testdata/root.go.golden
сгенерированный
поставляемый
89
vendor/github.com/spf13/cobra/cobra/cmd/testdata/root.go.golden
сгенерированный
поставляемый
@@ -1,89 +0,0 @@
|
||||
// Copyright © 2017 NAME HERE <EMAIL ADDRESS>
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
|
||||
homedir "github.com/mitchellh/go-homedir"
|
||||
"github.com/spf13/cobra"
|
||||
"github.com/spf13/viper"
|
||||
)
|
||||
|
||||
var cfgFile string
|
||||
|
||||
// rootCmd represents the base command when called without any subcommands
|
||||
var rootCmd = &cobra.Command{
|
||||
Use: "testproject",
|
||||
Short: "A brief description of your application",
|
||||
Long: `A longer description that spans multiple lines and likely contains
|
||||
examples and usage of using your application. For example:
|
||||
|
||||
Cobra is a CLI library for Go that empowers applications.
|
||||
This application is a tool to generate the needed files
|
||||
to quickly create a Cobra application.`,
|
||||
// Uncomment the following line if your bare application
|
||||
// has an action associated with it:
|
||||
// Run: func(cmd *cobra.Command, args []string) { },
|
||||
}
|
||||
|
||||
// Execute adds all child commands to the root command and sets flags appropriately.
|
||||
// This is called by main.main(). It only needs to happen once to the rootCmd.
|
||||
func Execute() {
|
||||
if err := rootCmd.Execute(); err != nil {
|
||||
fmt.Println(err)
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
|
||||
func init() {
|
||||
cobra.OnInitialize(initConfig)
|
||||
|
||||
// Here you will define your flags and configuration settings.
|
||||
// Cobra supports persistent flags, which, if defined here,
|
||||
// will be global for your application.
|
||||
rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.testproject.yaml)")
|
||||
|
||||
// Cobra also supports local flags, which will only run
|
||||
// when this action is called directly.
|
||||
rootCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
|
||||
}
|
||||
|
||||
// initConfig reads in config file and ENV variables if set.
|
||||
func initConfig() {
|
||||
if cfgFile != "" {
|
||||
// Use config file from the flag.
|
||||
viper.SetConfigFile(cfgFile)
|
||||
} else {
|
||||
// Find home directory.
|
||||
home, err := homedir.Dir()
|
||||
if err != nil {
|
||||
fmt.Println(err)
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
// Search config in home directory with name ".testproject" (without extension).
|
||||
viper.AddConfigPath(home)
|
||||
viper.SetConfigName(".testproject")
|
||||
}
|
||||
|
||||
viper.AutomaticEnv() // read in environment variables that match
|
||||
|
||||
// If a config file is found, read it in.
|
||||
if err := viper.ReadInConfig(); err == nil {
|
||||
fmt.Println("Using config file:", viper.ConfigFileUsed())
|
||||
}
|
||||
}
|
||||
50
vendor/github.com/spf13/cobra/cobra/cmd/testdata/test.go.golden
сгенерированный
поставляемый
50
vendor/github.com/spf13/cobra/cobra/cmd/testdata/test.go.golden
сгенерированный
поставляемый
@@ -1,50 +0,0 @@
|
||||
// Copyright © 2017 NAME HERE <EMAIL ADDRESS>
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
// testCmd represents the test command
|
||||
var testCmd = &cobra.Command{
|
||||
Use: "test",
|
||||
Short: "A brief description of your command",
|
||||
Long: `A longer description that spans multiple lines and likely contains examples
|
||||
and usage of using your command. For example:
|
||||
|
||||
Cobra is a CLI library for Go that empowers applications.
|
||||
This application is a tool to generate the needed files
|
||||
to quickly create a Cobra application.`,
|
||||
Run: func(cmd *cobra.Command, args []string) {
|
||||
fmt.Println("test called")
|
||||
},
|
||||
}
|
||||
|
||||
func init() {
|
||||
rootCmd.AddCommand(testCmd)
|
||||
|
||||
// Here you will define your flags and configuration settings.
|
||||
|
||||
// Cobra supports Persistent Flags which will work for this command
|
||||
// and all subcommands, e.g.:
|
||||
// testCmd.PersistentFlags().String("foo", "", "A help for foo")
|
||||
|
||||
// Cobra supports local flags which will only run when this command
|
||||
// is called directly, e.g.:
|
||||
// testCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
|
||||
}
|
||||
22
vendor/github.com/spf13/cobra/cobra_test.go
сгенерированный
поставляемый
22
vendor/github.com/spf13/cobra/cobra_test.go
сгенерированный
поставляемый
@@ -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)
|
||||
}
|
||||
}
|
||||
3
vendor/github.com/spf13/cobra/command.go
сгенерированный
поставляемый
3
vendor/github.com/spf13/cobra/command.go
сгенерированный
поставляемый
@@ -475,6 +475,9 @@ Loop:
|
||||
s := args[0]
|
||||
args = args[1:]
|
||||
switch {
|
||||
case s == "--":
|
||||
// "--" terminates the flags
|
||||
break Loop
|
||||
case strings.HasPrefix(s, "--") && !strings.Contains(s, "=") && !hasNoOptDefVal(s[2:], flags):
|
||||
// If '--flag arg' then
|
||||
// delete arg from args.
|
||||
|
||||
1628
vendor/github.com/spf13/cobra/command_test.go
сгенерированный
поставляемый
1628
vendor/github.com/spf13/cobra/command_test.go
сгенерированный
поставляемый
Разница между файлами не показана из-за своего большого размера
Загрузить разницу
86
vendor/github.com/spf13/cobra/doc/cmd_test.go
сгенерированный
поставляемый
86
vendor/github.com/spf13/cobra/doc/cmd_test.go
сгенерированный
поставляемый
@@ -1,86 +0,0 @@
|
||||
package doc
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
func emptyRun(*cobra.Command, []string) {}
|
||||
|
||||
func init() {
|
||||
rootCmd.PersistentFlags().StringP("rootflag", "r", "two", "")
|
||||
rootCmd.PersistentFlags().StringP("strtwo", "t", "two", "help message for parent flag strtwo")
|
||||
|
||||
echoCmd.PersistentFlags().StringP("strone", "s", "one", "help message for flag strone")
|
||||
echoCmd.PersistentFlags().BoolP("persistentbool", "p", false, "help message for flag persistentbool")
|
||||
echoCmd.Flags().IntP("intone", "i", 123, "help message for flag intone")
|
||||
echoCmd.Flags().BoolP("boolone", "b", true, "help message for flag boolone")
|
||||
|
||||
timesCmd.PersistentFlags().StringP("strtwo", "t", "2", "help message for child flag strtwo")
|
||||
timesCmd.Flags().IntP("inttwo", "j", 234, "help message for flag inttwo")
|
||||
timesCmd.Flags().BoolP("booltwo", "c", false, "help message for flag booltwo")
|
||||
|
||||
printCmd.PersistentFlags().StringP("strthree", "s", "three", "help message for flag strthree")
|
||||
printCmd.Flags().IntP("intthree", "i", 345, "help message for flag intthree")
|
||||
printCmd.Flags().BoolP("boolthree", "b", true, "help message for flag boolthree")
|
||||
|
||||
echoCmd.AddCommand(timesCmd, echoSubCmd, deprecatedCmd)
|
||||
rootCmd.AddCommand(printCmd, echoCmd)
|
||||
}
|
||||
|
||||
var rootCmd = &cobra.Command{
|
||||
Use: "root",
|
||||
Short: "Root short description",
|
||||
Long: "Root long description",
|
||||
Run: emptyRun,
|
||||
}
|
||||
|
||||
var echoCmd = &cobra.Command{
|
||||
Use: "echo [string to echo]",
|
||||
Aliases: []string{"say"},
|
||||
Short: "Echo anything to the screen",
|
||||
Long: "an utterly useless command for testing",
|
||||
Example: "Just run cobra-test echo",
|
||||
}
|
||||
|
||||
var echoSubCmd = &cobra.Command{
|
||||
Use: "echosub [string to print]",
|
||||
Short: "second sub command for echo",
|
||||
Long: "an absolutely utterly useless command for testing gendocs!.",
|
||||
Run: emptyRun,
|
||||
}
|
||||
|
||||
var timesCmd = &cobra.Command{
|
||||
Use: "times [# times] [string to echo]",
|
||||
SuggestFor: []string{"counts"},
|
||||
Short: "Echo anything to the screen more times",
|
||||
Long: `a slightly useless command for testing.`,
|
||||
Run: emptyRun,
|
||||
}
|
||||
|
||||
var deprecatedCmd = &cobra.Command{
|
||||
Use: "deprecated [can't do anything here]",
|
||||
Short: "A command which is deprecated",
|
||||
Long: `an absolutely utterly useless command for testing deprecation!.`,
|
||||
Deprecated: "Please use echo instead",
|
||||
}
|
||||
|
||||
var printCmd = &cobra.Command{
|
||||
Use: "print [string to print]",
|
||||
Short: "Print anything to the screen",
|
||||
Long: `an absolutely utterly useless command for testing.`,
|
||||
}
|
||||
|
||||
func checkStringContains(t *testing.T, got, expected string) {
|
||||
if !strings.Contains(got, expected) {
|
||||
t.Errorf("Expected to contain: \n %v\nGot:\n %v\n", expected, got)
|
||||
}
|
||||
}
|
||||
|
||||
func checkStringOmits(t *testing.T, got, expected string) {
|
||||
if strings.Contains(got, expected) {
|
||||
t.Errorf("Expected to not contain: \n %v\nGot: %v", expected, got)
|
||||
}
|
||||
}
|
||||
236
vendor/github.com/spf13/cobra/doc/man_docs.go
сгенерированный
поставляемый
236
vendor/github.com/spf13/cobra/doc/man_docs.go
сгенерированный
поставляемый
@@ -1,236 +0,0 @@
|
||||
// Copyright 2015 Red Hat Inc. All rights reserved.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package doc
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/cpuguy83/go-md2man/md2man"
|
||||
"github.com/spf13/cobra"
|
||||
"github.com/spf13/pflag"
|
||||
)
|
||||
|
||||
// GenManTree will generate a man page for this command and all descendants
|
||||
// in the directory given. The header may be nil. This function may not work
|
||||
// correctly if your command names have `-` in them. If you have `cmd` with two
|
||||
// subcmds, `sub` and `sub-third`, and `sub` has a subcommand called `third`
|
||||
// it is undefined which help output will be in the file `cmd-sub-third.1`.
|
||||
func GenManTree(cmd *cobra.Command, header *GenManHeader, dir string) error {
|
||||
return GenManTreeFromOpts(cmd, GenManTreeOptions{
|
||||
Header: header,
|
||||
Path: dir,
|
||||
CommandSeparator: "-",
|
||||
})
|
||||
}
|
||||
|
||||
// GenManTreeFromOpts generates a man page for the command and all descendants.
|
||||
// The pages are written to the opts.Path directory.
|
||||
func GenManTreeFromOpts(cmd *cobra.Command, opts GenManTreeOptions) error {
|
||||
header := opts.Header
|
||||
if header == nil {
|
||||
header = &GenManHeader{}
|
||||
}
|
||||
for _, c := range cmd.Commands() {
|
||||
if !c.IsAvailableCommand() || c.IsAdditionalHelpTopicCommand() {
|
||||
continue
|
||||
}
|
||||
if err := GenManTreeFromOpts(c, opts); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
section := "1"
|
||||
if header.Section != "" {
|
||||
section = header.Section
|
||||
}
|
||||
|
||||
separator := "_"
|
||||
if opts.CommandSeparator != "" {
|
||||
separator = opts.CommandSeparator
|
||||
}
|
||||
basename := strings.Replace(cmd.CommandPath(), " ", separator, -1)
|
||||
filename := filepath.Join(opts.Path, basename+"."+section)
|
||||
f, err := os.Create(filename)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer f.Close()
|
||||
|
||||
headerCopy := *header
|
||||
return GenMan(cmd, &headerCopy, f)
|
||||
}
|
||||
|
||||
// GenManTreeOptions is the options for generating the man pages.
|
||||
// Used only in GenManTreeFromOpts.
|
||||
type GenManTreeOptions struct {
|
||||
Header *GenManHeader
|
||||
Path string
|
||||
CommandSeparator string
|
||||
}
|
||||
|
||||
// GenManHeader is a lot like the .TH header at the start of man pages. These
|
||||
// include the title, section, date, source, and manual. We will use the
|
||||
// current time if Date if unset and will use "Auto generated by spf13/cobra"
|
||||
// if the Source is unset.
|
||||
type GenManHeader struct {
|
||||
Title string
|
||||
Section string
|
||||
Date *time.Time
|
||||
date string
|
||||
Source string
|
||||
Manual string
|
||||
}
|
||||
|
||||
// GenMan will generate a man page for the given command and write it to
|
||||
// w. The header argument may be nil, however obviously w may not.
|
||||
func GenMan(cmd *cobra.Command, header *GenManHeader, w io.Writer) error {
|
||||
if header == nil {
|
||||
header = &GenManHeader{}
|
||||
}
|
||||
fillHeader(header, cmd.CommandPath())
|
||||
|
||||
b := genMan(cmd, header)
|
||||
_, err := w.Write(md2man.Render(b))
|
||||
return err
|
||||
}
|
||||
|
||||
func fillHeader(header *GenManHeader, name string) {
|
||||
if header.Title == "" {
|
||||
header.Title = strings.ToUpper(strings.Replace(name, " ", "\\-", -1))
|
||||
}
|
||||
if header.Section == "" {
|
||||
header.Section = "1"
|
||||
}
|
||||
if header.Date == nil {
|
||||
now := time.Now()
|
||||
header.Date = &now
|
||||
}
|
||||
header.date = (*header.Date).Format("Jan 2006")
|
||||
if header.Source == "" {
|
||||
header.Source = "Auto generated by spf13/cobra"
|
||||
}
|
||||
}
|
||||
|
||||
func manPreamble(buf *bytes.Buffer, header *GenManHeader, cmd *cobra.Command, dashedName string) {
|
||||
description := cmd.Long
|
||||
if len(description) == 0 {
|
||||
description = cmd.Short
|
||||
}
|
||||
|
||||
buf.WriteString(fmt.Sprintf(`%% %s(%s)%s
|
||||
%% %s
|
||||
%% %s
|
||||
# NAME
|
||||
`, header.Title, header.Section, header.date, header.Source, header.Manual))
|
||||
buf.WriteString(fmt.Sprintf("%s \\- %s\n\n", dashedName, cmd.Short))
|
||||
buf.WriteString("# SYNOPSIS\n")
|
||||
buf.WriteString(fmt.Sprintf("**%s**\n\n", cmd.UseLine()))
|
||||
buf.WriteString("# DESCRIPTION\n")
|
||||
buf.WriteString(description + "\n\n")
|
||||
}
|
||||
|
||||
func manPrintFlags(buf *bytes.Buffer, flags *pflag.FlagSet) {
|
||||
flags.VisitAll(func(flag *pflag.Flag) {
|
||||
if len(flag.Deprecated) > 0 || flag.Hidden {
|
||||
return
|
||||
}
|
||||
format := ""
|
||||
if len(flag.Shorthand) > 0 && len(flag.ShorthandDeprecated) == 0 {
|
||||
format = fmt.Sprintf("**-%s**, **--%s**", flag.Shorthand, flag.Name)
|
||||
} else {
|
||||
format = fmt.Sprintf("**--%s**", flag.Name)
|
||||
}
|
||||
if len(flag.NoOptDefVal) > 0 {
|
||||
format += "["
|
||||
}
|
||||
if flag.Value.Type() == "string" {
|
||||
// put quotes on the value
|
||||
format += "=%q"
|
||||
} else {
|
||||
format += "=%s"
|
||||
}
|
||||
if len(flag.NoOptDefVal) > 0 {
|
||||
format += "]"
|
||||
}
|
||||
format += "\n\t%s\n\n"
|
||||
buf.WriteString(fmt.Sprintf(format, flag.DefValue, flag.Usage))
|
||||
})
|
||||
}
|
||||
|
||||
func manPrintOptions(buf *bytes.Buffer, command *cobra.Command) {
|
||||
flags := command.NonInheritedFlags()
|
||||
if flags.HasFlags() {
|
||||
buf.WriteString("# OPTIONS\n")
|
||||
manPrintFlags(buf, flags)
|
||||
buf.WriteString("\n")
|
||||
}
|
||||
flags = command.InheritedFlags()
|
||||
if flags.HasFlags() {
|
||||
buf.WriteString("# OPTIONS INHERITED FROM PARENT COMMANDS\n")
|
||||
manPrintFlags(buf, flags)
|
||||
buf.WriteString("\n")
|
||||
}
|
||||
}
|
||||
|
||||
func genMan(cmd *cobra.Command, header *GenManHeader) []byte {
|
||||
cmd.InitDefaultHelpCmd()
|
||||
cmd.InitDefaultHelpFlag()
|
||||
|
||||
// something like `rootcmd-subcmd1-subcmd2`
|
||||
dashCommandName := strings.Replace(cmd.CommandPath(), " ", "-", -1)
|
||||
|
||||
buf := new(bytes.Buffer)
|
||||
|
||||
manPreamble(buf, header, cmd, dashCommandName)
|
||||
manPrintOptions(buf, cmd)
|
||||
if len(cmd.Example) > 0 {
|
||||
buf.WriteString("# EXAMPLE\n")
|
||||
buf.WriteString(fmt.Sprintf("```\n%s\n```\n", cmd.Example))
|
||||
}
|
||||
if hasSeeAlso(cmd) {
|
||||
buf.WriteString("# SEE ALSO\n")
|
||||
seealsos := make([]string, 0)
|
||||
if cmd.HasParent() {
|
||||
parentPath := cmd.Parent().CommandPath()
|
||||
dashParentPath := strings.Replace(parentPath, " ", "-", -1)
|
||||
seealso := fmt.Sprintf("**%s(%s)**", dashParentPath, header.Section)
|
||||
seealsos = append(seealsos, seealso)
|
||||
cmd.VisitParents(func(c *cobra.Command) {
|
||||
if c.DisableAutoGenTag {
|
||||
cmd.DisableAutoGenTag = c.DisableAutoGenTag
|
||||
}
|
||||
})
|
||||
}
|
||||
children := cmd.Commands()
|
||||
sort.Sort(byName(children))
|
||||
for _, c := range children {
|
||||
if !c.IsAvailableCommand() || c.IsAdditionalHelpTopicCommand() {
|
||||
continue
|
||||
}
|
||||
seealso := fmt.Sprintf("**%s-%s(%s)**", dashCommandName, c.Name(), header.Section)
|
||||
seealsos = append(seealsos, seealso)
|
||||
}
|
||||
buf.WriteString(strings.Join(seealsos, ", ") + "\n")
|
||||
}
|
||||
if !cmd.DisableAutoGenTag {
|
||||
buf.WriteString(fmt.Sprintf("# HISTORY\n%s Auto generated by spf13/cobra\n", header.Date.Format("2-Jan-2006")))
|
||||
}
|
||||
return buf.Bytes()
|
||||
}
|
||||
31
vendor/github.com/spf13/cobra/doc/man_docs.md
сгенерированный
поставляемый
31
vendor/github.com/spf13/cobra/doc/man_docs.md
сгенерированный
поставляемый
@@ -1,31 +0,0 @@
|
||||
# Generating Man Pages For Your Own cobra.Command
|
||||
|
||||
Generating man pages from a cobra command is incredibly easy. An example is as follows:
|
||||
|
||||
```go
|
||||
package main
|
||||
|
||||
import (
|
||||
"log"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
"github.com/spf13/cobra/doc"
|
||||
)
|
||||
|
||||
func main() {
|
||||
cmd := &cobra.Command{
|
||||
Use: "test",
|
||||
Short: "my test program",
|
||||
}
|
||||
header := &doc.GenManHeader{
|
||||
Title: "MINE",
|
||||
Section: "3",
|
||||
}
|
||||
err := doc.GenManTree(cmd, header, "/tmp")
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
That will get you a man page `/tmp/test.3`
|
||||
177
vendor/github.com/spf13/cobra/doc/man_docs_test.go
сгенерированный
поставляемый
177
vendor/github.com/spf13/cobra/doc/man_docs_test.go
сгенерированный
поставляемый
@@ -1,177 +0,0 @@
|
||||
package doc
|
||||
|
||||
import (
|
||||
"bufio"
|
||||
"bytes"
|
||||
"fmt"
|
||||
"io/ioutil"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
func translate(in string) string {
|
||||
return strings.Replace(in, "-", "\\-", -1)
|
||||
}
|
||||
|
||||
func TestGenManDoc(t *testing.T) {
|
||||
header := &GenManHeader{
|
||||
Title: "Project",
|
||||
Section: "2",
|
||||
}
|
||||
|
||||
// We generate on a subcommand so we have both subcommands and parents
|
||||
buf := new(bytes.Buffer)
|
||||
if err := GenMan(echoCmd, header, buf); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
output := buf.String()
|
||||
|
||||
// Make sure parent has - in CommandPath() in SEE ALSO:
|
||||
parentPath := echoCmd.Parent().CommandPath()
|
||||
dashParentPath := strings.Replace(parentPath, " ", "-", -1)
|
||||
expected := translate(dashParentPath)
|
||||
expected = expected + "(" + header.Section + ")"
|
||||
checkStringContains(t, output, expected)
|
||||
|
||||
checkStringContains(t, output, translate(echoCmd.Name()))
|
||||
checkStringContains(t, output, translate(echoCmd.Name()))
|
||||
checkStringContains(t, output, "boolone")
|
||||
checkStringContains(t, output, "rootflag")
|
||||
checkStringContains(t, output, translate(rootCmd.Name()))
|
||||
checkStringContains(t, output, translate(echoSubCmd.Name()))
|
||||
checkStringOmits(t, output, translate(deprecatedCmd.Name()))
|
||||
checkStringContains(t, output, translate("Auto generated"))
|
||||
}
|
||||
|
||||
func TestGenManNoGenTag(t *testing.T) {
|
||||
echoCmd.DisableAutoGenTag = true
|
||||
defer func() { echoCmd.DisableAutoGenTag = false }()
|
||||
|
||||
header := &GenManHeader{
|
||||
Title: "Project",
|
||||
Section: "2",
|
||||
}
|
||||
|
||||
// We generate on a subcommand so we have both subcommands and parents
|
||||
buf := new(bytes.Buffer)
|
||||
if err := GenMan(echoCmd, header, buf); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
output := buf.String()
|
||||
|
||||
unexpected := translate("#HISTORY")
|
||||
checkStringOmits(t, output, unexpected)
|
||||
}
|
||||
|
||||
func TestGenManSeeAlso(t *testing.T) {
|
||||
rootCmd := &cobra.Command{Use: "root", Run: emptyRun}
|
||||
aCmd := &cobra.Command{Use: "aaa", Run: emptyRun, Hidden: true} // #229
|
||||
bCmd := &cobra.Command{Use: "bbb", Run: emptyRun}
|
||||
cCmd := &cobra.Command{Use: "ccc", Run: emptyRun}
|
||||
rootCmd.AddCommand(aCmd, bCmd, cCmd)
|
||||
|
||||
buf := new(bytes.Buffer)
|
||||
header := &GenManHeader{}
|
||||
if err := GenMan(rootCmd, header, buf); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
scanner := bufio.NewScanner(buf)
|
||||
|
||||
if err := assertLineFound(scanner, ".SH SEE ALSO"); err != nil {
|
||||
t.Fatalf("Couldn't find SEE ALSO section header: %v", err)
|
||||
}
|
||||
if err := assertNextLineEquals(scanner, ".PP"); err != nil {
|
||||
t.Fatalf("First line after SEE ALSO wasn't break-indent: %v", err)
|
||||
}
|
||||
if err := assertNextLineEquals(scanner, `\fBroot\-bbb(1)\fP, \fBroot\-ccc(1)\fP`); err != nil {
|
||||
t.Fatalf("Second line after SEE ALSO wasn't correct: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestManPrintFlagsHidesShortDeperecated(t *testing.T) {
|
||||
c := &cobra.Command{}
|
||||
c.Flags().StringP("foo", "f", "default", "Foo flag")
|
||||
c.Flags().MarkShorthandDeprecated("foo", "don't use it no more")
|
||||
|
||||
buf := new(bytes.Buffer)
|
||||
manPrintFlags(buf, c.Flags())
|
||||
|
||||
got := buf.String()
|
||||
expected := "**--foo**=\"default\"\n\tFoo flag\n\n"
|
||||
if got != expected {
|
||||
t.Errorf("Expected %v, got %v", expected, got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGenManTree(t *testing.T) {
|
||||
c := &cobra.Command{Use: "do [OPTIONS] arg1 arg2"}
|
||||
header := &GenManHeader{Section: "2"}
|
||||
tmpdir, err := ioutil.TempDir("", "test-gen-man-tree")
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to create tmpdir: %s", err.Error())
|
||||
}
|
||||
defer os.RemoveAll(tmpdir)
|
||||
|
||||
if err := GenManTree(c, header, tmpdir); err != nil {
|
||||
t.Fatalf("GenManTree failed: %s", err.Error())
|
||||
}
|
||||
|
||||
if _, err := os.Stat(filepath.Join(tmpdir, "do.2")); err != nil {
|
||||
t.Fatalf("Expected file 'do.2' to exist")
|
||||
}
|
||||
|
||||
if header.Title != "" {
|
||||
t.Fatalf("Expected header.Title to be unmodified")
|
||||
}
|
||||
}
|
||||
|
||||
func assertLineFound(scanner *bufio.Scanner, expectedLine string) error {
|
||||
for scanner.Scan() {
|
||||
line := scanner.Text()
|
||||
if line == expectedLine {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
if err := scanner.Err(); err != nil {
|
||||
return fmt.Errorf("scan failed: %s", err)
|
||||
}
|
||||
|
||||
return fmt.Errorf("hit EOF before finding %v", expectedLine)
|
||||
}
|
||||
|
||||
func assertNextLineEquals(scanner *bufio.Scanner, expectedLine string) error {
|
||||
if scanner.Scan() {
|
||||
line := scanner.Text()
|
||||
if line == expectedLine {
|
||||
return nil
|
||||
}
|
||||
return fmt.Errorf("got %v, not %v", line, expectedLine)
|
||||
}
|
||||
|
||||
if err := scanner.Err(); err != nil {
|
||||
return fmt.Errorf("scan failed: %v", err)
|
||||
}
|
||||
|
||||
return fmt.Errorf("hit EOF before finding %v", expectedLine)
|
||||
}
|
||||
|
||||
func BenchmarkGenManToFile(b *testing.B) {
|
||||
file, err := ioutil.TempFile("", "")
|
||||
if err != nil {
|
||||
b.Fatal(err)
|
||||
}
|
||||
defer os.Remove(file.Name())
|
||||
defer file.Close()
|
||||
|
||||
b.ResetTimer()
|
||||
for i := 0; i < b.N; i++ {
|
||||
if err := GenMan(rootCmd, nil, file); err != nil {
|
||||
b.Fatal(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
35
vendor/github.com/spf13/cobra/doc/man_examples_test.go
сгенерированный
поставляемый
35
vendor/github.com/spf13/cobra/doc/man_examples_test.go
сгенерированный
поставляемый
@@ -1,35 +0,0 @@
|
||||
package doc_test
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
"github.com/spf13/cobra/doc"
|
||||
)
|
||||
|
||||
func ExampleGenManTree() {
|
||||
cmd := &cobra.Command{
|
||||
Use: "test",
|
||||
Short: "my test program",
|
||||
}
|
||||
header := &doc.GenManHeader{
|
||||
Title: "MINE",
|
||||
Section: "3",
|
||||
}
|
||||
doc.GenManTree(cmd, header, "/tmp")
|
||||
}
|
||||
|
||||
func ExampleGenMan() {
|
||||
cmd := &cobra.Command{
|
||||
Use: "test",
|
||||
Short: "my test program",
|
||||
}
|
||||
header := &doc.GenManHeader{
|
||||
Title: "MINE",
|
||||
Section: "3",
|
||||
}
|
||||
out := new(bytes.Buffer)
|
||||
doc.GenMan(cmd, header, out)
|
||||
fmt.Print(out.String())
|
||||
}
|
||||
159
vendor/github.com/spf13/cobra/doc/md_docs.go
сгенерированный
поставляемый
159
vendor/github.com/spf13/cobra/doc/md_docs.go
сгенерированный
поставляемый
@@ -1,159 +0,0 @@
|
||||
//Copyright 2015 Red Hat Inc. All rights reserved.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package doc
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
func printOptions(buf *bytes.Buffer, cmd *cobra.Command, name string) error {
|
||||
flags := cmd.NonInheritedFlags()
|
||||
flags.SetOutput(buf)
|
||||
if flags.HasFlags() {
|
||||
buf.WriteString("### Options\n\n```\n")
|
||||
flags.PrintDefaults()
|
||||
buf.WriteString("```\n\n")
|
||||
}
|
||||
|
||||
parentFlags := cmd.InheritedFlags()
|
||||
parentFlags.SetOutput(buf)
|
||||
if parentFlags.HasFlags() {
|
||||
buf.WriteString("### Options inherited from parent commands\n\n```\n")
|
||||
parentFlags.PrintDefaults()
|
||||
buf.WriteString("```\n\n")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// GenMarkdown creates markdown output.
|
||||
func GenMarkdown(cmd *cobra.Command, w io.Writer) error {
|
||||
return GenMarkdownCustom(cmd, w, func(s string) string { return s })
|
||||
}
|
||||
|
||||
// GenMarkdownCustom creates custom markdown output.
|
||||
func GenMarkdownCustom(cmd *cobra.Command, w io.Writer, linkHandler func(string) string) error {
|
||||
cmd.InitDefaultHelpCmd()
|
||||
cmd.InitDefaultHelpFlag()
|
||||
|
||||
buf := new(bytes.Buffer)
|
||||
name := cmd.CommandPath()
|
||||
|
||||
short := cmd.Short
|
||||
long := cmd.Long
|
||||
if len(long) == 0 {
|
||||
long = short
|
||||
}
|
||||
|
||||
buf.WriteString("## " + name + "\n\n")
|
||||
buf.WriteString(short + "\n\n")
|
||||
buf.WriteString("### Synopsis\n\n")
|
||||
buf.WriteString(long + "\n\n")
|
||||
|
||||
if cmd.Runnable() {
|
||||
buf.WriteString(fmt.Sprintf("```\n%s\n```\n\n", cmd.UseLine()))
|
||||
}
|
||||
|
||||
if len(cmd.Example) > 0 {
|
||||
buf.WriteString("### Examples\n\n")
|
||||
buf.WriteString(fmt.Sprintf("```\n%s\n```\n\n", cmd.Example))
|
||||
}
|
||||
|
||||
if err := printOptions(buf, cmd, name); err != nil {
|
||||
return err
|
||||
}
|
||||
if hasSeeAlso(cmd) {
|
||||
buf.WriteString("### SEE ALSO\n\n")
|
||||
if cmd.HasParent() {
|
||||
parent := cmd.Parent()
|
||||
pname := parent.CommandPath()
|
||||
link := pname + ".md"
|
||||
link = strings.Replace(link, " ", "_", -1)
|
||||
buf.WriteString(fmt.Sprintf("* [%s](%s)\t - %s\n", pname, linkHandler(link), parent.Short))
|
||||
cmd.VisitParents(func(c *cobra.Command) {
|
||||
if c.DisableAutoGenTag {
|
||||
cmd.DisableAutoGenTag = c.DisableAutoGenTag
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
children := cmd.Commands()
|
||||
sort.Sort(byName(children))
|
||||
|
||||
for _, child := range children {
|
||||
if !child.IsAvailableCommand() || child.IsAdditionalHelpTopicCommand() {
|
||||
continue
|
||||
}
|
||||
cname := name + " " + child.Name()
|
||||
link := cname + ".md"
|
||||
link = strings.Replace(link, " ", "_", -1)
|
||||
buf.WriteString(fmt.Sprintf("* [%s](%s)\t - %s\n", cname, linkHandler(link), child.Short))
|
||||
}
|
||||
buf.WriteString("\n")
|
||||
}
|
||||
if !cmd.DisableAutoGenTag {
|
||||
buf.WriteString("###### Auto generated by spf13/cobra on " + time.Now().Format("2-Jan-2006") + "\n")
|
||||
}
|
||||
_, err := buf.WriteTo(w)
|
||||
return err
|
||||
}
|
||||
|
||||
// GenMarkdownTree will generate a markdown page for this command and all
|
||||
// descendants in the directory given. The header may be nil.
|
||||
// This function may not work correctly if your command names have `-` in them.
|
||||
// If you have `cmd` with two subcmds, `sub` and `sub-third`,
|
||||
// and `sub` has a subcommand called `third`, it is undefined which
|
||||
// help output will be in the file `cmd-sub-third.1`.
|
||||
func GenMarkdownTree(cmd *cobra.Command, dir string) error {
|
||||
identity := func(s string) string { return s }
|
||||
emptyStr := func(s string) string { return "" }
|
||||
return GenMarkdownTreeCustom(cmd, dir, emptyStr, identity)
|
||||
}
|
||||
|
||||
// GenMarkdownTreeCustom is the the same as GenMarkdownTree, but
|
||||
// with custom filePrepender and linkHandler.
|
||||
func GenMarkdownTreeCustom(cmd *cobra.Command, dir string, filePrepender, linkHandler func(string) string) error {
|
||||
for _, c := range cmd.Commands() {
|
||||
if !c.IsAvailableCommand() || c.IsAdditionalHelpTopicCommand() {
|
||||
continue
|
||||
}
|
||||
if err := GenMarkdownTreeCustom(c, dir, filePrepender, linkHandler); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
basename := strings.Replace(cmd.CommandPath(), " ", "_", -1) + ".md"
|
||||
filename := filepath.Join(dir, basename)
|
||||
f, err := os.Create(filename)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer f.Close()
|
||||
|
||||
if _, err := io.WriteString(f, filePrepender(filename)); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := GenMarkdownCustom(cmd, f, linkHandler); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
115
vendor/github.com/spf13/cobra/doc/md_docs.md
сгенерированный
поставляемый
115
vendor/github.com/spf13/cobra/doc/md_docs.md
сгенерированный
поставляемый
@@ -1,115 +0,0 @@
|
||||
# Generating Markdown Docs For Your Own cobra.Command
|
||||
|
||||
Generating man pages from a cobra command is incredibly easy. An example is as follows:
|
||||
|
||||
```go
|
||||
package main
|
||||
|
||||
import (
|
||||
"log"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
"github.com/spf13/cobra/doc"
|
||||
)
|
||||
|
||||
func main() {
|
||||
cmd := &cobra.Command{
|
||||
Use: "test",
|
||||
Short: "my test program",
|
||||
}
|
||||
err := doc.GenMarkdownTree(cmd, "/tmp")
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
That will get you a Markdown document `/tmp/test.md`
|
||||
|
||||
## Generate markdown docs for the entire command tree
|
||||
|
||||
This program can actually generate docs for the kubectl command in the kubernetes project
|
||||
|
||||
```go
|
||||
package main
|
||||
|
||||
import (
|
||||
"log"
|
||||
"io/ioutil"
|
||||
"os"
|
||||
|
||||
"k8s.io/kubernetes/pkg/kubectl/cmd"
|
||||
cmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util"
|
||||
|
||||
"github.com/spf13/cobra/doc"
|
||||
)
|
||||
|
||||
func main() {
|
||||
kubectl := cmd.NewKubectlCommand(cmdutil.NewFactory(nil), os.Stdin, ioutil.Discard, ioutil.Discard)
|
||||
err := doc.GenMarkdownTree(kubectl, "./")
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
This will generate a whole series of files, one for each command in the tree, in the directory specified (in this case "./")
|
||||
|
||||
## Generate markdown docs for a single command
|
||||
|
||||
You may wish to have more control over the output, or only generate for a single command, instead of the entire command tree. If this is the case you may prefer to `GenMarkdown` instead of `GenMarkdownTree`
|
||||
|
||||
```go
|
||||
out := new(bytes.Buffer)
|
||||
err := doc.GenMarkdown(cmd, out)
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
```
|
||||
|
||||
This will write the markdown doc for ONLY "cmd" into the out, buffer.
|
||||
|
||||
## Customize the output
|
||||
|
||||
Both `GenMarkdown` and `GenMarkdownTree` have alternate versions with callbacks to get some control of the output:
|
||||
|
||||
```go
|
||||
func GenMarkdownTreeCustom(cmd *Command, dir string, filePrepender, linkHandler func(string) string) error {
|
||||
//...
|
||||
}
|
||||
```
|
||||
|
||||
```go
|
||||
func GenMarkdownCustom(cmd *Command, out *bytes.Buffer, linkHandler func(string) string) error {
|
||||
//...
|
||||
}
|
||||
```
|
||||
|
||||
The `filePrepender` will prepend the return value given the full filepath to the rendered Markdown file. A common use case is to add front matter to use the generated documentation with [Hugo](http://gohugo.io/):
|
||||
|
||||
```go
|
||||
const fmTemplate = `---
|
||||
date: %s
|
||||
title: "%s"
|
||||
slug: %s
|
||||
url: %s
|
||||
---
|
||||
`
|
||||
|
||||
filePrepender := func(filename string) string {
|
||||
now := time.Now().Format(time.RFC3339)
|
||||
name := filepath.Base(filename)
|
||||
base := strings.TrimSuffix(name, path.Ext(name))
|
||||
url := "/commands/" + strings.ToLower(base) + "/"
|
||||
return fmt.Sprintf(fmTemplate, now, strings.Replace(base, "_", " ", -1), base, url)
|
||||
}
|
||||
```
|
||||
|
||||
The `linkHandler` can be used to customize the rendered internal links to the commands, given a filename:
|
||||
|
||||
```go
|
||||
linkHandler := func(name string) string {
|
||||
base := strings.TrimSuffix(name, path.Ext(name))
|
||||
return "/commands/" + strings.ToLower(base) + "/"
|
||||
}
|
||||
```
|
||||
74
vendor/github.com/spf13/cobra/doc/md_docs_test.go
сгенерированный
поставляемый
74
vendor/github.com/spf13/cobra/doc/md_docs_test.go
сгенерированный
поставляемый
@@ -1,74 +0,0 @@
|
||||
package doc
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"io/ioutil"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
func TestGenMdDoc(t *testing.T) {
|
||||
// We generate on subcommand so we have both subcommands and parents.
|
||||
buf := new(bytes.Buffer)
|
||||
if err := GenMarkdown(echoCmd, buf); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
output := buf.String()
|
||||
|
||||
checkStringContains(t, output, echoCmd.Long)
|
||||
checkStringContains(t, output, echoCmd.Example)
|
||||
checkStringContains(t, output, "boolone")
|
||||
checkStringContains(t, output, "rootflag")
|
||||
checkStringContains(t, output, rootCmd.Short)
|
||||
checkStringContains(t, output, echoSubCmd.Short)
|
||||
checkStringOmits(t, output, deprecatedCmd.Short)
|
||||
}
|
||||
|
||||
func TestGenMdNoTag(t *testing.T) {
|
||||
rootCmd.DisableAutoGenTag = true
|
||||
defer func() { rootCmd.DisableAutoGenTag = false }()
|
||||
|
||||
buf := new(bytes.Buffer)
|
||||
if err := GenMarkdown(rootCmd, buf); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
output := buf.String()
|
||||
|
||||
checkStringOmits(t, output, "Auto generated")
|
||||
}
|
||||
|
||||
func TestGenMdTree(t *testing.T) {
|
||||
c := &cobra.Command{Use: "do [OPTIONS] arg1 arg2"}
|
||||
tmpdir, err := ioutil.TempDir("", "test-gen-md-tree")
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to create tmpdir: %v", err)
|
||||
}
|
||||
defer os.RemoveAll(tmpdir)
|
||||
|
||||
if err := GenMarkdownTree(c, tmpdir); err != nil {
|
||||
t.Fatalf("GenMarkdownTree failed: %v", err)
|
||||
}
|
||||
|
||||
if _, err := os.Stat(filepath.Join(tmpdir, "do.md")); err != nil {
|
||||
t.Fatalf("Expected file 'do.md' to exist")
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkGenMarkdownToFile(b *testing.B) {
|
||||
file, err := ioutil.TempFile("", "")
|
||||
if err != nil {
|
||||
b.Fatal(err)
|
||||
}
|
||||
defer os.Remove(file.Name())
|
||||
defer file.Close()
|
||||
|
||||
b.ResetTimer()
|
||||
for i := 0; i < b.N; i++ {
|
||||
if err := GenMarkdown(rootCmd, file); err != nil {
|
||||
b.Fatal(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
185
vendor/github.com/spf13/cobra/doc/rest_docs.go
сгенерированный
поставляемый
185
vendor/github.com/spf13/cobra/doc/rest_docs.go
сгенерированный
поставляемый
@@ -1,185 +0,0 @@
|
||||
//Copyright 2015 Red Hat Inc. All rights reserved.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package doc
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
func printOptionsReST(buf *bytes.Buffer, cmd *cobra.Command, name string) error {
|
||||
flags := cmd.NonInheritedFlags()
|
||||
flags.SetOutput(buf)
|
||||
if flags.HasFlags() {
|
||||
buf.WriteString("Options\n")
|
||||
buf.WriteString("~~~~~~~\n\n::\n\n")
|
||||
flags.PrintDefaults()
|
||||
buf.WriteString("\n")
|
||||
}
|
||||
|
||||
parentFlags := cmd.InheritedFlags()
|
||||
parentFlags.SetOutput(buf)
|
||||
if parentFlags.HasFlags() {
|
||||
buf.WriteString("Options inherited from parent commands\n")
|
||||
buf.WriteString("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n::\n\n")
|
||||
parentFlags.PrintDefaults()
|
||||
buf.WriteString("\n")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// linkHandler for default ReST hyperlink markup
|
||||
func defaultLinkHandler(name, ref string) string {
|
||||
return fmt.Sprintf("`%s <%s.rst>`_", name, ref)
|
||||
}
|
||||
|
||||
// GenReST creates reStructured Text output.
|
||||
func GenReST(cmd *cobra.Command, w io.Writer) error {
|
||||
return GenReSTCustom(cmd, w, defaultLinkHandler)
|
||||
}
|
||||
|
||||
// GenReSTCustom creates custom reStructured Text output.
|
||||
func GenReSTCustom(cmd *cobra.Command, w io.Writer, linkHandler func(string, string) string) error {
|
||||
cmd.InitDefaultHelpCmd()
|
||||
cmd.InitDefaultHelpFlag()
|
||||
|
||||
buf := new(bytes.Buffer)
|
||||
name := cmd.CommandPath()
|
||||
|
||||
short := cmd.Short
|
||||
long := cmd.Long
|
||||
if len(long) == 0 {
|
||||
long = short
|
||||
}
|
||||
ref := strings.Replace(name, " ", "_", -1)
|
||||
|
||||
buf.WriteString(".. _" + ref + ":\n\n")
|
||||
buf.WriteString(name + "\n")
|
||||
buf.WriteString(strings.Repeat("-", len(name)) + "\n\n")
|
||||
buf.WriteString(short + "\n\n")
|
||||
buf.WriteString("Synopsis\n")
|
||||
buf.WriteString("~~~~~~~~\n\n")
|
||||
buf.WriteString("\n" + long + "\n\n")
|
||||
|
||||
if cmd.Runnable() {
|
||||
buf.WriteString(fmt.Sprintf("::\n\n %s\n\n", cmd.UseLine()))
|
||||
}
|
||||
|
||||
if len(cmd.Example) > 0 {
|
||||
buf.WriteString("Examples\n")
|
||||
buf.WriteString("~~~~~~~~\n\n")
|
||||
buf.WriteString(fmt.Sprintf("::\n\n%s\n\n", indentString(cmd.Example, " ")))
|
||||
}
|
||||
|
||||
if err := printOptionsReST(buf, cmd, name); err != nil {
|
||||
return err
|
||||
}
|
||||
if hasSeeAlso(cmd) {
|
||||
buf.WriteString("SEE ALSO\n")
|
||||
buf.WriteString("~~~~~~~~\n\n")
|
||||
if cmd.HasParent() {
|
||||
parent := cmd.Parent()
|
||||
pname := parent.CommandPath()
|
||||
ref = strings.Replace(pname, " ", "_", -1)
|
||||
buf.WriteString(fmt.Sprintf("* %s \t - %s\n", linkHandler(pname, ref), parent.Short))
|
||||
cmd.VisitParents(func(c *cobra.Command) {
|
||||
if c.DisableAutoGenTag {
|
||||
cmd.DisableAutoGenTag = c.DisableAutoGenTag
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
children := cmd.Commands()
|
||||
sort.Sort(byName(children))
|
||||
|
||||
for _, child := range children {
|
||||
if !child.IsAvailableCommand() || child.IsAdditionalHelpTopicCommand() {
|
||||
continue
|
||||
}
|
||||
cname := name + " " + child.Name()
|
||||
ref = strings.Replace(cname, " ", "_", -1)
|
||||
buf.WriteString(fmt.Sprintf("* %s \t - %s\n", linkHandler(cname, ref), child.Short))
|
||||
}
|
||||
buf.WriteString("\n")
|
||||
}
|
||||
if !cmd.DisableAutoGenTag {
|
||||
buf.WriteString("*Auto generated by spf13/cobra on " + time.Now().Format("2-Jan-2006") + "*\n")
|
||||
}
|
||||
_, err := buf.WriteTo(w)
|
||||
return err
|
||||
}
|
||||
|
||||
// GenReSTTree will generate a ReST page for this command and all
|
||||
// descendants in the directory given.
|
||||
// This function may not work correctly if your command names have `-` in them.
|
||||
// If you have `cmd` with two subcmds, `sub` and `sub-third`,
|
||||
// and `sub` has a subcommand called `third`, it is undefined which
|
||||
// help output will be in the file `cmd-sub-third.1`.
|
||||
func GenReSTTree(cmd *cobra.Command, dir string) error {
|
||||
emptyStr := func(s string) string { return "" }
|
||||
return GenReSTTreeCustom(cmd, dir, emptyStr, defaultLinkHandler)
|
||||
}
|
||||
|
||||
// GenReSTTreeCustom is the the same as GenReSTTree, but
|
||||
// with custom filePrepender and linkHandler.
|
||||
func GenReSTTreeCustom(cmd *cobra.Command, dir string, filePrepender func(string) string, linkHandler func(string, string) string) error {
|
||||
for _, c := range cmd.Commands() {
|
||||
if !c.IsAvailableCommand() || c.IsAdditionalHelpTopicCommand() {
|
||||
continue
|
||||
}
|
||||
if err := GenReSTTreeCustom(c, dir, filePrepender, linkHandler); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
basename := strings.Replace(cmd.CommandPath(), " ", "_", -1) + ".rst"
|
||||
filename := filepath.Join(dir, basename)
|
||||
f, err := os.Create(filename)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer f.Close()
|
||||
|
||||
if _, err := io.WriteString(f, filePrepender(filename)); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := GenReSTCustom(cmd, f, linkHandler); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// adapted from: https://github.com/kr/text/blob/main/indent.go
|
||||
func indentString(s, p string) string {
|
||||
var res []byte
|
||||
b := []byte(s)
|
||||
prefix := []byte(p)
|
||||
bol := true
|
||||
for _, c := range b {
|
||||
if bol && c != '\n' {
|
||||
res = append(res, prefix...)
|
||||
}
|
||||
res = append(res, c)
|
||||
bol = c == '\n'
|
||||
}
|
||||
return string(res)
|
||||
}
|
||||
114
vendor/github.com/spf13/cobra/doc/rest_docs.md
сгенерированный
поставляемый
114
vendor/github.com/spf13/cobra/doc/rest_docs.md
сгенерированный
поставляемый
@@ -1,114 +0,0 @@
|
||||
# Generating ReStructured Text Docs For Your Own cobra.Command
|
||||
|
||||
Generating ReST pages from a cobra command is incredibly easy. An example is as follows:
|
||||
|
||||
```go
|
||||
package main
|
||||
|
||||
import (
|
||||
"log"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
"github.com/spf13/cobra/doc"
|
||||
)
|
||||
|
||||
func main() {
|
||||
cmd := &cobra.Command{
|
||||
Use: "test",
|
||||
Short: "my test program",
|
||||
}
|
||||
err := doc.GenReSTTree(cmd, "/tmp")
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
That will get you a ReST document `/tmp/test.rst`
|
||||
|
||||
## Generate ReST docs for the entire command tree
|
||||
|
||||
This program can actually generate docs for the kubectl command in the kubernetes project
|
||||
|
||||
```go
|
||||
package main
|
||||
|
||||
import (
|
||||
"log"
|
||||
"io/ioutil"
|
||||
"os"
|
||||
|
||||
"k8s.io/kubernetes/pkg/kubectl/cmd"
|
||||
cmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util"
|
||||
|
||||
"github.com/spf13/cobra/doc"
|
||||
)
|
||||
|
||||
func main() {
|
||||
kubectl := cmd.NewKubectlCommand(cmdutil.NewFactory(nil), os.Stdin, ioutil.Discard, ioutil.Discard)
|
||||
err := doc.GenReSTTree(kubectl, "./")
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
This will generate a whole series of files, one for each command in the tree, in the directory specified (in this case "./")
|
||||
|
||||
## Generate ReST docs for a single command
|
||||
|
||||
You may wish to have more control over the output, or only generate for a single command, instead of the entire command tree. If this is the case you may prefer to `GenReST` instead of `GenReSTTree`
|
||||
|
||||
```go
|
||||
out := new(bytes.Buffer)
|
||||
err := doc.GenReST(cmd, out)
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
```
|
||||
|
||||
This will write the ReST doc for ONLY "cmd" into the out, buffer.
|
||||
|
||||
## Customize the output
|
||||
|
||||
Both `GenReST` and `GenReSTTree` have alternate versions with callbacks to get some control of the output:
|
||||
|
||||
```go
|
||||
func GenReSTTreeCustom(cmd *Command, dir string, filePrepender func(string) string, linkHandler func(string, string) string) error {
|
||||
//...
|
||||
}
|
||||
```
|
||||
|
||||
```go
|
||||
func GenReSTCustom(cmd *Command, out *bytes.Buffer, linkHandler func(string, string) string) error {
|
||||
//...
|
||||
}
|
||||
```
|
||||
|
||||
The `filePrepender` will prepend the return value given the full filepath to the rendered ReST file. A common use case is to add front matter to use the generated documentation with [Hugo](http://gohugo.io/):
|
||||
|
||||
```go
|
||||
const fmTemplate = `---
|
||||
date: %s
|
||||
title: "%s"
|
||||
slug: %s
|
||||
url: %s
|
||||
---
|
||||
`
|
||||
filePrepender := func(filename string) string {
|
||||
now := time.Now().Format(time.RFC3339)
|
||||
name := filepath.Base(filename)
|
||||
base := strings.TrimSuffix(name, path.Ext(name))
|
||||
url := "/commands/" + strings.ToLower(base) + "/"
|
||||
return fmt.Sprintf(fmTemplate, now, strings.Replace(base, "_", " ", -1), base, url)
|
||||
}
|
||||
```
|
||||
|
||||
The `linkHandler` can be used to customize the rendered links to the commands, given a command name and reference. This is useful while converting rst to html or while generating documentation with tools like Sphinx where `:ref:` is used:
|
||||
|
||||
```go
|
||||
// Sphinx cross-referencing format
|
||||
linkHandler := func(name, ref string) string {
|
||||
return fmt.Sprintf(":ref:`%s <%s>`", name, ref)
|
||||
}
|
||||
```
|
||||
76
vendor/github.com/spf13/cobra/doc/rest_docs_test.go
сгенерированный
поставляемый
76
vendor/github.com/spf13/cobra/doc/rest_docs_test.go
сгенерированный
поставляемый
@@ -1,76 +0,0 @@
|
||||
package doc
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"io/ioutil"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
func TestGenRSTDoc(t *testing.T) {
|
||||
// We generate on a subcommand so we have both subcommands and parents
|
||||
buf := new(bytes.Buffer)
|
||||
if err := GenReST(echoCmd, buf); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
output := buf.String()
|
||||
|
||||
checkStringContains(t, output, echoCmd.Long)
|
||||
checkStringContains(t, output, echoCmd.Example)
|
||||
checkStringContains(t, output, "boolone")
|
||||
checkStringContains(t, output, "rootflag")
|
||||
checkStringContains(t, output, rootCmd.Short)
|
||||
checkStringContains(t, output, echoSubCmd.Short)
|
||||
checkStringOmits(t, output, deprecatedCmd.Short)
|
||||
}
|
||||
|
||||
func TestGenRSTNoTag(t *testing.T) {
|
||||
rootCmd.DisableAutoGenTag = true
|
||||
defer func() { rootCmd.DisableAutoGenTag = false }()
|
||||
|
||||
buf := new(bytes.Buffer)
|
||||
if err := GenReST(rootCmd, buf); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
output := buf.String()
|
||||
|
||||
unexpected := "Auto generated"
|
||||
checkStringOmits(t, output, unexpected)
|
||||
}
|
||||
|
||||
func TestGenRSTTree(t *testing.T) {
|
||||
c := &cobra.Command{Use: "do [OPTIONS] arg1 arg2"}
|
||||
|
||||
tmpdir, err := ioutil.TempDir("", "test-gen-rst-tree")
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to create tmpdir: %s", err.Error())
|
||||
}
|
||||
defer os.RemoveAll(tmpdir)
|
||||
|
||||
if err := GenReSTTree(c, tmpdir); err != nil {
|
||||
t.Fatalf("GenReSTTree failed: %s", err.Error())
|
||||
}
|
||||
|
||||
if _, err := os.Stat(filepath.Join(tmpdir, "do.rst")); err != nil {
|
||||
t.Fatalf("Expected file 'do.rst' to exist")
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkGenReSTToFile(b *testing.B) {
|
||||
file, err := ioutil.TempFile("", "")
|
||||
if err != nil {
|
||||
b.Fatal(err)
|
||||
}
|
||||
defer os.Remove(file.Name())
|
||||
defer file.Close()
|
||||
|
||||
b.ResetTimer()
|
||||
for i := 0; i < b.N; i++ {
|
||||
if err := GenReST(rootCmd, file); err != nil {
|
||||
b.Fatal(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
51
vendor/github.com/spf13/cobra/doc/util.go
сгенерированный
поставляемый
51
vendor/github.com/spf13/cobra/doc/util.go
сгенерированный
поставляемый
@@ -1,51 +0,0 @@
|
||||
// Copyright 2015 Red Hat Inc. All rights reserved.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package doc
|
||||
|
||||
import (
|
||||
"strings"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
// Test to see if we have a reason to print See Also information in docs
|
||||
// Basically this is a test for a parent commend or a subcommand which is
|
||||
// both not deprecated and not the autogenerated help command.
|
||||
func hasSeeAlso(cmd *cobra.Command) bool {
|
||||
if cmd.HasParent() {
|
||||
return true
|
||||
}
|
||||
for _, c := range cmd.Commands() {
|
||||
if !c.IsAvailableCommand() || c.IsAdditionalHelpTopicCommand() {
|
||||
continue
|
||||
}
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// Temporary workaround for yaml lib generating incorrect yaml with long strings
|
||||
// that do not contain \n.
|
||||
func forceMultiLine(s string) string {
|
||||
if len(s) > 60 && !strings.Contains(s, "\n") {
|
||||
s = s + "\n"
|
||||
}
|
||||
return s
|
||||
}
|
||||
|
||||
type byName []*cobra.Command
|
||||
|
||||
func (s byName) Len() int { return len(s) }
|
||||
func (s byName) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
|
||||
func (s byName) Less(i, j int) bool { return s[i].Name() < s[j].Name() }
|
||||
169
vendor/github.com/spf13/cobra/doc/yaml_docs.go
сгенерированный
поставляемый
169
vendor/github.com/spf13/cobra/doc/yaml_docs.go
сгенерированный
поставляемый
@@ -1,169 +0,0 @@
|
||||
// Copyright 2016 French Ben. All rights reserved.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package doc
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sort"
|
||||
"strings"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
"github.com/spf13/pflag"
|
||||
"gopkg.in/yaml.v2"
|
||||
)
|
||||
|
||||
type cmdOption struct {
|
||||
Name string
|
||||
Shorthand string `yaml:",omitempty"`
|
||||
DefaultValue string `yaml:"default_value,omitempty"`
|
||||
Usage string `yaml:",omitempty"`
|
||||
}
|
||||
|
||||
type cmdDoc struct {
|
||||
Name string
|
||||
Synopsis string `yaml:",omitempty"`
|
||||
Description string `yaml:",omitempty"`
|
||||
Options []cmdOption `yaml:",omitempty"`
|
||||
InheritedOptions []cmdOption `yaml:"inherited_options,omitempty"`
|
||||
Example string `yaml:",omitempty"`
|
||||
SeeAlso []string `yaml:"see_also,omitempty"`
|
||||
}
|
||||
|
||||
// GenYamlTree creates yaml structured ref files for this command and all descendants
|
||||
// in the directory given. This function may not work
|
||||
// correctly if your command names have `-` in them. If you have `cmd` with two
|
||||
// subcmds, `sub` and `sub-third`, and `sub` has a subcommand called `third`
|
||||
// it is undefined which help output will be in the file `cmd-sub-third.1`.
|
||||
func GenYamlTree(cmd *cobra.Command, dir string) error {
|
||||
identity := func(s string) string { return s }
|
||||
emptyStr := func(s string) string { return "" }
|
||||
return GenYamlTreeCustom(cmd, dir, emptyStr, identity)
|
||||
}
|
||||
|
||||
// GenYamlTreeCustom creates yaml structured ref files.
|
||||
func GenYamlTreeCustom(cmd *cobra.Command, dir string, filePrepender, linkHandler func(string) string) error {
|
||||
for _, c := range cmd.Commands() {
|
||||
if !c.IsAvailableCommand() || c.IsAdditionalHelpTopicCommand() {
|
||||
continue
|
||||
}
|
||||
if err := GenYamlTreeCustom(c, dir, filePrepender, linkHandler); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
basename := strings.Replace(cmd.CommandPath(), " ", "_", -1) + ".yaml"
|
||||
filename := filepath.Join(dir, basename)
|
||||
f, err := os.Create(filename)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer f.Close()
|
||||
|
||||
if _, err := io.WriteString(f, filePrepender(filename)); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := GenYamlCustom(cmd, f, linkHandler); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// GenYaml creates yaml output.
|
||||
func GenYaml(cmd *cobra.Command, w io.Writer) error {
|
||||
return GenYamlCustom(cmd, w, func(s string) string { return s })
|
||||
}
|
||||
|
||||
// GenYamlCustom creates custom yaml output.
|
||||
func GenYamlCustom(cmd *cobra.Command, w io.Writer, linkHandler func(string) string) error {
|
||||
cmd.InitDefaultHelpCmd()
|
||||
cmd.InitDefaultHelpFlag()
|
||||
|
||||
yamlDoc := cmdDoc{}
|
||||
yamlDoc.Name = cmd.CommandPath()
|
||||
|
||||
yamlDoc.Synopsis = forceMultiLine(cmd.Short)
|
||||
yamlDoc.Description = forceMultiLine(cmd.Long)
|
||||
|
||||
if len(cmd.Example) > 0 {
|
||||
yamlDoc.Example = cmd.Example
|
||||
}
|
||||
|
||||
flags := cmd.NonInheritedFlags()
|
||||
if flags.HasFlags() {
|
||||
yamlDoc.Options = genFlagResult(flags)
|
||||
}
|
||||
flags = cmd.InheritedFlags()
|
||||
if flags.HasFlags() {
|
||||
yamlDoc.InheritedOptions = genFlagResult(flags)
|
||||
}
|
||||
|
||||
if hasSeeAlso(cmd) {
|
||||
result := []string{}
|
||||
if cmd.HasParent() {
|
||||
parent := cmd.Parent()
|
||||
result = append(result, parent.CommandPath()+" - "+parent.Short)
|
||||
}
|
||||
children := cmd.Commands()
|
||||
sort.Sort(byName(children))
|
||||
for _, child := range children {
|
||||
if !child.IsAvailableCommand() || child.IsAdditionalHelpTopicCommand() {
|
||||
continue
|
||||
}
|
||||
result = append(result, child.Name()+" - "+child.Short)
|
||||
}
|
||||
yamlDoc.SeeAlso = result
|
||||
}
|
||||
|
||||
final, err := yaml.Marshal(&yamlDoc)
|
||||
if err != nil {
|
||||
fmt.Println(err)
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
if _, err := w.Write(final); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func genFlagResult(flags *pflag.FlagSet) []cmdOption {
|
||||
var result []cmdOption
|
||||
|
||||
flags.VisitAll(func(flag *pflag.Flag) {
|
||||
// Todo, when we mark a shorthand is deprecated, but specify an empty message.
|
||||
// The flag.ShorthandDeprecated is empty as the shorthand is deprecated.
|
||||
// Using len(flag.ShorthandDeprecated) > 0 can't handle this, others are ok.
|
||||
if !(len(flag.ShorthandDeprecated) > 0) && len(flag.Shorthand) > 0 {
|
||||
opt := cmdOption{
|
||||
flag.Name,
|
||||
flag.Shorthand,
|
||||
flag.DefValue,
|
||||
forceMultiLine(flag.Usage),
|
||||
}
|
||||
result = append(result, opt)
|
||||
} else {
|
||||
opt := cmdOption{
|
||||
Name: flag.Name,
|
||||
DefaultValue: forceMultiLine(flag.DefValue),
|
||||
Usage: forceMultiLine(flag.Usage),
|
||||
}
|
||||
result = append(result, opt)
|
||||
}
|
||||
})
|
||||
|
||||
return result
|
||||
}
|
||||
112
vendor/github.com/spf13/cobra/doc/yaml_docs.md
сгенерированный
поставляемый
112
vendor/github.com/spf13/cobra/doc/yaml_docs.md
сгенерированный
поставляемый
@@ -1,112 +0,0 @@
|
||||
# Generating Yaml Docs For Your Own cobra.Command
|
||||
|
||||
Generating yaml files from a cobra command is incredibly easy. An example is as follows:
|
||||
|
||||
```go
|
||||
package main
|
||||
|
||||
import (
|
||||
"log"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
"github.com/spf13/cobra/doc"
|
||||
)
|
||||
|
||||
func main() {
|
||||
cmd := &cobra.Command{
|
||||
Use: "test",
|
||||
Short: "my test program",
|
||||
}
|
||||
err := doc.GenYamlTree(cmd, "/tmp")
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
That will get you a Yaml document `/tmp/test.yaml`
|
||||
|
||||
## Generate yaml docs for the entire command tree
|
||||
|
||||
This program can actually generate docs for the kubectl command in the kubernetes project
|
||||
|
||||
```go
|
||||
package main
|
||||
|
||||
import (
|
||||
"io/ioutil"
|
||||
"log"
|
||||
"os"
|
||||
|
||||
"k8s.io/kubernetes/pkg/kubectl/cmd"
|
||||
cmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util"
|
||||
|
||||
"github.com/spf13/cobra/doc"
|
||||
)
|
||||
|
||||
func main() {
|
||||
kubectl := cmd.NewKubectlCommand(cmdutil.NewFactory(nil), os.Stdin, ioutil.Discard, ioutil.Discard)
|
||||
err := doc.GenYamlTree(kubectl, "./")
|
||||
if err != nil {
|
||||
log.Fatal(err)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
This will generate a whole series of files, one for each command in the tree, in the directory specified (in this case "./")
|
||||
|
||||
## Generate yaml docs for a single command
|
||||
|
||||
You may wish to have more control over the output, or only generate for a single command, instead of the entire command tree. If this is the case you may prefer to `GenYaml` instead of `GenYamlTree`
|
||||
|
||||
```go
|
||||
out := new(bytes.Buffer)
|
||||
doc.GenYaml(cmd, out)
|
||||
```
|
||||
|
||||
This will write the yaml doc for ONLY "cmd" into the out, buffer.
|
||||
|
||||
## Customize the output
|
||||
|
||||
Both `GenYaml` and `GenYamlTree` have alternate versions with callbacks to get some control of the output:
|
||||
|
||||
```go
|
||||
func GenYamlTreeCustom(cmd *Command, dir string, filePrepender, linkHandler func(string) string) error {
|
||||
//...
|
||||
}
|
||||
```
|
||||
|
||||
```go
|
||||
func GenYamlCustom(cmd *Command, out *bytes.Buffer, linkHandler func(string) string) error {
|
||||
//...
|
||||
}
|
||||
```
|
||||
|
||||
The `filePrepender` will prepend the return value given the full filepath to the rendered Yaml file. A common use case is to add front matter to use the generated documentation with [Hugo](http://gohugo.io/):
|
||||
|
||||
```go
|
||||
const fmTemplate = `---
|
||||
date: %s
|
||||
title: "%s"
|
||||
slug: %s
|
||||
url: %s
|
||||
---
|
||||
`
|
||||
|
||||
filePrepender := func(filename string) string {
|
||||
now := time.Now().Format(time.RFC3339)
|
||||
name := filepath.Base(filename)
|
||||
base := strings.TrimSuffix(name, path.Ext(name))
|
||||
url := "/commands/" + strings.ToLower(base) + "/"
|
||||
return fmt.Sprintf(fmTemplate, now, strings.Replace(base, "_", " ", -1), base, url)
|
||||
}
|
||||
```
|
||||
|
||||
The `linkHandler` can be used to customize the rendered internal links to the commands, given a filename:
|
||||
|
||||
```go
|
||||
linkHandler := func(name string) string {
|
||||
base := strings.TrimSuffix(name, path.Ext(name))
|
||||
return "/commands/" + strings.ToLower(base) + "/"
|
||||
}
|
||||
```
|
||||
74
vendor/github.com/spf13/cobra/doc/yaml_docs_test.go
сгенерированный
поставляемый
74
vendor/github.com/spf13/cobra/doc/yaml_docs_test.go
сгенерированный
поставляемый
@@ -1,74 +0,0 @@
|
||||
package doc
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"io/ioutil"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
func TestGenYamlDoc(t *testing.T) {
|
||||
// We generate on s subcommand so we have both subcommands and parents
|
||||
buf := new(bytes.Buffer)
|
||||
if err := GenYaml(echoCmd, buf); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
output := buf.String()
|
||||
|
||||
checkStringContains(t, output, echoCmd.Long)
|
||||
checkStringContains(t, output, echoCmd.Example)
|
||||
checkStringContains(t, output, "boolone")
|
||||
checkStringContains(t, output, "rootflag")
|
||||
checkStringContains(t, output, rootCmd.Short)
|
||||
checkStringContains(t, output, echoSubCmd.Short)
|
||||
}
|
||||
|
||||
func TestGenYamlNoTag(t *testing.T) {
|
||||
rootCmd.DisableAutoGenTag = true
|
||||
defer func() { rootCmd.DisableAutoGenTag = false }()
|
||||
|
||||
buf := new(bytes.Buffer)
|
||||
if err := GenYaml(rootCmd, buf); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
output := buf.String()
|
||||
|
||||
checkStringOmits(t, output, "Auto generated")
|
||||
}
|
||||
|
||||
func TestGenYamlTree(t *testing.T) {
|
||||
c := &cobra.Command{Use: "do [OPTIONS] arg1 arg2"}
|
||||
|
||||
tmpdir, err := ioutil.TempDir("", "test-gen-yaml-tree")
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to create tmpdir: %s", err.Error())
|
||||
}
|
||||
defer os.RemoveAll(tmpdir)
|
||||
|
||||
if err := GenYamlTree(c, tmpdir); err != nil {
|
||||
t.Fatalf("GenYamlTree failed: %s", err.Error())
|
||||
}
|
||||
|
||||
if _, err := os.Stat(filepath.Join(tmpdir, "do.yaml")); err != nil {
|
||||
t.Fatalf("Expected file 'do.yaml' to exist")
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkGenYamlToFile(b *testing.B) {
|
||||
file, err := ioutil.TempFile("", "")
|
||||
if err != nil {
|
||||
b.Fatal(err)
|
||||
}
|
||||
defer os.Remove(file.Name())
|
||||
defer file.Close()
|
||||
|
||||
b.ResetTimer()
|
||||
for i := 0; i < b.N; i++ {
|
||||
if err := GenYaml(rootCmd, file); err != nil {
|
||||
b.Fatal(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
89
vendor/github.com/spf13/cobra/zsh_completions_test.go
сгенерированный
поставляемый
89
vendor/github.com/spf13/cobra/zsh_completions_test.go
сгенерированный
поставляемый
@@ -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)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
102
vendor/github.com/spf13/jwalterweatherman/default_notepad_test.go
сгенерированный
поставляемый
102
vendor/github.com/spf13/jwalterweatherman/default_notepad_test.go
сгенерированный
поставляемый
@@ -1,102 +0,0 @@
|
||||
// Copyright © 2016 Steve Francia <spf@spf13.com>.
|
||||
//
|
||||
// Use of this source code is governed by an MIT-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
package jwalterweatherman
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"io/ioutil"
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestThresholds(t *testing.T) {
|
||||
SetStdoutThreshold(LevelError)
|
||||
require.Equal(t, StdoutThreshold(), LevelError)
|
||||
SetLogThreshold(LevelCritical)
|
||||
require.Equal(t, LogThreshold(), LevelCritical)
|
||||
require.NotEqual(t, StdoutThreshold(), LevelCritical)
|
||||
SetStdoutThreshold(LevelWarn)
|
||||
require.Equal(t, StdoutThreshold(), LevelWarn)
|
||||
}
|
||||
|
||||
func TestDefaultLogging(t *testing.T) {
|
||||
var outputBuf, logBuf bytes.Buffer
|
||||
|
||||
defaultNotepad.logHandle = &logBuf
|
||||
defaultNotepad.outHandle = &outputBuf
|
||||
|
||||
SetLogThreshold(LevelWarn)
|
||||
SetStdoutThreshold(LevelError)
|
||||
|
||||
FATAL.Println("fatal err")
|
||||
CRITICAL.Println("critical err")
|
||||
ERROR.Println("an error")
|
||||
WARN.Println("a warning")
|
||||
INFO.Println("information")
|
||||
DEBUG.Println("debugging info")
|
||||
TRACE.Println("trace")
|
||||
|
||||
require.Contains(t, logBuf.String(), "fatal err")
|
||||
require.Contains(t, logBuf.String(), "critical err")
|
||||
require.Contains(t, logBuf.String(), "an error")
|
||||
require.Contains(t, logBuf.String(), "a warning")
|
||||
require.NotContains(t, logBuf.String(), "information")
|
||||
require.NotContains(t, logBuf.String(), "debugging info")
|
||||
require.NotContains(t, logBuf.String(), "trace")
|
||||
|
||||
require.Contains(t, outputBuf.String(), "fatal err")
|
||||
require.Contains(t, outputBuf.String(), "critical err")
|
||||
require.Contains(t, outputBuf.String(), "an error")
|
||||
require.NotContains(t, outputBuf.String(), "a warning")
|
||||
require.NotContains(t, outputBuf.String(), "information")
|
||||
require.NotContains(t, outputBuf.String(), "debugging info")
|
||||
require.NotContains(t, outputBuf.String(), "trace")
|
||||
}
|
||||
|
||||
func TestLogCounter(t *testing.T) {
|
||||
defaultNotepad.logHandle = ioutil.Discard
|
||||
defaultNotepad.outHandle = ioutil.Discard
|
||||
|
||||
SetLogThreshold(LevelTrace)
|
||||
SetStdoutThreshold(LevelTrace)
|
||||
|
||||
FATAL.Println("fatal err")
|
||||
CRITICAL.Println("critical err")
|
||||
WARN.Println("a warning")
|
||||
WARN.Println("another warning")
|
||||
INFO.Println("information")
|
||||
DEBUG.Println("debugging info")
|
||||
TRACE.Println("trace")
|
||||
|
||||
wg := &sync.WaitGroup{}
|
||||
|
||||
for i := 0; i < 10; i++ {
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
for j := 0; j < 10; j++ {
|
||||
ERROR.Println("error", j)
|
||||
// check for data races
|
||||
require.True(t, LogCountForLevel(LevelError) > uint64(j))
|
||||
require.True(t, LogCountForLevelsGreaterThanorEqualTo(LevelError) > uint64(j))
|
||||
}
|
||||
}()
|
||||
|
||||
}
|
||||
|
||||
wg.Wait()
|
||||
|
||||
require.Equal(t, uint64(1), LogCountForLevel(LevelFatal))
|
||||
require.Equal(t, uint64(1), LogCountForLevel(LevelCritical))
|
||||
require.Equal(t, uint64(2), LogCountForLevel(LevelWarn))
|
||||
require.Equal(t, uint64(1), LogCountForLevel(LevelInfo))
|
||||
require.Equal(t, uint64(1), LogCountForLevel(LevelDebug))
|
||||
require.Equal(t, uint64(1), LogCountForLevel(LevelTrace))
|
||||
require.Equal(t, uint64(100), LogCountForLevel(LevelError))
|
||||
require.Equal(t, uint64(102), LogCountForLevelsGreaterThanorEqualTo(LevelError))
|
||||
}
|
||||
50
vendor/github.com/spf13/jwalterweatherman/notepad_test.go
сгенерированный
поставляемый
50
vendor/github.com/spf13/jwalterweatherman/notepad_test.go
сгенерированный
поставляемый
@@ -1,50 +0,0 @@
|
||||
// Copyright © 2016 Steve Francia <spf@spf13.com>.
|
||||
//
|
||||
// Use of this source code is governed by an MIT-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
package jwalterweatherman
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestNotepad(t *testing.T) {
|
||||
var logHandle, outHandle bytes.Buffer
|
||||
|
||||
n := NewNotepad(LevelCritical, LevelError, &outHandle, &logHandle, "TestNotePad", 0)
|
||||
|
||||
require.Equal(t, LevelCritical, n.GetStdoutThreshold())
|
||||
require.Equal(t, LevelError, n.GetLogThreshold())
|
||||
|
||||
n.DEBUG.Println("Some debug")
|
||||
n.ERROR.Println("Some error")
|
||||
n.CRITICAL.Println("Some critical error")
|
||||
|
||||
require.Contains(t, logHandle.String(), "[TestNotePad] ERROR Some error")
|
||||
require.NotContains(t, logHandle.String(), "Some debug")
|
||||
require.NotContains(t, outHandle.String(), "Some error")
|
||||
require.Contains(t, outHandle.String(), "Some critical error")
|
||||
|
||||
require.Equal(t, n.LogCountForLevel(LevelError), uint64(1))
|
||||
require.Equal(t, n.LogCountForLevel(LevelDebug), uint64(1))
|
||||
require.Equal(t, n.LogCountForLevel(LevelTrace), uint64(0))
|
||||
}
|
||||
|
||||
func TestThresholdString(t *testing.T) {
|
||||
require.Equal(t, LevelError.String(), "ERROR")
|
||||
require.Equal(t, LevelTrace.String(), "TRACE")
|
||||
}
|
||||
|
||||
func BenchmarkLogPrintOnlyToCounter(b *testing.B) {
|
||||
var logHandle, outHandle bytes.Buffer
|
||||
n := NewNotepad(LevelCritical, LevelCritical, &outHandle, &logHandle, "TestNotePad", 0)
|
||||
|
||||
b.ResetTimer()
|
||||
for i := 0; i < b.N; i++ {
|
||||
n.INFO.Print("Test")
|
||||
}
|
||||
}
|
||||
215
vendor/github.com/spf13/pflag/bool_slice_test.go
сгенерированный
поставляемый
215
vendor/github.com/spf13/pflag/bool_slice_test.go
сгенерированный
поставляемый
@@ -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)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
179
vendor/github.com/spf13/pflag/bool_test.go
сгенерированный
поставляемый
179
vendor/github.com/spf13/pflag/bool_test.go
сгенерированный
поставляемый
@@ -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)
|
||||
}
|
||||
}
|
||||
105
vendor/github.com/spf13/pflag/bytes.go
сгенерированный
поставляемый
Обычный файл
105
vendor/github.com/spf13/pflag/bytes.go
сгенерированный
поставляемый
Обычный файл
@@ -0,0 +1,105 @@
|
||||
package pflag
|
||||
|
||||
import (
|
||||
"encoding/hex"
|
||||
"fmt"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// BytesHex adapts []byte for use as a flag. Value of flag is HEX encoded
|
||||
type bytesHexValue []byte
|
||||
|
||||
func (bytesHex bytesHexValue) String() string {
|
||||
return fmt.Sprintf("%X", []byte(bytesHex))
|
||||
}
|
||||
|
||||
func (bytesHex *bytesHexValue) Set(value string) error {
|
||||
bin, err := hex.DecodeString(strings.TrimSpace(value))
|
||||
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
*bytesHex = bin
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (*bytesHexValue) Type() string {
|
||||
return "bytesHex"
|
||||
}
|
||||
|
||||
func newBytesHexValue(val []byte, p *[]byte) *bytesHexValue {
|
||||
*p = val
|
||||
return (*bytesHexValue)(p)
|
||||
}
|
||||
|
||||
func bytesHexConv(sval string) (interface{}, error) {
|
||||
|
||||
bin, err := hex.DecodeString(sval)
|
||||
|
||||
if err == nil {
|
||||
return bin, nil
|
||||
}
|
||||
|
||||
return nil, fmt.Errorf("invalid string being converted to Bytes: %s %s", sval, err)
|
||||
}
|
||||
|
||||
// GetBytesHex return the []byte value of a flag with the given name
|
||||
func (f *FlagSet) GetBytesHex(name string) ([]byte, error) {
|
||||
val, err := f.getFlagType(name, "bytesHex", bytesHexConv)
|
||||
|
||||
if err != nil {
|
||||
return []byte{}, err
|
||||
}
|
||||
|
||||
return val.([]byte), nil
|
||||
}
|
||||
|
||||
// BytesHexVar defines an []byte flag with specified name, default value, and usage string.
|
||||
// The argument p points to an []byte variable in which to store the value of the flag.
|
||||
func (f *FlagSet) BytesHexVar(p *[]byte, name string, value []byte, usage string) {
|
||||
f.VarP(newBytesHexValue(value, p), name, "", usage)
|
||||
}
|
||||
|
||||
// BytesHexVarP is like BytesHexVar, but accepts a shorthand letter that can be used after a single dash.
|
||||
func (f *FlagSet) BytesHexVarP(p *[]byte, name, shorthand string, value []byte, usage string) {
|
||||
f.VarP(newBytesHexValue(value, p), name, shorthand, usage)
|
||||
}
|
||||
|
||||
// BytesHexVar defines an []byte flag with specified name, default value, and usage string.
|
||||
// The argument p points to an []byte variable in which to store the value of the flag.
|
||||
func BytesHexVar(p *[]byte, name string, value []byte, usage string) {
|
||||
CommandLine.VarP(newBytesHexValue(value, p), name, "", usage)
|
||||
}
|
||||
|
||||
// BytesHexVarP is like BytesHexVar, but accepts a shorthand letter that can be used after a single dash.
|
||||
func BytesHexVarP(p *[]byte, name, shorthand string, value []byte, usage string) {
|
||||
CommandLine.VarP(newBytesHexValue(value, p), name, shorthand, usage)
|
||||
}
|
||||
|
||||
// BytesHex defines an []byte flag with specified name, default value, and usage string.
|
||||
// The return value is the address of an []byte variable that stores the value of the flag.
|
||||
func (f *FlagSet) BytesHex(name string, value []byte, usage string) *[]byte {
|
||||
p := new([]byte)
|
||||
f.BytesHexVarP(p, name, "", value, usage)
|
||||
return p
|
||||
}
|
||||
|
||||
// BytesHexP is like BytesHex, but accepts a shorthand letter that can be used after a single dash.
|
||||
func (f *FlagSet) BytesHexP(name, shorthand string, value []byte, usage string) *[]byte {
|
||||
p := new([]byte)
|
||||
f.BytesHexVarP(p, name, shorthand, value, usage)
|
||||
return p
|
||||
}
|
||||
|
||||
// BytesHex defines an []byte flag with specified name, default value, and usage string.
|
||||
// The return value is the address of an []byte variable that stores the value of the flag.
|
||||
func BytesHex(name string, value []byte, usage string) *[]byte {
|
||||
return CommandLine.BytesHexP(name, "", value, usage)
|
||||
}
|
||||
|
||||
// BytesHexP is like BytesHex, but accepts a shorthand letter that can be used after a single dash.
|
||||
func BytesHexP(name, shorthand string, value []byte, usage string) *[]byte {
|
||||
return CommandLine.BytesHexP(name, shorthand, value, usage)
|
||||
}
|
||||
56
vendor/github.com/spf13/pflag/count_test.go
сгенерированный
поставляемый
56
vendor/github.com/spf13/pflag/count_test.go
сгенерированный
поставляемый
@@ -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)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
165
vendor/github.com/spf13/pflag/duration_slice_test.go
сгенерированный
поставляемый
165
vendor/github.com/spf13/pflag/duration_slice_test.go
сгенерированный
поставляемый
@@ -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)
|
||||
}
|
||||
}
|
||||
}
|
||||
36
vendor/github.com/spf13/pflag/example_test.go
сгенерированный
поставляемый
36
vendor/github.com/spf13/pflag/example_test.go
сгенерированный
поставляемый
@@ -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)
|
||||
}
|
||||
29
vendor/github.com/spf13/pflag/export_test.go
сгенерированный
поставляемый
29
vendor/github.com/spf13/pflag/export_test.go
сгенерированный
поставляемый
@@ -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
|
||||
}
|
||||
98
vendor/github.com/spf13/pflag/flag.go
сгенерированный
поставляемый
98
vendor/github.com/spf13/pflag/flag.go
сгенерированный
поставляемый
@@ -101,6 +101,7 @@ package pflag
|
||||
import (
|
||||
"bytes"
|
||||
"errors"
|
||||
goflag "flag"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
@@ -123,6 +124,12 @@ const (
|
||||
PanicOnError
|
||||
)
|
||||
|
||||
// ParseErrorsWhitelist defines the parsing errors that can be ignored
|
||||
type ParseErrorsWhitelist struct {
|
||||
// UnknownFlags will ignore unknown flags errors and continue parsing rest of the flags
|
||||
UnknownFlags bool
|
||||
}
|
||||
|
||||
// NormalizedName is a flag name that has been normalized according to rules
|
||||
// for the FlagSet (e.g. making '-' and '_' equivalent).
|
||||
type NormalizedName string
|
||||
@@ -138,6 +145,9 @@ type FlagSet struct {
|
||||
// help/usage messages.
|
||||
SortFlags bool
|
||||
|
||||
// ParseErrorsWhitelist is used to configure a whitelist of errors
|
||||
ParseErrorsWhitelist ParseErrorsWhitelist
|
||||
|
||||
name string
|
||||
parsed bool
|
||||
actual map[NormalizedName]*Flag
|
||||
@@ -153,6 +163,8 @@ type FlagSet struct {
|
||||
output io.Writer // nil means stderr; use out() accessor
|
||||
interspersed bool // allow interspersed option/non-option args
|
||||
normalizeNameFunc func(f *FlagSet, name string) NormalizedName
|
||||
|
||||
addedGoFlagSets []*goflag.FlagSet
|
||||
}
|
||||
|
||||
// A Flag represents the state of a flag.
|
||||
@@ -267,16 +279,16 @@ func (f *FlagSet) VisitAll(fn func(*Flag)) {
|
||||
}
|
||||
}
|
||||
|
||||
// HasFlags returns a bool to indicate if the FlagSet has any flags definied.
|
||||
// HasFlags returns a bool to indicate if the FlagSet has any flags defined.
|
||||
func (f *FlagSet) HasFlags() bool {
|
||||
return len(f.formal) > 0
|
||||
}
|
||||
|
||||
// HasAvailableFlags returns a bool to indicate if the FlagSet has any flags
|
||||
// definied that are not hidden or deprecated.
|
||||
// that are not hidden.
|
||||
func (f *FlagSet) HasAvailableFlags() bool {
|
||||
for _, flag := range f.formal {
|
||||
if !flag.Hidden && len(flag.Deprecated) == 0 {
|
||||
if !flag.Hidden {
|
||||
return true
|
||||
}
|
||||
}
|
||||
@@ -386,6 +398,7 @@ func (f *FlagSet) MarkDeprecated(name string, usageMessage string) error {
|
||||
return fmt.Errorf("deprecated message for flag %q must be set", name)
|
||||
}
|
||||
flag.Deprecated = usageMessage
|
||||
flag.Hidden = true
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -586,11 +599,14 @@ func wrapN(i, slop int, s string) (string, string) {
|
||||
return s, ""
|
||||
}
|
||||
|
||||
w := strings.LastIndexAny(s[:i], " \t")
|
||||
w := strings.LastIndexAny(s[:i], " \t\n")
|
||||
if w <= 0 {
|
||||
return s, ""
|
||||
}
|
||||
|
||||
nlPos := strings.LastIndex(s[:i], "\n")
|
||||
if nlPos > 0 && nlPos < w {
|
||||
return s[:nlPos], s[nlPos+1:]
|
||||
}
|
||||
return s[:w], s[w+1:]
|
||||
}
|
||||
|
||||
@@ -599,7 +615,7 @@ func wrapN(i, slop int, s string) (string, string) {
|
||||
// caller). Pass `w` == 0 to do no wrapping
|
||||
func wrap(i, w int, s string) string {
|
||||
if w == 0 {
|
||||
return s
|
||||
return strings.Replace(s, "\n", "\n"+strings.Repeat(" ", i), -1)
|
||||
}
|
||||
|
||||
// space between indent i and end of line width w into which
|
||||
@@ -617,7 +633,7 @@ func wrap(i, w int, s string) string {
|
||||
}
|
||||
// If still not enough space then don't even try to wrap.
|
||||
if wrap < 24 {
|
||||
return s
|
||||
return strings.Replace(s, "\n", r, -1)
|
||||
}
|
||||
|
||||
// Try to avoid short orphan words on the final line, by
|
||||
@@ -629,14 +645,14 @@ func wrap(i, w int, s string) string {
|
||||
// Handle first line, which is indented by the caller (or the
|
||||
// special case above)
|
||||
l, s = wrapN(wrap, slop, s)
|
||||
r = r + l
|
||||
r = r + strings.Replace(l, "\n", "\n"+strings.Repeat(" ", i), -1)
|
||||
|
||||
// Now wrap the rest
|
||||
for s != "" {
|
||||
var t string
|
||||
|
||||
t, s = wrapN(wrap, slop, s)
|
||||
r = r + "\n" + strings.Repeat(" ", i) + t
|
||||
r = r + "\n" + strings.Repeat(" ", i) + strings.Replace(t, "\n", "\n"+strings.Repeat(" ", i), -1)
|
||||
}
|
||||
|
||||
return r
|
||||
@@ -653,7 +669,7 @@ func (f *FlagSet) FlagUsagesWrapped(cols int) string {
|
||||
|
||||
maxlen := 0
|
||||
f.VisitAll(func(flag *Flag) {
|
||||
if flag.Deprecated != "" || flag.Hidden {
|
||||
if flag.Hidden {
|
||||
return
|
||||
}
|
||||
|
||||
@@ -700,6 +716,9 @@ func (f *FlagSet) FlagUsagesWrapped(cols int) string {
|
||||
line += fmt.Sprintf(" (default %s)", flag.DefValue)
|
||||
}
|
||||
}
|
||||
if len(flag.Deprecated) != 0 {
|
||||
line += fmt.Sprintf(" (DEPRECATED: %s)", flag.Deprecated)
|
||||
}
|
||||
|
||||
lines = append(lines, line)
|
||||
})
|
||||
@@ -896,6 +915,25 @@ func (f *FlagSet) usage() {
|
||||
}
|
||||
}
|
||||
|
||||
//--unknown (args will be empty)
|
||||
//--unknown --next-flag ... (args will be --next-flag ...)
|
||||
//--unknown arg ... (args will be arg ...)
|
||||
func stripUnknownFlagValue(args []string) []string {
|
||||
if len(args) == 0 {
|
||||
//--unknown
|
||||
return args
|
||||
}
|
||||
|
||||
first := args[0]
|
||||
if first[0] == '-' {
|
||||
//--unknown --next-flag ...
|
||||
return args
|
||||
}
|
||||
|
||||
//--unknown arg ... (args will be arg ...)
|
||||
return args[1:]
|
||||
}
|
||||
|
||||
func (f *FlagSet) parseLongArg(s string, args []string, fn parseFunc) (a []string, err error) {
|
||||
a = args
|
||||
name := s[2:]
|
||||
@@ -907,13 +945,24 @@ func (f *FlagSet) parseLongArg(s string, args []string, fn parseFunc) (a []strin
|
||||
split := strings.SplitN(name, "=", 2)
|
||||
name = split[0]
|
||||
flag, exists := f.formal[f.normalizeFlagName(name)]
|
||||
|
||||
if !exists {
|
||||
if name == "help" { // special case for nice help message.
|
||||
switch {
|
||||
case name == "help":
|
||||
f.usage()
|
||||
return a, ErrHelp
|
||||
case f.ParseErrorsWhitelist.UnknownFlags:
|
||||
// --unknown=unknownval arg ...
|
||||
// we do not want to lose arg in this case
|
||||
if len(split) >= 2 {
|
||||
return a, nil
|
||||
}
|
||||
|
||||
return stripUnknownFlagValue(a), nil
|
||||
default:
|
||||
err = f.failf("unknown flag: --%s", name)
|
||||
return
|
||||
}
|
||||
err = f.failf("unknown flag: --%s", name)
|
||||
return
|
||||
}
|
||||
|
||||
var value string
|
||||
@@ -951,13 +1000,25 @@ func (f *FlagSet) parseSingleShortArg(shorthands string, args []string, fn parse
|
||||
|
||||
flag, exists := f.shorthands[c]
|
||||
if !exists {
|
||||
if c == 'h' { // special case for nice help message.
|
||||
switch {
|
||||
case c == 'h':
|
||||
f.usage()
|
||||
err = ErrHelp
|
||||
return
|
||||
case f.ParseErrorsWhitelist.UnknownFlags:
|
||||
// '-f=arg arg ...'
|
||||
// we do not want to lose arg in this case
|
||||
if len(shorthands) > 2 && shorthands[1] == '=' {
|
||||
outShorts = ""
|
||||
return
|
||||
}
|
||||
|
||||
outArgs = stripUnknownFlagValue(outArgs)
|
||||
return
|
||||
default:
|
||||
err = f.failf("unknown shorthand flag: %q in -%s", c, shorthands)
|
||||
return
|
||||
}
|
||||
err = f.failf("unknown shorthand flag: %q in -%s", c, shorthands)
|
||||
return
|
||||
}
|
||||
|
||||
var value string
|
||||
@@ -1044,6 +1105,11 @@ func (f *FlagSet) parseArgs(args []string, fn parseFunc) (err error) {
|
||||
// are defined and before flags are accessed by the program.
|
||||
// The return value will be ErrHelp if -help was set but not defined.
|
||||
func (f *FlagSet) Parse(arguments []string) error {
|
||||
if f.addedGoFlagSets != nil {
|
||||
for _, goFlagSet := range f.addedGoFlagSets {
|
||||
goFlagSet.Parse(nil)
|
||||
}
|
||||
}
|
||||
f.parsed = true
|
||||
|
||||
if len(arguments) < 0 {
|
||||
|
||||
1158
vendor/github.com/spf13/pflag/flag_test.go
сгенерированный
поставляемый
1158
vendor/github.com/spf13/pflag/flag_test.go
сгенерированный
поставляемый
Разница между файлами не показана из-за своего большого размера
Загрузить разницу
4
vendor/github.com/spf13/pflag/golangflag.go
сгенерированный
поставляемый
4
vendor/github.com/spf13/pflag/golangflag.go
сгенерированный
поставляемый
@@ -98,4 +98,8 @@ func (f *FlagSet) AddGoFlagSet(newSet *goflag.FlagSet) {
|
||||
newSet.VisitAll(func(goflag *goflag.Flag) {
|
||||
f.AddGoFlag(goflag)
|
||||
})
|
||||
if f.addedGoFlagSets == nil {
|
||||
f.addedGoFlagSets = make([]*goflag.FlagSet, 0)
|
||||
}
|
||||
f.addedGoFlagSets = append(f.addedGoFlagSets, newSet)
|
||||
}
|
||||
|
||||
39
vendor/github.com/spf13/pflag/golangflag_test.go
сгенерированный
поставляемый
39
vendor/github.com/spf13/pflag/golangflag_test.go
сгенерированный
поставляемый
@@ -1,39 +0,0 @@
|
||||
// Copyright 2009 The Go Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
package pflag
|
||||
|
||||
import (
|
||||
goflag "flag"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestGoflags(t *testing.T) {
|
||||
goflag.String("stringFlag", "stringFlag", "stringFlag")
|
||||
goflag.Bool("boolFlag", false, "boolFlag")
|
||||
|
||||
f := NewFlagSet("test", ContinueOnError)
|
||||
|
||||
f.AddGoFlagSet(goflag.CommandLine)
|
||||
err := f.Parse([]string{"--stringFlag=bob", "--boolFlag"})
|
||||
if err != nil {
|
||||
t.Fatal("expected no error; get", err)
|
||||
}
|
||||
|
||||
getString, err := f.GetString("stringFlag")
|
||||
if err != nil {
|
||||
t.Fatal("expected no error; get", err)
|
||||
}
|
||||
if getString != "bob" {
|
||||
t.Fatalf("expected getString=bob but got getString=%s", getString)
|
||||
}
|
||||
|
||||
getBool, err := f.GetBool("boolFlag")
|
||||
if err != nil {
|
||||
t.Fatal("expected no error; get", err)
|
||||
}
|
||||
if getBool != true {
|
||||
t.Fatalf("expected getBool=true but got getBool=%v", getBool)
|
||||
}
|
||||
}
|
||||
165
vendor/github.com/spf13/pflag/int_slice_test.go
сгенерированный
поставляемый
165
vendor/github.com/spf13/pflag/int_slice_test.go
сгенерированный
поставляемый
@@ -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)
|
||||
}
|
||||
}
|
||||
}
|
||||
222
vendor/github.com/spf13/pflag/ip_slice_test.go
сгенерированный
поставляемый
222
vendor/github.com/spf13/pflag/ip_slice_test.go
сгенерированный
поставляемый
@@ -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)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
63
vendor/github.com/spf13/pflag/ip_test.go
сгенерированный
поставляемый
63
vendor/github.com/spf13/pflag/ip_test.go
сгенерированный
поставляемый
@@ -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())
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
70
vendor/github.com/spf13/pflag/ipnet_test.go
сгенерированный
поставляемый
70
vendor/github.com/spf13/pflag/ipnet_test.go
сгенерированный
поставляемый
@@ -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())
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
8
vendor/github.com/spf13/pflag/string_array.go
сгенерированный
поставляемый
8
vendor/github.com/spf13/pflag/string_array.go
сгенерированный
поставляемый
@@ -52,7 +52,7 @@ func (f *FlagSet) GetStringArray(name string) ([]string, error) {
|
||||
|
||||
// StringArrayVar defines a string flag with specified name, default value, and usage string.
|
||||
// The argument p points to a []string variable in which to store the values of the multiple flags.
|
||||
// The value of each argument will not try to be separated by comma
|
||||
// The value of each argument will not try to be separated by comma. Use a StringSlice for that.
|
||||
func (f *FlagSet) StringArrayVar(p *[]string, name string, value []string, usage string) {
|
||||
f.VarP(newStringArrayValue(value, p), name, "", usage)
|
||||
}
|
||||
@@ -64,7 +64,7 @@ func (f *FlagSet) StringArrayVarP(p *[]string, name, shorthand string, value []s
|
||||
|
||||
// StringArrayVar defines a string flag with specified name, default value, and usage string.
|
||||
// The argument p points to a []string variable in which to store the value of the flag.
|
||||
// The value of each argument will not try to be separated by comma
|
||||
// The value of each argument will not try to be separated by comma. Use a StringSlice for that.
|
||||
func StringArrayVar(p *[]string, name string, value []string, usage string) {
|
||||
CommandLine.VarP(newStringArrayValue(value, p), name, "", usage)
|
||||
}
|
||||
@@ -76,7 +76,7 @@ func StringArrayVarP(p *[]string, name, shorthand string, value []string, usage
|
||||
|
||||
// StringArray defines a string flag with specified name, default value, and usage string.
|
||||
// The return value is the address of a []string variable that stores the value of the flag.
|
||||
// The value of each argument will not try to be separated by comma
|
||||
// The value of each argument will not try to be separated by comma. Use a StringSlice for that.
|
||||
func (f *FlagSet) StringArray(name string, value []string, usage string) *[]string {
|
||||
p := []string{}
|
||||
f.StringArrayVarP(&p, name, "", value, usage)
|
||||
@@ -92,7 +92,7 @@ func (f *FlagSet) StringArrayP(name, shorthand string, value []string, usage str
|
||||
|
||||
// StringArray defines a string flag with specified name, default value, and usage string.
|
||||
// The return value is the address of a []string variable that stores the value of the flag.
|
||||
// The value of each argument will not try to be separated by comma
|
||||
// The value of each argument will not try to be separated by comma. Use a StringSlice for that.
|
||||
func StringArray(name string, value []string, usage string) *[]string {
|
||||
return CommandLine.StringArrayP(name, "", value, usage)
|
||||
}
|
||||
|
||||
233
vendor/github.com/spf13/pflag/string_array_test.go
сгенерированный
поставляемый
233
vendor/github.com/spf13/pflag/string_array_test.go
сгенерированный
поставляемый
@@ -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)
|
||||
}
|
||||
}
|
||||
}
|
||||
20
vendor/github.com/spf13/pflag/string_slice.go
сгенерированный
поставляемый
20
vendor/github.com/spf13/pflag/string_slice.go
сгенерированный
поставляемый
@@ -82,6 +82,11 @@ func (f *FlagSet) GetStringSlice(name string) ([]string, error) {
|
||||
|
||||
// StringSliceVar defines a string flag with specified name, default value, and usage string.
|
||||
// The argument p points to a []string variable in which to store the value of the flag.
|
||||
// Compared to StringArray flags, StringSlice flags take comma-separated value as arguments and split them accordingly.
|
||||
// For example:
|
||||
// --ss="v1,v2" -ss="v3"
|
||||
// will result in
|
||||
// []string{"v1", "v2", "v3"}
|
||||
func (f *FlagSet) StringSliceVar(p *[]string, name string, value []string, usage string) {
|
||||
f.VarP(newStringSliceValue(value, p), name, "", usage)
|
||||
}
|
||||
@@ -93,6 +98,11 @@ func (f *FlagSet) StringSliceVarP(p *[]string, name, shorthand string, value []s
|
||||
|
||||
// StringSliceVar defines a string flag with specified name, default value, and usage string.
|
||||
// The argument p points to a []string variable in which to store the value of the flag.
|
||||
// Compared to StringArray flags, StringSlice flags take comma-separated value as arguments and split them accordingly.
|
||||
// For example:
|
||||
// --ss="v1,v2" -ss="v3"
|
||||
// will result in
|
||||
// []string{"v1", "v2", "v3"}
|
||||
func StringSliceVar(p *[]string, name string, value []string, usage string) {
|
||||
CommandLine.VarP(newStringSliceValue(value, p), name, "", usage)
|
||||
}
|
||||
@@ -104,6 +114,11 @@ func StringSliceVarP(p *[]string, name, shorthand string, value []string, usage
|
||||
|
||||
// StringSlice defines a string flag with specified name, default value, and usage string.
|
||||
// The return value is the address of a []string variable that stores the value of the flag.
|
||||
// Compared to StringArray flags, StringSlice flags take comma-separated value as arguments and split them accordingly.
|
||||
// For example:
|
||||
// --ss="v1,v2" -ss="v3"
|
||||
// will result in
|
||||
// []string{"v1", "v2", "v3"}
|
||||
func (f *FlagSet) StringSlice(name string, value []string, usage string) *[]string {
|
||||
p := []string{}
|
||||
f.StringSliceVarP(&p, name, "", value, usage)
|
||||
@@ -119,6 +134,11 @@ func (f *FlagSet) StringSliceP(name, shorthand string, value []string, usage str
|
||||
|
||||
// StringSlice defines a string flag with specified name, default value, and usage string.
|
||||
// The return value is the address of a []string variable that stores the value of the flag.
|
||||
// Compared to StringArray flags, StringSlice flags take comma-separated value as arguments and split them accordingly.
|
||||
// For example:
|
||||
// --ss="v1,v2" -ss="v3"
|
||||
// will result in
|
||||
// []string{"v1", "v2", "v3"}
|
||||
func StringSlice(name string, value []string, usage string) *[]string {
|
||||
return CommandLine.StringSliceP(name, "", value, usage)
|
||||
}
|
||||
|
||||
253
vendor/github.com/spf13/pflag/string_slice_test.go
сгенерированный
поставляемый
253
vendor/github.com/spf13/pflag/string_slice_test.go
сгенерированный
поставляемый
@@ -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)
|
||||
}
|
||||
}
|
||||
}
|
||||
161
vendor/github.com/spf13/pflag/uint_slice_test.go
сгенерированный
поставляемый
161
vendor/github.com/spf13/pflag/uint_slice_test.go
сгенерированный
поставляемый
@@ -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)
|
||||
}
|
||||
}
|
||||
}
|
||||
69
vendor/github.com/spf13/pflag/verify/all.sh
сгенерированный
поставляемый
69
vendor/github.com/spf13/pflag/verify/all.sh
сгенерированный
поставляемый
@@ -1,69 +0,0 @@
|
||||
#!/bin/bash
|
||||
|
||||
set -o errexit
|
||||
set -o nounset
|
||||
set -o pipefail
|
||||
|
||||
ROOT=$(dirname "${BASH_SOURCE}")/..
|
||||
|
||||
# Some useful colors.
|
||||
if [[ -z "${color_start-}" ]]; then
|
||||
declare -r color_start="\033["
|
||||
declare -r color_red="${color_start}0;31m"
|
||||
declare -r color_yellow="${color_start}0;33m"
|
||||
declare -r color_green="${color_start}0;32m"
|
||||
declare -r color_norm="${color_start}0m"
|
||||
fi
|
||||
|
||||
SILENT=true
|
||||
|
||||
function is-excluded {
|
||||
for e in $EXCLUDE; do
|
||||
if [[ $1 -ef ${BASH_SOURCE} ]]; then
|
||||
return
|
||||
fi
|
||||
if [[ $1 -ef "$ROOT/hack/$e" ]]; then
|
||||
return
|
||||
fi
|
||||
done
|
||||
return 1
|
||||
}
|
||||
|
||||
while getopts ":v" opt; do
|
||||
case $opt in
|
||||
v)
|
||||
SILENT=false
|
||||
;;
|
||||
\?)
|
||||
echo "Invalid flag: -$OPTARG" >&2
|
||||
exit 1
|
||||
;;
|
||||
esac
|
||||
done
|
||||
|
||||
if $SILENT ; then
|
||||
echo "Running in the silent mode, run with -v if you want to see script logs."
|
||||
fi
|
||||
|
||||
EXCLUDE="all.sh"
|
||||
|
||||
ret=0
|
||||
for t in `ls $ROOT/verify/*.sh`
|
||||
do
|
||||
if is-excluded $t ; then
|
||||
echo "Skipping $t"
|
||||
continue
|
||||
fi
|
||||
if $SILENT ; then
|
||||
echo -e "Verifying $t"
|
||||
if bash "$t" &> /dev/null; then
|
||||
echo -e "${color_green}SUCCESS${color_norm}"
|
||||
else
|
||||
echo -e "${color_red}FAILED${color_norm}"
|
||||
ret=1
|
||||
fi
|
||||
else
|
||||
bash "$t" || ret=1
|
||||
fi
|
||||
done
|
||||
exit $ret
|
||||
19
vendor/github.com/spf13/pflag/verify/gofmt.sh
сгенерированный
поставляемый
19
vendor/github.com/spf13/pflag/verify/gofmt.sh
сгенерированный
поставляемый
@@ -1,19 +0,0 @@
|
||||
#!/bin/bash
|
||||
|
||||
set -o errexit
|
||||
set -o nounset
|
||||
set -o pipefail
|
||||
|
||||
ROOT=$(dirname "${BASH_SOURCE}")/..
|
||||
|
||||
pushd "${ROOT}" > /dev/null
|
||||
|
||||
GOFMT=${GOFMT:-"gofmt"}
|
||||
bad_files=$(find . -name '*.go' | xargs $GOFMT -s -l)
|
||||
if [[ -n "${bad_files}" ]]; then
|
||||
echo "!!! '$GOFMT' needs to be run on the following files: "
|
||||
echo "${bad_files}"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# ex: ts=2 sw=2 et filetype=sh
|
||||
15
vendor/github.com/spf13/pflag/verify/golint.sh
сгенерированный
поставляемый
15
vendor/github.com/spf13/pflag/verify/golint.sh
сгенерированный
поставляемый
@@ -1,15 +0,0 @@
|
||||
#!/bin/bash
|
||||
|
||||
ROOT=$(dirname "${BASH_SOURCE}")/..
|
||||
GOLINT=${GOLINT:-"golint"}
|
||||
|
||||
pushd "${ROOT}" > /dev/null
|
||||
bad_files=$($GOLINT -min_confidence=0.9 ./...)
|
||||
if [[ -n "${bad_files}" ]]; then
|
||||
echo "!!! '$GOLINT' problems: "
|
||||
echo "${bad_files}"
|
||||
exit 1
|
||||
fi
|
||||
popd > /dev/null
|
||||
|
||||
# ex: ts=2 sw=2 et filetype=sh
|
||||
65
vendor/github.com/spf13/viper/flags_test.go
сгенерированный
поставляемый
65
vendor/github.com/spf13/viper/flags_test.go
сгенерированный
поставляемый
@@ -1,65 +0,0 @@
|
||||
package viper
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/spf13/pflag"
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
func TestBindFlagValueSet(t *testing.T) {
|
||||
flagSet := pflag.NewFlagSet("test", pflag.ContinueOnError)
|
||||
|
||||
var testValues = map[string]*string{
|
||||
"host": nil,
|
||||
"port": nil,
|
||||
"endpoint": nil,
|
||||
}
|
||||
|
||||
var mutatedTestValues = map[string]string{
|
||||
"host": "localhost",
|
||||
"port": "6060",
|
||||
"endpoint": "/public",
|
||||
}
|
||||
|
||||
for name := range testValues {
|
||||
testValues[name] = flagSet.String(name, "", "test")
|
||||
}
|
||||
|
||||
flagValueSet := pflagValueSet{flagSet}
|
||||
|
||||
err := BindFlagValues(flagValueSet)
|
||||
if err != nil {
|
||||
t.Fatalf("error binding flag set, %v", err)
|
||||
}
|
||||
|
||||
flagSet.VisitAll(func(flag *pflag.Flag) {
|
||||
flag.Value.Set(mutatedTestValues[flag.Name])
|
||||
flag.Changed = true
|
||||
})
|
||||
|
||||
for name, expected := range mutatedTestValues {
|
||||
assert.Equal(t, Get(name), expected)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBindFlagValue(t *testing.T) {
|
||||
var testString = "testing"
|
||||
var testValue = newStringValue(testString, &testString)
|
||||
|
||||
flag := &pflag.Flag{
|
||||
Name: "testflag",
|
||||
Value: testValue,
|
||||
Changed: false,
|
||||
}
|
||||
|
||||
flagValue := pflagValue{flag}
|
||||
BindFlagValue("testvalue", flagValue)
|
||||
|
||||
assert.Equal(t, testString, Get("testvalue"))
|
||||
|
||||
flag.Value.Set("testing_mutate")
|
||||
flag.Changed = true //hack for pflag usage
|
||||
|
||||
assert.Equal(t, "testing_mutate", Get("testvalue"))
|
||||
}
|
||||
173
vendor/github.com/spf13/viper/overrides_test.go
сгенерированный
поставляемый
173
vendor/github.com/spf13/viper/overrides_test.go
сгенерированный
поставляемый
@@ -1,173 +0,0 @@
|
||||
package viper
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/spf13/cast"
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
type layer int
|
||||
|
||||
const (
|
||||
defaultLayer layer = iota + 1
|
||||
overrideLayer
|
||||
)
|
||||
|
||||
func TestNestedOverrides(t *testing.T) {
|
||||
assert := assert.New(t)
|
||||
var v *Viper
|
||||
|
||||
// Case 0: value overridden by a value
|
||||
overrideDefault(assert, "tom", 10, "tom", 20) // "tom" is first given 10 as default value, then overridden by 20
|
||||
override(assert, "tom", 10, "tom", 20) // "tom" is first given value 10, then overridden by 20
|
||||
overrideDefault(assert, "tom.age", 10, "tom.age", 20)
|
||||
override(assert, "tom.age", 10, "tom.age", 20)
|
||||
overrideDefault(assert, "sawyer.tom.age", 10, "sawyer.tom.age", 20)
|
||||
override(assert, "sawyer.tom.age", 10, "sawyer.tom.age", 20)
|
||||
|
||||
// Case 1: key:value overridden by a value
|
||||
v = overrideDefault(assert, "tom.age", 10, "tom", "boy") // "tom.age" is first given 10 as default value, then "tom" is overridden by "boy"
|
||||
assert.Nil(v.Get("tom.age")) // "tom.age" should not exist anymore
|
||||
v = override(assert, "tom.age", 10, "tom", "boy")
|
||||
assert.Nil(v.Get("tom.age"))
|
||||
|
||||
// Case 2: value overridden by a key:value
|
||||
overrideDefault(assert, "tom", "boy", "tom.age", 10) // "tom" is first given "boy" as default value, then "tom" is overridden by map{"age":10}
|
||||
override(assert, "tom.age", 10, "tom", "boy")
|
||||
|
||||
// Case 3: key:value overridden by a key:value
|
||||
v = overrideDefault(assert, "tom.size", 4, "tom.age", 10)
|
||||
assert.Equal(4, v.Get("tom.size")) // value should still be reachable
|
||||
v = override(assert, "tom.size", 4, "tom.age", 10)
|
||||
assert.Equal(4, v.Get("tom.size"))
|
||||
deepCheckValue(assert, v, overrideLayer, []string{"tom", "size"}, 4)
|
||||
|
||||
// Case 4: key:value overridden by a map
|
||||
v = overrideDefault(assert, "tom.size", 4, "tom", map[string]interface{}{"age": 10}) // "tom.size" is first given "4" as default value, then "tom" is overridden by map{"age":10}
|
||||
assert.Equal(4, v.Get("tom.size")) // "tom.size" should still be reachable
|
||||
assert.Equal(10, v.Get("tom.age")) // new value should be there
|
||||
deepCheckValue(assert, v, overrideLayer, []string{"tom", "age"}, 10) // new value should be there
|
||||
v = override(assert, "tom.size", 4, "tom", map[string]interface{}{"age": 10})
|
||||
assert.Nil(v.Get("tom.size"))
|
||||
assert.Equal(10, v.Get("tom.age"))
|
||||
deepCheckValue(assert, v, overrideLayer, []string{"tom", "age"}, 10)
|
||||
|
||||
// Case 5: array overridden by a value
|
||||
overrideDefault(assert, "tom", []int{10, 20}, "tom", 30)
|
||||
override(assert, "tom", []int{10, 20}, "tom", 30)
|
||||
overrideDefault(assert, "tom.age", []int{10, 20}, "tom.age", 30)
|
||||
override(assert, "tom.age", []int{10, 20}, "tom.age", 30)
|
||||
|
||||
// Case 6: array overridden by an array
|
||||
overrideDefault(assert, "tom", []int{10, 20}, "tom", []int{30, 40})
|
||||
override(assert, "tom", []int{10, 20}, "tom", []int{30, 40})
|
||||
overrideDefault(assert, "tom.age", []int{10, 20}, "tom.age", []int{30, 40})
|
||||
v = override(assert, "tom.age", []int{10, 20}, "tom.age", []int{30, 40})
|
||||
// explicit array merge:
|
||||
s, ok := v.Get("tom.age").([]int)
|
||||
if assert.True(ok, "tom[\"age\"] is not a slice") {
|
||||
v.Set("tom.age", append(s, []int{50, 60}...))
|
||||
assert.Equal([]int{30, 40, 50, 60}, v.Get("tom.age"))
|
||||
deepCheckValue(assert, v, overrideLayer, []string{"tom", "age"}, []int{30, 40, 50, 60})
|
||||
}
|
||||
}
|
||||
|
||||
func overrideDefault(assert *assert.Assertions, firstPath string, firstValue interface{}, secondPath string, secondValue interface{}) *Viper {
|
||||
return overrideFromLayer(defaultLayer, assert, firstPath, firstValue, secondPath, secondValue)
|
||||
}
|
||||
func override(assert *assert.Assertions, firstPath string, firstValue interface{}, secondPath string, secondValue interface{}) *Viper {
|
||||
return overrideFromLayer(overrideLayer, assert, firstPath, firstValue, secondPath, secondValue)
|
||||
}
|
||||
|
||||
// overrideFromLayer performs the sequential override and low-level checks.
|
||||
//
|
||||
// First assignment is made on layer l for path firstPath with value firstValue,
|
||||
// the second one on the override layer (i.e., with the Set() function)
|
||||
// for path secondPath with value secondValue.
|
||||
//
|
||||
// firstPath and secondPath can include an arbitrary number of dots to indicate
|
||||
// a nested element.
|
||||
//
|
||||
// After each assignment, the value is checked, retrieved both by its full path
|
||||
// and by its key sequence (successive maps).
|
||||
func overrideFromLayer(l layer, assert *assert.Assertions, firstPath string, firstValue interface{}, secondPath string, secondValue interface{}) *Viper {
|
||||
v := New()
|
||||
firstKeys := strings.Split(firstPath, v.keyDelim)
|
||||
if assert == nil ||
|
||||
len(firstKeys) == 0 || len(firstKeys[0]) == 0 {
|
||||
return v
|
||||
}
|
||||
|
||||
// Set and check first value
|
||||
switch l {
|
||||
case defaultLayer:
|
||||
v.SetDefault(firstPath, firstValue)
|
||||
case overrideLayer:
|
||||
v.Set(firstPath, firstValue)
|
||||
default:
|
||||
return v
|
||||
}
|
||||
assert.Equal(firstValue, v.Get(firstPath))
|
||||
deepCheckValue(assert, v, l, firstKeys, firstValue)
|
||||
|
||||
// Override and check new value
|
||||
secondKeys := strings.Split(secondPath, v.keyDelim)
|
||||
if len(secondKeys) == 0 || len(secondKeys[0]) == 0 {
|
||||
return v
|
||||
}
|
||||
v.Set(secondPath, secondValue)
|
||||
assert.Equal(secondValue, v.Get(secondPath))
|
||||
deepCheckValue(assert, v, overrideLayer, secondKeys, secondValue)
|
||||
|
||||
return v
|
||||
}
|
||||
|
||||
// deepCheckValue checks that all given keys correspond to a valid path in the
|
||||
// configuration map of the given layer, and that the final value equals the one given
|
||||
func deepCheckValue(assert *assert.Assertions, v *Viper, l layer, keys []string, value interface{}) {
|
||||
if assert == nil || v == nil ||
|
||||
len(keys) == 0 || len(keys[0]) == 0 {
|
||||
return
|
||||
}
|
||||
|
||||
// init
|
||||
var val interface{}
|
||||
var ms string
|
||||
switch l {
|
||||
case defaultLayer:
|
||||
val = v.defaults
|
||||
ms = "v.defaults"
|
||||
case overrideLayer:
|
||||
val = v.override
|
||||
ms = "v.override"
|
||||
}
|
||||
|
||||
// loop through map
|
||||
var m map[string]interface{}
|
||||
err := false
|
||||
for _, k := range keys {
|
||||
if val == nil {
|
||||
assert.Fail(fmt.Sprintf("%s is not a map[string]interface{}", ms))
|
||||
return
|
||||
}
|
||||
|
||||
// deep scan of the map to get the final value
|
||||
switch val.(type) {
|
||||
case map[interface{}]interface{}:
|
||||
m = cast.ToStringMap(val)
|
||||
case map[string]interface{}:
|
||||
m = val.(map[string]interface{})
|
||||
default:
|
||||
assert.Fail(fmt.Sprintf("%s is not a map[string]interface{}", ms))
|
||||
return
|
||||
}
|
||||
ms = ms + "[\"" + k + "\"]"
|
||||
val = m[k]
|
||||
}
|
||||
if !err {
|
||||
assert.Equal(value, val)
|
||||
}
|
||||
}
|
||||
105
vendor/github.com/spf13/viper/remote/remote.go
сгенерированный
поставляемый
105
vendor/github.com/spf13/viper/remote/remote.go
сгенерированный
поставляемый
@@ -1,105 +0,0 @@
|
||||
// Copyright © 2015 Steve Francia <spf@spf13.com>.
|
||||
//
|
||||
// Use of this source code is governed by an MIT-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
// Package remote integrates the remote features of Viper.
|
||||
package remote
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"io"
|
||||
"os"
|
||||
|
||||
"github.com/spf13/viper"
|
||||
crypt "github.com/xordataexchange/crypt/config"
|
||||
)
|
||||
|
||||
type remoteConfigProvider struct{}
|
||||
|
||||
func (rc remoteConfigProvider) Get(rp viper.RemoteProvider) (io.Reader, error) {
|
||||
cm, err := getConfigManager(rp)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
b, err := cm.Get(rp.Path())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return bytes.NewReader(b), nil
|
||||
}
|
||||
|
||||
func (rc remoteConfigProvider) Watch(rp viper.RemoteProvider) (io.Reader, error) {
|
||||
cm, err := getConfigManager(rp)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
resp, err := cm.Get(rp.Path())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return bytes.NewReader(resp), nil
|
||||
}
|
||||
|
||||
func (rc remoteConfigProvider) WatchChannel(rp viper.RemoteProvider) (<-chan *viper.RemoteResponse, chan bool) {
|
||||
cm, err := getConfigManager(rp)
|
||||
if err != nil {
|
||||
return nil, nil
|
||||
}
|
||||
quit := make(chan bool)
|
||||
quitwc := make(chan bool)
|
||||
viperResponsCh := make(chan *viper.RemoteResponse)
|
||||
cryptoResponseCh := cm.Watch(rp.Path(), quit)
|
||||
// need this function to convert the Channel response form crypt.Response to viper.Response
|
||||
go func(cr <-chan *crypt.Response, vr chan<- *viper.RemoteResponse, quitwc <-chan bool, quit chan<- bool) {
|
||||
for {
|
||||
select {
|
||||
case <-quitwc:
|
||||
quit <- true
|
||||
return
|
||||
case resp := <-cr:
|
||||
vr <- &viper.RemoteResponse{
|
||||
Error: resp.Error,
|
||||
Value: resp.Value,
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
}(cryptoResponseCh, viperResponsCh, quitwc, quit)
|
||||
|
||||
return viperResponsCh, quitwc
|
||||
}
|
||||
|
||||
func getConfigManager(rp viper.RemoteProvider) (crypt.ConfigManager, error) {
|
||||
var cm crypt.ConfigManager
|
||||
var err error
|
||||
|
||||
if rp.SecretKeyring() != "" {
|
||||
kr, err := os.Open(rp.SecretKeyring())
|
||||
defer kr.Close()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if rp.Provider() == "etcd" {
|
||||
cm, err = crypt.NewEtcdConfigManager([]string{rp.Endpoint()}, kr)
|
||||
} else {
|
||||
cm, err = crypt.NewConsulConfigManager([]string{rp.Endpoint()}, kr)
|
||||
}
|
||||
} else {
|
||||
if rp.Provider() == "etcd" {
|
||||
cm, err = crypt.NewStandardEtcdConfigManager([]string{rp.Endpoint()})
|
||||
} else {
|
||||
cm, err = crypt.NewStandardConsulConfigManager([]string{rp.Endpoint()})
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return cm, nil
|
||||
}
|
||||
|
||||
func init() {
|
||||
viper.RemoteConfig = &remoteConfigProvider{}
|
||||
}
|
||||
54
vendor/github.com/spf13/viper/util_test.go
сгенерированный
поставляемый
54
vendor/github.com/spf13/viper/util_test.go
сгенерированный
поставляемый
@@ -1,54 +0,0 @@
|
||||
// Copyright © 2016 Steve Francia <spf@spf13.com>.
|
||||
//
|
||||
// Use of this source code is governed by an MIT-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
// Viper is a application configuration system.
|
||||
// It believes that applications can be configured a variety of ways
|
||||
// via flags, ENVIRONMENT variables, configuration files retrieved
|
||||
// from the file system, or a remote key/value store.
|
||||
|
||||
package viper
|
||||
|
||||
import (
|
||||
"reflect"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestCopyAndInsensitiviseMap(t *testing.T) {
|
||||
var (
|
||||
given = map[string]interface{}{
|
||||
"Foo": 32,
|
||||
"Bar": map[interface{}]interface {
|
||||
}{
|
||||
"ABc": "A",
|
||||
"cDE": "B"},
|
||||
}
|
||||
expected = map[string]interface{}{
|
||||
"foo": 32,
|
||||
"bar": map[string]interface {
|
||||
}{
|
||||
"abc": "A",
|
||||
"cde": "B"},
|
||||
}
|
||||
)
|
||||
|
||||
got := copyAndInsensitiviseMap(given)
|
||||
|
||||
if !reflect.DeepEqual(got, expected) {
|
||||
t.Fatalf("Got %q\nexpected\n%q", got, expected)
|
||||
}
|
||||
|
||||
if _, ok := given["foo"]; ok {
|
||||
t.Fatal("Input map changed")
|
||||
}
|
||||
|
||||
if _, ok := given["bar"]; ok {
|
||||
t.Fatal("Input map changed")
|
||||
}
|
||||
|
||||
m := given["Bar"].(map[interface{}]interface{})
|
||||
if _, ok := m["ABc"]; !ok {
|
||||
t.Fatal("Input map changed")
|
||||
}
|
||||
}
|
||||
1406
vendor/github.com/spf13/viper/viper_test.go
сгенерированный
поставляемый
1406
vendor/github.com/spf13/viper/viper_test.go
сгенерированный
поставляемый
Разница между файлами не показана из-за своего большого размера
Загрузить разницу
Ссылка в новой задаче
Block a user