Upgrade server dependencies, manage them with govendor
This commit is contained in:
parent
ebee2746d6
commit
971278e7e5
1748 changed files with 196165 additions and 194500 deletions
174
vendor/github.com/spf13/afero/LICENSE.txt
generated
vendored
Normal file
174
vendor/github.com/spf13/afero/LICENSE.txt
generated
vendored
Normal file
|
@ -0,0 +1,174 @@
|
|||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
449
vendor/github.com/spf13/afero/README.md
generated
vendored
Normal file
449
vendor/github.com/spf13/afero/README.md
generated
vendored
Normal file
|
@ -0,0 +1,449 @@
|
|||

|
||||
|
||||
A FileSystem Abstraction System for Go
|
||||
|
||||
[](https://travis-ci.org/spf13/afero) [](https://ci.appveyor.com/project/spf13/afero) [](https://godoc.org/github.com/spf13/afero) [](https://gitter.im/spf13/afero?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
|
||||
|
||||
# Overview
|
||||
|
||||
Afero is an filesystem framework providing a simple, uniform and universal API
|
||||
interacting with any filesystem, as an abstraction layer providing interfaces,
|
||||
types and methods. Afero has an exceptionally clean interface and simple design
|
||||
without needless constructors or initialization methods.
|
||||
|
||||
Afero is also a library providing a base set of interoperable backend
|
||||
filesystems that make it easy to work with afero while retaining all the power
|
||||
and benefit of the os and ioutil packages.
|
||||
|
||||
Afero provides significant improvements over using the os package alone, most
|
||||
notably the ability to create mock and testing filesystems without relying on the disk.
|
||||
|
||||
It is suitable for use in a any situation where you would consider using the OS
|
||||
package as it provides an additional abstraction that makes it easy to use a
|
||||
memory backed file system during testing. It also adds support for the http
|
||||
filesystem for full interoperability.
|
||||
|
||||
|
||||
## Afero Features
|
||||
|
||||
* A single consistent API for accessing a variety of filesystems
|
||||
* Interoperation between a variety of file system types
|
||||
* A set of interfaces to encourage and enforce interoperability between backends
|
||||
* An atomic cross platform memory backed file system
|
||||
* Support for compositional (union) file systems by combining multiple file systems acting as one
|
||||
* Specialized backends which modify existing filesystems (Read Only, Regexp filtered)
|
||||
* A set of utility functions ported from io, ioutil & hugo to be afero aware
|
||||
|
||||
|
||||
# Using Afero
|
||||
|
||||
Afero is easy to use and easier to adopt.
|
||||
|
||||
A few different ways you could use Afero:
|
||||
|
||||
* Use the interfaces alone to define you own file system.
|
||||
* Wrap for the OS packages.
|
||||
* Define different filesystems for different parts of your application.
|
||||
* Use Afero for mock filesystems while testing
|
||||
|
||||
## Step 1: Install Afero
|
||||
|
||||
First use go get to install the latest version of the library.
|
||||
|
||||
$ go get github.com/spf13/afero
|
||||
|
||||
Next include Afero in your application.
|
||||
```go
|
||||
import "github.com/spf13/afero"
|
||||
```
|
||||
|
||||
## Step 2: Declare a backend
|
||||
|
||||
First define a package variable and set it to a pointer to a filesystem.
|
||||
```go
|
||||
var AppFs afero.Fs = afero.NewMemMapFs()
|
||||
|
||||
or
|
||||
|
||||
var AppFs afero.Fs = afero.NewOsFs()
|
||||
```
|
||||
It is important to note that if you repeat the composite literal you
|
||||
will be using a completely new and isolated filesystem. In the case of
|
||||
OsFs it will still use the same underlying filesystem but will reduce
|
||||
the ability to drop in other filesystems as desired.
|
||||
|
||||
## Step 3: Use it like you would the OS package
|
||||
|
||||
Throughout your application use any function and method like you normally
|
||||
would.
|
||||
|
||||
So if my application before had:
|
||||
```go
|
||||
os.Open('/tmp/foo')
|
||||
```
|
||||
We would replace it with a call to `AppFs.Open('/tmp/foo')`.
|
||||
|
||||
`AppFs` being the variable we defined above.
|
||||
|
||||
|
||||
## List of all available functions
|
||||
|
||||
File System Methods Available:
|
||||
```go
|
||||
Chmod(name string, mode os.FileMode) : error
|
||||
Chtimes(name string, atime time.Time, mtime time.Time) : error
|
||||
Create(name string) : File, error
|
||||
Mkdir(name string, perm os.FileMode) : error
|
||||
MkdirAll(path string, perm os.FileMode) : error
|
||||
Name() : string
|
||||
Open(name string) : File, error
|
||||
OpenFile(name string, flag int, perm os.FileMode) : File, error
|
||||
Remove(name string) : error
|
||||
RemoveAll(path string) : error
|
||||
Rename(oldname, newname string) : error
|
||||
Stat(name string) : os.FileInfo, error
|
||||
```
|
||||
File Interfaces and Methods Available:
|
||||
```go
|
||||
io.Closer
|
||||
io.Reader
|
||||
io.ReaderAt
|
||||
io.Seeker
|
||||
io.Writer
|
||||
io.WriterAt
|
||||
|
||||
Name() : string
|
||||
Readdir(count int) : []os.FileInfo, error
|
||||
Readdirnames(n int) : []string, error
|
||||
Stat() : os.FileInfo, error
|
||||
Sync() : error
|
||||
Truncate(size int64) : error
|
||||
WriteString(s string) : ret int, err error
|
||||
```
|
||||
In some applications it may make sense to define a new package that
|
||||
simply exports the file system variable for easy access from anywhere.
|
||||
|
||||
## Using Afero's utility functions
|
||||
|
||||
Afero provides a set of functions to make it easier to use the underlying file systems.
|
||||
These functions have been primarily ported from io & ioutil with some developed for Hugo.
|
||||
|
||||
The afero utilities support all afero compatible backends.
|
||||
|
||||
The list of utilities includes:
|
||||
|
||||
```go
|
||||
DirExists(path string) (bool, error)
|
||||
Exists(path string) (bool, error)
|
||||
FileContainsBytes(filename string, subslice []byte) (bool, error)
|
||||
GetTempDir(subPath string) string
|
||||
IsDir(path string) (bool, error)
|
||||
IsEmpty(path string) (bool, error)
|
||||
ReadDir(dirname string) ([]os.FileInfo, error)
|
||||
ReadFile(filename string) ([]byte, error)
|
||||
SafeWriteReader(path string, r io.Reader) (err error)
|
||||
TempDir(dir, prefix string) (name string, err error)
|
||||
TempFile(dir, prefix string) (f File, err error)
|
||||
Walk(root string, walkFn filepath.WalkFunc) error
|
||||
WriteFile(filename string, data []byte, perm os.FileMode) error
|
||||
WriteReader(path string, r io.Reader) (err error)
|
||||
```
|
||||
For a complete list see [Afero's GoDoc](https://godoc.org/github.com/spf13/afero)
|
||||
|
||||
They are available under two different approaches to use. You can either call
|
||||
them directly where the first parameter of each function will be the file
|
||||
system, or you can declare a new `Afero`, a custom type used to bind these
|
||||
functions as methods to a given filesystem.
|
||||
|
||||
### Calling utilities directly
|
||||
|
||||
```go
|
||||
fs := new(afero.MemMapFs)
|
||||
f, err := afero.TempFile(fs,"", "ioutil-test")
|
||||
|
||||
```
|
||||
|
||||
### Calling via Afero
|
||||
|
||||
```go
|
||||
fs := afero.NewMemMapFs
|
||||
afs := &Afero{Fs: fs}
|
||||
f, err := afs.TempFile("", "ioutil-test")
|
||||
```
|
||||
|
||||
## Using Afero for Testing
|
||||
|
||||
There is a large benefit to using a mock filesystem for testing. It has a
|
||||
completely blank state every time it is initialized and can be easily
|
||||
reproducible regardless of OS. You could create files to your heart’s content
|
||||
and the file access would be fast while also saving you from all the annoying
|
||||
issues with deleting temporary files, Windows file locking, etc. The MemMapFs
|
||||
backend is perfect for testing.
|
||||
|
||||
* Much faster than performing I/O operations on disk
|
||||
* Avoid security issues and permissions
|
||||
* Far more control. 'rm -rf /' with confidence
|
||||
* Test setup is far more easier to do
|
||||
* No test cleanup needed
|
||||
|
||||
One way to accomplish this is to define a variable as mentioned above.
|
||||
In your application this will be set to afero.NewOsFs() during testing you
|
||||
can set it to afero.NewMemMapFs().
|
||||
|
||||
It wouldn't be uncommon to have each test initialize a blank slate memory
|
||||
backend. To do this I would define my `appFS = afero.NewOsFs()` somewhere
|
||||
appropriate in my application code. This approach ensures that Tests are order
|
||||
independent, with no test relying on the state left by an earlier test.
|
||||
|
||||
Then in my tests I would initialize a new MemMapFs for each test:
|
||||
```go
|
||||
func TestExist(t *testing.T) {
|
||||
appFS := afero.NewMemMapFs()
|
||||
// create test files and directories
|
||||
appFS.MkdirAll("src/a", 0755)
|
||||
afero.WriteFile(appFS, "src/a/b", []byte("file b"), 0644)
|
||||
afero.WriteFile(appFS, "src/c", []byte("file c"), 0644)
|
||||
name := "src/c"
|
||||
_, err := appFS.Stat(name)
|
||||
if os.IsNotExist(err) {
|
||||
t.Errorf("file \"%s\" does not exist.\n", name)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
# Available Backends
|
||||
|
||||
## Operating System Native
|
||||
|
||||
### OsFs
|
||||
|
||||
The first is simply a wrapper around the native OS calls. This makes it
|
||||
very easy to use as all of the calls are the same as the existing OS
|
||||
calls. It also makes it trivial to have your code use the OS during
|
||||
operation and a mock filesystem during testing or as needed.
|
||||
|
||||
```go
|
||||
appfs := afero.NewOsFs()
|
||||
appfs.MkdirAll("src/a", 0755))
|
||||
```
|
||||
|
||||
## Memory Backed Storage
|
||||
|
||||
### MemMapFs
|
||||
|
||||
Afero also provides a fully atomic memory backed filesystem perfect for use in
|
||||
mocking and to speed up unnecessary disk io when persistence isn’t
|
||||
necessary. It is fully concurrent and will work within go routines
|
||||
safely.
|
||||
|
||||
```go
|
||||
mm := afero.NewMemMapFs()
|
||||
mm.MkdirAll("src/a", 0755))
|
||||
```
|
||||
|
||||
#### InMemoryFile
|
||||
|
||||
As part of MemMapFs, Afero also provides an atomic, fully concurrent memory
|
||||
backed file implementation. This can be used in other memory backed file
|
||||
systems with ease. Plans are to add a radix tree memory stored file
|
||||
system using InMemoryFile.
|
||||
|
||||
## Network Interfaces
|
||||
|
||||
### SftpFs
|
||||
|
||||
Afero has experimental support for secure file transfer protocol (sftp). Which can
|
||||
be used to perform file operations over a encrypted channel.
|
||||
|
||||
## Filtering Backends
|
||||
|
||||
### BasePathFs
|
||||
|
||||
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 source Fs.
|
||||
|
||||
```go
|
||||
bp := afero.NewBasePathFs(afero.NewOsFs(), "/base/path")
|
||||
```
|
||||
|
||||
### ReadOnlyFs
|
||||
|
||||
A thin wrapper around the source Fs providing a read only view.
|
||||
|
||||
```go
|
||||
fs := afero.NewReadOnlyFs(afero.NewOsFs())
|
||||
_, err := fs.Create("/file.txt")
|
||||
// err = syscall.EPERM
|
||||
```
|
||||
|
||||
# RegexpFs
|
||||
|
||||
A filtered view on file names, any file NOT matching
|
||||
the passed regexp will be treated as non-existing.
|
||||
Files not matching the regexp provided will not be created.
|
||||
Directories are not filtered.
|
||||
|
||||
```go
|
||||
fs := afero.NewRegexpFs(afero.NewMemMapFs(), regexp.MustCompile(`\.txt$`))
|
||||
_, err := fs.Create("/file.html")
|
||||
// err = syscall.ENOENT
|
||||
```
|
||||
|
||||
### HttpFs
|
||||
|
||||
Afero provides an http compatible backend which can wrap any of the existing
|
||||
backends.
|
||||
|
||||
The Http package requires a slightly specific version of Open which
|
||||
returns an http.File type.
|
||||
|
||||
Afero provides an httpFs file system which satisfies this requirement.
|
||||
Any Afero FileSystem can be used as an httpFs.
|
||||
|
||||
```go
|
||||
httpFs := afero.NewHttpFs(<ExistingFS>)
|
||||
fileserver := http.FileServer(httpFs.Dir(<PATH>)))
|
||||
http.Handle("/", fileserver)
|
||||
```
|
||||
|
||||
## Composite Backends
|
||||
|
||||
Afero provides the ability have two filesystems (or more) act as a single
|
||||
file system.
|
||||
|
||||
### CacheOnReadFs
|
||||
|
||||
The CacheOnReadFs will lazily make copies of any accessed files from the base
|
||||
layer into the overlay. Subsequent reads will be pulled from the overlay
|
||||
directly permitting the request is within the cache duration of when it was
|
||||
created in the overlay.
|
||||
|
||||
If the base filesystem is writeable, any changes to files will be
|
||||
done first to the base, then to the overlay layer. Write calls to open file
|
||||
handles like `Write()` or `Truncate()` to the overlay first.
|
||||
|
||||
To writing files to the overlay only, you can use the overlay Fs directly (not
|
||||
via the union Fs).
|
||||
|
||||
Cache files in the layer for the given time.Duration, a cache duration of 0
|
||||
means "forever" meaning the file will not be re-requested from the base ever.
|
||||
|
||||
A read-only base will make the overlay also read-only but still copy files
|
||||
from the base to the overlay when they're not present (or outdated) in the
|
||||
caching layer.
|
||||
|
||||
```go
|
||||
base := afero.NewOsFs()
|
||||
layer := afero.NewMemMapFs()
|
||||
ufs := afero.NewCacheOnReadFs(base, layer, 100 * time.Second)
|
||||
```
|
||||
|
||||
### CopyOnWriteFs()
|
||||
|
||||
The CopyOnWriteFs is a read only base file system with a potentially
|
||||
writeable layer on top.
|
||||
|
||||
Read operations will first look in the overlay and if not found there, will
|
||||
serve the file from the base.
|
||||
|
||||
Changes to the file system will only be made in the overlay.
|
||||
|
||||
Any attempt to modify a file found only in the base will copy the file to the
|
||||
overlay layer before modification (including opening a file with a writable
|
||||
handle).
|
||||
|
||||
Removing and Renaming files present only in the base layer is not currently
|
||||
permitted. If a file is present in the base layer and the overlay, only the
|
||||
overlay will be removed/renamed.
|
||||
|
||||
```go
|
||||
base := afero.NewOsFs()
|
||||
roBase := afero.NewReadOnlyFs(base)
|
||||
ufs := afero.NewCopyOnWriteFs(roBase, afero.NewMemMapFs())
|
||||
|
||||
fh, _ = ufs.Create("/home/test/file2.txt")
|
||||
fh.WriteString("This is a test")
|
||||
fh.Close()
|
||||
```
|
||||
|
||||
In this example all write operations will only occur in memory (MemMapFs)
|
||||
leaving the base filesystem (OsFs) untouched.
|
||||
|
||||
|
||||
## Desired/possible backends
|
||||
|
||||
The following is a short list of possible backends we hope someone will
|
||||
implement:
|
||||
|
||||
* SSH
|
||||
* ZIP
|
||||
* TAR
|
||||
* S3
|
||||
|
||||
# About the project
|
||||
|
||||
## What's in the name
|
||||
|
||||
Afero comes from the latin roots Ad-Facere.
|
||||
|
||||
**"Ad"** is a prefix meaning "to".
|
||||
|
||||
**"Facere"** is a form of the root "faciō" making "make or do".
|
||||
|
||||
The literal meaning of afero is "to make" or "to do" which seems very fitting
|
||||
for a library that allows one to make files and directories and do things with them.
|
||||
|
||||
The English word that shares the same roots as Afero is "affair". Affair shares
|
||||
the same concept but as a noun it means "something that is made or done" or "an
|
||||
object of a particular type".
|
||||
|
||||
It's also nice that unlike some of my other libraries (hugo, cobra, viper) it
|
||||
Googles very well.
|
||||
|
||||
## Release Notes
|
||||
|
||||
* **0.10.0** 2015.12.10
|
||||
* Full compatibility with Windows
|
||||
* Introduction of afero utilities
|
||||
* Test suite rewritten to work cross platform
|
||||
* Normalize paths for MemMapFs
|
||||
* Adding Sync to the file interface
|
||||
* **Breaking Change** Walk and ReadDir have changed parameter order
|
||||
* Moving types used by MemMapFs to a subpackage
|
||||
* General bugfixes and improvements
|
||||
* **0.9.0** 2015.11.05
|
||||
* New Walk function similar to filepath.Walk
|
||||
* MemMapFs.OpenFile handles O_CREATE, O_APPEND, O_TRUNC
|
||||
* MemMapFs.Remove now really deletes the file
|
||||
* InMemoryFile.Readdir and Readdirnames work correctly
|
||||
* InMemoryFile functions lock it for concurrent access
|
||||
* Test suite improvements
|
||||
* **0.8.0** 2014.10.28
|
||||
* First public version
|
||||
* Interfaces feel ready for people to build using
|
||||
* Interfaces satisfy all known uses
|
||||
* MemMapFs passes the majority of the OS test suite
|
||||
* OsFs passes the majority of the OS test suite
|
||||
|
||||
## Contributing
|
||||
|
||||
1. Fork it
|
||||
2. Create your feature branch (`git checkout -b my-new-feature`)
|
||||
3. Commit your changes (`git commit -am 'Add some feature'`)
|
||||
4. Push to the branch (`git push origin my-new-feature`)
|
||||
5. Create new Pull Request
|
||||
|
||||
## Contributors
|
||||
|
||||
Names in no particular order:
|
||||
|
||||
* [spf13](https://github.com/spf13)
|
||||
* [jaqx0r](https://github.com/jaqx0r)
|
||||
* [mbertschler](https://github.com/mbertschler)
|
||||
* [xor-gate](https://github.com/xor-gate)
|
||||
|
||||
## License
|
||||
|
||||
Afero is released under the Apache 2.0 license. See
|
||||
[LICENSE.txt](https://github.com/spf13/afero/blob/master/LICENSE.txt)
|
108
vendor/github.com/spf13/afero/afero.go
generated
vendored
Normal file
108
vendor/github.com/spf13/afero/afero.go
generated
vendored
Normal file
|
@ -0,0 +1,108 @@
|
|||
// Copyright © 2014 Steve Francia <spf@spf13.com>.
|
||||
// Copyright 2013 tsuru 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 provides types and methods for interacting with the filesystem,
|
||||
// as an abstraction layer.
|
||||
|
||||
// Afero also provides a few implementations that are mostly interoperable. One that
|
||||
// uses the operating system filesystem, one that uses memory to store files
|
||||
// (cross platform) and an interface that should be implemented if you want to
|
||||
// provide your own filesystem.
|
||||
|
||||
package afero
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"io"
|
||||
"os"
|
||||
"time"
|
||||
)
|
||||
|
||||
type Afero struct {
|
||||
Fs
|
||||
}
|
||||
|
||||
// File represents a file in the filesystem.
|
||||
type File interface {
|
||||
io.Closer
|
||||
io.Reader
|
||||
io.ReaderAt
|
||||
io.Seeker
|
||||
io.Writer
|
||||
io.WriterAt
|
||||
|
||||
Name() string
|
||||
Readdir(count int) ([]os.FileInfo, error)
|
||||
Readdirnames(n int) ([]string, error)
|
||||
Stat() (os.FileInfo, error)
|
||||
Sync() error
|
||||
Truncate(size int64) error
|
||||
WriteString(s string) (ret int, err error)
|
||||
}
|
||||
|
||||
// Fs is the filesystem interface.
|
||||
//
|
||||
// Any simulated or real filesystem should implement this interface.
|
||||
type Fs interface {
|
||||
// Create creates a file in the filesystem, returning the file and an
|
||||
// error, if any happens.
|
||||
Create(name string) (File, error)
|
||||
|
||||
// Mkdir creates a directory in the filesystem, return an error if any
|
||||
// happens.
|
||||
Mkdir(name string, perm os.FileMode) error
|
||||
|
||||
// MkdirAll creates a directory path and all parents that does not exist
|
||||
// yet.
|
||||
MkdirAll(path string, perm os.FileMode) error
|
||||
|
||||
// Open opens a file, returning it or an error, if any happens.
|
||||
Open(name string) (File, error)
|
||||
|
||||
// OpenFile opens a file using the given flags and the given mode.
|
||||
OpenFile(name string, flag int, perm os.FileMode) (File, error)
|
||||
|
||||
// Remove removes a file identified by name, returning an error, if any
|
||||
// happens.
|
||||
Remove(name string) error
|
||||
|
||||
// RemoveAll removes a directory path and any children it contains. It
|
||||
// does not fail if the path does not exist (return nil).
|
||||
RemoveAll(path string) error
|
||||
|
||||
// Rename renames a file.
|
||||
Rename(oldname, newname string) error
|
||||
|
||||
// Stat returns a FileInfo describing the named file, or an error, if any
|
||||
// happens.
|
||||
Stat(name string) (os.FileInfo, error)
|
||||
|
||||
// The name of this FileSystem
|
||||
Name() string
|
||||
|
||||
//Chmod changes the mode of the named file to mode.
|
||||
Chmod(name string, mode os.FileMode) error
|
||||
|
||||
//Chtimes changes the access and modification times of the named file
|
||||
Chtimes(name string, atime time.Time, mtime time.Time) error
|
||||
}
|
||||
|
||||
var (
|
||||
ErrFileClosed = errors.New("File is closed")
|
||||
ErrOutOfRange = errors.New("Out of range")
|
||||
ErrTooLarge = errors.New("Too large")
|
||||
ErrFileNotFound = os.ErrNotExist
|
||||
ErrFileExists = os.ErrExist
|
||||
ErrDestinationExists = os.ErrExist
|
||||
)
|
15
vendor/github.com/spf13/afero/appveyor.yml
generated
vendored
Normal file
15
vendor/github.com/spf13/afero/appveyor.yml
generated
vendored
Normal file
|
@ -0,0 +1,15 @@
|
|||
version: '{build}'
|
||||
clone_folder: C:\gopath\src\github.com\spf13\afero
|
||||
environment:
|
||||
GOPATH: C:\gopath
|
||||
build_script:
|
||||
- cmd: >-
|
||||
go version
|
||||
|
||||
go env
|
||||
|
||||
go get -v github.com/spf13/afero/...
|
||||
|
||||
go build github.com/spf13/afero
|
||||
test_script:
|
||||
- cmd: go test -v github.com/spf13/afero
|
145
vendor/github.com/spf13/afero/basepath.go
generated
vendored
Normal file
145
vendor/github.com/spf13/afero/basepath.go
generated
vendored
Normal file
|
@ -0,0 +1,145 @@
|
|||
package afero
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// 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.
|
||||
// Any file name (after filepath.Clean()) outside this base path will be
|
||||
// treated as non existing file.
|
||||
//
|
||||
// Note that it does not clean the error messages on return, so you may
|
||||
// reveal the real path on errors.
|
||||
type BasePathFs struct {
|
||||
source Fs
|
||||
path string
|
||||
}
|
||||
|
||||
func NewBasePathFs(source Fs, path string) Fs {
|
||||
return &BasePathFs{source: source, path: path}
|
||||
}
|
||||
|
||||
// on a file outside the base path it returns the given file name and an error,
|
||||
// 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
|
||||
}
|
||||
|
||||
bpath := filepath.Clean(b.path)
|
||||
path = filepath.Clean(filepath.Join(bpath, name))
|
||||
if !strings.HasPrefix(path, bpath) {
|
||||
return name, os.ErrNotExist
|
||||
}
|
||||
|
||||
return path, nil
|
||||
}
|
||||
|
||||
func validateBasePathName(name string) error {
|
||||
if runtime.GOOS != "windows" {
|
||||
// Not much to do here;
|
||||
// the virtual file paths all look absolute on *nix.
|
||||
return nil
|
||||
}
|
||||
|
||||
// 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 nil
|
||||
}
|
||||
|
||||
func (b *BasePathFs) Chtimes(name string, atime, mtime time.Time) (err error) {
|
||||
if name, err = b.RealPath(name); err != nil {
|
||||
return &os.PathError{Op: "chtimes", Path: name, Err: err}
|
||||
}
|
||||
return b.source.Chtimes(name, atime, mtime)
|
||||
}
|
||||
|
||||
func (b *BasePathFs) Chmod(name string, mode os.FileMode) (err error) {
|
||||
if name, err = b.RealPath(name); err != nil {
|
||||
return &os.PathError{Op: "chmod", Path: name, Err: err}
|
||||
}
|
||||
return b.source.Chmod(name, mode)
|
||||
}
|
||||
|
||||
func (b *BasePathFs) Name() string {
|
||||
return "BasePathFs"
|
||||
}
|
||||
|
||||
func (b *BasePathFs) Stat(name string) (fi os.FileInfo, err error) {
|
||||
if name, err = b.RealPath(name); err != nil {
|
||||
return nil, &os.PathError{Op: "stat", Path: name, Err: err}
|
||||
}
|
||||
return b.source.Stat(name)
|
||||
}
|
||||
|
||||
func (b *BasePathFs) Rename(oldname, newname string) (err error) {
|
||||
if oldname, err = b.RealPath(oldname); err != nil {
|
||||
return &os.PathError{Op: "rename", Path: oldname, Err: err}
|
||||
}
|
||||
if newname, err = b.RealPath(newname); err != nil {
|
||||
return &os.PathError{Op: "rename", Path: newname, Err: err}
|
||||
}
|
||||
return b.source.Rename(oldname, newname)
|
||||
}
|
||||
|
||||
func (b *BasePathFs) RemoveAll(name string) (err error) {
|
||||
if name, err = b.RealPath(name); err != nil {
|
||||
return &os.PathError{Op: "remove_all", Path: name, Err: err}
|
||||
}
|
||||
return b.source.RemoveAll(name)
|
||||
}
|
||||
|
||||
func (b *BasePathFs) Remove(name string) (err error) {
|
||||
if name, err = b.RealPath(name); err != nil {
|
||||
return &os.PathError{Op: "remove", Path: name, Err: err}
|
||||
}
|
||||
return b.source.Remove(name)
|
||||
}
|
||||
|
||||
func (b *BasePathFs) OpenFile(name string, flag int, mode os.FileMode) (f File, err error) {
|
||||
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)
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
|
||||
func (b *BasePathFs) Mkdir(name string, mode os.FileMode) (err error) {
|
||||
if name, err = b.RealPath(name); err != nil {
|
||||
return &os.PathError{Op: "mkdir", Path: name, Err: err}
|
||||
}
|
||||
return b.source.Mkdir(name, mode)
|
||||
}
|
||||
|
||||
func (b *BasePathFs) MkdirAll(name string, mode os.FileMode) (err error) {
|
||||
if name, err = b.RealPath(name); err != nil {
|
||||
return &os.PathError{Op: "mkdir", Path: name, Err: err}
|
||||
}
|
||||
return b.source.MkdirAll(name, mode)
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
|
||||
// vim: ts=4 sw=4 noexpandtab nolist syn=go
|
295
vendor/github.com/spf13/afero/cacheOnReadFs.go
generated
vendored
Normal file
295
vendor/github.com/spf13/afero/cacheOnReadFs.go
generated
vendored
Normal file
|
@ -0,0 +1,295 @@
|
|||
package afero
|
||||
|
||||
import (
|
||||
"os"
|
||||
"syscall"
|
||||
"time"
|
||||
)
|
||||
|
||||
// If the cache duration is 0, cache time will be unlimited, i.e. once
|
||||
// a file is in the layer, the base will never be read again for this file.
|
||||
//
|
||||
// For cache times greater than 0, the modification time of a file is
|
||||
// checked. Note that a lot of file system implementations only allow a
|
||||
// resolution of a second for timestamps... or as the godoc for os.Chtimes()
|
||||
// states: "The underlying filesystem may truncate or round the values to a
|
||||
// less precise time unit."
|
||||
//
|
||||
// This caching union will forward all write calls also to the base file
|
||||
// system first. To prevent writing to the base Fs, wrap it in a read-only
|
||||
// filter - Note: this will also make the overlay read-only, for writing files
|
||||
// in the overlay, use the overlay Fs directly, not via the union Fs.
|
||||
type CacheOnReadFs struct {
|
||||
base Fs
|
||||
layer Fs
|
||||
cacheTime time.Duration
|
||||
}
|
||||
|
||||
func NewCacheOnReadFs(base Fs, layer Fs, cacheTime time.Duration) Fs {
|
||||
return &CacheOnReadFs{base: base, layer: layer, cacheTime: cacheTime}
|
||||
}
|
||||
|
||||
type cacheState int
|
||||
|
||||
const (
|
||||
// not present in the overlay, unknown if it exists in the base:
|
||||
cacheMiss cacheState = iota
|
||||
// present in the overlay and in base, base file is newer:
|
||||
cacheStale
|
||||
// present in the overlay - with cache time == 0 it may exist in the base,
|
||||
// with cacheTime > 0 it exists in the base and is same age or newer in the
|
||||
// overlay
|
||||
cacheHit
|
||||
// happens if someone writes directly to the overlay without
|
||||
// going through this union
|
||||
cacheLocal
|
||||
)
|
||||
|
||||
func (u *CacheOnReadFs) cacheStatus(name string) (state cacheState, fi os.FileInfo, err error) {
|
||||
var lfi, bfi os.FileInfo
|
||||
lfi, err = u.layer.Stat(name)
|
||||
if err == nil {
|
||||
if u.cacheTime == 0 {
|
||||
return cacheHit, lfi, nil
|
||||
}
|
||||
if lfi.ModTime().Add(u.cacheTime).Before(time.Now()) {
|
||||
bfi, err = u.base.Stat(name)
|
||||
if err != nil {
|
||||
return cacheLocal, lfi, nil
|
||||
}
|
||||
if bfi.ModTime().After(lfi.ModTime()) {
|
||||
return cacheStale, bfi, nil
|
||||
}
|
||||
}
|
||||
return cacheHit, lfi, nil
|
||||
}
|
||||
|
||||
if err == syscall.ENOENT {
|
||||
return cacheMiss, nil, nil
|
||||
}
|
||||
var ok bool
|
||||
if err, ok = err.(*os.PathError); ok {
|
||||
if err == os.ErrNotExist {
|
||||
return cacheMiss, nil, nil
|
||||
}
|
||||
}
|
||||
return cacheMiss, nil, err
|
||||
}
|
||||
|
||||
func (u *CacheOnReadFs) copyToLayer(name string) error {
|
||||
return copyToLayer(u.base, u.layer, name)
|
||||
}
|
||||
|
||||
func (u *CacheOnReadFs) Chtimes(name string, atime, mtime time.Time) error {
|
||||
st, _, err := u.cacheStatus(name)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
switch st {
|
||||
case cacheLocal:
|
||||
case cacheHit:
|
||||
err = u.base.Chtimes(name, atime, mtime)
|
||||
case cacheStale, cacheMiss:
|
||||
if err := u.copyToLayer(name); err != nil {
|
||||
return err
|
||||
}
|
||||
err = u.base.Chtimes(name, atime, mtime)
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return u.layer.Chtimes(name, atime, mtime)
|
||||
}
|
||||
|
||||
func (u *CacheOnReadFs) Chmod(name string, mode os.FileMode) error {
|
||||
st, _, err := u.cacheStatus(name)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
switch st {
|
||||
case cacheLocal:
|
||||
case cacheHit:
|
||||
err = u.base.Chmod(name, mode)
|
||||
case cacheStale, cacheMiss:
|
||||
if err := u.copyToLayer(name); err != nil {
|
||||
return err
|
||||
}
|
||||
err = u.base.Chmod(name, mode)
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return u.layer.Chmod(name, mode)
|
||||
}
|
||||
|
||||
func (u *CacheOnReadFs) Stat(name string) (os.FileInfo, error) {
|
||||
st, fi, err := u.cacheStatus(name)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
switch st {
|
||||
case cacheMiss:
|
||||
return u.base.Stat(name)
|
||||
default: // cacheStale has base, cacheHit and cacheLocal the layer os.FileInfo
|
||||
return fi, nil
|
||||
}
|
||||
}
|
||||
|
||||
func (u *CacheOnReadFs) Rename(oldname, newname string) error {
|
||||
st, _, err := u.cacheStatus(oldname)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
switch st {
|
||||
case cacheLocal:
|
||||
case cacheHit:
|
||||
err = u.base.Rename(oldname, newname)
|
||||
case cacheStale, cacheMiss:
|
||||
if err := u.copyToLayer(oldname); err != nil {
|
||||
return err
|
||||
}
|
||||
err = u.base.Rename(oldname, newname)
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return u.layer.Rename(oldname, newname)
|
||||
}
|
||||
|
||||
func (u *CacheOnReadFs) Remove(name string) error {
|
||||
st, _, err := u.cacheStatus(name)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
switch st {
|
||||
case cacheLocal:
|
||||
case cacheHit, cacheStale, cacheMiss:
|
||||
err = u.base.Remove(name)
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return u.layer.Remove(name)
|
||||
}
|
||||
|
||||
func (u *CacheOnReadFs) RemoveAll(name string) error {
|
||||
st, _, err := u.cacheStatus(name)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
switch st {
|
||||
case cacheLocal:
|
||||
case cacheHit, cacheStale, cacheMiss:
|
||||
err = u.base.RemoveAll(name)
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return u.layer.RemoveAll(name)
|
||||
}
|
||||
|
||||
func (u *CacheOnReadFs) OpenFile(name string, flag int, perm os.FileMode) (File, error) {
|
||||
st, _, err := u.cacheStatus(name)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
switch st {
|
||||
case cacheLocal, cacheHit:
|
||||
default:
|
||||
if err := u.copyToLayer(name); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
if flag&(os.O_WRONLY|syscall.O_RDWR|os.O_APPEND|os.O_CREATE|os.O_TRUNC) != 0 {
|
||||
bfi, err := u.base.OpenFile(name, flag, perm)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
lfi, err := u.layer.OpenFile(name, flag, perm)
|
||||
if err != nil {
|
||||
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 u.layer.OpenFile(name, flag, perm)
|
||||
}
|
||||
|
||||
func (u *CacheOnReadFs) Open(name string) (File, error) {
|
||||
st, fi, err := u.cacheStatus(name)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
switch st {
|
||||
case cacheLocal:
|
||||
return u.layer.Open(name)
|
||||
|
||||
case cacheMiss:
|
||||
bfi, err := u.base.Stat(name)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if bfi.IsDir() {
|
||||
return u.base.Open(name)
|
||||
}
|
||||
if err := u.copyToLayer(name); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return u.layer.Open(name)
|
||||
|
||||
case cacheStale:
|
||||
if !fi.IsDir() {
|
||||
if err := u.copyToLayer(name); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return u.layer.Open(name)
|
||||
}
|
||||
case cacheHit:
|
||||
if !fi.IsDir() {
|
||||
return u.layer.Open(name)
|
||||
}
|
||||
}
|
||||
// the dirs from cacheHit, cacheStale fall down here:
|
||||
bfile, _ := u.base.Open(name)
|
||||
lfile, err := u.layer.Open(name)
|
||||
if err != nil && bfile == nil {
|
||||
return nil, err
|
||||
}
|
||||
return &UnionFile{base: bfile, layer: lfile}, nil
|
||||
}
|
||||
|
||||
func (u *CacheOnReadFs) Mkdir(name string, perm os.FileMode) error {
|
||||
err := u.base.Mkdir(name, perm)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return u.layer.MkdirAll(name, perm) // yes, MkdirAll... we cannot assume it exists in the cache
|
||||
}
|
||||
|
||||
func (u *CacheOnReadFs) Name() string {
|
||||
return "CacheOnReadFs"
|
||||
}
|
||||
|
||||
func (u *CacheOnReadFs) MkdirAll(name string, perm os.FileMode) error {
|
||||
err := u.base.MkdirAll(name, perm)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return u.layer.MkdirAll(name, perm)
|
||||
}
|
||||
|
||||
func (u *CacheOnReadFs) Create(name string) (File, error) {
|
||||
bfh, err := u.base.Create(name)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
lfh, err := u.layer.Create(name)
|
||||
if err != nil {
|
||||
// oops, see comment about OS_TRUNC above, should we remove? then we have to
|
||||
// remember if the file did not exist before
|
||||
bfh.Close()
|
||||
return nil, err
|
||||
}
|
||||
return &UnionFile{base: bfh, layer: lfh}, nil
|
||||
}
|
22
vendor/github.com/spf13/afero/const_bsds.go
generated
vendored
Normal file
22
vendor/github.com/spf13/afero/const_bsds.go
generated
vendored
Normal file
|
@ -0,0 +1,22 @@
|
|||
// Copyright © 2016 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.
|
||||
|
||||
// +build darwin openbsd freebsd netbsd dragonfly
|
||||
|
||||
package afero
|
||||
|
||||
import (
|
||||
"syscall"
|
||||
)
|
||||
|
||||
const BADFD = syscall.EBADF
|
25
vendor/github.com/spf13/afero/const_win_unix.go
generated
vendored
Normal file
25
vendor/github.com/spf13/afero/const_win_unix.go
generated
vendored
Normal file
|
@ -0,0 +1,25 @@
|
|||
// Copyright © 2016 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.
|
||||
// +build !darwin
|
||||
// +build !openbsd
|
||||
// +build !freebsd
|
||||
// +build !dragonfly
|
||||
// +build !netbsd
|
||||
|
||||
package afero
|
||||
|
||||
import (
|
||||
"syscall"
|
||||
)
|
||||
|
||||
const BADFD = syscall.EBADFD
|
253
vendor/github.com/spf13/afero/copyOnWriteFs.go
generated
vendored
Normal file
253
vendor/github.com/spf13/afero/copyOnWriteFs.go
generated
vendored
Normal file
|
@ -0,0 +1,253 @@
|
|||
package afero
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"syscall"
|
||||
"time"
|
||||
)
|
||||
|
||||
// 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
|
||||
// is not present in the overlay will copy the file to the overlay ("changing"
|
||||
// includes also calls to e.g. Chtimes() and Chmod()).
|
||||
//
|
||||
// Reading directories is currently only supported via Open(), not OpenFile().
|
||||
type CopyOnWriteFs struct {
|
||||
base Fs
|
||||
layer Fs
|
||||
}
|
||||
|
||||
func NewCopyOnWriteFs(base Fs, layer Fs) Fs {
|
||||
return &CopyOnWriteFs{base: base, layer: layer}
|
||||
}
|
||||
|
||||
// Returns true if the file is not in the overlay
|
||||
func (u *CopyOnWriteFs) isBaseFile(name string) (bool, error) {
|
||||
if _, err := u.layer.Stat(name); err == nil {
|
||||
return false, nil
|
||||
}
|
||||
_, err := u.base.Stat(name)
|
||||
if err != nil {
|
||||
if oerr, ok := err.(*os.PathError); ok {
|
||||
if oerr.Err == os.ErrNotExist || oerr.Err == syscall.ENOENT || oerr.Err == syscall.ENOTDIR {
|
||||
return false, nil
|
||||
}
|
||||
}
|
||||
if err == syscall.ENOENT {
|
||||
return false, nil
|
||||
}
|
||||
}
|
||||
return true, err
|
||||
}
|
||||
|
||||
func (u *CopyOnWriteFs) copyToLayer(name string) error {
|
||||
return copyToLayer(u.base, u.layer, name)
|
||||
}
|
||||
|
||||
func (u *CopyOnWriteFs) Chtimes(name string, atime, mtime time.Time) error {
|
||||
b, err := u.isBaseFile(name)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if b {
|
||||
if err := u.copyToLayer(name); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return u.layer.Chtimes(name, atime, mtime)
|
||||
}
|
||||
|
||||
func (u *CopyOnWriteFs) Chmod(name string, mode os.FileMode) error {
|
||||
b, err := u.isBaseFile(name)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if b {
|
||||
if err := u.copyToLayer(name); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return u.layer.Chmod(name, mode)
|
||||
}
|
||||
|
||||
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 == syscall.ENOENT || err == syscall.ENOTDIR {
|
||||
return u.base.Stat(name)
|
||||
}
|
||||
return nil, origErr
|
||||
}
|
||||
return fi, nil
|
||||
}
|
||||
|
||||
// Renaming files present only in the base layer is not permitted
|
||||
func (u *CopyOnWriteFs) Rename(oldname, newname string) error {
|
||||
b, err := u.isBaseFile(oldname)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if b {
|
||||
return syscall.EPERM
|
||||
}
|
||||
return u.layer.Rename(oldname, newname)
|
||||
}
|
||||
|
||||
// Removing files present only in the base layer is not permitted. If
|
||||
// a file is present in the base layer and the overlay, only the overlay
|
||||
// will be removed.
|
||||
func (u *CopyOnWriteFs) Remove(name string) error {
|
||||
err := u.layer.Remove(name)
|
||||
switch err {
|
||||
case syscall.ENOENT:
|
||||
_, err = u.base.Stat(name)
|
||||
if err == nil {
|
||||
return syscall.EPERM
|
||||
}
|
||||
return syscall.ENOENT
|
||||
default:
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
func (u *CopyOnWriteFs) RemoveAll(name string) error {
|
||||
err := u.layer.RemoveAll(name)
|
||||
switch err {
|
||||
case syscall.ENOENT:
|
||||
_, err = u.base.Stat(name)
|
||||
if err == nil {
|
||||
return syscall.EPERM
|
||||
}
|
||||
return syscall.ENOENT
|
||||
default:
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
func (u *CopyOnWriteFs) OpenFile(name string, flag int, perm os.FileMode) (File, error) {
|
||||
b, err := u.isBaseFile(name)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if flag&(os.O_WRONLY|os.O_RDWR|os.O_APPEND|os.O_CREATE|os.O_TRUNC) != 0 {
|
||||
if b {
|
||||
if err = u.copyToLayer(name); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return u.layer.OpenFile(name, flag, perm)
|
||||
}
|
||||
|
||||
dir := filepath.Dir(name)
|
||||
isaDir, err := IsDir(u.base, dir)
|
||||
if err != nil && !os.IsNotExist(err) {
|
||||
return nil, err
|
||||
}
|
||||
if isaDir {
|
||||
if err = u.layer.MkdirAll(dir, 0777); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return u.layer.OpenFile(name, flag, perm)
|
||||
}
|
||||
|
||||
isaDir, err = IsDir(u.layer, dir)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if isaDir {
|
||||
return u.layer.OpenFile(name, flag, perm)
|
||||
}
|
||||
|
||||
return nil, &os.PathError{Op: "open", Path: name, Err: syscall.ENOTDIR} // ...or os.ErrNotExist?
|
||||
}
|
||||
if b {
|
||||
return u.base.OpenFile(name, flag, perm)
|
||||
}
|
||||
return u.layer.OpenFile(name, flag, perm)
|
||||
}
|
||||
|
||||
// This function handles the 9 different possibilities caused
|
||||
// by the union which are the intersection of the following...
|
||||
// layer: doesn't exist, exists as a file, and exists as a directory
|
||||
// base: doesn't exist, exists as a file, and exists as a directory
|
||||
func (u *CopyOnWriteFs) Open(name string) (File, error) {
|
||||
// Since the overlay overrides the base we check that first
|
||||
b, err := u.isBaseFile(name)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// If overlay doesn't exist, return the base (base state irrelevant)
|
||||
if b {
|
||||
return u.base.Open(name)
|
||||
}
|
||||
|
||||
// If overlay is a file, return it (base state irrelevant)
|
||||
dir, err := IsDir(u.layer, name)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if !dir {
|
||||
return u.layer.Open(name)
|
||||
}
|
||||
|
||||
// Overlay is a directory, base state now matters.
|
||||
// Base state has 3 states to check but 2 outcomes:
|
||||
// A. It's a file or non-readable in the base (return just the overlay)
|
||||
// B. It's an accessible directory in the base (return a UnionFile)
|
||||
|
||||
// If base is file or nonreadable, return overlay
|
||||
dir, err = IsDir(u.base, name)
|
||||
if !dir || err != nil {
|
||||
return u.layer.Open(name)
|
||||
}
|
||||
|
||||
// Both base & layer are directories
|
||||
// Return union file (if opens are without error)
|
||||
bfile, bErr := u.base.Open(name)
|
||||
lfile, lErr := u.layer.Open(name)
|
||||
|
||||
// If either have errors at this point something is very wrong. Return nil and the errors
|
||||
if bErr != nil || lErr != nil {
|
||||
return nil, fmt.Errorf("BaseErr: %v\nOverlayErr: %v", bErr, lErr)
|
||||
}
|
||||
|
||||
return &UnionFile{base: bfile, layer: lfile}, nil
|
||||
}
|
||||
|
||||
func (u *CopyOnWriteFs) Mkdir(name string, perm os.FileMode) error {
|
||||
dir, err := IsDir(u.base, name)
|
||||
if err != nil {
|
||||
return u.layer.MkdirAll(name, perm)
|
||||
}
|
||||
if dir {
|
||||
return syscall.EEXIST
|
||||
}
|
||||
return u.layer.MkdirAll(name, perm)
|
||||
}
|
||||
|
||||
func (u *CopyOnWriteFs) Name() string {
|
||||
return "CopyOnWriteFs"
|
||||
}
|
||||
|
||||
func (u *CopyOnWriteFs) MkdirAll(name string, perm os.FileMode) error {
|
||||
dir, err := IsDir(u.base, name)
|
||||
if err != nil {
|
||||
return u.layer.MkdirAll(name, perm)
|
||||
}
|
||||
if dir {
|
||||
return syscall.EEXIST
|
||||
}
|
||||
return u.layer.MkdirAll(name, perm)
|
||||
}
|
||||
|
||||
func (u *CopyOnWriteFs) Create(name string) (File, error) {
|
||||
return u.OpenFile(name, os.O_CREATE|os.O_TRUNC|os.O_RDWR, 0666)
|
||||
}
|
110
vendor/github.com/spf13/afero/httpFs.go
generated
vendored
Normal file
110
vendor/github.com/spf13/afero/httpFs.go
generated
vendored
Normal file
|
@ -0,0 +1,110 @@
|
|||
// Copyright © 2014 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 (
|
||||
"errors"
|
||||
"net/http"
|
||||
"os"
|
||||
"path"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
type httpDir struct {
|
||||
basePath string
|
||||
fs HttpFs
|
||||
}
|
||||
|
||||
func (d httpDir) Open(name string) (http.File, error) {
|
||||
if filepath.Separator != '/' && strings.IndexRune(name, filepath.Separator) >= 0 ||
|
||||
strings.Contains(name, "\x00") {
|
||||
return nil, errors.New("http: invalid character in file path")
|
||||
}
|
||||
dir := string(d.basePath)
|
||||
if dir == "" {
|
||||
dir = "."
|
||||
}
|
||||
|
||||
f, err := d.fs.Open(filepath.Join(dir, filepath.FromSlash(path.Clean("/"+name))))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return f, nil
|
||||
}
|
||||
|
||||
type HttpFs struct {
|
||||
source Fs
|
||||
}
|
||||
|
||||
func NewHttpFs(source Fs) *HttpFs {
|
||||
return &HttpFs{source: source}
|
||||
}
|
||||
|
||||
func (h HttpFs) Dir(s string) *httpDir {
|
||||
return &httpDir{basePath: s, fs: h}
|
||||
}
|
||||
|
||||
func (h HttpFs) Name() string { return "h HttpFs" }
|
||||
|
||||
func (h HttpFs) Create(name string) (File, error) {
|
||||
return h.source.Create(name)
|
||||
}
|
||||
|
||||
func (h HttpFs) Chmod(name string, mode os.FileMode) error {
|
||||
return h.source.Chmod(name, mode)
|
||||
}
|
||||
|
||||
func (h HttpFs) Chtimes(name string, atime time.Time, mtime time.Time) error {
|
||||
return h.source.Chtimes(name, atime, mtime)
|
||||
}
|
||||
|
||||
func (h HttpFs) Mkdir(name string, perm os.FileMode) error {
|
||||
return h.source.Mkdir(name, perm)
|
||||
}
|
||||
|
||||
func (h HttpFs) MkdirAll(path string, perm os.FileMode) error {
|
||||
return h.source.MkdirAll(path, perm)
|
||||
}
|
||||
|
||||
func (h HttpFs) Open(name string) (http.File, error) {
|
||||
f, err := h.source.Open(name)
|
||||
if err == nil {
|
||||
if httpfile, ok := f.(http.File); ok {
|
||||
return httpfile, nil
|
||||
}
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
|
||||
func (h HttpFs) OpenFile(name string, flag int, perm os.FileMode) (File, error) {
|
||||
return h.source.OpenFile(name, flag, perm)
|
||||
}
|
||||
|
||||
func (h HttpFs) Remove(name string) error {
|
||||
return h.source.Remove(name)
|
||||
}
|
||||
|
||||
func (h HttpFs) RemoveAll(path string) error {
|
||||
return h.source.RemoveAll(path)
|
||||
}
|
||||
|
||||
func (h HttpFs) Rename(oldname, newname string) error {
|
||||
return h.source.Rename(oldname, newname)
|
||||
}
|
||||
|
||||
func (h HttpFs) Stat(name string) (os.FileInfo, error) {
|
||||
return h.source.Stat(name)
|
||||
}
|
230
vendor/github.com/spf13/afero/ioutil.go
generated
vendored
Normal file
230
vendor/github.com/spf13/afero/ioutil.go
generated
vendored
Normal file
|
@ -0,0 +1,230 @@
|
|||
// Copyright ©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 (
|
||||
"bytes"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sort"
|
||||
"strconv"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
// byName implements sort.Interface.
|
||||
type byName []os.FileInfo
|
||||
|
||||
func (f byName) Len() int { return len(f) }
|
||||
func (f byName) Less(i, j int) bool { return f[i].Name() < f[j].Name() }
|
||||
func (f byName) Swap(i, j int) { f[i], f[j] = f[j], f[i] }
|
||||
|
||||
// ReadDir reads the directory named by dirname and returns
|
||||
// a list of sorted directory entries.
|
||||
func (a Afero) ReadDir(dirname string) ([]os.FileInfo, error) {
|
||||
return ReadDir(a.Fs, dirname)
|
||||
}
|
||||
|
||||
func ReadDir(fs Fs, dirname string) ([]os.FileInfo, error) {
|
||||
f, err := fs.Open(dirname)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
list, err := f.Readdir(-1)
|
||||
f.Close()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
sort.Sort(byName(list))
|
||||
return list, nil
|
||||
}
|
||||
|
||||
// ReadFile reads the file named by filename and returns the contents.
|
||||
// A successful call returns err == nil, not err == EOF. Because ReadFile
|
||||
// reads the whole file, it does not treat an EOF from Read as an error
|
||||
// to be reported.
|
||||
func (a Afero) ReadFile(filename string) ([]byte, error) {
|
||||
return ReadFile(a.Fs, filename)
|
||||
}
|
||||
|
||||
func ReadFile(fs Fs, filename string) ([]byte, error) {
|
||||
f, err := fs.Open(filename)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer f.Close()
|
||||
// It's a good but not certain bet that FileInfo will tell us exactly how much to
|
||||
// read, so let's try it but be prepared for the answer to be wrong.
|
||||
var n int64
|
||||
|
||||
if fi, err := f.Stat(); err == nil {
|
||||
// Don't preallocate a huge buffer, just in case.
|
||||
if size := fi.Size(); size < 1e9 {
|
||||
n = size
|
||||
}
|
||||
}
|
||||
// As initial capacity for readAll, use n + a little extra in case Size is zero,
|
||||
// and to avoid another allocation after Read has filled the buffer. The readAll
|
||||
// call will read into its allocated internal buffer cheaply. If the size was
|
||||
// wrong, we'll either waste some space off the end or reallocate as needed, but
|
||||
// in the overwhelmingly common case we'll get it just right.
|
||||
return readAll(f, n+bytes.MinRead)
|
||||
}
|
||||
|
||||
// readAll reads from r until an error or EOF and returns the data it read
|
||||
// from the internal buffer allocated with a specified capacity.
|
||||
func readAll(r io.Reader, capacity int64) (b []byte, err error) {
|
||||
buf := bytes.NewBuffer(make([]byte, 0, capacity))
|
||||
// If the buffer overflows, we will get bytes.ErrTooLarge.
|
||||
// Return that as an error. Any other panic remains.
|
||||
defer func() {
|
||||
e := recover()
|
||||
if e == nil {
|
||||
return
|
||||
}
|
||||
if panicErr, ok := e.(error); ok && panicErr == bytes.ErrTooLarge {
|
||||
err = panicErr
|
||||
} else {
|
||||
panic(e)
|
||||
}
|
||||
}()
|
||||
_, err = buf.ReadFrom(r)
|
||||
return buf.Bytes(), err
|
||||
}
|
||||
|
||||
// ReadAll reads from r until an error or EOF and returns the data it read.
|
||||
// A successful call returns err == nil, not err == EOF. Because ReadAll is
|
||||
// defined to read from src until EOF, it does not treat an EOF from Read
|
||||
// as an error to be reported.
|
||||
func ReadAll(r io.Reader) ([]byte, error) {
|
||||
return readAll(r, bytes.MinRead)
|
||||
}
|
||||
|
||||
// WriteFile writes data to a file named by filename.
|
||||
// If the file does not exist, WriteFile creates it with permissions perm;
|
||||
// otherwise WriteFile truncates it before writing.
|
||||
func (a Afero) WriteFile(filename string, data []byte, perm os.FileMode) error {
|
||||
return WriteFile(a.Fs, filename, data, perm)
|
||||
}
|
||||
|
||||
func WriteFile(fs Fs, filename string, data []byte, perm os.FileMode) error {
|
||||
f, err := fs.OpenFile(filename, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, perm)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
n, err := f.Write(data)
|
||||
if err == nil && n < len(data) {
|
||||
err = io.ErrShortWrite
|
||||
}
|
||||
if err1 := f.Close(); err == nil {
|
||||
err = err1
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
// Random number state.
|
||||
// We generate random temporary file names so that there's a good
|
||||
// chance the file doesn't exist yet - keeps the number of tries in
|
||||
// TempFile to a minimum.
|
||||
var rand uint32
|
||||
var randmu sync.Mutex
|
||||
|
||||
func reseed() uint32 {
|
||||
return uint32(time.Now().UnixNano() + int64(os.Getpid()))
|
||||
}
|
||||
|
||||
func nextSuffix() string {
|
||||
randmu.Lock()
|
||||
r := rand
|
||||
if r == 0 {
|
||||
r = reseed()
|
||||
}
|
||||
r = r*1664525 + 1013904223 // constants from Numerical Recipes
|
||||
rand = r
|
||||
randmu.Unlock()
|
||||
return strconv.Itoa(int(1e9 + r%1e9))[1:]
|
||||
}
|
||||
|
||||
// TempFile creates a new temporary file in the directory dir
|
||||
// with a name beginning with prefix, opens the file for reading
|
||||
// and writing, and returns the resulting *File.
|
||||
// If dir is the empty string, TempFile uses the default directory
|
||||
// for temporary files (see os.TempDir).
|
||||
// Multiple programs calling TempFile simultaneously
|
||||
// will not choose the same file. The caller can use f.Name()
|
||||
// to find the pathname of the file. It is the caller's responsibility
|
||||
// to remove the file when no longer needed.
|
||||
func (a Afero) TempFile(dir, prefix string) (f File, err error) {
|
||||
return TempFile(a.Fs, dir, prefix)
|
||||
}
|
||||
|
||||
func TempFile(fs Fs, dir, prefix string) (f File, err error) {
|
||||
if dir == "" {
|
||||
dir = os.TempDir()
|
||||
}
|
||||
|
||||
nconflict := 0
|
||||
for i := 0; i < 10000; i++ {
|
||||
name := filepath.Join(dir, prefix+nextSuffix())
|
||||
f, err = fs.OpenFile(name, os.O_RDWR|os.O_CREATE|os.O_EXCL, 0600)
|
||||
if os.IsExist(err) {
|
||||
if nconflict++; nconflict > 10 {
|
||||
randmu.Lock()
|
||||
rand = reseed()
|
||||
randmu.Unlock()
|
||||
}
|
||||
continue
|
||||
}
|
||||
break
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// TempDir creates a new temporary directory in the directory dir
|
||||
// with a name beginning with prefix and returns the path of the
|
||||
// new directory. If dir is the empty string, TempDir uses the
|
||||
// default directory for temporary files (see os.TempDir).
|
||||
// Multiple programs calling TempDir simultaneously
|
||||
// will not choose the same directory. It is the caller's responsibility
|
||||
// to remove the directory when no longer needed.
|
||||
func (a Afero) TempDir(dir, prefix string) (name string, err error) {
|
||||
return TempDir(a.Fs, dir, prefix)
|
||||
}
|
||||
func TempDir(fs Fs, dir, prefix string) (name string, err error) {
|
||||
if dir == "" {
|
||||
dir = os.TempDir()
|
||||
}
|
||||
|
||||
nconflict := 0
|
||||
for i := 0; i < 10000; i++ {
|
||||
try := filepath.Join(dir, prefix+nextSuffix())
|
||||
err = fs.Mkdir(try, 0700)
|
||||
if os.IsExist(err) {
|
||||
if nconflict++; nconflict > 10 {
|
||||
randmu.Lock()
|
||||
rand = reseed()
|
||||
randmu.Unlock()
|
||||
}
|
||||
continue
|
||||
}
|
||||
if err == nil {
|
||||
name = try
|
||||
}
|
||||
break
|
||||
}
|
||||
return
|
||||
}
|
37
vendor/github.com/spf13/afero/mem/dir.go
generated
vendored
Normal file
37
vendor/github.com/spf13/afero/mem/dir.go
generated
vendored
Normal file
|
@ -0,0 +1,37 @@
|
|||
// Copyright © 2014 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 mem
|
||||
|
||||
type Dir interface {
|
||||
Len() int
|
||||
Names() []string
|
||||
Files() []*FileData
|
||||
Add(*FileData)
|
||||
Remove(*FileData)
|
||||
}
|
||||
|
||||
func RemoveFromMemDir(dir *FileData, f *FileData) {
|
||||
dir.memDir.Remove(f)
|
||||
}
|
||||
|
||||
func AddToMemDir(dir *FileData, f *FileData) {
|
||||
dir.memDir.Add(f)
|
||||
}
|
||||
|
||||
func InitializeDir(d *FileData) {
|
||||
if d.memDir == nil {
|
||||
d.dir = true
|
||||
d.memDir = &DirMap{}
|
||||
}
|
||||
}
|
43
vendor/github.com/spf13/afero/mem/dirmap.go
generated
vendored
Normal file
43
vendor/github.com/spf13/afero/mem/dirmap.go
generated
vendored
Normal file
|
@ -0,0 +1,43 @@
|
|||
// 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 mem
|
||||
|
||||
import "sort"
|
||||
|
||||
type DirMap map[string]*FileData
|
||||
|
||||
func (m DirMap) Len() int { return len(m) }
|
||||
func (m DirMap) Add(f *FileData) { m[f.name] = f }
|
||||
func (m DirMap) Remove(f *FileData) { delete(m, f.name) }
|
||||
func (m DirMap) Files() (files []*FileData) {
|
||||
for _, f := range m {
|
||||
files = append(files, f)
|
||||
}
|
||||
sort.Sort(filesSorter(files))
|
||||
return files
|
||||
}
|
||||
|
||||
// implement sort.Interface for []*FileData
|
||||
type filesSorter []*FileData
|
||||
|
||||
func (s filesSorter) Len() int { return len(s) }
|
||||
func (s filesSorter) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
|
||||
func (s filesSorter) Less(i, j int) bool { return s[i].name < s[j].name }
|
||||
|
||||
func (m DirMap) Names() (names []string) {
|
||||
for x := range m {
|
||||
names = append(names, x)
|
||||
}
|
||||
return names
|
||||
}
|
285
vendor/github.com/spf13/afero/mem/file.go
generated
vendored
Normal file
285
vendor/github.com/spf13/afero/mem/file.go
generated
vendored
Normal file
|
@ -0,0 +1,285 @@
|
|||
// Copyright © 2015 Steve Francia <spf@spf13.com>.
|
||||
// Copyright 2013 tsuru 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 mem
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"errors"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
)
|
||||
|
||||
import "time"
|
||||
|
||||
const FilePathSeparator = string(filepath.Separator)
|
||||
|
||||
type File struct {
|
||||
// atomic requires 64-bit alignment for struct field access
|
||||
at int64
|
||||
readDirCount int64
|
||||
closed bool
|
||||
readOnly bool
|
||||
fileData *FileData
|
||||
}
|
||||
|
||||
func NewFileHandle(data *FileData) *File {
|
||||
return &File{fileData: data}
|
||||
}
|
||||
|
||||
func NewReadOnlyFileHandle(data *FileData) *File {
|
||||
return &File{fileData: data, readOnly: true}
|
||||
}
|
||||
|
||||
func (f File) Data() *FileData {
|
||||
return f.fileData
|
||||
}
|
||||
|
||||
type FileData struct {
|
||||
sync.Mutex
|
||||
name string
|
||||
data []byte
|
||||
memDir Dir
|
||||
dir bool
|
||||
mode os.FileMode
|
||||
modtime time.Time
|
||||
}
|
||||
|
||||
func (d *FileData) Name() string {
|
||||
d.Lock()
|
||||
defer d.Unlock()
|
||||
return d.name
|
||||
}
|
||||
|
||||
func CreateFile(name string) *FileData {
|
||||
return &FileData{name: name, mode: os.ModeTemporary, modtime: time.Now()}
|
||||
}
|
||||
|
||||
func CreateDir(name string) *FileData {
|
||||
return &FileData{name: name, memDir: &DirMap{}, dir: true}
|
||||
}
|
||||
|
||||
func ChangeFileName(f *FileData, newname string) {
|
||||
f.name = newname
|
||||
}
|
||||
|
||||
func SetMode(f *FileData, mode os.FileMode) {
|
||||
f.mode = mode
|
||||
}
|
||||
|
||||
func SetModTime(f *FileData, mtime time.Time) {
|
||||
f.modtime = mtime
|
||||
}
|
||||
|
||||
func GetFileInfo(f *FileData) *FileInfo {
|
||||
return &FileInfo{f}
|
||||
}
|
||||
|
||||
func (f *File) Open() error {
|
||||
atomic.StoreInt64(&f.at, 0)
|
||||
atomic.StoreInt64(&f.readDirCount, 0)
|
||||
f.fileData.Lock()
|
||||
f.closed = false
|
||||
f.fileData.Unlock()
|
||||
return nil
|
||||
}
|
||||
|
||||
func (f *File) Close() error {
|
||||
f.fileData.Lock()
|
||||
f.closed = true
|
||||
if !f.readOnly {
|
||||
SetModTime(f.fileData, time.Now())
|
||||
}
|
||||
f.fileData.Unlock()
|
||||
return nil
|
||||
}
|
||||
|
||||
func (f *File) Name() string {
|
||||
return f.fileData.Name()
|
||||
}
|
||||
|
||||
func (f *File) Stat() (os.FileInfo, error) {
|
||||
return &FileInfo{f.fileData}, nil
|
||||
}
|
||||
|
||||
func (f *File) Sync() error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (f *File) Readdir(count int) (res []os.FileInfo, err error) {
|
||||
var outLength int64
|
||||
|
||||
f.fileData.Lock()
|
||||
files := f.fileData.memDir.Files()[f.readDirCount:]
|
||||
if count > 0 {
|
||||
if len(files) < count {
|
||||
outLength = int64(len(files))
|
||||
} else {
|
||||
outLength = int64(count)
|
||||
}
|
||||
if len(files) == 0 {
|
||||
err = io.EOF
|
||||
}
|
||||
} else {
|
||||
outLength = int64(len(files))
|
||||
}
|
||||
f.readDirCount += outLength
|
||||
f.fileData.Unlock()
|
||||
|
||||
res = make([]os.FileInfo, outLength)
|
||||
for i := range res {
|
||||
res[i] = &FileInfo{files[i]}
|
||||
}
|
||||
|
||||
return res, err
|
||||
}
|
||||
|
||||
func (f *File) Readdirnames(n int) (names []string, err error) {
|
||||
fi, err := f.Readdir(n)
|
||||
names = make([]string, len(fi))
|
||||
for i, f := range fi {
|
||||
_, names[i] = filepath.Split(f.Name())
|
||||
}
|
||||
return names, err
|
||||
}
|
||||
|
||||
func (f *File) Read(b []byte) (n int, err error) {
|
||||
f.fileData.Lock()
|
||||
defer f.fileData.Unlock()
|
||||
if f.closed == true {
|
||||
return 0, ErrFileClosed
|
||||
}
|
||||
if len(b) > 0 && int(f.at) == len(f.fileData.data) {
|
||||
return 0, io.EOF
|
||||
}
|
||||
if len(f.fileData.data)-int(f.at) >= len(b) {
|
||||
n = len(b)
|
||||
} else {
|
||||
n = len(f.fileData.data) - int(f.at)
|
||||
}
|
||||
copy(b, f.fileData.data[f.at:f.at+int64(n)])
|
||||
atomic.AddInt64(&f.at, int64(n))
|
||||
return
|
||||
}
|
||||
|
||||
func (f *File) ReadAt(b []byte, off int64) (n int, err error) {
|
||||
atomic.StoreInt64(&f.at, off)
|
||||
return f.Read(b)
|
||||
}
|
||||
|
||||
func (f *File) Truncate(size int64) error {
|
||||
if f.closed == true {
|
||||
return ErrFileClosed
|
||||
}
|
||||
if f.readOnly {
|
||||
return &os.PathError{Op: "truncate", Path: f.fileData.name, Err: errors.New("file handle is read only")}
|
||||
}
|
||||
if size < 0 {
|
||||
return ErrOutOfRange
|
||||
}
|
||||
if size > int64(len(f.fileData.data)) {
|
||||
diff := size - int64(len(f.fileData.data))
|
||||
f.fileData.data = append(f.fileData.data, bytes.Repeat([]byte{00}, int(diff))...)
|
||||
} else {
|
||||
f.fileData.data = f.fileData.data[0:size]
|
||||
}
|
||||
SetModTime(f.fileData, time.Now())
|
||||
return nil
|
||||
}
|
||||
|
||||
func (f *File) Seek(offset int64, whence int) (int64, error) {
|
||||
if f.closed == true {
|
||||
return 0, ErrFileClosed
|
||||
}
|
||||
switch whence {
|
||||
case 0:
|
||||
atomic.StoreInt64(&f.at, offset)
|
||||
case 1:
|
||||
atomic.AddInt64(&f.at, int64(offset))
|
||||
case 2:
|
||||
atomic.StoreInt64(&f.at, int64(len(f.fileData.data))+offset)
|
||||
}
|
||||
return f.at, nil
|
||||
}
|
||||
|
||||
func (f *File) Write(b []byte) (n int, err error) {
|
||||
if f.readOnly {
|
||||
return 0, &os.PathError{Op: "write", Path: f.fileData.name, Err: errors.New("file handle is read only")}
|
||||
}
|
||||
n = len(b)
|
||||
cur := atomic.LoadInt64(&f.at)
|
||||
f.fileData.Lock()
|
||||
defer f.fileData.Unlock()
|
||||
diff := cur - int64(len(f.fileData.data))
|
||||
var tail []byte
|
||||
if n+int(cur) < len(f.fileData.data) {
|
||||
tail = f.fileData.data[n+int(cur):]
|
||||
}
|
||||
if diff > 0 {
|
||||
f.fileData.data = append(bytes.Repeat([]byte{00}, int(diff)), b...)
|
||||
f.fileData.data = append(f.fileData.data, tail...)
|
||||
} else {
|
||||
f.fileData.data = append(f.fileData.data[:cur], b...)
|
||||
f.fileData.data = append(f.fileData.data, tail...)
|
||||
}
|
||||
SetModTime(f.fileData, time.Now())
|
||||
|
||||
atomic.StoreInt64(&f.at, int64(len(f.fileData.data)))
|
||||
return
|
||||
}
|
||||
|
||||
func (f *File) WriteAt(b []byte, off int64) (n int, err error) {
|
||||
atomic.StoreInt64(&f.at, off)
|
||||
return f.Write(b)
|
||||
}
|
||||
|
||||
func (f *File) WriteString(s string) (ret int, err error) {
|
||||
return f.Write([]byte(s))
|
||||
}
|
||||
|
||||
func (f *File) Info() *FileInfo {
|
||||
return &FileInfo{f.fileData}
|
||||
}
|
||||
|
||||
type FileInfo struct {
|
||||
*FileData
|
||||
}
|
||||
|
||||
// Implements os.FileInfo
|
||||
func (s *FileInfo) Name() string {
|
||||
_, name := filepath.Split(s.name)
|
||||
return name
|
||||
}
|
||||
func (s *FileInfo) Mode() os.FileMode { return s.mode }
|
||||
func (s *FileInfo) ModTime() time.Time { return s.modtime }
|
||||
func (s *FileInfo) IsDir() bool { return s.dir }
|
||||
func (s *FileInfo) Sys() interface{} { return nil }
|
||||
func (s *FileInfo) Size() int64 {
|
||||
if s.IsDir() {
|
||||
return int64(42)
|
||||
}
|
||||
return int64(len(s.data))
|
||||
}
|
||||
|
||||
var (
|
||||
ErrFileClosed = errors.New("File is closed")
|
||||
ErrOutOfRange = errors.New("Out of range")
|
||||
ErrTooLarge = errors.New("Too large")
|
||||
ErrFileNotFound = os.ErrNotExist
|
||||
ErrFileExists = os.ErrExist
|
||||
ErrDestinationExists = os.ErrExist
|
||||
)
|
361
vendor/github.com/spf13/afero/memmap.go
generated
vendored
Normal file
361
vendor/github.com/spf13/afero/memmap.go
generated
vendored
Normal file
|
@ -0,0 +1,361 @@
|
|||
// Copyright © 2014 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 (
|
||||
"fmt"
|
||||
"log"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/spf13/afero/mem"
|
||||
)
|
||||
|
||||
type MemMapFs struct {
|
||||
mu sync.RWMutex
|
||||
data map[string]*mem.FileData
|
||||
init sync.Once
|
||||
}
|
||||
|
||||
func NewMemMapFs() Fs {
|
||||
return &MemMapFs{}
|
||||
}
|
||||
|
||||
func (m *MemMapFs) getData() map[string]*mem.FileData {
|
||||
m.init.Do(func() {
|
||||
m.data = make(map[string]*mem.FileData)
|
||||
// Root should always exist, right?
|
||||
// TODO: what about windows?
|
||||
m.data[FilePathSeparator] = mem.CreateDir(FilePathSeparator)
|
||||
})
|
||||
return m.data
|
||||
}
|
||||
|
||||
func (*MemMapFs) Name() string { return "MemMapFS" }
|
||||
|
||||
func (m *MemMapFs) Create(name string) (File, error) {
|
||||
name = normalizePath(name)
|
||||
m.mu.Lock()
|
||||
file := mem.CreateFile(name)
|
||||
m.getData()[name] = file
|
||||
m.registerWithParent(file)
|
||||
m.mu.Unlock()
|
||||
return mem.NewFileHandle(file), nil
|
||||
}
|
||||
|
||||
func (m *MemMapFs) unRegisterWithParent(fileName string) error {
|
||||
f, err := m.lockfreeOpen(fileName)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
parent := m.findParent(f)
|
||||
if parent == nil {
|
||||
log.Panic("parent of ", f.Name(), " is nil")
|
||||
}
|
||||
mem.RemoveFromMemDir(parent, f)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *MemMapFs) findParent(f *mem.FileData) *mem.FileData {
|
||||
pdir, _ := filepath.Split(f.Name())
|
||||
pdir = filepath.Clean(pdir)
|
||||
pfile, err := m.lockfreeOpen(pdir)
|
||||
if err != nil {
|
||||
return nil
|
||||
}
|
||||
return pfile
|
||||
}
|
||||
|
||||
func (m *MemMapFs) registerWithParent(f *mem.FileData) {
|
||||
if f == nil {
|
||||
return
|
||||
}
|
||||
parent := m.findParent(f)
|
||||
if parent == nil {
|
||||
pdir := filepath.Dir(filepath.Clean(f.Name()))
|
||||
err := m.lockfreeMkdir(pdir, 0777)
|
||||
if err != nil {
|
||||
//log.Println("Mkdir error:", err)
|
||||
return
|
||||
}
|
||||
parent, err = m.lockfreeOpen(pdir)
|
||||
if err != nil {
|
||||
//log.Println("Open after Mkdir error:", err)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
mem.InitializeDir(parent)
|
||||
mem.AddToMemDir(parent, f)
|
||||
}
|
||||
|
||||
func (m *MemMapFs) lockfreeMkdir(name string, perm os.FileMode) error {
|
||||
name = normalizePath(name)
|
||||
x, ok := m.getData()[name]
|
||||
if ok {
|
||||
// Only return ErrFileExists if it's a file, not a directory.
|
||||
i := mem.FileInfo{FileData: x}
|
||||
if !i.IsDir() {
|
||||
return ErrFileExists
|
||||
}
|
||||
} else {
|
||||
item := mem.CreateDir(name)
|
||||
m.getData()[name] = item
|
||||
m.registerWithParent(item)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *MemMapFs) Mkdir(name string, perm os.FileMode) error {
|
||||
name = normalizePath(name)
|
||||
|
||||
m.mu.RLock()
|
||||
_, ok := m.getData()[name]
|
||||
m.mu.RUnlock()
|
||||
if ok {
|
||||
return &os.PathError{Op: "mkdir", Path: name, Err: ErrFileExists}
|
||||
}
|
||||
|
||||
m.mu.Lock()
|
||||
item := mem.CreateDir(name)
|
||||
m.getData()[name] = item
|
||||
m.registerWithParent(item)
|
||||
m.mu.Unlock()
|
||||
|
||||
m.Chmod(name, perm)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *MemMapFs) MkdirAll(path string, perm os.FileMode) error {
|
||||
err := m.Mkdir(path, perm)
|
||||
if err != nil {
|
||||
if err.(*os.PathError).Err == ErrFileExists {
|
||||
return nil
|
||||
} else {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Handle some relative paths
|
||||
func normalizePath(path string) string {
|
||||
path = filepath.Clean(path)
|
||||
|
||||
switch path {
|
||||
case ".":
|
||||
return FilePathSeparator
|
||||
case "..":
|
||||
return FilePathSeparator
|
||||
default:
|
||||
return path
|
||||
}
|
||||
}
|
||||
|
||||
func (m *MemMapFs) Open(name string) (File, error) {
|
||||
f, err := m.open(name)
|
||||
if f != nil {
|
||||
return mem.NewReadOnlyFileHandle(f), err
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
|
||||
func (m *MemMapFs) openWrite(name string) (File, error) {
|
||||
f, err := m.open(name)
|
||||
if f != nil {
|
||||
return mem.NewFileHandle(f), err
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
|
||||
func (m *MemMapFs) open(name string) (*mem.FileData, error) {
|
||||
name = normalizePath(name)
|
||||
|
||||
m.mu.RLock()
|
||||
f, ok := m.getData()[name]
|
||||
m.mu.RUnlock()
|
||||
if !ok {
|
||||
return nil, &os.PathError{Op: "open", Path: name, Err: ErrFileNotFound}
|
||||
}
|
||||
return f, nil
|
||||
}
|
||||
|
||||
func (m *MemMapFs) lockfreeOpen(name string) (*mem.FileData, error) {
|
||||
name = normalizePath(name)
|
||||
f, ok := m.getData()[name]
|
||||
if ok {
|
||||
return f, nil
|
||||
} else {
|
||||
return nil, ErrFileNotFound
|
||||
}
|
||||
}
|
||||
|
||||
func (m *MemMapFs) OpenFile(name string, flag int, perm os.FileMode) (File, error) {
|
||||
chmod := false
|
||||
file, err := m.openWrite(name)
|
||||
if os.IsNotExist(err) && (flag&os.O_CREATE > 0) {
|
||||
file, err = m.Create(name)
|
||||
chmod = true
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if flag == os.O_RDONLY {
|
||||
file = mem.NewReadOnlyFileHandle(file.(*mem.File).Data())
|
||||
}
|
||||
if flag&os.O_APPEND > 0 {
|
||||
_, err = file.Seek(0, os.SEEK_END)
|
||||
if err != nil {
|
||||
file.Close()
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
if flag&os.O_TRUNC > 0 && flag&(os.O_RDWR|os.O_WRONLY) > 0 {
|
||||
err = file.Truncate(0)
|
||||
if err != nil {
|
||||
file.Close()
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
if chmod {
|
||||
m.Chmod(name, perm)
|
||||
}
|
||||
return file, nil
|
||||
}
|
||||
|
||||
func (m *MemMapFs) Remove(name string) error {
|
||||
name = normalizePath(name)
|
||||
|
||||
m.mu.Lock()
|
||||
defer m.mu.Unlock()
|
||||
|
||||
if _, ok := m.getData()[name]; ok {
|
||||
err := m.unRegisterWithParent(name)
|
||||
if err != nil {
|
||||
return &os.PathError{Op: "remove", Path: name, Err: err}
|
||||
}
|
||||
delete(m.getData(), name)
|
||||
} else {
|
||||
return &os.PathError{Op: "remove", Path: name, Err: os.ErrNotExist}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *MemMapFs) RemoveAll(path string) error {
|
||||
path = normalizePath(path)
|
||||
m.mu.Lock()
|
||||
m.unRegisterWithParent(path)
|
||||
m.mu.Unlock()
|
||||
|
||||
m.mu.RLock()
|
||||
defer m.mu.RUnlock()
|
||||
|
||||
for p, _ := range m.getData() {
|
||||
if strings.HasPrefix(p, path) {
|
||||
m.mu.RUnlock()
|
||||
m.mu.Lock()
|
||||
delete(m.getData(), p)
|
||||
m.mu.Unlock()
|
||||
m.mu.RLock()
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *MemMapFs) Rename(oldname, newname string) error {
|
||||
oldname = normalizePath(oldname)
|
||||
newname = normalizePath(newname)
|
||||
|
||||
if oldname == newname {
|
||||
return nil
|
||||
}
|
||||
|
||||
m.mu.RLock()
|
||||
defer m.mu.RUnlock()
|
||||
if _, ok := m.getData()[oldname]; ok {
|
||||
m.mu.RUnlock()
|
||||
m.mu.Lock()
|
||||
m.unRegisterWithParent(oldname)
|
||||
fileData := m.getData()[oldname]
|
||||
delete(m.getData(), oldname)
|
||||
mem.ChangeFileName(fileData, newname)
|
||||
m.getData()[newname] = fileData
|
||||
m.registerWithParent(fileData)
|
||||
m.mu.Unlock()
|
||||
m.mu.RLock()
|
||||
} else {
|
||||
return &os.PathError{Op: "rename", Path: oldname, Err: ErrFileNotFound}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *MemMapFs) Stat(name string) (os.FileInfo, error) {
|
||||
f, err := m.Open(name)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
fi := mem.GetFileInfo(f.(*mem.File).Data())
|
||||
return fi, nil
|
||||
}
|
||||
|
||||
func (m *MemMapFs) Chmod(name string, mode os.FileMode) error {
|
||||
name = normalizePath(name)
|
||||
|
||||
m.mu.RLock()
|
||||
f, ok := m.getData()[name]
|
||||
m.mu.RUnlock()
|
||||
if !ok {
|
||||
return &os.PathError{Op: "chmod", Path: name, Err: ErrFileNotFound}
|
||||
}
|
||||
|
||||
m.mu.Lock()
|
||||
mem.SetMode(f, mode)
|
||||
m.mu.Unlock()
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *MemMapFs) Chtimes(name string, atime time.Time, mtime time.Time) error {
|
||||
name = normalizePath(name)
|
||||
|
||||
m.mu.RLock()
|
||||
f, ok := m.getData()[name]
|
||||
m.mu.RUnlock()
|
||||
if !ok {
|
||||
return &os.PathError{Op: "chtimes", Path: name, Err: ErrFileNotFound}
|
||||
}
|
||||
|
||||
m.mu.Lock()
|
||||
mem.SetModTime(f, mtime)
|
||||
m.mu.Unlock()
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *MemMapFs) List() {
|
||||
for _, x := range m.data {
|
||||
y := mem.FileInfo{FileData: x}
|
||||
fmt.Println(x.Name(), y.Size())
|
||||
}
|
||||
}
|
||||
|
||||
// func debugMemMapList(fs Fs) {
|
||||
// if x, ok := fs.(*MemMapFs); ok {
|
||||
// x.List()
|
||||
// }
|
||||
// }
|
10
vendor/github.com/spf13/cobra/cobra/main.go → vendor/github.com/spf13/afero/memradix.go
generated
vendored
10
vendor/github.com/spf13/cobra/cobra/main.go → vendor/github.com/spf13/afero/memradix.go
generated
vendored
|
@ -1,4 +1,4 @@
|
|||
// Copyright © 2015 Steve Francia <spf@spf13.com>.
|
||||
// Copyright © 2014 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,4 @@
|
|||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package main
|
||||
|
||||
import "github.com/spf13/cobra/cobra/cmd"
|
||||
|
||||
func main() {
|
||||
cmd.Execute()
|
||||
}
|
||||
package afero
|
94
vendor/github.com/spf13/afero/os.go
generated
vendored
Normal file
94
vendor/github.com/spf13/afero/os.go
generated
vendored
Normal file
|
@ -0,0 +1,94 @@
|
|||
// Copyright © 2014 Steve Francia <spf@spf13.com>.
|
||||
// Copyright 2013 tsuru 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"
|
||||
"time"
|
||||
)
|
||||
|
||||
// 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
|
||||
// (http://golang.org/pkg/os/).
|
||||
type OsFs struct{}
|
||||
|
||||
func NewOsFs() Fs {
|
||||
return &OsFs{}
|
||||
}
|
||||
|
||||
func (OsFs) Name() string { return "OsFs" }
|
||||
|
||||
func (OsFs) Create(name string) (File, error) {
|
||||
f, e := os.Create(name)
|
||||
if f == nil {
|
||||
// while this looks strange, we need to return a bare nil (of type nil) not
|
||||
// a nil value of type *os.File or nil won't be nil
|
||||
return nil, e
|
||||
}
|
||||
return f, e
|
||||
}
|
||||
|
||||
func (OsFs) Mkdir(name string, perm os.FileMode) error {
|
||||
return os.Mkdir(name, perm)
|
||||
}
|
||||
|
||||
func (OsFs) MkdirAll(path string, perm os.FileMode) error {
|
||||
return os.MkdirAll(path, perm)
|
||||
}
|
||||
|
||||
func (OsFs) Open(name string) (File, error) {
|
||||
f, e := os.Open(name)
|
||||
if f == nil {
|
||||
// while this looks strange, we need to return a bare nil (of type nil) not
|
||||
// a nil value of type *os.File or nil won't be nil
|
||||
return nil, e
|
||||
}
|
||||
return f, e
|
||||
}
|
||||
|
||||
func (OsFs) OpenFile(name string, flag int, perm os.FileMode) (File, error) {
|
||||
f, e := os.OpenFile(name, flag, perm)
|
||||
if f == nil {
|
||||
// while this looks strange, we need to return a bare nil (of type nil) not
|
||||
// a nil value of type *os.File or nil won't be nil
|
||||
return nil, e
|
||||
}
|
||||
return f, e
|
||||
}
|
||||
|
||||
func (OsFs) Remove(name string) error {
|
||||
return os.Remove(name)
|
||||
}
|
||||
|
||||
func (OsFs) RemoveAll(path string) error {
|
||||
return os.RemoveAll(path)
|
||||
}
|
||||
|
||||
func (OsFs) Rename(oldname, newname string) error {
|
||||
return os.Rename(oldname, newname)
|
||||
}
|
||||
|
||||
func (OsFs) Stat(name string) (os.FileInfo, error) {
|
||||
return os.Stat(name)
|
||||
}
|
||||
|
||||
func (OsFs) Chmod(name string, mode os.FileMode) error {
|
||||
return os.Chmod(name, mode)
|
||||
}
|
||||
|
||||
func (OsFs) Chtimes(name string, atime time.Time, mtime time.Time) error {
|
||||
return os.Chtimes(name, atime, mtime)
|
||||
}
|
108
vendor/github.com/spf13/afero/path.go
generated
vendored
Normal file
108
vendor/github.com/spf13/afero/path.go
generated
vendored
Normal file
|
@ -0,0 +1,108 @@
|
|||
// Copyright ©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 (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sort"
|
||||
)
|
||||
|
||||
// readDirNames reads the directory named by dirname and returns
|
||||
// a sorted list of directory entries.
|
||||
// adapted from https://golang.org/src/path/filepath/path.go
|
||||
func readDirNames(fs Fs, dirname string) ([]string, error) {
|
||||
f, err := fs.Open(dirname)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
names, err := f.Readdirnames(-1)
|
||||
f.Close()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
sort.Strings(names)
|
||||
return names, nil
|
||||
}
|
||||
|
||||
// walk recursively descends path, calling walkFn
|
||||
// adapted from https://golang.org/src/path/filepath/path.go
|
||||
func walk(fs Fs, path string, info os.FileInfo, walkFn filepath.WalkFunc) error {
|
||||
err := walkFn(path, info, nil)
|
||||
if err != nil {
|
||||
if info.IsDir() && err == filepath.SkipDir {
|
||||
return nil
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
if !info.IsDir() {
|
||||
return nil
|
||||
}
|
||||
|
||||
names, err := readDirNames(fs, path)
|
||||
if err != nil {
|
||||
return walkFn(path, info, err)
|
||||
}
|
||||
|
||||
for _, name := range names {
|
||||
filename := filepath.Join(path, name)
|
||||
fileInfo, err := lstatIfOs(fs, filename)
|
||||
if err != nil {
|
||||
if err := walkFn(filename, fileInfo, err); err != nil && err != filepath.SkipDir {
|
||||
return err
|
||||
}
|
||||
} else {
|
||||
err = walk(fs, filename, fileInfo, walkFn)
|
||||
if err != nil {
|
||||
if !fileInfo.IsDir() || err != filepath.SkipDir {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
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)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// Walk walks the file tree rooted at root, calling walkFn for each file or
|
||||
// directory in the tree, including root. All errors that arise visiting files
|
||||
// and directories are filtered by walkFn. The files are walked in lexical
|
||||
// order, which makes the output deterministic but means that for very
|
||||
// large directories Walk can be inefficient.
|
||||
// Walk does not follow symbolic links.
|
||||
|
||||
func (a Afero) Walk(root string, walkFn filepath.WalkFunc) error {
|
||||
return Walk(a.Fs, root, walkFn)
|
||||
}
|
||||
|
||||
func Walk(fs Fs, root string, walkFn filepath.WalkFunc) error {
|
||||
info, err := lstatIfOs(fs, root)
|
||||
if err != nil {
|
||||
return walkFn(root, nil, err)
|
||||
}
|
||||
return walk(fs, root, info, walkFn)
|
||||
}
|
70
vendor/github.com/spf13/afero/readonlyfs.go
generated
vendored
Normal file
70
vendor/github.com/spf13/afero/readonlyfs.go
generated
vendored
Normal file
|
@ -0,0 +1,70 @@
|
|||
package afero
|
||||
|
||||
import (
|
||||
"os"
|
||||
"syscall"
|
||||
"time"
|
||||
)
|
||||
|
||||
type ReadOnlyFs struct {
|
||||
source Fs
|
||||
}
|
||||
|
||||
func NewReadOnlyFs(source Fs) Fs {
|
||||
return &ReadOnlyFs{source: source}
|
||||
}
|
||||
|
||||
func (r *ReadOnlyFs) ReadDir(name string) ([]os.FileInfo, error) {
|
||||
return ReadDir(r.source, name)
|
||||
}
|
||||
|
||||
func (r *ReadOnlyFs) Chtimes(n string, a, m time.Time) error {
|
||||
return syscall.EPERM
|
||||
}
|
||||
|
||||
func (r *ReadOnlyFs) Chmod(n string, m os.FileMode) error {
|
||||
return syscall.EPERM
|
||||
}
|
||||
|
||||
func (r *ReadOnlyFs) Name() string {
|
||||
return "ReadOnlyFilter"
|
||||
}
|
||||
|
||||
func (r *ReadOnlyFs) Stat(name string) (os.FileInfo, error) {
|
||||
return r.source.Stat(name)
|
||||
}
|
||||
|
||||
func (r *ReadOnlyFs) Rename(o, n string) error {
|
||||
return syscall.EPERM
|
||||
}
|
||||
|
||||
func (r *ReadOnlyFs) RemoveAll(p string) error {
|
||||
return syscall.EPERM
|
||||
}
|
||||
|
||||
func (r *ReadOnlyFs) Remove(n string) error {
|
||||
return syscall.EPERM
|
||||
}
|
||||
|
||||
func (r *ReadOnlyFs) OpenFile(name string, flag int, perm os.FileMode) (File, error) {
|
||||
if flag&(os.O_WRONLY|syscall.O_RDWR|os.O_APPEND|os.O_CREATE|os.O_TRUNC) != 0 {
|
||||
return nil, syscall.EPERM
|
||||
}
|
||||
return r.source.OpenFile(name, flag, perm)
|
||||
}
|
||||
|
||||
func (r *ReadOnlyFs) Open(n string) (File, error) {
|
||||
return r.source.Open(n)
|
||||
}
|
||||
|
||||
func (r *ReadOnlyFs) Mkdir(n string, p os.FileMode) error {
|
||||
return syscall.EPERM
|
||||
}
|
||||
|
||||
func (r *ReadOnlyFs) MkdirAll(n string, p os.FileMode) error {
|
||||
return syscall.EPERM
|
||||
}
|
||||
|
||||
func (r *ReadOnlyFs) Create(n string) (File, error) {
|
||||
return nil, syscall.EPERM
|
||||
}
|
214
vendor/github.com/spf13/afero/regexpfs.go
generated
vendored
Normal file
214
vendor/github.com/spf13/afero/regexpfs.go
generated
vendored
Normal file
|
@ -0,0 +1,214 @@
|
|||
package afero
|
||||
|
||||
import (
|
||||
"os"
|
||||
"regexp"
|
||||
"syscall"
|
||||
"time"
|
||||
)
|
||||
|
||||
// The RegexpFs filters files (not directories) by regular expression. Only
|
||||
// files matching the given regexp will be allowed, all others get a ENOENT error (
|
||||
// "No such file or directory").
|
||||
//
|
||||
type RegexpFs struct {
|
||||
re *regexp.Regexp
|
||||
source Fs
|
||||
}
|
||||
|
||||
func NewRegexpFs(source Fs, re *regexp.Regexp) Fs {
|
||||
return &RegexpFs{source: source, re: re}
|
||||
}
|
||||
|
||||
type RegexpFile struct {
|
||||
f File
|
||||
re *regexp.Regexp
|
||||
}
|
||||
|
||||
func (r *RegexpFs) matchesName(name string) error {
|
||||
if r.re == nil {
|
||||
return nil
|
||||
}
|
||||
if r.re.MatchString(name) {
|
||||
return nil
|
||||
}
|
||||
return syscall.ENOENT
|
||||
}
|
||||
|
||||
func (r *RegexpFs) dirOrMatches(name string) error {
|
||||
dir, err := IsDir(r.source, name)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if dir {
|
||||
return nil
|
||||
}
|
||||
return r.matchesName(name)
|
||||
}
|
||||
|
||||
func (r *RegexpFs) Chtimes(name string, a, m time.Time) error {
|
||||
if err := r.dirOrMatches(name); err != nil {
|
||||
return err
|
||||
}
|
||||
return r.source.Chtimes(name, a, m)
|
||||
}
|
||||
|
||||
func (r *RegexpFs) Chmod(name string, mode os.FileMode) error {
|
||||
if err := r.dirOrMatches(name); err != nil {
|
||||
return err
|
||||
}
|
||||
return r.source.Chmod(name, mode)
|
||||
}
|
||||
|
||||
func (r *RegexpFs) Name() string {
|
||||
return "RegexpFs"
|
||||
}
|
||||
|
||||
func (r *RegexpFs) Stat(name string) (os.FileInfo, error) {
|
||||
if err := r.dirOrMatches(name); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return r.source.Stat(name)
|
||||
}
|
||||
|
||||
func (r *RegexpFs) Rename(oldname, newname string) error {
|
||||
dir, err := IsDir(r.source, oldname)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if dir {
|
||||
return nil
|
||||
}
|
||||
if err := r.matchesName(oldname); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := r.matchesName(newname); err != nil {
|
||||
return err
|
||||
}
|
||||
return r.source.Rename(oldname, newname)
|
||||
}
|
||||
|
||||
func (r *RegexpFs) RemoveAll(p string) error {
|
||||
dir, err := IsDir(r.source, p)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !dir {
|
||||
if err := r.matchesName(p); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return r.source.RemoveAll(p)
|
||||
}
|
||||
|
||||
func (r *RegexpFs) Remove(name string) error {
|
||||
if err := r.dirOrMatches(name); err != nil {
|
||||
return err
|
||||
}
|
||||
return r.source.Remove(name)
|
||||
}
|
||||
|
||||
func (r *RegexpFs) OpenFile(name string, flag int, perm os.FileMode) (File, error) {
|
||||
if err := r.dirOrMatches(name); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return r.source.OpenFile(name, flag, perm)
|
||||
}
|
||||
|
||||
func (r *RegexpFs) Open(name string) (File, error) {
|
||||
dir, err := IsDir(r.source, name)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if !dir {
|
||||
if err := r.matchesName(name); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
f, err := r.source.Open(name)
|
||||
return &RegexpFile{f: f, re: r.re}, nil
|
||||
}
|
||||
|
||||
func (r *RegexpFs) Mkdir(n string, p os.FileMode) error {
|
||||
return r.source.Mkdir(n, p)
|
||||
}
|
||||
|
||||
func (r *RegexpFs) MkdirAll(n string, p os.FileMode) error {
|
||||
return r.source.MkdirAll(n, p)
|
||||
}
|
||||
|
||||
func (r *RegexpFs) Create(name string) (File, error) {
|
||||
if err := r.matchesName(name); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return r.source.Create(name)
|
||||
}
|
||||
|
||||
func (f *RegexpFile) Close() error {
|
||||
return f.f.Close()
|
||||
}
|
||||
|
||||
func (f *RegexpFile) Read(s []byte) (int, error) {
|
||||
return f.f.Read(s)
|
||||
}
|
||||
|
||||
func (f *RegexpFile) ReadAt(s []byte, o int64) (int, error) {
|
||||
return f.f.ReadAt(s, o)
|
||||
}
|
||||
|
||||
func (f *RegexpFile) Seek(o int64, w int) (int64, error) {
|
||||
return f.f.Seek(o, w)
|
||||
}
|
||||
|
||||
func (f *RegexpFile) Write(s []byte) (int, error) {
|
||||
return f.f.Write(s)
|
||||
}
|
||||
|
||||
func (f *RegexpFile) WriteAt(s []byte, o int64) (int, error) {
|
||||
return f.f.WriteAt(s, o)
|
||||
}
|
||||
|
||||
func (f *RegexpFile) Name() string {
|
||||
return f.f.Name()
|
||||
}
|
||||
|
||||
func (f *RegexpFile) Readdir(c int) (fi []os.FileInfo, err error) {
|
||||
var rfi []os.FileInfo
|
||||
rfi, err = f.f.Readdir(c)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, i := range rfi {
|
||||
if i.IsDir() || f.re.MatchString(i.Name()) {
|
||||
fi = append(fi, i)
|
||||
}
|
||||
}
|
||||
return fi, nil
|
||||
}
|
||||
|
||||
func (f *RegexpFile) Readdirnames(c int) (n []string, err error) {
|
||||
fi, err := f.Readdir(c)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, s := range fi {
|
||||
n = append(n, s.Name())
|
||||
}
|
||||
return n, nil
|
||||
}
|
||||
|
||||
func (f *RegexpFile) Stat() (os.FileInfo, error) {
|
||||
return f.f.Stat()
|
||||
}
|
||||
|
||||
func (f *RegexpFile) Sync() error {
|
||||
return f.f.Sync()
|
||||
}
|
||||
|
||||
func (f *RegexpFile) Truncate(s int64) error {
|
||||
return f.f.Truncate(s)
|
||||
}
|
||||
|
||||
func (f *RegexpFile) WriteString(s string) (int, error) {
|
||||
return f.f.WriteString(s)
|
||||
}
|
274
vendor/github.com/spf13/afero/unionFile.go
generated
vendored
Normal file
274
vendor/github.com/spf13/afero/unionFile.go
generated
vendored
Normal file
|
@ -0,0 +1,274 @@
|
|||
package afero
|
||||
|
||||
import (
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"syscall"
|
||||
)
|
||||
|
||||
// The UnionFile implements the afero.File interface and will be returned
|
||||
// when reading a directory present at least in the overlay or opening a file
|
||||
// for writing.
|
||||
//
|
||||
// The calls to
|
||||
// Readdir() and Readdirnames() merge the file os.FileInfo / names from the
|
||||
// base and the overlay - for files present in both layers, only those
|
||||
// from the overlay will be used.
|
||||
//
|
||||
// When opening files for writing (Create() / OpenFile() with the right flags)
|
||||
// the operations will be done in both layers, starting with the overlay. A
|
||||
// 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
|
||||
}
|
||||
|
||||
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.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 {
|
||||
// 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 {
|
||||
// only overwrite err in case the seek fails: we need to
|
||||
// report an eventual io.EOF to the caller
|
||||
err = seekErr
|
||||
}
|
||||
}
|
||||
return n, err
|
||||
}
|
||||
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)
|
||||
}
|
||||
return n, err
|
||||
}
|
||||
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)
|
||||
}
|
||||
return pos, err
|
||||
}
|
||||
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)
|
||||
}
|
||||
return n, err
|
||||
}
|
||||
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)
|
||||
}
|
||||
return n, err
|
||||
}
|
||||
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()
|
||||
}
|
||||
return f.base.Name()
|
||||
}
|
||||
|
||||
// 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) {
|
||||
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)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, fi := range rfi {
|
||||
files[fi.Name()] = fi
|
||||
}
|
||||
}
|
||||
|
||||
if f.base != nil {
|
||||
rfi, 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)
|
||||
}
|
||||
}
|
||||
if c == -1 {
|
||||
return f.files[f.off:], nil
|
||||
}
|
||||
defer func() { f.off += c }()
|
||||
return f.files[f.off:c], nil
|
||||
}
|
||||
|
||||
func (f *UnionFile) Readdirnames(c int) ([]string, error) {
|
||||
rfi, err := f.Readdir(c)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var names []string
|
||||
for _, fi := range rfi {
|
||||
names = append(names, fi.Name())
|
||||
}
|
||||
return names, nil
|
||||
}
|
||||
|
||||
func (f *UnionFile) Stat() (os.FileInfo, error) {
|
||||
if f.layer != nil {
|
||||
return f.layer.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()
|
||||
}
|
||||
return err
|
||||
}
|
||||
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)
|
||||
}
|
||||
return err
|
||||
}
|
||||
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)
|
||||
}
|
||||
return n, err
|
||||
}
|
||||
if f.base != nil {
|
||||
return f.base.WriteString(s)
|
||||
}
|
||||
return 0, BADFD
|
||||
}
|
||||
|
||||
func copyToLayer(base Fs, layer Fs, name string) error {
|
||||
bfh, err := base.Open(name)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer bfh.Close()
|
||||
|
||||
// First make sure the directory exists
|
||||
exists, err := Exists(layer, filepath.Dir(name))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !exists {
|
||||
err = layer.MkdirAll(filepath.Dir(name), 0777) // FIXME?
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
// Create the file on the overlay
|
||||
lfh, err := layer.Create(name)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
n, err := io.Copy(lfh, bfh)
|
||||
if err != nil {
|
||||
// If anything fails, clean up the file
|
||||
layer.Remove(name)
|
||||
lfh.Close()
|
||||
return err
|
||||
}
|
||||
|
||||
bfi, err := bfh.Stat()
|
||||
if err != nil || bfi.Size() != n {
|
||||
layer.Remove(name)
|
||||
lfh.Close()
|
||||
return syscall.EIO
|
||||
}
|
||||
|
||||
err = lfh.Close()
|
||||
if err != nil {
|
||||
layer.Remove(name)
|
||||
lfh.Close()
|
||||
return err
|
||||
}
|
||||
return layer.Chtimes(name, bfi.ModTime(), bfi.ModTime())
|
||||
}
|
331
vendor/github.com/spf13/afero/util.go
generated
vendored
Normal file
331
vendor/github.com/spf13/afero/util.go
generated
vendored
Normal file
|
@ -0,0 +1,331 @@
|
|||
// Copyright ©2015 Steve Francia <spf@spf13.com>
|
||||
// Portions Copyright ©2015 The Hugo Authors
|
||||
// Portions Copyright 2016-present Bjørn Erik Pedersen <bjorn.erik.pedersen@gmail.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 (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"io"
|
||||
"log"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"unicode"
|
||||
|
||||
"golang.org/x/text/transform"
|
||||
"golang.org/x/text/unicode/norm"
|
||||
)
|
||||
|
||||
// Filepath separator defined by os.Separator.
|
||||
const FilePathSeparator = string(filepath.Separator)
|
||||
|
||||
// Takes a reader and a path and writes the content
|
||||
func (a Afero) WriteReader(path string, r io.Reader) (err error) {
|
||||
return WriteReader(a.Fs, path, r)
|
||||
}
|
||||
|
||||
func WriteReader(fs Fs, path string, r io.Reader) (err error) {
|
||||
dir, _ := filepath.Split(path)
|
||||
ospath := filepath.FromSlash(dir)
|
||||
|
||||
if ospath != "" {
|
||||
err = fs.MkdirAll(ospath, 0777) // rwx, rw, r
|
||||
if err != nil {
|
||||
if err != os.ErrExist {
|
||||
log.Panicln(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
file, err := fs.Create(path)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
defer file.Close()
|
||||
|
||||
_, err = io.Copy(file, r)
|
||||
return
|
||||
}
|
||||
|
||||
// Same as WriteReader but checks to see if file/directory already exists.
|
||||
func (a Afero) SafeWriteReader(path string, r io.Reader) (err error) {
|
||||
return SafeWriteReader(a.Fs, path, r)
|
||||
}
|
||||
|
||||
func SafeWriteReader(fs Fs, path string, r io.Reader) (err error) {
|
||||
dir, _ := filepath.Split(path)
|
||||
ospath := filepath.FromSlash(dir)
|
||||
|
||||
if ospath != "" {
|
||||
err = fs.MkdirAll(ospath, 0777) // rwx, rw, r
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
exists, err := Exists(fs, path)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
if exists {
|
||||
return fmt.Errorf("%v already exists", path)
|
||||
}
|
||||
|
||||
file, err := fs.Create(path)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
defer file.Close()
|
||||
|
||||
_, err = io.Copy(file, r)
|
||||
return
|
||||
}
|
||||
|
||||
func (a Afero) GetTempDir(subPath string) string {
|
||||
return GetTempDir(a.Fs, subPath)
|
||||
}
|
||||
|
||||
// GetTempDir returns the default temp directory with trailing slash
|
||||
// if subPath is not empty then it will be created recursively with mode 777 rwx rwx rwx
|
||||
func GetTempDir(fs Fs, subPath string) string {
|
||||
addSlash := func(p string) string {
|
||||
if FilePathSeparator != p[len(p)-1:] {
|
||||
p = p + FilePathSeparator
|
||||
}
|
||||
return p
|
||||
}
|
||||
dir := addSlash(os.TempDir())
|
||||
|
||||
if subPath != "" {
|
||||
// preserve windows backslash :-(
|
||||
if FilePathSeparator == "\\" {
|
||||
subPath = strings.Replace(subPath, "\\", "____", -1)
|
||||
}
|
||||
dir = dir + UnicodeSanitize((subPath))
|
||||
if FilePathSeparator == "\\" {
|
||||
dir = strings.Replace(dir, "____", "\\", -1)
|
||||
}
|
||||
|
||||
if exists, _ := Exists(fs, dir); exists {
|
||||
return addSlash(dir)
|
||||
}
|
||||
|
||||
err := fs.MkdirAll(dir, 0777)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
dir = addSlash(dir)
|
||||
}
|
||||
return dir
|
||||
}
|
||||
|
||||
// Rewrite string to remove non-standard path characters
|
||||
func UnicodeSanitize(s string) string {
|
||||
source := []rune(s)
|
||||
target := make([]rune, 0, len(source))
|
||||
|
||||
for _, r := range source {
|
||||
if unicode.IsLetter(r) ||
|
||||
unicode.IsDigit(r) ||
|
||||
unicode.IsMark(r) ||
|
||||
r == '.' ||
|
||||
r == '/' ||
|
||||
r == '\\' ||
|
||||
r == '_' ||
|
||||
r == '-' ||
|
||||
r == '%' ||
|
||||
r == ' ' ||
|
||||
r == '#' {
|
||||
target = append(target, r)
|
||||
}
|
||||
}
|
||||
|
||||
return string(target)
|
||||
}
|
||||
|
||||
// Transform characters with accents into plan forms
|
||||
func NeuterAccents(s string) string {
|
||||
t := transform.Chain(norm.NFD, transform.RemoveFunc(isMn), norm.NFC)
|
||||
result, _, _ := transform.String(t, string(s))
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
func isMn(r rune) bool {
|
||||
return unicode.Is(unicode.Mn, r) // Mn: nonspacing marks
|
||||
}
|
||||
|
||||
func (a Afero) FileContainsBytes(filename string, subslice []byte) (bool, error) {
|
||||
return FileContainsBytes(a.Fs, filename, subslice)
|
||||
}
|
||||
|
||||
// Check if a file contains a specified byte slice.
|
||||
func FileContainsBytes(fs Fs, filename string, subslice []byte) (bool, error) {
|
||||
f, err := fs.Open(filename)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
defer f.Close()
|
||||
|
||||
return readerContainsAny(f, subslice), nil
|
||||
}
|
||||
|
||||
func (a Afero) FileContainsAnyBytes(filename string, subslices [][]byte) (bool, error) {
|
||||
return FileContainsAnyBytes(a.Fs, filename, subslices)
|
||||
}
|
||||
|
||||
// Check if a file contains any of the specified byte slices.
|
||||
func FileContainsAnyBytes(fs Fs, filename string, subslices [][]byte) (bool, error) {
|
||||
f, err := fs.Open(filename)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
defer f.Close()
|
||||
|
||||
return readerContainsAny(f, subslices...), nil
|
||||
}
|
||||
|
||||
// readerContains reports whether any of the subslices is within r.
|
||||
func readerContainsAny(r io.Reader, subslices ...[]byte) bool {
|
||||
|
||||
if r == nil || len(subslices) == 0 {
|
||||
return false
|
||||
}
|
||||
|
||||
largestSlice := 0
|
||||
|
||||
for _, sl := range subslices {
|
||||
if len(sl) > largestSlice {
|
||||
largestSlice = len(sl)
|
||||
}
|
||||
}
|
||||
|
||||
if largestSlice == 0 {
|
||||
return false
|
||||
}
|
||||
|
||||
bufflen := largestSlice * 4
|
||||
halflen := bufflen / 2
|
||||
buff := make([]byte, bufflen)
|
||||
var err error
|
||||
var n, i int
|
||||
|
||||
for {
|
||||
i++
|
||||
if i == 1 {
|
||||
n, err = io.ReadAtLeast(r, buff[:halflen], halflen)
|
||||
} else {
|
||||
if i != 2 {
|
||||
// shift left to catch overlapping matches
|
||||
copy(buff[:], buff[halflen:])
|
||||
}
|
||||
n, err = io.ReadAtLeast(r, buff[halflen:], halflen)
|
||||
}
|
||||
|
||||
if n > 0 {
|
||||
for _, sl := range subslices {
|
||||
if bytes.Contains(buff, sl) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
break
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (a Afero) DirExists(path string) (bool, error) {
|
||||
return DirExists(a.Fs, path)
|
||||
}
|
||||
|
||||
// DirExists checks if a path exists and is a directory.
|
||||
func DirExists(fs Fs, path string) (bool, error) {
|
||||
fi, err := fs.Stat(path)
|
||||
if err == nil && fi.IsDir() {
|
||||
return true, nil
|
||||
}
|
||||
if os.IsNotExist(err) {
|
||||
return false, nil
|
||||
}
|
||||
return false, err
|
||||
}
|
||||
|
||||
func (a Afero) IsDir(path string) (bool, error) {
|
||||
return IsDir(a.Fs, path)
|
||||
}
|
||||
|
||||
// IsDir checks if a given path is a directory.
|
||||
func IsDir(fs Fs, path string) (bool, error) {
|
||||
fi, err := fs.Stat(path)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
return fi.IsDir(), nil
|
||||
}
|
||||
|
||||
func (a Afero) IsEmpty(path string) (bool, error) {
|
||||
return IsEmpty(a.Fs, path)
|
||||
}
|
||||
|
||||
// IsEmpty checks if a given file or directory is empty.
|
||||
func IsEmpty(fs Fs, path string) (bool, error) {
|
||||
if b, _ := Exists(fs, path); !b {
|
||||
return false, fmt.Errorf("%q path does not exist", path)
|
||||
}
|
||||
fi, err := fs.Stat(path)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
if fi.IsDir() {
|
||||
f, err := fs.Open(path)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
defer f.Close()
|
||||
list, err := f.Readdir(-1)
|
||||
return len(list) == 0, nil
|
||||
}
|
||||
return fi.Size() == 0, nil
|
||||
}
|
||||
|
||||
func (a Afero) Exists(path string) (bool, error) {
|
||||
return Exists(a.Fs, path)
|
||||
}
|
||||
|
||||
// Check if a file or directory exists.
|
||||
func Exists(fs Fs, path string) (bool, error) {
|
||||
_, err := fs.Stat(path)
|
||||
if err == nil {
|
||||
return true, nil
|
||||
}
|
||||
if os.IsNotExist(err) {
|
||||
return false, nil
|
||||
}
|
||||
return false, err
|
||||
}
|
||||
|
||||
func FullBaseFsPath(basePathFs *BasePathFs, relativePath string) string {
|
||||
combinedPath := filepath.Join(basePathFs.path, relativePath)
|
||||
if parent, ok := basePathFs.source.(*BasePathFs); ok {
|
||||
return FullBaseFsPath(parent, combinedPath)
|
||||
}
|
||||
|
||||
return combinedPath
|
||||
}
|
38
vendor/github.com/spf13/cast/Makefile
generated
vendored
Normal file
38
vendor/github.com/spf13/cast/Makefile
generated
vendored
Normal file
|
@ -0,0 +1,38 @@
|
|||
# A Self-Documenting Makefile: http://marmelab.com/blog/2016/02/29/auto-documented-makefile.html
|
||||
|
||||
.PHONY: check fmt lint test test-race vet test-cover-html help
|
||||
.DEFAULT_GOAL := help
|
||||
|
||||
check: test-race fmt vet lint ## Run tests and linters
|
||||
|
||||
test: ## Run tests
|
||||
go test ./...
|
||||
|
||||
test-race: ## Run tests with race detector
|
||||
go test -race ./...
|
||||
|
||||
fmt: ## Run gofmt linter
|
||||
@for d in `go list` ; do \
|
||||
if [ "`gofmt -l -s $$GOPATH/src/$$d | tee /dev/stderr`" ]; then \
|
||||
echo "^ improperly formatted go files" && echo && exit 1; \
|
||||
fi \
|
||||
done
|
||||
|
||||
lint: ## Run golint linter
|
||||
@for d in `go list` ; do \
|
||||
if [ "`golint $$d | tee /dev/stderr`" ]; then \
|
||||
echo "^ golint errors!" && echo && exit 1; \
|
||||
fi \
|
||||
done
|
||||
|
||||
vet: ## Run go vet linter
|
||||
@if [ "`go vet | tee /dev/stderr`" ]; then \
|
||||
echo "^ go vet errors!" && echo && exit 1; \
|
||||
fi
|
||||
|
||||
test-cover-html: ## Generate test coverage report
|
||||
go test -coverprofile=coverage.out -covermode=count
|
||||
go tool cover -func=coverage.out
|
||||
|
||||
help:
|
||||
@grep -E '^[a-zA-Z0-9_-]+:.*?## .*$$' $(MAKEFILE_LIST) | sort | awk 'BEGIN {FS = ":.*?## "}; {printf "\033[36m%-30s\033[0m %s\n", $$1, $$2}'
|
3
vendor/github.com/spf13/cast/README.md
generated
vendored
3
vendor/github.com/spf13/cast/README.md
generated
vendored
|
@ -1,5 +1,8 @@
|
|||
cast
|
||||
====
|
||||
[](https://godoc.org/github.com/spf13/cast)
|
||||
[](https://travis-ci.org/spf13/cast)
|
||||
[](https://goreportcard.com/report/github.com/spf13/cast)
|
||||
|
||||
Easy and safe casting from one type to another in Go
|
||||
|
||||
|
|
86
vendor/github.com/spf13/cast/cast.go
generated
vendored
86
vendor/github.com/spf13/cast/cast.go
generated
vendored
|
@ -3,71 +3,157 @@
|
|||
// Use of this source code is governed by an MIT-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
// Package cast provides easy and safe casting in Go.
|
||||
package cast
|
||||
|
||||
import "time"
|
||||
|
||||
// ToBool casts an interface to a bool type.
|
||||
func ToBool(i interface{}) bool {
|
||||
v, _ := ToBoolE(i)
|
||||
return v
|
||||
}
|
||||
|
||||
// ToTime casts an interface to a time.Time type.
|
||||
func ToTime(i interface{}) time.Time {
|
||||
v, _ := ToTimeE(i)
|
||||
return v
|
||||
}
|
||||
|
||||
// ToDuration casts an interface to a time.Duration type.
|
||||
func ToDuration(i interface{}) time.Duration {
|
||||
v, _ := ToDurationE(i)
|
||||
return v
|
||||
}
|
||||
|
||||
// ToFloat64 casts an interface to a float64 type.
|
||||
func ToFloat64(i interface{}) float64 {
|
||||
v, _ := ToFloat64E(i)
|
||||
return v
|
||||
}
|
||||
|
||||
// ToFloat32 casts an interface to a float32 type.
|
||||
func ToFloat32(i interface{}) float32 {
|
||||
v, _ := ToFloat32E(i)
|
||||
return v
|
||||
}
|
||||
|
||||
// ToInt64 casts an interface to an int64 type.
|
||||
func ToInt64(i interface{}) int64 {
|
||||
v, _ := ToInt64E(i)
|
||||
return v
|
||||
}
|
||||
|
||||
// ToInt32 casts an interface to an int32 type.
|
||||
func ToInt32(i interface{}) int32 {
|
||||
v, _ := ToInt32E(i)
|
||||
return v
|
||||
}
|
||||
|
||||
// ToInt16 casts an interface to an int16 type.
|
||||
func ToInt16(i interface{}) int16 {
|
||||
v, _ := ToInt16E(i)
|
||||
return v
|
||||
}
|
||||
|
||||
// ToInt8 casts an interface to an int8 type.
|
||||
func ToInt8(i interface{}) int8 {
|
||||
v, _ := ToInt8E(i)
|
||||
return v
|
||||
}
|
||||
|
||||
// ToInt casts an interface to an int type.
|
||||
func ToInt(i interface{}) int {
|
||||
v, _ := ToIntE(i)
|
||||
return v
|
||||
}
|
||||
|
||||
// ToUint casts an interface to a uint type.
|
||||
func ToUint(i interface{}) uint {
|
||||
v, _ := ToUintE(i)
|
||||
return v
|
||||
}
|
||||
|
||||
// ToUint64 casts an interface to a uint64 type.
|
||||
func ToUint64(i interface{}) uint64 {
|
||||
v, _ := ToUint64E(i)
|
||||
return v
|
||||
}
|
||||
|
||||
// ToUint32 casts an interface to a uint32 type.
|
||||
func ToUint32(i interface{}) uint32 {
|
||||
v, _ := ToUint32E(i)
|
||||
return v
|
||||
}
|
||||
|
||||
// ToUint16 casts an interface to a uint16 type.
|
||||
func ToUint16(i interface{}) uint16 {
|
||||
v, _ := ToUint16E(i)
|
||||
return v
|
||||
}
|
||||
|
||||
// ToUint8 casts an interface to a uint8 type.
|
||||
func ToUint8(i interface{}) uint8 {
|
||||
v, _ := ToUint8E(i)
|
||||
return v
|
||||
}
|
||||
|
||||
// ToString casts an interface to a string type.
|
||||
func ToString(i interface{}) string {
|
||||
v, _ := ToStringE(i)
|
||||
return v
|
||||
}
|
||||
|
||||
// ToStringMapString casts an interface to a map[string]string type.
|
||||
func ToStringMapString(i interface{}) map[string]string {
|
||||
v, _ := ToStringMapStringE(i)
|
||||
return v
|
||||
}
|
||||
|
||||
// ToStringMapStringSlice casts an interface to a map[string][]string type.
|
||||
func ToStringMapStringSlice(i interface{}) map[string][]string {
|
||||
v, _ := ToStringMapStringSliceE(i)
|
||||
return v
|
||||
}
|
||||
|
||||
// ToStringMapBool casts an interface to a map[string]bool type.
|
||||
func ToStringMapBool(i interface{}) map[string]bool {
|
||||
v, _ := ToStringMapBoolE(i)
|
||||
return v
|
||||
}
|
||||
|
||||
// ToStringMap casts an interface to a map[string]interface{} type.
|
||||
func ToStringMap(i interface{}) map[string]interface{} {
|
||||
v, _ := ToStringMapE(i)
|
||||
return v
|
||||
}
|
||||
|
||||
// ToSlice casts an interface to a []interface{} type.
|
||||
func ToSlice(i interface{}) []interface{} {
|
||||
v, _ := ToSliceE(i)
|
||||
return v
|
||||
}
|
||||
|
||||
// ToBoolSlice casts an interface to a []bool type.
|
||||
func ToBoolSlice(i interface{}) []bool {
|
||||
v, _ := ToBoolSliceE(i)
|
||||
return v
|
||||
}
|
||||
|
||||
// ToStringSlice casts an interface to a []string type.
|
||||
func ToStringSlice(i interface{}) []string {
|
||||
v, _ := ToStringSliceE(i)
|
||||
return v
|
||||
}
|
||||
|
||||
// ToIntSlice casts an interface to a []int type.
|
||||
func ToIntSlice(i interface{}) []int {
|
||||
v, _ := ToIntSliceE(i)
|
||||
return v
|
||||
}
|
||||
|
||||
// ToDurationSlice casts an interface to a []time.Duration type.
|
||||
func ToDurationSlice(i interface{}) []time.Duration {
|
||||
v, _ := ToDurationSliceE(i)
|
||||
return v
|
||||
}
|
||||
|
|
164
vendor/github.com/spf13/cast/cast_test.go
generated
vendored
164
vendor/github.com/spf13/cast/cast_test.go
generated
vendored
|
@ -1,164 +0,0 @@
|
|||
// Copyright © 2014 Steve Francia <spf@spf13.com>.
|
||||
//
|
||||
// Use of this source code is governed by an MIT-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
package cast
|
||||
|
||||
import (
|
||||
"html/template"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
func TestToInt(t *testing.T) {
|
||||
var eight interface{} = 8
|
||||
assert.Equal(t, ToInt(8), 8)
|
||||
assert.Equal(t, ToInt(8.31), 8)
|
||||
assert.Equal(t, ToInt("8"), 8)
|
||||
assert.Equal(t, ToInt(true), 1)
|
||||
assert.Equal(t, ToInt(false), 0)
|
||||
assert.Equal(t, ToInt(eight), 8)
|
||||
}
|
||||
|
||||
func TestToFloat64(t *testing.T) {
|
||||
var eight interface{} = 8
|
||||
assert.Equal(t, ToFloat64(8), 8.00)
|
||||
assert.Equal(t, ToFloat64(8.31), 8.31)
|
||||
assert.Equal(t, ToFloat64("8.31"), 8.31)
|
||||
assert.Equal(t, ToFloat64(eight), 8.0)
|
||||
}
|
||||
|
||||
func TestToString(t *testing.T) {
|
||||
var foo interface{} = "one more time"
|
||||
assert.Equal(t, ToString(8), "8")
|
||||
assert.Equal(t, ToString(8.12), "8.12")
|
||||
assert.Equal(t, ToString([]byte("one time")), "one time")
|
||||
assert.Equal(t, ToString(template.HTML("one time")), "one time")
|
||||
assert.Equal(t, ToString(template.URL("http://somehost.foo")), "http://somehost.foo")
|
||||
assert.Equal(t, ToString(foo), "one more time")
|
||||
assert.Equal(t, ToString(nil), "")
|
||||
assert.Equal(t, ToString(true), "true")
|
||||
assert.Equal(t, ToString(false), "false")
|
||||
}
|
||||
|
||||
type foo struct {
|
||||
val string
|
||||
}
|
||||
|
||||
func (x foo) String() string {
|
||||
return x.val
|
||||
}
|
||||
|
||||
func TestStringerToString(t *testing.T) {
|
||||
|
||||
var x foo
|
||||
x.val = "bar"
|
||||
assert.Equal(t, "bar", ToString(x))
|
||||
}
|
||||
|
||||
type fu struct {
|
||||
val string
|
||||
}
|
||||
|
||||
func (x fu) Error() string {
|
||||
return x.val
|
||||
}
|
||||
|
||||
func TestErrorToString(t *testing.T) {
|
||||
var x fu
|
||||
x.val = "bar"
|
||||
assert.Equal(t, "bar", ToString(x))
|
||||
}
|
||||
|
||||
func TestMaps(t *testing.T) {
|
||||
var taxonomies = map[interface{}]interface{}{"tag": "tags", "group": "groups"}
|
||||
var stringMapBool = map[interface{}]interface{}{"v1": true, "v2": false}
|
||||
|
||||
// ToStringMapString inputs/outputs
|
||||
var stringMapString = map[string]string{"key 1": "value 1", "key 2": "value 2", "key 3": "value 3"}
|
||||
var stringMapInterface = map[string]interface{}{"key 1": "value 1", "key 2": "value 2", "key 3": "value 3"}
|
||||
var interfaceMapString = map[interface{}]string{"key 1": "value 1", "key 2": "value 2", "key 3": "value 3"}
|
||||
var interfaceMapInterface = map[interface{}]interface{}{"key 1": "value 1", "key 2": "value 2", "key 3": "value 3"}
|
||||
|
||||
// ToStringMapStringSlice inputs/outputs
|
||||
var stringMapStringSlice = map[string][]string{"key 1": []string{"value 1", "value 2", "value 3"}, "key 2": []string{"value 1", "value 2", "value 3"}, "key 3": []string{"value 1", "value 2", "value 3"}}
|
||||
var stringMapInterfaceSlice = map[string][]interface{}{"key 1": []interface{}{"value 1", "value 2", "value 3"}, "key 2": []interface{}{"value 1", "value 2", "value 3"}, "key 3": []interface{}{"value 1", "value 2", "value 3"}}
|
||||
var stringMapStringSingleSliceFieldsResult = map[string][]string{"key 1": []string{"value", "1"}, "key 2": []string{"value", "2"}, "key 3": []string{"value", "3"}}
|
||||
var interfaceMapStringSlice = map[interface{}][]string{"key 1": []string{"value 1", "value 2", "value 3"}, "key 2": []string{"value 1", "value 2", "value 3"}, "key 3": []string{"value 1", "value 2", "value 3"}}
|
||||
var interfaceMapInterfaceSlice = map[interface{}][]interface{}{"key 1": []interface{}{"value 1", "value 2", "value 3"}, "key 2": []interface{}{"value 1", "value 2", "value 3"}, "key 3": []interface{}{"value 1", "value 2", "value 3"}}
|
||||
|
||||
var stringMapStringSliceMultiple = map[string][]string{"key 1": []string{"value 1", "value 2", "value 3"}, "key 2": []string{"value 1", "value 2", "value 3"}, "key 3": []string{"value 1", "value 2", "value 3"}}
|
||||
var stringMapStringSliceSingle = map[string][]string{"key 1": []string{"value 1"}, "key 2": []string{"value 2"}, "key 3": []string{"value 3"}}
|
||||
|
||||
assert.Equal(t, ToStringMap(taxonomies), map[string]interface{}{"tag": "tags", "group": "groups"})
|
||||
assert.Equal(t, ToStringMapBool(stringMapBool), map[string]bool{"v1": true, "v2": false})
|
||||
|
||||
// ToStringMapString tests
|
||||
assert.Equal(t, ToStringMapString(stringMapString), stringMapString)
|
||||
assert.Equal(t, ToStringMapString(stringMapInterface), stringMapString)
|
||||
assert.Equal(t, ToStringMapString(interfaceMapString), stringMapString)
|
||||
assert.Equal(t, ToStringMapString(interfaceMapInterface), stringMapString)
|
||||
|
||||
// ToStringMapStringSlice tests
|
||||
assert.Equal(t, ToStringMapStringSlice(stringMapStringSlice), stringMapStringSlice)
|
||||
assert.Equal(t, ToStringMapStringSlice(stringMapInterfaceSlice), stringMapStringSlice)
|
||||
assert.Equal(t, ToStringMapStringSlice(stringMapStringSliceMultiple), stringMapStringSlice)
|
||||
assert.Equal(t, ToStringMapStringSlice(stringMapStringSliceMultiple), stringMapStringSlice)
|
||||
assert.Equal(t, ToStringMapStringSlice(stringMapString), stringMapStringSliceSingle)
|
||||
assert.Equal(t, ToStringMapStringSlice(stringMapInterface), stringMapStringSliceSingle)
|
||||
assert.Equal(t, ToStringMapStringSlice(interfaceMapStringSlice), stringMapStringSlice)
|
||||
assert.Equal(t, ToStringMapStringSlice(interfaceMapInterfaceSlice), stringMapStringSlice)
|
||||
assert.Equal(t, ToStringMapStringSlice(interfaceMapString), stringMapStringSingleSliceFieldsResult)
|
||||
assert.Equal(t, ToStringMapStringSlice(interfaceMapInterface), stringMapStringSingleSliceFieldsResult)
|
||||
}
|
||||
|
||||
func TestSlices(t *testing.T) {
|
||||
assert.Equal(t, []string{"a", "b"}, ToStringSlice([]string{"a", "b"}))
|
||||
assert.Equal(t, []string{"1", "3"}, ToStringSlice([]interface{}{1, 3}))
|
||||
assert.Equal(t, []int{1, 3}, ToIntSlice([]int{1, 3}))
|
||||
assert.Equal(t, []int{1, 3}, ToIntSlice([]interface{}{1.2, 3.2}))
|
||||
assert.Equal(t, []int{2, 3}, ToIntSlice([]string{"2", "3"}))
|
||||
assert.Equal(t, []int{2, 3}, ToIntSlice([2]string{"2", "3"}))
|
||||
}
|
||||
|
||||
func TestToBool(t *testing.T) {
|
||||
assert.Equal(t, ToBool(0), false)
|
||||
assert.Equal(t, ToBool(nil), false)
|
||||
assert.Equal(t, ToBool("false"), false)
|
||||
assert.Equal(t, ToBool("FALSE"), false)
|
||||
assert.Equal(t, ToBool("False"), false)
|
||||
assert.Equal(t, ToBool("f"), false)
|
||||
assert.Equal(t, ToBool("F"), false)
|
||||
assert.Equal(t, ToBool(false), false)
|
||||
assert.Equal(t, ToBool("foo"), false)
|
||||
|
||||
assert.Equal(t, ToBool("true"), true)
|
||||
assert.Equal(t, ToBool("TRUE"), true)
|
||||
assert.Equal(t, ToBool("True"), true)
|
||||
assert.Equal(t, ToBool("t"), true)
|
||||
assert.Equal(t, ToBool("T"), true)
|
||||
assert.Equal(t, ToBool(1), true)
|
||||
assert.Equal(t, ToBool(true), true)
|
||||
assert.Equal(t, ToBool(-1), true)
|
||||
}
|
||||
|
||||
func TestIndirectPointers(t *testing.T) {
|
||||
x := 13
|
||||
y := &x
|
||||
z := &y
|
||||
|
||||
assert.Equal(t, ToInt(y), 13)
|
||||
assert.Equal(t, ToInt(z), 13)
|
||||
}
|
||||
|
||||
func TestToDuration(t *testing.T) {
|
||||
a := time.Second * 5
|
||||
ai := int64(a)
|
||||
b := time.Second * 5
|
||||
bf := float64(b)
|
||||
assert.Equal(t, ToDuration(ai), a)
|
||||
assert.Equal(t, ToDuration(bf), b)
|
||||
}
|
856
vendor/github.com/spf13/cast/caste.go
generated
vendored
856
vendor/github.com/spf13/cast/caste.go
generated
vendored
File diff suppressed because it is too large
Load diff
52
vendor/github.com/spf13/cobra/README.md
generated
vendored
52
vendor/github.com/spf13/cobra/README.md
generated
vendored
|
@ -8,6 +8,7 @@ Many of the most widely used Go projects are built using Cobra including:
|
|||
* [Hugo](http://gohugo.io)
|
||||
* [rkt](https://github.com/coreos/rkt)
|
||||
* [etcd](https://github.com/coreos/etcd)
|
||||
* [Docker](https://github.com/docker/docker)
|
||||
* [Docker (distribution)](https://github.com/docker/distribution)
|
||||
* [OpenShift](https://www.openshift.com/)
|
||||
* [Delve](https://github.com/derekparker/delve)
|
||||
|
@ -22,6 +23,7 @@ Many of the most widely used Go projects are built using Cobra including:
|
|||
|
||||
[](https://travis-ci.org/spf13/cobra)
|
||||
[](https://circleci.com/gh/spf13/cobra)
|
||||
[](https://godoc.org/github.com/spf13/cobra)
|
||||
|
||||

|
||||
|
||||
|
@ -156,12 +158,17 @@ In a Cobra app, typically the main.go file is very bare. It serves, one purpose,
|
|||
```go
|
||||
package main
|
||||
|
||||
import "{pathToYourApp}/cmd"
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
|
||||
"{pathToYourApp}/cmd"
|
||||
)
|
||||
|
||||
func main() {
|
||||
if err := cmd.RootCmd.Execute(); err != nil {
|
||||
fmt.Println(err)
|
||||
os.Exit(-1)
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
@ -171,6 +178,12 @@ func main() {
|
|||
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 install github.com/spf13/cobra/cobra
|
||||
|
||||
This will create the cobra executable under your go path bin directory!
|
||||
|
||||
### cobra init
|
||||
|
||||
The `cobra init [yourApp]` command will create your initial application code
|
||||
|
@ -226,13 +239,27 @@ 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:
|
||||
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.
|
||||
```
|
||||
|
||||
## Manually implementing Cobra
|
||||
|
||||
To manually implement cobra you need to create a bare main.go file and a RootCmd file.
|
||||
|
@ -292,12 +319,17 @@ In a Cobra app, typically the main.go file is very bare. It serves, one purpose,
|
|||
```go
|
||||
package main
|
||||
|
||||
import "{pathToYourApp}/cmd"
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
|
||||
"{pathToYourApp}/cmd"
|
||||
)
|
||||
|
||||
func main() {
|
||||
if err := cmd.RootCmd.Execute(); err != nil {
|
||||
fmt.Println(err)
|
||||
os.Exit(-1)
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
@ -316,6 +348,7 @@ package cmd
|
|||
|
||||
import (
|
||||
"github.com/spf13/cobra"
|
||||
"fmt"
|
||||
)
|
||||
|
||||
func init() {
|
||||
|
@ -642,7 +675,7 @@ command.SetUsageTemplate(s string)
|
|||
|
||||
## PreRun or PostRun Hooks
|
||||
|
||||
It is possible to run functions before or after the main `Run` function of your command. The `PersistentPreRun` and `PreRun` functions will be executed before `Run`. `PersistentPostRun` and `PostRun` will be executed after `Run`. The `Persistent*Run` functions will be inherrited by children if they do not declare their own. These function are run in the following order:
|
||||
It is possible to run functions before or after the main `Run` function of your command. The `PersistentPreRun` and `PreRun` functions will be executed before `Run`. `PersistentPostRun` and `PostRun` will be executed after `Run`. The `Persistent*Run` functions will be inherited by children if they do not declare their own. These functions are run in the following order:
|
||||
|
||||
- `PersistentPreRun`
|
||||
- `PreRun`
|
||||
|
@ -713,7 +746,8 @@ func main() {
|
|||
|
||||
## Alternative Error Handling
|
||||
|
||||
Cobra also has functions where the return signature is an error. This allows for errors to bubble up to the top, providing a way to handle the errors in one location. The current list of functions that return an error is:
|
||||
Cobra also has functions where the return signature is an error. This allows for errors to bubble up to the top,
|
||||
providing a way to handle the errors in one location. The current list of functions that return an error is:
|
||||
|
||||
* PersistentPreRunE
|
||||
* PreRunE
|
||||
|
@ -721,6 +755,10 @@ Cobra also has functions where the return signature is an error. This allows for
|
|||
* PostRunE
|
||||
* PersistentPostRunE
|
||||
|
||||
If you would like to silence the default `error` and `usage` output in favor of your own, you can set `SilenceUsage`
|
||||
and `SilenceErrors` to `true` on the command. A child command respects these flags if they are set on the parent
|
||||
command.
|
||||
|
||||
**Example Usage using RunE:**
|
||||
|
||||
```go
|
||||
|
|
167
vendor/github.com/spf13/cobra/bash_completions.go
generated
vendored
167
vendor/github.com/spf13/cobra/bash_completions.go
generated
vendored
|
@ -10,8 +10,10 @@ import (
|
|||
"github.com/spf13/pflag"
|
||||
)
|
||||
|
||||
// Annotations for Bash completion.
|
||||
const (
|
||||
BashCompFilenameExt = "cobra_annotation_bash_completion_filename_extentions"
|
||||
BashCompFilenameExt = "cobra_annotation_bash_completion_filename_extensions"
|
||||
BashCompCustom = "cobra_annotation_bash_completion_custom"
|
||||
BashCompOneRequiredFlag = "cobra_annotation_bash_completion_one_required_flag"
|
||||
BashCompSubdirsInDir = "cobra_annotation_bash_completion_subdirs_in_dir"
|
||||
)
|
||||
|
@ -21,7 +23,7 @@ func preamble(out io.Writer, name string) error {
|
|||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = fmt.Fprintf(out, `
|
||||
preamStr := `
|
||||
__debug()
|
||||
{
|
||||
if [[ -n ${BASH_COMP_DEBUG_FILE} ]]; then
|
||||
|
@ -34,7 +36,7 @@ __debug()
|
|||
__my_init_completion()
|
||||
{
|
||||
COMPREPLY=()
|
||||
_get_comp_words_by_ref cur prev words cword
|
||||
_get_comp_words_by_ref "$@" cur prev words cword
|
||||
}
|
||||
|
||||
__index_of_word()
|
||||
|
@ -60,7 +62,7 @@ __contains_word()
|
|||
|
||||
__handle_reply()
|
||||
{
|
||||
__debug "${FUNCNAME}"
|
||||
__debug "${FUNCNAME[0]}"
|
||||
case $cur in
|
||||
-*)
|
||||
if [[ $(type -t compopt) = "builtin" ]]; then
|
||||
|
@ -74,7 +76,28 @@ __handle_reply()
|
|||
fi
|
||||
COMPREPLY=( $(compgen -W "${allflags[*]}" -- "$cur") )
|
||||
if [[ $(type -t compopt) = "builtin" ]]; then
|
||||
[[ $COMPREPLY == *= ]] || compopt +o nospace
|
||||
[[ "${COMPREPLY[0]}" == *= ]] || compopt +o nospace
|
||||
fi
|
||||
|
||||
# complete after --flag=abc
|
||||
if [[ $cur == *=* ]]; then
|
||||
if [[ $(type -t compopt) = "builtin" ]]; then
|
||||
compopt +o nospace
|
||||
fi
|
||||
|
||||
local index flag
|
||||
flag="${cur%%=*}"
|
||||
__index_of_word "${flag}" "${flags_with_completion[@]}"
|
||||
COMPREPLY=()
|
||||
if [[ ${index} -ge 0 ]]; then
|
||||
PREFIX=""
|
||||
cur="${cur#*=}"
|
||||
${flags_completion[${index}]}
|
||||
if [ -n "${ZSH_VERSION}" ]; then
|
||||
# zfs completion needs --flag= prefix
|
||||
eval "COMPREPLY=( \"\${COMPREPLY[@]/#/${flag}=}\" )"
|
||||
fi
|
||||
fi
|
||||
fi
|
||||
return 0;
|
||||
;;
|
||||
|
@ -94,15 +117,19 @@ __handle_reply()
|
|||
fi
|
||||
|
||||
local completions
|
||||
if [[ ${#must_have_one_flag[@]} -ne 0 ]]; then
|
||||
completions=("${must_have_one_flag[@]}")
|
||||
elif [[ ${#must_have_one_noun[@]} -ne 0 ]]; then
|
||||
completions=("${commands[@]}")
|
||||
if [[ ${#must_have_one_noun[@]} -ne 0 ]]; then
|
||||
completions=("${must_have_one_noun[@]}")
|
||||
else
|
||||
completions=("${commands[@]}")
|
||||
fi
|
||||
if [[ ${#must_have_one_flag[@]} -ne 0 ]]; then
|
||||
completions+=("${must_have_one_flag[@]}")
|
||||
fi
|
||||
COMPREPLY=( $(compgen -W "${completions[*]}" -- "$cur") )
|
||||
|
||||
if [[ ${#COMPREPLY[@]} -eq 0 && ${#noun_aliases[@]} -gt 0 && ${#must_have_one_noun[@]} -ne 0 ]]; then
|
||||
COMPREPLY=( $(compgen -W "${noun_aliases[*]}" -- "$cur") )
|
||||
fi
|
||||
|
||||
if [[ ${#COMPREPLY[@]} -eq 0 ]]; then
|
||||
declare -F __custom_func >/dev/null && __custom_func
|
||||
fi
|
||||
|
@ -125,7 +152,7 @@ __handle_subdirs_in_dir_flag()
|
|||
|
||||
__handle_flag()
|
||||
{
|
||||
__debug "${FUNCNAME}: c is $c words[c] is ${words[c]}"
|
||||
__debug "${FUNCNAME[0]}: c is $c words[c] is ${words[c]}"
|
||||
|
||||
# if a command required a flag, and we found it, unset must_have_one_flag()
|
||||
local flagname=${words[c]}
|
||||
|
@ -136,15 +163,20 @@ __handle_flag()
|
|||
flagname=${flagname%%=*} # strip everything after the =
|
||||
flagname="${flagname}=" # but put the = back
|
||||
fi
|
||||
__debug "${FUNCNAME}: looking for ${flagname}"
|
||||
__debug "${FUNCNAME[0]}: looking for ${flagname}"
|
||||
if __contains_word "${flagname}" "${must_have_one_flag[@]}"; then
|
||||
must_have_one_flag=()
|
||||
fi
|
||||
|
||||
# if you set a flag which only applies to this command, don't show subcommands
|
||||
if __contains_word "${flagname}" "${local_nonpersistent_flags[@]}"; then
|
||||
commands=()
|
||||
fi
|
||||
|
||||
# keep flag value with flagname as flaghash
|
||||
if [ ${flagvalue} ] ; then
|
||||
if [ -n "${flagvalue}" ] ; then
|
||||
flaghash[${flagname}]=${flagvalue}
|
||||
elif [ ${words[ $((c+1)) ]} ] ; then
|
||||
elif [ -n "${words[ $((c+1)) ]}" ] ; then
|
||||
flaghash[${flagname}]=${words[ $((c+1)) ]}
|
||||
else
|
||||
flaghash[${flagname}]="true" # pad "true" for bool flag
|
||||
|
@ -165,10 +197,12 @@ __handle_flag()
|
|||
|
||||
__handle_noun()
|
||||
{
|
||||
__debug "${FUNCNAME}: c is $c words[c] is ${words[c]}"
|
||||
__debug "${FUNCNAME[0]}: c is $c words[c] is ${words[c]}"
|
||||
|
||||
if __contains_word "${words[c]}" "${must_have_one_noun[@]}"; then
|
||||
must_have_one_noun=()
|
||||
elif __contains_word "${words[c]}" "${noun_aliases[@]}"; then
|
||||
must_have_one_noun=()
|
||||
fi
|
||||
|
||||
nouns+=("${words[c]}")
|
||||
|
@ -177,21 +211,21 @@ __handle_noun()
|
|||
|
||||
__handle_command()
|
||||
{
|
||||
__debug "${FUNCNAME}: c is $c words[c] is ${words[c]}"
|
||||
__debug "${FUNCNAME[0]}: c is $c words[c] is ${words[c]}"
|
||||
|
||||
local next_command
|
||||
if [[ -n ${last_command} ]]; then
|
||||
next_command="_${last_command}_${words[c]//:/__}"
|
||||
else
|
||||
if [[ $c -eq 0 ]]; then
|
||||
next_command="_$(basename ${words[c]//:/__})"
|
||||
next_command="_$(basename "${words[c]//:/__}")"
|
||||
else
|
||||
next_command="_${words[c]//:/__}"
|
||||
fi
|
||||
fi
|
||||
c=$((c+1))
|
||||
__debug "${FUNCNAME}: looking for ${next_command}"
|
||||
declare -F $next_command >/dev/null && $next_command
|
||||
__debug "${FUNCNAME[0]}: looking for ${next_command}"
|
||||
declare -F "$next_command" >/dev/null && $next_command
|
||||
}
|
||||
|
||||
__handle_word()
|
||||
|
@ -200,12 +234,12 @@ __handle_word()
|
|||
__handle_reply
|
||||
return
|
||||
fi
|
||||
__debug "${FUNCNAME}: c is $c words[c] is ${words[c]}"
|
||||
__debug "${FUNCNAME[0]}: c is $c words[c] is ${words[c]}"
|
||||
if [[ "${words[c]}" == -* ]]; then
|
||||
__handle_flag
|
||||
elif __contains_word "${words[c]}" "${commands[@]}"; then
|
||||
__handle_command
|
||||
elif [[ $c -eq 0 ]] && __contains_word "$(basename ${words[c]})" "${commands[@]}"; then
|
||||
elif [[ $c -eq 0 ]] && __contains_word "$(basename "${words[c]}")" "${commands[@]}"; then
|
||||
__handle_command
|
||||
else
|
||||
__handle_noun
|
||||
|
@ -213,7 +247,8 @@ __handle_word()
|
|||
__handle_word
|
||||
}
|
||||
|
||||
`)
|
||||
`
|
||||
_, err = fmt.Fprint(out, preamStr)
|
||||
return err
|
||||
}
|
||||
|
||||
|
@ -229,12 +264,13 @@ func postscript(w io.Writer, name string) error {
|
|||
if declare -F _init_completion >/dev/null 2>&1; then
|
||||
_init_completion -s || return
|
||||
else
|
||||
__my_init_completion || return
|
||||
__my_init_completion -n "=" || return
|
||||
fi
|
||||
|
||||
local c=0
|
||||
local flags=()
|
||||
local two_word_flags=()
|
||||
local local_nonpersistent_flags=()
|
||||
local flags_with_completion=()
|
||||
local flags_completion=()
|
||||
local commands=("%s")
|
||||
|
@ -299,6 +335,20 @@ func writeFlagHandler(name string, annotations map[string][]string, w io.Writer)
|
|||
if err != nil {
|
||||
return err
|
||||
}
|
||||
case BashCompCustom:
|
||||
_, err := fmt.Fprintf(w, " flags_with_completion+=(%q)\n", name)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if len(value) > 0 {
|
||||
handlers := strings.Join(value, "; ")
|
||||
_, err = fmt.Fprintf(w, " flags_completion+=(%q)\n", handlers)
|
||||
} else {
|
||||
_, err = fmt.Fprintf(w, " flags_completion+=(:)\n")
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
case BashCompSubdirsInDir:
|
||||
_, err := fmt.Fprintf(w, " flags_with_completion+=(%q)\n", name)
|
||||
|
||||
|
@ -318,7 +368,7 @@ func writeFlagHandler(name string, annotations map[string][]string, w io.Writer)
|
|||
}
|
||||
|
||||
func writeShortFlag(flag *pflag.Flag, w io.Writer) error {
|
||||
b := (flag.Value.Type() == "bool")
|
||||
b := (len(flag.NoOptDefVal) > 0)
|
||||
name := flag.Shorthand
|
||||
format := " "
|
||||
if !b {
|
||||
|
@ -332,7 +382,7 @@ func writeShortFlag(flag *pflag.Flag, w io.Writer) error {
|
|||
}
|
||||
|
||||
func writeFlag(flag *pflag.Flag, w io.Writer) error {
|
||||
b := (flag.Value.Type() == "bool")
|
||||
b := (len(flag.NoOptDefVal) > 0)
|
||||
name := flag.Name
|
||||
format := " flags+=(\"--%s"
|
||||
if !b {
|
||||
|
@ -345,9 +395,22 @@ func writeFlag(flag *pflag.Flag, w io.Writer) error {
|
|||
return writeFlagHandler("--"+name, flag.Annotations, w)
|
||||
}
|
||||
|
||||
func writeLocalNonPersistentFlag(flag *pflag.Flag, w io.Writer) error {
|
||||
b := (len(flag.NoOptDefVal) > 0)
|
||||
name := flag.Name
|
||||
format := " local_nonpersistent_flags+=(\"--%s"
|
||||
if !b {
|
||||
format += "="
|
||||
}
|
||||
format += "\")\n"
|
||||
_, err := fmt.Fprintf(w, format, name)
|
||||
return err
|
||||
}
|
||||
|
||||
func writeFlags(cmd *Command, w io.Writer) error {
|
||||
_, err := fmt.Fprintf(w, ` flags=()
|
||||
two_word_flags=()
|
||||
local_nonpersistent_flags=()
|
||||
flags_with_completion=()
|
||||
flags_completion=()
|
||||
|
||||
|
@ -355,8 +418,12 @@ func writeFlags(cmd *Command, w io.Writer) error {
|
|||
if err != nil {
|
||||
return err
|
||||
}
|
||||
localNonPersistentFlags := cmd.LocalNonPersistentFlags()
|
||||
var visitErr error
|
||||
cmd.NonInheritedFlags().VisitAll(func(flag *pflag.Flag) {
|
||||
if nonCompletableFlag(flag) {
|
||||
return
|
||||
}
|
||||
if err := writeFlag(flag, w); err != nil {
|
||||
visitErr = err
|
||||
return
|
||||
|
@ -367,11 +434,20 @@ func writeFlags(cmd *Command, w io.Writer) error {
|
|||
return
|
||||
}
|
||||
}
|
||||
if localNonPersistentFlags.Lookup(flag.Name) != nil {
|
||||
if err := writeLocalNonPersistentFlag(flag, w); err != nil {
|
||||
visitErr = err
|
||||
return
|
||||
}
|
||||
}
|
||||
})
|
||||
if visitErr != nil {
|
||||
return visitErr
|
||||
}
|
||||
cmd.InheritedFlags().VisitAll(func(flag *pflag.Flag) {
|
||||
if nonCompletableFlag(flag) {
|
||||
return
|
||||
}
|
||||
if err := writeFlag(flag, w); err != nil {
|
||||
visitErr = err
|
||||
return
|
||||
|
@ -398,6 +474,9 @@ func writeRequiredFlag(cmd *Command, w io.Writer) error {
|
|||
flags := cmd.NonInheritedFlags()
|
||||
var visitErr error
|
||||
flags.VisitAll(func(flag *pflag.Flag) {
|
||||
if nonCompletableFlag(flag) {
|
||||
return
|
||||
}
|
||||
for key := range flag.Annotations {
|
||||
switch key {
|
||||
case BashCompOneRequiredFlag:
|
||||
|
@ -424,7 +503,7 @@ func writeRequiredFlag(cmd *Command, w io.Writer) error {
|
|||
return visitErr
|
||||
}
|
||||
|
||||
func writeRequiredNoun(cmd *Command, w io.Writer) error {
|
||||
func writeRequiredNouns(cmd *Command, w io.Writer) error {
|
||||
if _, err := fmt.Fprintf(w, " must_have_one_noun=()\n"); err != nil {
|
||||
return err
|
||||
}
|
||||
|
@ -437,6 +516,19 @@ func writeRequiredNoun(cmd *Command, w io.Writer) error {
|
|||
return nil
|
||||
}
|
||||
|
||||
func writeArgAliases(cmd *Command, w io.Writer) error {
|
||||
if _, err := fmt.Fprintf(w, " noun_aliases=()\n"); err != nil {
|
||||
return err
|
||||
}
|
||||
sort.Sort(sort.StringSlice(cmd.ArgAliases))
|
||||
for _, value := range cmd.ArgAliases {
|
||||
if _, err := fmt.Fprintf(w, " noun_aliases+=(%q)\n", value); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func gen(cmd *Command, w io.Writer) error {
|
||||
for _, c := range cmd.Commands() {
|
||||
if !c.IsAvailableCommand() || c == cmd.helpCommand {
|
||||
|
@ -464,7 +556,10 @@ func gen(cmd *Command, w io.Writer) error {
|
|||
if err := writeRequiredFlag(cmd, w); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := writeRequiredNoun(cmd, w); err != nil {
|
||||
if err := writeRequiredNouns(cmd, w); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := writeArgAliases(cmd, w); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := fmt.Fprintf(w, "}\n\n"); err != nil {
|
||||
|
@ -473,6 +568,7 @@ func gen(cmd *Command, w io.Writer) error {
|
|||
return nil
|
||||
}
|
||||
|
||||
// GenBashCompletion generates bash completion file and writes to the passed writer.
|
||||
func (cmd *Command) GenBashCompletion(w io.Writer) error {
|
||||
if err := preamble(w, cmd.Name()); err != nil {
|
||||
return err
|
||||
|
@ -488,6 +584,11 @@ func (cmd *Command) GenBashCompletion(w io.Writer) error {
|
|||
return postscript(w, cmd.Name())
|
||||
}
|
||||
|
||||
func nonCompletableFlag(flag *pflag.Flag) bool {
|
||||
return flag.Hidden || len(flag.Deprecated) > 0
|
||||
}
|
||||
|
||||
// GenBashCompletionFile generates bash completion file.
|
||||
func (cmd *Command) GenBashCompletionFile(filename string) error {
|
||||
outFile, err := os.Create(filename)
|
||||
if err != nil {
|
||||
|
@ -519,6 +620,12 @@ func (cmd *Command) MarkFlagFilename(name string, extensions ...string) error {
|
|||
return MarkFlagFilename(cmd.Flags(), name, extensions...)
|
||||
}
|
||||
|
||||
// MarkFlagCustom adds the BashCompCustom annotation to the named flag, if it exists.
|
||||
// Generated bash autocompletion will call the bash function f for the flag.
|
||||
func (cmd *Command) MarkFlagCustom(name string, f string) error {
|
||||
return MarkFlagCustom(cmd.Flags(), name, f)
|
||||
}
|
||||
|
||||
// MarkPersistentFlagFilename adds the BashCompFilenameExt annotation to the named persistent flag, if it exists.
|
||||
// Generated bash autocompletion will select filenames for the flag, limiting to named extensions if provided.
|
||||
func (cmd *Command) MarkPersistentFlagFilename(name string, extensions ...string) error {
|
||||
|
@ -530,3 +637,9 @@ func (cmd *Command) MarkPersistentFlagFilename(name string, extensions ...string
|
|||
func MarkFlagFilename(flags *pflag.FlagSet, name string, extensions ...string) error {
|
||||
return flags.SetAnnotation(name, BashCompFilenameExt, extensions)
|
||||
}
|
||||
|
||||
// MarkFlagCustom adds the BashCompCustom annotation to the named flag in the flag set, if it exists.
|
||||
// Generated bash autocompletion will call the bash function f for the flag.
|
||||
func MarkFlagCustom(flags *pflag.FlagSet, name string, f string) error {
|
||||
return flags.SetAnnotation(name, BashCompCustom, []string{f})
|
||||
}
|
||||
|
|
63
vendor/github.com/spf13/cobra/bash_completions.md
generated
vendored
63
vendor/github.com/spf13/cobra/bash_completions.md
generated
vendored
|
@ -18,7 +18,7 @@ func main() {
|
|||
}
|
||||
```
|
||||
|
||||
That will get you completions of subcommands and flags. If you make additional annotations to your code, you can get even more intelligent and flexible behavior.
|
||||
`out.sh` will get you completions of subcommands and flags. Copy it to `/etc/bash_completion.d/` as described [here](https://debian-administration.org/article/316/An_introduction_to_bash_completion_part_1) and reset your terminal to use autocompletion. If you make additional annotations to your code, you can get even more intelligent and flexible behavior.
|
||||
|
||||
## Creating your own custom functions
|
||||
|
||||
|
@ -80,7 +80,7 @@ The `BashCompletionFunction` option is really only valid/useful on the root comm
|
|||
In the above example "pod" was assumed to already be typed. But if you want `kubectl get [tab][tab]` to show a list of valid "nouns" you have to set them. Simplified code from `kubectl get` looks like:
|
||||
|
||||
```go
|
||||
validArgs []string = { "pods", "nodes", "services", "replicationControllers" }
|
||||
validArgs []string = { "pod", "node", "service", "replicationcontroller" }
|
||||
|
||||
cmd := &cobra.Command{
|
||||
Use: "get [(-o|--output=)json|yaml|template|...] (RESOURCE [NAME] | RESOURCE/NAME ...)",
|
||||
|
@ -99,9 +99,34 @@ Notice we put the "ValidArgs" on the "get" subcommand. Doing so will give result
|
|||
|
||||
```bash
|
||||
# kubectl get [tab][tab]
|
||||
nodes pods replicationControllers services
|
||||
node pod replicationcontroller service
|
||||
```
|
||||
|
||||
## Plural form and shortcuts for nouns
|
||||
|
||||
If your nouns have a number of aliases, you can define them alongside `ValidArgs` using `ArgAliases`:
|
||||
|
||||
```go`
|
||||
argAliases []string = { "pods", "nodes", "services", "svc", "replicationcontrollers", "rc" }
|
||||
|
||||
cmd := &cobra.Command{
|
||||
...
|
||||
ValidArgs: validArgs,
|
||||
ArgAliases: argAliases
|
||||
}
|
||||
```
|
||||
|
||||
The aliases are not shown to the user on tab completion, but they are accepted as valid nouns by
|
||||
the completion algorithm if entered manually, e.g. in:
|
||||
|
||||
```bash
|
||||
# kubectl get rc [tab][tab]
|
||||
backend frontend database
|
||||
```
|
||||
|
||||
Note that without declaring `rc` as an alias, the completion algorithm would show the list of nouns
|
||||
in this example again instead of the replication controllers.
|
||||
|
||||
## Mark flags as required
|
||||
|
||||
Most of the time completions will only show subcommands. But if a flag is required to make a subcommand work, you probably want it to show up when the user types [tab][tab]. Marking a flag as 'Required' is incredibly easy.
|
||||
|
@ -147,3 +172,35 @@ hello.yml test.json
|
|||
```
|
||||
|
||||
So while there are many other files in the CWD it only shows me subdirs and those with valid extensions.
|
||||
|
||||
# Specifiy custom flag completion
|
||||
|
||||
Similar to the filename completion and filtering using cobra.BashCompFilenameExt, you can specifiy
|
||||
a custom flag completion function with cobra.BashCompCustom:
|
||||
|
||||
```go
|
||||
annotation := make(map[string][]string)
|
||||
annotation[cobra.BashCompFilenameExt] = []string{"__kubectl_get_namespaces"}
|
||||
|
||||
flag := &pflag.Flag{
|
||||
Name: "namespace",
|
||||
Usage: usage,
|
||||
Annotations: annotation,
|
||||
}
|
||||
cmd.Flags().AddFlag(flag)
|
||||
```
|
||||
|
||||
In addition add the `__handle_namespace_flag` implementation in the `BashCompletionFunction`
|
||||
value, e.g.:
|
||||
|
||||
```bash
|
||||
__kubectl_get_namespaces()
|
||||
{
|
||||
local template
|
||||
template="{{ range .items }}{{ .metadata.name }} {{ end }}"
|
||||
local kubectl_out
|
||||
if kubectl_out=$(kubectl get -o template --template="${template}" namespace 2>/dev/null); then
|
||||
COMPREPLY=( $( compgen -W "${kubectl_out}[*]" -- "$cur" ) )
|
||||
fi
|
||||
}
|
||||
```
|
||||
|
|
95
vendor/github.com/spf13/cobra/bash_completions_test.go
generated
vendored
95
vendor/github.com/spf13/cobra/bash_completions_test.go
generated
vendored
|
@ -1,95 +0,0 @@
|
|||
package cobra
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"os"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
var _ = fmt.Println
|
||||
var _ = os.Stderr
|
||||
|
||||
func checkOmit(t *testing.T, found, unexpected string) {
|
||||
if strings.Contains(found, unexpected) {
|
||||
t.Errorf("Unexpected response.\nGot: %q\nBut should not have!\n", unexpected)
|
||||
}
|
||||
}
|
||||
|
||||
func check(t *testing.T, found, expected string) {
|
||||
if !strings.Contains(found, expected) {
|
||||
t.Errorf("Unexpected response.\nExpecting to contain: \n %q\nGot:\n %q\n", expected, found)
|
||||
}
|
||||
}
|
||||
|
||||
// World worst custom function, just keep telling you to enter hello!
|
||||
const (
|
||||
bash_completion_func = `__custom_func() {
|
||||
COMPREPLY=( "hello" )
|
||||
}
|
||||
`
|
||||
)
|
||||
|
||||
func TestBashCompletions(t *testing.T) {
|
||||
c := initializeWithRootCmd()
|
||||
cmdEcho.AddCommand(cmdTimes)
|
||||
c.AddCommand(cmdEcho, cmdPrint, cmdDeprecated, cmdColon)
|
||||
|
||||
// custom completion function
|
||||
c.BashCompletionFunction = bash_completion_func
|
||||
|
||||
// required flag
|
||||
c.MarkFlagRequired("introot")
|
||||
|
||||
// valid nouns
|
||||
validArgs := []string{"pods", "nodes", "services", "replicationControllers"}
|
||||
c.ValidArgs = validArgs
|
||||
|
||||
// filename
|
||||
var flagval string
|
||||
c.Flags().StringVar(&flagval, "filename", "", "Enter a filename")
|
||||
c.MarkFlagFilename("filename", "json", "yaml", "yml")
|
||||
|
||||
// persistent filename
|
||||
var flagvalPersistent string
|
||||
c.PersistentFlags().StringVar(&flagvalPersistent, "persistent-filename", "", "Enter a filename")
|
||||
c.MarkPersistentFlagFilename("persistent-filename")
|
||||
c.MarkPersistentFlagRequired("persistent-filename")
|
||||
|
||||
// filename extensions
|
||||
var flagvalExt string
|
||||
c.Flags().StringVar(&flagvalExt, "filename-ext", "", "Enter a filename (extension limited)")
|
||||
c.MarkFlagFilename("filename-ext")
|
||||
|
||||
// subdirectories in a given directory
|
||||
var flagvalTheme string
|
||||
c.Flags().StringVar(&flagvalTheme, "theme", "", "theme to use (located in /themes/THEMENAME/)")
|
||||
c.Flags().SetAnnotation("theme", BashCompSubdirsInDir, []string{"themes"})
|
||||
|
||||
out := new(bytes.Buffer)
|
||||
c.GenBashCompletion(out)
|
||||
str := out.String()
|
||||
|
||||
check(t, str, "_cobra-test")
|
||||
check(t, str, "_cobra-test_echo")
|
||||
check(t, str, "_cobra-test_echo_times")
|
||||
check(t, str, "_cobra-test_print")
|
||||
check(t, str, "_cobra-test_cmd__colon")
|
||||
|
||||
// check for required flags
|
||||
check(t, str, `must_have_one_flag+=("--introot=")`)
|
||||
check(t, str, `must_have_one_flag+=("--persistent-filename=")`)
|
||||
// check for custom completion function
|
||||
check(t, str, `COMPREPLY=( "hello" )`)
|
||||
// check for required nouns
|
||||
check(t, str, `must_have_one_noun+=("pods")`)
|
||||
// check for filename extension flags
|
||||
check(t, str, `flags_completion+=("_filedir")`)
|
||||
// check for filename extension flags
|
||||
check(t, str, `flags_completion+=("__handle_filename_extension_flag json|yaml|yml")`)
|
||||
// check for subdirs_in_dir flags
|
||||
check(t, str, `flags_completion+=("__handle_subdirs_in_dir_flag themes")`)
|
||||
|
||||
checkOmit(t, str, cmdDeprecated.Name())
|
||||
}
|
58
vendor/github.com/spf13/cobra/cobra.go
generated
vendored
58
vendor/github.com/spf13/cobra/cobra.go
generated
vendored
|
@ -26,44 +26,48 @@ import (
|
|||
"unicode"
|
||||
)
|
||||
|
||||
var templateFuncs template.FuncMap = template.FuncMap{
|
||||
"trim": strings.TrimSpace,
|
||||
"trimRightSpace": trimRightSpace,
|
||||
"rpad": rpad,
|
||||
"gt": Gt,
|
||||
"eq": Eq,
|
||||
var templateFuncs = template.FuncMap{
|
||||
"trim": strings.TrimSpace,
|
||||
"trimRightSpace": trimRightSpace,
|
||||
"appendIfNotPresent": appendIfNotPresent,
|
||||
"rpad": rpad,
|
||||
"gt": Gt,
|
||||
"eq": Eq,
|
||||
}
|
||||
|
||||
var initializers []func()
|
||||
|
||||
// automatic prefix matching can be a dangerous thing to automatically enable in CLI tools.
|
||||
// Set this to true to enable it
|
||||
var EnablePrefixMatching bool = false
|
||||
// EnablePrefixMatching allows to set automatic prefix matching. Automatic prefix matching can be a dangerous thing
|
||||
// to automatically enable in CLI tools.
|
||||
// Set this to true to enable it.
|
||||
var EnablePrefixMatching = false
|
||||
|
||||
//AddTemplateFunc adds a template function that's available to Usage and Help
|
||||
//template generation.
|
||||
// EnableCommandSorting controls sorting of the slice of commands, which is turned on by default.
|
||||
// To disable sorting, set it to false.
|
||||
var EnableCommandSorting = true
|
||||
|
||||
// AddTemplateFunc adds a template function that's available to Usage and Help
|
||||
// template generation.
|
||||
func AddTemplateFunc(name string, tmplFunc interface{}) {
|
||||
templateFuncs[name] = tmplFunc
|
||||
}
|
||||
|
||||
//AddTemplateFuncs adds multiple template functions availalble to Usage and
|
||||
//Help template generation.
|
||||
// AddTemplateFuncs adds multiple template functions that are available to Usage and
|
||||
// Help template generation.
|
||||
func AddTemplateFuncs(tmplFuncs template.FuncMap) {
|
||||
for k, v := range tmplFuncs {
|
||||
templateFuncs[k] = v
|
||||
}
|
||||
}
|
||||
|
||||
//OnInitialize takes a series of func() arguments and appends them to a slice of func().
|
||||
// OnInitialize takes a series of func() arguments and appends them to a slice of func().
|
||||
func OnInitialize(y ...func()) {
|
||||
for _, x := range y {
|
||||
initializers = append(initializers, x)
|
||||
}
|
||||
initializers = append(initializers, y...)
|
||||
}
|
||||
|
||||
//Gt takes two types and checks whether the first type is greater than the second. In case of types Arrays, Chans,
|
||||
//Maps and Slices, Gt will compare their lengths. Ints are compared directly while strings are first parsed as
|
||||
//ints and then compared.
|
||||
// Gt takes two types and checks whether the first type is greater than the second. In case of types Arrays, Chans,
|
||||
// Maps and Slices, Gt will compare their lengths. Ints are compared directly while strings are first parsed as
|
||||
// ints and then compared.
|
||||
func Gt(a interface{}, b interface{}) bool {
|
||||
var left, right int64
|
||||
av := reflect.ValueOf(a)
|
||||
|
@ -91,7 +95,7 @@ func Gt(a interface{}, b interface{}) bool {
|
|||
return left > right
|
||||
}
|
||||
|
||||
//Eq takes two types and checks whether they are equal. Supported types are int and string. Unsupported types will panic.
|
||||
// Eq takes two types and checks whether they are equal. Supported types are int and string. Unsupported types will panic.
|
||||
func Eq(a interface{}, b interface{}) bool {
|
||||
av := reflect.ValueOf(a)
|
||||
bv := reflect.ValueOf(b)
|
||||
|
@ -111,7 +115,15 @@ func trimRightSpace(s string) string {
|
|||
return strings.TrimRightFunc(s, unicode.IsSpace)
|
||||
}
|
||||
|
||||
//rpad adds padding to the right of a string
|
||||
// appendIfNotPresent will append stringToAppend to the end of s, but only if it's not yet present in s.
|
||||
func appendIfNotPresent(s, stringToAppend string) string {
|
||||
if strings.Contains(s, stringToAppend) {
|
||||
return s
|
||||
}
|
||||
return s + " " + stringToAppend
|
||||
}
|
||||
|
||||
// rpad adds padding to the right of a string.
|
||||
func rpad(s string, padding int) string {
|
||||
template := fmt.Sprintf("%%-%ds", padding)
|
||||
return fmt.Sprintf(template, s)
|
||||
|
@ -125,7 +137,7 @@ func tmpl(w io.Writer, text string, data interface{}) error {
|
|||
return t.Execute(w, data)
|
||||
}
|
||||
|
||||
// ld compares two strings and returns the levenshtein distance between them
|
||||
// ld compares two strings and returns the levenshtein distance between them.
|
||||
func ld(s, t string, ignoreCase bool) int {
|
||||
if ignoreCase {
|
||||
s = strings.ToLower(s)
|
||||
|
|
128
vendor/github.com/spf13/cobra/cobra/cmd/add.go
generated
vendored
128
vendor/github.com/spf13/cobra/cobra/cmd/add.go
generated
vendored
|
@ -1,128 +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"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
"github.com/spf13/viper"
|
||||
)
|
||||
|
||||
func init() {
|
||||
RootCmd.AddCommand(addCmd)
|
||||
}
|
||||
|
||||
var pName string
|
||||
|
||||
// initialize Command
|
||||
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")
|
||||
}
|
||||
guessProjectPath()
|
||||
createCmdFile(args[0])
|
||||
},
|
||||
}
|
||||
|
||||
func init() {
|
||||
addCmd.Flags().StringVarP(&pName, "parent", "p", "RootCmd", "name of parent command for this command")
|
||||
}
|
||||
|
||||
func parentName() string {
|
||||
if !strings.HasSuffix(strings.ToLower(pName), "cmd") {
|
||||
return pName + "Cmd"
|
||||
}
|
||||
|
||||
return pName
|
||||
}
|
||||
|
||||
func createCmdFile(cmdName string) {
|
||||
lic := getLicense()
|
||||
|
||||
template := `{{ comment .copyright }}
|
||||
{{ comment .license }}
|
||||
|
||||
package cmd
|
||||
|
||||
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) {
|
||||
// TODO: Work your own magic here
|
||||
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")
|
||||
|
||||
}
|
||||
`
|
||||
|
||||
var data map[string]interface{}
|
||||
data = make(map[string]interface{})
|
||||
|
||||
data["copyright"] = copyrightLine()
|
||||
data["license"] = lic.Header
|
||||
data["appName"] = projectName()
|
||||
data["viper"] = viper.GetBool("useViper")
|
||||
data["parentName"] = parentName()
|
||||
data["cmdName"] = cmdName
|
||||
|
||||
err := writeTemplateToFile(filepath.Join(ProjectPath(), guessCmdDir()), cmdName+".go", template, data)
|
||||
if err != nil {
|
||||
er(err)
|
||||
}
|
||||
fmt.Println(cmdName, "created at", filepath.Join(ProjectPath(), guessCmdDir(), cmdName+".go"))
|
||||
}
|
347
vendor/github.com/spf13/cobra/cobra/cmd/helpers.go
generated
vendored
347
vendor/github.com/spf13/cobra/cobra/cmd/helpers.go
generated
vendored
|
@ -1,347 +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"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"text/template"
|
||||
"time"
|
||||
|
||||
"github.com/spf13/viper"
|
||||
)
|
||||
|
||||
// var BaseDir = ""
|
||||
// var AppName = ""
|
||||
// var CommandDir = ""
|
||||
|
||||
var funcMap template.FuncMap
|
||||
var projectPath = ""
|
||||
var inputPath = ""
|
||||
var projectBase = ""
|
||||
|
||||
// for testing only
|
||||
var testWd = ""
|
||||
|
||||
var cmdDirs = []string{"cmd", "cmds", "command", "commands"}
|
||||
|
||||
func init() {
|
||||
funcMap = template.FuncMap{
|
||||
"comment": commentifyString,
|
||||
}
|
||||
}
|
||||
|
||||
func er(msg interface{}) {
|
||||
fmt.Println("Error:", msg)
|
||||
os.Exit(-1)
|
||||
}
|
||||
|
||||
// Check if a file or directory exists.
|
||||
func exists(path string) (bool, error) {
|
||||
_, err := os.Stat(path)
|
||||
if err == nil {
|
||||
return true, nil
|
||||
}
|
||||
if os.IsNotExist(err) {
|
||||
return false, nil
|
||||
}
|
||||
return false, err
|
||||
}
|
||||
|
||||
func ProjectPath() string {
|
||||
if projectPath == "" {
|
||||
guessProjectPath()
|
||||
}
|
||||
|
||||
return projectPath
|
||||
}
|
||||
|
||||
// wrapper of the os package so we can test better
|
||||
func getWd() (string, error) {
|
||||
if testWd == "" {
|
||||
return os.Getwd()
|
||||
}
|
||||
return testWd, nil
|
||||
}
|
||||
|
||||
func guessCmdDir() string {
|
||||
guessProjectPath()
|
||||
if b, _ := isEmpty(projectPath); b {
|
||||
return "cmd"
|
||||
}
|
||||
|
||||
files, _ := filepath.Glob(projectPath + string(os.PathSeparator) + "c*")
|
||||
for _, f := range files {
|
||||
for _, c := range cmdDirs {
|
||||
if f == c {
|
||||
return c
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return "cmd"
|
||||
}
|
||||
|
||||
func guessImportPath() string {
|
||||
guessProjectPath()
|
||||
|
||||
if !strings.HasPrefix(projectPath, getSrcPath()) {
|
||||
er("Cobra only supports project within $GOPATH")
|
||||
}
|
||||
|
||||
return filepath.ToSlash(filepath.Clean(strings.TrimPrefix(projectPath, getSrcPath())))
|
||||
}
|
||||
|
||||
func getSrcPath() string {
|
||||
return filepath.Join(os.Getenv("GOPATH"), "src") + string(os.PathSeparator)
|
||||
}
|
||||
|
||||
func projectName() string {
|
||||
return filepath.Base(ProjectPath())
|
||||
}
|
||||
|
||||
func guessProjectPath() {
|
||||
// if no path is provided... assume CWD.
|
||||
if inputPath == "" {
|
||||
x, err := getWd()
|
||||
if err != nil {
|
||||
er(err)
|
||||
}
|
||||
|
||||
// inspect CWD
|
||||
base := filepath.Base(x)
|
||||
|
||||
// if we are in the cmd directory.. back up
|
||||
for _, c := range cmdDirs {
|
||||
if base == c {
|
||||
projectPath = filepath.Dir(x)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
if projectPath == "" {
|
||||
projectPath = filepath.Clean(x)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
srcPath := getSrcPath()
|
||||
// if provided, inspect for logical locations
|
||||
if strings.ContainsRune(inputPath, os.PathSeparator) {
|
||||
if filepath.IsAbs(inputPath) || filepath.HasPrefix(inputPath, string(os.PathSeparator)) {
|
||||
// if Absolute, use it
|
||||
projectPath = filepath.Clean(inputPath)
|
||||
return
|
||||
}
|
||||
// If not absolute but contains slashes,
|
||||
// assuming it means create it from $GOPATH
|
||||
count := strings.Count(inputPath, string(os.PathSeparator))
|
||||
|
||||
switch count {
|
||||
// If only one directory deep, assume "github.com"
|
||||
case 1:
|
||||
projectPath = filepath.Join(srcPath, "github.com", inputPath)
|
||||
return
|
||||
case 2:
|
||||
projectPath = filepath.Join(srcPath, inputPath)
|
||||
return
|
||||
default:
|
||||
er("Unknown directory")
|
||||
}
|
||||
} else {
|
||||
// hardest case.. just a word.
|
||||
if projectBase == "" {
|
||||
x, err := getWd()
|
||||
if err == nil {
|
||||
projectPath = filepath.Join(x, inputPath)
|
||||
return
|
||||
}
|
||||
er(err)
|
||||
} else {
|
||||
projectPath = filepath.Join(srcPath, projectBase, inputPath)
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// isEmpty checks if a given path is empty.
|
||||
func isEmpty(path string) (bool, error) {
|
||||
if b, _ := exists(path); !b {
|
||||
return false, fmt.Errorf("%q path does not exist", path)
|
||||
}
|
||||
fi, err := os.Stat(path)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
if fi.IsDir() {
|
||||
f, err := os.Open(path)
|
||||
// FIX: Resource leak - f.close() should be called here by defer or is missed
|
||||
// if the err != nil branch is taken.
|
||||
defer f.Close()
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
list, err := f.Readdir(-1)
|
||||
// f.Close() - see bug fix above
|
||||
return len(list) == 0, nil
|
||||
}
|
||||
return fi.Size() == 0, nil
|
||||
}
|
||||
|
||||
// isDir checks if a given path is a directory.
|
||||
func isDir(path string) (bool, error) {
|
||||
fi, err := os.Stat(path)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
return fi.IsDir(), nil
|
||||
}
|
||||
|
||||
// dirExists checks if a path exists and is a directory.
|
||||
func dirExists(path string) (bool, error) {
|
||||
fi, err := os.Stat(path)
|
||||
if err == nil && fi.IsDir() {
|
||||
return true, nil
|
||||
}
|
||||
if os.IsNotExist(err) {
|
||||
return false, nil
|
||||
}
|
||||
return false, err
|
||||
}
|
||||
|
||||
func writeTemplateToFile(path string, file string, template string, data interface{}) error {
|
||||
filename := filepath.Join(path, file)
|
||||
|
||||
r, err := templateToReader(template, data)
|
||||
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
err = safeWriteToDisk(filename, r)
|
||||
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func writeStringToFile(path, file, text string) error {
|
||||
filename := filepath.Join(path, file)
|
||||
|
||||
r := strings.NewReader(text)
|
||||
err := safeWriteToDisk(filename, r)
|
||||
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func templateToReader(tpl string, data interface{}) (io.Reader, error) {
|
||||
tmpl := template.New("")
|
||||
tmpl.Funcs(funcMap)
|
||||
tmpl, err := tmpl.Parse(tpl)
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
buf := new(bytes.Buffer)
|
||||
err = tmpl.Execute(buf, data)
|
||||
|
||||
return buf, err
|
||||
}
|
||||
|
||||
// Same as WriteToDisk but checks to see if file/directory already exists.
|
||||
func safeWriteToDisk(inpath string, r io.Reader) (err error) {
|
||||
dir, _ := filepath.Split(inpath)
|
||||
ospath := filepath.FromSlash(dir)
|
||||
|
||||
if ospath != "" {
|
||||
err = os.MkdirAll(ospath, 0777) // rwx, rw, r
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
ex, err := exists(inpath)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
if ex {
|
||||
return fmt.Errorf("%v already exists", inpath)
|
||||
}
|
||||
|
||||
file, err := os.Create(inpath)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
defer file.Close()
|
||||
|
||||
_, err = io.Copy(file, r)
|
||||
return
|
||||
}
|
||||
|
||||
func getLicense() License {
|
||||
l := whichLicense()
|
||||
if l != "" {
|
||||
if x, ok := Licenses[l]; ok {
|
||||
return x
|
||||
}
|
||||
}
|
||||
|
||||
return Licenses["apache"]
|
||||
}
|
||||
|
||||
func whichLicense() string {
|
||||
// if explicitly flagged, use that
|
||||
if userLicense != "" {
|
||||
return matchLicense(userLicense)
|
||||
}
|
||||
|
||||
// if already present in the project, use that
|
||||
// TODO: Inspect project for existing license
|
||||
|
||||
// default to viper's setting
|
||||
|
||||
return matchLicense(viper.GetString("license"))
|
||||
}
|
||||
|
||||
func copyrightLine() string {
|
||||
author := viper.GetString("author")
|
||||
year := time.Now().Format("2006")
|
||||
|
||||
return "Copyright © " + year + " " + author
|
||||
}
|
||||
|
||||
func commentifyString(in string) string {
|
||||
var newlines []string
|
||||
lines := strings.Split(in, "\n")
|
||||
for _, x := range lines {
|
||||
if !strings.HasPrefix(x, "//") {
|
||||
if x != "" {
|
||||
newlines = append(newlines, "// "+x)
|
||||
} else {
|
||||
newlines = append(newlines, "//")
|
||||
}
|
||||
} else {
|
||||
newlines = append(newlines, x)
|
||||
}
|
||||
}
|
||||
return strings.Join(newlines, "\n")
|
||||
}
|
40
vendor/github.com/spf13/cobra/cobra/cmd/helpers_test.go
generated
vendored
40
vendor/github.com/spf13/cobra/cobra/cmd/helpers_test.go
generated
vendored
|
@ -1,40 +0,0 @@
|
|||
package cmd
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
)
|
||||
|
||||
var _ = fmt.Println
|
||||
var _ = os.Stderr
|
||||
|
||||
func checkGuess(t *testing.T, wd, input, expected string) {
|
||||
testWd = wd
|
||||
inputPath = input
|
||||
guessProjectPath()
|
||||
|
||||
if projectPath != expected {
|
||||
t.Errorf("Unexpected Project Path. \n Got: %q\nExpected: %q\n", projectPath, expected)
|
||||
}
|
||||
|
||||
reset()
|
||||
}
|
||||
|
||||
func reset() {
|
||||
testWd = ""
|
||||
inputPath = ""
|
||||
projectPath = ""
|
||||
}
|
||||
|
||||
func TestProjectPath(t *testing.T) {
|
||||
checkGuess(t, "", filepath.Join("github.com", "spf13", "hugo"), filepath.Join(getSrcPath(), "github.com", "spf13", "hugo"))
|
||||
checkGuess(t, "", filepath.Join("spf13", "hugo"), filepath.Join(getSrcPath(), "github.com", "spf13", "hugo"))
|
||||
checkGuess(t, "", filepath.Join("/", "bar", "foo"), filepath.Join("/", "bar", "foo"))
|
||||
checkGuess(t, "/bar/foo", "baz", filepath.Join("/", "bar", "foo", "baz"))
|
||||
checkGuess(t, "/bar/foo/cmd", "", filepath.Join("/", "bar", "foo"))
|
||||
checkGuess(t, "/bar/foo/command", "", filepath.Join("/", "bar", "foo"))
|
||||
checkGuess(t, "/bar/foo/commands", "", filepath.Join("/", "bar", "foo"))
|
||||
checkGuess(t, "github.com/spf13/hugo/../hugo", "", filepath.Join("github.com", "spf13", "hugo"))
|
||||
}
|
226
vendor/github.com/spf13/cobra/cobra/cmd/init.go
generated
vendored
226
vendor/github.com/spf13/cobra/cobra/cmd/init.go
generated
vendored
|
@ -1,226 +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"
|
||||
"strings"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
"github.com/spf13/viper"
|
||||
)
|
||||
|
||||
func init() {
|
||||
RootCmd.AddCommand(initCmd)
|
||||
}
|
||||
|
||||
// initialize Command
|
||||
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) {
|
||||
switch len(args) {
|
||||
case 0:
|
||||
inputPath = ""
|
||||
|
||||
case 1:
|
||||
inputPath = args[0]
|
||||
|
||||
default:
|
||||
er("init doesn't support more than 1 parameter")
|
||||
}
|
||||
guessProjectPath()
|
||||
initializePath(projectPath)
|
||||
},
|
||||
}
|
||||
|
||||
func initializePath(path string) {
|
||||
b, err := exists(path)
|
||||
if err != nil {
|
||||
er(err)
|
||||
}
|
||||
|
||||
if !b { // If path doesn't yet exist, create it
|
||||
err := os.MkdirAll(path, os.ModePerm)
|
||||
if err != nil {
|
||||
er(err)
|
||||
}
|
||||
} else { // If path exists and is not empty don't use it
|
||||
empty, err := exists(path)
|
||||
if err != nil {
|
||||
er(err)
|
||||
}
|
||||
if !empty {
|
||||
er("Cobra will not create a new project in a non empty directory")
|
||||
}
|
||||
}
|
||||
// We have a directory and it's empty.. Time to initialize it.
|
||||
|
||||
createLicenseFile()
|
||||
createMainFile()
|
||||
createRootCmdFile()
|
||||
}
|
||||
|
||||
func createLicenseFile() {
|
||||
lic := getLicense()
|
||||
|
||||
template := lic.Text
|
||||
|
||||
var data map[string]interface{}
|
||||
data = make(map[string]interface{})
|
||||
|
||||
// Try to remove the email address, if any
|
||||
data["copyright"] = strings.Split(copyrightLine(), " <")[0]
|
||||
|
||||
err := writeTemplateToFile(ProjectPath(), "LICENSE", template, data)
|
||||
_ = err
|
||||
// if err != nil {
|
||||
// er(err)
|
||||
// }
|
||||
}
|
||||
|
||||
func createMainFile() {
|
||||
lic := getLicense()
|
||||
|
||||
template := `{{ comment .copyright }}
|
||||
{{ comment .license }}
|
||||
|
||||
package main
|
||||
|
||||
import "{{ .importpath }}"
|
||||
|
||||
func main() {
|
||||
cmd.Execute()
|
||||
}
|
||||
`
|
||||
var data map[string]interface{}
|
||||
data = make(map[string]interface{})
|
||||
|
||||
data["copyright"] = copyrightLine()
|
||||
data["license"] = lic.Header
|
||||
data["importpath"] = guessImportPath() + "/" + guessCmdDir()
|
||||
|
||||
err := writeTemplateToFile(ProjectPath(), "main.go", template, data)
|
||||
_ = err
|
||||
// if err != nil {
|
||||
// er(err)
|
||||
// }
|
||||
}
|
||||
|
||||
func createRootCmdFile() {
|
||||
lic := getLicense()
|
||||
|
||||
template := `{{ comment .copyright }}
|
||||
{{ comment .license }}
|
||||
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
{{ if .viper }} "github.com/spf13/viper"
|
||||
{{ end }})
|
||||
{{if .viper}}
|
||||
var cfgFile string
|
||||
{{ end }}
|
||||
// This 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 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 != "" { // enable ability to specify config file via flag
|
||||
viper.SetConfigFile(cfgFile)
|
||||
}
|
||||
|
||||
viper.SetConfigName(".{{ .appName }}") // name of config file (without extension)
|
||||
viper.AddConfigPath("$HOME") // adding home directory as first search path
|
||||
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 }}`
|
||||
|
||||
var data map[string]interface{}
|
||||
data = make(map[string]interface{})
|
||||
|
||||
data["copyright"] = copyrightLine()
|
||||
data["license"] = lic.Header
|
||||
data["appName"] = projectName()
|
||||
data["viper"] = viper.GetBool("useViper")
|
||||
|
||||
err := writeTemplateToFile(ProjectPath()+string(os.PathSeparator)+guessCmdDir(), "root.go", template, data)
|
||||
if err != nil {
|
||||
er(err)
|
||||
}
|
||||
|
||||
fmt.Println("Your Cobra application is ready at")
|
||||
fmt.Println(ProjectPath())
|
||||
fmt.Println("Give it a try by going there and running `go run main.go`")
|
||||
fmt.Println("Add commands to it by running `cobra add [cmdname]`")
|
||||
}
|
1133
vendor/github.com/spf13/cobra/cobra/cmd/licenses.go
generated
vendored
1133
vendor/github.com/spf13/cobra/cobra/cmd/licenses.go
generated
vendored
File diff suppressed because it is too large
Load diff
84
vendor/github.com/spf13/cobra/cobra/cmd/root.go
generated
vendored
84
vendor/github.com/spf13/cobra/cobra/cmd/root.go
generated
vendored
|
@ -1,84 +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"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
"github.com/spf13/viper"
|
||||
)
|
||||
|
||||
var cfgFile string
|
||||
var userLicense string
|
||||
|
||||
// This represents the base command when called without any subcommands
|
||||
var 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 adds all child commands to the root command sets flags appropriately.
|
||||
func Execute() {
|
||||
if err := RootCmd.Execute(); err != nil {
|
||||
fmt.Println(err)
|
||||
os.Exit(-1)
|
||||
}
|
||||
}
|
||||
|
||||
func init() {
|
||||
cobra.OnInitialize(initConfig)
|
||||
RootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.cobra.yaml)")
|
||||
RootCmd.PersistentFlags().StringVarP(&projectBase, "projectbase", "b", "", "base project directory, e.g. github.com/spf13/")
|
||||
RootCmd.PersistentFlags().StringP("author", "a", "YOUR NAME", "Author name for copyright attribution")
|
||||
RootCmd.PersistentFlags().StringVarP(&userLicense, "license", "l", "", "Name of license for the project (can provide `licensetext` in config)")
|
||||
RootCmd.PersistentFlags().Bool("viper", true, "Use Viper for configuration")
|
||||
viper.BindPFlag("author", RootCmd.PersistentFlags().Lookup("author"))
|
||||
viper.BindPFlag("projectbase", RootCmd.PersistentFlags().Lookup("projectbase"))
|
||||
viper.BindPFlag("useViper", RootCmd.PersistentFlags().Lookup("viper"))
|
||||
viper.SetDefault("author", "NAME HERE <EMAIL ADDRESS>")
|
||||
viper.SetDefault("license", "apache")
|
||||
viper.SetDefault("licenseText", `
|
||||
// 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.
|
||||
`)
|
||||
}
|
||||
|
||||
// Read in config file and ENV variables if set.
|
||||
func initConfig() {
|
||||
if cfgFile != "" { // enable ability to specify config file via flag
|
||||
viper.SetConfigFile(cfgFile)
|
||||
}
|
||||
|
||||
viper.SetConfigName(".cobra") // name of config file (without extension)
|
||||
viper.AddConfigPath("$HOME") // adding home directory as first search path
|
||||
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())
|
||||
}
|
||||
}
|
1169
vendor/github.com/spf13/cobra/cobra_test.go
generated
vendored
1169
vendor/github.com/spf13/cobra/cobra_test.go
generated
vendored
File diff suppressed because it is too large
Load diff
426
vendor/github.com/spf13/cobra/command.go
generated
vendored
426
vendor/github.com/spf13/cobra/command.go
generated
vendored
|
@ -21,6 +21,7 @@ import (
|
|||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sort"
|
||||
"strings"
|
||||
|
||||
flag "github.com/spf13/pflag"
|
||||
|
@ -45,14 +46,20 @@ type Command struct {
|
|||
Long string
|
||||
// Examples of how to use the command
|
||||
Example string
|
||||
// List of all valid non-flag arguments, used for bash completions *TODO* actually validate these
|
||||
// List of all valid non-flag arguments that are accepted in bash completions
|
||||
ValidArgs []string
|
||||
// List of aliases for ValidArgs. These are not suggested to the user in the bash
|
||||
// completion, but accepted if entered manually.
|
||||
ArgAliases []string
|
||||
// Custom functions used by the bash autocompletion generator
|
||||
BashCompletionFunction string
|
||||
// Is this command deprecated and should print this string when used?
|
||||
Deprecated string
|
||||
// Is this command hidden and should NOT show up in the list of available commands?
|
||||
Hidden bool
|
||||
// Annotations are key/value pairs that can be used by applications to identify or
|
||||
// group commands
|
||||
Annotations map[string]string
|
||||
// Full set of flags
|
||||
flags *flag.FlagSet
|
||||
// Set of flags childrens of this command will inherit
|
||||
|
@ -100,13 +107,16 @@ type Command struct {
|
|||
commandsMaxUseLen int
|
||||
commandsMaxCommandPathLen int
|
||||
commandsMaxNameLen int
|
||||
// is commands slice are sorted or not
|
||||
commandsAreSorted bool
|
||||
|
||||
flagErrorBuf *bytes.Buffer
|
||||
|
||||
args []string // actual args parsed from flags
|
||||
output *io.Writer // nil means stderr; use Out() method instead
|
||||
usageFunc func(*Command) error // Usage can be defined by application
|
||||
usageTemplate string // Can be defined by Application
|
||||
args []string // actual args parsed from flags
|
||||
output io.Writer // out writer if set in SetOutput(w)
|
||||
usageFunc func(*Command) error // Usage can be defined by application
|
||||
usageTemplate string // Can be defined by Application
|
||||
flagErrorFunc func(*Command, error) error
|
||||
helpTemplate string // Can be defined by Application
|
||||
helpFunc func(*Command, []string) // Help can be defined by application
|
||||
helpCommand *Command // The help command
|
||||
|
@ -117,60 +127,50 @@ type Command struct {
|
|||
DisableSuggestions bool
|
||||
// If displaying suggestions, allows to set the minimum levenshtein distance to display, must be > 0
|
||||
SuggestionsMinimumDistance int
|
||||
|
||||
// Disable the flag parsing. If this is true all flags will be passed to the command as arguments.
|
||||
DisableFlagParsing bool
|
||||
}
|
||||
|
||||
// os.Args[1:] by default, if desired, can be overridden
|
||||
// SetArgs sets arguments for the command. It is set to os.Args[1:] by default, if desired, can be overridden
|
||||
// particularly useful when testing.
|
||||
func (c *Command) SetArgs(a []string) {
|
||||
c.args = a
|
||||
}
|
||||
|
||||
func (c *Command) getOut(def io.Writer) io.Writer {
|
||||
if c.output != nil {
|
||||
return *c.output
|
||||
}
|
||||
|
||||
if c.HasParent() {
|
||||
return c.parent.Out()
|
||||
} else {
|
||||
return def
|
||||
}
|
||||
}
|
||||
|
||||
func (c *Command) Out() io.Writer {
|
||||
return c.getOut(os.Stderr)
|
||||
}
|
||||
|
||||
func (c *Command) getOutOrStdout() io.Writer {
|
||||
return c.getOut(os.Stdout)
|
||||
}
|
||||
|
||||
// SetOutput sets the destination for usage and error messages.
|
||||
// If output is nil, os.Stderr is used.
|
||||
func (c *Command) SetOutput(output io.Writer) {
|
||||
c.output = &output
|
||||
c.output = output
|
||||
}
|
||||
|
||||
// Usage can be defined by application
|
||||
// SetUsageFunc sets usage function. Usage can be defined by application.
|
||||
func (c *Command) SetUsageFunc(f func(*Command) error) {
|
||||
c.usageFunc = f
|
||||
}
|
||||
|
||||
// Can be defined by Application
|
||||
// SetUsageTemplate sets usage template. Can be defined by Application.
|
||||
func (c *Command) SetUsageTemplate(s string) {
|
||||
c.usageTemplate = s
|
||||
}
|
||||
|
||||
// Can be defined by Application
|
||||
// SetFlagErrorFunc sets a function to generate an error when flag parsing
|
||||
// fails.
|
||||
func (c *Command) SetFlagErrorFunc(f func(*Command, error) error) {
|
||||
c.flagErrorFunc = f
|
||||
}
|
||||
|
||||
// SetHelpFunc sets help function. Can be defined by Application.
|
||||
func (c *Command) SetHelpFunc(f func(*Command, []string)) {
|
||||
c.helpFunc = f
|
||||
}
|
||||
|
||||
// SetHelpCommand sets help command.
|
||||
func (c *Command) SetHelpCommand(cmd *Command) {
|
||||
c.helpCommand = cmd
|
||||
}
|
||||
|
||||
// Can be defined by Application
|
||||
// SetHelpTemplate sets help template to be used. Application can use it to set custom template.
|
||||
func (c *Command) SetHelpTemplate(s string) {
|
||||
c.helpTemplate = s
|
||||
}
|
||||
|
@ -187,6 +187,28 @@ func (c *Command) SetGlobalNormalizationFunc(n func(f *flag.FlagSet, name string
|
|||
}
|
||||
}
|
||||
|
||||
// OutOrStdout returns output to stdout.
|
||||
func (c *Command) OutOrStdout() io.Writer {
|
||||
return c.getOut(os.Stdout)
|
||||
}
|
||||
|
||||
// OutOrStderr returns output to stderr
|
||||
func (c *Command) OutOrStderr() io.Writer {
|
||||
return c.getOut(os.Stderr)
|
||||
}
|
||||
|
||||
func (c *Command) getOut(def io.Writer) io.Writer {
|
||||
if c.output != nil {
|
||||
return c.output
|
||||
}
|
||||
if c.HasParent() {
|
||||
return c.parent.getOut(def)
|
||||
}
|
||||
return def
|
||||
}
|
||||
|
||||
// UsageFunc returns either the function set by SetUsageFunc for this command
|
||||
// or a parent, or it returns a default usage function.
|
||||
func (c *Command) UsageFunc() (f func(*Command) error) {
|
||||
if c.usageFunc != nil {
|
||||
return c.usageFunc
|
||||
|
@ -194,66 +216,118 @@ func (c *Command) UsageFunc() (f func(*Command) error) {
|
|||
|
||||
if c.HasParent() {
|
||||
return c.parent.UsageFunc()
|
||||
} else {
|
||||
return func(c *Command) error {
|
||||
err := tmpl(c.Out(), c.UsageTemplate(), c)
|
||||
if err != nil {
|
||||
fmt.Print(err)
|
||||
}
|
||||
return err
|
||||
}
|
||||
return func(c *Command) error {
|
||||
c.mergePersistentFlags()
|
||||
err := tmpl(c.OutOrStderr(), c.UsageTemplate(), c)
|
||||
if err != nil {
|
||||
c.Println(err)
|
||||
}
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
// Usage puts out the usage for the command.
|
||||
// Used when a user provides invalid input.
|
||||
// Can be defined by user by overriding UsageFunc.
|
||||
func (c *Command) Usage() error {
|
||||
return c.UsageFunc()(c)
|
||||
}
|
||||
|
||||
// HelpFunc returns either the function set by SetHelpFunc for this command
|
||||
// or a parent, or it returns a function which calls c.Help()
|
||||
// or a parent, or it returns a function with default help behavior.
|
||||
func (c *Command) HelpFunc() func(*Command, []string) {
|
||||
cmd := c
|
||||
for cmd != nil {
|
||||
if cmd.helpFunc != nil {
|
||||
return cmd.helpFunc
|
||||
}
|
||||
cmd = cmd.parent
|
||||
if helpFunc := c.checkHelpFunc(); helpFunc != nil {
|
||||
return helpFunc
|
||||
}
|
||||
return func(*Command, []string) {
|
||||
err := c.Help()
|
||||
c.mergePersistentFlags()
|
||||
err := tmpl(c.OutOrStdout(), c.HelpTemplate(), c)
|
||||
if err != nil {
|
||||
c.Println(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var minUsagePadding int = 25
|
||||
// checkHelpFunc checks if there is helpFunc in ancestors of c.
|
||||
func (c *Command) checkHelpFunc() func(*Command, []string) {
|
||||
if c == nil {
|
||||
return nil
|
||||
}
|
||||
if c.helpFunc != nil {
|
||||
return c.helpFunc
|
||||
}
|
||||
if c.HasParent() {
|
||||
return c.parent.checkHelpFunc()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Help puts out the help for the command.
|
||||
// Used when a user calls help [command].
|
||||
// Can be defined by user by overriding HelpFunc.
|
||||
func (c *Command) Help() error {
|
||||
c.HelpFunc()(c, []string{})
|
||||
return nil
|
||||
}
|
||||
|
||||
// UsageString return usage string.
|
||||
func (c *Command) UsageString() string {
|
||||
tmpOutput := c.output
|
||||
bb := new(bytes.Buffer)
|
||||
c.SetOutput(bb)
|
||||
c.Usage()
|
||||
c.output = tmpOutput
|
||||
return bb.String()
|
||||
}
|
||||
|
||||
// FlagErrorFunc returns either the function set by SetFlagErrorFunc for this
|
||||
// command or a parent, or it returns a function which returns the original
|
||||
// error.
|
||||
func (c *Command) FlagErrorFunc() (f func(*Command, error) error) {
|
||||
if c.flagErrorFunc != nil {
|
||||
return c.flagErrorFunc
|
||||
}
|
||||
|
||||
if c.HasParent() {
|
||||
return c.parent.FlagErrorFunc()
|
||||
}
|
||||
return func(c *Command, err error) error {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
var minUsagePadding = 25
|
||||
|
||||
// UsagePadding return padding for the usage.
|
||||
func (c *Command) UsagePadding() int {
|
||||
if c.parent == nil || minUsagePadding > c.parent.commandsMaxUseLen {
|
||||
return minUsagePadding
|
||||
} else {
|
||||
return c.parent.commandsMaxUseLen
|
||||
}
|
||||
return c.parent.commandsMaxUseLen
|
||||
}
|
||||
|
||||
var minCommandPathPadding int = 11
|
||||
var minCommandPathPadding = 11
|
||||
|
||||
//
|
||||
// CommandPathPadding return padding for the command path.
|
||||
func (c *Command) CommandPathPadding() int {
|
||||
if c.parent == nil || minCommandPathPadding > c.parent.commandsMaxCommandPathLen {
|
||||
return minCommandPathPadding
|
||||
} else {
|
||||
return c.parent.commandsMaxCommandPathLen
|
||||
}
|
||||
return c.parent.commandsMaxCommandPathLen
|
||||
}
|
||||
|
||||
var minNamePadding int = 11
|
||||
var minNamePadding = 11
|
||||
|
||||
// NamePadding returns padding for the name.
|
||||
func (c *Command) NamePadding() int {
|
||||
if c.parent == nil || minNamePadding > c.parent.commandsMaxNameLen {
|
||||
return minNamePadding
|
||||
} else {
|
||||
return c.parent.commandsMaxNameLen
|
||||
}
|
||||
return c.parent.commandsMaxNameLen
|
||||
}
|
||||
|
||||
// UsageTemplate returns usage template for the command.
|
||||
func (c *Command) UsageTemplate() string {
|
||||
if c.usageTemplate != "" {
|
||||
return c.usageTemplate
|
||||
|
@ -261,35 +335,34 @@ func (c *Command) UsageTemplate() string {
|
|||
|
||||
if c.HasParent() {
|
||||
return c.parent.UsageTemplate()
|
||||
} else {
|
||||
return `Usage:{{if .Runnable}}
|
||||
{{.UseLine}}{{if .HasFlags}} [flags]{{end}}{{end}}{{if .HasSubCommands}}
|
||||
}
|
||||
return `Usage:{{if .Runnable}}
|
||||
{{if .HasAvailableFlags}}{{appendIfNotPresent .UseLine "[flags]"}}{{else}}{{.UseLine}}{{end}}{{end}}{{if .HasAvailableSubCommands}}
|
||||
{{ .CommandPath}} [command]{{end}}{{if gt .Aliases 0}}
|
||||
|
||||
Aliases:
|
||||
{{.NameAndAliases}}
|
||||
{{end}}{{if .HasExample}}
|
||||
{{.NameAndAliases}}{{end}}{{if .HasExample}}
|
||||
|
||||
Examples:
|
||||
{{ .Example }}{{end}}{{ if .HasAvailableSubCommands}}
|
||||
{{ .Example }}{{end}}{{if .HasAvailableSubCommands}}
|
||||
|
||||
Available Commands:{{range .Commands}}{{if .IsAvailableCommand}}
|
||||
{{rpad .Name .NamePadding }} {{.Short}}{{end}}{{end}}{{end}}{{ if .HasLocalFlags}}
|
||||
Available Commands:{{range .Commands}}{{if (or .IsAvailableCommand (eq .Name "help"))}}
|
||||
{{rpad .Name .NamePadding }} {{.Short}}{{end}}{{end}}{{end}}{{if .HasAvailableLocalFlags}}
|
||||
|
||||
Flags:
|
||||
{{.LocalFlags.FlagUsages | trimRightSpace}}{{end}}{{ if .HasInheritedFlags}}
|
||||
{{.LocalFlags.FlagUsages | trimRightSpace}}{{end}}{{if .HasAvailableInheritedFlags}}
|
||||
|
||||
Global Flags:
|
||||
{{.InheritedFlags.FlagUsages | trimRightSpace}}{{end}}{{if .HasHelpSubCommands}}
|
||||
|
||||
Additional help topics:{{range .Commands}}{{if .IsHelpCommand}}
|
||||
{{rpad .CommandPath .CommandPathPadding}} {{.Short}}{{end}}{{end}}{{end}}{{ if .HasSubCommands }}
|
||||
Additional help topics:{{range .Commands}}{{if .IsAdditionalHelpTopicCommand}}
|
||||
{{rpad .CommandPath .CommandPathPadding}} {{.Short}}{{end}}{{end}}{{end}}{{if .HasAvailableSubCommands}}
|
||||
|
||||
Use "{{.CommandPath}} [command] --help" for more information about a command.{{end}}
|
||||
`
|
||||
}
|
||||
}
|
||||
|
||||
// HelpTemplate return help template for the command.
|
||||
func (c *Command) HelpTemplate() string {
|
||||
if c.helpTemplate != "" {
|
||||
return c.helpTemplate
|
||||
|
@ -297,34 +370,31 @@ func (c *Command) HelpTemplate() string {
|
|||
|
||||
if c.HasParent() {
|
||||
return c.parent.HelpTemplate()
|
||||
} else {
|
||||
return `{{with or .Long .Short }}{{. | trim}}
|
||||
}
|
||||
return `{{with or .Long .Short }}{{. | trim}}
|
||||
|
||||
{{end}}{{if or .Runnable .HasSubCommands}}{{.UsageString}}{{end}}`
|
||||
}
|
||||
}
|
||||
|
||||
// Really only used when casting a command to a commander
|
||||
// Really only used when casting a command to a commander.
|
||||
func (c *Command) resetChildrensParents() {
|
||||
for _, x := range c.commands {
|
||||
x.parent = c
|
||||
}
|
||||
}
|
||||
|
||||
// Test if the named flag is a boolean flag.
|
||||
func isBooleanFlag(name string, f *flag.FlagSet) bool {
|
||||
func hasNoOptDefVal(name string, f *flag.FlagSet) bool {
|
||||
flag := f.Lookup(name)
|
||||
if flag == nil {
|
||||
return false
|
||||
}
|
||||
return flag.Value.Type() == "bool"
|
||||
return len(flag.NoOptDefVal) > 0
|
||||
}
|
||||
|
||||
// Test if the named flag is a boolean flag.
|
||||
func isBooleanShortFlag(name string, f *flag.FlagSet) bool {
|
||||
func shortHasNoOptDefVal(name string, fs *flag.FlagSet) bool {
|
||||
result := false
|
||||
f.VisitAll(func(f *flag.Flag) {
|
||||
if f.Shorthand == name && f.Value.Type() == "bool" {
|
||||
fs.VisitAll(func(flag *flag.Flag) {
|
||||
if flag.Shorthand == name && len(flag.NoOptDefVal) > 0 {
|
||||
result = true
|
||||
}
|
||||
})
|
||||
|
@ -350,13 +420,13 @@ func stripFlags(args []string, c *Command) []string {
|
|||
inQuote = true
|
||||
case strings.HasPrefix(y, "--") && !strings.Contains(y, "="):
|
||||
// TODO: this isn't quite right, we should really check ahead for 'true' or 'false'
|
||||
inFlag = !isBooleanFlag(y[2:], c.Flags())
|
||||
case strings.HasPrefix(y, "-") && !strings.Contains(y, "=") && len(y) == 2 && !isBooleanShortFlag(y[1:], c.Flags()):
|
||||
inFlag = !hasNoOptDefVal(y[2:], c.Flags())
|
||||
case strings.HasPrefix(y, "-") && !strings.Contains(y, "=") && len(y) == 2 && !shortHasNoOptDefVal(y[1:], c.Flags()):
|
||||
inFlag = true
|
||||
case inFlag:
|
||||
inFlag = false
|
||||
case y == "":
|
||||
// strip empty commands, as the go tests expect this to be ok....
|
||||
// strip empty commands, as the go tests expect this to be ok....
|
||||
case !strings.HasPrefix(y, "-"):
|
||||
commands = append(commands, y)
|
||||
inFlag = false
|
||||
|
@ -385,7 +455,7 @@ func argsMinusFirstX(args []string, x string) []string {
|
|||
return args
|
||||
}
|
||||
|
||||
// find the target command given the args and command tree
|
||||
// Find the target command given the args and command tree
|
||||
// Meant to be run on the highest node. Only searches down.
|
||||
func (c *Command) Find(args []string) (*Command, []string, error) {
|
||||
if c == nil {
|
||||
|
@ -453,6 +523,7 @@ func (c *Command) Find(args []string) (*Command, []string, error) {
|
|||
return commandFound, a, nil
|
||||
}
|
||||
|
||||
// SuggestionsFor provides suggestions for the typedName.
|
||||
func (c *Command) SuggestionsFor(typedName string) []string {
|
||||
suggestions := []string{}
|
||||
for _, cmd := range c.commands {
|
||||
|
@ -473,6 +544,7 @@ func (c *Command) SuggestionsFor(typedName string) []string {
|
|||
return suggestions
|
||||
}
|
||||
|
||||
// VisitParents visits all parents of the command and invokes fn on each parent.
|
||||
func (c *Command) VisitParents(fn func(*Command)) {
|
||||
var traverse func(*Command) *Command
|
||||
|
||||
|
@ -488,6 +560,7 @@ func (c *Command) VisitParents(fn func(*Command)) {
|
|||
traverse(c)
|
||||
}
|
||||
|
||||
// Root finds root command.
|
||||
func (c *Command) Root() *Command {
|
||||
var findRoot func(*Command) *Command
|
||||
|
||||
|
@ -524,7 +597,7 @@ func (c *Command) execute(a []string) (err error) {
|
|||
|
||||
err = c.ParseFlags(a)
|
||||
if err != nil {
|
||||
return err
|
||||
return c.FlagErrorFunc()(c, err)
|
||||
}
|
||||
// If help is called, regardless of other flags, return we want help
|
||||
// Also say we need help if the command isn't runnable.
|
||||
|
@ -535,12 +608,17 @@ func (c *Command) execute(a []string) (err error) {
|
|||
c.Println("\"help\" flag declared as non-bool. Please correct your code")
|
||||
return err
|
||||
}
|
||||
|
||||
if helpVal || !c.Runnable() {
|
||||
return flag.ErrHelp
|
||||
}
|
||||
|
||||
c.preRun()
|
||||
|
||||
argWoFlags := c.Flags().Args()
|
||||
if c.DisableFlagParsing {
|
||||
argWoFlags = a
|
||||
}
|
||||
|
||||
for p := c; p != nil; p = p.Parent() {
|
||||
if p.PersistentPreRunE != nil {
|
||||
|
@ -603,12 +681,11 @@ func (c *Command) errorMsgFromParse() string {
|
|||
|
||||
if len(x) > 0 {
|
||||
return x[0]
|
||||
} else {
|
||||
return ""
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// Call execute to use the args (os.Args[1:] by default)
|
||||
// Execute Call execute to use the args (os.Args[1:] by default)
|
||||
// and run through the command tree finding appropriate matches
|
||||
// for commands and then corresponding flags.
|
||||
func (c *Command) Execute() error {
|
||||
|
@ -616,8 +693,8 @@ func (c *Command) Execute() error {
|
|||
return err
|
||||
}
|
||||
|
||||
// ExecuteC executes the command.
|
||||
func (c *Command) ExecuteC() (cmd *Command, err error) {
|
||||
|
||||
// Regardless of what command execute is called on, run on Root only
|
||||
if c.HasParent() {
|
||||
return c.Root().ExecuteC()
|
||||
|
@ -679,6 +756,7 @@ func (c *Command) ExecuteC() (cmd *Command, err error) {
|
|||
}
|
||||
|
||||
func (c *Command) initHelpFlag() {
|
||||
c.mergePersistentFlags()
|
||||
if c.Flags().Lookup("help") == nil {
|
||||
c.Flags().BoolP("help", "h", false, "help for "+c.Name())
|
||||
}
|
||||
|
@ -701,26 +779,38 @@ func (c *Command) initHelpCmd() {
|
|||
Run: func(c *Command, args []string) {
|
||||
cmd, _, e := c.Root().Find(args)
|
||||
if cmd == nil || e != nil {
|
||||
c.Printf("Unknown help topic %#q.", args)
|
||||
c.Printf("Unknown help topic %#q\n", args)
|
||||
c.Root().Usage()
|
||||
} else {
|
||||
helpFunc := cmd.HelpFunc()
|
||||
helpFunc(cmd, args)
|
||||
cmd.Help()
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
c.RemoveCommand(c.helpCommand)
|
||||
c.AddCommand(c.helpCommand)
|
||||
}
|
||||
|
||||
// Used for testing
|
||||
// ResetCommands used for testing.
|
||||
func (c *Command) ResetCommands() {
|
||||
c.commands = nil
|
||||
c.helpCommand = nil
|
||||
}
|
||||
|
||||
//Commands returns a slice of child commands.
|
||||
// Sorts commands by their names.
|
||||
type commandSorterByName []*Command
|
||||
|
||||
func (c commandSorterByName) Len() int { return len(c) }
|
||||
func (c commandSorterByName) Swap(i, j int) { c[i], c[j] = c[j], c[i] }
|
||||
func (c commandSorterByName) Less(i, j int) bool { return c[i].Name() < c[j].Name() }
|
||||
|
||||
// Commands returns a sorted slice of child commands.
|
||||
func (c *Command) Commands() []*Command {
|
||||
// do not sort commands if it already sorted or sorting was disabled
|
||||
if EnableCommandSorting && !c.commandsAreSorted {
|
||||
sort.Sort(commandSorterByName(c.commands))
|
||||
c.commandsAreSorted = true
|
||||
}
|
||||
return c.commands
|
||||
}
|
||||
|
||||
|
@ -749,10 +839,11 @@ func (c *Command) AddCommand(cmds ...*Command) {
|
|||
x.SetGlobalNormalizationFunc(c.globNormFunc)
|
||||
}
|
||||
c.commands = append(c.commands, x)
|
||||
c.commandsAreSorted = false
|
||||
}
|
||||
}
|
||||
|
||||
// AddCommand removes one or more commands from a parent command.
|
||||
// RemoveCommand removes one or more commands from a parent command.
|
||||
func (c *Command) RemoveCommand(cmds ...*Command) {
|
||||
commands := []*Command{}
|
||||
main:
|
||||
|
@ -786,50 +877,23 @@ main:
|
|||
}
|
||||
}
|
||||
|
||||
// Convenience method to Print to the defined output
|
||||
// Print is a convenience method to Print to the defined output, fallback to Stderr if not set.
|
||||
func (c *Command) Print(i ...interface{}) {
|
||||
fmt.Fprint(c.Out(), i...)
|
||||
fmt.Fprint(c.OutOrStderr(), i...)
|
||||
}
|
||||
|
||||
// Convenience method to Println to the defined output
|
||||
// Println is a convenience method to Println to the defined output, fallback to Stderr if not set.
|
||||
func (c *Command) Println(i ...interface{}) {
|
||||
str := fmt.Sprintln(i...)
|
||||
c.Print(str)
|
||||
}
|
||||
|
||||
// Convenience method to Printf to the defined output
|
||||
// Printf is a convenience method to Printf to the defined output, fallback to Stderr if not set.
|
||||
func (c *Command) Printf(format string, i ...interface{}) {
|
||||
str := fmt.Sprintf(format, i...)
|
||||
c.Print(str)
|
||||
}
|
||||
|
||||
// Output the usage for the command
|
||||
// Used when a user provides invalid input
|
||||
// Can be defined by user by overriding UsageFunc
|
||||
func (c *Command) Usage() error {
|
||||
c.mergePersistentFlags()
|
||||
err := c.UsageFunc()(c)
|
||||
return err
|
||||
}
|
||||
|
||||
// Output the help for the command
|
||||
// Used when a user calls help [command]
|
||||
// by the default HelpFunc in the commander
|
||||
func (c *Command) Help() error {
|
||||
c.mergePersistentFlags()
|
||||
err := tmpl(c.getOutOrStdout(), c.HelpTemplate(), c)
|
||||
return err
|
||||
}
|
||||
|
||||
func (c *Command) UsageString() string {
|
||||
tmpOutput := c.output
|
||||
bb := new(bytes.Buffer)
|
||||
c.SetOutput(bb)
|
||||
c.Usage()
|
||||
c.output = tmpOutput
|
||||
return bb.String()
|
||||
}
|
||||
|
||||
// CommandPath returns the full path to this command.
|
||||
func (c *Command) CommandPath() string {
|
||||
str := c.Name()
|
||||
|
@ -841,7 +905,7 @@ func (c *Command) CommandPath() string {
|
|||
return str
|
||||
}
|
||||
|
||||
//The full usage for a given command (including parents)
|
||||
// UseLine puts out the full usage for a given command (including parents).
|
||||
func (c *Command) UseLine() string {
|
||||
str := ""
|
||||
if c.HasParent() {
|
||||
|
@ -850,8 +914,8 @@ func (c *Command) UseLine() string {
|
|||
return str + c.Use
|
||||
}
|
||||
|
||||
// For use in determining which flags have been assigned to which commands
|
||||
// and which persist
|
||||
// DebugFlags used to determine which flags have been assigned to which commands
|
||||
// and which persist.
|
||||
func (c *Command) DebugFlags() {
|
||||
c.Println("DebugFlags called on", c.Name())
|
||||
var debugflags func(*Command)
|
||||
|
@ -905,10 +969,11 @@ func (c *Command) Name() string {
|
|||
if i >= 0 {
|
||||
name = name[:i]
|
||||
}
|
||||
return name
|
||||
c.name = name
|
||||
return c.name
|
||||
}
|
||||
|
||||
// Determine if a given string is an alias of the command.
|
||||
// HasAlias determines if a given string is an alias of the command.
|
||||
func (c *Command) HasAlias(s string) bool {
|
||||
for _, a := range c.Aliases {
|
||||
if a == s {
|
||||
|
@ -918,26 +983,28 @@ func (c *Command) HasAlias(s string) bool {
|
|||
return false
|
||||
}
|
||||
|
||||
// NameAndAliases returns string containing name and all aliases
|
||||
func (c *Command) NameAndAliases() string {
|
||||
return strings.Join(append([]string{c.Name()}, c.Aliases...), ", ")
|
||||
}
|
||||
|
||||
// HasExample determines if the command has example.
|
||||
func (c *Command) HasExample() bool {
|
||||
return len(c.Example) > 0
|
||||
}
|
||||
|
||||
// Determine if the command is itself runnable
|
||||
// Runnable determines if the command is itself runnable.
|
||||
func (c *Command) Runnable() bool {
|
||||
return c.Run != nil || c.RunE != nil
|
||||
}
|
||||
|
||||
// Determine if the command has children commands
|
||||
// HasSubCommands determines if the command has children commands.
|
||||
func (c *Command) HasSubCommands() bool {
|
||||
return len(c.commands) > 0
|
||||
}
|
||||
|
||||
// IsAvailableCommand determines if a command is available as a non-help command
|
||||
// (this includes all non deprecated/hidden commands)
|
||||
// (this includes all non deprecated/hidden commands).
|
||||
func (c *Command) IsAvailableCommand() bool {
|
||||
if len(c.Deprecated) != 0 || c.Hidden {
|
||||
return false
|
||||
|
@ -954,11 +1021,12 @@ func (c *Command) IsAvailableCommand() bool {
|
|||
return false
|
||||
}
|
||||
|
||||
// IsHelpCommand determines if a command is a 'help' command; a help command is
|
||||
// determined by the fact that it is NOT runnable/hidden/deprecated, and has no
|
||||
// sub commands that are runnable/hidden/deprecated
|
||||
func (c *Command) IsHelpCommand() bool {
|
||||
|
||||
// IsAdditionalHelpTopicCommand determines if a command is an additional
|
||||
// help topic command; additional help topic command is determined by the
|
||||
// fact that it is NOT runnable/hidden/deprecated, and has no sub commands that
|
||||
// are runnable/hidden/deprecated.
|
||||
// Concrete example: https://github.com/spf13/cobra/issues/393#issuecomment-282741924.
|
||||
func (c *Command) IsAdditionalHelpTopicCommand() bool {
|
||||
// if a command is runnable, deprecated, or hidden it is not a 'help' command
|
||||
if c.Runnable() || len(c.Deprecated) != 0 || c.Hidden {
|
||||
return false
|
||||
|
@ -966,7 +1034,7 @@ func (c *Command) IsHelpCommand() bool {
|
|||
|
||||
// if any non-help sub commands are found, the command is not a 'help' command
|
||||
for _, sub := range c.commands {
|
||||
if !sub.IsHelpCommand() {
|
||||
if !sub.IsAdditionalHelpTopicCommand() {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
@ -975,14 +1043,13 @@ func (c *Command) IsHelpCommand() bool {
|
|||
return true
|
||||
}
|
||||
|
||||
// HasHelpSubCommands determines if a command has any avilable 'help' sub commands
|
||||
// HasHelpSubCommands determines if a command has any available 'help' sub commands
|
||||
// that need to be shown in the usage/help default template under 'additional help
|
||||
// topics'
|
||||
// topics'.
|
||||
func (c *Command) HasHelpSubCommands() bool {
|
||||
|
||||
// return true on the first found available 'help' sub command
|
||||
for _, sub := range c.commands {
|
||||
if sub.IsHelpCommand() {
|
||||
if sub.IsAdditionalHelpTopicCommand() {
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
@ -992,9 +1059,8 @@ func (c *Command) HasHelpSubCommands() bool {
|
|||
}
|
||||
|
||||
// HasAvailableSubCommands determines if a command has available sub commands that
|
||||
// need to be shown in the usage/help default template under 'available commands'
|
||||
// need to be shown in the usage/help default template under 'available commands'.
|
||||
func (c *Command) HasAvailableSubCommands() bool {
|
||||
|
||||
// return true on the first found available (non deprecated/help/hidden)
|
||||
// sub command
|
||||
for _, sub := range c.commands {
|
||||
|
@ -1008,17 +1074,18 @@ func (c *Command) HasAvailableSubCommands() bool {
|
|||
return false
|
||||
}
|
||||
|
||||
// Determine if the command is a child command
|
||||
// HasParent determines if the command is a child command.
|
||||
func (c *Command) HasParent() bool {
|
||||
return c.parent != nil
|
||||
}
|
||||
|
||||
// GlobalNormalizationFunc returns the global normalization function or nil if doesn't exists
|
||||
// GlobalNormalizationFunc returns the global normalization function or nil if doesn't exists.
|
||||
func (c *Command) GlobalNormalizationFunc() func(f *flag.FlagSet, name string) flag.NormalizedName {
|
||||
return c.globNormFunc
|
||||
}
|
||||
|
||||
// Get the complete FlagSet that applies to this command (local and persistent declared here and by all parents)
|
||||
// Flags returns the complete FlagSet that applies
|
||||
// to this command (local and persistent declared here and by all parents).
|
||||
func (c *Command) Flags() *flag.FlagSet {
|
||||
if c.flags == nil {
|
||||
c.flags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)
|
||||
|
@ -1030,7 +1097,20 @@ func (c *Command) Flags() *flag.FlagSet {
|
|||
return c.flags
|
||||
}
|
||||
|
||||
// Get the local FlagSet specifically set in the current command
|
||||
// LocalNonPersistentFlags are flags specific to this command which will NOT persist to subcommands.
|
||||
func (c *Command) LocalNonPersistentFlags() *flag.FlagSet {
|
||||
persistentFlags := c.PersistentFlags()
|
||||
|
||||
out := flag.NewFlagSet(c.Name(), flag.ContinueOnError)
|
||||
c.LocalFlags().VisitAll(func(f *flag.Flag) {
|
||||
if persistentFlags.Lookup(f.Name) == nil {
|
||||
out.AddFlag(f)
|
||||
}
|
||||
})
|
||||
return out
|
||||
}
|
||||
|
||||
// LocalFlags returns the local FlagSet specifically set in the current command.
|
||||
func (c *Command) LocalFlags() *flag.FlagSet {
|
||||
c.mergePersistentFlags()
|
||||
|
||||
|
@ -1048,7 +1128,7 @@ func (c *Command) LocalFlags() *flag.FlagSet {
|
|||
return local
|
||||
}
|
||||
|
||||
// All Flags which were inherited from parents commands
|
||||
// InheritedFlags returns all flags which were inherited from parents commands.
|
||||
func (c *Command) InheritedFlags() *flag.FlagSet {
|
||||
c.mergePersistentFlags()
|
||||
|
||||
|
@ -1077,12 +1157,12 @@ func (c *Command) InheritedFlags() *flag.FlagSet {
|
|||
return inherited
|
||||
}
|
||||
|
||||
// All Flags which were not inherited from parent commands
|
||||
// NonInheritedFlags returns all flags which were not inherited from parent commands.
|
||||
func (c *Command) NonInheritedFlags() *flag.FlagSet {
|
||||
return c.LocalFlags()
|
||||
}
|
||||
|
||||
// Get the Persistent FlagSet specifically set in the current command
|
||||
// PersistentFlags returns the persistent FlagSet specifically set in the current command.
|
||||
func (c *Command) PersistentFlags() *flag.FlagSet {
|
||||
if c.pflags == nil {
|
||||
c.pflags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)
|
||||
|
@ -1094,7 +1174,7 @@ func (c *Command) PersistentFlags() *flag.FlagSet {
|
|||
return c.pflags
|
||||
}
|
||||
|
||||
// For use in testing
|
||||
// ResetFlags is used in testing.
|
||||
func (c *Command) ResetFlags() {
|
||||
c.flagErrorBuf = new(bytes.Buffer)
|
||||
c.flagErrorBuf.Reset()
|
||||
|
@ -1104,26 +1184,50 @@ func (c *Command) ResetFlags() {
|
|||
c.pflags.SetOutput(c.flagErrorBuf)
|
||||
}
|
||||
|
||||
// Does the command contain any flags (local plus persistent from the entire structure)
|
||||
// HasFlags checks if the command contains any flags (local plus persistent from the entire structure).
|
||||
func (c *Command) HasFlags() bool {
|
||||
return c.Flags().HasFlags()
|
||||
}
|
||||
|
||||
// Does the command contain persistent flags
|
||||
// HasPersistentFlags checks if the command contains persistent flags.
|
||||
func (c *Command) HasPersistentFlags() bool {
|
||||
return c.PersistentFlags().HasFlags()
|
||||
}
|
||||
|
||||
// Does the command has flags specifically declared locally
|
||||
// HasLocalFlags checks if the command has flags specifically declared locally.
|
||||
func (c *Command) HasLocalFlags() bool {
|
||||
return c.LocalFlags().HasFlags()
|
||||
}
|
||||
|
||||
// HasInheritedFlags checks if the command has flags inherited from its parent command.
|
||||
func (c *Command) HasInheritedFlags() bool {
|
||||
return c.InheritedFlags().HasFlags()
|
||||
}
|
||||
|
||||
// Climbs up the command tree looking for matching flag
|
||||
// HasAvailableFlags checks if the command contains any flags (local plus persistent from the entire
|
||||
// structure) which are not hidden or deprecated.
|
||||
func (c *Command) HasAvailableFlags() bool {
|
||||
return c.Flags().HasAvailableFlags()
|
||||
}
|
||||
|
||||
// HasAvailablePersistentFlags checks if the command contains persistent flags which are not hidden or deprecated.
|
||||
func (c *Command) HasAvailablePersistentFlags() bool {
|
||||
return c.PersistentFlags().HasAvailableFlags()
|
||||
}
|
||||
|
||||
// HasAvailableLocalFlags checks if the command has flags specifically declared locally which are not hidden
|
||||
// or deprecated.
|
||||
func (c *Command) HasAvailableLocalFlags() bool {
|
||||
return c.LocalFlags().HasAvailableFlags()
|
||||
}
|
||||
|
||||
// HasAvailableInheritedFlags checks if the command has flags inherited from its parent command which are
|
||||
// not hidden or deprecated.
|
||||
func (c *Command) HasAvailableInheritedFlags() bool {
|
||||
return c.InheritedFlags().HasAvailableFlags()
|
||||
}
|
||||
|
||||
// Flag climbs up the command tree looking for matching flag.
|
||||
func (c *Command) Flag(name string) (flag *flag.Flag) {
|
||||
flag = c.Flags().Lookup(name)
|
||||
|
||||
|
@ -1134,7 +1238,7 @@ func (c *Command) Flag(name string) (flag *flag.Flag) {
|
|||
return
|
||||
}
|
||||
|
||||
// recursively find matching persistent flag
|
||||
// Recursively find matching persistent flag.
|
||||
func (c *Command) persistentFlag(name string) (flag *flag.Flag) {
|
||||
if c.HasPersistentFlags() {
|
||||
flag = c.PersistentFlags().Lookup(name)
|
||||
|
@ -1146,13 +1250,17 @@ func (c *Command) persistentFlag(name string) (flag *flag.Flag) {
|
|||
return
|
||||
}
|
||||
|
||||
// Parses persistent flag tree & local flags
|
||||
// ParseFlags parses persistent flag tree and local flags.
|
||||
func (c *Command) ParseFlags(args []string) (err error) {
|
||||
if c.DisableFlagParsing {
|
||||
return nil
|
||||
}
|
||||
c.mergePersistentFlags()
|
||||
err = c.Flags().Parse(args)
|
||||
return
|
||||
}
|
||||
|
||||
// Parent returns a commands parent command.
|
||||
func (c *Command) Parent() *Command {
|
||||
return c.parent
|
||||
}
|
||||
|
|
2
vendor/github.com/spf13/cobra/command_notwin.go
generated
vendored
2
vendor/github.com/spf13/cobra/command_notwin.go
generated
vendored
|
@ -2,4 +2,4 @@
|
|||
|
||||
package cobra
|
||||
|
||||
var preExecHookFn func(*Command) = nil
|
||||
var preExecHookFn func(*Command)
|
||||
|
|
114
vendor/github.com/spf13/cobra/command_test.go
generated
vendored
114
vendor/github.com/spf13/cobra/command_test.go
generated
vendored
|
@ -1,114 +0,0 @@
|
|||
package cobra
|
||||
|
||||
import (
|
||||
"reflect"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// test to ensure hidden commands run as intended
|
||||
func TestHiddenCommandExecutes(t *testing.T) {
|
||||
|
||||
// ensure that outs does not already equal what the command will be setting it
|
||||
// to, if it did this test would not actually be testing anything...
|
||||
if outs == "hidden" {
|
||||
t.Errorf("outs should NOT EQUAL hidden")
|
||||
}
|
||||
|
||||
cmdHidden.Execute()
|
||||
|
||||
// upon running the command, the value of outs should now be 'hidden'
|
||||
if outs != "hidden" {
|
||||
t.Errorf("Hidden command failed to run!")
|
||||
}
|
||||
}
|
||||
|
||||
// test to ensure hidden commands do not show up in usage/help text
|
||||
func TestHiddenCommandIsHidden(t *testing.T) {
|
||||
if cmdHidden.IsAvailableCommand() {
|
||||
t.Errorf("Hidden command found!")
|
||||
}
|
||||
}
|
||||
|
||||
func TestStripFlags(t *testing.T) {
|
||||
tests := []struct {
|
||||
input []string
|
||||
output []string
|
||||
}{
|
||||
{
|
||||
[]string{"foo", "bar"},
|
||||
[]string{"foo", "bar"},
|
||||
},
|
||||
{
|
||||
[]string{"foo", "--bar", "-b"},
|
||||
[]string{"foo"},
|
||||
},
|
||||
{
|
||||
[]string{"-b", "foo", "--bar", "bar"},
|
||||
[]string{},
|
||||
},
|
||||
{
|
||||
[]string{"-i10", "echo"},
|
||||
[]string{"echo"},
|
||||
},
|
||||
{
|
||||
[]string{"-i=10", "echo"},
|
||||
[]string{"echo"},
|
||||
},
|
||||
{
|
||||
[]string{"--int=100", "echo"},
|
||||
[]string{"echo"},
|
||||
},
|
||||
{
|
||||
[]string{"-ib", "echo", "-bfoo", "baz"},
|
||||
[]string{"echo", "baz"},
|
||||
},
|
||||
{
|
||||
[]string{"-i=baz", "bar", "-i", "foo", "blah"},
|
||||
[]string{"bar", "blah"},
|
||||
},
|
||||
{
|
||||
[]string{"--int=baz", "-bbar", "-i", "foo", "blah"},
|
||||
[]string{"blah"},
|
||||
},
|
||||
{
|
||||
[]string{"--cat", "bar", "-i", "foo", "blah"},
|
||||
[]string{"bar", "blah"},
|
||||
},
|
||||
{
|
||||
[]string{"-c", "bar", "-i", "foo", "blah"},
|
||||
[]string{"bar", "blah"},
|
||||
},
|
||||
{
|
||||
[]string{"--persist", "bar"},
|
||||
[]string{"bar"},
|
||||
},
|
||||
{
|
||||
[]string{"-p", "bar"},
|
||||
[]string{"bar"},
|
||||
},
|
||||
}
|
||||
|
||||
cmdPrint := &Command{
|
||||
Use: "print [string to print]",
|
||||
Short: "Print anything to the screen",
|
||||
Long: `an utterly useless command for testing.`,
|
||||
Run: func(cmd *Command, args []string) {
|
||||
tp = args
|
||||
},
|
||||
}
|
||||
|
||||
var flagi int
|
||||
var flagstr string
|
||||
var flagbool bool
|
||||
cmdPrint.PersistentFlags().BoolVarP(&flagbool, "persist", "p", false, "help for persistent one")
|
||||
cmdPrint.Flags().IntVarP(&flagi, "int", "i", 345, "help message for flag int")
|
||||
cmdPrint.Flags().StringVarP(&flagstr, "bar", "b", "bar", "help message for flag string")
|
||||
cmdPrint.Flags().BoolVarP(&flagbool, "cat", "c", false, "help message for flag bool")
|
||||
|
||||
for _, test := range tests {
|
||||
output := stripFlags(test.input, cmdPrint)
|
||||
if !reflect.DeepEqual(test.output, output) {
|
||||
t.Errorf("expected: %v, got: %v", test.output, output)
|
||||
}
|
||||
}
|
||||
}
|
145
vendor/github.com/spf13/cobra/doc/cmd_test.go
generated
vendored
145
vendor/github.com/spf13/cobra/doc/cmd_test.go
generated
vendored
|
@ -1,145 +0,0 @@
|
|||
package doc
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"runtime"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
var flagb1, flagb2, flagb3, flagbr, flagbp bool
|
||||
var flags1, flags2a, flags2b, flags3 string
|
||||
var flagi1, flagi2, flagi3, flagir int
|
||||
|
||||
const strtwoParentHelp = "help message for parent flag strtwo"
|
||||
const strtwoChildHelp = "help message for child flag strtwo"
|
||||
|
||||
var cmdEcho = &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 cmdEchoSub = &cobra.Command{
|
||||
Use: "echosub [string to print]",
|
||||
Short: "second sub command for echo",
|
||||
Long: `an absolutely utterly useless command for testing gendocs!.`,
|
||||
Run: func(cmd *cobra.Command, args []string) {},
|
||||
}
|
||||
|
||||
var cmdDeprecated = &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 cmdTimes = &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.`,
|
||||
PersistentPreRun: func(cmd *cobra.Command, args []string) {},
|
||||
Run: func(cmd *cobra.Command, args []string) {},
|
||||
}
|
||||
|
||||
var cmdPrint = &cobra.Command{
|
||||
Use: "print [string to print]",
|
||||
Short: "Print anything to the screen",
|
||||
Long: `an absolutely utterly useless command for testing.`,
|
||||
}
|
||||
|
||||
var cmdRootNoRun = &cobra.Command{
|
||||
Use: "cobra-test",
|
||||
Short: "The root can run its own function",
|
||||
Long: "The root description for help",
|
||||
}
|
||||
|
||||
var cmdRootSameName = &cobra.Command{
|
||||
Use: "print",
|
||||
Short: "Root with the same name as a subcommand",
|
||||
Long: "The root description for help",
|
||||
}
|
||||
|
||||
var cmdRootWithRun = &cobra.Command{
|
||||
Use: "cobra-test",
|
||||
Short: "The root can run its own function",
|
||||
Long: "The root description for help",
|
||||
}
|
||||
|
||||
var cmdSubNoRun = &cobra.Command{
|
||||
Use: "subnorun",
|
||||
Short: "A subcommand without a Run function",
|
||||
Long: "A long output about a subcommand without a Run function",
|
||||
}
|
||||
|
||||
var cmdVersion1 = &cobra.Command{
|
||||
Use: "version",
|
||||
Short: "Print the version number",
|
||||
Long: `First version of the version command`,
|
||||
}
|
||||
|
||||
var cmdVersion2 = &cobra.Command{
|
||||
Use: "version",
|
||||
Short: "Print the version number",
|
||||
Long: `Second version of the version command`,
|
||||
}
|
||||
|
||||
func flagInit() {
|
||||
cmdEcho.ResetFlags()
|
||||
cmdPrint.ResetFlags()
|
||||
cmdTimes.ResetFlags()
|
||||
cmdRootNoRun.ResetFlags()
|
||||
cmdRootSameName.ResetFlags()
|
||||
cmdRootWithRun.ResetFlags()
|
||||
cmdSubNoRun.ResetFlags()
|
||||
cmdRootNoRun.PersistentFlags().StringVarP(&flags2a, "strtwo", "t", "two", strtwoParentHelp)
|
||||
cmdEcho.Flags().IntVarP(&flagi1, "intone", "i", 123, "help message for flag intone")
|
||||
cmdTimes.Flags().IntVarP(&flagi2, "inttwo", "j", 234, "help message for flag inttwo")
|
||||
cmdPrint.Flags().IntVarP(&flagi3, "intthree", "i", 345, "help message for flag intthree")
|
||||
cmdEcho.PersistentFlags().StringVarP(&flags1, "strone", "s", "one", "help message for flag strone")
|
||||
cmdEcho.PersistentFlags().BoolVarP(&flagbp, "persistentbool", "p", false, "help message for flag persistentbool")
|
||||
cmdTimes.PersistentFlags().StringVarP(&flags2b, "strtwo", "t", "2", strtwoChildHelp)
|
||||
cmdPrint.PersistentFlags().StringVarP(&flags3, "strthree", "s", "three", "help message for flag strthree")
|
||||
cmdEcho.Flags().BoolVarP(&flagb1, "boolone", "b", true, "help message for flag boolone")
|
||||
cmdTimes.Flags().BoolVarP(&flagb2, "booltwo", "c", false, "help message for flag booltwo")
|
||||
cmdPrint.Flags().BoolVarP(&flagb3, "boolthree", "b", true, "help message for flag boolthree")
|
||||
cmdVersion1.ResetFlags()
|
||||
cmdVersion2.ResetFlags()
|
||||
}
|
||||
|
||||
func initializeWithRootCmd() *cobra.Command {
|
||||
cmdRootWithRun.ResetCommands()
|
||||
flagInit()
|
||||
cmdRootWithRun.Flags().BoolVarP(&flagbr, "boolroot", "b", false, "help message for flag boolroot")
|
||||
cmdRootWithRun.Flags().IntVarP(&flagir, "introot", "i", 321, "help message for flag introot")
|
||||
return cmdRootWithRun
|
||||
}
|
||||
|
||||
func checkStringContains(t *testing.T, found, expected string) {
|
||||
if !strings.Contains(found, expected) {
|
||||
logErr(t, found, expected)
|
||||
}
|
||||
}
|
||||
|
||||
func checkStringOmits(t *testing.T, found, expected string) {
|
||||
if strings.Contains(found, expected) {
|
||||
logErr(t, found, expected)
|
||||
}
|
||||
}
|
||||
|
||||
func logErr(t *testing.T, found, expected string) {
|
||||
out := new(bytes.Buffer)
|
||||
|
||||
_, _, line, ok := runtime.Caller(2)
|
||||
if ok {
|
||||
fmt.Fprintf(out, "Line: %d ", line)
|
||||
}
|
||||
fmt.Fprintf(out, "Unexpected response.\nExpecting to contain: \n %q\nGot:\n %q\n", expected, found)
|
||||
t.Errorf(out.String())
|
||||
}
|
218
vendor/github.com/spf13/cobra/doc/man_docs.go
generated
vendored
218
vendor/github.com/spf13/cobra/doc/man_docs.go
generated
vendored
|
@ -1,218 +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"
|
||||
|
||||
mangen "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 decendants
|
||||
// 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 {
|
||||
if header == nil {
|
||||
header = &GenManHeader{}
|
||||
}
|
||||
for _, c := range cmd.Commands() {
|
||||
if !c.IsAvailableCommand() || c.IsHelpCommand() {
|
||||
continue
|
||||
}
|
||||
if err := GenManTree(c, header, dir); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
needToResetTitle := header.Title == ""
|
||||
|
||||
basename := strings.Replace(cmd.CommandPath(), " ", "_", -1) + ".1"
|
||||
filename := filepath.Join(dir, basename)
|
||||
f, err := os.Create(filename)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer f.Close()
|
||||
|
||||
if err := GenMan(cmd, header, f); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if needToResetTitle {
|
||||
header.Title = ""
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// 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{}
|
||||
}
|
||||
b := genMan(cmd, header)
|
||||
final := mangen.Render(b)
|
||||
_, err := w.Write(final)
|
||||
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(out io.Writer, header *GenManHeader, name, short, long string) {
|
||||
dashName := strings.Replace(name, " ", "-", -1)
|
||||
fmt.Fprintf(out, `%% %s(%s)%s
|
||||
%% %s
|
||||
%% %s
|
||||
# NAME
|
||||
`, header.Title, header.Section, header.date, header.Source, header.Manual)
|
||||
fmt.Fprintf(out, "%s \\- %s\n\n", dashName, short)
|
||||
fmt.Fprintf(out, "# SYNOPSIS\n")
|
||||
fmt.Fprintf(out, "**%s** [OPTIONS]\n\n", name)
|
||||
fmt.Fprintf(out, "# DESCRIPTION\n")
|
||||
fmt.Fprintf(out, "%s\n\n", long)
|
||||
}
|
||||
|
||||
func manPrintFlags(out io.Writer, flags *pflag.FlagSet) {
|
||||
flags.VisitAll(func(flag *pflag.Flag) {
|
||||
if len(flag.Deprecated) > 0 || flag.Hidden {
|
||||
return
|
||||
}
|
||||
format := ""
|
||||
if len(flag.Shorthand) > 0 {
|
||||
format = "**-%s**, **--%s**"
|
||||
} else {
|
||||
format = "%s**--%s**"
|
||||
}
|
||||
if len(flag.NoOptDefVal) > 0 {
|
||||
format = format + "["
|
||||
}
|
||||
if flag.Value.Type() == "string" {
|
||||
// put quotes on the value
|
||||
format = format + "=%q"
|
||||
} else {
|
||||
format = format + "=%s"
|
||||
}
|
||||
if len(flag.NoOptDefVal) > 0 {
|
||||
format = format + "]"
|
||||
}
|
||||
format = format + "\n\t%s\n\n"
|
||||
fmt.Fprintf(out, format, flag.Shorthand, flag.Name, flag.DefValue, flag.Usage)
|
||||
})
|
||||
}
|
||||
|
||||
func manPrintOptions(out io.Writer, command *cobra.Command) {
|
||||
flags := command.NonInheritedFlags()
|
||||
if flags.HasFlags() {
|
||||
fmt.Fprintf(out, "# OPTIONS\n")
|
||||
manPrintFlags(out, flags)
|
||||
fmt.Fprintf(out, "\n")
|
||||
}
|
||||
flags = command.InheritedFlags()
|
||||
if flags.HasFlags() {
|
||||
fmt.Fprintf(out, "# OPTIONS INHERITED FROM PARENT COMMANDS\n")
|
||||
manPrintFlags(out, flags)
|
||||
fmt.Fprintf(out, "\n")
|
||||
}
|
||||
}
|
||||
|
||||
func genMan(cmd *cobra.Command, header *GenManHeader) []byte {
|
||||
// something like `rootcmd subcmd1 subcmd2`
|
||||
commandName := cmd.CommandPath()
|
||||
// something like `rootcmd-subcmd1-subcmd2`
|
||||
dashCommandName := strings.Replace(commandName, " ", "-", -1)
|
||||
|
||||
fillHeader(header, commandName)
|
||||
|
||||
buf := new(bytes.Buffer)
|
||||
|
||||
short := cmd.Short
|
||||
long := cmd.Long
|
||||
if len(long) == 0 {
|
||||
long = short
|
||||
}
|
||||
|
||||
manPreamble(buf, header, commandName, short, long)
|
||||
manPrintOptions(buf, cmd)
|
||||
if len(cmd.Example) > 0 {
|
||||
fmt.Fprintf(buf, "# EXAMPLE\n")
|
||||
fmt.Fprintf(buf, "```\n%s\n```\n", cmd.Example)
|
||||
}
|
||||
if hasSeeAlso(cmd) {
|
||||
fmt.Fprintf(buf, "# SEE ALSO\n")
|
||||
if cmd.HasParent() {
|
||||
parentPath := cmd.Parent().CommandPath()
|
||||
dashParentPath := strings.Replace(parentPath, " ", "-", -1)
|
||||
fmt.Fprintf(buf, "**%s(%s)**", dashParentPath, header.Section)
|
||||
cmd.VisitParents(func(c *cobra.Command) {
|
||||
if c.DisableAutoGenTag {
|
||||
cmd.DisableAutoGenTag = c.DisableAutoGenTag
|
||||
}
|
||||
})
|
||||
}
|
||||
children := cmd.Commands()
|
||||
sort.Sort(byName(children))
|
||||
for i, c := range children {
|
||||
if !c.IsAvailableCommand() || c.IsHelpCommand() {
|
||||
continue
|
||||
}
|
||||
if cmd.HasParent() || i > 0 {
|
||||
fmt.Fprintf(buf, ", ")
|
||||
}
|
||||
fmt.Fprintf(buf, "**%s-%s(%s)**", dashCommandName, c.Name(), header.Section)
|
||||
}
|
||||
fmt.Fprintf(buf, "\n")
|
||||
}
|
||||
if !cmd.DisableAutoGenTag {
|
||||
fmt.Fprintf(buf, "# HISTORY\n%s Auto generated by spf13/cobra\n", header.Date.Format("2-Jan-2006"))
|
||||
}
|
||||
return buf.Bytes()
|
||||
}
|
26
vendor/github.com/spf13/cobra/doc/man_docs.md
generated
vendored
26
vendor/github.com/spf13/cobra/doc/man_docs.md
generated
vendored
|
@ -1,26 +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 (
|
||||
"github.com/spf13/cobra"
|
||||
"github.com/spf13/cobra/doc"
|
||||
)
|
||||
|
||||
func main() {
|
||||
cmd := &cobra.Command{
|
||||
Use: "test",
|
||||
Short: "my test program",
|
||||
}
|
||||
header := &cobra.GenManHeader{
|
||||
Title: "MINE",
|
||||
Section: "3",
|
||||
}
|
||||
doc.GenManTree(cmd, header, "/tmp")
|
||||
}
|
||||
```
|
||||
|
||||
That will get you a man page `/tmp/test.1`
|
97
vendor/github.com/spf13/cobra/doc/man_docs_test.go
generated
vendored
97
vendor/github.com/spf13/cobra/doc/man_docs_test.go
generated
vendored
|
@ -1,97 +0,0 @@
|
|||
package doc
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"os"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
var _ = fmt.Println
|
||||
var _ = os.Stderr
|
||||
|
||||
func translate(in string) string {
|
||||
return strings.Replace(in, "-", "\\-", -1)
|
||||
}
|
||||
|
||||
func TestGenManDoc(t *testing.T) {
|
||||
c := initializeWithRootCmd()
|
||||
// Need two commands to run the command alphabetical sort
|
||||
cmdEcho.AddCommand(cmdTimes, cmdEchoSub, cmdDeprecated)
|
||||
c.AddCommand(cmdPrint, cmdEcho)
|
||||
cmdRootWithRun.PersistentFlags().StringVarP(&flags2a, "rootflag", "r", "two", strtwoParentHelp)
|
||||
|
||||
out := new(bytes.Buffer)
|
||||
|
||||
header := &GenManHeader{
|
||||
Title: "Project",
|
||||
Section: "2",
|
||||
}
|
||||
// We generate on a subcommand so we have both subcommands and parents
|
||||
if err := GenMan(cmdEcho, header, out); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
found := out.String()
|
||||
|
||||
// Make sure parent has - in CommandPath() in SEE ALSO:
|
||||
parentPath := cmdEcho.Parent().CommandPath()
|
||||
dashParentPath := strings.Replace(parentPath, " ", "-", -1)
|
||||
expected := translate(dashParentPath)
|
||||
expected = expected + "(" + header.Section + ")"
|
||||
checkStringContains(t, found, expected)
|
||||
|
||||
// Our description
|
||||
expected = translate(cmdEcho.Name())
|
||||
checkStringContains(t, found, expected)
|
||||
|
||||
// Better have our example
|
||||
expected = translate(cmdEcho.Name())
|
||||
checkStringContains(t, found, expected)
|
||||
|
||||
// A local flag
|
||||
expected = "boolone"
|
||||
checkStringContains(t, found, expected)
|
||||
|
||||
// persistent flag on parent
|
||||
expected = "rootflag"
|
||||
checkStringContains(t, found, expected)
|
||||
|
||||
// We better output info about our parent
|
||||
expected = translate(cmdRootWithRun.Name())
|
||||
checkStringContains(t, found, expected)
|
||||
|
||||
// And about subcommands
|
||||
expected = translate(cmdEchoSub.Name())
|
||||
checkStringContains(t, found, expected)
|
||||
|
||||
unexpected := translate(cmdDeprecated.Name())
|
||||
checkStringOmits(t, found, unexpected)
|
||||
|
||||
// auto generated
|
||||
expected = translate("Auto generated")
|
||||
checkStringContains(t, found, expected)
|
||||
}
|
||||
|
||||
func TestGenManNoGenTag(t *testing.T) {
|
||||
c := initializeWithRootCmd()
|
||||
// Need two commands to run the command alphabetical sort
|
||||
cmdEcho.AddCommand(cmdTimes, cmdEchoSub, cmdDeprecated)
|
||||
c.AddCommand(cmdPrint, cmdEcho)
|
||||
cmdRootWithRun.PersistentFlags().StringVarP(&flags2a, "rootflag", "r", "two", strtwoParentHelp)
|
||||
cmdEcho.DisableAutoGenTag = true
|
||||
out := new(bytes.Buffer)
|
||||
|
||||
header := &GenManHeader{
|
||||
Title: "Project",
|
||||
Section: "2",
|
||||
}
|
||||
// We generate on a subcommand so we have both subcommands and parents
|
||||
if err := GenMan(cmdEcho, header, out); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
found := out.String()
|
||||
|
||||
unexpected := translate("#HISTORY")
|
||||
checkStringOmits(t, found, unexpected)
|
||||
}
|
35
vendor/github.com/spf13/cobra/doc/man_examples_test.go
generated
vendored
35
vendor/github.com/spf13/cobra/doc/man_examples_test.go
generated
vendored
|
@ -1,35 +0,0 @@
|
|||
package doc_test
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
"github.com/spf13/cobra/doc"
|
||||
)
|
||||
|
||||
func ExampleCommand_GenManTree() {
|
||||
cmd := &cobra.Command{
|
||||
Use: "test",
|
||||
Short: "my test program",
|
||||
}
|
||||
header := &doc.GenManHeader{
|
||||
Title: "MINE",
|
||||
Section: "3",
|
||||
}
|
||||
doc.GenManTree(cmd, header, "/tmp")
|
||||
}
|
||||
|
||||
func ExampleCommand_GenMan() {
|
||||
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())
|
||||
}
|
175
vendor/github.com/spf13/cobra/doc/md_docs.go
generated
vendored
175
vendor/github.com/spf13/cobra/doc/md_docs.go
generated
vendored
|
@ -1,175 +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 (
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
func printOptions(w io.Writer, cmd *cobra.Command, name string) error {
|
||||
flags := cmd.NonInheritedFlags()
|
||||
flags.SetOutput(w)
|
||||
if flags.HasFlags() {
|
||||
if _, err := fmt.Fprintf(w, "### Options\n\n```\n"); err != nil {
|
||||
return err
|
||||
}
|
||||
flags.PrintDefaults()
|
||||
if _, err := fmt.Fprintf(w, "```\n\n"); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
parentFlags := cmd.InheritedFlags()
|
||||
parentFlags.SetOutput(w)
|
||||
if parentFlags.HasFlags() {
|
||||
if _, err := fmt.Fprintf(w, "### Options inherited from parent commands\n\n```\n"); err != nil {
|
||||
return err
|
||||
}
|
||||
parentFlags.PrintDefaults()
|
||||
if _, err := fmt.Fprintf(w, "```\n\n"); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func GenMarkdown(cmd *cobra.Command, w io.Writer) error {
|
||||
return GenMarkdownCustom(cmd, w, func(s string) string { return s })
|
||||
}
|
||||
|
||||
func GenMarkdownCustom(cmd *cobra.Command, w io.Writer, linkHandler func(string) string) error {
|
||||
name := cmd.CommandPath()
|
||||
|
||||
short := cmd.Short
|
||||
long := cmd.Long
|
||||
if len(long) == 0 {
|
||||
long = short
|
||||
}
|
||||
|
||||
if _, err := fmt.Fprintf(w, "## %s\n\n", name); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := fmt.Fprintf(w, "%s\n\n", short); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := fmt.Fprintf(w, "### Synopsis\n\n"); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := fmt.Fprintf(w, "\n%s\n\n", long); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if cmd.Runnable() {
|
||||
if _, err := fmt.Fprintf(w, "```\n%s\n```\n\n", cmd.UseLine()); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
if len(cmd.Example) > 0 {
|
||||
if _, err := fmt.Fprintf(w, "### Examples\n\n"); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := fmt.Fprintf(w, "```\n%s\n```\n\n", cmd.Example); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
if err := printOptions(w, cmd, name); err != nil {
|
||||
return err
|
||||
}
|
||||
if hasSeeAlso(cmd) {
|
||||
if _, err := fmt.Fprintf(w, "### SEE ALSO\n"); err != nil {
|
||||
return err
|
||||
}
|
||||
if cmd.HasParent() {
|
||||
parent := cmd.Parent()
|
||||
pname := parent.CommandPath()
|
||||
link := pname + ".md"
|
||||
link = strings.Replace(link, " ", "_", -1)
|
||||
if _, err := fmt.Fprintf(w, "* [%s](%s)\t - %s\n", pname, linkHandler(link), parent.Short); err != nil {
|
||||
return err
|
||||
}
|
||||
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.IsHelpCommand() {
|
||||
continue
|
||||
}
|
||||
cname := name + " " + child.Name()
|
||||
link := cname + ".md"
|
||||
link = strings.Replace(link, " ", "_", -1)
|
||||
if _, err := fmt.Fprintf(w, "* [%s](%s)\t - %s\n", cname, linkHandler(link), child.Short); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if _, err := fmt.Fprintf(w, "\n"); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if !cmd.DisableAutoGenTag {
|
||||
if _, err := fmt.Fprintf(w, "###### Auto generated by spf13/cobra on %s\n", time.Now().Format("2-Jan-2006")); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
|
||||
func GenMarkdownTreeCustom(cmd *cobra.Command, dir string, filePrepender, linkHandler func(string) string) error {
|
||||
for _, c := range cmd.Commands() {
|
||||
if !c.IsAvailableCommand() || c.IsHelpCommand() {
|
||||
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
|
||||
}
|
104
vendor/github.com/spf13/cobra/doc/md_docs.md
generated
vendored
104
vendor/github.com/spf13/cobra/doc/md_docs.md
generated
vendored
|
@ -1,104 +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 (
|
||||
"github.com/spf13/cobra"
|
||||
"github.com/spf13/cobra/doc"
|
||||
)
|
||||
|
||||
func main() {
|
||||
cmd := &cobra.Command{
|
||||
Use: "test",
|
||||
Short: "my test program",
|
||||
}
|
||||
doc.GenMarkdownTree(cmd, "/tmp")
|
||||
}
|
||||
```
|
||||
|
||||
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 (
|
||||
"io/ioutil"
|
||||
"os"
|
||||
|
||||
kubectlcmd "k8s.io/kubernetes/pkg/kubectl/cmd"
|
||||
cmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util"
|
||||
|
||||
"github.com/spf13/cobra/doc"
|
||||
)
|
||||
|
||||
func main() {
|
||||
cmd := kubectlcmd.NewKubectlCommand(cmdutil.NewFactory(nil), os.Stdin, ioutil.Discard, ioutil.Discard)
|
||||
doc.GenMarkdownTree(cmd, "./")
|
||||
}
|
||||
```
|
||||
|
||||
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)
|
||||
doc.GenMarkdown(cmd, out)
|
||||
```
|
||||
|
||||
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) + "/"
|
||||
}
|
||||
```
|
||||
|
88
vendor/github.com/spf13/cobra/doc/md_docs_test.go
generated
vendored
88
vendor/github.com/spf13/cobra/doc/md_docs_test.go
generated
vendored
|
@ -1,88 +0,0 @@
|
|||
package doc
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"os"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
var _ = fmt.Println
|
||||
var _ = os.Stderr
|
||||
|
||||
func TestGenMdDoc(t *testing.T) {
|
||||
c := initializeWithRootCmd()
|
||||
// Need two commands to run the command alphabetical sort
|
||||
cmdEcho.AddCommand(cmdTimes, cmdEchoSub, cmdDeprecated)
|
||||
c.AddCommand(cmdPrint, cmdEcho)
|
||||
cmdRootWithRun.PersistentFlags().StringVarP(&flags2a, "rootflag", "r", "two", strtwoParentHelp)
|
||||
|
||||
out := new(bytes.Buffer)
|
||||
|
||||
// We generate on s subcommand so we have both subcommands and parents
|
||||
if err := GenMarkdown(cmdEcho, out); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
found := out.String()
|
||||
|
||||
// Our description
|
||||
expected := cmdEcho.Long
|
||||
if !strings.Contains(found, expected) {
|
||||
t.Errorf("Unexpected response.\nExpecting to contain: \n %q\nGot:\n %q\n", expected, found)
|
||||
}
|
||||
|
||||
// Better have our example
|
||||
expected = cmdEcho.Example
|
||||
if !strings.Contains(found, expected) {
|
||||
t.Errorf("Unexpected response.\nExpecting to contain: \n %q\nGot:\n %q\n", expected, found)
|
||||
}
|
||||
|
||||
// A local flag
|
||||
expected = "boolone"
|
||||
if !strings.Contains(found, expected) {
|
||||
t.Errorf("Unexpected response.\nExpecting to contain: \n %q\nGot:\n %q\n", expected, found)
|
||||
}
|
||||
|
||||
// persistent flag on parent
|
||||
expected = "rootflag"
|
||||
if !strings.Contains(found, expected) {
|
||||
t.Errorf("Unexpected response.\nExpecting to contain: \n %q\nGot:\n %q\n", expected, found)
|
||||
}
|
||||
|
||||
// We better output info about our parent
|
||||
expected = cmdRootWithRun.Short
|
||||
if !strings.Contains(found, expected) {
|
||||
t.Errorf("Unexpected response.\nExpecting to contain: \n %q\nGot:\n %q\n", expected, found)
|
||||
}
|
||||
|
||||
// And about subcommands
|
||||
expected = cmdEchoSub.Short
|
||||
if !strings.Contains(found, expected) {
|
||||
t.Errorf("Unexpected response.\nExpecting to contain: \n %q\nGot:\n %q\n", expected, found)
|
||||
}
|
||||
|
||||
unexpected := cmdDeprecated.Short
|
||||
if strings.Contains(found, unexpected) {
|
||||
t.Errorf("Unexpected response.\nFound: %v\nBut should not have!!\n", unexpected)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGenMdNoTag(t *testing.T) {
|
||||
c := initializeWithRootCmd()
|
||||
// Need two commands to run the command alphabetical sort
|
||||
cmdEcho.AddCommand(cmdTimes, cmdEchoSub, cmdDeprecated)
|
||||
c.AddCommand(cmdPrint, cmdEcho)
|
||||
c.DisableAutoGenTag = true
|
||||
cmdRootWithRun.PersistentFlags().StringVarP(&flags2a, "rootflag", "r", "two", strtwoParentHelp)
|
||||
out := new(bytes.Buffer)
|
||||
|
||||
if err := GenMarkdown(c, out); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
found := out.String()
|
||||
|
||||
unexpected := "Auto generated"
|
||||
checkStringOmits(t, found, unexpected)
|
||||
|
||||
}
|
38
vendor/github.com/spf13/cobra/doc/util.go
generated
vendored
38
vendor/github.com/spf13/cobra/doc/util.go
generated
vendored
|
@ -1,38 +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 "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.IsHelpCommand() {
|
||||
continue
|
||||
}
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
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() }
|
33
vendor/github.com/spf13/jwalterweatherman/README.md
generated
vendored
33
vendor/github.com/spf13/jwalterweatherman/README.md
generated
vendored
|
@ -44,7 +44,7 @@ Available Loggers are:
|
|||
* FATAL
|
||||
|
||||
These each are loggers based on the log standard library and follow the
|
||||
standard usage. Eg..
|
||||
standard usage. Eg.
|
||||
|
||||
```go
|
||||
import (
|
||||
|
@ -79,6 +79,13 @@ standard usage. Eg..
|
|||
|
||||
```
|
||||
|
||||
NOTE: You can also use the library in a non-global setting by creating an instance of a Notebook:
|
||||
|
||||
```go
|
||||
notepad = jww.NewNotepad(jww.LevelInfo, jww.LevelTrace, os.Stdout, ioutil.Discard, "", log.Ldate|log.Ltime)
|
||||
notepad.WARN.Println("Some warning"")
|
||||
```
|
||||
|
||||
_Why 7 levels?_
|
||||
|
||||
Maybe you think that 7 levels are too much for any application... and you
|
||||
|
@ -118,35 +125,15 @@ verbosity.
|
|||
Note that JWW's own internal output uses log levels as well, so set the log
|
||||
level before making any other calls if you want to see what it's up to.
|
||||
|
||||
### Using a temp log file
|
||||
|
||||
JWW conveniently creates a temporary file and sets the log Handle to
|
||||
a io.Writer created for it. You should call this early in your application
|
||||
initialization routine as it will only log calls made after it is executed.
|
||||
When this option is used, the library will fmt.Println where to find the
|
||||
log file.
|
||||
|
||||
```go
|
||||
import (
|
||||
jww "github.com/spf13/jwalterweatherman"
|
||||
)
|
||||
|
||||
jww.UseTempLogFile("YourAppName")
|
||||
|
||||
```
|
||||
|
||||
### Setting a log file
|
||||
|
||||
JWW can log to any file you provide a path to (provided it’s writable).
|
||||
Will only append to this file.
|
||||
JWW can log to any `io.Writer`:
|
||||
|
||||
|
||||
```go
|
||||
import (
|
||||
jww "github.com/spf13/jwalterweatherman"
|
||||
)
|
||||
|
||||
jww.SetLogFile("/path/to/logfile")
|
||||
jww.SetLogOutput(customWriter)
|
||||
|
||||
```
|
||||
|
||||
|
|
113
vendor/github.com/spf13/jwalterweatherman/default_notepad.go
generated
vendored
Normal file
113
vendor/github.com/spf13/jwalterweatherman/default_notepad.go
generated
vendored
Normal file
|
@ -0,0 +1,113 @@
|
|||
// 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 (
|
||||
"io"
|
||||
"io/ioutil"
|
||||
"log"
|
||||
"os"
|
||||
)
|
||||
|
||||
var (
|
||||
TRACE *log.Logger
|
||||
DEBUG *log.Logger
|
||||
INFO *log.Logger
|
||||
WARN *log.Logger
|
||||
ERROR *log.Logger
|
||||
CRITICAL *log.Logger
|
||||
FATAL *log.Logger
|
||||
|
||||
LOG *log.Logger
|
||||
FEEDBACK *Feedback
|
||||
|
||||
defaultNotepad *Notepad
|
||||
)
|
||||
|
||||
func reloadDefaultNotepad() {
|
||||
TRACE = defaultNotepad.TRACE
|
||||
DEBUG = defaultNotepad.DEBUG
|
||||
INFO = defaultNotepad.INFO
|
||||
WARN = defaultNotepad.WARN
|
||||
ERROR = defaultNotepad.ERROR
|
||||
CRITICAL = defaultNotepad.CRITICAL
|
||||
FATAL = defaultNotepad.FATAL
|
||||
|
||||
LOG = defaultNotepad.LOG
|
||||
FEEDBACK = defaultNotepad.FEEDBACK
|
||||
}
|
||||
|
||||
func init() {
|
||||
defaultNotepad = NewNotepad(LevelError, LevelWarn, os.Stdout, ioutil.Discard, "", log.Ldate|log.Ltime)
|
||||
reloadDefaultNotepad()
|
||||
}
|
||||
|
||||
// SetLogThreshold set the log threshold for the default notepad. Trace by default.
|
||||
func SetLogThreshold(threshold Threshold) {
|
||||
defaultNotepad.SetLogThreshold(threshold)
|
||||
reloadDefaultNotepad()
|
||||
}
|
||||
|
||||
// SetLogOutput set the log output for the default notepad. Discarded by default.
|
||||
func SetLogOutput(handle io.Writer) {
|
||||
defaultNotepad.SetLogOutput(handle)
|
||||
reloadDefaultNotepad()
|
||||
}
|
||||
|
||||
// SetStdoutThreshold set the standard output threshold for the default notepad.
|
||||
// Info by default.
|
||||
func SetStdoutThreshold(threshold Threshold) {
|
||||
defaultNotepad.SetStdoutThreshold(threshold)
|
||||
reloadDefaultNotepad()
|
||||
}
|
||||
|
||||
// SetPrefix set the prefix for the default logger. Empty by default.
|
||||
func SetPrefix(prefix string) {
|
||||
defaultNotepad.SetPrefix(prefix)
|
||||
reloadDefaultNotepad()
|
||||
}
|
||||
|
||||
// SetFlags set the flags for the default logger. "log.Ldate | log.Ltime" by default.
|
||||
func SetFlags(flags int) {
|
||||
defaultNotepad.SetFlags(flags)
|
||||
reloadDefaultNotepad()
|
||||
}
|
||||
|
||||
// Level returns the current global log threshold.
|
||||
func LogThreshold() Threshold {
|
||||
return defaultNotepad.logThreshold
|
||||
}
|
||||
|
||||
// Level returns the current global output threshold.
|
||||
func StdoutThreshold() Threshold {
|
||||
return defaultNotepad.stdoutThreshold
|
||||
}
|
||||
|
||||
// GetStdoutThreshold returns the defined Treshold for the log logger.
|
||||
func GetLogThreshold() Threshold {
|
||||
return defaultNotepad.GetLogThreshold()
|
||||
}
|
||||
|
||||
// GetStdoutThreshold returns the Treshold for the stdout logger.
|
||||
func GetStdoutThreshold() Threshold {
|
||||
return defaultNotepad.GetStdoutThreshold()
|
||||
}
|
||||
|
||||
// LogCountForLevel returns the number of log invocations for a given threshold.
|
||||
func LogCountForLevel(l Threshold) uint64 {
|
||||
return defaultNotepad.LogCountForLevel(l)
|
||||
}
|
||||
|
||||
// LogCountForLevelsGreaterThanorEqualTo returns the number of log invocations
|
||||
// greater than or equal to a given threshold.
|
||||
func LogCountForLevelsGreaterThanorEqualTo(threshold Threshold) uint64 {
|
||||
return defaultNotepad.LogCountForLevelsGreaterThanorEqualTo(threshold)
|
||||
}
|
||||
|
||||
// ResetLogCounters resets the invocation counters for all levels.
|
||||
func ResetLogCounters() {
|
||||
defaultNotepad.ResetLogCounters()
|
||||
}
|
56
vendor/github.com/spf13/jwalterweatherman/jww_test.go
generated
vendored
56
vendor/github.com/spf13/jwalterweatherman/jww_test.go
generated
vendored
|
@ -1,56 +0,0 @@
|
|||
// Copyright © 2014 Steve Francia <spf@spf13.com>.
|
||||
//
|
||||
// Use of this source code is governed by an MIT-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
package jwalterweatherman
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestLevels(t *testing.T) {
|
||||
SetStdoutThreshold(LevelError)
|
||||
assert.Equal(t, StdoutThreshold(), LevelError)
|
||||
SetLogThreshold(LevelCritical)
|
||||
assert.Equal(t, LogThreshold(), LevelCritical)
|
||||
assert.NotEqual(t, StdoutThreshold(), LevelCritical)
|
||||
SetStdoutThreshold(LevelWarn)
|
||||
assert.Equal(t, StdoutThreshold(), LevelWarn)
|
||||
}
|
||||
|
||||
func TestDefaultLogging(t *testing.T) {
|
||||
outputBuf := new(bytes.Buffer)
|
||||
logBuf := new(bytes.Buffer)
|
||||
LogHandle = logBuf
|
||||
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")
|
||||
|
||||
assert.Contains(t, logBuf.String(), "fatal err")
|
||||
assert.Contains(t, logBuf.String(), "critical err")
|
||||
assert.Contains(t, logBuf.String(), "an error")
|
||||
assert.Contains(t, logBuf.String(), "a warning")
|
||||
assert.NotContains(t, logBuf.String(), "information")
|
||||
assert.NotContains(t, logBuf.String(), "debugging info")
|
||||
assert.NotContains(t, logBuf.String(), "trace")
|
||||
|
||||
assert.Contains(t, outputBuf.String(), "fatal err")
|
||||
assert.Contains(t, outputBuf.String(), "critical err")
|
||||
assert.Contains(t, outputBuf.String(), "an error")
|
||||
assert.NotContains(t, outputBuf.String(), "a warning")
|
||||
assert.NotContains(t, outputBuf.String(), "information")
|
||||
assert.NotContains(t, outputBuf.String(), "debugging info")
|
||||
assert.NotContains(t, outputBuf.String(), "trace")
|
||||
}
|
56
vendor/github.com/spf13/jwalterweatherman/log_counter.go
generated
vendored
Normal file
56
vendor/github.com/spf13/jwalterweatherman/log_counter.go
generated
vendored
Normal file
|
@ -0,0 +1,56 @@
|
|||
// 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 (
|
||||
"sync/atomic"
|
||||
)
|
||||
|
||||
type logCounter struct {
|
||||
counter uint64
|
||||
}
|
||||
|
||||
func (c *logCounter) incr() {
|
||||
atomic.AddUint64(&c.counter, 1)
|
||||
}
|
||||
|
||||
func (c *logCounter) resetCounter() {
|
||||
atomic.StoreUint64(&c.counter, 0)
|
||||
}
|
||||
|
||||
func (c *logCounter) getCount() uint64 {
|
||||
return atomic.LoadUint64(&c.counter)
|
||||
}
|
||||
|
||||
func (c *logCounter) Write(p []byte) (n int, err error) {
|
||||
c.incr()
|
||||
|
||||
return len(p), nil
|
||||
}
|
||||
|
||||
// LogCountForLevel returns the number of log invocations for a given threshold.
|
||||
func (n *Notepad) LogCountForLevel(l Threshold) uint64 {
|
||||
return n.logCounters[l].getCount()
|
||||
}
|
||||
|
||||
// LogCountForLevelsGreaterThanorEqualTo returns the number of log invocations
|
||||
// greater than or equal to a given threshold.
|
||||
func (n *Notepad) LogCountForLevelsGreaterThanorEqualTo(threshold Threshold) uint64 {
|
||||
var cnt uint64
|
||||
|
||||
for i := int(threshold); i < len(n.logCounters); i++ {
|
||||
cnt += n.LogCountForLevel(Threshold(i))
|
||||
}
|
||||
|
||||
return cnt
|
||||
}
|
||||
|
||||
// ResetLogCounters resets the invocation counters for all levels.
|
||||
func (n *Notepad) ResetLogCounters() {
|
||||
for _, np := range n.logCounters {
|
||||
np.resetCounter()
|
||||
}
|
||||
}
|
195
vendor/github.com/spf13/jwalterweatherman/notepad.go
generated
vendored
Normal file
195
vendor/github.com/spf13/jwalterweatherman/notepad.go
generated
vendored
Normal file
|
@ -0,0 +1,195 @@
|
|||
// 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 (
|
||||
"fmt"
|
||||
"io"
|
||||
"log"
|
||||
"os"
|
||||
)
|
||||
|
||||
type Threshold int
|
||||
|
||||
func (t Threshold) String() string {
|
||||
return prefixes[t]
|
||||
}
|
||||
|
||||
const (
|
||||
LevelTrace Threshold = iota
|
||||
LevelDebug
|
||||
LevelInfo
|
||||
LevelWarn
|
||||
LevelError
|
||||
LevelCritical
|
||||
LevelFatal
|
||||
)
|
||||
|
||||
var prefixes map[Threshold]string = map[Threshold]string{
|
||||
LevelTrace: "TRACE",
|
||||
LevelDebug: "DEBUG",
|
||||
LevelInfo: "INFO",
|
||||
LevelWarn: "WARN",
|
||||
LevelError: "ERROR",
|
||||
LevelCritical: "CRITICAL",
|
||||
LevelFatal: "FATAL",
|
||||
}
|
||||
|
||||
func prefix(t Threshold) string {
|
||||
return t.String() + " "
|
||||
}
|
||||
|
||||
// Notepad is where you leave a note !
|
||||
type Notepad struct {
|
||||
TRACE *log.Logger
|
||||
DEBUG *log.Logger
|
||||
INFO *log.Logger
|
||||
WARN *log.Logger
|
||||
ERROR *log.Logger
|
||||
CRITICAL *log.Logger
|
||||
FATAL *log.Logger
|
||||
|
||||
LOG *log.Logger
|
||||
FEEDBACK *Feedback
|
||||
|
||||
loggers []**log.Logger
|
||||
logHandle io.Writer
|
||||
outHandle io.Writer
|
||||
logThreshold Threshold
|
||||
stdoutThreshold Threshold
|
||||
prefix string
|
||||
flags int
|
||||
|
||||
// One per Threshold
|
||||
logCounters [7]*logCounter
|
||||
}
|
||||
|
||||
// NewNotepad create a new notepad.
|
||||
func NewNotepad(outThreshold Threshold, logThreshold Threshold, outHandle, logHandle io.Writer, prefix string, flags int) *Notepad {
|
||||
n := &Notepad{}
|
||||
|
||||
n.loggers = append(n.loggers, &n.TRACE, &n.DEBUG, &n.INFO, &n.WARN, &n.ERROR, &n.CRITICAL, &n.FATAL)
|
||||
n.logHandle = logHandle
|
||||
n.outHandle = outHandle
|
||||
n.logThreshold = logThreshold
|
||||
n.stdoutThreshold = outThreshold
|
||||
|
||||
if len(prefix) != 0 {
|
||||
n.prefix = "[" + prefix + "] "
|
||||
} else {
|
||||
n.prefix = ""
|
||||
}
|
||||
|
||||
n.flags = flags
|
||||
|
||||
n.LOG = log.New(n.logHandle,
|
||||
"LOG: ",
|
||||
n.flags)
|
||||
|
||||
n.FEEDBACK = &Feedback{n}
|
||||
|
||||
n.init()
|
||||
|
||||
return n
|
||||
}
|
||||
|
||||
// Feedback is special. It writes plainly to the output while
|
||||
// logging with the standard extra information (date, file, etc)
|
||||
// Only Println and Printf are currently provided for this
|
||||
type Feedback struct {
|
||||
*Notepad
|
||||
}
|
||||
|
||||
// init create the loggers for each level depending on the notepad thresholds
|
||||
func (n *Notepad) init() {
|
||||
bothHandle := io.MultiWriter(n.outHandle, n.logHandle)
|
||||
|
||||
for t, logger := range n.loggers {
|
||||
threshold := Threshold(t)
|
||||
counter := &logCounter{}
|
||||
n.logCounters[t] = counter
|
||||
|
||||
switch {
|
||||
case threshold >= n.logThreshold && threshold >= n.stdoutThreshold:
|
||||
*logger = log.New(io.MultiWriter(counter, bothHandle), n.prefix+prefix(threshold), n.flags)
|
||||
|
||||
case threshold >= n.logThreshold:
|
||||
*logger = log.New(io.MultiWriter(counter, n.logHandle), n.prefix+prefix(threshold), n.flags)
|
||||
|
||||
case threshold >= n.stdoutThreshold:
|
||||
*logger = log.New(io.MultiWriter(counter, os.Stdout), n.prefix+prefix(threshold), n.flags)
|
||||
|
||||
default:
|
||||
*logger = log.New(counter, n.prefix+prefix(threshold), n.flags)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// SetLogThreshold change the threshold above which messages are written to the
|
||||
// log file
|
||||
func (n *Notepad) SetLogThreshold(threshold Threshold) {
|
||||
n.logThreshold = threshold
|
||||
n.init()
|
||||
}
|
||||
|
||||
// SetLogOutput change the file where log messages are written
|
||||
func (n *Notepad) SetLogOutput(handle io.Writer) {
|
||||
n.logHandle = handle
|
||||
n.init()
|
||||
}
|
||||
|
||||
// GetStdoutThreshold returns the defined Treshold for the log logger.
|
||||
func (n *Notepad) GetLogThreshold() Threshold {
|
||||
return n.logThreshold
|
||||
}
|
||||
|
||||
// SetStdoutThreshold change the threshold above which messages are written to the
|
||||
// standard output
|
||||
func (n *Notepad) SetStdoutThreshold(threshold Threshold) {
|
||||
n.stdoutThreshold = threshold
|
||||
n.init()
|
||||
}
|
||||
|
||||
// GetStdoutThreshold returns the Treshold for the stdout logger.
|
||||
func (n *Notepad) GetStdoutThreshold() Threshold {
|
||||
return n.stdoutThreshold
|
||||
}
|
||||
|
||||
// SetPrefix change the prefix used by the notepad. Prefixes are displayed between
|
||||
// brackets at the begining of the line. An empty prefix won't be displayed at all.
|
||||
func (n *Notepad) SetPrefix(prefix string) {
|
||||
if len(prefix) != 0 {
|
||||
n.prefix = "[" + prefix + "] "
|
||||
} else {
|
||||
n.prefix = ""
|
||||
}
|
||||
n.init()
|
||||
}
|
||||
|
||||
// SetFlags choose which flags the logger will display (after prefix and message
|
||||
// level). See the package log for more informations on this.
|
||||
func (n *Notepad) SetFlags(flags int) {
|
||||
n.flags = flags
|
||||
n.init()
|
||||
}
|
||||
|
||||
// Feedback is special. It writes plainly to the output while
|
||||
// logging with the standard extra information (date, file, etc)
|
||||
// Only Println and Printf are currently provided for this
|
||||
func (fb *Feedback) Println(v ...interface{}) {
|
||||
s := fmt.Sprintln(v...)
|
||||
fmt.Print(s)
|
||||
fb.LOG.Output(2, s)
|
||||
}
|
||||
|
||||
// Feedback is special. It writes plainly to the output while
|
||||
// logging with the standard extra information (date, file, etc)
|
||||
// Only Println and Printf are currently provided for this
|
||||
func (fb *Feedback) Printf(format string, v ...interface{}) {
|
||||
s := fmt.Sprintf(format, v...)
|
||||
fmt.Print(s)
|
||||
fb.LOG.Output(2, s)
|
||||
}
|
198
vendor/github.com/spf13/jwalterweatherman/thatswhyyoualwaysleaveanote.go
generated
vendored
198
vendor/github.com/spf13/jwalterweatherman/thatswhyyoualwaysleaveanote.go
generated
vendored
|
@ -1,198 +0,0 @@
|
|||
// Copyright © 2014 Steve Francia <spf@spf13.com>.
|
||||
//
|
||||
// Use of this source code is governed by an MIT-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
package jwalterweatherman
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"io/ioutil"
|
||||
"log"
|
||||
"os"
|
||||
)
|
||||
|
||||
// Level describes the chosen log level between
|
||||
// debug and critical.
|
||||
type Level int
|
||||
|
||||
type NotePad struct {
|
||||
Handle io.Writer
|
||||
Level Level
|
||||
Prefix string
|
||||
Logger **log.Logger
|
||||
}
|
||||
|
||||
// Feedback is special. It writes plainly to the output while
|
||||
// logging with the standard extra information (date, file, etc)
|
||||
// Only Println and Printf are currently provided for this
|
||||
type Feedback struct{}
|
||||
|
||||
const (
|
||||
LevelTrace Level = iota
|
||||
LevelDebug
|
||||
LevelInfo
|
||||
LevelWarn
|
||||
LevelError
|
||||
LevelCritical
|
||||
LevelFatal
|
||||
DefaultLogThreshold = LevelWarn
|
||||
DefaultStdoutThreshold = LevelError
|
||||
)
|
||||
|
||||
var (
|
||||
TRACE *log.Logger
|
||||
DEBUG *log.Logger
|
||||
INFO *log.Logger
|
||||
WARN *log.Logger
|
||||
ERROR *log.Logger
|
||||
CRITICAL *log.Logger
|
||||
FATAL *log.Logger
|
||||
LOG *log.Logger
|
||||
FEEDBACK Feedback
|
||||
LogHandle io.Writer = ioutil.Discard
|
||||
OutHandle io.Writer = os.Stdout
|
||||
BothHandle io.Writer = io.MultiWriter(LogHandle, OutHandle)
|
||||
NotePads []*NotePad = []*NotePad{trace, debug, info, warn, err, critical, fatal}
|
||||
|
||||
trace *NotePad = &NotePad{Level: LevelTrace, Handle: os.Stdout, Logger: &TRACE, Prefix: "TRACE: "}
|
||||
debug *NotePad = &NotePad{Level: LevelDebug, Handle: os.Stdout, Logger: &DEBUG, Prefix: "DEBUG: "}
|
||||
info *NotePad = &NotePad{Level: LevelInfo, Handle: os.Stdout, Logger: &INFO, Prefix: "INFO: "}
|
||||
warn *NotePad = &NotePad{Level: LevelWarn, Handle: os.Stdout, Logger: &WARN, Prefix: "WARN: "}
|
||||
err *NotePad = &NotePad{Level: LevelError, Handle: os.Stdout, Logger: &ERROR, Prefix: "ERROR: "}
|
||||
critical *NotePad = &NotePad{Level: LevelCritical, Handle: os.Stdout, Logger: &CRITICAL, Prefix: "CRITICAL: "}
|
||||
fatal *NotePad = &NotePad{Level: LevelFatal, Handle: os.Stdout, Logger: &FATAL, Prefix: "FATAL: "}
|
||||
logThreshold Level = DefaultLogThreshold
|
||||
outputThreshold Level = DefaultStdoutThreshold
|
||||
|
||||
DATE = log.Ldate
|
||||
TIME = log.Ltime
|
||||
SFILE = log.Lshortfile
|
||||
LFILE = log.Llongfile
|
||||
MSEC = log.Lmicroseconds
|
||||
logFlags = DATE | TIME | SFILE
|
||||
)
|
||||
|
||||
func init() {
|
||||
SetStdoutThreshold(DefaultStdoutThreshold)
|
||||
}
|
||||
|
||||
// initialize will setup the jWalterWeatherman standard approach of providing the user
|
||||
// some feedback and logging a potentially different amount based on independent log and output thresholds.
|
||||
// By default the output has a lower threshold than logged
|
||||
// Don't use if you have manually set the Handles of the different levels as it will overwrite them.
|
||||
func initialize() {
|
||||
BothHandle = io.MultiWriter(LogHandle, OutHandle)
|
||||
|
||||
for _, n := range NotePads {
|
||||
if n.Level < outputThreshold && n.Level < logThreshold {
|
||||
n.Handle = ioutil.Discard
|
||||
} else if n.Level >= outputThreshold && n.Level >= logThreshold {
|
||||
n.Handle = BothHandle
|
||||
} else if n.Level >= outputThreshold && n.Level < logThreshold {
|
||||
n.Handle = OutHandle
|
||||
} else {
|
||||
n.Handle = LogHandle
|
||||
}
|
||||
}
|
||||
|
||||
for _, n := range NotePads {
|
||||
*n.Logger = log.New(n.Handle, n.Prefix, logFlags)
|
||||
}
|
||||
|
||||
LOG = log.New(LogHandle,
|
||||
"LOG: ",
|
||||
logFlags)
|
||||
}
|
||||
|
||||
// Set the log Flags (Available flag: DATE, TIME, SFILE, LFILE and MSEC)
|
||||
func SetLogFlag(flags int) {
|
||||
logFlags = flags
|
||||
}
|
||||
|
||||
// Level returns the current global log threshold.
|
||||
func LogThreshold() Level {
|
||||
return logThreshold
|
||||
}
|
||||
|
||||
// Level returns the current global output threshold.
|
||||
func StdoutThreshold() Level {
|
||||
return outputThreshold
|
||||
}
|
||||
|
||||
// Ensures that the level provided is within the bounds of available levels
|
||||
func levelCheck(level Level) Level {
|
||||
switch {
|
||||
case level <= LevelTrace:
|
||||
return LevelTrace
|
||||
case level >= LevelFatal:
|
||||
return LevelFatal
|
||||
default:
|
||||
return level
|
||||
}
|
||||
}
|
||||
|
||||
// Establishes a threshold where anything matching or above will be logged
|
||||
func SetLogThreshold(level Level) {
|
||||
logThreshold = levelCheck(level)
|
||||
initialize()
|
||||
}
|
||||
|
||||
// Establishes a threshold where anything matching or above will be output
|
||||
func SetStdoutThreshold(level Level) {
|
||||
outputThreshold = levelCheck(level)
|
||||
initialize()
|
||||
}
|
||||
|
||||
// Conveniently Sets the Log Handle to a io.writer created for the file behind the given filepath
|
||||
// Will only append to this file
|
||||
func SetLogFile(path string) {
|
||||
file, err := os.OpenFile(path, os.O_RDWR|os.O_APPEND|os.O_CREATE, 0666)
|
||||
if err != nil {
|
||||
CRITICAL.Println("Failed to open log file:", path, err)
|
||||
os.Exit(-1)
|
||||
}
|
||||
|
||||
INFO.Println("Logging to", file.Name())
|
||||
|
||||
LogHandle = file
|
||||
initialize()
|
||||
}
|
||||
|
||||
// Conveniently Creates a temporary file and sets the Log Handle to a io.writer created for it
|
||||
func UseTempLogFile(prefix string) {
|
||||
file, err := ioutil.TempFile(os.TempDir(), prefix)
|
||||
if err != nil {
|
||||
CRITICAL.Println(err)
|
||||
}
|
||||
|
||||
INFO.Println("Logging to", file.Name())
|
||||
|
||||
LogHandle = file
|
||||
initialize()
|
||||
}
|
||||
|
||||
// Disables logging for the entire JWW system
|
||||
func DiscardLogging() {
|
||||
LogHandle = ioutil.Discard
|
||||
initialize()
|
||||
}
|
||||
|
||||
// Feedback is special. It writes plainly to the output while
|
||||
// logging with the standard extra information (date, file, etc)
|
||||
// Only Println and Printf are currently provided for this
|
||||
func (fb *Feedback) Println(v ...interface{}) {
|
||||
s := fmt.Sprintln(v...)
|
||||
fmt.Print(s)
|
||||
LOG.Output(2, s)
|
||||
}
|
||||
|
||||
// Feedback is special. It writes plainly to the output while
|
||||
// logging with the standard extra information (date, file, etc)
|
||||
// Only Println and Printf are currently provided for this
|
||||
func (fb *Feedback) Printf(format string, v ...interface{}) {
|
||||
s := fmt.Sprintf(format, v...)
|
||||
fmt.Print(s)
|
||||
LOG.Output(2, s)
|
||||
}
|
33
vendor/github.com/spf13/pflag/README.md
generated
vendored
33
vendor/github.com/spf13/pflag/README.md
generated
vendored
|
@ -1,4 +1,6 @@
|
|||
[](https://travis-ci.org/spf13/pflag)
|
||||
[](https://goreportcard.com/report/github.com/spf13/pflag)
|
||||
[](https://godoc.org/github.com/spf13/pflag)
|
||||
|
||||
## Description
|
||||
|
||||
|
@ -85,7 +87,7 @@ fmt.Println("flagvar has value ", flagvar)
|
|||
```
|
||||
|
||||
There are helpers function to get values later if you have the FlagSet but
|
||||
it was difficult to keep up with all of the the flag pointers in your code.
|
||||
it was difficult to keep up with all of the flag pointers in your code.
|
||||
If you have a pflag.FlagSet with a flag called 'flagname' of type int you
|
||||
can use GetInt() to get the int value. But notice that 'flagname' must exist
|
||||
and it must be an int. GetString("flagname") will fail.
|
||||
|
@ -106,9 +108,9 @@ that give one-letter shorthands for flags. You can use these by appending
|
|||
var ip = flag.IntP("flagname", "f", 1234, "help message")
|
||||
var flagvar bool
|
||||
func init() {
|
||||
flag.BoolVarP("boolname", "b", true, "help message")
|
||||
flag.BoolVarP(&flagvar, "boolname", "b", true, "help message")
|
||||
}
|
||||
flag.VarP(&flagVar, "varname", "v", 1234, "help message")
|
||||
flag.VarP(&flagVal, "varname", "v", "help message")
|
||||
```
|
||||
|
||||
Shorthand letters can be used with single dashes on the command line.
|
||||
|
@ -244,13 +246,32 @@ It is possible to mark a flag as hidden, meaning it will still function as norma
|
|||
flags.MarkHidden("secretFlag")
|
||||
```
|
||||
|
||||
## Supporting Go flags when using pflag
|
||||
In order to support flags defined using Go's `flag` package, they must be added to the `pflag` flagset. This is usually necessary
|
||||
to support flags defined by third-party dependencies (e.g. `golang/glog`).
|
||||
|
||||
**Example**: You want to add the Go flags to the `CommandLine` flagset
|
||||
```go
|
||||
import (
|
||||
goflag "flag"
|
||||
flag "github.com/spf13/pflag"
|
||||
)
|
||||
|
||||
var ip *int = flag.Int("flagname", 1234, "help message for flagname")
|
||||
|
||||
func main() {
|
||||
flag.CommandLine.AddGoFlagSet(goflag.CommandLine)
|
||||
flag.Parse()
|
||||
}
|
||||
```
|
||||
|
||||
## More info
|
||||
|
||||
You can see the full reference documentation of the pflag package
|
||||
[at godoc.org][3], or through go's standard documentation system by
|
||||
running `godoc -http=:6060` and browsing to
|
||||
[http://localhost:6060/pkg/github.com/ogier/pflag][2] after
|
||||
[http://localhost:6060/pkg/github.com/spf13/pflag][2] after
|
||||
installation.
|
||||
|
||||
[2]: http://localhost:6060/pkg/github.com/ogier/pflag
|
||||
[3]: http://godoc.org/github.com/ogier/pflag
|
||||
[2]: http://localhost:6060/pkg/github.com/spf13/pflag
|
||||
[3]: http://godoc.org/github.com/spf13/pflag
|
||||
|
|
7
vendor/github.com/spf13/pflag/bool.go
generated
vendored
7
vendor/github.com/spf13/pflag/bool.go
generated
vendored
|
@ -1,9 +1,6 @@
|
|||
package pflag
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strconv"
|
||||
)
|
||||
import "strconv"
|
||||
|
||||
// optional interface to indicate boolean flags that can be
|
||||
// supplied without "=value" text
|
||||
|
@ -30,7 +27,7 @@ func (b *boolValue) Type() string {
|
|||
return "bool"
|
||||
}
|
||||
|
||||
func (b *boolValue) String() string { return fmt.Sprintf("%v", *b) }
|
||||
func (b *boolValue) String() string { return strconv.FormatBool(bool(*b)) }
|
||||
|
||||
func (b *boolValue) IsBoolFlag() bool { return true }
|
||||
|
||||
|
|
147
vendor/github.com/spf13/pflag/bool_slice.go
generated
vendored
Normal file
147
vendor/github.com/spf13/pflag/bool_slice.go
generated
vendored
Normal file
|
@ -0,0 +1,147 @@
|
|||
package pflag
|
||||
|
||||
import (
|
||||
"io"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// -- boolSlice Value
|
||||
type boolSliceValue struct {
|
||||
value *[]bool
|
||||
changed bool
|
||||
}
|
||||
|
||||
func newBoolSliceValue(val []bool, p *[]bool) *boolSliceValue {
|
||||
bsv := new(boolSliceValue)
|
||||
bsv.value = p
|
||||
*bsv.value = val
|
||||
return bsv
|
||||
}
|
||||
|
||||
// Set converts, and assigns, the comma-separated boolean argument string representation as the []bool value of this flag.
|
||||
// If Set is called on a flag that already has a []bool assigned, the newly converted values will be appended.
|
||||
func (s *boolSliceValue) Set(val string) error {
|
||||
|
||||
// remove all quote characters
|
||||
rmQuote := strings.NewReplacer(`"`, "", `'`, "", "`", "")
|
||||
|
||||
// read flag arguments with CSV parser
|
||||
boolStrSlice, err := readAsCSV(rmQuote.Replace(val))
|
||||
if err != nil && err != io.EOF {
|
||||
return err
|
||||
}
|
||||
|
||||
// parse boolean values into slice
|
||||
out := make([]bool, 0, len(boolStrSlice))
|
||||
for _, boolStr := range boolStrSlice {
|
||||
b, err := strconv.ParseBool(strings.TrimSpace(boolStr))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
out = append(out, b)
|
||||
}
|
||||
|
||||
if !s.changed {
|
||||
*s.value = out
|
||||
} else {
|
||||
*s.value = append(*s.value, out...)
|
||||
}
|
||||
|
||||
s.changed = true
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// Type returns a string that uniquely represents this flag's type.
|
||||
func (s *boolSliceValue) Type() string {
|
||||
return "boolSlice"
|
||||
}
|
||||
|
||||
// String defines a "native" format for this boolean slice flag value.
|
||||
func (s *boolSliceValue) String() string {
|
||||
|
||||
boolStrSlice := make([]string, len(*s.value))
|
||||
for i, b := range *s.value {
|
||||
boolStrSlice[i] = strconv.FormatBool(b)
|
||||
}
|
||||
|
||||
out, _ := writeAsCSV(boolStrSlice)
|
||||
|
||||
return "[" + out + "]"
|
||||
}
|
||||
|
||||
func boolSliceConv(val string) (interface{}, error) {
|
||||
val = strings.Trim(val, "[]")
|
||||
// Empty string would cause a slice with one (empty) entry
|
||||
if len(val) == 0 {
|
||||
return []bool{}, nil
|
||||
}
|
||||
ss := strings.Split(val, ",")
|
||||
out := make([]bool, len(ss))
|
||||
for i, t := range ss {
|
||||
var err error
|
||||
out[i], err = strconv.ParseBool(t)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// GetBoolSlice returns the []bool value of a flag with the given name.
|
||||
func (f *FlagSet) GetBoolSlice(name string) ([]bool, error) {
|
||||
val, err := f.getFlagType(name, "boolSlice", boolSliceConv)
|
||||
if err != nil {
|
||||
return []bool{}, err
|
||||
}
|
||||
return val.([]bool), nil
|
||||
}
|
||||
|
||||
// BoolSliceVar defines a boolSlice flag with specified name, default value, and usage string.
|
||||
// The argument p points to a []bool variable in which to store the value of the flag.
|
||||
func (f *FlagSet) BoolSliceVar(p *[]bool, name string, value []bool, usage string) {
|
||||
f.VarP(newBoolSliceValue(value, p), name, "", usage)
|
||||
}
|
||||
|
||||
// BoolSliceVarP is like BoolSliceVar, but accepts a shorthand letter that can be used after a single dash.
|
||||
func (f *FlagSet) BoolSliceVarP(p *[]bool, name, shorthand string, value []bool, usage string) {
|
||||
f.VarP(newBoolSliceValue(value, p), name, shorthand, usage)
|
||||
}
|
||||
|
||||
// BoolSliceVar defines a []bool flag with specified name, default value, and usage string.
|
||||
// The argument p points to a []bool variable in which to store the value of the flag.
|
||||
func BoolSliceVar(p *[]bool, name string, value []bool, usage string) {
|
||||
CommandLine.VarP(newBoolSliceValue(value, p), name, "", usage)
|
||||
}
|
||||
|
||||
// BoolSliceVarP is like BoolSliceVar, but accepts a shorthand letter that can be used after a single dash.
|
||||
func BoolSliceVarP(p *[]bool, name, shorthand string, value []bool, usage string) {
|
||||
CommandLine.VarP(newBoolSliceValue(value, p), name, shorthand, usage)
|
||||
}
|
||||
|
||||
// BoolSlice defines a []bool flag with specified name, default value, and usage string.
|
||||
// The return value is the address of a []bool variable that stores the value of the flag.
|
||||
func (f *FlagSet) BoolSlice(name string, value []bool, usage string) *[]bool {
|
||||
p := []bool{}
|
||||
f.BoolSliceVarP(&p, name, "", value, usage)
|
||||
return &p
|
||||
}
|
||||
|
||||
// BoolSliceP is like BoolSlice, but accepts a shorthand letter that can be used after a single dash.
|
||||
func (f *FlagSet) BoolSliceP(name, shorthand string, value []bool, usage string) *[]bool {
|
||||
p := []bool{}
|
||||
f.BoolSliceVarP(&p, name, shorthand, value, usage)
|
||||
return &p
|
||||
}
|
||||
|
||||
// BoolSlice defines a []bool flag with specified name, default value, and usage string.
|
||||
// The return value is the address of a []bool variable that stores the value of the flag.
|
||||
func BoolSlice(name string, value []bool, usage string) *[]bool {
|
||||
return CommandLine.BoolSliceP(name, "", value, usage)
|
||||
}
|
||||
|
||||
// BoolSliceP is like BoolSlice, but accepts a shorthand letter that can be used after a single dash.
|
||||
func BoolSliceP(name, shorthand string, value []bool, usage string) *[]bool {
|
||||
return CommandLine.BoolSliceP(name, shorthand, value, usage)
|
||||
}
|
180
vendor/github.com/spf13/pflag/bool_test.go
generated
vendored
180
vendor/github.com/spf13/pflag/bool_test.go
generated
vendored
|
@ -1,180 +0,0 @@
|
|||
// Copyright 2009 The Go Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
package pflag
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"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 fmt.Sprintf("%v", bool(*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=%s", b)
|
||||
}
|
||||
if *c != false {
|
||||
t.Errorf("expect c=false got c=%s", c)
|
||||
}
|
||||
}
|
7
vendor/github.com/spf13/pflag/count.go
generated
vendored
7
vendor/github.com/spf13/pflag/count.go
generated
vendored
|
@ -1,9 +1,6 @@
|
|||
package pflag
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strconv"
|
||||
)
|
||||
import "strconv"
|
||||
|
||||
// -- count Value
|
||||
type countValue int
|
||||
|
@ -28,7 +25,7 @@ func (i *countValue) Type() string {
|
|||
return "count"
|
||||
}
|
||||
|
||||
func (i *countValue) String() string { return fmt.Sprintf("%v", *i) }
|
||||
func (i *countValue) String() string { return strconv.Itoa(int(*i)) }
|
||||
|
||||
func countConv(sval string) (interface{}, error) {
|
||||
i, err := strconv.Atoi(sval)
|
||||
|
|
55
vendor/github.com/spf13/pflag/count_test.go
generated
vendored
55
vendor/github.com/spf13/pflag/count_test.go
generated
vendored
|
@ -1,55 +0,0 @@
|
|||
package pflag
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"testing"
|
||||
)
|
||||
|
||||
var _ = fmt.Printf
|
||||
|
||||
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{"-vvv"}, true, 3},
|
||||
{[]string{"-v", "-v", "-v"}, true, 3},
|
||||
{[]string{"-v", "--verbose", "-v"}, true, 3},
|
||||
{[]string{"-v=3", "-v"}, true, 4},
|
||||
{[]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 %q, got %q", tc.expected, c)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
77
vendor/github.com/spf13/pflag/example_test.go
generated
vendored
77
vendor/github.com/spf13/pflag/example_test.go
generated
vendored
|
@ -1,77 +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.
|
||||
|
||||
// These examples demonstrate more intricate uses of the flag package.
|
||||
package pflag_test
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
flag "github.com/spf13/pflag"
|
||||
)
|
||||
|
||||
// Example 1: A single string flag called "species" with default value "gopher".
|
||||
var species = flag.String("species", "gopher", "the species we are studying")
|
||||
|
||||
// Example 2: A flag with a shorthand letter.
|
||||
var gopherType = flag.StringP("gopher_type", "g", "pocket", "the variety of gopher")
|
||||
|
||||
// Example 3: A user-defined flag type, a slice of durations.
|
||||
type interval []time.Duration
|
||||
|
||||
// String is the method to format the flag's value, part of the flag.Value interface.
|
||||
// The String method's output will be used in diagnostics.
|
||||
func (i *interval) String() string {
|
||||
return fmt.Sprint(*i)
|
||||
}
|
||||
|
||||
func (i *interval) Type() string {
|
||||
return "interval"
|
||||
}
|
||||
|
||||
// Set is the method to set the flag value, part of the flag.Value interface.
|
||||
// Set's argument is a string to be parsed to set the flag.
|
||||
// It's a comma-separated list, so we split it.
|
||||
func (i *interval) Set(value string) error {
|
||||
// If we wanted to allow the flag to be set multiple times,
|
||||
// accumulating values, we would delete this if statement.
|
||||
// That would permit usages such as
|
||||
// -deltaT 10s -deltaT 15s
|
||||
// and other combinations.
|
||||
if len(*i) > 0 {
|
||||
return errors.New("interval flag already set")
|
||||
}
|
||||
for _, dt := range strings.Split(value, ",") {
|
||||
duration, err := time.ParseDuration(dt)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
*i = append(*i, duration)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Define a flag to accumulate durations. Because it has a special type,
|
||||
// we need to use the Var function and therefore create the flag during
|
||||
// init.
|
||||
|
||||
var intervalFlag interval
|
||||
|
||||
func init() {
|
||||
// Tie the command-line flag to the intervalFlag variable and
|
||||
// set a usage message.
|
||||
flag.Var(&intervalFlag, "deltaT", "comma-separated list of intervals to use between events")
|
||||
}
|
||||
|
||||
func Example() {
|
||||
// All the interesting pieces are with the variables declared above, but
|
||||
// to enable the flag package to see the flags defined there, one must
|
||||
// execute, typically at the start of main (not init!):
|
||||
// flag.Parse()
|
||||
// We don't run it here because this is not a main function and
|
||||
// the testing suite has already parsed the flags.
|
||||
}
|
29
vendor/github.com/spf13/pflag/export_test.go
generated
vendored
29
vendor/github.com/spf13/pflag/export_test.go
generated
vendored
|
@ -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
|
||||
}
|
291
vendor/github.com/spf13/pflag/flag.go
generated
vendored
291
vendor/github.com/spf13/pflag/flag.go
generated
vendored
|
@ -16,9 +16,9 @@ pflag is a drop-in replacement of Go's native flag package. If you import
|
|||
pflag under the name "flag" then all code should continue to function
|
||||
with no changes.
|
||||
|
||||
import flag "github.com/ogier/pflag"
|
||||
import flag "github.com/spf13/pflag"
|
||||
|
||||
There is one exception to this: if you directly instantiate the Flag struct
|
||||
There is one exception to this: if you directly instantiate the Flag struct
|
||||
there is one more field "Shorthand" that you will need to set.
|
||||
Most code never instantiates this struct directly, and instead uses
|
||||
functions such as String(), BoolVar(), and Var(), and is therefore
|
||||
|
@ -134,14 +134,19 @@ type FlagSet struct {
|
|||
// a custom error handler.
|
||||
Usage func()
|
||||
|
||||
// SortFlags is used to indicate, if user wants to have sorted flags in
|
||||
// help/usage messages.
|
||||
SortFlags bool
|
||||
|
||||
name string
|
||||
parsed bool
|
||||
actual map[NormalizedName]*Flag
|
||||
orderedActual []*Flag
|
||||
formal map[NormalizedName]*Flag
|
||||
orderedFormal []*Flag
|
||||
shorthands map[byte]*Flag
|
||||
args []string // arguments after flags
|
||||
argsLenAtDash int // len(args) when a '--' was located when parsing, or -1 if no --
|
||||
exitOnError bool // does the program exit if there's an error?
|
||||
errorHandling ErrorHandling
|
||||
output io.Writer // nil means stderr; use out() accessor
|
||||
interspersed bool // allow interspersed option/non-option args
|
||||
|
@ -156,7 +161,7 @@ type Flag struct {
|
|||
Value Value // value as set
|
||||
DefValue string // default value (as text); for usage message
|
||||
Changed bool // If the user set the value (or if left to default)
|
||||
NoOptDefVal string //default value (as text); if the flag is on the command line without any options
|
||||
NoOptDefVal string // default value (as text); if the flag is on the command line without any options
|
||||
Deprecated string // If this flag is deprecated, this string is the new or now thing to use
|
||||
Hidden bool // used by cobra.Command to allow flags to be hidden from help/usage text
|
||||
ShorthandDeprecated string // If the shorthand of this flag is deprecated, this string is the new or now thing to use
|
||||
|
@ -194,11 +199,12 @@ func sortFlags(flags map[NormalizedName]*Flag) []*Flag {
|
|||
// "--getUrl" which may also be translated to "geturl" and everything will work.
|
||||
func (f *FlagSet) SetNormalizeFunc(n func(f *FlagSet, name string) NormalizedName) {
|
||||
f.normalizeNameFunc = n
|
||||
for k, v := range f.formal {
|
||||
delete(f.formal, k)
|
||||
nname := f.normalizeFlagName(string(k))
|
||||
f.formal[nname] = v
|
||||
for k, v := range f.orderedFormal {
|
||||
delete(f.formal, NormalizedName(v.Name))
|
||||
nname := f.normalizeFlagName(v.Name)
|
||||
v.Name = string(nname)
|
||||
f.formal[nname] = v
|
||||
f.orderedFormal[k] = v
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -229,10 +235,18 @@ func (f *FlagSet) SetOutput(output io.Writer) {
|
|||
f.output = output
|
||||
}
|
||||
|
||||
// VisitAll visits the flags in lexicographical order, calling fn for each.
|
||||
// VisitAll visits the flags in lexicographical order or
|
||||
// in primordial order if f.SortFlags is false, calling fn for each.
|
||||
// It visits all flags, even those not set.
|
||||
func (f *FlagSet) VisitAll(fn func(*Flag)) {
|
||||
for _, flag := range sortFlags(f.formal) {
|
||||
var flags []*Flag
|
||||
if f.SortFlags {
|
||||
flags = sortFlags(f.formal)
|
||||
} else {
|
||||
flags = f.orderedFormal
|
||||
}
|
||||
|
||||
for _, flag := range flags {
|
||||
fn(flag)
|
||||
}
|
||||
}
|
||||
|
@ -242,22 +256,43 @@ func (f *FlagSet) HasFlags() bool {
|
|||
return len(f.formal) > 0
|
||||
}
|
||||
|
||||
// VisitAll visits the command-line flags in lexicographical order, calling
|
||||
// fn for each. It visits all flags, even those not set.
|
||||
// HasAvailableFlags returns a bool to indicate if the FlagSet has any flags
|
||||
// definied that are not hidden or deprecated.
|
||||
func (f *FlagSet) HasAvailableFlags() bool {
|
||||
for _, flag := range f.formal {
|
||||
if !flag.Hidden && len(flag.Deprecated) == 0 {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// VisitAll visits the command-line flags in lexicographical order or
|
||||
// in primordial order if f.SortFlags is false, calling fn for each.
|
||||
// It visits all flags, even those not set.
|
||||
func VisitAll(fn func(*Flag)) {
|
||||
CommandLine.VisitAll(fn)
|
||||
}
|
||||
|
||||
// Visit visits the flags in lexicographical order, calling fn for each.
|
||||
// Visit visits the flags in lexicographical order or
|
||||
// in primordial order if f.SortFlags is false, calling fn for each.
|
||||
// It visits only those flags that have been set.
|
||||
func (f *FlagSet) Visit(fn func(*Flag)) {
|
||||
for _, flag := range sortFlags(f.actual) {
|
||||
var flags []*Flag
|
||||
if f.SortFlags {
|
||||
flags = sortFlags(f.actual)
|
||||
} else {
|
||||
flags = f.orderedActual
|
||||
}
|
||||
|
||||
for _, flag := range flags {
|
||||
fn(flag)
|
||||
}
|
||||
}
|
||||
|
||||
// Visit visits the command-line flags in lexicographical order, calling fn
|
||||
// for each. It visits only those flags that have been set.
|
||||
// Visit visits the command-line flags in lexicographical order or
|
||||
// in primordial order if f.SortFlags is false, calling fn for each.
|
||||
// It visits only those flags that have been set.
|
||||
func Visit(fn func(*Flag)) {
|
||||
CommandLine.Visit(fn)
|
||||
}
|
||||
|
@ -362,6 +397,7 @@ func (f *FlagSet) Set(name, value string) error {
|
|||
f.actual = make(map[NormalizedName]*Flag)
|
||||
}
|
||||
f.actual[normalName] = flag
|
||||
f.orderedActual = append(f.orderedActual, flag)
|
||||
flag.Changed = true
|
||||
if len(flag.Deprecated) > 0 {
|
||||
fmt.Fprintf(os.Stderr, "Flag --%s has been deprecated, %s\n", flag.Name, flag.Deprecated)
|
||||
|
@ -405,23 +441,39 @@ func Set(name, value string) error {
|
|||
// otherwise, the default values of all defined flags in the set.
|
||||
func (f *FlagSet) PrintDefaults() {
|
||||
usages := f.FlagUsages()
|
||||
fmt.Fprintf(f.out(), "%s", usages)
|
||||
fmt.Fprint(f.out(), usages)
|
||||
}
|
||||
|
||||
// isZeroValue guesses whether the string represents the zero
|
||||
// value for a flag. It is not accurate but in practice works OK.
|
||||
func isZeroValue(value string) bool {
|
||||
switch value {
|
||||
case "false":
|
||||
return true
|
||||
case "<nil>":
|
||||
return true
|
||||
case "":
|
||||
return true
|
||||
case "0":
|
||||
return true
|
||||
// defaultIsZeroValue returns true if the default value for this flag represents
|
||||
// a zero value.
|
||||
func (f *Flag) defaultIsZeroValue() bool {
|
||||
switch f.Value.(type) {
|
||||
case boolFlag:
|
||||
return f.DefValue == "false"
|
||||
case *durationValue:
|
||||
// Beginning in Go 1.7, duration zero values are "0s"
|
||||
return f.DefValue == "0" || f.DefValue == "0s"
|
||||
case *intValue, *int8Value, *int32Value, *int64Value, *uintValue, *uint8Value, *uint16Value, *uint32Value, *uint64Value, *countValue, *float32Value, *float64Value:
|
||||
return f.DefValue == "0"
|
||||
case *stringValue:
|
||||
return f.DefValue == ""
|
||||
case *ipValue, *ipMaskValue, *ipNetValue:
|
||||
return f.DefValue == "<nil>"
|
||||
case *intSliceValue, *stringSliceValue, *stringArrayValue:
|
||||
return f.DefValue == "[]"
|
||||
default:
|
||||
switch f.Value.String() {
|
||||
case "false":
|
||||
return true
|
||||
case "<nil>":
|
||||
return true
|
||||
case "":
|
||||
return true
|
||||
case "0":
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// UnquoteUsage extracts a back-quoted name from the usage
|
||||
|
@ -444,28 +496,92 @@ func UnquoteUsage(flag *Flag) (name string, usage string) {
|
|||
break // Only one back quote; use type name.
|
||||
}
|
||||
}
|
||||
// No explicit name, so use type if we can find one.
|
||||
name = "value"
|
||||
switch flag.Value.(type) {
|
||||
case boolFlag:
|
||||
|
||||
name = flag.Value.Type()
|
||||
switch name {
|
||||
case "bool":
|
||||
name = ""
|
||||
case *durationValue:
|
||||
name = "duration"
|
||||
case *float64Value:
|
||||
case "float64":
|
||||
name = "float"
|
||||
case *intValue, *int64Value:
|
||||
case "int64":
|
||||
name = "int"
|
||||
case *stringValue:
|
||||
name = "string"
|
||||
case *uintValue, *uint64Value:
|
||||
case "uint64":
|
||||
name = "uint"
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
// FlagUsages Returns a string containing the usage information for all flags in
|
||||
// the FlagSet
|
||||
func (f *FlagSet) FlagUsages() string {
|
||||
// Splits the string `s` on whitespace into an initial substring up to
|
||||
// `i` runes in length and the remainder. Will go `slop` over `i` if
|
||||
// that encompasses the entire string (which allows the caller to
|
||||
// avoid short orphan words on the final line).
|
||||
func wrapN(i, slop int, s string) (string, string) {
|
||||
if i+slop > len(s) {
|
||||
return s, ""
|
||||
}
|
||||
|
||||
w := strings.LastIndexAny(s[:i], " \t")
|
||||
if w <= 0 {
|
||||
return s, ""
|
||||
}
|
||||
|
||||
return s[:w], s[w+1:]
|
||||
}
|
||||
|
||||
// Wraps the string `s` to a maximum width `w` with leading indent
|
||||
// `i`. The first line is not indented (this is assumed to be done by
|
||||
// caller). Pass `w` == 0 to do no wrapping
|
||||
func wrap(i, w int, s string) string {
|
||||
if w == 0 {
|
||||
return s
|
||||
}
|
||||
|
||||
// space between indent i and end of line width w into which
|
||||
// we should wrap the text.
|
||||
wrap := w - i
|
||||
|
||||
var r, l string
|
||||
|
||||
// Not enough space for sensible wrapping. Wrap as a block on
|
||||
// the next line instead.
|
||||
if wrap < 24 {
|
||||
i = 16
|
||||
wrap = w - i
|
||||
r += "\n" + strings.Repeat(" ", i)
|
||||
}
|
||||
// If still not enough space then don't even try to wrap.
|
||||
if wrap < 24 {
|
||||
return s
|
||||
}
|
||||
|
||||
// Try to avoid short orphan words on the final line, by
|
||||
// allowing wrapN to go a bit over if that would fit in the
|
||||
// remainder of the line.
|
||||
slop := 5
|
||||
wrap = wrap - slop
|
||||
|
||||
// Handle first line, which is indented by the caller (or the
|
||||
// special case above)
|
||||
l, s = wrapN(wrap, slop, s)
|
||||
r = r + l
|
||||
|
||||
// Now wrap the rest
|
||||
for s != "" {
|
||||
var t string
|
||||
|
||||
t, s = wrapN(wrap, slop, s)
|
||||
r = r + "\n" + strings.Repeat(" ", i) + t
|
||||
}
|
||||
|
||||
return r
|
||||
|
||||
}
|
||||
|
||||
// FlagUsagesWrapped returns a string containing the usage information
|
||||
// for all flags in the FlagSet. Wrapped to `cols` columns (0 for no
|
||||
// wrapping)
|
||||
func (f *FlagSet) FlagUsagesWrapped(cols int) string {
|
||||
x := new(bytes.Buffer)
|
||||
|
||||
lines := make([]string, 0, len(f.formal))
|
||||
|
@ -490,7 +606,7 @@ func (f *FlagSet) FlagUsages() string {
|
|||
if len(flag.NoOptDefVal) > 0 {
|
||||
switch flag.Value.Type() {
|
||||
case "string":
|
||||
line += fmt.Sprintf("[=%q]", flag.NoOptDefVal)
|
||||
line += fmt.Sprintf("[=\"%s\"]", flag.NoOptDefVal)
|
||||
case "bool":
|
||||
if flag.NoOptDefVal != "true" {
|
||||
line += fmt.Sprintf("[=%s]", flag.NoOptDefVal)
|
||||
|
@ -508,7 +624,7 @@ func (f *FlagSet) FlagUsages() string {
|
|||
}
|
||||
|
||||
line += usage
|
||||
if !isZeroValue(flag.DefValue) {
|
||||
if !flag.defaultIsZeroValue() {
|
||||
if flag.Value.Type() == "string" {
|
||||
line += fmt.Sprintf(" (default %q)", flag.DefValue)
|
||||
} else {
|
||||
|
@ -522,12 +638,19 @@ func (f *FlagSet) FlagUsages() string {
|
|||
for _, line := range lines {
|
||||
sidx := strings.Index(line, "\x00")
|
||||
spacing := strings.Repeat(" ", maxlen-sidx)
|
||||
fmt.Fprintln(x, line[:sidx], spacing, line[sidx+1:])
|
||||
// maxlen + 2 comes from + 1 for the \x00 and + 1 for the (deliberate) off-by-one in maxlen-sidx
|
||||
fmt.Fprintln(x, line[:sidx], spacing, wrap(maxlen+2, cols, line[sidx+1:]))
|
||||
}
|
||||
|
||||
return x.String()
|
||||
}
|
||||
|
||||
// FlagUsages returns a string containing the usage information for all flags in
|
||||
// the FlagSet
|
||||
func (f *FlagSet) FlagUsages() string {
|
||||
return f.FlagUsagesWrapped(0)
|
||||
}
|
||||
|
||||
// PrintDefaults prints to standard error the default values of all defined command-line flags.
|
||||
func PrintDefaults() {
|
||||
CommandLine.PrintDefaults()
|
||||
|
@ -611,7 +734,7 @@ func (f *FlagSet) VarPF(value Value, name, shorthand, usage string) *Flag {
|
|||
|
||||
// VarP is like Var, but accepts a shorthand letter that can be used after a single dash.
|
||||
func (f *FlagSet) VarP(value Value, name, shorthand, usage string) {
|
||||
_ = f.VarPF(value, name, shorthand, usage)
|
||||
f.VarPF(value, name, shorthand, usage)
|
||||
}
|
||||
|
||||
// AddFlag will add the flag to the FlagSet
|
||||
|
@ -631,6 +754,7 @@ func (f *FlagSet) AddFlag(flag *Flag) {
|
|||
|
||||
flag.Name = string(normalizedFlagName)
|
||||
f.formal[normalizedFlagName] = flag
|
||||
f.orderedFormal = append(f.orderedFormal, flag)
|
||||
|
||||
if len(flag.Shorthand) == 0 {
|
||||
return
|
||||
|
@ -709,6 +833,7 @@ func (f *FlagSet) setFlag(flag *Flag, value string, origArg string) error {
|
|||
f.actual = make(map[NormalizedName]*Flag)
|
||||
}
|
||||
f.actual[f.normalizeFlagName(flag.Name)] = flag
|
||||
f.orderedActual = append(f.orderedActual, flag)
|
||||
flag.Changed = true
|
||||
if len(flag.Deprecated) > 0 {
|
||||
fmt.Fprintf(os.Stderr, "Flag --%s has been deprecated, %s\n", flag.Name, flag.Deprecated)
|
||||
|
@ -728,7 +853,7 @@ func containsShorthand(arg, shorthand string) bool {
|
|||
return strings.Contains(arg, shorthand)
|
||||
}
|
||||
|
||||
func (f *FlagSet) parseLongArg(s string, args []string) (a []string, err error) {
|
||||
func (f *FlagSet) parseLongArg(s string, args []string, fn parseFunc) (a []string, err error) {
|
||||
a = args
|
||||
name := s[2:]
|
||||
if len(name) == 0 || name[0] == '-' || name[0] == '=' {
|
||||
|
@ -762,11 +887,14 @@ func (f *FlagSet) parseLongArg(s string, args []string) (a []string, err error)
|
|||
err = f.failf("flag needs an argument: %s", s)
|
||||
return
|
||||
}
|
||||
err = f.setFlag(flag, value, s)
|
||||
err = fn(flag, value, s)
|
||||
return
|
||||
}
|
||||
|
||||
func (f *FlagSet) parseSingleShortArg(shorthands string, args []string) (outShorts string, outArgs []string, err error) {
|
||||
func (f *FlagSet) parseSingleShortArg(shorthands string, args []string, fn parseFunc) (outShorts string, outArgs []string, err error) {
|
||||
if strings.HasPrefix(shorthands, "test.") {
|
||||
return
|
||||
}
|
||||
outArgs = args
|
||||
outShorts = shorthands[1:]
|
||||
c := shorthands[0]
|
||||
|
@ -798,16 +926,16 @@ func (f *FlagSet) parseSingleShortArg(shorthands string, args []string) (outShor
|
|||
err = f.failf("flag needs an argument: %q in -%s", c, shorthands)
|
||||
return
|
||||
}
|
||||
err = f.setFlag(flag, value, shorthands)
|
||||
err = fn(flag, value, shorthands)
|
||||
return
|
||||
}
|
||||
|
||||
func (f *FlagSet) parseShortArg(s string, args []string) (a []string, err error) {
|
||||
func (f *FlagSet) parseShortArg(s string, args []string, fn parseFunc) (a []string, err error) {
|
||||
a = args
|
||||
shorthands := s[1:]
|
||||
|
||||
for len(shorthands) > 0 {
|
||||
shorthands, a, err = f.parseSingleShortArg(shorthands, args)
|
||||
shorthands, a, err = f.parseSingleShortArg(shorthands, args, fn)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
@ -816,7 +944,7 @@ func (f *FlagSet) parseShortArg(s string, args []string) (a []string, err error)
|
|||
return
|
||||
}
|
||||
|
||||
func (f *FlagSet) parseArgs(args []string) (err error) {
|
||||
func (f *FlagSet) parseArgs(args []string, fn parseFunc) (err error) {
|
||||
for len(args) > 0 {
|
||||
s := args[0]
|
||||
args = args[1:]
|
||||
|
@ -836,9 +964,9 @@ func (f *FlagSet) parseArgs(args []string) (err error) {
|
|||
f.args = append(f.args, args...)
|
||||
break
|
||||
}
|
||||
args, err = f.parseLongArg(s, args)
|
||||
args, err = f.parseLongArg(s, args, fn)
|
||||
} else {
|
||||
args, err = f.parseShortArg(s, args)
|
||||
args, err = f.parseShortArg(s, args, fn)
|
||||
}
|
||||
if err != nil {
|
||||
return
|
||||
|
@ -854,7 +982,41 @@ func (f *FlagSet) parseArgs(args []string) (err error) {
|
|||
func (f *FlagSet) Parse(arguments []string) error {
|
||||
f.parsed = true
|
||||
f.args = make([]string, 0, len(arguments))
|
||||
err := f.parseArgs(arguments)
|
||||
|
||||
assign := func(flag *Flag, value, origArg string) error {
|
||||
return f.setFlag(flag, value, origArg)
|
||||
}
|
||||
|
||||
err := f.parseArgs(arguments, assign)
|
||||
if err != nil {
|
||||
switch f.errorHandling {
|
||||
case ContinueOnError:
|
||||
return err
|
||||
case ExitOnError:
|
||||
os.Exit(2)
|
||||
case PanicOnError:
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
type parseFunc func(flag *Flag, value, origArg string) error
|
||||
|
||||
// ParseAll parses flag definitions from the argument list, which should not
|
||||
// include the command name. The arguments for fn are flag and value. Must be
|
||||
// called after all flags in the FlagSet 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) ParseAll(arguments []string, fn func(flag *Flag, value string) error) error {
|
||||
f.parsed = true
|
||||
f.args = make([]string, 0, len(arguments))
|
||||
|
||||
assign := func(flag *Flag, value, origArg string) error {
|
||||
return fn(flag, value)
|
||||
}
|
||||
|
||||
err := f.parseArgs(arguments, assign)
|
||||
if err != nil {
|
||||
switch f.errorHandling {
|
||||
case ContinueOnError:
|
||||
|
@ -880,6 +1042,14 @@ func Parse() {
|
|||
CommandLine.Parse(os.Args[1:])
|
||||
}
|
||||
|
||||
// ParseAll parses the command-line flags from os.Args[1:] and called fn for each.
|
||||
// The arguments for fn are flag and value. Must be called after all flags are
|
||||
// defined and before flags are accessed by the program.
|
||||
func ParseAll(fn func(flag *Flag, value string) error) {
|
||||
// Ignore errors; CommandLine is set for ExitOnError.
|
||||
CommandLine.ParseAll(os.Args[1:], fn)
|
||||
}
|
||||
|
||||
// SetInterspersed sets whether to support interspersed option/non-option arguments.
|
||||
func SetInterspersed(interspersed bool) {
|
||||
CommandLine.SetInterspersed(interspersed)
|
||||
|
@ -893,14 +1063,15 @@ func Parsed() bool {
|
|||
// CommandLine is the default set of command-line flags, parsed from os.Args.
|
||||
var CommandLine = NewFlagSet(os.Args[0], ExitOnError)
|
||||
|
||||
// NewFlagSet returns a new, empty flag set with the specified name and
|
||||
// error handling property.
|
||||
// NewFlagSet returns a new, empty flag set with the specified name,
|
||||
// error handling property and SortFlags set to true.
|
||||
func NewFlagSet(name string, errorHandling ErrorHandling) *FlagSet {
|
||||
f := &FlagSet{
|
||||
name: name,
|
||||
errorHandling: errorHandling,
|
||||
argsLenAtDash: -1,
|
||||
interspersed: true,
|
||||
SortFlags: true,
|
||||
}
|
||||
return f
|
||||
}
|
||||
|
|
913
vendor/github.com/spf13/pflag/flag_test.go
generated
vendored
913
vendor/github.com/spf13/pflag/flag_test.go
generated
vendored
|
@ -1,913 +0,0 @@
|
|||
// Copyright 2009 The Go Authors. All rights reserved.
|
||||
// Use of this source code is governed by a BSD-style
|
||||
// license that can be found in the LICENSE file.
|
||||
|
||||
package pflag
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"io"
|
||||
"io/ioutil"
|
||||
"net"
|
||||
"os"
|
||||
"reflect"
|
||||
"sort"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
var (
|
||||
testBool = Bool("test_bool", false, "bool value")
|
||||
testInt = Int("test_int", 0, "int value")
|
||||
testInt64 = Int64("test_int64", 0, "int64 value")
|
||||
testUint = Uint("test_uint", 0, "uint value")
|
||||
testUint64 = Uint64("test_uint64", 0, "uint64 value")
|
||||
testString = String("test_string", "0", "string value")
|
||||
testFloat = Float64("test_float64", 0, "float64 value")
|
||||
testDuration = Duration("test_duration", 0, "time.Duration value")
|
||||
testOptionalInt = Int("test_optional_int", 0, "optional int value")
|
||||
normalizeFlagNameInvocations = 0
|
||||
)
|
||||
|
||||
func boolString(s string) string {
|
||||
if s == "0" {
|
||||
return "false"
|
||||
}
|
||||
return "true"
|
||||
}
|
||||
|
||||
func TestEverything(t *testing.T) {
|
||||
m := make(map[string]*Flag)
|
||||
desired := "0"
|
||||
visitor := func(f *Flag) {
|
||||
if len(f.Name) > 5 && f.Name[0:5] == "test_" {
|
||||
m[f.Name] = f
|
||||
ok := false
|
||||
switch {
|
||||
case f.Value.String() == desired:
|
||||
ok = true
|
||||
case f.Name == "test_bool" && f.Value.String() == boolString(desired):
|
||||
ok = true
|
||||
case f.Name == "test_duration" && f.Value.String() == desired+"s":
|
||||
ok = true
|
||||
}
|
||||
if !ok {
|
||||
t.Error("Visit: bad value", f.Value.String(), "for", f.Name)
|
||||
}
|
||||
}
|
||||
}
|
||||
VisitAll(visitor)
|
||||
if len(m) != 9 {
|
||||
t.Error("VisitAll misses some flags")
|
||||
for k, v := range m {
|
||||
t.Log(k, *v)
|
||||
}
|
||||
}
|
||||
m = make(map[string]*Flag)
|
||||
Visit(visitor)
|
||||
if len(m) != 0 {
|
||||
t.Errorf("Visit sees unset flags")
|
||||
for k, v := range m {
|
||||
t.Log(k, *v)
|
||||
}
|
||||
}
|
||||
// Now set all flags
|
||||
Set("test_bool", "true")
|
||||
Set("test_int", "1")
|
||||
Set("test_int64", "1")
|
||||
Set("test_uint", "1")
|
||||
Set("test_uint64", "1")
|
||||
Set("test_string", "1")
|
||||
Set("test_float64", "1")
|
||||
Set("test_duration", "1s")
|
||||
Set("test_optional_int", "1")
|
||||
desired = "1"
|
||||
Visit(visitor)
|
||||
if len(m) != 9 {
|
||||
t.Error("Visit fails after set")
|
||||
for k, v := range m {
|
||||
t.Log(k, *v)
|
||||
}
|
||||
}
|
||||
// Now test they're visited in sort order.
|
||||
var flagNames []string
|
||||
Visit(func(f *Flag) { flagNames = append(flagNames, f.Name) })
|
||||
if !sort.StringsAreSorted(flagNames) {
|
||||
t.Errorf("flag names not sorted: %v", flagNames)
|
||||
}
|
||||
}
|
||||
|
||||
func TestUsage(t *testing.T) {
|
||||
called := false
|
||||
ResetForTesting(func() { called = true })
|
||||
if GetCommandLine().Parse([]string{"--x"}) == nil {
|
||||
t.Error("parse did not fail for unknown flag")
|
||||
}
|
||||
if !called {
|
||||
t.Error("did not call Usage for unknown flag")
|
||||
}
|
||||
}
|
||||
|
||||
func TestAddFlagSet(t *testing.T) {
|
||||
oldSet := NewFlagSet("old", ContinueOnError)
|
||||
newSet := NewFlagSet("new", ContinueOnError)
|
||||
|
||||
oldSet.String("flag1", "flag1", "flag1")
|
||||
oldSet.String("flag2", "flag2", "flag2")
|
||||
|
||||
newSet.String("flag2", "flag2", "flag2")
|
||||
newSet.String("flag3", "flag3", "flag3")
|
||||
|
||||
oldSet.AddFlagSet(newSet)
|
||||
|
||||
if len(oldSet.formal) != 3 {
|
||||
t.Errorf("Unexpected result adding a FlagSet to a FlagSet %v", oldSet)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAnnotation(t *testing.T) {
|
||||
f := NewFlagSet("shorthand", ContinueOnError)
|
||||
|
||||
if err := f.SetAnnotation("missing-flag", "key", nil); err == nil {
|
||||
t.Errorf("Expected error setting annotation on non-existent flag")
|
||||
}
|
||||
|
||||
f.StringP("stringa", "a", "", "string value")
|
||||
if err := f.SetAnnotation("stringa", "key", nil); err != nil {
|
||||
t.Errorf("Unexpected error setting new nil annotation: %v", err)
|
||||
}
|
||||
if annotation := f.Lookup("stringa").Annotations["key"]; annotation != nil {
|
||||
t.Errorf("Unexpected annotation: %v", annotation)
|
||||
}
|
||||
|
||||
f.StringP("stringb", "b", "", "string2 value")
|
||||
if err := f.SetAnnotation("stringb", "key", []string{"value1"}); err != nil {
|
||||
t.Errorf("Unexpected error setting new annotation: %v", err)
|
||||
}
|
||||
if annotation := f.Lookup("stringb").Annotations["key"]; !reflect.DeepEqual(annotation, []string{"value1"}) {
|
||||
t.Errorf("Unexpected annotation: %v", annotation)
|
||||
}
|
||||
|
||||
if err := f.SetAnnotation("stringb", "key", []string{"value2"}); err != nil {
|
||||
t.Errorf("Unexpected error updating annotation: %v", err)
|
||||
}
|
||||
if annotation := f.Lookup("stringb").Annotations["key"]; !reflect.DeepEqual(annotation, []string{"value2"}) {
|
||||
t.Errorf("Unexpected annotation: %v", annotation)
|
||||
}
|
||||
}
|
||||
|
||||
func testParse(f *FlagSet, t *testing.T) {
|
||||
if f.Parsed() {
|
||||
t.Error("f.Parse() = true before Parse")
|
||||
}
|
||||
boolFlag := f.Bool("bool", false, "bool value")
|
||||
bool2Flag := f.Bool("bool2", false, "bool2 value")
|
||||
bool3Flag := f.Bool("bool3", false, "bool3 value")
|
||||
intFlag := f.Int("int", 0, "int value")
|
||||
int8Flag := f.Int8("int8", 0, "int value")
|
||||
int32Flag := f.Int32("int32", 0, "int value")
|
||||
int64Flag := f.Int64("int64", 0, "int64 value")
|
||||
uintFlag := f.Uint("uint", 0, "uint value")
|
||||
uint8Flag := f.Uint8("uint8", 0, "uint value")
|
||||
uint16Flag := f.Uint16("uint16", 0, "uint value")
|
||||
uint32Flag := f.Uint32("uint32", 0, "uint value")
|
||||
uint64Flag := f.Uint64("uint64", 0, "uint64 value")
|
||||
stringFlag := f.String("string", "0", "string value")
|
||||
float32Flag := f.Float32("float32", 0, "float32 value")
|
||||
float64Flag := f.Float64("float64", 0, "float64 value")
|
||||
ipFlag := f.IP("ip", net.ParseIP("127.0.0.1"), "ip value")
|
||||
maskFlag := f.IPMask("mask", ParseIPv4Mask("0.0.0.0"), "mask value")
|
||||
durationFlag := f.Duration("duration", 5*time.Second, "time.Duration value")
|
||||
optionalIntNoValueFlag := f.Int("optional-int-no-value", 0, "int value")
|
||||
f.Lookup("optional-int-no-value").NoOptDefVal = "9"
|
||||
optionalIntWithValueFlag := f.Int("optional-int-with-value", 0, "int value")
|
||||
f.Lookup("optional-int-no-value").NoOptDefVal = "9"
|
||||
extra := "one-extra-argument"
|
||||
args := []string{
|
||||
"--bool",
|
||||
"--bool2=true",
|
||||
"--bool3=false",
|
||||
"--int=22",
|
||||
"--int8=-8",
|
||||
"--int32=-32",
|
||||
"--int64=0x23",
|
||||
"--uint", "24",
|
||||
"--uint8=8",
|
||||
"--uint16=16",
|
||||
"--uint32=32",
|
||||
"--uint64=25",
|
||||
"--string=hello",
|
||||
"--float32=-172e12",
|
||||
"--float64=2718e28",
|
||||
"--ip=10.11.12.13",
|
||||
"--mask=255.255.255.0",
|
||||
"--duration=2m",
|
||||
"--optional-int-no-value",
|
||||
"--optional-int-with-value=42",
|
||||
extra,
|
||||
}
|
||||
if err := f.Parse(args); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !f.Parsed() {
|
||||
t.Error("f.Parse() = false after Parse")
|
||||
}
|
||||
if *boolFlag != true {
|
||||
t.Error("bool flag should be true, is ", *boolFlag)
|
||||
}
|
||||
if v, err := f.GetBool("bool"); err != nil || v != *boolFlag {
|
||||
t.Error("GetBool does not work.")
|
||||
}
|
||||
if *bool2Flag != true {
|
||||
t.Error("bool2 flag should be true, is ", *bool2Flag)
|
||||
}
|
||||
if *bool3Flag != false {
|
||||
t.Error("bool3 flag should be false, is ", *bool2Flag)
|
||||
}
|
||||
if *intFlag != 22 {
|
||||
t.Error("int flag should be 22, is ", *intFlag)
|
||||
}
|
||||
if v, err := f.GetInt("int"); err != nil || v != *intFlag {
|
||||
t.Error("GetInt does not work.")
|
||||
}
|
||||
if *int8Flag != -8 {
|
||||
t.Error("int8 flag should be 0x23, is ", *int8Flag)
|
||||
}
|
||||
if v, err := f.GetInt8("int8"); err != nil || v != *int8Flag {
|
||||
t.Error("GetInt8 does not work.")
|
||||
}
|
||||
if *int32Flag != -32 {
|
||||
t.Error("int32 flag should be 0x23, is ", *int32Flag)
|
||||
}
|
||||
if v, err := f.GetInt32("int32"); err != nil || v != *int32Flag {
|
||||
t.Error("GetInt32 does not work.")
|
||||
}
|
||||
if *int64Flag != 0x23 {
|
||||
t.Error("int64 flag should be 0x23, is ", *int64Flag)
|
||||
}
|
||||
if v, err := f.GetInt64("int64"); err != nil || v != *int64Flag {
|
||||
t.Error("GetInt64 does not work.")
|
||||
}
|
||||
if *uintFlag != 24 {
|
||||
t.Error("uint flag should be 24, is ", *uintFlag)
|
||||
}
|
||||
if v, err := f.GetUint("uint"); err != nil || v != *uintFlag {
|
||||
t.Error("GetUint does not work.")
|
||||
}
|
||||
if *uint8Flag != 8 {
|
||||
t.Error("uint8 flag should be 8, is ", *uint8Flag)
|
||||
}
|
||||
if v, err := f.GetUint8("uint8"); err != nil || v != *uint8Flag {
|
||||
t.Error("GetUint8 does not work.")
|
||||
}
|
||||
if *uint16Flag != 16 {
|
||||
t.Error("uint16 flag should be 16, is ", *uint16Flag)
|
||||
}
|
||||
if v, err := f.GetUint16("uint16"); err != nil || v != *uint16Flag {
|
||||
t.Error("GetUint16 does not work.")
|
||||
}
|
||||
if *uint32Flag != 32 {
|
||||
t.Error("uint32 flag should be 32, is ", *uint32Flag)
|
||||
}
|
||||
if v, err := f.GetUint32("uint32"); err != nil || v != *uint32Flag {
|
||||
t.Error("GetUint32 does not work.")
|
||||
}
|
||||
if *uint64Flag != 25 {
|
||||
t.Error("uint64 flag should be 25, is ", *uint64Flag)
|
||||
}
|
||||
if v, err := f.GetUint64("uint64"); err != nil || v != *uint64Flag {
|
||||
t.Error("GetUint64 does not work.")
|
||||
}
|
||||
if *stringFlag != "hello" {
|
||||
t.Error("string flag should be `hello`, is ", *stringFlag)
|
||||
}
|
||||
if v, err := f.GetString("string"); err != nil || v != *stringFlag {
|
||||
t.Error("GetString does not work.")
|
||||
}
|
||||
if *float32Flag != -172e12 {
|
||||
t.Error("float32 flag should be -172e12, is ", *float32Flag)
|
||||
}
|
||||
if v, err := f.GetFloat32("float32"); err != nil || v != *float32Flag {
|
||||
t.Errorf("GetFloat32 returned %v but float32Flag was %v", v, *float32Flag)
|
||||
}
|
||||
if *float64Flag != 2718e28 {
|
||||
t.Error("float64 flag should be 2718e28, is ", *float64Flag)
|
||||
}
|
||||
if v, err := f.GetFloat64("float64"); err != nil || v != *float64Flag {
|
||||
t.Errorf("GetFloat64 returned %v but float64Flag was %v", v, *float64Flag)
|
||||
}
|
||||
if !(*ipFlag).Equal(net.ParseIP("10.11.12.13")) {
|
||||
t.Error("ip flag should be 10.11.12.13, is ", *ipFlag)
|
||||
}
|
||||
if v, err := f.GetIP("ip"); err != nil || !v.Equal(*ipFlag) {
|
||||
t.Errorf("GetIP returned %v but ipFlag was %v", v, *ipFlag)
|
||||
}
|
||||
if (*maskFlag).String() != ParseIPv4Mask("255.255.255.0").String() {
|
||||
t.Error("mask flag should be 255.255.255.0, is ", (*maskFlag).String())
|
||||
}
|
||||
if v, err := f.GetIPv4Mask("mask"); err != nil || v.String() != (*maskFlag).String() {
|
||||
t.Errorf("GetIP returned %v maskFlag was %v error was %v", v, *maskFlag, err)
|
||||
}
|
||||
if *durationFlag != 2*time.Minute {
|
||||
t.Error("duration flag should be 2m, is ", *durationFlag)
|
||||
}
|
||||
if v, err := f.GetDuration("duration"); err != nil || v != *durationFlag {
|
||||
t.Error("GetDuration does not work.")
|
||||
}
|
||||
if _, err := f.GetInt("duration"); err == nil {
|
||||
t.Error("GetInt parsed a time.Duration?!?!")
|
||||
}
|
||||
if *optionalIntNoValueFlag != 9 {
|
||||
t.Error("optional int flag should be the default value, is ", *optionalIntNoValueFlag)
|
||||
}
|
||||
if *optionalIntWithValueFlag != 42 {
|
||||
t.Error("optional int flag should be 42, is ", *optionalIntWithValueFlag)
|
||||
}
|
||||
if len(f.Args()) != 1 {
|
||||
t.Error("expected one argument, got", len(f.Args()))
|
||||
} else if f.Args()[0] != extra {
|
||||
t.Errorf("expected argument %q got %q", extra, f.Args()[0])
|
||||
}
|
||||
}
|
||||
|
||||
func TestShorthand(t *testing.T) {
|
||||
f := NewFlagSet("shorthand", ContinueOnError)
|
||||
if f.Parsed() {
|
||||
t.Error("f.Parse() = true before Parse")
|
||||
}
|
||||
boolaFlag := f.BoolP("boola", "a", false, "bool value")
|
||||
boolbFlag := f.BoolP("boolb", "b", false, "bool2 value")
|
||||
boolcFlag := f.BoolP("boolc", "c", false, "bool3 value")
|
||||
booldFlag := f.BoolP("boold", "d", false, "bool4 value")
|
||||
stringaFlag := f.StringP("stringa", "s", "0", "string value")
|
||||
stringzFlag := f.StringP("stringz", "z", "0", "string value")
|
||||
extra := "interspersed-argument"
|
||||
notaflag := "--i-look-like-a-flag"
|
||||
args := []string{
|
||||
"-ab",
|
||||
extra,
|
||||
"-cs",
|
||||
"hello",
|
||||
"-z=something",
|
||||
"-d=true",
|
||||
"--",
|
||||
notaflag,
|
||||
}
|
||||
f.SetOutput(ioutil.Discard)
|
||||
if err := f.Parse(args); err != nil {
|
||||
t.Error("expected no error, got ", err)
|
||||
}
|
||||
if !f.Parsed() {
|
||||
t.Error("f.Parse() = false after Parse")
|
||||
}
|
||||
if *boolaFlag != true {
|
||||
t.Error("boola flag should be true, is ", *boolaFlag)
|
||||
}
|
||||
if *boolbFlag != true {
|
||||
t.Error("boolb flag should be true, is ", *boolbFlag)
|
||||
}
|
||||
if *boolcFlag != true {
|
||||
t.Error("boolc flag should be true, is ", *boolcFlag)
|
||||
}
|
||||
if *booldFlag != true {
|
||||
t.Error("boold flag should be true, is ", *booldFlag)
|
||||
}
|
||||
if *stringaFlag != "hello" {
|
||||
t.Error("stringa flag should be `hello`, is ", *stringaFlag)
|
||||
}
|
||||
if *stringzFlag != "something" {
|
||||
t.Error("stringz flag should be `something`, is ", *stringzFlag)
|
||||
}
|
||||
if len(f.Args()) != 2 {
|
||||
t.Error("expected one argument, got", len(f.Args()))
|
||||
} else if f.Args()[0] != extra {
|
||||
t.Errorf("expected argument %q got %q", extra, f.Args()[0])
|
||||
} else if f.Args()[1] != notaflag {
|
||||
t.Errorf("expected argument %q got %q", notaflag, f.Args()[1])
|
||||
}
|
||||
if f.ArgsLenAtDash() != 1 {
|
||||
t.Errorf("expected argsLenAtDash %d got %d", f.ArgsLenAtDash(), 1)
|
||||
}
|
||||
}
|
||||
|
||||
func TestParse(t *testing.T) {
|
||||
ResetForTesting(func() { t.Error("bad parse") })
|
||||
testParse(GetCommandLine(), t)
|
||||
}
|
||||
|
||||
func TestFlagSetParse(t *testing.T) {
|
||||
testParse(NewFlagSet("test", ContinueOnError), t)
|
||||
}
|
||||
|
||||
func TestChangedHelper(t *testing.T) {
|
||||
f := NewFlagSet("changedtest", ContinueOnError)
|
||||
_ = f.Bool("changed", false, "changed bool")
|
||||
_ = f.Bool("settrue", true, "true to true")
|
||||
_ = f.Bool("setfalse", false, "false to false")
|
||||
_ = f.Bool("unchanged", false, "unchanged bool")
|
||||
|
||||
args := []string{"--changed", "--settrue", "--setfalse=false"}
|
||||
if err := f.Parse(args); err != nil {
|
||||
t.Error("f.Parse() = false after Parse")
|
||||
}
|
||||
if !f.Changed("changed") {
|
||||
t.Errorf("--changed wasn't changed!")
|
||||
}
|
||||
if !f.Changed("settrue") {
|
||||
t.Errorf("--settrue wasn't changed!")
|
||||
}
|
||||
if !f.Changed("setfalse") {
|
||||
t.Errorf("--setfalse wasn't changed!")
|
||||
}
|
||||
if f.Changed("unchanged") {
|
||||
t.Errorf("--unchanged was changed!")
|
||||
}
|
||||
if f.Changed("invalid") {
|
||||
t.Errorf("--invalid was changed!")
|
||||
}
|
||||
if f.ArgsLenAtDash() != -1 {
|
||||
t.Errorf("Expected argsLenAtDash: %d but got %d", -1, f.ArgsLenAtDash())
|
||||
}
|
||||
}
|
||||
|
||||
func replaceSeparators(name string, from []string, to string) string {
|
||||
result := name
|
||||
for _, sep := range from {
|
||||
result = strings.Replace(result, sep, to, -1)
|
||||
}
|
||||
// Type convert to indicate normalization has been done.
|
||||
return result
|
||||
}
|
||||
|
||||
func wordSepNormalizeFunc(f *FlagSet, name string) NormalizedName {
|
||||
seps := []string{"-", "_"}
|
||||
name = replaceSeparators(name, seps, ".")
|
||||
normalizeFlagNameInvocations++
|
||||
|
||||
return NormalizedName(name)
|
||||
}
|
||||
|
||||
func testWordSepNormalizedNames(args []string, t *testing.T) {
|
||||
f := NewFlagSet("normalized", ContinueOnError)
|
||||
if f.Parsed() {
|
||||
t.Error("f.Parse() = true before Parse")
|
||||
}
|
||||
withDashFlag := f.Bool("with-dash-flag", false, "bool value")
|
||||
// Set this after some flags have been added and before others.
|
||||
f.SetNormalizeFunc(wordSepNormalizeFunc)
|
||||
withUnderFlag := f.Bool("with_under_flag", false, "bool value")
|
||||
withBothFlag := f.Bool("with-both_flag", false, "bool value")
|
||||
if err := f.Parse(args); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !f.Parsed() {
|
||||
t.Error("f.Parse() = false after Parse")
|
||||
}
|
||||
if *withDashFlag != true {
|
||||
t.Error("withDashFlag flag should be true, is ", *withDashFlag)
|
||||
}
|
||||
if *withUnderFlag != true {
|
||||
t.Error("withUnderFlag flag should be true, is ", *withUnderFlag)
|
||||
}
|
||||
if *withBothFlag != true {
|
||||
t.Error("withBothFlag flag should be true, is ", *withBothFlag)
|
||||
}
|
||||
}
|
||||
|
||||
func TestWordSepNormalizedNames(t *testing.T) {
|
||||
args := []string{
|
||||
"--with-dash-flag",
|
||||
"--with-under-flag",
|
||||
"--with-both-flag",
|
||||
}
|
||||
testWordSepNormalizedNames(args, t)
|
||||
|
||||
args = []string{
|
||||
"--with_dash_flag",
|
||||
"--with_under_flag",
|
||||
"--with_both_flag",
|
||||
}
|
||||
testWordSepNormalizedNames(args, t)
|
||||
|
||||
args = []string{
|
||||
"--with-dash_flag",
|
||||
"--with-under_flag",
|
||||
"--with-both_flag",
|
||||
}
|
||||
testWordSepNormalizedNames(args, t)
|
||||
}
|
||||
|
||||
func aliasAndWordSepFlagNames(f *FlagSet, name string) NormalizedName {
|
||||
seps := []string{"-", "_"}
|
||||
|
||||
oldName := replaceSeparators("old-valid_flag", seps, ".")
|
||||
newName := replaceSeparators("valid-flag", seps, ".")
|
||||
|
||||
name = replaceSeparators(name, seps, ".")
|
||||
switch name {
|
||||
case oldName:
|
||||
name = newName
|
||||
break
|
||||
}
|
||||
|
||||
return NormalizedName(name)
|
||||
}
|
||||
|
||||
func TestCustomNormalizedNames(t *testing.T) {
|
||||
f := NewFlagSet("normalized", ContinueOnError)
|
||||
if f.Parsed() {
|
||||
t.Error("f.Parse() = true before Parse")
|
||||
}
|
||||
|
||||
validFlag := f.Bool("valid-flag", false, "bool value")
|
||||
f.SetNormalizeFunc(aliasAndWordSepFlagNames)
|
||||
someOtherFlag := f.Bool("some-other-flag", false, "bool value")
|
||||
|
||||
args := []string{"--old_valid_flag", "--some-other_flag"}
|
||||
if err := f.Parse(args); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if *validFlag != true {
|
||||
t.Errorf("validFlag is %v even though we set the alias --old_valid_falg", *validFlag)
|
||||
}
|
||||
if *someOtherFlag != true {
|
||||
t.Error("someOtherFlag should be true, is ", *someOtherFlag)
|
||||
}
|
||||
}
|
||||
|
||||
// Every flag we add, the name (displayed also in usage) should normalized
|
||||
func TestNormalizationFuncShouldChangeFlagName(t *testing.T) {
|
||||
// Test normalization after addition
|
||||
f := NewFlagSet("normalized", ContinueOnError)
|
||||
|
||||
f.Bool("valid_flag", false, "bool value")
|
||||
if f.Lookup("valid_flag").Name != "valid_flag" {
|
||||
t.Error("The new flag should have the name 'valid_flag' instead of ", f.Lookup("valid_flag").Name)
|
||||
}
|
||||
|
||||
f.SetNormalizeFunc(wordSepNormalizeFunc)
|
||||
if f.Lookup("valid_flag").Name != "valid.flag" {
|
||||
t.Error("The new flag should have the name 'valid.flag' instead of ", f.Lookup("valid_flag").Name)
|
||||
}
|
||||
|
||||
// Test normalization before addition
|
||||
f = NewFlagSet("normalized", ContinueOnError)
|
||||
f.SetNormalizeFunc(wordSepNormalizeFunc)
|
||||
|
||||
f.Bool("valid_flag", false, "bool value")
|
||||
if f.Lookup("valid_flag").Name != "valid.flag" {
|
||||
t.Error("The new flag should have the name 'valid.flag' instead of ", f.Lookup("valid_flag").Name)
|
||||
}
|
||||
}
|
||||
|
||||
// Declare a user-defined flag type.
|
||||
type flagVar []string
|
||||
|
||||
func (f *flagVar) String() string {
|
||||
return fmt.Sprint([]string(*f))
|
||||
}
|
||||
|
||||
func (f *flagVar) Set(value string) error {
|
||||
*f = append(*f, value)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (f *flagVar) Type() string {
|
||||
return "flagVar"
|
||||
}
|
||||
|
||||
func TestUserDefined(t *testing.T) {
|
||||
var flags FlagSet
|
||||
flags.Init("test", ContinueOnError)
|
||||
var v flagVar
|
||||
flags.VarP(&v, "v", "v", "usage")
|
||||
if err := flags.Parse([]string{"--v=1", "-v2", "-v", "3"}); err != nil {
|
||||
t.Error(err)
|
||||
}
|
||||
if len(v) != 3 {
|
||||
t.Fatal("expected 3 args; got ", len(v))
|
||||
}
|
||||
expect := "[1 2 3]"
|
||||
if v.String() != expect {
|
||||
t.Errorf("expected value %q got %q", expect, v.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestSetOutput(t *testing.T) {
|
||||
var flags FlagSet
|
||||
var buf bytes.Buffer
|
||||
flags.SetOutput(&buf)
|
||||
flags.Init("test", ContinueOnError)
|
||||
flags.Parse([]string{"--unknown"})
|
||||
if out := buf.String(); !strings.Contains(out, "--unknown") {
|
||||
t.Logf("expected output mentioning unknown; got %q", out)
|
||||
}
|
||||
}
|
||||
|
||||
// This tests that one can reset the flags. This still works but not well, and is
|
||||
// superseded by FlagSet.
|
||||
func TestChangingArgs(t *testing.T) {
|
||||
ResetForTesting(func() { t.Fatal("bad parse") })
|
||||
oldArgs := os.Args
|
||||
defer func() { os.Args = oldArgs }()
|
||||
os.Args = []string{"cmd", "--before", "subcmd"}
|
||||
before := Bool("before", false, "")
|
||||
if err := GetCommandLine().Parse(os.Args[1:]); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
cmd := Arg(0)
|
||||
os.Args = []string{"subcmd", "--after", "args"}
|
||||
after := Bool("after", false, "")
|
||||
Parse()
|
||||
args := Args()
|
||||
|
||||
if !*before || cmd != "subcmd" || !*after || len(args) != 1 || args[0] != "args" {
|
||||
t.Fatalf("expected true subcmd true [args] got %v %v %v %v", *before, cmd, *after, args)
|
||||
}
|
||||
}
|
||||
|
||||
// Test that -help invokes the usage message and returns ErrHelp.
|
||||
func TestHelp(t *testing.T) {
|
||||
var helpCalled = false
|
||||
fs := NewFlagSet("help test", ContinueOnError)
|
||||
fs.Usage = func() { helpCalled = true }
|
||||
var flag bool
|
||||
fs.BoolVar(&flag, "flag", false, "regular flag")
|
||||
// Regular flag invocation should work
|
||||
err := fs.Parse([]string{"--flag=true"})
|
||||
if err != nil {
|
||||
t.Fatal("expected no error; got ", err)
|
||||
}
|
||||
if !flag {
|
||||
t.Error("flag was not set by --flag")
|
||||
}
|
||||
if helpCalled {
|
||||
t.Error("help called for regular flag")
|
||||
helpCalled = false // reset for next test
|
||||
}
|
||||
// Help flag should work as expected.
|
||||
err = fs.Parse([]string{"--help"})
|
||||
if err == nil {
|
||||
t.Fatal("error expected")
|
||||
}
|
||||
if err != ErrHelp {
|
||||
t.Fatal("expected ErrHelp; got ", err)
|
||||
}
|
||||
if !helpCalled {
|
||||
t.Fatal("help was not called")
|
||||
}
|
||||
// If we define a help flag, that should override.
|
||||
var help bool
|
||||
fs.BoolVar(&help, "help", false, "help flag")
|
||||
helpCalled = false
|
||||
err = fs.Parse([]string{"--help"})
|
||||
if err != nil {
|
||||
t.Fatal("expected no error for defined --help; got ", err)
|
||||
}
|
||||
if helpCalled {
|
||||
t.Fatal("help was called; should not have been for defined help flag")
|
||||
}
|
||||
}
|
||||
|
||||
func TestNoInterspersed(t *testing.T) {
|
||||
f := NewFlagSet("test", ContinueOnError)
|
||||
f.SetInterspersed(false)
|
||||
f.Bool("true", true, "always true")
|
||||
f.Bool("false", false, "always false")
|
||||
err := f.Parse([]string{"--true", "break", "--false"})
|
||||
if err != nil {
|
||||
t.Fatal("expected no error; got ", err)
|
||||
}
|
||||
args := f.Args()
|
||||
if len(args) != 2 || args[0] != "break" || args[1] != "--false" {
|
||||
t.Fatal("expected interspersed options/non-options to fail")
|
||||
}
|
||||
}
|
||||
|
||||
func TestTermination(t *testing.T) {
|
||||
f := NewFlagSet("termination", ContinueOnError)
|
||||
boolFlag := f.BoolP("bool", "l", false, "bool value")
|
||||
if f.Parsed() {
|
||||
t.Error("f.Parse() = true before Parse")
|
||||
}
|
||||
arg1 := "ls"
|
||||
arg2 := "-l"
|
||||
args := []string{
|
||||
"--",
|
||||
arg1,
|
||||
arg2,
|
||||
}
|
||||
f.SetOutput(ioutil.Discard)
|
||||
if err := f.Parse(args); err != nil {
|
||||
t.Fatal("expected no error; got ", err)
|
||||
}
|
||||
if !f.Parsed() {
|
||||
t.Error("f.Parse() = false after Parse")
|
||||
}
|
||||
if *boolFlag {
|
||||
t.Error("expected boolFlag=false, got true")
|
||||
}
|
||||
if len(f.Args()) != 2 {
|
||||
t.Errorf("expected 2 arguments, got %d: %v", len(f.Args()), f.Args())
|
||||
}
|
||||
if f.Args()[0] != arg1 {
|
||||
t.Errorf("expected argument %q got %q", arg1, f.Args()[0])
|
||||
}
|
||||
if f.Args()[1] != arg2 {
|
||||
t.Errorf("expected argument %q got %q", arg2, f.Args()[1])
|
||||
}
|
||||
if f.ArgsLenAtDash() != 0 {
|
||||
t.Errorf("expected argsLenAtDash %d got %d", 0, f.ArgsLenAtDash())
|
||||
}
|
||||
}
|
||||
|
||||
func TestDeprecatedFlagInDocs(t *testing.T) {
|
||||
f := NewFlagSet("bob", ContinueOnError)
|
||||
f.Bool("badflag", true, "always true")
|
||||
f.MarkDeprecated("badflag", "use --good-flag instead")
|
||||
|
||||
out := new(bytes.Buffer)
|
||||
f.SetOutput(out)
|
||||
f.PrintDefaults()
|
||||
|
||||
if strings.Contains(out.String(), "badflag") {
|
||||
t.Errorf("found deprecated flag in usage!")
|
||||
}
|
||||
}
|
||||
|
||||
func TestDeprecatedFlagShorthandInDocs(t *testing.T) {
|
||||
f := NewFlagSet("bob", ContinueOnError)
|
||||
name := "noshorthandflag"
|
||||
f.BoolP(name, "n", true, "always true")
|
||||
f.MarkShorthandDeprecated("noshorthandflag", fmt.Sprintf("use --%s instead", name))
|
||||
|
||||
out := new(bytes.Buffer)
|
||||
f.SetOutput(out)
|
||||
f.PrintDefaults()
|
||||
|
||||
if strings.Contains(out.String(), "-n,") {
|
||||
t.Errorf("found deprecated flag shorthand in usage!")
|
||||
}
|
||||
}
|
||||
|
||||
func parseReturnStderr(t *testing.T, f *FlagSet, args []string) (string, error) {
|
||||
oldStderr := os.Stderr
|
||||
r, w, _ := os.Pipe()
|
||||
os.Stderr = w
|
||||
|
||||
err := f.Parse(args)
|
||||
|
||||
outC := make(chan string)
|
||||
// copy the output in a separate goroutine so printing can't block indefinitely
|
||||
go func() {
|
||||
var buf bytes.Buffer
|
||||
io.Copy(&buf, r)
|
||||
outC <- buf.String()
|
||||
}()
|
||||
|
||||
w.Close()
|
||||
os.Stderr = oldStderr
|
||||
out := <-outC
|
||||
|
||||
return out, err
|
||||
}
|
||||
|
||||
func TestDeprecatedFlagUsage(t *testing.T) {
|
||||
f := NewFlagSet("bob", ContinueOnError)
|
||||
f.Bool("badflag", true, "always true")
|
||||
usageMsg := "use --good-flag instead"
|
||||
f.MarkDeprecated("badflag", usageMsg)
|
||||
|
||||
args := []string{"--badflag"}
|
||||
out, err := parseReturnStderr(t, f, args)
|
||||
if err != nil {
|
||||
t.Fatal("expected no error; got ", err)
|
||||
}
|
||||
|
||||
if !strings.Contains(out, usageMsg) {
|
||||
t.Errorf("usageMsg not printed when using a deprecated flag!")
|
||||
}
|
||||
}
|
||||
|
||||
func TestDeprecatedFlagShorthandUsage(t *testing.T) {
|
||||
f := NewFlagSet("bob", ContinueOnError)
|
||||
name := "noshorthandflag"
|
||||
f.BoolP(name, "n", true, "always true")
|
||||
usageMsg := fmt.Sprintf("use --%s instead", name)
|
||||
f.MarkShorthandDeprecated(name, usageMsg)
|
||||
|
||||
args := []string{"-n"}
|
||||
out, err := parseReturnStderr(t, f, args)
|
||||
if err != nil {
|
||||
t.Fatal("expected no error; got ", err)
|
||||
}
|
||||
|
||||
if !strings.Contains(out, usageMsg) {
|
||||
t.Errorf("usageMsg not printed when using a deprecated flag!")
|
||||
}
|
||||
}
|
||||
|
||||
func TestDeprecatedFlagUsageNormalized(t *testing.T) {
|
||||
f := NewFlagSet("bob", ContinueOnError)
|
||||
f.Bool("bad-double_flag", true, "always true")
|
||||
f.SetNormalizeFunc(wordSepNormalizeFunc)
|
||||
usageMsg := "use --good-flag instead"
|
||||
f.MarkDeprecated("bad_double-flag", usageMsg)
|
||||
|
||||
args := []string{"--bad_double_flag"}
|
||||
out, err := parseReturnStderr(t, f, args)
|
||||
if err != nil {
|
||||
t.Fatal("expected no error; got ", err)
|
||||
}
|
||||
|
||||
if !strings.Contains(out, usageMsg) {
|
||||
t.Errorf("usageMsg not printed when using a deprecated flag!")
|
||||
}
|
||||
}
|
||||
|
||||
// Name normalization function should be called only once on flag addition
|
||||
func TestMultipleNormalizeFlagNameInvocations(t *testing.T) {
|
||||
normalizeFlagNameInvocations = 0
|
||||
|
||||
f := NewFlagSet("normalized", ContinueOnError)
|
||||
f.SetNormalizeFunc(wordSepNormalizeFunc)
|
||||
f.Bool("with_under_flag", false, "bool value")
|
||||
|
||||
if normalizeFlagNameInvocations != 1 {
|
||||
t.Fatal("Expected normalizeFlagNameInvocations to be 1; got ", normalizeFlagNameInvocations)
|
||||
}
|
||||
}
|
||||
|
||||
//
|
||||
func TestHiddenFlagInUsage(t *testing.T) {
|
||||
f := NewFlagSet("bob", ContinueOnError)
|
||||
f.Bool("secretFlag", true, "shhh")
|
||||
f.MarkHidden("secretFlag")
|
||||
|
||||
out := new(bytes.Buffer)
|
||||
f.SetOutput(out)
|
||||
f.PrintDefaults()
|
||||
|
||||
if strings.Contains(out.String(), "secretFlag") {
|
||||
t.Errorf("found hidden flag in usage!")
|
||||
}
|
||||
}
|
||||
|
||||
//
|
||||
func TestHiddenFlagUsage(t *testing.T) {
|
||||
f := NewFlagSet("bob", ContinueOnError)
|
||||
f.Bool("secretFlag", true, "shhh")
|
||||
f.MarkHidden("secretFlag")
|
||||
|
||||
args := []string{"--secretFlag"}
|
||||
out, err := parseReturnStderr(t, f, args)
|
||||
if err != nil {
|
||||
t.Fatal("expected no error; got ", err)
|
||||
}
|
||||
|
||||
if strings.Contains(out, "shhh") {
|
||||
t.Errorf("usage message printed when using a hidden flag!")
|
||||
}
|
||||
}
|
||||
|
||||
const defaultOutput = ` --A for bootstrapping, allow 'any' type
|
||||
--Alongflagname disable bounds checking
|
||||
-C, --CCC a boolean defaulting to true (default true)
|
||||
--D path set relative path for local imports
|
||||
--F number a non-zero number (default 2.7)
|
||||
--G float a float that defaults to zero
|
||||
--N int a non-zero int (default 27)
|
||||
--ND1 string[="bar"] a string with NoOptDefVal (default "foo")
|
||||
--ND2 num[=4321] a num with NoOptDefVal (default 1234)
|
||||
--Z int an int that defaults to zero
|
||||
--maxT timeout set timeout for dial
|
||||
`
|
||||
|
||||
func TestPrintDefaults(t *testing.T) {
|
||||
fs := NewFlagSet("print defaults test", ContinueOnError)
|
||||
var buf bytes.Buffer
|
||||
fs.SetOutput(&buf)
|
||||
fs.Bool("A", false, "for bootstrapping, allow 'any' type")
|
||||
fs.Bool("Alongflagname", false, "disable bounds checking")
|
||||
fs.BoolP("CCC", "C", true, "a boolean defaulting to true")
|
||||
fs.String("D", "", "set relative `path` for local imports")
|
||||
fs.Float64("F", 2.7, "a non-zero `number`")
|
||||
fs.Float64("G", 0, "a float that defaults to zero")
|
||||
fs.Int("N", 27, "a non-zero int")
|
||||
fs.Int("Z", 0, "an int that defaults to zero")
|
||||
fs.Duration("maxT", 0, "set `timeout` for dial")
|
||||
fs.String("ND1", "foo", "a string with NoOptDefVal")
|
||||
fs.Lookup("ND1").NoOptDefVal = "bar"
|
||||
fs.Int("ND2", 1234, "a `num` with NoOptDefVal")
|
||||
fs.Lookup("ND2").NoOptDefVal = "4321"
|
||||
fs.PrintDefaults()
|
||||
got := buf.String()
|
||||
if got != defaultOutput {
|
||||
fmt.Println("\n" + got)
|
||||
fmt.Println("\n" + defaultOutput)
|
||||
t.Errorf("got %q want %q\n", got, defaultOutput)
|
||||
}
|
||||
}
|
7
vendor/github.com/spf13/pflag/float32.go
generated
vendored
7
vendor/github.com/spf13/pflag/float32.go
generated
vendored
|
@ -1,9 +1,6 @@
|
|||
package pflag
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strconv"
|
||||
)
|
||||
import "strconv"
|
||||
|
||||
// -- float32 Value
|
||||
type float32Value float32
|
||||
|
@ -23,7 +20,7 @@ func (f *float32Value) Type() string {
|
|||
return "float32"
|
||||
}
|
||||
|
||||
func (f *float32Value) String() string { return fmt.Sprintf("%v", *f) }
|
||||
func (f *float32Value) String() string { return strconv.FormatFloat(float64(*f), 'g', -1, 32) }
|
||||
|
||||
func float32Conv(sval string) (interface{}, error) {
|
||||
v, err := strconv.ParseFloat(sval, 32)
|
||||
|
|
7
vendor/github.com/spf13/pflag/float64.go
generated
vendored
7
vendor/github.com/spf13/pflag/float64.go
generated
vendored
|
@ -1,9 +1,6 @@
|
|||
package pflag
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strconv"
|
||||
)
|
||||
import "strconv"
|
||||
|
||||
// -- float64 Value
|
||||
type float64Value float64
|
||||
|
@ -23,7 +20,7 @@ func (f *float64Value) Type() string {
|
|||
return "float64"
|
||||
}
|
||||
|
||||
func (f *float64Value) String() string { return fmt.Sprintf("%v", *f) }
|
||||
func (f *float64Value) String() string { return strconv.FormatFloat(float64(*f), 'g', -1, 64) }
|
||||
|
||||
func float64Conv(sval string) (interface{}, error) {
|
||||
return strconv.ParseFloat(sval, 64)
|
||||
|
|
3
vendor/github.com/spf13/pflag/golangflag.go
generated
vendored
3
vendor/github.com/spf13/pflag/golangflag.go
generated
vendored
|
@ -6,13 +6,10 @@ package pflag
|
|||
|
||||
import (
|
||||
goflag "flag"
|
||||
"fmt"
|
||||
"reflect"
|
||||
"strings"
|
||||
)
|
||||
|
||||
var _ = fmt.Print
|
||||
|
||||
// flagValueWrapper implements pflag.Value around a flag.Value. The main
|
||||
// difference here is the addition of the Type method that returns a string
|
||||
// name of the type. As this is generally unknown, we approximate that with
|
||||
|
|
39
vendor/github.com/spf13/pflag/golangflag_test.go
generated
vendored
39
vendor/github.com/spf13/pflag/golangflag_test.go
generated
vendored
|
@ -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)
|
||||
}
|
||||
}
|
7
vendor/github.com/spf13/pflag/int.go
generated
vendored
7
vendor/github.com/spf13/pflag/int.go
generated
vendored
|
@ -1,9 +1,6 @@
|
|||
package pflag
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strconv"
|
||||
)
|
||||
import "strconv"
|
||||
|
||||
// -- int Value
|
||||
type intValue int
|
||||
|
@ -23,7 +20,7 @@ func (i *intValue) Type() string {
|
|||
return "int"
|
||||
}
|
||||
|
||||
func (i *intValue) String() string { return fmt.Sprintf("%v", *i) }
|
||||
func (i *intValue) String() string { return strconv.Itoa(int(*i)) }
|
||||
|
||||
func intConv(sval string) (interface{}, error) {
|
||||
return strconv.Atoi(sval)
|
||||
|
|
7
vendor/github.com/spf13/pflag/int32.go
generated
vendored
7
vendor/github.com/spf13/pflag/int32.go
generated
vendored
|
@ -1,9 +1,6 @@
|
|||
package pflag
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strconv"
|
||||
)
|
||||
import "strconv"
|
||||
|
||||
// -- int32 Value
|
||||
type int32Value int32
|
||||
|
@ -23,7 +20,7 @@ func (i *int32Value) Type() string {
|
|||
return "int32"
|
||||
}
|
||||
|
||||
func (i *int32Value) String() string { return fmt.Sprintf("%v", *i) }
|
||||
func (i *int32Value) String() string { return strconv.FormatInt(int64(*i), 10) }
|
||||
|
||||
func int32Conv(sval string) (interface{}, error) {
|
||||
v, err := strconv.ParseInt(sval, 0, 32)
|
||||
|
|
7
vendor/github.com/spf13/pflag/int64.go
generated
vendored
7
vendor/github.com/spf13/pflag/int64.go
generated
vendored
|
@ -1,9 +1,6 @@
|
|||
package pflag
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strconv"
|
||||
)
|
||||
import "strconv"
|
||||
|
||||
// -- int64 Value
|
||||
type int64Value int64
|
||||
|
@ -23,7 +20,7 @@ func (i *int64Value) Type() string {
|
|||
return "int64"
|
||||
}
|
||||
|
||||
func (i *int64Value) String() string { return fmt.Sprintf("%v", *i) }
|
||||
func (i *int64Value) String() string { return strconv.FormatInt(int64(*i), 10) }
|
||||
|
||||
func int64Conv(sval string) (interface{}, error) {
|
||||
return strconv.ParseInt(sval, 0, 64)
|
||||
|
|
7
vendor/github.com/spf13/pflag/int8.go
generated
vendored
7
vendor/github.com/spf13/pflag/int8.go
generated
vendored
|
@ -1,9 +1,6 @@
|
|||
package pflag
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strconv"
|
||||
)
|
||||
import "strconv"
|
||||
|
||||
// -- int8 Value
|
||||
type int8Value int8
|
||||
|
@ -23,7 +20,7 @@ func (i *int8Value) Type() string {
|
|||
return "int8"
|
||||
}
|
||||
|
||||
func (i *int8Value) String() string { return fmt.Sprintf("%v", *i) }
|
||||
func (i *int8Value) String() string { return strconv.FormatInt(int64(*i), 10) }
|
||||
|
||||
func int8Conv(sval string) (interface{}, error) {
|
||||
v, err := strconv.ParseInt(sval, 0, 8)
|
||||
|
|
162
vendor/github.com/spf13/pflag/int_slice_test.go
generated
vendored
162
vendor/github.com/spf13/pflag/int_slice_test.go
generated
vendored
|
@ -1,162 +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")
|
||||
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)
|
||||
}
|
||||
}
|
||||
}
|
2
vendor/github.com/spf13/pflag/ip.go
generated
vendored
2
vendor/github.com/spf13/pflag/ip.go
generated
vendored
|
@ -6,8 +6,6 @@ import (
|
|||
"strings"
|
||||
)
|
||||
|
||||
var _ = strings.TrimSpace
|
||||
|
||||
// -- net.IP value
|
||||
type ipValue net.IP
|
||||
|
||||
|
|
148
vendor/github.com/spf13/pflag/ip_slice.go
generated
vendored
Normal file
148
vendor/github.com/spf13/pflag/ip_slice.go
generated
vendored
Normal file
|
@ -0,0 +1,148 @@
|
|||
package pflag
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// -- ipSlice Value
|
||||
type ipSliceValue struct {
|
||||
value *[]net.IP
|
||||
changed bool
|
||||
}
|
||||
|
||||
func newIPSliceValue(val []net.IP, p *[]net.IP) *ipSliceValue {
|
||||
ipsv := new(ipSliceValue)
|
||||
ipsv.value = p
|
||||
*ipsv.value = val
|
||||
return ipsv
|
||||
}
|
||||
|
||||
// Set converts, and assigns, the comma-separated IP argument string representation as the []net.IP value of this flag.
|
||||
// If Set is called on a flag that already has a []net.IP assigned, the newly converted values will be appended.
|
||||
func (s *ipSliceValue) Set(val string) error {
|
||||
|
||||
// remove all quote characters
|
||||
rmQuote := strings.NewReplacer(`"`, "", `'`, "", "`", "")
|
||||
|
||||
// read flag arguments with CSV parser
|
||||
ipStrSlice, err := readAsCSV(rmQuote.Replace(val))
|
||||
if err != nil && err != io.EOF {
|
||||
return err
|
||||
}
|
||||
|
||||
// parse ip values into slice
|
||||
out := make([]net.IP, 0, len(ipStrSlice))
|
||||
for _, ipStr := range ipStrSlice {
|
||||
ip := net.ParseIP(strings.TrimSpace(ipStr))
|
||||
if ip == nil {
|
||||
return fmt.Errorf("invalid string being converted to IP address: %s", ipStr)
|
||||
}
|
||||
out = append(out, ip)
|
||||
}
|
||||
|
||||
if !s.changed {
|
||||
*s.value = out
|
||||
} else {
|
||||
*s.value = append(*s.value, out...)
|
||||
}
|
||||
|
||||
s.changed = true
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// Type returns a string that uniquely represents this flag's type.
|
||||
func (s *ipSliceValue) Type() string {
|
||||
return "ipSlice"
|
||||
}
|
||||
|
||||
// String defines a "native" format for this net.IP slice flag value.
|
||||
func (s *ipSliceValue) String() string {
|
||||
|
||||
ipStrSlice := make([]string, len(*s.value))
|
||||
for i, ip := range *s.value {
|
||||
ipStrSlice[i] = ip.String()
|
||||
}
|
||||
|
||||
out, _ := writeAsCSV(ipStrSlice)
|
||||
|
||||
return "[" + out + "]"
|
||||
}
|
||||
|
||||
func ipSliceConv(val string) (interface{}, error) {
|
||||
val = strings.Trim(val, "[]")
|
||||
// Emtpy string would cause a slice with one (empty) entry
|
||||
if len(val) == 0 {
|
||||
return []net.IP{}, nil
|
||||
}
|
||||
ss := strings.Split(val, ",")
|
||||
out := make([]net.IP, len(ss))
|
||||
for i, sval := range ss {
|
||||
ip := net.ParseIP(strings.TrimSpace(sval))
|
||||
if ip == nil {
|
||||
return nil, fmt.Errorf("invalid string being converted to IP address: %s", sval)
|
||||
}
|
||||
out[i] = ip
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// GetIPSlice returns the []net.IP value of a flag with the given name
|
||||
func (f *FlagSet) GetIPSlice(name string) ([]net.IP, error) {
|
||||
val, err := f.getFlagType(name, "ipSlice", ipSliceConv)
|
||||
if err != nil {
|
||||
return []net.IP{}, err
|
||||
}
|
||||
return val.([]net.IP), nil
|
||||
}
|
||||
|
||||
// IPSliceVar defines a ipSlice flag with specified name, default value, and usage string.
|
||||
// The argument p points to a []net.IP variable in which to store the value of the flag.
|
||||
func (f *FlagSet) IPSliceVar(p *[]net.IP, name string, value []net.IP, usage string) {
|
||||
f.VarP(newIPSliceValue(value, p), name, "", usage)
|
||||
}
|
||||
|
||||
// IPSliceVarP is like IPSliceVar, but accepts a shorthand letter that can be used after a single dash.
|
||||
func (f *FlagSet) IPSliceVarP(p *[]net.IP, name, shorthand string, value []net.IP, usage string) {
|
||||
f.VarP(newIPSliceValue(value, p), name, shorthand, usage)
|
||||
}
|
||||
|
||||
// IPSliceVar defines a []net.IP flag with specified name, default value, and usage string.
|
||||
// The argument p points to a []net.IP variable in which to store the value of the flag.
|
||||
func IPSliceVar(p *[]net.IP, name string, value []net.IP, usage string) {
|
||||
CommandLine.VarP(newIPSliceValue(value, p), name, "", usage)
|
||||
}
|
||||
|
||||
// IPSliceVarP is like IPSliceVar, but accepts a shorthand letter that can be used after a single dash.
|
||||
func IPSliceVarP(p *[]net.IP, name, shorthand string, value []net.IP, usage string) {
|
||||
CommandLine.VarP(newIPSliceValue(value, p), name, shorthand, usage)
|
||||
}
|
||||
|
||||
// IPSlice defines a []net.IP flag with specified name, default value, and usage string.
|
||||
// The return value is the address of a []net.IP variable that stores the value of that flag.
|
||||
func (f *FlagSet) IPSlice(name string, value []net.IP, usage string) *[]net.IP {
|
||||
p := []net.IP{}
|
||||
f.IPSliceVarP(&p, name, "", value, usage)
|
||||
return &p
|
||||
}
|
||||
|
||||
// IPSliceP is like IPSlice, but accepts a shorthand letter that can be used after a single dash.
|
||||
func (f *FlagSet) IPSliceP(name, shorthand string, value []net.IP, usage string) *[]net.IP {
|
||||
p := []net.IP{}
|
||||
f.IPSliceVarP(&p, name, shorthand, value, usage)
|
||||
return &p
|
||||
}
|
||||
|
||||
// IPSlice defines a []net.IP flag with specified name, default value, and usage string.
|
||||
// The return value is the address of a []net.IP variable that stores the value of the flag.
|
||||
func IPSlice(name string, value []net.IP, usage string) *[]net.IP {
|
||||
return CommandLine.IPSliceP(name, "", value, usage)
|
||||
}
|
||||
|
||||
// IPSliceP is like IPSlice, but accepts a shorthand letter that can be used after a single dash.
|
||||
func IPSliceP(name, shorthand string, value []net.IP, usage string) *[]net.IP {
|
||||
return CommandLine.IPSliceP(name, shorthand, value, usage)
|
||||
}
|
63
vendor/github.com/spf13/pflag/ip_test.go
generated
vendored
63
vendor/github.com/spf13/pflag/ip_test.go
generated
vendored
|
@ -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())
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
2
vendor/github.com/spf13/pflag/ipnet.go
generated
vendored
2
vendor/github.com/spf13/pflag/ipnet.go
generated
vendored
|
@ -27,8 +27,6 @@ func (*ipNetValue) Type() string {
|
|||
return "ipNet"
|
||||
}
|
||||
|
||||
var _ = strings.TrimSpace
|
||||
|
||||
func newIPNetValue(val net.IPNet, p *net.IPNet) *ipNetValue {
|
||||
*p = val
|
||||
return (*ipNetValue)(p)
|
||||
|
|
70
vendor/github.com/spf13/pflag/ipnet_test.go
generated
vendored
70
vendor/github.com/spf13/pflag/ipnet_test.go
generated
vendored
|
@ -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())
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
4
vendor/github.com/spf13/pflag/string.go
generated
vendored
4
vendor/github.com/spf13/pflag/string.go
generated
vendored
|
@ -1,7 +1,5 @@
|
|||
package pflag
|
||||
|
||||
import "fmt"
|
||||
|
||||
// -- string Value
|
||||
type stringValue string
|
||||
|
||||
|
@ -18,7 +16,7 @@ func (s *stringValue) Type() string {
|
|||
return "string"
|
||||
}
|
||||
|
||||
func (s *stringValue) String() string { return fmt.Sprintf("%s", *s) }
|
||||
func (s *stringValue) String() string { return string(*s) }
|
||||
|
||||
func stringConv(sval string) (interface{}, error) {
|
||||
return sval, nil
|
||||
|
|
103
vendor/github.com/spf13/pflag/string_array.go
generated
vendored
Normal file
103
vendor/github.com/spf13/pflag/string_array.go
generated
vendored
Normal file
|
@ -0,0 +1,103 @@
|
|||
package pflag
|
||||
|
||||
// -- stringArray Value
|
||||
type stringArrayValue struct {
|
||||
value *[]string
|
||||
changed bool
|
||||
}
|
||||
|
||||
func newStringArrayValue(val []string, p *[]string) *stringArrayValue {
|
||||
ssv := new(stringArrayValue)
|
||||
ssv.value = p
|
||||
*ssv.value = val
|
||||
return ssv
|
||||
}
|
||||
|
||||
func (s *stringArrayValue) Set(val string) error {
|
||||
if !s.changed {
|
||||
*s.value = []string{val}
|
||||
s.changed = true
|
||||
} else {
|
||||
*s.value = append(*s.value, val)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *stringArrayValue) Type() string {
|
||||
return "stringArray"
|
||||
}
|
||||
|
||||
func (s *stringArrayValue) String() string {
|
||||
str, _ := writeAsCSV(*s.value)
|
||||
return "[" + str + "]"
|
||||
}
|
||||
|
||||
func stringArrayConv(sval string) (interface{}, error) {
|
||||
sval = sval[1 : len(sval)-1]
|
||||
// An empty string would cause a array with one (empty) string
|
||||
if len(sval) == 0 {
|
||||
return []string{}, nil
|
||||
}
|
||||
return readAsCSV(sval)
|
||||
}
|
||||
|
||||
// GetStringArray return the []string value of a flag with the given name
|
||||
func (f *FlagSet) GetStringArray(name string) ([]string, error) {
|
||||
val, err := f.getFlagType(name, "stringArray", stringArrayConv)
|
||||
if err != nil {
|
||||
return []string{}, err
|
||||
}
|
||||
return val.([]string), nil
|
||||
}
|
||||
|
||||
// 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
|
||||
func (f *FlagSet) StringArrayVar(p *[]string, name string, value []string, usage string) {
|
||||
f.VarP(newStringArrayValue(value, p), name, "", usage)
|
||||
}
|
||||
|
||||
// StringArrayVarP is like StringArrayVar, but accepts a shorthand letter that can be used after a single dash.
|
||||
func (f *FlagSet) StringArrayVarP(p *[]string, name, shorthand string, value []string, usage string) {
|
||||
f.VarP(newStringArrayValue(value, p), name, shorthand, usage)
|
||||
}
|
||||
|
||||
// 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
|
||||
func StringArrayVar(p *[]string, name string, value []string, usage string) {
|
||||
CommandLine.VarP(newStringArrayValue(value, p), name, "", usage)
|
||||
}
|
||||
|
||||
// StringArrayVarP is like StringArrayVar, but accepts a shorthand letter that can be used after a single dash.
|
||||
func StringArrayVarP(p *[]string, name, shorthand string, value []string, usage string) {
|
||||
CommandLine.VarP(newStringArrayValue(value, p), name, shorthand, 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
|
||||
func (f *FlagSet) StringArray(name string, value []string, usage string) *[]string {
|
||||
p := []string{}
|
||||
f.StringArrayVarP(&p, name, "", value, usage)
|
||||
return &p
|
||||
}
|
||||
|
||||
// StringArrayP is like StringArray, but accepts a shorthand letter that can be used after a single dash.
|
||||
func (f *FlagSet) StringArrayP(name, shorthand string, value []string, usage string) *[]string {
|
||||
p := []string{}
|
||||
f.StringArrayVarP(&p, name, shorthand, value, usage)
|
||||
return &p
|
||||
}
|
||||
|
||||
// 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
|
||||
func StringArray(name string, value []string, usage string) *[]string {
|
||||
return CommandLine.StringArrayP(name, "", value, usage)
|
||||
}
|
||||
|
||||
// StringArrayP is like StringArray, but accepts a shorthand letter that can be used after a single dash.
|
||||
func StringArrayP(name, shorthand string, value []string, usage string) *[]string {
|
||||
return CommandLine.StringArrayP(name, shorthand, value, usage)
|
||||
}
|
36
vendor/github.com/spf13/pflag/string_slice.go
generated
vendored
36
vendor/github.com/spf13/pflag/string_slice.go
generated
vendored
|
@ -1,13 +1,11 @@
|
|||
package pflag
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/csv"
|
||||
"fmt"
|
||||
"strings"
|
||||
)
|
||||
|
||||
var _ = fmt.Fprint
|
||||
|
||||
// -- stringSlice Value
|
||||
type stringSliceValue struct {
|
||||
value *[]string
|
||||
|
@ -21,10 +19,28 @@ func newStringSliceValue(val []string, p *[]string) *stringSliceValue {
|
|||
return ssv
|
||||
}
|
||||
|
||||
func (s *stringSliceValue) Set(val string) error {
|
||||
func readAsCSV(val string) ([]string, error) {
|
||||
if val == "" {
|
||||
return []string{}, nil
|
||||
}
|
||||
stringReader := strings.NewReader(val)
|
||||
csvReader := csv.NewReader(stringReader)
|
||||
v, err := csvReader.Read()
|
||||
return csvReader.Read()
|
||||
}
|
||||
|
||||
func writeAsCSV(vals []string) (string, error) {
|
||||
b := &bytes.Buffer{}
|
||||
w := csv.NewWriter(b)
|
||||
err := w.Write(vals)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
w.Flush()
|
||||
return strings.TrimSuffix(b.String(), "\n"), nil
|
||||
}
|
||||
|
||||
func (s *stringSliceValue) Set(val string) error {
|
||||
v, err := readAsCSV(val)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
@ -41,16 +57,18 @@ func (s *stringSliceValue) Type() string {
|
|||
return "stringSlice"
|
||||
}
|
||||
|
||||
func (s *stringSliceValue) String() string { return "[" + strings.Join(*s.value, ",") + "]" }
|
||||
func (s *stringSliceValue) String() string {
|
||||
str, _ := writeAsCSV(*s.value)
|
||||
return "[" + str + "]"
|
||||
}
|
||||
|
||||
func stringSliceConv(sval string) (interface{}, error) {
|
||||
sval = strings.Trim(sval, "[]")
|
||||
sval = sval[1 : len(sval)-1]
|
||||
// An empty string would cause a slice with one (empty) string
|
||||
if len(sval) == 0 {
|
||||
return []string{}, nil
|
||||
}
|
||||
v := strings.Split(sval, ",")
|
||||
return v, nil
|
||||
return readAsCSV(sval)
|
||||
}
|
||||
|
||||
// GetStringSlice return the []string value of a flag with the given name
|
||||
|
|
161
vendor/github.com/spf13/pflag/string_slice_test.go
generated
vendored
161
vendor/github.com/spf13/pflag/string_slice_test.go
generated
vendored
|
@ -1,161 +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 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)
|
||||
}
|
||||
for i, v := range ss {
|
||||
if expected[i] != v {
|
||||
t.Fatalf("expected 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"`}
|
||||
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)
|
||||
}
|
||||
for i, v := range ss {
|
||||
if expected[i] != v {
|
||||
t.Fatalf("expected ss[%d] to be %s but got: %s", i, expected[i], v)
|
||||
}
|
||||
}
|
||||
}
|
7
vendor/github.com/spf13/pflag/uint.go
generated
vendored
7
vendor/github.com/spf13/pflag/uint.go
generated
vendored
|
@ -1,9 +1,6 @@
|
|||
package pflag
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strconv"
|
||||
)
|
||||
import "strconv"
|
||||
|
||||
// -- uint Value
|
||||
type uintValue uint
|
||||
|
@ -23,7 +20,7 @@ func (i *uintValue) Type() string {
|
|||
return "uint"
|
||||
}
|
||||
|
||||
func (i *uintValue) String() string { return fmt.Sprintf("%v", *i) }
|
||||
func (i *uintValue) String() string { return strconv.FormatUint(uint64(*i), 10) }
|
||||
|
||||
func uintConv(sval string) (interface{}, error) {
|
||||
v, err := strconv.ParseUint(sval, 0, 0)
|
||||
|
|
9
vendor/github.com/spf13/pflag/uint16.go
generated
vendored
9
vendor/github.com/spf13/pflag/uint16.go
generated
vendored
|
@ -1,9 +1,6 @@
|
|||
package pflag
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strconv"
|
||||
)
|
||||
import "strconv"
|
||||
|
||||
// -- uint16 value
|
||||
type uint16Value uint16
|
||||
|
@ -12,7 +9,7 @@ func newUint16Value(val uint16, p *uint16) *uint16Value {
|
|||
*p = val
|
||||
return (*uint16Value)(p)
|
||||
}
|
||||
func (i *uint16Value) String() string { return fmt.Sprintf("%d", *i) }
|
||||
|
||||
func (i *uint16Value) Set(s string) error {
|
||||
v, err := strconv.ParseUint(s, 0, 16)
|
||||
*i = uint16Value(v)
|
||||
|
@ -23,6 +20,8 @@ func (i *uint16Value) Type() string {
|
|||
return "uint16"
|
||||
}
|
||||
|
||||
func (i *uint16Value) String() string { return strconv.FormatUint(uint64(*i), 10) }
|
||||
|
||||
func uint16Conv(sval string) (interface{}, error) {
|
||||
v, err := strconv.ParseUint(sval, 0, 16)
|
||||
if err != nil {
|
||||
|
|
11
vendor/github.com/spf13/pflag/uint32.go
generated
vendored
11
vendor/github.com/spf13/pflag/uint32.go
generated
vendored
|
@ -1,18 +1,15 @@
|
|||
package pflag
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strconv"
|
||||
)
|
||||
import "strconv"
|
||||
|
||||
// -- uint16 value
|
||||
// -- uint32 value
|
||||
type uint32Value uint32
|
||||
|
||||
func newUint32Value(val uint32, p *uint32) *uint32Value {
|
||||
*p = val
|
||||
return (*uint32Value)(p)
|
||||
}
|
||||
func (i *uint32Value) String() string { return fmt.Sprintf("%d", *i) }
|
||||
|
||||
func (i *uint32Value) Set(s string) error {
|
||||
v, err := strconv.ParseUint(s, 0, 32)
|
||||
*i = uint32Value(v)
|
||||
|
@ -23,6 +20,8 @@ func (i *uint32Value) Type() string {
|
|||
return "uint32"
|
||||
}
|
||||
|
||||
func (i *uint32Value) String() string { return strconv.FormatUint(uint64(*i), 10) }
|
||||
|
||||
func uint32Conv(sval string) (interface{}, error) {
|
||||
v, err := strconv.ParseUint(sval, 0, 32)
|
||||
if err != nil {
|
||||
|
|
7
vendor/github.com/spf13/pflag/uint64.go
generated
vendored
7
vendor/github.com/spf13/pflag/uint64.go
generated
vendored
|
@ -1,9 +1,6 @@
|
|||
package pflag
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strconv"
|
||||
)
|
||||
import "strconv"
|
||||
|
||||
// -- uint64 Value
|
||||
type uint64Value uint64
|
||||
|
@ -23,7 +20,7 @@ func (i *uint64Value) Type() string {
|
|||
return "uint64"
|
||||
}
|
||||
|
||||
func (i *uint64Value) String() string { return fmt.Sprintf("%v", *i) }
|
||||
func (i *uint64Value) String() string { return strconv.FormatUint(uint64(*i), 10) }
|
||||
|
||||
func uint64Conv(sval string) (interface{}, error) {
|
||||
v, err := strconv.ParseUint(sval, 0, 64)
|
||||
|
|
7
vendor/github.com/spf13/pflag/uint8.go
generated
vendored
7
vendor/github.com/spf13/pflag/uint8.go
generated
vendored
|
@ -1,9 +1,6 @@
|
|||
package pflag
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strconv"
|
||||
)
|
||||
import "strconv"
|
||||
|
||||
// -- uint8 Value
|
||||
type uint8Value uint8
|
||||
|
@ -23,7 +20,7 @@ func (i *uint8Value) Type() string {
|
|||
return "uint8"
|
||||
}
|
||||
|
||||
func (i *uint8Value) String() string { return fmt.Sprintf("%v", *i) }
|
||||
func (i *uint8Value) String() string { return strconv.FormatUint(uint64(*i), 10) }
|
||||
|
||||
func uint8Conv(sval string) (interface{}, error) {
|
||||
v, err := strconv.ParseUint(sval, 0, 8)
|
||||
|
|
126
vendor/github.com/spf13/pflag/uint_slice.go
generated
vendored
Normal file
126
vendor/github.com/spf13/pflag/uint_slice.go
generated
vendored
Normal file
|
@ -0,0 +1,126 @@
|
|||
package pflag
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// -- uintSlice Value
|
||||
type uintSliceValue struct {
|
||||
value *[]uint
|
||||
changed bool
|
||||
}
|
||||
|
||||
func newUintSliceValue(val []uint, p *[]uint) *uintSliceValue {
|
||||
uisv := new(uintSliceValue)
|
||||
uisv.value = p
|
||||
*uisv.value = val
|
||||
return uisv
|
||||
}
|
||||
|
||||
func (s *uintSliceValue) Set(val string) error {
|
||||
ss := strings.Split(val, ",")
|
||||
out := make([]uint, len(ss))
|
||||
for i, d := range ss {
|
||||
u, err := strconv.ParseUint(d, 10, 0)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
out[i] = uint(u)
|
||||
}
|
||||
if !s.changed {
|
||||
*s.value = out
|
||||
} else {
|
||||
*s.value = append(*s.value, out...)
|
||||
}
|
||||
s.changed = true
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *uintSliceValue) Type() string {
|
||||
return "uintSlice"
|
||||
}
|
||||
|
||||
func (s *uintSliceValue) String() string {
|
||||
out := make([]string, len(*s.value))
|
||||
for i, d := range *s.value {
|
||||
out[i] = fmt.Sprintf("%d", d)
|
||||
}
|
||||
return "[" + strings.Join(out, ",") + "]"
|
||||
}
|
||||
|
||||
func uintSliceConv(val string) (interface{}, error) {
|
||||
val = strings.Trim(val, "[]")
|
||||
// Empty string would cause a slice with one (empty) entry
|
||||
if len(val) == 0 {
|
||||
return []uint{}, nil
|
||||
}
|
||||
ss := strings.Split(val, ",")
|
||||
out := make([]uint, len(ss))
|
||||
for i, d := range ss {
|
||||
u, err := strconv.ParseUint(d, 10, 0)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out[i] = uint(u)
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// GetUintSlice returns the []uint value of a flag with the given name.
|
||||
func (f *FlagSet) GetUintSlice(name string) ([]uint, error) {
|
||||
val, err := f.getFlagType(name, "uintSlice", uintSliceConv)
|
||||
if err != nil {
|
||||
return []uint{}, err
|
||||
}
|
||||
return val.([]uint), nil
|
||||
}
|
||||
|
||||
// UintSliceVar defines a uintSlice flag with specified name, default value, and usage string.
|
||||
// The argument p points to a []uint variable in which to store the value of the flag.
|
||||
func (f *FlagSet) UintSliceVar(p *[]uint, name string, value []uint, usage string) {
|
||||
f.VarP(newUintSliceValue(value, p), name, "", usage)
|
||||
}
|
||||
|
||||
// UintSliceVarP is like UintSliceVar, but accepts a shorthand letter that can be used after a single dash.
|
||||
func (f *FlagSet) UintSliceVarP(p *[]uint, name, shorthand string, value []uint, usage string) {
|
||||
f.VarP(newUintSliceValue(value, p), name, shorthand, usage)
|
||||
}
|
||||
|
||||
// UintSliceVar defines a uint[] flag with specified name, default value, and usage string.
|
||||
// The argument p points to a uint[] variable in which to store the value of the flag.
|
||||
func UintSliceVar(p *[]uint, name string, value []uint, usage string) {
|
||||
CommandLine.VarP(newUintSliceValue(value, p), name, "", usage)
|
||||
}
|
||||
|
||||
// UintSliceVarP is like the UintSliceVar, but accepts a shorthand letter that can be used after a single dash.
|
||||
func UintSliceVarP(p *[]uint, name, shorthand string, value []uint, usage string) {
|
||||
CommandLine.VarP(newUintSliceValue(value, p), name, shorthand, usage)
|
||||
}
|
||||
|
||||
// UintSlice defines a []uint flag with specified name, default value, and usage string.
|
||||
// The return value is the address of a []uint variable that stores the value of the flag.
|
||||
func (f *FlagSet) UintSlice(name string, value []uint, usage string) *[]uint {
|
||||
p := []uint{}
|
||||
f.UintSliceVarP(&p, name, "", value, usage)
|
||||
return &p
|
||||
}
|
||||
|
||||
// UintSliceP is like UintSlice, but accepts a shorthand letter that can be used after a single dash.
|
||||
func (f *FlagSet) UintSliceP(name, shorthand string, value []uint, usage string) *[]uint {
|
||||
p := []uint{}
|
||||
f.UintSliceVarP(&p, name, shorthand, value, usage)
|
||||
return &p
|
||||
}
|
||||
|
||||
// UintSlice defines a []uint flag with specified name, default value, and usage string.
|
||||
// The return value is the address of a []uint variable that stores the value of the flag.
|
||||
func UintSlice(name string, value []uint, usage string) *[]uint {
|
||||
return CommandLine.UintSliceP(name, "", value, usage)
|
||||
}
|
||||
|
||||
// UintSliceP is like UintSlice, but accepts a shorthand letter that can be used after a single dash.
|
||||
func UintSliceP(name, shorthand string, value []uint, usage string) *[]uint {
|
||||
return CommandLine.UintSliceP(name, shorthand, value, usage)
|
||||
}
|
69
vendor/github.com/spf13/pflag/verify/all.sh
generated
vendored
69
vendor/github.com/spf13/pflag/verify/all.sh
generated
vendored
|
@ -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
generated
vendored
19
vendor/github.com/spf13/pflag/verify/gofmt.sh
generated
vendored
|
@ -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
generated
vendored
15
vendor/github.com/spf13/pflag/verify/golint.sh
generated
vendored
|
@ -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
|
35
vendor/github.com/spf13/viper/README.md
generated
vendored
35
vendor/github.com/spf13/viper/README.md
generated
vendored
|
@ -10,9 +10,9 @@ Many Go projects are built using Viper including:
|
|||
* [Nanobox](https://github.com/nanobox-io/nanobox)/[Nanopack](https://github.com/nanopack)
|
||||
* [Docker Notary](https://github.com/docker/Notary)
|
||||
* [BloomApi](https://www.bloomapi.com/)
|
||||
* [DOIt](https://github.com/bryanl/doit)
|
||||
* [doctl](https://github.com/digitalocean/doctl)
|
||||
|
||||
[](https://travis-ci.org/spf13/viper) [](https://gitter.im/spf13/viper?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
|
||||
[](https://travis-ci.org/spf13/viper) [](https://gitter.im/spf13/viper?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) [](https://godoc.org/github.com/spf13/viper)
|
||||
|
||||
|
||||
## What is Viper?
|
||||
|
@ -110,7 +110,7 @@ Gone are the days of needing to restart a server to have a config take effect,
|
|||
viper powered applications can read an update to a config file while running and
|
||||
not miss a beat.
|
||||
|
||||
Simply tell the viper instance to watchConfig.
|
||||
Simply tell the viper instance to watchConfig.
|
||||
Optionally you can provide a function for Viper to run each time a change occurs.
|
||||
|
||||
**Make sure you add all of the configPaths prior to calling `WatchConfig()`**
|
||||
|
@ -277,10 +277,10 @@ Viper provides two Go interfaces to bind other flag systems if you don't use `Pf
|
|||
|
||||
```go
|
||||
type myFlag struct {}
|
||||
func (f myFlag) IsChanged() { return false }
|
||||
func (f myFlag) Name() { return "my-flag-name" }
|
||||
func (f myFlag) ValueString() { return "my-flag-value" }
|
||||
func (f myFlag) ValueType() { return "string" }
|
||||
func (f myFlag) HasChanged() bool { return false }
|
||||
func (f myFlag) Name() string { return "my-flag-name" }
|
||||
func (f myFlag) ValueString() string { return "my-flag-value" }
|
||||
func (f myFlag) ValueType() string { return "string" }
|
||||
```
|
||||
|
||||
Once your flag implements this interface, you can simply tell Viper to bind it:
|
||||
|
@ -298,7 +298,7 @@ type myFlagSet struct {
|
|||
|
||||
func (f myFlagSet) VisitAll(fn func(FlagValue)) {
|
||||
for _, flag := range flags {
|
||||
fn(flag)
|
||||
fn(flag)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
@ -458,16 +458,17 @@ Viper can access a nested field by passing a `.` delimited path of keys:
|
|||
GetString("datastore.metric.host") // (returns "127.0.0.1")
|
||||
```
|
||||
|
||||
This obeys the precedence rules established above; the search for the root key
|
||||
(in this example, `datastore`) will cascade through the remaining configuration
|
||||
registries until found. The search for the sub-keys (`metric` and `host`),
|
||||
however, will not.
|
||||
This obeys the precedence rules established above; the search for the path
|
||||
will cascade through the remaining configuration registries until found.
|
||||
|
||||
For example, if the `metric` key was not defined in the configuration loaded
|
||||
from file, but was defined in the defaults, Viper would return the zero value.
|
||||
For example, given this configuration file, both `datastore.metric.host` and
|
||||
`datastore.metric.port` are already defined (and may be overridden). If in addition
|
||||
`datastore.metric.protocol` was defined in the defaults, Viper would also find it.
|
||||
|
||||
On the other hand, if the primary key was not defined, Viper would go through
|
||||
the remaining registries looking for it.
|
||||
However, if `datastore.metric` was overridden (by a flag, an environment variable,
|
||||
the `Set()` method, …) with an immediate value, then all sub-keys of
|
||||
`datastore.metric` become undefined, they are “shadowed” by the higher-priority
|
||||
configuration level.
|
||||
|
||||
Lastly, if there exists a key that matches the delimited key path, its value
|
||||
will be returned instead. E.g.
|
||||
|
@ -491,7 +492,7 @@ will be returned instead. E.g.
|
|||
}
|
||||
}
|
||||
|
||||
GetString("datastore.metric.host") //returns "0.0.0.0"
|
||||
GetString("datastore.metric.host") // returns "0.0.0.0"
|
||||
```
|
||||
|
||||
### Extract sub-tree
|
||||
|
|
66
vendor/github.com/spf13/viper/flags_test.go
generated
vendored
66
vendor/github.com/spf13/viper/flags_test.go
generated
vendored
|
@ -1,66 +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"))
|
||||
|
||||
}
|
1
vendor/github.com/spf13/viper/nohup.out
generated
vendored
Normal file
1
vendor/github.com/spf13/viper/nohup.out
generated
vendored
Normal file
|
@ -0,0 +1 @@
|
|||
QProcess::start: Process is already running
|
77
vendor/github.com/spf13/viper/remote/remote.go
generated
vendored
77
vendor/github.com/spf13/viper/remote/remote.go
generated
vendored
|
@ -1,77 +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"
|
||||
"github.com/spf13/viper"
|
||||
crypt "github.com/xordataexchange/crypt/config"
|
||||
"io"
|
||||
"os"
|
||||
)
|
||||
|
||||
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 := <-cm.Watch(rp.Path(), nil)
|
||||
err = resp.Error
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return bytes.NewReader(resp.Value), nil
|
||||
}
|
||||
|
||||
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{}
|
||||
}
|
129
vendor/github.com/spf13/viper/util.go
generated
vendored
129
vendor/github.com/spf13/viper/util.go
generated
vendored
|
@ -21,31 +21,76 @@ import (
|
|||
"strings"
|
||||
"unicode"
|
||||
|
||||
"github.com/BurntSushi/toml"
|
||||
"github.com/hashicorp/hcl"
|
||||
"github.com/magiconair/properties"
|
||||
toml "github.com/pelletier/go-toml"
|
||||
"github.com/spf13/cast"
|
||||
jww "github.com/spf13/jwalterweatherman"
|
||||
"gopkg.in/yaml.v2"
|
||||
)
|
||||
|
||||
// Denotes failing to parse configuration file.
|
||||
// ConfigParseError denotes failing to parse configuration file.
|
||||
type ConfigParseError struct {
|
||||
err error
|
||||
}
|
||||
|
||||
// Returns the formatted configuration error.
|
||||
// Error returns the formatted configuration error.
|
||||
func (pe ConfigParseError) Error() string {
|
||||
return fmt.Sprintf("While parsing config: %s", pe.err.Error())
|
||||
}
|
||||
|
||||
// toCaseInsensitiveValue checks if the value is a map;
|
||||
// if so, create a copy and lower-case the keys recursively.
|
||||
func toCaseInsensitiveValue(value interface{}) interface{} {
|
||||
switch v := value.(type) {
|
||||
case map[interface{}]interface{}:
|
||||
value = copyAndInsensitiviseMap(cast.ToStringMap(v))
|
||||
case map[string]interface{}:
|
||||
value = copyAndInsensitiviseMap(v)
|
||||
}
|
||||
|
||||
return value
|
||||
}
|
||||
|
||||
// copyAndInsensitiviseMap behaves like insensitiviseMap, but creates a copy of
|
||||
// any map it makes case insensitive.
|
||||
func copyAndInsensitiviseMap(m map[string]interface{}) map[string]interface{} {
|
||||
nm := make(map[string]interface{})
|
||||
|
||||
for key, val := range m {
|
||||
lkey := strings.ToLower(key)
|
||||
switch v := val.(type) {
|
||||
case map[interface{}]interface{}:
|
||||
nm[lkey] = copyAndInsensitiviseMap(cast.ToStringMap(v))
|
||||
case map[string]interface{}:
|
||||
nm[lkey] = copyAndInsensitiviseMap(v)
|
||||
default:
|
||||
nm[lkey] = v
|
||||
}
|
||||
}
|
||||
|
||||
return nm
|
||||
}
|
||||
|
||||
func insensitiviseMap(m map[string]interface{}) {
|
||||
for key, val := range m {
|
||||
switch val.(type) {
|
||||
case map[interface{}]interface{}:
|
||||
// nested map: cast and recursively insensitivise
|
||||
val = cast.ToStringMap(val)
|
||||
insensitiviseMap(val.(map[string]interface{}))
|
||||
case map[string]interface{}:
|
||||
// nested map: recursively insensitivise
|
||||
insensitiviseMap(val.(map[string]interface{}))
|
||||
}
|
||||
|
||||
lower := strings.ToLower(key)
|
||||
if key != lower {
|
||||
// remove old key (not lower-cased)
|
||||
delete(m, key)
|
||||
m[lower] = val
|
||||
}
|
||||
// update map
|
||||
m[lower] = val
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -68,16 +113,16 @@ func absPathify(inPath string) string {
|
|||
p, err := filepath.Abs(inPath)
|
||||
if err == nil {
|
||||
return filepath.Clean(p)
|
||||
} else {
|
||||
jww.ERROR.Println("Couldn't discover absolute path")
|
||||
jww.ERROR.Println(err)
|
||||
}
|
||||
|
||||
jww.ERROR.Println("Couldn't discover absolute path")
|
||||
jww.ERROR.Println(err)
|
||||
return ""
|
||||
}
|
||||
|
||||
// Check if File / Directory Exists
|
||||
func exists(path string) (bool, error) {
|
||||
_, err := os.Stat(path)
|
||||
_, err := v.fs.Stat(path)
|
||||
if err == nil {
|
||||
return true, nil
|
||||
}
|
||||
|
@ -107,29 +152,6 @@ func userHomeDir() string {
|
|||
return os.Getenv("HOME")
|
||||
}
|
||||
|
||||
func findCWD() (string, error) {
|
||||
serverFile, err := filepath.Abs(os.Args[0])
|
||||
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("Can't get absolute path for executable: %v", err)
|
||||
}
|
||||
|
||||
path := filepath.Dir(serverFile)
|
||||
realFile, err := filepath.EvalSymlinks(serverFile)
|
||||
|
||||
if err != nil {
|
||||
if _, err = os.Stat(serverFile + ".exe"); err == nil {
|
||||
realFile = filepath.Clean(serverFile + ".exe")
|
||||
}
|
||||
}
|
||||
|
||||
if err == nil && realFile != serverFile {
|
||||
path = filepath.Dir(realFile)
|
||||
}
|
||||
|
||||
return path, nil
|
||||
}
|
||||
|
||||
func unmarshallConfigReader(in io.Reader, c map[string]interface{}, configType string) error {
|
||||
buf := new(bytes.Buffer)
|
||||
buf.ReadFrom(in)
|
||||
|
@ -155,9 +177,14 @@ func unmarshallConfigReader(in io.Reader, c map[string]interface{}, configType s
|
|||
}
|
||||
|
||||
case "toml":
|
||||
if _, err := toml.Decode(buf.String(), &c); err != nil {
|
||||
tree, err := toml.LoadReader(buf)
|
||||
if err != nil {
|
||||
return ConfigParseError{err}
|
||||
}
|
||||
tmap := tree.ToMap()
|
||||
for k, v := range tmap {
|
||||
c[k] = v
|
||||
}
|
||||
|
||||
case "properties", "props", "prop":
|
||||
var p *properties.Properties
|
||||
|
@ -167,7 +194,12 @@ func unmarshallConfigReader(in io.Reader, c map[string]interface{}, configType s
|
|||
}
|
||||
for _, key := range p.Keys() {
|
||||
value, _ := p.Get(key)
|
||||
c[key] = value
|
||||
// recursively build nested maps
|
||||
path := strings.Split(key, ".")
|
||||
lastKey := strings.ToLower(path[len(path)-1])
|
||||
deepestMap := deepSearch(c, path[0:len(path)-1])
|
||||
// set innermost value
|
||||
deepestMap[lastKey] = value
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -217,3 +249,34 @@ func parseSizeInBytes(sizeStr string) uint {
|
|||
|
||||
return safeMul(uint(size), multiplier)
|
||||
}
|
||||
|
||||
// deepSearch scans deep maps, following the key indexes listed in the
|
||||
// sequence "path".
|
||||
// The last value is expected to be another map, and is returned.
|
||||
//
|
||||
// In case intermediate keys do not exist, or map to a non-map value,
|
||||
// a new map is created and inserted, and the search continues from there:
|
||||
// the initial map "m" may be modified!
|
||||
func deepSearch(m map[string]interface{}, path []string) map[string]interface{} {
|
||||
for _, k := range path {
|
||||
m2, ok := m[k]
|
||||
if !ok {
|
||||
// intermediate key does not exist
|
||||
// => create it and continue from there
|
||||
m3 := make(map[string]interface{})
|
||||
m[k] = m3
|
||||
m = m3
|
||||
continue
|
||||
}
|
||||
m3, ok := m2.(map[string]interface{})
|
||||
if !ok {
|
||||
// intermediate key is a value
|
||||
// => replace with a new map
|
||||
m3 = make(map[string]interface{})
|
||||
m[k] = m3
|
||||
}
|
||||
// continue search from here
|
||||
m = m3
|
||||
}
|
||||
return m
|
||||
}
|
||||
|
|
852
vendor/github.com/spf13/viper/viper.go
generated
vendored
852
vendor/github.com/spf13/viper/viper.go
generated
vendored
File diff suppressed because it is too large
Load diff
Some files were not shown because too many files have changed in this diff Show more
Loading…
Add table
Add a link
Reference in a new issue