Add cobra, move the server code into its own package
This commit is contained in:
parent
bb729a5c8e
commit
e63c012aad
12
Godeps/Godeps.json
generated
12
Godeps/Godeps.json
generated
@ -31,6 +31,10 @@
|
||||
"ImportPath": "github.com/golang/protobuf/proto",
|
||||
"Rev": "655cdfa588ea190e901bc5590e65d5621688847c"
|
||||
},
|
||||
{
|
||||
"ImportPath": "github.com/inconshreveable/mousetrap",
|
||||
"Rev": "76626ae9c91c4f2a10f34cad8ce83ea42c93bb75"
|
||||
},
|
||||
{
|
||||
"ImportPath": "github.com/julienschmidt/httprouter",
|
||||
"Rev": "b428fda53bb0a764fea9c76c9413512eda291dec"
|
||||
@ -39,6 +43,14 @@
|
||||
"ImportPath": "github.com/ryszard/goskiplist/skiplist",
|
||||
"Rev": "2dfbae5fcf46374f166f8969cb07e167f1be6273"
|
||||
},
|
||||
{
|
||||
"ImportPath": "github.com/spf13/cobra",
|
||||
"Rev": "3ee9552eebbb5db27cb81abcae66c6f1430cad29"
|
||||
},
|
||||
{
|
||||
"ImportPath": "github.com/spf13/pflag",
|
||||
"Rev": "32bfad653e29e893e4ed3812fdc0294a05126c08"
|
||||
},
|
||||
{
|
||||
"ImportPath": "github.com/steveyen/gtreap",
|
||||
"Rev": "72cd76f34c91f8d64a031af97b499e4a0b1a6e0c"
|
||||
|
13
Godeps/_workspace/src/github.com/inconshreveable/mousetrap/LICENSE
generated
vendored
Normal file
13
Godeps/_workspace/src/github.com/inconshreveable/mousetrap/LICENSE
generated
vendored
Normal file
@ -0,0 +1,13 @@
|
||||
Copyright 2014 Alan Shreve
|
||||
|
||||
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.
|
23
Godeps/_workspace/src/github.com/inconshreveable/mousetrap/README.md
generated
vendored
Normal file
23
Godeps/_workspace/src/github.com/inconshreveable/mousetrap/README.md
generated
vendored
Normal file
@ -0,0 +1,23 @@
|
||||
# mousetrap
|
||||
|
||||
mousetrap is a tiny library that answers a single question.
|
||||
|
||||
On a Windows machine, was the process invoked by someone double clicking on
|
||||
the executable file while browsing in explorer?
|
||||
|
||||
### Motivation
|
||||
|
||||
Windows developers unfamiliar with command line tools will often "double-click"
|
||||
the executable for a tool. Because most CLI tools print the help and then exit
|
||||
when invoked without arguments, this is often very frustrating for those users.
|
||||
|
||||
mousetrap provides a way to detect these invocations so that you can provide
|
||||
more helpful behavior and instructions on how to run the CLI tool. To see what
|
||||
this looks like, both from an organizational and a technical perspective, see
|
||||
https://inconshreveable.com/09-09-2014/sweat-the-small-stuff/
|
||||
|
||||
### The interface
|
||||
|
||||
The library exposes a single interface:
|
||||
|
||||
func StartedByExplorer() (bool)
|
15
Godeps/_workspace/src/github.com/inconshreveable/mousetrap/trap_others.go
generated
vendored
Normal file
15
Godeps/_workspace/src/github.com/inconshreveable/mousetrap/trap_others.go
generated
vendored
Normal file
@ -0,0 +1,15 @@
|
||||
// +build !windows
|
||||
|
||||
package mousetrap
|
||||
|
||||
// StartedByExplorer returns true if the program was invoked by the user
|
||||
// double-clicking on the executable from explorer.exe
|
||||
//
|
||||
// It is conservative and returns false if any of the internal calls fail.
|
||||
// It does not guarantee that the program was run from a terminal. It only can tell you
|
||||
// whether it was launched from explorer.exe
|
||||
//
|
||||
// On non-Windows platforms, it always returns false.
|
||||
func StartedByExplorer() bool {
|
||||
return false
|
||||
}
|
98
Godeps/_workspace/src/github.com/inconshreveable/mousetrap/trap_windows.go
generated
vendored
Normal file
98
Godeps/_workspace/src/github.com/inconshreveable/mousetrap/trap_windows.go
generated
vendored
Normal file
@ -0,0 +1,98 @@
|
||||
// +build windows
|
||||
// +build !go1.4
|
||||
|
||||
package mousetrap
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"syscall"
|
||||
"unsafe"
|
||||
)
|
||||
|
||||
const (
|
||||
// defined by the Win32 API
|
||||
th32cs_snapprocess uintptr = 0x2
|
||||
)
|
||||
|
||||
var (
|
||||
kernel = syscall.MustLoadDLL("kernel32.dll")
|
||||
CreateToolhelp32Snapshot = kernel.MustFindProc("CreateToolhelp32Snapshot")
|
||||
Process32First = kernel.MustFindProc("Process32FirstW")
|
||||
Process32Next = kernel.MustFindProc("Process32NextW")
|
||||
)
|
||||
|
||||
// ProcessEntry32 structure defined by the Win32 API
|
||||
type processEntry32 struct {
|
||||
dwSize uint32
|
||||
cntUsage uint32
|
||||
th32ProcessID uint32
|
||||
th32DefaultHeapID int
|
||||
th32ModuleID uint32
|
||||
cntThreads uint32
|
||||
th32ParentProcessID uint32
|
||||
pcPriClassBase int32
|
||||
dwFlags uint32
|
||||
szExeFile [syscall.MAX_PATH]uint16
|
||||
}
|
||||
|
||||
func getProcessEntry(pid int) (pe *processEntry32, err error) {
|
||||
snapshot, _, e1 := CreateToolhelp32Snapshot.Call(th32cs_snapprocess, uintptr(0))
|
||||
if snapshot == uintptr(syscall.InvalidHandle) {
|
||||
err = fmt.Errorf("CreateToolhelp32Snapshot: %v", e1)
|
||||
return
|
||||
}
|
||||
defer syscall.CloseHandle(syscall.Handle(snapshot))
|
||||
|
||||
var processEntry processEntry32
|
||||
processEntry.dwSize = uint32(unsafe.Sizeof(processEntry))
|
||||
ok, _, e1 := Process32First.Call(snapshot, uintptr(unsafe.Pointer(&processEntry)))
|
||||
if ok == 0 {
|
||||
err = fmt.Errorf("Process32First: %v", e1)
|
||||
return
|
||||
}
|
||||
|
||||
for {
|
||||
if processEntry.th32ProcessID == uint32(pid) {
|
||||
pe = &processEntry
|
||||
return
|
||||
}
|
||||
|
||||
ok, _, e1 = Process32Next.Call(snapshot, uintptr(unsafe.Pointer(&processEntry)))
|
||||
if ok == 0 {
|
||||
err = fmt.Errorf("Process32Next: %v", e1)
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func getppid() (pid int, err error) {
|
||||
pe, err := getProcessEntry(os.Getpid())
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
|
||||
pid = int(pe.th32ParentProcessID)
|
||||
return
|
||||
}
|
||||
|
||||
// StartedByExplorer returns true if the program was invoked by the user double-clicking
|
||||
// on the executable from explorer.exe
|
||||
//
|
||||
// It is conservative and returns false if any of the internal calls fail.
|
||||
// It does not guarantee that the program was run from a terminal. It only can tell you
|
||||
// whether it was launched from explorer.exe
|
||||
func StartedByExplorer() bool {
|
||||
ppid, err := getppid()
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
|
||||
pe, err := getProcessEntry(ppid)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
|
||||
name := syscall.UTF16ToString(pe.szExeFile[:])
|
||||
return name == "explorer.exe"
|
||||
}
|
46
Godeps/_workspace/src/github.com/inconshreveable/mousetrap/trap_windows_1.4.go
generated
vendored
Normal file
46
Godeps/_workspace/src/github.com/inconshreveable/mousetrap/trap_windows_1.4.go
generated
vendored
Normal file
@ -0,0 +1,46 @@
|
||||
// +build windows
|
||||
// +build go1.4
|
||||
|
||||
package mousetrap
|
||||
|
||||
import (
|
||||
"os"
|
||||
"syscall"
|
||||
"unsafe"
|
||||
)
|
||||
|
||||
func getProcessEntry(pid int) (*syscall.ProcessEntry32, error) {
|
||||
snapshot, err := syscall.CreateToolhelp32Snapshot(syscall.TH32CS_SNAPPROCESS, 0)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer syscall.CloseHandle(snapshot)
|
||||
var procEntry syscall.ProcessEntry32
|
||||
procEntry.Size = uint32(unsafe.Sizeof(procEntry))
|
||||
if err = syscall.Process32First(snapshot, &procEntry); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for {
|
||||
if procEntry.ProcessID == uint32(pid) {
|
||||
return &procEntry, nil
|
||||
}
|
||||
err = syscall.Process32Next(snapshot, &procEntry)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// StartedByExplorer returns true if the program was invoked by the user double-clicking
|
||||
// on the executable from explorer.exe
|
||||
//
|
||||
// It is conservative and returns false if any of the internal calls fail.
|
||||
// It does not guarantee that the program was run from a terminal. It only can tell you
|
||||
// whether it was launched from explorer.exe
|
||||
func StartedByExplorer() bool {
|
||||
pe, err := getProcessEntry(os.Getppid())
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
return "explorer.exe" == syscall.UTF16ToString(pe.ExeFile[:])
|
||||
}
|
24
Godeps/_workspace/src/github.com/spf13/cobra/.gitignore
generated
vendored
Normal file
24
Godeps/_workspace/src/github.com/spf13/cobra/.gitignore
generated
vendored
Normal file
@ -0,0 +1,24 @@
|
||||
# Compiled Object files, Static and Dynamic libs (Shared Objects)
|
||||
*.o
|
||||
*.a
|
||||
*.so
|
||||
|
||||
# Folders
|
||||
_obj
|
||||
_test
|
||||
|
||||
# Architecture specific extensions/prefixes
|
||||
*.[568vq]
|
||||
[568vq].out
|
||||
|
||||
*.cgo1.go
|
||||
*.cgo2.c
|
||||
_cgo_defun.c
|
||||
_cgo_gotypes.go
|
||||
_cgo_export.*
|
||||
|
||||
_testmain.go
|
||||
|
||||
*.exe
|
||||
|
||||
cobra.test
|
8
Godeps/_workspace/src/github.com/spf13/cobra/.travis.yml
generated
vendored
Normal file
8
Godeps/_workspace/src/github.com/spf13/cobra/.travis.yml
generated
vendored
Normal file
@ -0,0 +1,8 @@
|
||||
language: go
|
||||
go:
|
||||
- 1.3
|
||||
- 1.4.2
|
||||
- tip
|
||||
script:
|
||||
- go test ./...
|
||||
- go build
|
174
Godeps/_workspace/src/github.com/spf13/cobra/LICENSE.txt
generated
vendored
Normal file
174
Godeps/_workspace/src/github.com/spf13/cobra/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.
|
485
Godeps/_workspace/src/github.com/spf13/cobra/README.md
generated
vendored
Normal file
485
Godeps/_workspace/src/github.com/spf13/cobra/README.md
generated
vendored
Normal file
@ -0,0 +1,485 @@
|
||||
# Cobra
|
||||
|
||||
A Commander for modern go CLI interactions
|
||||
|
||||
[![Build Status](https://travis-ci.org/spf13/cobra.svg)](https://travis-ci.org/spf13/cobra)
|
||||
|
||||
## Overview
|
||||
|
||||
Cobra is a commander providing a simple interface to create powerful modern CLI
|
||||
interfaces similar to git & go tools. In addition to providing an interface, Cobra
|
||||
simultaneously provides a controller to organize your application code.
|
||||
|
||||
Inspired by go, go-Commander, gh and subcommand, Cobra improves on these by
|
||||
providing **fully posix compliant flags** (including short & long versions),
|
||||
**nesting commands**, and the ability to **define your own help and usage** for any or
|
||||
all commands.
|
||||
|
||||
Cobra has an exceptionally clean interface and simple design without needless
|
||||
constructors or initialization methods.
|
||||
|
||||
Applications built with Cobra commands are designed to be as user friendly as
|
||||
possible. Flags can be placed before or after the command (as long as a
|
||||
confusing space isn’t provided). Both short and long flags can be used. A
|
||||
command need not even be fully typed. The shortest unambiguous string will
|
||||
suffice. Help is automatically generated and available for the application or
|
||||
for a specific command using either the help command or the --help flag.
|
||||
|
||||
## Concepts
|
||||
|
||||
Cobra is built on a structure of commands & flags.
|
||||
|
||||
**Commands** represent actions and **Flags** are modifiers for those actions.
|
||||
|
||||
In the following example 'server' is a command and 'port' is a flag.
|
||||
|
||||
hugo server --port=1313
|
||||
|
||||
### Commands
|
||||
|
||||
Command is the central point of the application. Each interaction that
|
||||
the application supports will be contained in a Command. A command can
|
||||
have children commands and optionally run an action.
|
||||
|
||||
In the example above 'server' is the command
|
||||
|
||||
A Command has the following structure:
|
||||
|
||||
type Command struct {
|
||||
Use string // The one-line usage message.
|
||||
Short string // The short description shown in the 'help' output.
|
||||
Long string // The long message shown in the 'help <this-command>' output.
|
||||
Run func(cmd *Command, args []string) // Run runs the command.
|
||||
}
|
||||
|
||||
### Flags
|
||||
|
||||
A Flag is a way to modify the behavior of an command. Cobra supports
|
||||
fully posix compliant flags as well as the go flag package.
|
||||
A Cobra command can define flags that persist through to children commands
|
||||
and flags that are only available to that command.
|
||||
|
||||
In the example above 'port' is the flag.
|
||||
|
||||
Flag functionality is provided by the [pflag
|
||||
libary](https://github.com/ogier/pflag), a fork of the flag standard library
|
||||
which maintains the same interface while adding posix compliance.
|
||||
|
||||
## Usage
|
||||
|
||||
Cobra works by creating a set of commands and then organizing them into a tree.
|
||||
The tree defines the structure of the application.
|
||||
|
||||
Once each command is defined with it's corresponding flags, then the
|
||||
tree is assigned to the commander which is finally executed.
|
||||
|
||||
### Installing
|
||||
Using Cobra is easy. First use go get to install the latest version
|
||||
of the library.
|
||||
|
||||
$ go get github.com/spf13/cobra
|
||||
|
||||
Next include cobra in your application.
|
||||
|
||||
import "github.com/spf13/cobra"
|
||||
|
||||
### Create the root command
|
||||
|
||||
The root command represents your binary itself.
|
||||
|
||||
Cobra doesn't require any special constructors. Simply create your commands.
|
||||
|
||||
var HugoCmd = &cobra.Command{
|
||||
Use: "hugo",
|
||||
Short: "Hugo is a very fast static site generator",
|
||||
Long: `A Fast and Flexible Static Site Generator built with
|
||||
love by spf13 and friends in Go.
|
||||
Complete documentation is available at http://hugo.spf13.com`,
|
||||
Run: func(cmd *cobra.Command, args []string) {
|
||||
// Do Stuff Here
|
||||
},
|
||||
}
|
||||
|
||||
### Create additional commands
|
||||
|
||||
Additional commands can be defined.
|
||||
|
||||
var versionCmd = &cobra.Command{
|
||||
Use: "version",
|
||||
Short: "Print the version number of Hugo",
|
||||
Long: `All software has versions. This is Hugo's`,
|
||||
Run: func(cmd *cobra.Command, args []string) {
|
||||
fmt.Println("Hugo Static Site Generator v0.9 -- HEAD")
|
||||
},
|
||||
}
|
||||
|
||||
### Attach command to its parent
|
||||
In this example we are attaching it to the root, but commands can be attached at any level.
|
||||
|
||||
HugoCmd.AddCommand(versionCmd)
|
||||
|
||||
### Assign flags to a command
|
||||
|
||||
Since the flags are defined and used in different locations, we need to
|
||||
define a variable outside with the correct scope to assign the flag to
|
||||
work with.
|
||||
|
||||
var Verbose bool
|
||||
var Source string
|
||||
|
||||
There are two different approaches to assign a flag.
|
||||
|
||||
#### Persistent Flags
|
||||
|
||||
A flag can be 'persistent' meaning that this flag will be available to the
|
||||
command it's assigned to as well as every command under that command. For
|
||||
global flags assign a flag as a persistent flag on the root.
|
||||
|
||||
HugoCmd.PersistentFlags().BoolVarP(&Verbose, "verbose", "v", false, "verbose output")
|
||||
|
||||
#### Local Flags
|
||||
|
||||
A flag can also be assigned locally which will only apply to that specific command.
|
||||
|
||||
HugoCmd.Flags().StringVarP(&Source, "source", "s", "", "Source directory to read from")
|
||||
|
||||
### Remove a command from its parent
|
||||
|
||||
Removing a command is not a common action in simple programs but it allows 3rd parties to customize an existing command tree.
|
||||
|
||||
In this example, we remove the existing `VersionCmd` command of an existing root command, and we replace it by our own version.
|
||||
|
||||
mainlib.RootCmd.RemoveCommand(mainlib.VersionCmd)
|
||||
mainlib.RootCmd.AddCommand(versionCmd)
|
||||
|
||||
### Once all commands and flags are defined, Execute the commands
|
||||
|
||||
Execute should be run on the root for clarity, though it can be called on any command.
|
||||
|
||||
HugoCmd.Execute()
|
||||
|
||||
## Example
|
||||
|
||||
In the example below we have defined three commands. Two are at the top level
|
||||
and one (cmdTimes) is a child of one of the top commands. In this case the root
|
||||
is not executable meaning that a subcommand is required. This is accomplished
|
||||
by not providing a 'Run' for the 'rootCmd'.
|
||||
|
||||
We have only defined one flag for a single command.
|
||||
|
||||
More documentation about flags is available at https://github.com/spf13/pflag
|
||||
|
||||
import(
|
||||
"github.com/spf13/cobra"
|
||||
"fmt"
|
||||
"strings"
|
||||
)
|
||||
|
||||
func main() {
|
||||
|
||||
var echoTimes int
|
||||
|
||||
var cmdPrint = &cobra.Command{
|
||||
Use: "print [string to print]",
|
||||
Short: "Print anything to the screen",
|
||||
Long: `print is for printing anything back to the screen.
|
||||
For many years people have printed back to the screen.
|
||||
`,
|
||||
Run: func(cmd *cobra.Command, args []string) {
|
||||
fmt.Println("Print: " + strings.Join(args, " "))
|
||||
},
|
||||
}
|
||||
|
||||
var cmdEcho = &cobra.Command{
|
||||
Use: "echo [string to echo]",
|
||||
Short: "Echo anything to the screen",
|
||||
Long: `echo is for echoing anything back.
|
||||
Echo works a lot like print, except it has a child command.
|
||||
`,
|
||||
Run: func(cmd *cobra.Command, args []string) {
|
||||
fmt.Println("Print: " + strings.Join(args, " "))
|
||||
},
|
||||
}
|
||||
|
||||
var cmdTimes = &cobra.Command{
|
||||
Use: "times [# times] [string to echo]",
|
||||
Short: "Echo anything to the screen more times",
|
||||
Long: `echo things multiple times back to the user by providing
|
||||
a count and a string.`,
|
||||
Run: func(cmd *cobra.Command, args []string) {
|
||||
for i:=0; i < echoTimes; i++ {
|
||||
fmt.Println("Echo: " + strings.Join(args, " "))
|
||||
}
|
||||
},
|
||||
}
|
||||
|
||||
cmdTimes.Flags().IntVarP(&echoTimes, "times", "t", 1, "times to echo the input")
|
||||
|
||||
var rootCmd = &cobra.Command{Use: "app"}
|
||||
rootCmd.AddCommand(cmdPrint, cmdEcho)
|
||||
cmdEcho.AddCommand(cmdTimes)
|
||||
rootCmd.Execute()
|
||||
}
|
||||
|
||||
For a more complete example of a larger application, please checkout [Hugo](http://hugo.spf13.com)
|
||||
|
||||
## The Help Command
|
||||
|
||||
Cobra automatically adds a help command to your application when you have subcommands.
|
||||
This will be called when a user runs 'app help'. Additionally help will also
|
||||
support all other commands as input. Say for instance you have a command called
|
||||
'create' without any additional configuration cobra will work when 'app help
|
||||
create' is called. Every command will automatically have the '--help' flag added.
|
||||
|
||||
### Example
|
||||
|
||||
The following output is automatically generated by cobra. Nothing beyond the
|
||||
command and flag definitions are needed.
|
||||
|
||||
> hugo help
|
||||
|
||||
A Fast and Flexible Static Site Generator built with
|
||||
love by spf13 and friends in Go.
|
||||
|
||||
Complete documentation is available at http://hugo.spf13.com
|
||||
|
||||
Usage:
|
||||
hugo [flags]
|
||||
hugo [command]
|
||||
|
||||
Available Commands:
|
||||
server :: Hugo runs it's own a webserver to render the files
|
||||
version :: Print the version number of Hugo
|
||||
check :: Check content in the source directory
|
||||
benchmark :: Benchmark hugo by building a site a number of times
|
||||
help [command] :: Help about any command
|
||||
|
||||
Available Flags:
|
||||
-b, --base-url="": hostname (and path) to the root eg. http://spf13.com/
|
||||
-D, --build-drafts=false: include content marked as draft
|
||||
--config="": config file (default is path/config.yaml|json|toml)
|
||||
-d, --destination="": filesystem path to write files to
|
||||
-s, --source="": filesystem path to read files relative from
|
||||
--stepAnalysis=false: display memory and timing of different steps of the program
|
||||
--uglyurls=false: if true, use /filename.html instead of /filename/
|
||||
-v, --verbose=false: verbose output
|
||||
-w, --watch=false: watch filesystem for changes and recreate as needed
|
||||
|
||||
Use "hugo help [command]" for more information about that command.
|
||||
|
||||
|
||||
|
||||
Help is just a command like any other. There is no special logic or behavior
|
||||
around it. In fact you can provide your own if you want.
|
||||
|
||||
### Defining your own help
|
||||
|
||||
You can provide your own Help command or you own template for the default command to use.
|
||||
|
||||
The default help command is
|
||||
|
||||
func (c *Command) initHelp() {
|
||||
if c.helpCommand == nil {
|
||||
c.helpCommand = &Command{
|
||||
Use: "help [command]",
|
||||
Short: "Help about any command",
|
||||
Long: `Help provides help for any command in the application.
|
||||
Simply type ` + c.Name() + ` help [path to command] for full details.`,
|
||||
Run: c.HelpFunc(),
|
||||
}
|
||||
}
|
||||
c.AddCommand(c.helpCommand)
|
||||
}
|
||||
|
||||
You can provide your own command, function or template through the following methods.
|
||||
|
||||
command.SetHelpCommand(cmd *Command)
|
||||
|
||||
command.SetHelpFunc(f func(*Command, []string))
|
||||
|
||||
command.SetHelpTemplate(s string)
|
||||
|
||||
The latter two will also apply to any children commands.
|
||||
|
||||
## Usage
|
||||
|
||||
When the user provides an invalid flag or invalid command Cobra responds by
|
||||
showing the user the 'usage'
|
||||
|
||||
### Example
|
||||
You may recognize this from the help above. That's because the default help
|
||||
embeds the usage as part of it's output.
|
||||
|
||||
Usage:
|
||||
hugo [flags]
|
||||
hugo [command]
|
||||
|
||||
Available Commands:
|
||||
server Hugo runs it's own a webserver to render the files
|
||||
version Print the version number of Hugo
|
||||
check Check content in the source directory
|
||||
benchmark Benchmark hugo by building a site a number of times
|
||||
help [command] Help about any command
|
||||
|
||||
Available Flags:
|
||||
-b, --base-url="": hostname (and path) to the root eg. http://spf13.com/
|
||||
-D, --build-drafts=false: include content marked as draft
|
||||
--config="": config file (default is path/config.yaml|json|toml)
|
||||
-d, --destination="": filesystem path to write files to
|
||||
-s, --source="": filesystem path to read files relative from
|
||||
--stepAnalysis=false: display memory and timing of different steps of the program
|
||||
--uglyurls=false: if true, use /filename.html instead of /filename/
|
||||
-v, --verbose=false: verbose output
|
||||
-w, --watch=false: watch filesystem for changes and recreate as needed
|
||||
|
||||
### Defining your own usage
|
||||
You can provide your own usage function or template for cobra to use.
|
||||
|
||||
The default usage function is
|
||||
|
||||
return func(c *Command) error {
|
||||
err := tmpl(c.Out(), c.UsageTemplate(), c)
|
||||
return err
|
||||
}
|
||||
|
||||
Like help the function and template are over ridable through public methods.
|
||||
|
||||
command.SetUsageFunc(f func(*Command) error)
|
||||
|
||||
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`. `PersistendPostRun` 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:
|
||||
|
||||
- `PersistentPreRun`
|
||||
- `PreRun`
|
||||
- `Run`
|
||||
- `PostRun`
|
||||
- `PersistenPostRun`
|
||||
|
||||
And example of two commands which use all of these features is below. When the subcommand in executed it will run the root command's `PersistentPreRun` but not the root command's `PersistentPostRun`
|
||||
|
||||
```go
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
func main() {
|
||||
|
||||
var rootCmd = &cobra.Command{
|
||||
Use: "root [sub]",
|
||||
Short: "My root command",
|
||||
PersistentPreRun: func(cmd *cobra.Command, args []string) {
|
||||
fmt.Printf("Inside rootCmd PersistentPreRun with args: %v\n", args)
|
||||
},
|
||||
PreRun: func(cmd *cobra.Command, args []string) {
|
||||
fmt.Printf("Inside rootCmd PreRun with args: %v\n", args)
|
||||
},
|
||||
Run: func(cmd *cobra.Command, args []string) {
|
||||
fmt.Printf("Inside rootCmd Run with args: %v\n", args)
|
||||
},
|
||||
PostRun: func(cmd *cobra.Command, args []string) {
|
||||
fmt.Printf("Inside rootCmd PostRun with args: %v\n", args)
|
||||
},
|
||||
PersistentPostRun: func(cmd *cobra.Command, args []string) {
|
||||
fmt.Printf("Inside rootCmd PersistentPostRun with args: %v\n", args)
|
||||
},
|
||||
}
|
||||
|
||||
var subCmd = &cobra.Command{
|
||||
Use: "sub [no options!]",
|
||||
Short: "My sub command",
|
||||
PreRun: func(cmd *cobra.Command, args []string) {
|
||||
fmt.Printf("Inside subCmd PreRun with args: %v\n", args)
|
||||
},
|
||||
Run: func(cmd *cobra.Command, args []string) {
|
||||
fmt.Printf("Inside subCmd Run with args: %v\n", args)
|
||||
},
|
||||
PostRun: func(cmd *cobra.Command, args []string) {
|
||||
fmt.Printf("Inside subCmd PostRun with args: %v\n", args)
|
||||
},
|
||||
PersistentPostRun: func(cmd *cobra.Command, args []string) {
|
||||
fmt.Printf("Inside subCmd PersistentPostRun with args: %v\n", args)
|
||||
},
|
||||
}
|
||||
|
||||
rootCmd.AddCommand(subCmd)
|
||||
|
||||
rootCmd.SetArgs([]string{""})
|
||||
_ = rootCmd.Execute()
|
||||
fmt.Print("\n")
|
||||
rootCmd.SetArgs([]string{"sub", "arg1", "arg2"})
|
||||
_ = rootCmd.Execute()
|
||||
}
|
||||
```
|
||||
|
||||
## Generating markdown formatted documentation for your command
|
||||
|
||||
Cobra can generate a markdown formatted document based on the subcommands, flags, etc. A simple example of how to do this for your command can be found in [Markdown Docs](md_docs.md)
|
||||
|
||||
## Generating bash completions for your command
|
||||
|
||||
Cobra can generate a bash completions file. If you add more information to your command these completions can be amazingly powerful and flexible. Read more about [Bash Completions](bash_completions.md)
|
||||
|
||||
## Debugging
|
||||
|
||||
Cobra provides a ‘DebugFlags’ method on a command which when called will print
|
||||
out everything Cobra knows about the flags for each command
|
||||
|
||||
### Example
|
||||
|
||||
command.DebugFlags()
|
||||
|
||||
## Release Notes
|
||||
* **0.9.0** June 17, 2014
|
||||
* flags can appears anywhere in the args (provided they are unambiguous)
|
||||
* --help prints usage screen for app or command
|
||||
* Prefix matching for commands
|
||||
* Cleaner looking help and usage output
|
||||
* Extensive test suite
|
||||
* **0.8.0** Nov 5, 2013
|
||||
* Reworked interface to remove commander completely
|
||||
* Command now primary structure
|
||||
* No initialization needed
|
||||
* Usage & Help templates & functions definable at any level
|
||||
* Updated Readme
|
||||
* **0.7.0** Sept 24, 2013
|
||||
* Needs more eyes
|
||||
* Test suite
|
||||
* Support for automatic error messages
|
||||
* Support for help command
|
||||
* Support for printing to any io.Writer instead of os.Stderr
|
||||
* Support for persistent flags which cascade down tree
|
||||
* Ready for integration into Hugo
|
||||
* **0.1.0** Sept 3, 2013
|
||||
* Implement first draft
|
||||
|
||||
## ToDo
|
||||
* Launch proper documentation site
|
||||
|
||||
## 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)
|
||||
|
||||
## License
|
||||
|
||||
Cobra is released under the Apache 2.0 license. See [LICENSE.txt](https://github.com/spf13/cobra/blob/master/LICENSE.txt)
|
||||
|
||||
|
||||
[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/spf13/cobra/trend.png)](https://bitdeli.com/free "Bitdeli Badge")
|
||||
|
351
Godeps/_workspace/src/github.com/spf13/cobra/bash_completions.go
generated
vendored
Normal file
351
Godeps/_workspace/src/github.com/spf13/cobra/bash_completions.go
generated
vendored
Normal file
@ -0,0 +1,351 @@
|
||||
package cobra
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"os"
|
||||
"sort"
|
||||
"strings"
|
||||
|
||||
"github.com/khlieng/name_pending/Godeps/_workspace/src/github.com/spf13/pflag"
|
||||
)
|
||||
|
||||
const (
|
||||
BashCompFilenameExt = "cobra_annotation_bash_completion_filename_extentions"
|
||||
BashCompOneRequiredFlag = "cobra_annotation_bash_completion_one_required_flag"
|
||||
)
|
||||
|
||||
func preamble(out *bytes.Buffer) {
|
||||
fmt.Fprintf(out, `#!/bin/bash
|
||||
|
||||
|
||||
__debug()
|
||||
{
|
||||
if [[ -n ${BASH_COMP_DEBUG_FILE} ]]; then
|
||||
echo "$*" >> ${BASH_COMP_DEBUG_FILE}
|
||||
fi
|
||||
}
|
||||
|
||||
__index_of_word()
|
||||
{
|
||||
local w word=$1
|
||||
shift
|
||||
index=0
|
||||
for w in "$@"; do
|
||||
[[ $w = "$word" ]] && return
|
||||
index=$((index+1))
|
||||
done
|
||||
index=-1
|
||||
}
|
||||
|
||||
__contains_word()
|
||||
{
|
||||
local w word=$1; shift
|
||||
for w in "$@"; do
|
||||
[[ $w = "$word" ]] && return
|
||||
done
|
||||
return 1
|
||||
}
|
||||
|
||||
__handle_reply()
|
||||
{
|
||||
__debug "${FUNCNAME}"
|
||||
case $cur in
|
||||
-*)
|
||||
compopt -o nospace
|
||||
local allflags
|
||||
if [ ${#must_have_one_flag[@]} -ne 0 ]; then
|
||||
allflags=("${must_have_one_flag[@]}")
|
||||
else
|
||||
allflags=("${flags[*]} ${two_word_flags[*]}")
|
||||
fi
|
||||
COMPREPLY=( $(compgen -W "${allflags[*]}" -- "$cur") )
|
||||
[[ $COMPREPLY == *= ]] || compopt +o nospace
|
||||
return 0;
|
||||
;;
|
||||
esac
|
||||
|
||||
# check if we are handling a flag with special work handling
|
||||
local index
|
||||
__index_of_word "${prev}" "${flags_with_completion[@]}"
|
||||
if [[ ${index} -ge 0 ]]; then
|
||||
${flags_completion[${index}]}
|
||||
return
|
||||
fi
|
||||
|
||||
# we are parsing a flag and don't have a special handler, no completion
|
||||
if [[ ${cur} != "${words[cword]}" ]]; then
|
||||
return
|
||||
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=("${must_have_one_noun[@]}")
|
||||
else
|
||||
completions=("${commands[@]}")
|
||||
fi
|
||||
COMPREPLY=( $(compgen -W "${completions[*]}" -- "$cur") )
|
||||
|
||||
if [[ ${#COMPREPLY[@]} -eq 0 ]]; then
|
||||
declare -F __custom_func >/dev/null && __custom_func
|
||||
fi
|
||||
}
|
||||
|
||||
__handle_flag()
|
||||
{
|
||||
__debug "${FUNCNAME}: 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]}
|
||||
# if the word contained an =
|
||||
if [[ ${words[c]} == *"="* ]]; then
|
||||
flagname=${flagname%%=*} # strip everything after the =
|
||||
flagname="${flagname}=" # but put the = back
|
||||
fi
|
||||
__debug "${FUNCNAME}: looking for ${flagname}"
|
||||
if __contains_word "${flagname}" "${must_have_one_flag[@]}"; then
|
||||
must_have_one_flag=()
|
||||
fi
|
||||
|
||||
# skip the argument to a two word flag
|
||||
if __contains_word "${words[c]}" "${two_word_flags[@]}"; then
|
||||
c=$((c+1))
|
||||
# if we are looking for a flags value, don't show commands
|
||||
if [[ $c -eq $cword ]]; then
|
||||
commands=()
|
||||
fi
|
||||
fi
|
||||
|
||||
# skip the flag itself
|
||||
c=$((c+1))
|
||||
|
||||
}
|
||||
|
||||
__handle_noun()
|
||||
{
|
||||
__debug "${FUNCNAME}: c is $c words[c] is ${words[c]}"
|
||||
|
||||
if __contains_word "${words[c]}" "${must_have_one_noun[@]}"; then
|
||||
must_have_one_noun=()
|
||||
fi
|
||||
|
||||
nouns+=("${words[c]}")
|
||||
c=$((c+1))
|
||||
}
|
||||
|
||||
__handle_command()
|
||||
{
|
||||
__debug "${FUNCNAME}: c is $c words[c] is ${words[c]}"
|
||||
|
||||
local next_command
|
||||
if [[ -n ${last_command} ]]; then
|
||||
next_command="_${last_command}_${words[c]}"
|
||||
else
|
||||
next_command="_${words[c]}"
|
||||
fi
|
||||
c=$((c+1))
|
||||
__debug "${FUNCNAME}: looking for ${next_command}"
|
||||
declare -F $next_command >/dev/null && $next_command
|
||||
}
|
||||
|
||||
__handle_word()
|
||||
{
|
||||
if [[ $c -ge $cword ]]; then
|
||||
__handle_reply
|
||||
return
|
||||
fi
|
||||
__debug "${FUNCNAME}: c is $c words[c] is ${words[c]}"
|
||||
if [[ "${words[c]}" == -* ]]; then
|
||||
__handle_flag
|
||||
elif __contains_word "${words[c]}" "${commands[@]}"; then
|
||||
__handle_command
|
||||
else
|
||||
__handle_noun
|
||||
fi
|
||||
__handle_word
|
||||
}
|
||||
|
||||
`)
|
||||
}
|
||||
|
||||
func postscript(out *bytes.Buffer, name string) {
|
||||
fmt.Fprintf(out, "__start_%s()\n", name)
|
||||
fmt.Fprintf(out, `{
|
||||
local cur prev words cword split
|
||||
_init_completion -s || return
|
||||
|
||||
local completions_func
|
||||
local c=0
|
||||
local flags=()
|
||||
local two_word_flags=()
|
||||
local flags_with_completion=()
|
||||
local flags_completion=()
|
||||
local commands=("%s")
|
||||
local must_have_one_flag=()
|
||||
local must_have_one_noun=()
|
||||
local last_command
|
||||
local nouns=()
|
||||
|
||||
__handle_word
|
||||
}
|
||||
|
||||
`, name)
|
||||
fmt.Fprintf(out, "complete -F __start_%s %s\n", name, name)
|
||||
fmt.Fprintf(out, "# ex: ts=4 sw=4 et filetype=sh\n")
|
||||
}
|
||||
|
||||
func writeCommands(cmd *Command, out *bytes.Buffer) {
|
||||
fmt.Fprintf(out, " commands=()\n")
|
||||
for _, c := range cmd.Commands() {
|
||||
if len(c.Deprecated) > 0 {
|
||||
continue
|
||||
}
|
||||
fmt.Fprintf(out, " commands+=(%q)\n", c.Name())
|
||||
}
|
||||
fmt.Fprintf(out, "\n")
|
||||
}
|
||||
|
||||
func writeFlagHandler(name string, annotations map[string][]string, out *bytes.Buffer) {
|
||||
for key, value := range annotations {
|
||||
switch key {
|
||||
case BashCompFilenameExt:
|
||||
fmt.Fprintf(out, " flags_with_completion+=(%q)\n", name)
|
||||
|
||||
ext := strings.Join(value, "|")
|
||||
ext = "_filedir '@(" + ext + ")'"
|
||||
fmt.Fprintf(out, " flags_completion+=(%q)\n", ext)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func writeShortFlag(flag *pflag.Flag, out *bytes.Buffer) {
|
||||
b := (flag.Value.Type() == "bool")
|
||||
name := flag.Shorthand
|
||||
format := " "
|
||||
if !b {
|
||||
format += "two_word_"
|
||||
}
|
||||
format += "flags+=(\"-%s\")\n"
|
||||
fmt.Fprintf(out, format, name)
|
||||
writeFlagHandler("-"+name, flag.Annotations, out)
|
||||
}
|
||||
|
||||
func writeFlag(flag *pflag.Flag, out *bytes.Buffer) {
|
||||
b := (flag.Value.Type() == "bool")
|
||||
name := flag.Name
|
||||
format := " flags+=(\"--%s"
|
||||
if !b {
|
||||
format += "="
|
||||
}
|
||||
format += "\")\n"
|
||||
fmt.Fprintf(out, format, name)
|
||||
writeFlagHandler("--"+name, flag.Annotations, out)
|
||||
}
|
||||
|
||||
func writeFlags(cmd *Command, out *bytes.Buffer) {
|
||||
fmt.Fprintf(out, ` flags=()
|
||||
two_word_flags=()
|
||||
flags_with_completion=()
|
||||
flags_completion=()
|
||||
|
||||
`)
|
||||
cmd.NonInheritedFlags().VisitAll(func(flag *pflag.Flag) {
|
||||
writeFlag(flag, out)
|
||||
if len(flag.Shorthand) > 0 {
|
||||
writeShortFlag(flag, out)
|
||||
}
|
||||
})
|
||||
|
||||
fmt.Fprintf(out, "\n")
|
||||
}
|
||||
|
||||
func writeRequiredFlag(cmd *Command, out *bytes.Buffer) {
|
||||
fmt.Fprintf(out, " must_have_one_flag=()\n")
|
||||
flags := cmd.NonInheritedFlags()
|
||||
flags.VisitAll(func(flag *pflag.Flag) {
|
||||
for key, _ := range flag.Annotations {
|
||||
switch key {
|
||||
case BashCompOneRequiredFlag:
|
||||
format := " must_have_one_flag+=(\"--%s"
|
||||
b := (flag.Value.Type() == "bool")
|
||||
if !b {
|
||||
format += "="
|
||||
}
|
||||
format += "\")\n"
|
||||
fmt.Fprintf(out, format, flag.Name)
|
||||
|
||||
if len(flag.Shorthand) > 0 {
|
||||
fmt.Fprintf(out, " must_have_one_flag+=(\"-%s\")\n", flag.Shorthand)
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func writeRequiredNoun(cmd *Command, out *bytes.Buffer) {
|
||||
fmt.Fprintf(out, " must_have_one_noun=()\n")
|
||||
sort.Sort(sort.StringSlice(cmd.ValidArgs))
|
||||
for _, value := range cmd.ValidArgs {
|
||||
fmt.Fprintf(out, " must_have_one_noun+=(%q)\n", value)
|
||||
}
|
||||
}
|
||||
|
||||
func gen(cmd *Command, out *bytes.Buffer) {
|
||||
for _, c := range cmd.Commands() {
|
||||
if len(c.Deprecated) > 0 {
|
||||
continue
|
||||
}
|
||||
gen(c, out)
|
||||
}
|
||||
commandName := cmd.CommandPath()
|
||||
commandName = strings.Replace(commandName, " ", "_", -1)
|
||||
fmt.Fprintf(out, "_%s()\n{\n", commandName)
|
||||
fmt.Fprintf(out, " last_command=%q\n", commandName)
|
||||
writeCommands(cmd, out)
|
||||
writeFlags(cmd, out)
|
||||
writeRequiredFlag(cmd, out)
|
||||
writeRequiredNoun(cmd, out)
|
||||
fmt.Fprintf(out, "}\n\n")
|
||||
}
|
||||
|
||||
func (cmd *Command) GenBashCompletion(out *bytes.Buffer) {
|
||||
preamble(out)
|
||||
if len(cmd.BashCompletionFunction) > 0 {
|
||||
fmt.Fprintf(out, "%s\n", cmd.BashCompletionFunction)
|
||||
}
|
||||
gen(cmd, out)
|
||||
postscript(out, cmd.Name())
|
||||
}
|
||||
|
||||
func (cmd *Command) GenBashCompletionFile(filename string) error {
|
||||
out := new(bytes.Buffer)
|
||||
|
||||
cmd.GenBashCompletion(out)
|
||||
|
||||
outFile, err := os.Create(filename)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer outFile.Close()
|
||||
|
||||
_, err = outFile.Write(out.Bytes())
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (cmd *Command) MarkFlagRequired(name string) {
|
||||
flag := cmd.Flags().Lookup(name)
|
||||
if flag == nil {
|
||||
return
|
||||
}
|
||||
if flag.Annotations == nil {
|
||||
flag.Annotations = make(map[string][]string)
|
||||
}
|
||||
annotation := make([]string, 1)
|
||||
annotation[0] = "true"
|
||||
flag.Annotations[BashCompOneRequiredFlag] = annotation
|
||||
}
|
146
Godeps/_workspace/src/github.com/spf13/cobra/bash_completions.md
generated
vendored
Normal file
146
Godeps/_workspace/src/github.com/spf13/cobra/bash_completions.md
generated
vendored
Normal file
@ -0,0 +1,146 @@
|
||||
# Generating Bash Completions For Your Own cobra.Command
|
||||
|
||||
Generating bash completions from a cobra command is incredibly easy. An actual program which does so for the kubernetes kubectl binary is as follows:
|
||||
|
||||
```go
|
||||
package main
|
||||
|
||||
import (
|
||||
"io/ioutil"
|
||||
"os"
|
||||
|
||||
"github.com/GoogleCloudPlatform/kubernetes/pkg/kubectl/cmd"
|
||||
)
|
||||
|
||||
func main() {
|
||||
kubectl := cmd.NewFactory(nil).NewKubectlCommand(os.Stdin, ioutil.Discard, ioutil.Discard)
|
||||
kubectl.GenBashCompletionFile("out.sh")
|
||||
}
|
||||
```
|
||||
|
||||
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.
|
||||
|
||||
## Creating your own custom functions
|
||||
|
||||
Some more actual code that works in kubernetes:
|
||||
|
||||
```bash
|
||||
const (
|
||||
bash_completion_func = `__kubectl_parse_get()
|
||||
{
|
||||
local kubectl_output out
|
||||
if kubectl_output=$(kubectl get --no-headers "$1" 2>/dev/null); then
|
||||
out=($(echo "${kubectl_output}" | awk '{print $1}'))
|
||||
COMPREPLY=( $( compgen -W "${out[*]}" -- "$cur" ) )
|
||||
fi
|
||||
}
|
||||
|
||||
__kubectl_get_resource()
|
||||
{
|
||||
if [[ ${#nouns[@]} -eq 0 ]]; then
|
||||
return 1
|
||||
fi
|
||||
__kubectl_parse_get ${nouns[${#nouns[@]} -1]}
|
||||
if [[ $? -eq 0 ]]; then
|
||||
return 0
|
||||
fi
|
||||
}
|
||||
|
||||
__custom_func() {
|
||||
case ${last_command} in
|
||||
kubectl_get | kubectl_describe | kubectl_delete | kubectl_stop)
|
||||
__kubectl_get_resource
|
||||
return
|
||||
;;
|
||||
*)
|
||||
;;
|
||||
esac
|
||||
}
|
||||
`)
|
||||
```
|
||||
|
||||
And then I set that in my command definition:
|
||||
|
||||
```go
|
||||
cmds := &cobra.Command{
|
||||
Use: "kubectl",
|
||||
Short: "kubectl controls the Kubernetes cluster manager",
|
||||
Long: `kubectl controls the Kubernetes cluster manager.
|
||||
|
||||
Find more information at https://github.com/GoogleCloudPlatform/kubernetes.`,
|
||||
Run: runHelp,
|
||||
BashCompletionFunction: bash_completion_func,
|
||||
}
|
||||
```
|
||||
|
||||
The `BashCompletionFunction` option is really only valid/useful on the root command. Doing the above will cause `__custom_func()` to be called when the built in processor was unable to find a solution. In the case of kubernetes a valid command might look something like `kubectl get pod [mypod]`. If you type `kubectl get pod [tab][tab]` the `__customc_func()` will run because the cobra.Command only understood "kubectl" and "get." `__custom_func()` will see that the cobra.Command is "kubectl_get" and will thus call another helper `__kubectl_get_resource()`. `__kubectl_get_resource` will look at the 'nouns' collected. In our example the only noun will be `pod`. So it will call `__kubectl_parse_get pod`. `__kubectl_parse_get` will actually call out to kubernetes and get any pods. It will then set `COMPREPLY` to valid pods!
|
||||
|
||||
## Have the completions code complete your 'nouns'
|
||||
|
||||
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" }
|
||||
|
||||
cmd := &cobra.Command{
|
||||
Use: "get [(-o|--output=)json|yaml|template|...] (RESOURCE [NAME] | RESOURCE/NAME ...)",
|
||||
Short: "Display one or many resources",
|
||||
Long: get_long,
|
||||
Example: get_example,
|
||||
Run: func(cmd *cobra.Command, args []string) {
|
||||
err := RunGet(f, out, cmd, args)
|
||||
util.CheckErr(err)
|
||||
},
|
||||
ValidArgs: validArgs,
|
||||
}
|
||||
```
|
||||
|
||||
Notice we put the "ValidArgs" on the "get" subcommand. Doing so will give results like
|
||||
|
||||
```bash
|
||||
# kubectl get [tab][tab]
|
||||
nodes pods replicationControllers services
|
||||
```
|
||||
|
||||
## 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.
|
||||
|
||||
```go
|
||||
cmd.MarkFlagRequired("pod")
|
||||
cmd.MarkFlagRequired("container")
|
||||
```
|
||||
|
||||
and you'll get something like
|
||||
|
||||
```bash
|
||||
# kubectl exec [tab][tab][tab]
|
||||
-c --container= -p --pod=
|
||||
```
|
||||
|
||||
# Specify valid filename extentions for flags that take a filename
|
||||
|
||||
In this example we use --filename= and expect to get a json or yaml file as the argument. To make this easier we annotate the --filename flag with valid filename extensions.
|
||||
|
||||
```go
|
||||
annotations := make([]string, 3)
|
||||
annotations[0] = "json"
|
||||
annotations[1] = "yaml"
|
||||
annotations[2] = "yml"
|
||||
|
||||
annotation := make(map[string][]string)
|
||||
annotation[cobra.BashCompFilenameExt] = annotations
|
||||
|
||||
flag := &pflag.Flag{"filename", "f", usage, value, value.String(), false, annotation}
|
||||
cmd.Flags().AddFlag(flag)
|
||||
```
|
||||
|
||||
Now when you run a command with this filename flag you'll get something like
|
||||
|
||||
```bash
|
||||
# kubectl create -f
|
||||
test/ example/ rpmbuild/
|
||||
hello.yml test.json
|
||||
```
|
||||
|
||||
So while there are many other files in the CWD it only shows me subdirs and those with valid extensions.
|
82
Godeps/_workspace/src/github.com/spf13/cobra/bash_completions_test.go
generated
vendored
Normal file
82
Godeps/_workspace/src/github.com/spf13/cobra/bash_completions_test.go
generated
vendored
Normal file
@ -0,0 +1,82 @@
|
||||
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)
|
||||
|
||||
// custom completion function
|
||||
c.BashCompletionFunction = bash_completion_func
|
||||
|
||||
// required flag
|
||||
c.MarkFlagRequired("introot")
|
||||
|
||||
// valid nounds
|
||||
validArgs := []string{"pods", "nodes", "services", "replicationControllers"}
|
||||
c.ValidArgs = validArgs
|
||||
|
||||
// filename extentions
|
||||
annotations := make([]string, 3)
|
||||
annotations[0] = "json"
|
||||
annotations[1] = "yaml"
|
||||
annotations[2] = "yml"
|
||||
|
||||
annotation := make(map[string][]string)
|
||||
annotation[BashCompFilenameExt] = annotations
|
||||
|
||||
var flagval string
|
||||
c.Flags().StringVar(&flagval, "filename", "", "Enter a filename")
|
||||
flag := c.Flags().Lookup("filename")
|
||||
flag.Annotations = annotation
|
||||
|
||||
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 for required flags
|
||||
check(t, str, `must_have_one_flag+=("--introot=")`)
|
||||
// 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 extention flags
|
||||
check(t, str, `flags_completion+=("_filedir '@(json|yaml|yml)'")`)
|
||||
|
||||
checkOmit(t, str, cmdDeprecated.Name())
|
||||
}
|
112
Godeps/_workspace/src/github.com/spf13/cobra/cobra.go
generated
vendored
Normal file
112
Godeps/_workspace/src/github.com/spf13/cobra/cobra.go
generated
vendored
Normal file
@ -0,0 +1,112 @@
|
||||
// Copyright © 2013 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.
|
||||
|
||||
// Commands similar to git, go tools and other modern CLI tools
|
||||
// inspired by go, go-Commander, gh and subcommand
|
||||
|
||||
package cobra
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"reflect"
|
||||
"strconv"
|
||||
"strings"
|
||||
"text/template"
|
||||
)
|
||||
|
||||
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
|
||||
|
||||
// enables an information splash screen on Windows if the CLI is started from explorer.exe.
|
||||
var EnableWindowsMouseTrap bool = true
|
||||
|
||||
var MousetrapHelpText string = `This is a command line tool
|
||||
|
||||
You need to open cmd.exe and run it from there.
|
||||
`
|
||||
|
||||
//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)
|
||||
}
|
||||
}
|
||||
|
||||
//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)
|
||||
|
||||
switch av.Kind() {
|
||||
case reflect.Array, reflect.Chan, reflect.Map, reflect.Slice:
|
||||
left = int64(av.Len())
|
||||
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
|
||||
left = av.Int()
|
||||
case reflect.String:
|
||||
left, _ = strconv.ParseInt(av.String(), 10, 64)
|
||||
}
|
||||
|
||||
bv := reflect.ValueOf(b)
|
||||
|
||||
switch bv.Kind() {
|
||||
case reflect.Array, reflect.Chan, reflect.Map, reflect.Slice:
|
||||
right = int64(bv.Len())
|
||||
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
|
||||
right = bv.Int()
|
||||
case reflect.String:
|
||||
right, _ = strconv.ParseInt(bv.String(), 10, 64)
|
||||
}
|
||||
|
||||
return left > right
|
||||
}
|
||||
|
||||
//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)
|
||||
|
||||
switch av.Kind() {
|
||||
case reflect.Array, reflect.Chan, reflect.Map, reflect.Slice:
|
||||
panic("Eq called on unsupported type")
|
||||
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
|
||||
return av.Int() == bv.Int()
|
||||
case reflect.String:
|
||||
return av.String() == bv.String()
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
//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)
|
||||
}
|
||||
|
||||
// tmpl executes the given template text on data, writing the result to w.
|
||||
func tmpl(w io.Writer, text string, data interface{}) error {
|
||||
t := template.New("top")
|
||||
t.Funcs(template.FuncMap{
|
||||
"trim": strings.TrimSpace,
|
||||
"rpad": rpad,
|
||||
"gt": Gt,
|
||||
"eq": Eq,
|
||||
})
|
||||
template.Must(t.Parse(text))
|
||||
return t.Execute(w, data)
|
||||
}
|
871
Godeps/_workspace/src/github.com/spf13/cobra/cobra_test.go
generated
vendored
Normal file
871
Godeps/_workspace/src/github.com/spf13/cobra/cobra_test.go
generated
vendored
Normal file
@ -0,0 +1,871 @@
|
||||
package cobra
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"os"
|
||||
"runtime"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
var _ = fmt.Println
|
||||
var _ = os.Stderr
|
||||
|
||||
var tp, te, tt, t1 []string
|
||||
var rootPersPre, echoPre, echoPersPre, timesPersPre []string
|
||||
var flagb1, flagb2, flagb3, flagbr, flagbp bool
|
||||
var flags1, flags2a, flags2b, flags3 string
|
||||
var flagi1, flagi2, flagi3, flagir int
|
||||
var globalFlag1 bool
|
||||
var flagEcho, rootcalled bool
|
||||
var versionUsed int
|
||||
|
||||
const strtwoParentHelp = "help message for parent flag strtwo"
|
||||
const strtwoChildHelp = "help message for child flag strtwo"
|
||||
|
||||
var cmdPrint = &Command{
|
||||
Use: "print [string to print]",
|
||||
Short: "Print anything to the screen",
|
||||
Long: `an absolutely utterly useless command for testing.`,
|
||||
Run: func(cmd *Command, args []string) {
|
||||
tp = args
|
||||
},
|
||||
}
|
||||
|
||||
var cmdEcho = &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",
|
||||
PersistentPreRun: func(cmd *Command, args []string) {
|
||||
echoPersPre = args
|
||||
},
|
||||
PreRun: func(cmd *Command, args []string) {
|
||||
echoPre = args
|
||||
},
|
||||
Run: func(cmd *Command, args []string) {
|
||||
te = args
|
||||
},
|
||||
}
|
||||
|
||||
var cmdEchoSub = &Command{
|
||||
Use: "echosub [string to print]",
|
||||
Short: "second sub command for echo",
|
||||
Long: `an absolutely utterly useless command for testing gendocs!.`,
|
||||
Run: func(cmd *Command, args []string) {
|
||||
},
|
||||
}
|
||||
|
||||
var cmdDeprecated = &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",
|
||||
Run: func(cmd *Command, args []string) {
|
||||
},
|
||||
}
|
||||
|
||||
var cmdTimes = &Command{
|
||||
Use: "times [# times] [string to echo]",
|
||||
Short: "Echo anything to the screen more times",
|
||||
Long: `a slightly useless command for testing.`,
|
||||
PersistentPreRun: func(cmd *Command, args []string) {
|
||||
timesPersPre = args
|
||||
},
|
||||
Run: func(cmd *Command, args []string) {
|
||||
tt = args
|
||||
},
|
||||
}
|
||||
|
||||
var cmdRootNoRun = &Command{
|
||||
Use: "cobra-test",
|
||||
Short: "The root can run it's own function",
|
||||
Long: "The root description for help",
|
||||
PersistentPreRun: func(cmd *Command, args []string) {
|
||||
rootPersPre = args
|
||||
},
|
||||
}
|
||||
|
||||
var cmdRootSameName = &Command{
|
||||
Use: "print",
|
||||
Short: "Root with the same name as a subcommand",
|
||||
Long: "The root description for help",
|
||||
}
|
||||
|
||||
var cmdRootWithRun = &Command{
|
||||
Use: "cobra-test",
|
||||
Short: "The root can run it's own function",
|
||||
Long: "The root description for help",
|
||||
Run: func(cmd *Command, args []string) {
|
||||
rootcalled = true
|
||||
},
|
||||
}
|
||||
|
||||
var cmdSubNoRun = &Command{
|
||||
Use: "subnorun",
|
||||
Short: "A subcommand without a Run function",
|
||||
Long: "A long output about a subcommand without a Run function",
|
||||
}
|
||||
|
||||
var cmdVersion1 = &Command{
|
||||
Use: "version",
|
||||
Short: "Print the version number",
|
||||
Long: `First version of the version command`,
|
||||
Run: func(cmd *Command, args []string) {
|
||||
versionUsed = 1
|
||||
},
|
||||
}
|
||||
|
||||
var cmdVersion2 = &Command{
|
||||
Use: "version",
|
||||
Short: "Print the version number",
|
||||
Long: `Second version of the version command`,
|
||||
Run: func(cmd *Command, args []string) {
|
||||
versionUsed = 2
|
||||
},
|
||||
}
|
||||
|
||||
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 commandInit() {
|
||||
cmdEcho.ResetCommands()
|
||||
cmdPrint.ResetCommands()
|
||||
cmdTimes.ResetCommands()
|
||||
cmdRootNoRun.ResetCommands()
|
||||
cmdRootSameName.ResetCommands()
|
||||
cmdRootWithRun.ResetCommands()
|
||||
cmdSubNoRun.ResetCommands()
|
||||
}
|
||||
|
||||
func initialize() *Command {
|
||||
tt, tp, te = nil, nil, nil
|
||||
rootPersPre, echoPre, echoPersPre, timesPersPre = nil, nil, nil, nil
|
||||
|
||||
var c = cmdRootNoRun
|
||||
flagInit()
|
||||
commandInit()
|
||||
return c
|
||||
}
|
||||
|
||||
func initializeWithSameName() *Command {
|
||||
tt, tp, te = nil, nil, nil
|
||||
rootPersPre, echoPre, echoPersPre, timesPersPre = nil, nil, nil, nil
|
||||
var c = cmdRootSameName
|
||||
flagInit()
|
||||
commandInit()
|
||||
return c
|
||||
}
|
||||
|
||||
func initializeWithRootCmd() *Command {
|
||||
cmdRootWithRun.ResetCommands()
|
||||
tt, tp, te, rootcalled = nil, nil, nil, false
|
||||
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")
|
||||
commandInit()
|
||||
return cmdRootWithRun
|
||||
}
|
||||
|
||||
type resulter struct {
|
||||
Error error
|
||||
Output string
|
||||
Command *Command
|
||||
}
|
||||
|
||||
func fullSetupTest(input string) resulter {
|
||||
c := initializeWithRootCmd()
|
||||
|
||||
return fullTester(c, input)
|
||||
}
|
||||
|
||||
func noRRSetupTest(input string) resulter {
|
||||
c := initialize()
|
||||
|
||||
return fullTester(c, input)
|
||||
}
|
||||
|
||||
func rootOnlySetupTest(input string) resulter {
|
||||
c := initializeWithRootCmd()
|
||||
|
||||
return simpleTester(c, input)
|
||||
}
|
||||
|
||||
func simpleTester(c *Command, input string) resulter {
|
||||
buf := new(bytes.Buffer)
|
||||
// Testing flag with invalid input
|
||||
c.SetOutput(buf)
|
||||
c.SetArgs(strings.Split(input, " "))
|
||||
|
||||
err := c.Execute()
|
||||
output := buf.String()
|
||||
|
||||
return resulter{err, output, c}
|
||||
}
|
||||
|
||||
func fullTester(c *Command, input string) resulter {
|
||||
buf := new(bytes.Buffer)
|
||||
// Testing flag with invalid input
|
||||
c.SetOutput(buf)
|
||||
cmdEcho.AddCommand(cmdTimes)
|
||||
c.AddCommand(cmdPrint, cmdEcho, cmdSubNoRun, cmdDeprecated)
|
||||
c.SetArgs(strings.Split(input, " "))
|
||||
|
||||
err := c.Execute()
|
||||
output := buf.String()
|
||||
|
||||
return resulter{err, output, c}
|
||||
}
|
||||
|
||||
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())
|
||||
}
|
||||
|
||||
func checkResultContains(t *testing.T, x resulter, check string) {
|
||||
if !strings.Contains(x.Output, check) {
|
||||
logErr(t, x.Output, check)
|
||||
}
|
||||
}
|
||||
|
||||
func checkResultOmits(t *testing.T, x resulter, check string) {
|
||||
if strings.Contains(x.Output, check) {
|
||||
logErr(t, x.Output, check)
|
||||
}
|
||||
}
|
||||
|
||||
func checkOutputContains(t *testing.T, c *Command, check string) {
|
||||
buf := new(bytes.Buffer)
|
||||
c.SetOutput(buf)
|
||||
c.Execute()
|
||||
|
||||
if !strings.Contains(buf.String(), check) {
|
||||
logErr(t, buf.String(), check)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSingleCommand(t *testing.T) {
|
||||
noRRSetupTest("print one two")
|
||||
|
||||
if te != nil || tt != nil {
|
||||
t.Error("Wrong command called")
|
||||
}
|
||||
if tp == nil {
|
||||
t.Error("Wrong command called")
|
||||
}
|
||||
if strings.Join(tp, " ") != "one two" {
|
||||
t.Error("Command didn't parse correctly")
|
||||
}
|
||||
}
|
||||
|
||||
func TestChildCommand(t *testing.T) {
|
||||
noRRSetupTest("echo times one two")
|
||||
|
||||
if te != nil || tp != nil {
|
||||
t.Error("Wrong command called")
|
||||
}
|
||||
if tt == nil {
|
||||
t.Error("Wrong command called")
|
||||
}
|
||||
if strings.Join(tt, " ") != "one two" {
|
||||
t.Error("Command didn't parse correctly")
|
||||
}
|
||||
}
|
||||
|
||||
func TestCommandAlias(t *testing.T) {
|
||||
noRRSetupTest("say times one two")
|
||||
|
||||
if te != nil || tp != nil {
|
||||
t.Error("Wrong command called")
|
||||
}
|
||||
if tt == nil {
|
||||
t.Error("Wrong command called")
|
||||
}
|
||||
if strings.Join(tt, " ") != "one two" {
|
||||
t.Error("Command didn't parse correctly")
|
||||
}
|
||||
}
|
||||
|
||||
func TestPrefixMatching(t *testing.T) {
|
||||
EnablePrefixMatching = true
|
||||
noRRSetupTest("ech times one two")
|
||||
|
||||
if te != nil || tp != nil {
|
||||
t.Error("Wrong command called")
|
||||
}
|
||||
if tt == nil {
|
||||
t.Error("Wrong command called")
|
||||
}
|
||||
if strings.Join(tt, " ") != "one two" {
|
||||
t.Error("Command didn't parse correctly")
|
||||
}
|
||||
|
||||
EnablePrefixMatching = false
|
||||
}
|
||||
|
||||
func TestNoPrefixMatching(t *testing.T) {
|
||||
EnablePrefixMatching = false
|
||||
|
||||
noRRSetupTest("ech times one two")
|
||||
|
||||
if !(tt == nil && te == nil && tp == nil) {
|
||||
t.Error("Wrong command called")
|
||||
}
|
||||
}
|
||||
|
||||
func TestAliasPrefixMatching(t *testing.T) {
|
||||
EnablePrefixMatching = true
|
||||
noRRSetupTest("sa times one two")
|
||||
|
||||
if te != nil || tp != nil {
|
||||
t.Error("Wrong command called")
|
||||
}
|
||||
if tt == nil {
|
||||
t.Error("Wrong command called")
|
||||
}
|
||||
if strings.Join(tt, " ") != "one two" {
|
||||
t.Error("Command didn't parse correctly")
|
||||
}
|
||||
EnablePrefixMatching = false
|
||||
}
|
||||
|
||||
func TestChildSameName(t *testing.T) {
|
||||
c := initializeWithSameName()
|
||||
c.AddCommand(cmdPrint, cmdEcho)
|
||||
c.SetArgs(strings.Split("print one two", " "))
|
||||
c.Execute()
|
||||
|
||||
if te != nil || tt != nil {
|
||||
t.Error("Wrong command called")
|
||||
}
|
||||
if tp == nil {
|
||||
t.Error("Wrong command called")
|
||||
}
|
||||
if strings.Join(tp, " ") != "one two" {
|
||||
t.Error("Command didn't parse correctly")
|
||||
}
|
||||
}
|
||||
|
||||
func TestFlagLong(t *testing.T) {
|
||||
noRRSetupTest("echo --intone=13 something here")
|
||||
|
||||
if strings.Join(te, " ") != "something here" {
|
||||
t.Errorf("flags didn't leave proper args remaining..%s given", te)
|
||||
}
|
||||
if flagi1 != 13 {
|
||||
t.Errorf("int flag didn't get correct value, had %d", flagi1)
|
||||
}
|
||||
if flagi2 != 234 {
|
||||
t.Errorf("default flag value changed, 234 expected, %d given", flagi2)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFlagShort(t *testing.T) {
|
||||
noRRSetupTest("echo -i13 something here")
|
||||
|
||||
if strings.Join(te, " ") != "something here" {
|
||||
t.Errorf("flags didn't leave proper args remaining..%s given", te)
|
||||
}
|
||||
if flagi1 != 13 {
|
||||
t.Errorf("int flag didn't get correct value, had %d", flagi1)
|
||||
}
|
||||
if flagi2 != 234 {
|
||||
t.Errorf("default flag value changed, 234 expected, %d given", flagi2)
|
||||
}
|
||||
|
||||
noRRSetupTest("echo -i 13 something here")
|
||||
|
||||
if strings.Join(te, " ") != "something here" {
|
||||
t.Errorf("flags didn't leave proper args remaining..%s given", te)
|
||||
}
|
||||
if flagi1 != 13 {
|
||||
t.Errorf("int flag didn't get correct value, had %d", flagi1)
|
||||
}
|
||||
if flagi2 != 234 {
|
||||
t.Errorf("default flag value changed, 234 expected, %d given", flagi2)
|
||||
}
|
||||
|
||||
noRRSetupTest("print -i99 one two")
|
||||
|
||||
if strings.Join(tp, " ") != "one two" {
|
||||
t.Errorf("flags didn't leave proper args remaining..%s given", tp)
|
||||
}
|
||||
if flagi3 != 99 {
|
||||
t.Errorf("int flag didn't get correct value, had %d", flagi3)
|
||||
}
|
||||
if flagi1 != 123 {
|
||||
t.Errorf("default flag value changed on different command with same shortname, 234 expected, %d given", flagi2)
|
||||
}
|
||||
}
|
||||
|
||||
func TestChildCommandFlags(t *testing.T) {
|
||||
noRRSetupTest("echo times -j 99 one two")
|
||||
|
||||
if strings.Join(tt, " ") != "one two" {
|
||||
t.Errorf("flags didn't leave proper args remaining..%s given", tt)
|
||||
}
|
||||
|
||||
// Testing with flag that shouldn't be persistent
|
||||
r := noRRSetupTest("echo times -j 99 -i77 one two")
|
||||
|
||||
if r.Error == nil {
|
||||
t.Errorf("invalid flag should generate error")
|
||||
}
|
||||
|
||||
if !strings.Contains(r.Output, "unknown shorthand") {
|
||||
t.Errorf("Wrong error message displayed, \n %s", r.Output)
|
||||
}
|
||||
|
||||
if flagi2 != 99 {
|
||||
t.Errorf("flag value should be 99, %d given", flagi2)
|
||||
}
|
||||
|
||||
if flagi1 != 123 {
|
||||
t.Errorf("unset flag should have default value, expecting 123, given %d", flagi1)
|
||||
}
|
||||
|
||||
// Testing with flag only existing on child
|
||||
r = noRRSetupTest("echo -j 99 -i77 one two")
|
||||
|
||||
if r.Error == nil {
|
||||
t.Errorf("invalid flag should generate error")
|
||||
}
|
||||
|
||||
if !strings.Contains(r.Output, "unknown shorthand flag") {
|
||||
t.Errorf("Wrong error message displayed, \n %s", r.Output)
|
||||
}
|
||||
|
||||
// Testing with persistent flag overwritten by child
|
||||
noRRSetupTest("echo times --strtwo=child one two")
|
||||
|
||||
if flags2b != "child" {
|
||||
t.Errorf("flag value should be child, %s given", flags2b)
|
||||
}
|
||||
|
||||
if flags2a != "two" {
|
||||
t.Errorf("unset flag should have default value, expecting two, given %s", flags2a)
|
||||
}
|
||||
|
||||
// Testing flag with invalid input
|
||||
r = noRRSetupTest("echo -i10E")
|
||||
|
||||
if r.Error == nil {
|
||||
t.Errorf("invalid input should generate error")
|
||||
}
|
||||
|
||||
if !strings.Contains(r.Output, "invalid argument \"10E\" for -i10E") {
|
||||
t.Errorf("Wrong error message displayed, \n %s", r.Output)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTrailingCommandFlags(t *testing.T) {
|
||||
x := fullSetupTest("echo two -x")
|
||||
|
||||
if x.Error == nil {
|
||||
t.Errorf("invalid flag should generate error")
|
||||
}
|
||||
}
|
||||
|
||||
func TestInvalidSubCommandFlags(t *testing.T) {
|
||||
cmd := initializeWithRootCmd()
|
||||
cmd.AddCommand(cmdTimes)
|
||||
|
||||
result := simpleTester(cmd, "times --inttwo=2 --badflag=bar")
|
||||
|
||||
checkResultContains(t, result, "unknown flag: --badflag")
|
||||
|
||||
if strings.Contains(result.Output, "unknown flag: --inttwo") {
|
||||
t.Errorf("invalid --badflag flag shouldn't fail on 'unknown' --inttwo flag")
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
func TestSubCommandArgEvaluation(t *testing.T) {
|
||||
cmd := initializeWithRootCmd()
|
||||
|
||||
first := &Command{
|
||||
Use: "first",
|
||||
Run: func(cmd *Command, args []string) {
|
||||
},
|
||||
}
|
||||
cmd.AddCommand(first)
|
||||
|
||||
second := &Command{
|
||||
Use: "second",
|
||||
Run: func(cmd *Command, args []string) {
|
||||
fmt.Fprintf(cmd.Out(), "%v", args)
|
||||
},
|
||||
}
|
||||
first.AddCommand(second)
|
||||
|
||||
result := simpleTester(cmd, "first second first third")
|
||||
|
||||
expectedOutput := fmt.Sprintf("%v", []string{"first third"})
|
||||
if result.Output != expectedOutput {
|
||||
t.Errorf("exptected %v, got %v", expectedOutput, result.Output)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPersistentFlags(t *testing.T) {
|
||||
fullSetupTest("echo -s something -p more here")
|
||||
|
||||
// persistentFlag should act like normal flag on it's own command
|
||||
if strings.Join(te, " ") != "more here" {
|
||||
t.Errorf("flags didn't leave proper args remaining..%s given", te)
|
||||
}
|
||||
if flags1 != "something" {
|
||||
t.Errorf("string flag didn't get correct value, had %v", flags1)
|
||||
}
|
||||
if !flagbp {
|
||||
t.Errorf("persistent bool flag not parsed correctly. Expected true, had %v", flagbp)
|
||||
}
|
||||
|
||||
// persistentFlag should act like normal flag on it's own command
|
||||
fullSetupTest("echo times -s again -c -p test here")
|
||||
|
||||
if strings.Join(tt, " ") != "test here" {
|
||||
t.Errorf("flags didn't leave proper args remaining..%s given", tt)
|
||||
}
|
||||
|
||||
if flags1 != "again" {
|
||||
t.Errorf("string flag didn't get correct value, had %v", flags1)
|
||||
}
|
||||
|
||||
if !flagb2 {
|
||||
t.Errorf("local flag not parsed correctly. Expected true, had %v", flagb2)
|
||||
}
|
||||
if !flagbp {
|
||||
t.Errorf("persistent bool flag not parsed correctly. Expected true, had %v", flagbp)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHelpCommand(t *testing.T) {
|
||||
x := fullSetupTest("help")
|
||||
checkResultContains(t, x, cmdRootWithRun.Long)
|
||||
|
||||
x = fullSetupTest("help echo")
|
||||
checkResultContains(t, x, cmdEcho.Long)
|
||||
|
||||
x = fullSetupTest("help echo times")
|
||||
checkResultContains(t, x, cmdTimes.Long)
|
||||
}
|
||||
|
||||
func TestChildCommandHelp(t *testing.T) {
|
||||
c := noRRSetupTest("print --help")
|
||||
checkResultContains(t, c, strtwoParentHelp)
|
||||
r := noRRSetupTest("echo times --help")
|
||||
checkResultContains(t, r, strtwoChildHelp)
|
||||
}
|
||||
|
||||
func TestNonRunChildHelp(t *testing.T) {
|
||||
x := noRRSetupTest("subnorun")
|
||||
checkResultContains(t, x, cmdSubNoRun.Long)
|
||||
}
|
||||
|
||||
func TestRunnableRootCommand(t *testing.T) {
|
||||
fullSetupTest("")
|
||||
|
||||
if rootcalled != true {
|
||||
t.Errorf("Root Function was not called")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunnableRootCommandNilInput(t *testing.T) {
|
||||
empty_arg := make([]string, 0)
|
||||
c := initializeWithRootCmd()
|
||||
|
||||
buf := new(bytes.Buffer)
|
||||
// Testing flag with invalid input
|
||||
c.SetOutput(buf)
|
||||
cmdEcho.AddCommand(cmdTimes)
|
||||
c.AddCommand(cmdPrint, cmdEcho)
|
||||
c.SetArgs(empty_arg)
|
||||
|
||||
c.Execute()
|
||||
|
||||
if rootcalled != true {
|
||||
t.Errorf("Root Function was not called")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunnableRootCommandEmptyInput(t *testing.T) {
|
||||
args := make([]string, 3)
|
||||
args[0] = ""
|
||||
args[1] = "--introot=12"
|
||||
args[2] = ""
|
||||
c := initializeWithRootCmd()
|
||||
|
||||
buf := new(bytes.Buffer)
|
||||
// Testing flag with invalid input
|
||||
c.SetOutput(buf)
|
||||
cmdEcho.AddCommand(cmdTimes)
|
||||
c.AddCommand(cmdPrint, cmdEcho)
|
||||
c.SetArgs(args)
|
||||
|
||||
c.Execute()
|
||||
|
||||
if rootcalled != true {
|
||||
t.Errorf("Root Function was not called.\n\nOutput was:\n\n%s\n", buf)
|
||||
}
|
||||
}
|
||||
|
||||
func TestInvalidSubcommandWhenArgsAllowed(t *testing.T) {
|
||||
fullSetupTest("echo invalid-sub")
|
||||
|
||||
if te[0] != "invalid-sub" {
|
||||
t.Errorf("Subcommand didn't work...")
|
||||
}
|
||||
}
|
||||
|
||||
func TestRootFlags(t *testing.T) {
|
||||
fullSetupTest("-i 17 -b")
|
||||
|
||||
if flagbr != true {
|
||||
t.Errorf("flag value should be true, %v given", flagbr)
|
||||
}
|
||||
|
||||
if flagir != 17 {
|
||||
t.Errorf("flag value should be 17, %d given", flagir)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRootHelp(t *testing.T) {
|
||||
x := fullSetupTest("--help")
|
||||
|
||||
checkResultContains(t, x, "Available Commands:")
|
||||
checkResultContains(t, x, "for more information about a command")
|
||||
|
||||
if strings.Contains(x.Output, "unknown flag: --help") {
|
||||
t.Errorf("--help shouldn't trigger an error, Got: \n %s", x.Output)
|
||||
}
|
||||
|
||||
if strings.Contains(x.Output, cmdEcho.Use) {
|
||||
t.Errorf("--help shouldn't display subcommand's usage, Got: \n %s", x.Output)
|
||||
}
|
||||
|
||||
x = fullSetupTest("echo --help")
|
||||
|
||||
if strings.Contains(x.Output, cmdTimes.Use) {
|
||||
t.Errorf("--help shouldn't display subsubcommand's usage, Got: \n %s", x.Output)
|
||||
}
|
||||
|
||||
checkResultContains(t, x, "Available Commands:")
|
||||
checkResultContains(t, x, "for more information about a command")
|
||||
|
||||
if strings.Contains(x.Output, "unknown flag: --help") {
|
||||
t.Errorf("--help shouldn't trigger an error, Got: \n %s", x.Output)
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
func TestFlagAccess(t *testing.T) {
|
||||
initialize()
|
||||
|
||||
local := cmdTimes.LocalFlags()
|
||||
inherited := cmdTimes.InheritedFlags()
|
||||
|
||||
for _, f := range []string{"inttwo", "strtwo", "booltwo"} {
|
||||
if local.Lookup(f) == nil {
|
||||
t.Errorf("LocalFlags expected to contain %s, Got: nil", f)
|
||||
}
|
||||
}
|
||||
if inherited.Lookup("strone") == nil {
|
||||
t.Errorf("InheritedFlags expected to contain strone, Got: nil")
|
||||
}
|
||||
if inherited.Lookup("strtwo") != nil {
|
||||
t.Errorf("InheritedFlags shouldn not contain overwritten flag strtwo")
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
func TestNoNRunnableRootCommandNilInput(t *testing.T) {
|
||||
args := make([]string, 0)
|
||||
c := initialize()
|
||||
|
||||
buf := new(bytes.Buffer)
|
||||
// Testing flag with invalid input
|
||||
c.SetOutput(buf)
|
||||
cmdEcho.AddCommand(cmdTimes)
|
||||
c.AddCommand(cmdPrint, cmdEcho)
|
||||
c.SetArgs(args)
|
||||
|
||||
c.Execute()
|
||||
|
||||
if !strings.Contains(buf.String(), cmdRootNoRun.Long) {
|
||||
t.Errorf("Expected to get help output, Got: \n %s", buf)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRootNoCommandHelp(t *testing.T) {
|
||||
x := rootOnlySetupTest("--help")
|
||||
|
||||
checkResultOmits(t, x, "Available Commands:")
|
||||
checkResultOmits(t, x, "for more information about a command")
|
||||
|
||||
if strings.Contains(x.Output, "unknown flag: --help") {
|
||||
t.Errorf("--help shouldn't trigger an error, Got: \n %s", x.Output)
|
||||
}
|
||||
|
||||
x = rootOnlySetupTest("echo --help")
|
||||
|
||||
checkResultOmits(t, x, "Available Commands:")
|
||||
checkResultOmits(t, x, "for more information about a command")
|
||||
|
||||
if strings.Contains(x.Output, "unknown flag: --help") {
|
||||
t.Errorf("--help shouldn't trigger an error, Got: \n %s", x.Output)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRootUnknownCommand(t *testing.T) {
|
||||
r := noRRSetupTest("bogus")
|
||||
s := "Error: unknown command \"bogus\"\nRun 'cobra-test help' for usage.\n"
|
||||
|
||||
if r.Output != s {
|
||||
t.Errorf("Unexpected response.\nExpecting to be:\n %q\nGot:\n %q\n", s, r.Output)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFlagsBeforeCommand(t *testing.T) {
|
||||
// short without space
|
||||
x := fullSetupTest("-i10 echo")
|
||||
if x.Error != nil {
|
||||
t.Errorf("Valid Input shouldn't have errors, got:\n %q", x.Error)
|
||||
}
|
||||
|
||||
// short (int) with equals
|
||||
// It appears that pflags doesn't support this...
|
||||
// Commenting out until support can be added
|
||||
|
||||
//x = noRRSetupTest("echo -i=10")
|
||||
//if x.Error != nil {
|
||||
//t.Errorf("Valid Input shouldn't have errors, got:\n %s", x.Error)
|
||||
//}
|
||||
|
||||
// long with equals
|
||||
x = noRRSetupTest("--intone=123 echo one two")
|
||||
if x.Error != nil {
|
||||
t.Errorf("Valid Input shouldn't have errors, got:\n %s", x.Error)
|
||||
}
|
||||
|
||||
// With parsing error properly reported
|
||||
x = fullSetupTest("-i10E echo")
|
||||
if !strings.Contains(x.Output, "invalid argument \"10E\" for -i10E") {
|
||||
t.Errorf("Wrong error message displayed, \n %s", x.Output)
|
||||
}
|
||||
|
||||
//With quotes
|
||||
x = fullSetupTest("-s=\"walking\" echo")
|
||||
if x.Error != nil {
|
||||
t.Errorf("Valid Input shouldn't have errors, got:\n %q", x.Error)
|
||||
}
|
||||
|
||||
//With quotes and space
|
||||
x = fullSetupTest("-s=\"walking fast\" echo")
|
||||
if x.Error != nil {
|
||||
t.Errorf("Valid Input shouldn't have errors, got:\n %q", x.Error)
|
||||
}
|
||||
|
||||
//With inner quote
|
||||
x = fullSetupTest("-s=\"walking \\\"Inner Quote\\\" fast\" echo")
|
||||
if x.Error != nil {
|
||||
t.Errorf("Valid Input shouldn't have errors, got:\n %q", x.Error)
|
||||
}
|
||||
|
||||
//With quotes and space
|
||||
x = fullSetupTest("-s=\"walking \\\"Inner Quote\\\" fast\" echo")
|
||||
if x.Error != nil {
|
||||
t.Errorf("Valid Input shouldn't have errors, got:\n %q", x.Error)
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
func TestRemoveCommand(t *testing.T) {
|
||||
versionUsed = 0
|
||||
c := initializeWithRootCmd()
|
||||
c.AddCommand(cmdVersion1)
|
||||
c.RemoveCommand(cmdVersion1)
|
||||
x := fullTester(c, "version")
|
||||
if x.Error == nil {
|
||||
t.Errorf("Removed command should not have been called\n")
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
func TestReplaceCommandWithRemove(t *testing.T) {
|
||||
versionUsed = 0
|
||||
c := initializeWithRootCmd()
|
||||
c.AddCommand(cmdVersion1)
|
||||
c.RemoveCommand(cmdVersion1)
|
||||
c.AddCommand(cmdVersion2)
|
||||
x := fullTester(c, "version")
|
||||
if x.Error != nil {
|
||||
t.Errorf("Valid Input shouldn't have errors, got:\n %q", x.Error)
|
||||
return
|
||||
}
|
||||
if versionUsed == 1 {
|
||||
t.Errorf("Removed command shouldn't be called\n")
|
||||
}
|
||||
if versionUsed != 2 {
|
||||
t.Errorf("Replacing command should have been called but didn't\n")
|
||||
}
|
||||
}
|
||||
|
||||
func TestDeprecatedSub(t *testing.T) {
|
||||
c := fullSetupTest("deprecated")
|
||||
|
||||
checkResultContains(t, c, cmdDeprecated.Deprecated)
|
||||
}
|
||||
|
||||
func TestPreRun(t *testing.T) {
|
||||
noRRSetupTest("echo one two")
|
||||
if echoPre == nil || echoPersPre == nil {
|
||||
t.Error("PreRun or PersistentPreRun not called")
|
||||
}
|
||||
if rootPersPre != nil || timesPersPre != nil {
|
||||
t.Error("Wrong *Pre functions called!")
|
||||
}
|
||||
|
||||
noRRSetupTest("echo times one two")
|
||||
if timesPersPre == nil {
|
||||
t.Error("PreRun or PersistentPreRun not called")
|
||||
}
|
||||
if echoPre != nil || echoPersPre != nil || rootPersPre != nil {
|
||||
t.Error("Wrong *Pre functions called!")
|
||||
}
|
||||
|
||||
noRRSetupTest("print one two")
|
||||
if rootPersPre == nil {
|
||||
t.Error("Parent PersistentPreRun not called but should not have been")
|
||||
}
|
||||
if echoPre != nil || echoPersPre != nil || timesPersPre != nil {
|
||||
t.Error("Wrong *Pre functions called!")
|
||||
}
|
||||
}
|
1005
Godeps/_workspace/src/github.com/spf13/cobra/command.go
generated
vendored
Normal file
1005
Godeps/_workspace/src/github.com/spf13/cobra/command.go
generated
vendored
Normal file
File diff suppressed because it is too large
Load Diff
90
Godeps/_workspace/src/github.com/spf13/cobra/command_test.go
generated
vendored
Normal file
90
Godeps/_workspace/src/github.com/spf13/cobra/command_test.go
generated
vendored
Normal file
@ -0,0 +1,90 @@
|
||||
package cobra
|
||||
|
||||
import (
|
||||
"reflect"
|
||||
"testing"
|
||||
)
|
||||
|
||||
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)
|
||||
}
|
||||
}
|
||||
}
|
124
Godeps/_workspace/src/github.com/spf13/cobra/md_docs.go
generated
vendored
Normal file
124
Godeps/_workspace/src/github.com/spf13/cobra/md_docs.go
generated
vendored
Normal file
@ -0,0 +1,124 @@
|
||||
//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 cobra
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"os"
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
func printOptions(out *bytes.Buffer, cmd *Command, name string) {
|
||||
flags := cmd.NonInheritedFlags()
|
||||
flags.SetOutput(out)
|
||||
if flags.HasFlags() {
|
||||
fmt.Fprintf(out, "### Options\n\n```\n")
|
||||
flags.PrintDefaults()
|
||||
fmt.Fprintf(out, "```\n\n")
|
||||
}
|
||||
|
||||
parentFlags := cmd.InheritedFlags()
|
||||
parentFlags.SetOutput(out)
|
||||
if parentFlags.HasFlags() {
|
||||
fmt.Fprintf(out, "### Options inherited from parent commands\n\n```\n")
|
||||
parentFlags.PrintDefaults()
|
||||
fmt.Fprintf(out, "```\n\n")
|
||||
}
|
||||
}
|
||||
|
||||
type byName []*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() }
|
||||
|
||||
func GenMarkdown(cmd *Command, out *bytes.Buffer) {
|
||||
name := cmd.CommandPath()
|
||||
|
||||
short := cmd.Short
|
||||
long := cmd.Long
|
||||
if len(long) == 0 {
|
||||
long = short
|
||||
}
|
||||
|
||||
fmt.Fprintf(out, "## %s\n\n", name)
|
||||
fmt.Fprintf(out, "%s\n\n", short)
|
||||
fmt.Fprintf(out, "### Synopsis\n\n")
|
||||
fmt.Fprintf(out, "\n%s\n\n", long)
|
||||
|
||||
if cmd.Runnable() {
|
||||
fmt.Fprintf(out, "```\n%s\n```\n\n", cmd.UseLine())
|
||||
}
|
||||
|
||||
if len(cmd.Example) > 0 {
|
||||
fmt.Fprintf(out, "### Examples\n\n")
|
||||
fmt.Fprintf(out, "```\n%s\n```\n\n", cmd.Example)
|
||||
}
|
||||
|
||||
printOptions(out, cmd, name)
|
||||
|
||||
if len(cmd.Commands()) > 0 || cmd.HasParent() {
|
||||
fmt.Fprintf(out, "### SEE ALSO\n")
|
||||
if cmd.HasParent() {
|
||||
parent := cmd.Parent()
|
||||
pname := parent.CommandPath()
|
||||
link := pname + ".md"
|
||||
link = strings.Replace(link, " ", "_", -1)
|
||||
fmt.Fprintf(out, "* [%s](%s)\t - %s\n", pname, link, parent.Short)
|
||||
}
|
||||
|
||||
children := cmd.Commands()
|
||||
sort.Sort(byName(children))
|
||||
|
||||
for _, child := range children {
|
||||
if len(child.Deprecated) > 0 {
|
||||
continue
|
||||
}
|
||||
cname := name + " " + child.Name()
|
||||
link := cname + ".md"
|
||||
link = strings.Replace(link, " ", "_", -1)
|
||||
fmt.Fprintf(out, "* [%s](%s)\t - %s\n", cname, link, child.Short)
|
||||
}
|
||||
fmt.Fprintf(out, "\n")
|
||||
}
|
||||
|
||||
fmt.Fprintf(out, "###### Auto generated by spf13/cobra at %s\n", time.Now().UTC())
|
||||
}
|
||||
|
||||
func GenMarkdownTree(cmd *Command, dir string) {
|
||||
for _, c := range cmd.Commands() {
|
||||
GenMarkdownTree(c, dir)
|
||||
}
|
||||
|
||||
out := new(bytes.Buffer)
|
||||
|
||||
GenMarkdown(cmd, out)
|
||||
|
||||
filename := cmd.CommandPath()
|
||||
filename = dir + strings.Replace(filename, " ", "_", -1) + ".md"
|
||||
outFile, err := os.Create(filename)
|
||||
if err != nil {
|
||||
fmt.Println(err)
|
||||
os.Exit(1)
|
||||
}
|
||||
defer outFile.Close()
|
||||
_, err = outFile.Write(out.Bytes())
|
||||
if err != nil {
|
||||
fmt.Println(err)
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
35
Godeps/_workspace/src/github.com/spf13/cobra/md_docs.md
generated
vendored
Normal file
35
Godeps/_workspace/src/github.com/spf13/cobra/md_docs.md
generated
vendored
Normal file
@ -0,0 +1,35 @@
|
||||
# Generating Markdown Docs For Your Own cobra.Command
|
||||
|
||||
## 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"
|
||||
|
||||
"github.com/GoogleCloudPlatform/kubernetes/pkg/kubectl/cmd"
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
func main() {
|
||||
kubectl := cmd.NewFactory(nil).NewKubectlCommand(os.Stdin, ioutil.Discard, ioutil.Discard)
|
||||
cobra.GenMarkdownTree(kubectl, "./")
|
||||
}
|
||||
```
|
||||
|
||||
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)
|
||||
cobra.GenMarkdown(cmd, out)
|
||||
```
|
||||
|
||||
This will write the markdown doc for ONLY "cmd" into the out, buffer.
|
67
Godeps/_workspace/src/github.com/spf13/cobra/md_docs_test.go
generated
vendored
Normal file
67
Godeps/_workspace/src/github.com/spf13/cobra/md_docs_test.go
generated
vendored
Normal file
@ -0,0 +1,67 @@
|
||||
package cobra
|
||||
|
||||
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
|
||||
GenMarkdown(cmdEcho, out)
|
||||
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)
|
||||
}
|
||||
}
|
28
Godeps/_workspace/src/github.com/spf13/pflag/LICENSE
generated
vendored
Normal file
28
Godeps/_workspace/src/github.com/spf13/pflag/LICENSE
generated
vendored
Normal file
@ -0,0 +1,28 @@
|
||||
Copyright (c) 2012 Alex Ogier. All rights reserved.
|
||||
Copyright (c) 2012 The Go Authors. All rights reserved.
|
||||
|
||||
Redistribution and use in source and binary forms, with or without
|
||||
modification, are permitted provided that the following conditions are
|
||||
met:
|
||||
|
||||
* Redistributions of source code must retain the above copyright
|
||||
notice, this list of conditions and the following disclaimer.
|
||||
* Redistributions in binary form must reproduce the above
|
||||
copyright notice, this list of conditions and the following disclaimer
|
||||
in the documentation and/or other materials provided with the
|
||||
distribution.
|
||||
* Neither the name of Google Inc. nor the names of its
|
||||
contributors may be used to endorse or promote products derived from
|
||||
this software without specific prior written permission.
|
||||
|
||||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
||||
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
||||
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
||||
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
||||
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
||||
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
||||
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
189
Godeps/_workspace/src/github.com/spf13/pflag/README.md
generated
vendored
Normal file
189
Godeps/_workspace/src/github.com/spf13/pflag/README.md
generated
vendored
Normal file
@ -0,0 +1,189 @@
|
||||
## Description
|
||||
|
||||
pflag is a drop-in replacement for Go's flag package, implementing
|
||||
POSIX/GNU-style --flags.
|
||||
|
||||
pflag is compatible with the [GNU extensions to the POSIX recommendations
|
||||
for command-line options][1]. For a more precise description, see the
|
||||
"Command-line flag syntax" section below.
|
||||
|
||||
[1]: http://www.gnu.org/software/libc/manual/html_node/Argument-Syntax.html
|
||||
|
||||
pflag is available under the same style of BSD license as the Go language,
|
||||
which can be found in the LICENSE file.
|
||||
|
||||
## Installation
|
||||
|
||||
pflag is available using the standard `go get` command.
|
||||
|
||||
Install by running:
|
||||
|
||||
go get github.com/ogier/pflag
|
||||
|
||||
Run tests by running:
|
||||
|
||||
go test github.com/ogier/pflag
|
||||
|
||||
## Usage
|
||||
|
||||
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.
|
||||
|
||||
``` go
|
||||
import flag "github.com/ogier/pflag"
|
||||
```
|
||||
|
||||
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
|
||||
unaffected.
|
||||
|
||||
Define flags using flag.String(), Bool(), Int(), etc.
|
||||
|
||||
This declares an integer flag, -flagname, stored in the pointer ip, with type *int.
|
||||
|
||||
``` go
|
||||
var ip *int = flag.Int("flagname", 1234, "help message for flagname")
|
||||
```
|
||||
|
||||
If you like, you can bind the flag to a variable using the Var() functions.
|
||||
|
||||
``` go
|
||||
var flagvar int
|
||||
func init() {
|
||||
flag.IntVar(&flagvar, "flagname", 1234, "help message for flagname")
|
||||
}
|
||||
```
|
||||
|
||||
Or you can create custom flags that satisfy the Value interface (with
|
||||
pointer receivers) and couple them to flag parsing by
|
||||
|
||||
``` go
|
||||
flag.Var(&flagVal, "name", "help message for flagname")
|
||||
```
|
||||
|
||||
For such flags, the default value is just the initial value of the variable.
|
||||
|
||||
After all flags are defined, call
|
||||
|
||||
``` go
|
||||
flag.Parse()
|
||||
```
|
||||
|
||||
to parse the command line into the defined flags.
|
||||
|
||||
Flags may then be used directly. If you're using the flags themselves,
|
||||
they are all pointers; if you bind to variables, they're values.
|
||||
|
||||
``` go
|
||||
fmt.Println("ip has value ", *ip)
|
||||
fmt.Println("flagvar has value ", flagvar)
|
||||
```
|
||||
|
||||
After parsing, the arguments after the flag are available as the
|
||||
slice flag.Args() or individually as flag.Arg(i).
|
||||
The arguments are indexed from 0 through flag.NArg()-1.
|
||||
|
||||
The pflag package also defines some new functions that are not in flag,
|
||||
that give one-letter shorthands for flags. You can use these by appending
|
||||
'P' to the name of any function that defines a flag.
|
||||
|
||||
``` go
|
||||
var ip = flag.IntP("flagname", "f", 1234, "help message")
|
||||
var flagvar bool
|
||||
func init() {
|
||||
flag.BoolVarP("boolname", "b", true, "help message")
|
||||
}
|
||||
flag.VarP(&flagVar, "varname", "v", 1234, "help message")
|
||||
```
|
||||
|
||||
Shorthand letters can be used with single dashes on the command line.
|
||||
Boolean shorthand flags can be combined with other shorthand flags.
|
||||
|
||||
The default set of command-line flags is controlled by
|
||||
top-level functions. The FlagSet type allows one to define
|
||||
independent sets of flags, such as to implement subcommands
|
||||
in a command-line interface. The methods of FlagSet are
|
||||
analogous to the top-level functions for the command-line
|
||||
flag set.
|
||||
|
||||
## Command line flag syntax
|
||||
|
||||
```
|
||||
--flag // boolean flags only
|
||||
--flag=x
|
||||
```
|
||||
|
||||
Unlike the flag package, a single dash before an option means something
|
||||
different than a double dash. Single dashes signify a series of shorthand
|
||||
letters for flags. All but the last shorthand letter must be boolean flags.
|
||||
|
||||
```
|
||||
// boolean flags
|
||||
-f
|
||||
-abc
|
||||
|
||||
// non-boolean flags
|
||||
-n 1234
|
||||
-Ifile
|
||||
|
||||
// mixed
|
||||
-abcs "hello"
|
||||
-abcn1234
|
||||
```
|
||||
|
||||
Flag parsing stops after the terminator "--". Unlike the flag package,
|
||||
flags can be interspersed with arguments anywhere on the command line
|
||||
before this terminator.
|
||||
|
||||
Integer flags accept 1234, 0664, 0x1234 and may be negative.
|
||||
Boolean flags (in their long form) accept 1, 0, t, f, true, false,
|
||||
TRUE, FALSE, True, False.
|
||||
Duration flags accept any input valid for time.ParseDuration.
|
||||
|
||||
## Mutating or "Normalizing" Flag names
|
||||
|
||||
It is possible to set a custom flag name 'normalization function.' It allows flag names to be mutated both when created in the code and when used on the command line to some 'normalized' form. The 'normalized' form is used for comparison. Two examples of using the custom normalization func follow.
|
||||
|
||||
**Example #1**: You want -, _, and . in flags to compare the same. aka --my-flag == --my_flag == --my.flag
|
||||
|
||||
```go
|
||||
func wordSepNormalizeFunc(f *pflag.FlagSet, name string) pflag.NormalizedName {
|
||||
from := []string{"-", "_"}
|
||||
to := "."
|
||||
for _, sep := range from {
|
||||
name = strings.Replace(name, sep, to, -1)
|
||||
}
|
||||
return pflag.NormalizedName(name)
|
||||
}
|
||||
|
||||
myFlagSet.SetNormalizeFunc(wordSepNormalizeFunc)
|
||||
```
|
||||
|
||||
**Example #2**: You want to alias two flags. aka --old-flag-name == --new-flag-name
|
||||
|
||||
```go
|
||||
func aliasNormalizeFunc(f *pflag.FlagSet, name string) pflag.NormalizedName {
|
||||
switch name {
|
||||
case "old-flag-name":
|
||||
name = "new-flag-name"
|
||||
break
|
||||
}
|
||||
return pflag.NormalizedName(name)
|
||||
}
|
||||
|
||||
myFlagSet.SetNormalizeFunc(aliasNormalizeFunc)
|
||||
```
|
||||
|
||||
## 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
|
||||
installation.
|
||||
|
||||
[2]: http://localhost:6060/pkg/github.com/ogier/pflag
|
||||
[3]: http://godoc.org/github.com/ogier/pflag
|
83
Godeps/_workspace/src/github.com/spf13/pflag/bool.go
generated
vendored
Normal file
83
Godeps/_workspace/src/github.com/spf13/pflag/bool.go
generated
vendored
Normal file
@ -0,0 +1,83 @@
|
||||
package pflag
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strconv"
|
||||
)
|
||||
|
||||
// optional interface to indicate boolean flags that can be
|
||||
// supplied without "=value" text
|
||||
type boolFlag interface {
|
||||
Value
|
||||
IsBoolFlag() bool
|
||||
}
|
||||
|
||||
// -- bool Value
|
||||
type boolValue bool
|
||||
|
||||
func newBoolValue(val bool, p *bool) *boolValue {
|
||||
*p = val
|
||||
return (*boolValue)(p)
|
||||
}
|
||||
|
||||
func (b *boolValue) Set(s string) error {
|
||||
v, err := strconv.ParseBool(s)
|
||||
*b = boolValue(v)
|
||||
return err
|
||||
}
|
||||
|
||||
func (b *boolValue) Type() string {
|
||||
return "bool"
|
||||
}
|
||||
|
||||
func (b *boolValue) String() string { return fmt.Sprintf("%v", *b) }
|
||||
|
||||
func (b *boolValue) IsBoolFlag() bool { return true }
|
||||
|
||||
// BoolVar 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 (f *FlagSet) BoolVar(p *bool, name string, value bool, usage string) {
|
||||
f.VarP(newBoolValue(value, p), name, "", usage)
|
||||
}
|
||||
|
||||
// Like BoolVar, but accepts a shorthand letter that can be used after a single dash.
|
||||
func (f *FlagSet) BoolVarP(p *bool, name, shorthand string, value bool, usage string) {
|
||||
f.VarP(newBoolValue(value, p), name, shorthand, usage)
|
||||
}
|
||||
|
||||
// BoolVar 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 BoolVar(p *bool, name string, value bool, usage string) {
|
||||
CommandLine.VarP(newBoolValue(value, p), name, "", usage)
|
||||
}
|
||||
|
||||
// Like BoolVar, but accepts a shorthand letter that can be used after a single dash.
|
||||
func BoolVarP(p *bool, name, shorthand string, value bool, usage string) {
|
||||
CommandLine.VarP(newBoolValue(value, p), name, shorthand, usage)
|
||||
}
|
||||
|
||||
// Bool 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) Bool(name string, value bool, usage string) *bool {
|
||||
p := new(bool)
|
||||
f.BoolVarP(p, name, "", value, usage)
|
||||
return p
|
||||
}
|
||||
|
||||
// Like Bool, but accepts a shorthand letter that can be used after a single dash.
|
||||
func (f *FlagSet) BoolP(name, shorthand string, value bool, usage string) *bool {
|
||||
p := new(bool)
|
||||
f.BoolVarP(p, name, shorthand, value, usage)
|
||||
return p
|
||||
}
|
||||
|
||||
// Bool 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 Bool(name string, value bool, usage string) *bool {
|
||||
return CommandLine.BoolP(name, "", value, usage)
|
||||
}
|
||||
|
||||
// Like Bool, but accepts a shorthand letter that can be used after a single dash.
|
||||
func BoolP(name, shorthand string, value bool, usage string) *bool {
|
||||
return CommandLine.BoolP(name, shorthand, value, usage)
|
||||
}
|
164
Godeps/_workspace/src/github.com/spf13/pflag/bool_test.go
generated
vendored
Normal file
164
Godeps/_workspace/src/github.com/spf13/pflag/bool_test.go
generated
vendored
Normal file
@ -0,0 +1,164 @@
|
||||
// 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_test
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strconv"
|
||||
"testing"
|
||||
|
||||
. "github.com/khlieng/name_pending/Godeps/_workspace/src/github.com/spf13/pflag"
|
||||
)
|
||||
|
||||
// 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 requred by the pflag.Value interface
|
||||
func (v *triStateValue) Type() string {
|
||||
return "version"
|
||||
}
|
||||
|
||||
func setUpFlagSet(tristate *triStateValue) *FlagSet {
|
||||
f := NewFlagSet("test", ContinueOnError)
|
||||
*tristate = triStateFalse
|
||||
f.VarP(tristate, "tristate", "t", "tristate value (true, maybe or false)")
|
||||
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)
|
||||
args := []string{"--tristate=invalid"}
|
||||
_, err := parseReturnStderr(t, f, args)
|
||||
if err == nil {
|
||||
t.Fatal("expected an error but did not get any, tristate has value", tristate)
|
||||
}
|
||||
}
|
71
Godeps/_workspace/src/github.com/spf13/pflag/duration.go
generated
vendored
Normal file
71
Godeps/_workspace/src/github.com/spf13/pflag/duration.go
generated
vendored
Normal file
@ -0,0 +1,71 @@
|
||||
package pflag
|
||||
|
||||
import "time"
|
||||
|
||||
// -- time.Duration Value
|
||||
type durationValue time.Duration
|
||||
|
||||
func newDurationValue(val time.Duration, p *time.Duration) *durationValue {
|
||||
*p = val
|
||||
return (*durationValue)(p)
|
||||
}
|
||||
|
||||
func (d *durationValue) Set(s string) error {
|
||||
v, err := time.ParseDuration(s)
|
||||
*d = durationValue(v)
|
||||
return err
|
||||
}
|
||||
|
||||
func (d *durationValue) Type() string {
|
||||
return "duration"
|
||||
}
|
||||
|
||||
func (d *durationValue) String() string { return (*time.Duration)(d).String() }
|
||||
|
||||
// DurationVar defines a time.Duration flag with specified name, default value, and usage string.
|
||||
// The argument p points to a time.Duration variable in which to store the value of the flag.
|
||||
func (f *FlagSet) DurationVar(p *time.Duration, name string, value time.Duration, usage string) {
|
||||
f.VarP(newDurationValue(value, p), name, "", usage)
|
||||
}
|
||||
|
||||
// Like DurationVar, but accepts a shorthand letter that can be used after a single dash.
|
||||
func (f *FlagSet) DurationVarP(p *time.Duration, name, shorthand string, value time.Duration, usage string) {
|
||||
f.VarP(newDurationValue(value, p), name, shorthand, usage)
|
||||
}
|
||||
|
||||
// DurationVar defines a time.Duration flag with specified name, default value, and usage string.
|
||||
// The argument p points to a time.Duration variable in which to store the value of the flag.
|
||||
func DurationVar(p *time.Duration, name string, value time.Duration, usage string) {
|
||||
CommandLine.VarP(newDurationValue(value, p), name, "", usage)
|
||||
}
|
||||
|
||||
// Like DurationVar, but accepts a shorthand letter that can be used after a single dash.
|
||||
func DurationVarP(p *time.Duration, name, shorthand string, value time.Duration, usage string) {
|
||||
CommandLine.VarP(newDurationValue(value, p), name, shorthand, usage)
|
||||
}
|
||||
|
||||
// Duration defines a time.Duration flag with specified name, default value, and usage string.
|
||||
// The return value is the address of a time.Duration variable that stores the value of the flag.
|
||||
func (f *FlagSet) Duration(name string, value time.Duration, usage string) *time.Duration {
|
||||
p := new(time.Duration)
|
||||
f.DurationVarP(p, name, "", value, usage)
|
||||
return p
|
||||
}
|
||||
|
||||
// Like Duration, but accepts a shorthand letter that can be used after a single dash.
|
||||
func (f *FlagSet) DurationP(name, shorthand string, value time.Duration, usage string) *time.Duration {
|
||||
p := new(time.Duration)
|
||||
f.DurationVarP(p, name, shorthand, value, usage)
|
||||
return p
|
||||
}
|
||||
|
||||
// Duration defines a time.Duration flag with specified name, default value, and usage string.
|
||||
// The return value is the address of a time.Duration variable that stores the value of the flag.
|
||||
func Duration(name string, value time.Duration, usage string) *time.Duration {
|
||||
return CommandLine.DurationP(name, "", value, usage)
|
||||
}
|
||||
|
||||
// Like Duration, but accepts a shorthand letter that can be used after a single dash.
|
||||
func DurationP(name, shorthand string, value time.Duration, usage string) *time.Duration {
|
||||
return CommandLine.DurationP(name, shorthand, value, usage)
|
||||
}
|
77
Godeps/_workspace/src/github.com/spf13/pflag/example_test.go
generated
vendored
Normal file
77
Godeps/_workspace/src/github.com/spf13/pflag/example_test.go
generated
vendored
Normal file
@ -0,0 +1,77 @@
|
||||
// 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/khlieng/name_pending/Godeps/_workspace/src/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
Godeps/_workspace/src/github.com/spf13/pflag/export_test.go
generated
vendored
Normal file
29
Godeps/_workspace/src/github.com/spf13/pflag/export_test.go
generated
vendored
Normal file
@ -0,0 +1,29 @@
|
||||
// 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
|
||||
}
|
692
Godeps/_workspace/src/github.com/spf13/pflag/flag.go
generated
vendored
Normal file
692
Godeps/_workspace/src/github.com/spf13/pflag/flag.go
generated
vendored
Normal file
@ -0,0 +1,692 @@
|
||||
// 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.
|
||||
|
||||
/*
|
||||
pflag is a drop-in replacement for Go's flag package, implementing
|
||||
POSIX/GNU-style --flags.
|
||||
|
||||
pflag is compatible with the GNU extensions to the POSIX recommendations
|
||||
for command-line options. See
|
||||
http://www.gnu.org/software/libc/manual/html_node/Argument-Syntax.html
|
||||
|
||||
Usage:
|
||||
|
||||
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"
|
||||
|
||||
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
|
||||
unaffected.
|
||||
|
||||
Define flags using flag.String(), Bool(), Int(), etc.
|
||||
|
||||
This declares an integer flag, -flagname, stored in the pointer ip, with type *int.
|
||||
var ip = flag.Int("flagname", 1234, "help message for flagname")
|
||||
If you like, you can bind the flag to a variable using the Var() functions.
|
||||
var flagvar int
|
||||
func init() {
|
||||
flag.IntVar(&flagvar, "flagname", 1234, "help message for flagname")
|
||||
}
|
||||
Or you can create custom flags that satisfy the Value interface (with
|
||||
pointer receivers) and couple them to flag parsing by
|
||||
flag.Var(&flagVal, "name", "help message for flagname")
|
||||
For such flags, the default value is just the initial value of the variable.
|
||||
|
||||
After all flags are defined, call
|
||||
flag.Parse()
|
||||
to parse the command line into the defined flags.
|
||||
|
||||
Flags may then be used directly. If you're using the flags themselves,
|
||||
they are all pointers; if you bind to variables, they're values.
|
||||
fmt.Println("ip has value ", *ip)
|
||||
fmt.Println("flagvar has value ", flagvar)
|
||||
|
||||
After parsing, the arguments after the flag are available as the
|
||||
slice flag.Args() or individually as flag.Arg(i).
|
||||
The arguments are indexed from 0 through flag.NArg()-1.
|
||||
|
||||
The pflag package also defines some new functions that are not in flag,
|
||||
that give one-letter shorthands for flags. You can use these by appending
|
||||
'P' to the name of any function that defines a flag.
|
||||
var ip = flag.IntP("flagname", "f", 1234, "help message")
|
||||
var flagvar bool
|
||||
func init() {
|
||||
flag.BoolVarP("boolname", "b", true, "help message")
|
||||
}
|
||||
flag.VarP(&flagVar, "varname", "v", 1234, "help message")
|
||||
Shorthand letters can be used with single dashes on the command line.
|
||||
Boolean shorthand flags can be combined with other shorthand flags.
|
||||
|
||||
Command line flag syntax:
|
||||
--flag // boolean flags only
|
||||
--flag=x
|
||||
|
||||
Unlike the flag package, a single dash before an option means something
|
||||
different than a double dash. Single dashes signify a series of shorthand
|
||||
letters for flags. All but the last shorthand letter must be boolean flags.
|
||||
// boolean flags
|
||||
-f
|
||||
-abc
|
||||
// non-boolean flags
|
||||
-n 1234
|
||||
-Ifile
|
||||
// mixed
|
||||
-abcs "hello"
|
||||
-abcn1234
|
||||
|
||||
Flag parsing stops after the terminator "--". Unlike the flag package,
|
||||
flags can be interspersed with arguments anywhere on the command line
|
||||
before this terminator.
|
||||
|
||||
Integer flags accept 1234, 0664, 0x1234 and may be negative.
|
||||
Boolean flags (in their long form) accept 1, 0, t, f, true, false,
|
||||
TRUE, FALSE, True, False.
|
||||
Duration flags accept any input valid for time.ParseDuration.
|
||||
|
||||
The default set of command-line flags is controlled by
|
||||
top-level functions. The FlagSet type allows one to define
|
||||
independent sets of flags, such as to implement subcommands
|
||||
in a command-line interface. The methods of FlagSet are
|
||||
analogous to the top-level functions for the command-line
|
||||
flag set.
|
||||
*/
|
||||
package pflag
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"sort"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// ErrHelp is the error returned if the flag -help is invoked but no such flag is defined.
|
||||
var ErrHelp = errors.New("pflag: help requested")
|
||||
|
||||
// ErrorHandling defines how to handle flag parsing errors.
|
||||
type ErrorHandling int
|
||||
|
||||
const (
|
||||
ContinueOnError ErrorHandling = iota
|
||||
ExitOnError
|
||||
PanicOnError
|
||||
)
|
||||
|
||||
// NormalizedName is a flag name that has been normalized according to rules
|
||||
// for the FlagSet (e.g. making '-' and '_' equivalent).
|
||||
type NormalizedName string
|
||||
|
||||
// A FlagSet represents a set of defined flags.
|
||||
type FlagSet struct {
|
||||
// Usage is the function called when an error occurs while parsing flags.
|
||||
// The field is a function (not a method) that may be changed to point to
|
||||
// a custom error handler.
|
||||
Usage func()
|
||||
|
||||
name string
|
||||
parsed bool
|
||||
actual map[NormalizedName]*Flag
|
||||
formal map[NormalizedName]*Flag
|
||||
shorthands map[byte]*Flag
|
||||
args []string // arguments after flags
|
||||
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
|
||||
normalizeNameFunc func(f *FlagSet, name string) NormalizedName
|
||||
}
|
||||
|
||||
// A Flag represents the state of a flag.
|
||||
type Flag struct {
|
||||
Name string // name as it appears on command line
|
||||
Shorthand string // one-letter abbreviated flag
|
||||
Usage string // help message
|
||||
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)
|
||||
Deprecated string // If this flag is deprecated, this string is the new or now thing to use
|
||||
Annotations map[string][]string // used by cobra.Command bash autocomple code
|
||||
}
|
||||
|
||||
// Value is the interface to the dynamic value stored in a flag.
|
||||
// (The default value is represented as a string.)
|
||||
type Value interface {
|
||||
String() string
|
||||
Set(string) error
|
||||
Type() string
|
||||
}
|
||||
|
||||
// sortFlags returns the flags as a slice in lexicographical sorted order.
|
||||
func sortFlags(flags map[NormalizedName]*Flag) []*Flag {
|
||||
list := make(sort.StringSlice, len(flags))
|
||||
i := 0
|
||||
for k := range flags {
|
||||
list[i] = string(k)
|
||||
i++
|
||||
}
|
||||
list.Sort()
|
||||
result := make([]*Flag, len(list))
|
||||
for i, name := range list {
|
||||
result[i] = flags[NormalizedName(name)]
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func (f *FlagSet) SetNormalizeFunc(n func(f *FlagSet, name string) NormalizedName) {
|
||||
f.normalizeNameFunc = n
|
||||
for k, v := range f.formal {
|
||||
delete(f.formal, k)
|
||||
f.formal[f.normalizeFlagName(string(k))] = v
|
||||
}
|
||||
}
|
||||
|
||||
func (f *FlagSet) GetNormalizeFunc() func(f *FlagSet, name string) NormalizedName {
|
||||
if f.normalizeNameFunc != nil {
|
||||
return f.normalizeNameFunc
|
||||
}
|
||||
return func(f *FlagSet, name string) NormalizedName { return NormalizedName(name) }
|
||||
}
|
||||
|
||||
func (f *FlagSet) normalizeFlagName(name string) NormalizedName {
|
||||
n := f.GetNormalizeFunc()
|
||||
return n(f, name)
|
||||
}
|
||||
|
||||
func (f *FlagSet) out() io.Writer {
|
||||
if f.output == nil {
|
||||
return os.Stderr
|
||||
}
|
||||
return f.output
|
||||
}
|
||||
|
||||
// SetOutput sets the destination for usage and error messages.
|
||||
// If output is nil, os.Stderr is used.
|
||||
func (f *FlagSet) SetOutput(output io.Writer) {
|
||||
f.output = output
|
||||
}
|
||||
|
||||
// VisitAll visits the flags in lexicographical order, 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) {
|
||||
fn(flag)
|
||||
}
|
||||
}
|
||||
|
||||
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.
|
||||
func VisitAll(fn func(*Flag)) {
|
||||
CommandLine.VisitAll(fn)
|
||||
}
|
||||
|
||||
// Visit visits the flags in lexicographical order, 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) {
|
||||
fn(flag)
|
||||
}
|
||||
}
|
||||
|
||||
// Visit visits the command-line flags in lexicographical order, calling fn
|
||||
// for each. It visits only those flags that have been set.
|
||||
func Visit(fn func(*Flag)) {
|
||||
CommandLine.Visit(fn)
|
||||
}
|
||||
|
||||
// Lookup returns the Flag structure of the named flag, returning nil if none exists.
|
||||
func (f *FlagSet) Lookup(name string) *Flag {
|
||||
return f.lookup(f.normalizeFlagName(name))
|
||||
}
|
||||
|
||||
// lookup returns the Flag structure of the named flag, returning nil if none exists.
|
||||
func (f *FlagSet) lookup(name NormalizedName) *Flag {
|
||||
return f.formal[name]
|
||||
}
|
||||
|
||||
// Mark a flag deprecated in your program
|
||||
func (f *FlagSet) MarkDeprecated(name string, usageMessage string) error {
|
||||
flag := f.Lookup(name)
|
||||
if flag == nil {
|
||||
return fmt.Errorf("flag %q does not exist", name)
|
||||
}
|
||||
flag.Deprecated = usageMessage
|
||||
return nil
|
||||
}
|
||||
|
||||
// Lookup returns the Flag structure of the named command-line flag,
|
||||
// returning nil if none exists.
|
||||
func Lookup(name string) *Flag {
|
||||
return CommandLine.Lookup(name)
|
||||
}
|
||||
|
||||
// Set sets the value of the named flag.
|
||||
func (f *FlagSet) Set(name, value string) error {
|
||||
normalName := f.normalizeFlagName(name)
|
||||
flag, ok := f.formal[normalName]
|
||||
if !ok {
|
||||
return fmt.Errorf("no such flag -%v", name)
|
||||
}
|
||||
err := flag.Value.Set(value)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if f.actual == nil {
|
||||
f.actual = make(map[NormalizedName]*Flag)
|
||||
}
|
||||
f.actual[normalName] = flag
|
||||
flag.Changed = true
|
||||
if len(flag.Deprecated) > 0 {
|
||||
fmt.Fprintf(os.Stderr, "Flag --%s has been deprecated, %s\n", flag.Name, flag.Deprecated)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Set sets the value of the named command-line flag.
|
||||
func Set(name, value string) error {
|
||||
return CommandLine.Set(name, value)
|
||||
}
|
||||
|
||||
// PrintDefaults prints, to standard error unless configured
|
||||
// otherwise, the default values of all defined flags in the set.
|
||||
func (f *FlagSet) PrintDefaults() {
|
||||
f.VisitAll(func(flag *Flag) {
|
||||
if len(flag.Deprecated) > 0 {
|
||||
return
|
||||
}
|
||||
format := "--%s=%s: %s\n"
|
||||
if _, ok := flag.Value.(*stringValue); ok {
|
||||
// put quotes on the value
|
||||
format = "--%s=%q: %s\n"
|
||||
}
|
||||
if len(flag.Shorthand) > 0 {
|
||||
format = " -%s, " + format
|
||||
} else {
|
||||
format = " %s " + format
|
||||
}
|
||||
fmt.Fprintf(f.out(), format, flag.Shorthand, flag.Name, flag.DefValue, flag.Usage)
|
||||
})
|
||||
}
|
||||
|
||||
func (f *FlagSet) FlagUsages() string {
|
||||
x := new(bytes.Buffer)
|
||||
|
||||
f.VisitAll(func(flag *Flag) {
|
||||
if len(flag.Deprecated) > 0 {
|
||||
return
|
||||
}
|
||||
format := "--%s=%s: %s\n"
|
||||
if _, ok := flag.Value.(*stringValue); ok {
|
||||
// put quotes on the value
|
||||
format = "--%s=%q: %s\n"
|
||||
}
|
||||
if len(flag.Shorthand) > 0 {
|
||||
format = " -%s, " + format
|
||||
} else {
|
||||
format = " %s " + format
|
||||
}
|
||||
fmt.Fprintf(x, format, flag.Shorthand, flag.Name, flag.DefValue, flag.Usage)
|
||||
})
|
||||
|
||||
return x.String()
|
||||
}
|
||||
|
||||
// PrintDefaults prints to standard error the default values of all defined command-line flags.
|
||||
func PrintDefaults() {
|
||||
CommandLine.PrintDefaults()
|
||||
}
|
||||
|
||||
// defaultUsage is the default function to print a usage message.
|
||||
func defaultUsage(f *FlagSet) {
|
||||
fmt.Fprintf(f.out(), "Usage of %s:\n", f.name)
|
||||
f.PrintDefaults()
|
||||
}
|
||||
|
||||
// NOTE: Usage is not just defaultUsage(CommandLine)
|
||||
// because it serves (via godoc flag Usage) as the example
|
||||
// for how to write your own usage function.
|
||||
|
||||
// Usage prints to standard error a usage message documenting all defined command-line flags.
|
||||
// The function is a variable that may be changed to point to a custom function.
|
||||
var Usage = func() {
|
||||
fmt.Fprintf(os.Stderr, "Usage of %s:\n", os.Args[0])
|
||||
PrintDefaults()
|
||||
}
|
||||
|
||||
// NFlag returns the number of flags that have been set.
|
||||
func (f *FlagSet) NFlag() int { return len(f.actual) }
|
||||
|
||||
// NFlag returns the number of command-line flags that have been set.
|
||||
func NFlag() int { return len(CommandLine.actual) }
|
||||
|
||||
// Arg returns the i'th argument. Arg(0) is the first remaining argument
|
||||
// after flags have been processed.
|
||||
func (f *FlagSet) Arg(i int) string {
|
||||
if i < 0 || i >= len(f.args) {
|
||||
return ""
|
||||
}
|
||||
return f.args[i]
|
||||
}
|
||||
|
||||
// Arg returns the i'th command-line argument. Arg(0) is the first remaining argument
|
||||
// after flags have been processed.
|
||||
func Arg(i int) string {
|
||||
return CommandLine.Arg(i)
|
||||
}
|
||||
|
||||
// NArg is the number of arguments remaining after flags have been processed.
|
||||
func (f *FlagSet) NArg() int { return len(f.args) }
|
||||
|
||||
// NArg is the number of arguments remaining after flags have been processed.
|
||||
func NArg() int { return len(CommandLine.args) }
|
||||
|
||||
// Args returns the non-flag arguments.
|
||||
func (f *FlagSet) Args() []string { return f.args }
|
||||
|
||||
// Args returns the non-flag command-line arguments.
|
||||
func Args() []string { return CommandLine.args }
|
||||
|
||||
// Var defines a flag with the specified name and usage string. The type and
|
||||
// value of the flag are represented by the first argument, of type Value, which
|
||||
// typically holds a user-defined implementation of Value. For instance, the
|
||||
// caller could create a flag that turns a comma-separated string into a slice
|
||||
// of strings by giving the slice the methods of Value; in particular, Set would
|
||||
// decompose the comma-separated string into the slice.
|
||||
func (f *FlagSet) Var(value Value, name string, usage string) {
|
||||
f.VarP(value, name, "", usage)
|
||||
}
|
||||
|
||||
// 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) {
|
||||
// Remember the default value as a string; it won't change.
|
||||
flag := &Flag{
|
||||
Name: name,
|
||||
Shorthand: shorthand,
|
||||
Usage: usage,
|
||||
Value: value,
|
||||
DefValue: value.String(),
|
||||
}
|
||||
f.AddFlag(flag)
|
||||
}
|
||||
|
||||
func (f *FlagSet) AddFlag(flag *Flag) {
|
||||
_, alreadythere := f.formal[f.normalizeFlagName(flag.Name)]
|
||||
if alreadythere {
|
||||
msg := fmt.Sprintf("%s flag redefined: %s", f.name, flag.Name)
|
||||
fmt.Fprintln(f.out(), msg)
|
||||
panic(msg) // Happens only if flags are declared with identical names
|
||||
}
|
||||
if f.formal == nil {
|
||||
f.formal = make(map[NormalizedName]*Flag)
|
||||
}
|
||||
f.formal[f.normalizeFlagName(flag.Name)] = flag
|
||||
|
||||
if len(flag.Shorthand) == 0 {
|
||||
return
|
||||
}
|
||||
if len(flag.Shorthand) > 1 {
|
||||
fmt.Fprintf(f.out(), "%s shorthand more than ASCII character: %s\n", f.name, flag.Shorthand)
|
||||
panic("shorthand is more than one character")
|
||||
}
|
||||
if f.shorthands == nil {
|
||||
f.shorthands = make(map[byte]*Flag)
|
||||
}
|
||||
c := flag.Shorthand[0]
|
||||
old, alreadythere := f.shorthands[c]
|
||||
if alreadythere {
|
||||
fmt.Fprintf(f.out(), "%s shorthand reused: %q for %s already used for %s\n", f.name, c, flag.Name, old.Name)
|
||||
panic("shorthand redefinition")
|
||||
}
|
||||
f.shorthands[c] = flag
|
||||
}
|
||||
|
||||
// Var defines a flag with the specified name and usage string. The type and
|
||||
// value of the flag are represented by the first argument, of type Value, which
|
||||
// typically holds a user-defined implementation of Value. For instance, the
|
||||
// caller could create a flag that turns a comma-separated string into a slice
|
||||
// of strings by giving the slice the methods of Value; in particular, Set would
|
||||
// decompose the comma-separated string into the slice.
|
||||
func Var(value Value, name string, usage string) {
|
||||
CommandLine.VarP(value, name, "", usage)
|
||||
}
|
||||
|
||||
// Like Var, but accepts a shorthand letter that can be used after a single dash.
|
||||
func VarP(value Value, name, shorthand, usage string) {
|
||||
CommandLine.VarP(value, name, shorthand, usage)
|
||||
}
|
||||
|
||||
// failf prints to standard error a formatted error and usage message and
|
||||
// returns the error.
|
||||
func (f *FlagSet) failf(format string, a ...interface{}) error {
|
||||
err := fmt.Errorf(format, a...)
|
||||
fmt.Fprintln(f.out(), err)
|
||||
f.usage()
|
||||
return err
|
||||
}
|
||||
|
||||
// usage calls the Usage method for the flag set, or the usage function if
|
||||
// the flag set is CommandLine.
|
||||
func (f *FlagSet) usage() {
|
||||
if f == CommandLine {
|
||||
Usage()
|
||||
} else if f.Usage == nil {
|
||||
defaultUsage(f)
|
||||
} else {
|
||||
f.Usage()
|
||||
}
|
||||
}
|
||||
|
||||
func (f *FlagSet) setFlag(flag *Flag, value string, origArg string) error {
|
||||
if err := flag.Value.Set(value); err != nil {
|
||||
return f.failf("invalid argument %q for %s: %v", value, origArg, err)
|
||||
}
|
||||
// mark as visited for Visit()
|
||||
if f.actual == nil {
|
||||
f.actual = make(map[NormalizedName]*Flag)
|
||||
}
|
||||
f.actual[f.normalizeFlagName(flag.Name)] = flag
|
||||
flag.Changed = true
|
||||
if len(flag.Deprecated) > 0 {
|
||||
fmt.Fprintf(os.Stderr, "Flag --%s has been deprecated, %s\n", flag.Name, flag.Deprecated)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (f *FlagSet) parseLongArg(s string, args []string) (a []string, err error) {
|
||||
a = args
|
||||
if len(s) == 2 { // "--" terminates the flags
|
||||
f.args = append(f.args, args...)
|
||||
return
|
||||
}
|
||||
name := s[2:]
|
||||
if len(name) == 0 || name[0] == '-' || name[0] == '=' {
|
||||
err = f.failf("bad flag syntax: %s", s)
|
||||
return
|
||||
}
|
||||
split := strings.SplitN(name, "=", 2)
|
||||
name = split[0]
|
||||
m := f.formal
|
||||
flag, alreadythere := m[f.normalizeFlagName(name)] // BUG
|
||||
if !alreadythere {
|
||||
if name == "help" { // special case for nice help message.
|
||||
f.usage()
|
||||
return args, ErrHelp
|
||||
}
|
||||
err = f.failf("unknown flag: --%s", name)
|
||||
return
|
||||
}
|
||||
if len(split) == 1 {
|
||||
if bv, ok := flag.Value.(boolFlag); !ok || !bv.IsBoolFlag() {
|
||||
err = f.failf("flag needs an argument: %s", s)
|
||||
return
|
||||
}
|
||||
f.setFlag(flag, "true", s)
|
||||
} else {
|
||||
if e := f.setFlag(flag, split[1], s); e != nil {
|
||||
err = e
|
||||
return
|
||||
}
|
||||
}
|
||||
return args, nil
|
||||
}
|
||||
|
||||
func (f *FlagSet) parseShortArg(s string, args []string) (a []string, err error) {
|
||||
a = args
|
||||
shorthands := s[1:]
|
||||
|
||||
for i := 0; i < len(shorthands); i++ {
|
||||
c := shorthands[i]
|
||||
flag, alreadythere := f.shorthands[c]
|
||||
if !alreadythere {
|
||||
if c == 'h' { // special case for nice help message.
|
||||
f.usage()
|
||||
err = ErrHelp
|
||||
return
|
||||
}
|
||||
//TODO continue on error
|
||||
err = f.failf("unknown shorthand flag: %q in -%s", c, shorthands)
|
||||
if len(args) == 0 {
|
||||
return
|
||||
}
|
||||
return
|
||||
}
|
||||
if alreadythere {
|
||||
if bv, ok := flag.Value.(boolFlag); ok && bv.IsBoolFlag() {
|
||||
f.setFlag(flag, "true", s)
|
||||
continue
|
||||
}
|
||||
if i < len(shorthands)-1 {
|
||||
v := strings.TrimPrefix(shorthands[i+1:], "=")
|
||||
if e := f.setFlag(flag, v, s); e != nil {
|
||||
err = e
|
||||
return
|
||||
}
|
||||
break
|
||||
}
|
||||
if len(args) == 0 {
|
||||
err = f.failf("flag needs an argument: %q in -%s", c, shorthands)
|
||||
return
|
||||
}
|
||||
if e := f.setFlag(flag, args[0], s); e != nil {
|
||||
err = e
|
||||
return
|
||||
}
|
||||
}
|
||||
a = args[1:]
|
||||
break // should be unnecessary
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
func (f *FlagSet) parseArgs(args []string) (err error) {
|
||||
for len(args) > 0 {
|
||||
s := args[0]
|
||||
args = args[1:]
|
||||
if len(s) == 0 || s[0] != '-' || len(s) == 1 {
|
||||
if !f.interspersed {
|
||||
f.args = append(f.args, s)
|
||||
f.args = append(f.args, args...)
|
||||
return nil
|
||||
}
|
||||
f.args = append(f.args, s)
|
||||
continue
|
||||
}
|
||||
|
||||
if s[1] == '-' {
|
||||
args, err = f.parseLongArg(s, args)
|
||||
|
||||
if len(s) == 2 {
|
||||
// stop parsing after --
|
||||
break
|
||||
}
|
||||
} else {
|
||||
args, err = f.parseShortArg(s, args)
|
||||
}
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// Parse parses flag definitions from the argument list, which should not
|
||||
// include the command name. 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) Parse(arguments []string) error {
|
||||
f.parsed = true
|
||||
f.args = make([]string, 0, len(arguments))
|
||||
err := f.parseArgs(arguments)
|
||||
if err != nil {
|
||||
switch f.errorHandling {
|
||||
case ContinueOnError:
|
||||
return err
|
||||
case ExitOnError:
|
||||
os.Exit(2)
|
||||
case PanicOnError:
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Parsed reports whether f.Parse has been called.
|
||||
func (f *FlagSet) Parsed() bool {
|
||||
return f.parsed
|
||||
}
|
||||
|
||||
// Parse parses the command-line flags from os.Args[1:]. Must be called
|
||||
// after all flags are defined and before flags are accessed by the program.
|
||||
func Parse() {
|
||||
// Ignore errors; CommandLine is set for ExitOnError.
|
||||
CommandLine.Parse(os.Args[1:])
|
||||
}
|
||||
|
||||
// Whether to support interspersed option/non-option arguments.
|
||||
func SetInterspersed(interspersed bool) {
|
||||
CommandLine.SetInterspersed(interspersed)
|
||||
}
|
||||
|
||||
// Parsed returns true if the command-line flags have been parsed.
|
||||
func Parsed() bool {
|
||||
return CommandLine.Parsed()
|
||||
}
|
||||
|
||||
// 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.
|
||||
func NewFlagSet(name string, errorHandling ErrorHandling) *FlagSet {
|
||||
f := &FlagSet{
|
||||
name: name,
|
||||
errorHandling: errorHandling,
|
||||
interspersed: true,
|
||||
}
|
||||
return f
|
||||
}
|
||||
|
||||
// Whether to support interspersed option/non-option arguments.
|
||||
func (f *FlagSet) SetInterspersed(interspersed bool) {
|
||||
f.interspersed = interspersed
|
||||
}
|
||||
|
||||
// Init sets the name and error handling property for a flag set.
|
||||
// By default, the zero FlagSet uses an empty name and the
|
||||
// ContinueOnError error handling policy.
|
||||
func (f *FlagSet) Init(name string, errorHandling ErrorHandling) {
|
||||
f.name = name
|
||||
f.errorHandling = errorHandling
|
||||
}
|
573
Godeps/_workspace/src/github.com/spf13/pflag/flag_test.go
generated
vendored
Normal file
573
Godeps/_workspace/src/github.com/spf13/pflag/flag_test.go
generated
vendored
Normal file
@ -0,0 +1,573 @@
|
||||
// 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_test
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"io"
|
||||
"io/ioutil"
|
||||
"os"
|
||||
"sort"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
. "github.com/khlieng/name_pending/Godeps/_workspace/src/github.com/spf13/pflag"
|
||||
)
|
||||
|
||||
var (
|
||||
test_bool = Bool("test_bool", false, "bool value")
|
||||
test_int = Int("test_int", 0, "int value")
|
||||
test_int64 = Int64("test_int64", 0, "int64 value")
|
||||
test_uint = Uint("test_uint", 0, "uint value")
|
||||
test_uint64 = Uint64("test_uint64", 0, "uint64 value")
|
||||
test_string = String("test_string", "0", "string value")
|
||||
test_float64 = Float64("test_float64", 0, "float64 value")
|
||||
test_duration = Duration("test_duration", 0, "time.Duration value")
|
||||
)
|
||||
|
||||
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) != 8 {
|
||||
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")
|
||||
desired = "1"
|
||||
Visit(visitor)
|
||||
if len(m) != 8 {
|
||||
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 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")
|
||||
int64Flag := f.Int64("int64", 0, "int64 value")
|
||||
uintFlag := f.Uint("uint", 0, "uint value")
|
||||
uint64Flag := f.Uint64("uint64", 0, "uint64 value")
|
||||
stringFlag := f.String("string", "0", "string value")
|
||||
float64Flag := f.Float64("float64", 0, "float64 value")
|
||||
durationFlag := f.Duration("duration", 5*time.Second, "time.Duration value")
|
||||
extra := "one-extra-argument"
|
||||
args := []string{
|
||||
"--bool",
|
||||
"--bool2=true",
|
||||
"--bool3=false",
|
||||
"--int=22",
|
||||
"--int64=0x23",
|
||||
"--uint=24",
|
||||
"--uint64=25",
|
||||
"--string=hello",
|
||||
"--float64=2718e28",
|
||||
"--duration=2m",
|
||||
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 *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 *int64Flag != 0x23 {
|
||||
t.Error("int64 flag should be 0x23, is ", *int64Flag)
|
||||
}
|
||||
if *uintFlag != 24 {
|
||||
t.Error("uint flag should be 24, is ", *uintFlag)
|
||||
}
|
||||
if *uint64Flag != 25 {
|
||||
t.Error("uint64 flag should be 25, is ", *uint64Flag)
|
||||
}
|
||||
if *stringFlag != "hello" {
|
||||
t.Error("string flag should be `hello`, is ", *stringFlag)
|
||||
}
|
||||
if *float64Flag != 2718e28 {
|
||||
t.Error("float64 flag should be 2718e28, is ", *float64Flag)
|
||||
}
|
||||
if *durationFlag != 2*time.Minute {
|
||||
t.Error("duration flag should be 2m, is ", *durationFlag)
|
||||
}
|
||||
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")
|
||||
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",
|
||||
"--",
|
||||
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 *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])
|
||||
}
|
||||
}
|
||||
|
||||
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 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, ".")
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
||||
// 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])
|
||||
}
|
||||
}
|
||||
|
||||
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 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 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!")
|
||||
}
|
||||
}
|
74
Godeps/_workspace/src/github.com/spf13/pflag/float32.go
generated
vendored
Normal file
74
Godeps/_workspace/src/github.com/spf13/pflag/float32.go
generated
vendored
Normal file
@ -0,0 +1,74 @@
|
||||
package pflag
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strconv"
|
||||
)
|
||||
|
||||
// -- float32 Value
|
||||
type float32Value float32
|
||||
|
||||
func newFloat32Value(val float32, p *float32) *float32Value {
|
||||
*p = val
|
||||
return (*float32Value)(p)
|
||||
}
|
||||
|
||||
func (f *float32Value) Set(s string) error {
|
||||
v, err := strconv.ParseFloat(s, 32)
|
||||
*f = float32Value(v)
|
||||
return err
|
||||
}
|
||||
|
||||
func (f *float32Value) Type() string {
|
||||
return "float32"
|
||||
}
|
||||
|
||||
func (f *float32Value) String() string { return fmt.Sprintf("%v", *f) }
|
||||
|
||||
// Float32Var defines a float32 flag with specified name, default value, and usage string.
|
||||
// The argument p points to a float32 variable in which to store the value of the flag.
|
||||
func (f *FlagSet) Float32Var(p *float32, name string, value float32, usage string) {
|
||||
f.VarP(newFloat32Value(value, p), name, "", usage)
|
||||
}
|
||||
|
||||
// Like Float32Var, but accepts a shorthand letter that can be used after a single dash.
|
||||
func (f *FlagSet) Float32VarP(p *float32, name, shorthand string, value float32, usage string) {
|
||||
f.VarP(newFloat32Value(value, p), name, shorthand, usage)
|
||||
}
|
||||
|
||||
// Float32Var defines a float32 flag with specified name, default value, and usage string.
|
||||
// The argument p points to a float32 variable in which to store the value of the flag.
|
||||
func Float32Var(p *float32, name string, value float32, usage string) {
|
||||
CommandLine.VarP(newFloat32Value(value, p), name, "", usage)
|
||||
}
|
||||
|
||||
// Like Float32Var, but accepts a shorthand letter that can be used after a single dash.
|
||||
func Float32VarP(p *float32, name, shorthand string, value float32, usage string) {
|
||||
CommandLine.VarP(newFloat32Value(value, p), name, shorthand, usage)
|
||||
}
|
||||
|
||||
// Float32 defines a float32 flag with specified name, default value, and usage string.
|
||||
// The return value is the address of a float32 variable that stores the value of the flag.
|
||||
func (f *FlagSet) Float32(name string, value float32, usage string) *float32 {
|
||||
p := new(float32)
|
||||
f.Float32VarP(p, name, "", value, usage)
|
||||
return p
|
||||
}
|
||||
|
||||
// Like Float32, but accepts a shorthand letter that can be used after a single dash.
|
||||
func (f *FlagSet) Float32P(name, shorthand string, value float32, usage string) *float32 {
|
||||
p := new(float32)
|
||||
f.Float32VarP(p, name, shorthand, value, usage)
|
||||
return p
|
||||
}
|
||||
|
||||
// Float32 defines a float32 flag with specified name, default value, and usage string.
|
||||
// The return value is the address of a float32 variable that stores the value of the flag.
|
||||
func Float32(name string, value float32, usage string) *float32 {
|
||||
return CommandLine.Float32P(name, "", value, usage)
|
||||
}
|
||||
|
||||
// Like Float32, but accepts a shorthand letter that can be used after a single dash.
|
||||
func Float32P(name, shorthand string, value float32, usage string) *float32 {
|
||||
return CommandLine.Float32P(name, shorthand, value, usage)
|
||||
}
|
74
Godeps/_workspace/src/github.com/spf13/pflag/float64.go
generated
vendored
Normal file
74
Godeps/_workspace/src/github.com/spf13/pflag/float64.go
generated
vendored
Normal file
@ -0,0 +1,74 @@
|
||||
package pflag
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strconv"
|
||||
)
|
||||
|
||||
// -- float64 Value
|
||||
type float64Value float64
|
||||
|
||||
func newFloat64Value(val float64, p *float64) *float64Value {
|
||||
*p = val
|
||||
return (*float64Value)(p)
|
||||
}
|
||||
|
||||
func (f *float64Value) Set(s string) error {
|
||||
v, err := strconv.ParseFloat(s, 64)
|
||||
*f = float64Value(v)
|
||||
return err
|
||||
}
|
||||
|
||||
func (f *float64Value) Type() string {
|
||||
return "float64"
|
||||
}
|
||||
|
||||
func (f *float64Value) String() string { return fmt.Sprintf("%v", *f) }
|
||||
|
||||
// Float64Var defines a float64 flag with specified name, default value, and usage string.
|
||||
// The argument p points to a float64 variable in which to store the value of the flag.
|
||||
func (f *FlagSet) Float64Var(p *float64, name string, value float64, usage string) {
|
||||
f.VarP(newFloat64Value(value, p), name, "", usage)
|
||||
}
|
||||
|
||||
// Like Float64Var, but accepts a shorthand letter that can be used after a single dash.
|
||||
func (f *FlagSet) Float64VarP(p *float64, name, shorthand string, value float64, usage string) {
|
||||
f.VarP(newFloat64Value(value, p), name, shorthand, usage)
|
||||
}
|
||||
|
||||
// Float64Var defines a float64 flag with specified name, default value, and usage string.
|
||||
// The argument p points to a float64 variable in which to store the value of the flag.
|
||||
func Float64Var(p *float64, name string, value float64, usage string) {
|
||||
CommandLine.VarP(newFloat64Value(value, p), name, "", usage)
|
||||
}
|
||||
|
||||
// Like Float64Var, but accepts a shorthand letter that can be used after a single dash.
|
||||
func Float64VarP(p *float64, name, shorthand string, value float64, usage string) {
|
||||
CommandLine.VarP(newFloat64Value(value, p), name, shorthand, usage)
|
||||
}
|
||||
|
||||
// Float64 defines a float64 flag with specified name, default value, and usage string.
|
||||
// The return value is the address of a float64 variable that stores the value of the flag.
|
||||
func (f *FlagSet) Float64(name string, value float64, usage string) *float64 {
|
||||
p := new(float64)
|
||||
f.Float64VarP(p, name, "", value, usage)
|
||||
return p
|
||||
}
|
||||
|
||||
// Like Float64, but accepts a shorthand letter that can be used after a single dash.
|
||||
func (f *FlagSet) Float64P(name, shorthand string, value float64, usage string) *float64 {
|
||||
p := new(float64)
|
||||
f.Float64VarP(p, name, shorthand, value, usage)
|
||||
return p
|
||||
}
|
||||
|
||||
// Float64 defines a float64 flag with specified name, default value, and usage string.
|
||||
// The return value is the address of a float64 variable that stores the value of the flag.
|
||||
func Float64(name string, value float64, usage string) *float64 {
|
||||
return CommandLine.Float64P(name, "", value, usage)
|
||||
}
|
||||
|
||||
// Like Float64, but accepts a shorthand letter that can be used after a single dash.
|
||||
func Float64P(name, shorthand string, value float64, usage string) *float64 {
|
||||
return CommandLine.Float64P(name, shorthand, value, usage)
|
||||
}
|
74
Godeps/_workspace/src/github.com/spf13/pflag/int.go
generated
vendored
Normal file
74
Godeps/_workspace/src/github.com/spf13/pflag/int.go
generated
vendored
Normal file
@ -0,0 +1,74 @@
|
||||
package pflag
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strconv"
|
||||
)
|
||||
|
||||
// -- int Value
|
||||
type intValue int
|
||||
|
||||
func newIntValue(val int, p *int) *intValue {
|
||||
*p = val
|
||||
return (*intValue)(p)
|
||||
}
|
||||
|
||||
func (i *intValue) Set(s string) error {
|
||||
v, err := strconv.ParseInt(s, 0, 64)
|
||||
*i = intValue(v)
|
||||
return err
|
||||
}
|
||||
|
||||
func (i *intValue) Type() string {
|
||||
return "int"
|
||||
}
|
||||
|
||||
func (i *intValue) String() string { return fmt.Sprintf("%v", *i) }
|
||||
|
||||
// IntVar defines an int flag with specified name, default value, and usage string.
|
||||
// The argument p points to an int variable in which to store the value of the flag.
|
||||
func (f *FlagSet) IntVar(p *int, name string, value int, usage string) {
|
||||
f.VarP(newIntValue(value, p), name, "", usage)
|
||||
}
|
||||
|
||||
// Like IntVar, but accepts a shorthand letter that can be used after a single dash.
|
||||
func (f *FlagSet) IntVarP(p *int, name, shorthand string, value int, usage string) {
|
||||
f.VarP(newIntValue(value, p), name, shorthand, usage)
|
||||
}
|
||||
|
||||
// IntVar defines an int flag with specified name, default value, and usage string.
|
||||
// The argument p points to an int variable in which to store the value of the flag.
|
||||
func IntVar(p *int, name string, value int, usage string) {
|
||||
CommandLine.VarP(newIntValue(value, p), name, "", usage)
|
||||
}
|
||||
|
||||
// Like IntVar, but accepts a shorthand letter that can be used after a single dash.
|
||||
func IntVarP(p *int, name, shorthand string, value int, usage string) {
|
||||
CommandLine.VarP(newIntValue(value, p), name, shorthand, usage)
|
||||
}
|
||||
|
||||
// Int defines an int flag with specified name, default value, and usage string.
|
||||
// The return value is the address of an int variable that stores the value of the flag.
|
||||
func (f *FlagSet) Int(name string, value int, usage string) *int {
|
||||
p := new(int)
|
||||
f.IntVarP(p, name, "", value, usage)
|
||||
return p
|
||||
}
|
||||
|
||||
// Like Int, but accepts a shorthand letter that can be used after a single dash.
|
||||
func (f *FlagSet) IntP(name, shorthand string, value int, usage string) *int {
|
||||
p := new(int)
|
||||
f.IntVarP(p, name, shorthand, value, usage)
|
||||
return p
|
||||
}
|
||||
|
||||
// Int defines an int flag with specified name, default value, and usage string.
|
||||
// The return value is the address of an int variable that stores the value of the flag.
|
||||
func Int(name string, value int, usage string) *int {
|
||||
return CommandLine.IntP(name, "", value, usage)
|
||||
}
|
||||
|
||||
// Like Int, but accepts a shorthand letter that can be used after a single dash.
|
||||
func IntP(name, shorthand string, value int, usage string) *int {
|
||||
return CommandLine.IntP(name, shorthand, value, usage)
|
||||
}
|
74
Godeps/_workspace/src/github.com/spf13/pflag/int32.go
generated
vendored
Normal file
74
Godeps/_workspace/src/github.com/spf13/pflag/int32.go
generated
vendored
Normal file
@ -0,0 +1,74 @@
|
||||
package pflag
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strconv"
|
||||
)
|
||||
|
||||
// -- int32 Value
|
||||
type int32Value int32
|
||||
|
||||
func newInt32Value(val int32, p *int32) *int32Value {
|
||||
*p = val
|
||||
return (*int32Value)(p)
|
||||
}
|
||||
|
||||
func (i *int32Value) Set(s string) error {
|
||||
v, err := strconv.ParseInt(s, 0, 32)
|
||||
*i = int32Value(v)
|
||||
return err
|
||||
}
|
||||
|
||||
func (i *int32Value) Type() string {
|
||||
return "int32"
|
||||
}
|
||||
|
||||
func (i *int32Value) String() string { return fmt.Sprintf("%v", *i) }
|
||||
|
||||
// Int32Var defines an int32 flag with specified name, default value, and usage string.
|
||||
// The argument p points to an int32 variable in which to store the value of the flag.
|
||||
func (f *FlagSet) Int32Var(p *int32, name string, value int32, usage string) {
|
||||
f.VarP(newInt32Value(value, p), name, "", usage)
|
||||
}
|
||||
|
||||
// Like Int32Var, but accepts a shorthand letter that can be used after a single dash.
|
||||
func (f *FlagSet) Int32VarP(p *int32, name, shorthand string, value int32, usage string) {
|
||||
f.VarP(newInt32Value(value, p), name, shorthand, usage)
|
||||
}
|
||||
|
||||
// Int32Var defines an int32 flag with specified name, default value, and usage string.
|
||||
// The argument p points to an int32 variable in which to store the value of the flag.
|
||||
func Int32Var(p *int32, name string, value int32, usage string) {
|
||||
CommandLine.VarP(newInt32Value(value, p), name, "", usage)
|
||||
}
|
||||
|
||||
// Like Int32Var, but accepts a shorthand letter that can be used after a single dash.
|
||||
func Int32VarP(p *int32, name, shorthand string, value int32, usage string) {
|
||||
CommandLine.VarP(newInt32Value(value, p), name, shorthand, usage)
|
||||
}
|
||||
|
||||
// Int32 defines an int32 flag with specified name, default value, and usage string.
|
||||
// The return value is the address of an int32 variable that stores the value of the flag.
|
||||
func (f *FlagSet) Int32(name string, value int32, usage string) *int32 {
|
||||
p := new(int32)
|
||||
f.Int32VarP(p, name, "", value, usage)
|
||||
return p
|
||||
}
|
||||
|
||||
// Like Int32, but accepts a shorthand letter that can be used after a single dash.
|
||||
func (f *FlagSet) Int32P(name, shorthand string, value int32, usage string) *int32 {
|
||||
p := new(int32)
|
||||
f.Int32VarP(p, name, shorthand, value, usage)
|
||||
return p
|
||||
}
|
||||
|
||||
// Int32 defines an int32 flag with specified name, default value, and usage string.
|
||||
// The return value is the address of an int32 variable that stores the value of the flag.
|
||||
func Int32(name string, value int32, usage string) *int32 {
|
||||
return CommandLine.Int32P(name, "", value, usage)
|
||||
}
|
||||
|
||||
// Like Int32, but accepts a shorthand letter that can be used after a single dash.
|
||||
func Int32P(name, shorthand string, value int32, usage string) *int32 {
|
||||
return CommandLine.Int32P(name, shorthand, value, usage)
|
||||
}
|
74
Godeps/_workspace/src/github.com/spf13/pflag/int64.go
generated
vendored
Normal file
74
Godeps/_workspace/src/github.com/spf13/pflag/int64.go
generated
vendored
Normal file
@ -0,0 +1,74 @@
|
||||
package pflag
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strconv"
|
||||
)
|
||||
|
||||
// -- int64 Value
|
||||
type int64Value int64
|
||||
|
||||
func newInt64Value(val int64, p *int64) *int64Value {
|
||||
*p = val
|
||||
return (*int64Value)(p)
|
||||
}
|
||||
|
||||
func (i *int64Value) Set(s string) error {
|
||||
v, err := strconv.ParseInt(s, 0, 64)
|
||||
*i = int64Value(v)
|
||||
return err
|
||||
}
|
||||
|
||||
func (i *int64Value) Type() string {
|
||||
return "int64"
|
||||
}
|
||||
|
||||
func (i *int64Value) String() string { return fmt.Sprintf("%v", *i) }
|
||||
|
||||
// Int64Var defines an int64 flag with specified name, default value, and usage string.
|
||||
// The argument p points to an int64 variable in which to store the value of the flag.
|
||||
func (f *FlagSet) Int64Var(p *int64, name string, value int64, usage string) {
|
||||
f.VarP(newInt64Value(value, p), name, "", usage)
|
||||
}
|
||||
|
||||
// Like Int64Var, but accepts a shorthand letter that can be used after a single dash.
|
||||
func (f *FlagSet) Int64VarP(p *int64, name, shorthand string, value int64, usage string) {
|
||||
f.VarP(newInt64Value(value, p), name, shorthand, usage)
|
||||
}
|
||||
|
||||
// Int64Var defines an int64 flag with specified name, default value, and usage string.
|
||||
// The argument p points to an int64 variable in which to store the value of the flag.
|
||||
func Int64Var(p *int64, name string, value int64, usage string) {
|
||||
CommandLine.VarP(newInt64Value(value, p), name, "", usage)
|
||||
}
|
||||
|
||||
// Like Int64Var, but accepts a shorthand letter that can be used after a single dash.
|
||||
func Int64VarP(p *int64, name, shorthand string, value int64, usage string) {
|
||||
CommandLine.VarP(newInt64Value(value, p), name, shorthand, usage)
|
||||
}
|
||||
|
||||
// Int64 defines an int64 flag with specified name, default value, and usage string.
|
||||
// The return value is the address of an int64 variable that stores the value of the flag.
|
||||
func (f *FlagSet) Int64(name string, value int64, usage string) *int64 {
|
||||
p := new(int64)
|
||||
f.Int64VarP(p, name, "", value, usage)
|
||||
return p
|
||||
}
|
||||
|
||||
// Like Int64, but accepts a shorthand letter that can be used after a single dash.
|
||||
func (f *FlagSet) Int64P(name, shorthand string, value int64, usage string) *int64 {
|
||||
p := new(int64)
|
||||
f.Int64VarP(p, name, shorthand, value, usage)
|
||||
return p
|
||||
}
|
||||
|
||||
// Int64 defines an int64 flag with specified name, default value, and usage string.
|
||||
// The return value is the address of an int64 variable that stores the value of the flag.
|
||||
func Int64(name string, value int64, usage string) *int64 {
|
||||
return CommandLine.Int64P(name, "", value, usage)
|
||||
}
|
||||
|
||||
// Like Int64, but accepts a shorthand letter that can be used after a single dash.
|
||||
func Int64P(name, shorthand string, value int64, usage string) *int64 {
|
||||
return CommandLine.Int64P(name, shorthand, value, usage)
|
||||
}
|
74
Godeps/_workspace/src/github.com/spf13/pflag/int8.go
generated
vendored
Normal file
74
Godeps/_workspace/src/github.com/spf13/pflag/int8.go
generated
vendored
Normal file
@ -0,0 +1,74 @@
|
||||
package pflag
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strconv"
|
||||
)
|
||||
|
||||
// -- int8 Value
|
||||
type int8Value int8
|
||||
|
||||
func newInt8Value(val int8, p *int8) *int8Value {
|
||||
*p = val
|
||||
return (*int8Value)(p)
|
||||
}
|
||||
|
||||
func (i *int8Value) Set(s string) error {
|
||||
v, err := strconv.ParseInt(s, 0, 8)
|
||||
*i = int8Value(v)
|
||||
return err
|
||||
}
|
||||
|
||||
func (i *int8Value) Type() string {
|
||||
return "int8"
|
||||
}
|
||||
|
||||
func (i *int8Value) String() string { return fmt.Sprintf("%v", *i) }
|
||||
|
||||
// Int8Var defines an int8 flag with specified name, default value, and usage string.
|
||||
// The argument p points to an int8 variable in which to store the value of the flag.
|
||||
func (f *FlagSet) Int8Var(p *int8, name string, value int8, usage string) {
|
||||
f.VarP(newInt8Value(value, p), name, "", usage)
|
||||
}
|
||||
|
||||
// Like Int8Var, but accepts a shorthand letter that can be used after a single dash.
|
||||
func (f *FlagSet) Int8VarP(p *int8, name, shorthand string, value int8, usage string) {
|
||||
f.VarP(newInt8Value(value, p), name, shorthand, usage)
|
||||
}
|
||||
|
||||
// Int8Var defines an int8 flag with specified name, default value, and usage string.
|
||||
// The argument p points to an int8 variable in which to store the value of the flag.
|
||||
func Int8Var(p *int8, name string, value int8, usage string) {
|
||||
CommandLine.VarP(newInt8Value(value, p), name, "", usage)
|
||||
}
|
||||
|
||||
// Like Int8Var, but accepts a shorthand letter that can be used after a single dash.
|
||||
func Int8VarP(p *int8, name, shorthand string, value int8, usage string) {
|
||||
CommandLine.VarP(newInt8Value(value, p), name, shorthand, usage)
|
||||
}
|
||||
|
||||
// Int8 defines an int8 flag with specified name, default value, and usage string.
|
||||
// The return value is the address of an int8 variable that stores the value of the flag.
|
||||
func (f *FlagSet) Int8(name string, value int8, usage string) *int8 {
|
||||
p := new(int8)
|
||||
f.Int8VarP(p, name, "", value, usage)
|
||||
return p
|
||||
}
|
||||
|
||||
// Like Int8, but accepts a shorthand letter that can be used after a single dash.
|
||||
func (f *FlagSet) Int8P(name, shorthand string, value int8, usage string) *int8 {
|
||||
p := new(int8)
|
||||
f.Int8VarP(p, name, shorthand, value, usage)
|
||||
return p
|
||||
}
|
||||
|
||||
// Int8 defines an int8 flag with specified name, default value, and usage string.
|
||||
// The return value is the address of an int8 variable that stores the value of the flag.
|
||||
func Int8(name string, value int8, usage string) *int8 {
|
||||
return CommandLine.Int8P(name, "", value, usage)
|
||||
}
|
||||
|
||||
// Like Int8, but accepts a shorthand letter that can be used after a single dash.
|
||||
func Int8P(name, shorthand string, value int8, usage string) *int8 {
|
||||
return CommandLine.Int8P(name, shorthand, value, usage)
|
||||
}
|
79
Godeps/_workspace/src/github.com/spf13/pflag/ip.go
generated
vendored
Normal file
79
Godeps/_workspace/src/github.com/spf13/pflag/ip.go
generated
vendored
Normal file
@ -0,0 +1,79 @@
|
||||
package pflag
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net"
|
||||
)
|
||||
|
||||
// -- net.IP value
|
||||
type ipValue net.IP
|
||||
|
||||
func newIPValue(val net.IP, p *net.IP) *ipValue {
|
||||
*p = val
|
||||
return (*ipValue)(p)
|
||||
}
|
||||
|
||||
func (i *ipValue) String() string { return net.IP(*i).String() }
|
||||
func (i *ipValue) Set(s string) error {
|
||||
ip := net.ParseIP(s)
|
||||
if ip == nil {
|
||||
return fmt.Errorf("failed to parse IP: %q", s)
|
||||
}
|
||||
*i = ipValue(ip)
|
||||
return nil
|
||||
}
|
||||
func (i *ipValue) Get() interface{} {
|
||||
return net.IP(*i)
|
||||
}
|
||||
|
||||
func (i *ipValue) Type() string {
|
||||
return "ip"
|
||||
}
|
||||
|
||||
// IPVar defines an net.IP flag with specified name, default value, and usage string.
|
||||
// The argument p points to an net.IP variable in which to store the value of the flag.
|
||||
func (f *FlagSet) IPVar(p *net.IP, name string, value net.IP, usage string) {
|
||||
f.VarP(newIPValue(value, p), name, "", usage)
|
||||
}
|
||||
|
||||
// Like IPVar, but accepts a shorthand letter that can be used after a single dash.
|
||||
func (f *FlagSet) IPVarP(p *net.IP, name, shorthand string, value net.IP, usage string) {
|
||||
f.VarP(newIPValue(value, p), name, shorthand, usage)
|
||||
}
|
||||
|
||||
// IPVar defines an net.IP flag with specified name, default value, and usage string.
|
||||
// The argument p points to an net.IP variable in which to store the value of the flag.
|
||||
func IPVar(p *net.IP, name string, value net.IP, usage string) {
|
||||
CommandLine.VarP(newIPValue(value, p), name, "", usage)
|
||||
}
|
||||
|
||||
// Like IPVar, but accepts a shorthand letter that can be used after a single dash.
|
||||
func IPVarP(p *net.IP, name, shorthand string, value net.IP, usage string) {
|
||||
CommandLine.VarP(newIPValue(value, p), name, shorthand, usage)
|
||||
}
|
||||
|
||||
// IP defines an net.IP flag with specified name, default value, and usage string.
|
||||
// The return value is the address of an net.IP variable that stores the value of the flag.
|
||||
func (f *FlagSet) IP(name string, value net.IP, usage string) *net.IP {
|
||||
p := new(net.IP)
|
||||
f.IPVarP(p, name, "", value, usage)
|
||||
return p
|
||||
}
|
||||
|
||||
// Like IP, but accepts a shorthand letter that can be used after a single dash.
|
||||
func (f *FlagSet) IPP(name, shorthand string, value net.IP, usage string) *net.IP {
|
||||
p := new(net.IP)
|
||||
f.IPVarP(p, name, shorthand, value, usage)
|
||||
return p
|
||||
}
|
||||
|
||||
// IP defines an net.IP flag with specified name, default value, and usage string.
|
||||
// The return value is the address of an net.IP variable that stores the value of the flag.
|
||||
func IP(name string, value net.IP, usage string) *net.IP {
|
||||
return CommandLine.IPP(name, "", value, usage)
|
||||
}
|
||||
|
||||
// Like IP, but accepts a shorthand letter that can be used after a single dash.
|
||||
func IPP(name, shorthand string, value net.IP, usage string) *net.IP {
|
||||
return CommandLine.IPP(name, shorthand, value, usage)
|
||||
}
|
89
Godeps/_workspace/src/github.com/spf13/pflag/ipmask.go
generated
vendored
Normal file
89
Godeps/_workspace/src/github.com/spf13/pflag/ipmask.go
generated
vendored
Normal file
@ -0,0 +1,89 @@
|
||||
package pflag
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net"
|
||||
)
|
||||
|
||||
// -- net.IPMask value
|
||||
type ipMaskValue net.IPMask
|
||||
|
||||
func newIPMaskValue(val net.IPMask, p *net.IPMask) *ipMaskValue {
|
||||
*p = val
|
||||
return (*ipMaskValue)(p)
|
||||
}
|
||||
|
||||
func (i *ipMaskValue) String() string { return net.IPMask(*i).String() }
|
||||
func (i *ipMaskValue) Set(s string) error {
|
||||
ip := ParseIPv4Mask(s)
|
||||
if ip == nil {
|
||||
return fmt.Errorf("failed to parse IP mask: %q", s)
|
||||
}
|
||||
*i = ipMaskValue(ip)
|
||||
return nil
|
||||
}
|
||||
func (i *ipMaskValue) Get() interface{} {
|
||||
return net.IPMask(*i)
|
||||
}
|
||||
|
||||
func (i *ipMaskValue) Type() string {
|
||||
return "ipMask"
|
||||
}
|
||||
|
||||
// Parse IPv4 netmask written in IP form (e.g. 255.255.255.0).
|
||||
// This function should really belong to the net package.
|
||||
func ParseIPv4Mask(s string) net.IPMask {
|
||||
mask := net.ParseIP(s)
|
||||
if mask == nil {
|
||||
return nil
|
||||
}
|
||||
return net.IPv4Mask(mask[12], mask[13], mask[14], mask[15])
|
||||
}
|
||||
|
||||
// IPMaskVar defines an net.IPMask flag with specified name, default value, and usage string.
|
||||
// The argument p points to an net.IPMask variable in which to store the value of the flag.
|
||||
func (f *FlagSet) IPMaskVar(p *net.IPMask, name string, value net.IPMask, usage string) {
|
||||
f.VarP(newIPMaskValue(value, p), name, "", usage)
|
||||
}
|
||||
|
||||
// Like IPMaskVar, but accepts a shorthand letter that can be used after a single dash.
|
||||
func (f *FlagSet) IPMaskVarP(p *net.IPMask, name, shorthand string, value net.IPMask, usage string) {
|
||||
f.VarP(newIPMaskValue(value, p), name, shorthand, usage)
|
||||
}
|
||||
|
||||
// IPMaskVar defines an net.IPMask flag with specified name, default value, and usage string.
|
||||
// The argument p points to an net.IPMask variable in which to store the value of the flag.
|
||||
func IPMaskVar(p *net.IPMask, name string, value net.IPMask, usage string) {
|
||||
CommandLine.VarP(newIPMaskValue(value, p), name, "", usage)
|
||||
}
|
||||
|
||||
// Like IPMaskVar, but accepts a shorthand letter that can be used after a single dash.
|
||||
func IPMaskVarP(p *net.IPMask, name, shorthand string, value net.IPMask, usage string) {
|
||||
CommandLine.VarP(newIPMaskValue(value, p), name, shorthand, usage)
|
||||
}
|
||||
|
||||
// IPMask defines an net.IPMask flag with specified name, default value, and usage string.
|
||||
// The return value is the address of an net.IPMask variable that stores the value of the flag.
|
||||
func (f *FlagSet) IPMask(name string, value net.IPMask, usage string) *net.IPMask {
|
||||
p := new(net.IPMask)
|
||||
f.IPMaskVarP(p, name, "", value, usage)
|
||||
return p
|
||||
}
|
||||
|
||||
// Like IPMask, but accepts a shorthand letter that can be used after a single dash.
|
||||
func (f *FlagSet) IPMaskP(name, shorthand string, value net.IPMask, usage string) *net.IPMask {
|
||||
p := new(net.IPMask)
|
||||
f.IPMaskVarP(p, name, shorthand, value, usage)
|
||||
return p
|
||||
}
|
||||
|
||||
// IPMask defines an net.IPMask flag with specified name, default value, and usage string.
|
||||
// The return value is the address of an net.IPMask variable that stores the value of the flag.
|
||||
func IPMask(name string, value net.IPMask, usage string) *net.IPMask {
|
||||
return CommandLine.IPMaskP(name, "", value, usage)
|
||||
}
|
||||
|
||||
// Like IP, but accepts a shorthand letter that can be used after a single dash.
|
||||
func IPMaskP(name, shorthand string, value net.IPMask, usage string) *net.IPMask {
|
||||
return CommandLine.IPMaskP(name, shorthand, value, usage)
|
||||
}
|
69
Godeps/_workspace/src/github.com/spf13/pflag/string.go
generated
vendored
Normal file
69
Godeps/_workspace/src/github.com/spf13/pflag/string.go
generated
vendored
Normal file
@ -0,0 +1,69 @@
|
||||
package pflag
|
||||
|
||||
import "fmt"
|
||||
|
||||
// -- string Value
|
||||
type stringValue string
|
||||
|
||||
func newStringValue(val string, p *string) *stringValue {
|
||||
*p = val
|
||||
return (*stringValue)(p)
|
||||
}
|
||||
|
||||
func (s *stringValue) Set(val string) error {
|
||||
*s = stringValue(val)
|
||||
return nil
|
||||
}
|
||||
func (s *stringValue) Type() string {
|
||||
return "string"
|
||||
}
|
||||
|
||||
func (s *stringValue) String() string { return fmt.Sprintf("%s", *s) }
|
||||
|
||||
// StringVar 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.
|
||||
func (f *FlagSet) StringVar(p *string, name string, value string, usage string) {
|
||||
f.VarP(newStringValue(value, p), name, "", usage)
|
||||
}
|
||||
|
||||
// Like StringVar, but accepts a shorthand letter that can be used after a single dash.
|
||||
func (f *FlagSet) StringVarP(p *string, name, shorthand string, value string, usage string) {
|
||||
f.VarP(newStringValue(value, p), name, shorthand, usage)
|
||||
}
|
||||
|
||||
// StringVar 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.
|
||||
func StringVar(p *string, name string, value string, usage string) {
|
||||
CommandLine.VarP(newStringValue(value, p), name, "", usage)
|
||||
}
|
||||
|
||||
// Like StringVar, but accepts a shorthand letter that can be used after a single dash.
|
||||
func StringVarP(p *string, name, shorthand string, value string, usage string) {
|
||||
CommandLine.VarP(newStringValue(value, p), name, shorthand, usage)
|
||||
}
|
||||
|
||||
// String 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.
|
||||
func (f *FlagSet) String(name string, value string, usage string) *string {
|
||||
p := new(string)
|
||||
f.StringVarP(p, name, "", value, usage)
|
||||
return p
|
||||
}
|
||||
|
||||
// Like String, but accepts a shorthand letter that can be used after a single dash.
|
||||
func (f *FlagSet) StringP(name, shorthand string, value string, usage string) *string {
|
||||
p := new(string)
|
||||
f.StringVarP(p, name, shorthand, value, usage)
|
||||
return p
|
||||
}
|
||||
|
||||
// String 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.
|
||||
func String(name string, value string, usage string) *string {
|
||||
return CommandLine.StringP(name, "", value, usage)
|
||||
}
|
||||
|
||||
// Like String, but accepts a shorthand letter that can be used after a single dash.
|
||||
func StringP(name, shorthand string, value string, usage string) *string {
|
||||
return CommandLine.StringP(name, shorthand, value, usage)
|
||||
}
|
74
Godeps/_workspace/src/github.com/spf13/pflag/uint.go
generated
vendored
Normal file
74
Godeps/_workspace/src/github.com/spf13/pflag/uint.go
generated
vendored
Normal file
@ -0,0 +1,74 @@
|
||||
package pflag
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strconv"
|
||||
)
|
||||
|
||||
// -- uint Value
|
||||
type uintValue uint
|
||||
|
||||
func newUintValue(val uint, p *uint) *uintValue {
|
||||
*p = val
|
||||
return (*uintValue)(p)
|
||||
}
|
||||
|
||||
func (i *uintValue) Set(s string) error {
|
||||
v, err := strconv.ParseUint(s, 0, 64)
|
||||
*i = uintValue(v)
|
||||
return err
|
||||
}
|
||||
|
||||
func (i *uintValue) Type() string {
|
||||
return "uint"
|
||||
}
|
||||
|
||||
func (i *uintValue) String() string { return fmt.Sprintf("%v", *i) }
|
||||
|
||||
// UintVar 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 (f *FlagSet) UintVar(p *uint, name string, value uint, usage string) {
|
||||
f.VarP(newUintValue(value, p), name, "", usage)
|
||||
}
|
||||
|
||||
// Like UintVar, but accepts a shorthand letter that can be used after a single dash.
|
||||
func (f *FlagSet) UintVarP(p *uint, name, shorthand string, value uint, usage string) {
|
||||
f.VarP(newUintValue(value, p), name, shorthand, usage)
|
||||
}
|
||||
|
||||
// UintVar 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 UintVar(p *uint, name string, value uint, usage string) {
|
||||
CommandLine.VarP(newUintValue(value, p), name, "", usage)
|
||||
}
|
||||
|
||||
// Like UintVar, but accepts a shorthand letter that can be used after a single dash.
|
||||
func UintVarP(p *uint, name, shorthand string, value uint, usage string) {
|
||||
CommandLine.VarP(newUintValue(value, p), name, shorthand, usage)
|
||||
}
|
||||
|
||||
// Uint 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) Uint(name string, value uint, usage string) *uint {
|
||||
p := new(uint)
|
||||
f.UintVarP(p, name, "", value, usage)
|
||||
return p
|
||||
}
|
||||
|
||||
// Like Uint, but accepts a shorthand letter that can be used after a single dash.
|
||||
func (f *FlagSet) UintP(name, shorthand string, value uint, usage string) *uint {
|
||||
p := new(uint)
|
||||
f.UintVarP(p, name, shorthand, value, usage)
|
||||
return p
|
||||
}
|
||||
|
||||
// Uint 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 Uint(name string, value uint, usage string) *uint {
|
||||
return CommandLine.UintP(name, "", value, usage)
|
||||
}
|
||||
|
||||
// Like Uint, but accepts a shorthand letter that can be used after a single dash.
|
||||
func UintP(name, shorthand string, value uint, usage string) *uint {
|
||||
return CommandLine.UintP(name, shorthand, value, usage)
|
||||
}
|
76
Godeps/_workspace/src/github.com/spf13/pflag/uint16.go
generated
vendored
Normal file
76
Godeps/_workspace/src/github.com/spf13/pflag/uint16.go
generated
vendored
Normal file
@ -0,0 +1,76 @@
|
||||
package pflag
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strconv"
|
||||
)
|
||||
|
||||
// -- uint16 value
|
||||
type uint16Value uint16
|
||||
|
||||
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)
|
||||
return err
|
||||
}
|
||||
|
||||
func (i *uint16Value) Get() interface{} {
|
||||
return uint16(*i)
|
||||
}
|
||||
|
||||
func (i *uint16Value) Type() string {
|
||||
return "uint16"
|
||||
}
|
||||
|
||||
// Uint16Var 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 (f *FlagSet) Uint16Var(p *uint16, name string, value uint16, usage string) {
|
||||
f.VarP(newUint16Value(value, p), name, "", usage)
|
||||
}
|
||||
|
||||
// Like Uint16Var, but accepts a shorthand letter that can be used after a single dash.
|
||||
func (f *FlagSet) Uint16VarP(p *uint16, name, shorthand string, value uint16, usage string) {
|
||||
f.VarP(newUint16Value(value, p), name, shorthand, usage)
|
||||
}
|
||||
|
||||
// Uint16Var 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 Uint16Var(p *uint16, name string, value uint16, usage string) {
|
||||
CommandLine.VarP(newUint16Value(value, p), name, "", usage)
|
||||
}
|
||||
|
||||
// Like Uint16Var, but accepts a shorthand letter that can be used after a single dash.
|
||||
func Uint16VarP(p *uint16, name, shorthand string, value uint16, usage string) {
|
||||
CommandLine.VarP(newUint16Value(value, p), name, shorthand, usage)
|
||||
}
|
||||
|
||||
// Uint16 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) Uint16(name string, value uint16, usage string) *uint16 {
|
||||
p := new(uint16)
|
||||
f.Uint16VarP(p, name, "", value, usage)
|
||||
return p
|
||||
}
|
||||
|
||||
// Like Uint16, but accepts a shorthand letter that can be used after a single dash.
|
||||
func (f *FlagSet) Uint16P(name, shorthand string, value uint16, usage string) *uint16 {
|
||||
p := new(uint16)
|
||||
f.Uint16VarP(p, name, shorthand, value, usage)
|
||||
return p
|
||||
}
|
||||
|
||||
// Uint16 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 Uint16(name string, value uint16, usage string) *uint16 {
|
||||
return CommandLine.Uint16P(name, "", value, usage)
|
||||
}
|
||||
|
||||
// Like Uint16, but accepts a shorthand letter that can be used after a single dash.
|
||||
func Uint16P(name, shorthand string, value uint16, usage string) *uint16 {
|
||||
return CommandLine.Uint16P(name, shorthand, value, usage)
|
||||
}
|
75
Godeps/_workspace/src/github.com/spf13/pflag/uint32.go
generated
vendored
Normal file
75
Godeps/_workspace/src/github.com/spf13/pflag/uint32.go
generated
vendored
Normal file
@ -0,0 +1,75 @@
|
||||
package pflag
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strconv"
|
||||
)
|
||||
|
||||
// -- uint16 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)
|
||||
return err
|
||||
}
|
||||
func (i *uint32Value) Get() interface{} {
|
||||
return uint32(*i)
|
||||
}
|
||||
|
||||
func (i *uint32Value) Type() string {
|
||||
return "uint32"
|
||||
}
|
||||
|
||||
// Uint32Var defines a uint32 flag with specified name, default value, and usage string.
|
||||
// The argument p points to a uint32 variable in which to store the value of the flag.
|
||||
func (f *FlagSet) Uint32Var(p *uint32, name string, value uint32, usage string) {
|
||||
f.VarP(newUint32Value(value, p), name, "", usage)
|
||||
}
|
||||
|
||||
// Like Uint32Var, but accepts a shorthand letter that can be used after a single dash.
|
||||
func (f *FlagSet) Uint32VarP(p *uint32, name, shorthand string, value uint32, usage string) {
|
||||
f.VarP(newUint32Value(value, p), name, shorthand, usage)
|
||||
}
|
||||
|
||||
// Uint32Var defines a uint32 flag with specified name, default value, and usage string.
|
||||
// The argument p points to a uint32 variable in which to store the value of the flag.
|
||||
func Uint32Var(p *uint32, name string, value uint32, usage string) {
|
||||
CommandLine.VarP(newUint32Value(value, p), name, "", usage)
|
||||
}
|
||||
|
||||
// Like Uint32Var, but accepts a shorthand letter that can be used after a single dash.
|
||||
func Uint32VarP(p *uint32, name, shorthand string, value uint32, usage string) {
|
||||
CommandLine.VarP(newUint32Value(value, p), name, shorthand, usage)
|
||||
}
|
||||
|
||||
// Uint32 defines a uint32 flag with specified name, default value, and usage string.
|
||||
// The return value is the address of a uint32 variable that stores the value of the flag.
|
||||
func (f *FlagSet) Uint32(name string, value uint32, usage string) *uint32 {
|
||||
p := new(uint32)
|
||||
f.Uint32VarP(p, name, "", value, usage)
|
||||
return p
|
||||
}
|
||||
|
||||
// Like Uint32, but accepts a shorthand letter that can be used after a single dash.
|
||||
func (f *FlagSet) Uint32P(name, shorthand string, value uint32, usage string) *uint32 {
|
||||
p := new(uint32)
|
||||
f.Uint32VarP(p, name, shorthand, value, usage)
|
||||
return p
|
||||
}
|
||||
|
||||
// Uint32 defines a uint32 flag with specified name, default value, and usage string.
|
||||
// The return value is the address of a uint32 variable that stores the value of the flag.
|
||||
func Uint32(name string, value uint32, usage string) *uint32 {
|
||||
return CommandLine.Uint32P(name, "", value, usage)
|
||||
}
|
||||
|
||||
// Like Uint32, but accepts a shorthand letter that can be used after a single dash.
|
||||
func Uint32P(name, shorthand string, value uint32, usage string) *uint32 {
|
||||
return CommandLine.Uint32P(name, shorthand, value, usage)
|
||||
}
|
74
Godeps/_workspace/src/github.com/spf13/pflag/uint64.go
generated
vendored
Normal file
74
Godeps/_workspace/src/github.com/spf13/pflag/uint64.go
generated
vendored
Normal file
@ -0,0 +1,74 @@
|
||||
package pflag
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strconv"
|
||||
)
|
||||
|
||||
// -- uint64 Value
|
||||
type uint64Value uint64
|
||||
|
||||
func newUint64Value(val uint64, p *uint64) *uint64Value {
|
||||
*p = val
|
||||
return (*uint64Value)(p)
|
||||
}
|
||||
|
||||
func (i *uint64Value) Set(s string) error {
|
||||
v, err := strconv.ParseUint(s, 0, 64)
|
||||
*i = uint64Value(v)
|
||||
return err
|
||||
}
|
||||
|
||||
func (i *uint64Value) Type() string {
|
||||
return "uint64"
|
||||
}
|
||||
|
||||
func (i *uint64Value) String() string { return fmt.Sprintf("%v", *i) }
|
||||
|
||||
// Uint64Var defines a uint64 flag with specified name, default value, and usage string.
|
||||
// The argument p points to a uint64 variable in which to store the value of the flag.
|
||||
func (f *FlagSet) Uint64Var(p *uint64, name string, value uint64, usage string) {
|
||||
f.VarP(newUint64Value(value, p), name, "", usage)
|
||||
}
|
||||
|
||||
// Like Uint64Var, but accepts a shorthand letter that can be used after a single dash.
|
||||
func (f *FlagSet) Uint64VarP(p *uint64, name, shorthand string, value uint64, usage string) {
|
||||
f.VarP(newUint64Value(value, p), name, shorthand, usage)
|
||||
}
|
||||
|
||||
// Uint64Var defines a uint64 flag with specified name, default value, and usage string.
|
||||
// The argument p points to a uint64 variable in which to store the value of the flag.
|
||||
func Uint64Var(p *uint64, name string, value uint64, usage string) {
|
||||
CommandLine.VarP(newUint64Value(value, p), name, "", usage)
|
||||
}
|
||||
|
||||
// Like Uint64Var, but accepts a shorthand letter that can be used after a single dash.
|
||||
func Uint64VarP(p *uint64, name, shorthand string, value uint64, usage string) {
|
||||
CommandLine.VarP(newUint64Value(value, p), name, shorthand, usage)
|
||||
}
|
||||
|
||||
// Uint64 defines a uint64 flag with specified name, default value, and usage string.
|
||||
// The return value is the address of a uint64 variable that stores the value of the flag.
|
||||
func (f *FlagSet) Uint64(name string, value uint64, usage string) *uint64 {
|
||||
p := new(uint64)
|
||||
f.Uint64VarP(p, name, "", value, usage)
|
||||
return p
|
||||
}
|
||||
|
||||
// Like Uint64, but accepts a shorthand letter that can be used after a single dash.
|
||||
func (f *FlagSet) Uint64P(name, shorthand string, value uint64, usage string) *uint64 {
|
||||
p := new(uint64)
|
||||
f.Uint64VarP(p, name, shorthand, value, usage)
|
||||
return p
|
||||
}
|
||||
|
||||
// Uint64 defines a uint64 flag with specified name, default value, and usage string.
|
||||
// The return value is the address of a uint64 variable that stores the value of the flag.
|
||||
func Uint64(name string, value uint64, usage string) *uint64 {
|
||||
return CommandLine.Uint64P(name, "", value, usage)
|
||||
}
|
||||
|
||||
// Like Uint64, but accepts a shorthand letter that can be used after a single dash.
|
||||
func Uint64P(name, shorthand string, value uint64, usage string) *uint64 {
|
||||
return CommandLine.Uint64P(name, shorthand, value, usage)
|
||||
}
|
74
Godeps/_workspace/src/github.com/spf13/pflag/uint8.go
generated
vendored
Normal file
74
Godeps/_workspace/src/github.com/spf13/pflag/uint8.go
generated
vendored
Normal file
@ -0,0 +1,74 @@
|
||||
package pflag
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strconv"
|
||||
)
|
||||
|
||||
// -- uint8 Value
|
||||
type uint8Value uint8
|
||||
|
||||
func newUint8Value(val uint8, p *uint8) *uint8Value {
|
||||
*p = val
|
||||
return (*uint8Value)(p)
|
||||
}
|
||||
|
||||
func (i *uint8Value) Set(s string) error {
|
||||
v, err := strconv.ParseUint(s, 0, 8)
|
||||
*i = uint8Value(v)
|
||||
return err
|
||||
}
|
||||
|
||||
func (i *uint8Value) Type() string {
|
||||
return "uint8"
|
||||
}
|
||||
|
||||
func (i *uint8Value) String() string { return fmt.Sprintf("%v", *i) }
|
||||
|
||||
// Uint8Var defines a uint8 flag with specified name, default value, and usage string.
|
||||
// The argument p points to a uint8 variable in which to store the value of the flag.
|
||||
func (f *FlagSet) Uint8Var(p *uint8, name string, value uint8, usage string) {
|
||||
f.VarP(newUint8Value(value, p), name, "", usage)
|
||||
}
|
||||
|
||||
// Like Uint8Var, but accepts a shorthand letter that can be used after a single dash.
|
||||
func (f *FlagSet) Uint8VarP(p *uint8, name, shorthand string, value uint8, usage string) {
|
||||
f.VarP(newUint8Value(value, p), name, shorthand, usage)
|
||||
}
|
||||
|
||||
// Uint8Var defines a uint8 flag with specified name, default value, and usage string.
|
||||
// The argument p points to a uint8 variable in which to store the value of the flag.
|
||||
func Uint8Var(p *uint8, name string, value uint8, usage string) {
|
||||
CommandLine.VarP(newUint8Value(value, p), name, "", usage)
|
||||
}
|
||||
|
||||
// Like Uint8Var, but accepts a shorthand letter that can be used after a single dash.
|
||||
func Uint8VarP(p *uint8, name, shorthand string, value uint8, usage string) {
|
||||
CommandLine.VarP(newUint8Value(value, p), name, shorthand, usage)
|
||||
}
|
||||
|
||||
// Uint8 defines a uint8 flag with specified name, default value, and usage string.
|
||||
// The return value is the address of a uint8 variable that stores the value of the flag.
|
||||
func (f *FlagSet) Uint8(name string, value uint8, usage string) *uint8 {
|
||||
p := new(uint8)
|
||||
f.Uint8VarP(p, name, "", value, usage)
|
||||
return p
|
||||
}
|
||||
|
||||
// Like Uint8, but accepts a shorthand letter that can be used after a single dash.
|
||||
func (f *FlagSet) Uint8P(name, shorthand string, value uint8, usage string) *uint8 {
|
||||
p := new(uint8)
|
||||
f.Uint8VarP(p, name, shorthand, value, usage)
|
||||
return p
|
||||
}
|
||||
|
||||
// Uint8 defines a uint8 flag with specified name, default value, and usage string.
|
||||
// The return value is the address of a uint8 variable that stores the value of the flag.
|
||||
func Uint8(name string, value uint8, usage string) *uint8 {
|
||||
return CommandLine.Uint8P(name, "", value, usage)
|
||||
}
|
||||
|
||||
// Like Uint8, but accepts a shorthand letter that can be used after a single dash.
|
||||
func Uint8P(name, shorthand string, value uint8, usage string) *uint8 {
|
||||
return CommandLine.Uint8P(name, shorthand, value, usage)
|
||||
}
|
14
args/args.go
14
args/args.go
@ -1,14 +0,0 @@
|
||||
package args
|
||||
|
||||
import (
|
||||
"flag"
|
||||
)
|
||||
|
||||
var (
|
||||
Development bool
|
||||
)
|
||||
|
||||
func init() {
|
||||
flag.BoolVar(&Development, "dev", false, "")
|
||||
flag.Parse()
|
||||
}
|
@ -85,11 +85,11 @@ gulp.task('gzip', ['html', 'css', 'js', 'fonts'], function() {
|
||||
|
||||
function bindata(cb) {
|
||||
if (argv.production) {
|
||||
exec('go-bindata -nomemcopy -o ../bindata.go dist/...', function(err) {
|
||||
exec('go-bindata -nomemcopy -pkg server -o ../server/bindata.go dist/...', function(err) {
|
||||
cb(err);
|
||||
});
|
||||
} else {
|
||||
exec('go-bindata -debug -o ../bindata.go dist/...', function(err) {
|
||||
exec('go-bindata -debug -pkg server -o ../server/bindata.go dist/...', function(err) {
|
||||
cb(err);
|
||||
});
|
||||
}
|
||||
|
31
commands/name_pending.go
Normal file
31
commands/name_pending.go
Normal file
@ -0,0 +1,31 @@
|
||||
package commands
|
||||
|
||||
import (
|
||||
"github.com/khlieng/name_pending/Godeps/_workspace/src/github.com/spf13/cobra"
|
||||
|
||||
"github.com/khlieng/name_pending/server"
|
||||
"github.com/khlieng/name_pending/storage"
|
||||
)
|
||||
|
||||
var (
|
||||
rootCmd = &cobra.Command{
|
||||
Use: "name_pending",
|
||||
Long: "Web-based IRC client in Go.",
|
||||
Run: func(cmd *cobra.Command, args []string) {
|
||||
storage.Initialize(development)
|
||||
server.Run(port, development)
|
||||
},
|
||||
}
|
||||
|
||||
development bool
|
||||
port int
|
||||
)
|
||||
|
||||
func init() {
|
||||
rootCmd.Flags().BoolVarP(&development, "dev", "d", false, "development mode")
|
||||
rootCmd.Flags().IntVarP(&port, "port", "p", 1337, "port to listen on")
|
||||
}
|
||||
|
||||
func Execute() {
|
||||
rootCmd.Execute()
|
||||
}
|
119
main.go
119
main.go
@ -1,124 +1,9 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"log"
|
||||
"net/http"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
"github.com/khlieng/name_pending/Godeps/_workspace/src/github.com/julienschmidt/httprouter"
|
||||
"github.com/khlieng/name_pending/Godeps/_workspace/src/golang.org/x/net/websocket"
|
||||
|
||||
"github.com/khlieng/name_pending/args"
|
||||
"github.com/khlieng/name_pending/storage"
|
||||
"github.com/khlieng/name_pending/commands"
|
||||
)
|
||||
|
||||
var (
|
||||
channelStore *storage.ChannelStore
|
||||
sessions map[string]*Session
|
||||
sessionLock sync.Mutex
|
||||
fs http.Handler
|
||||
files []File
|
||||
)
|
||||
|
||||
type File struct {
|
||||
Path string
|
||||
ContentType string
|
||||
}
|
||||
|
||||
func reconnect() {
|
||||
for _, user := range storage.LoadUsers() {
|
||||
session := NewSession()
|
||||
session.user = user
|
||||
sessions[user.UUID] = session
|
||||
go session.write()
|
||||
|
||||
channels := user.GetChannels()
|
||||
|
||||
for _, server := range user.GetServers() {
|
||||
irc := NewIRC(server.Nick, server.Username)
|
||||
irc.TLS = server.TLS
|
||||
irc.Password = server.Password
|
||||
irc.Realname = server.Realname
|
||||
|
||||
go func() {
|
||||
err := irc.Connect(server.Address)
|
||||
if err != nil {
|
||||
log.Println(err)
|
||||
} else {
|
||||
session.setIRC(irc.Host, irc)
|
||||
|
||||
go handleMessages(irc, session)
|
||||
|
||||
var joining []string
|
||||
for _, channel := range channels {
|
||||
if channel.Server == server.Address {
|
||||
joining = append(joining, channel.Name)
|
||||
}
|
||||
}
|
||||
irc.Join(joining...)
|
||||
}
|
||||
}()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func serveFiles(w http.ResponseWriter, r *http.Request) {
|
||||
var ext string
|
||||
|
||||
if strings.Contains(r.Header.Get("Accept-Encoding"), "gzip") {
|
||||
w.Header().Set("Content-Encoding", "gzip")
|
||||
ext = ".gz"
|
||||
}
|
||||
|
||||
if r.URL.Path == "/" {
|
||||
w.Header().Set("Content-Type", "text/html")
|
||||
r.URL.Path = "/index.html" + ext
|
||||
fs.ServeHTTP(w, r)
|
||||
return
|
||||
}
|
||||
|
||||
for _, file := range files {
|
||||
if strings.HasSuffix(r.URL.Path, file.Path) {
|
||||
w.Header().Set("Content-Type", file.ContentType)
|
||||
r.URL.Path = file.Path + ext
|
||||
fs.ServeHTTP(w, r)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "text/html")
|
||||
r.URL.Path = "/index.html" + ext
|
||||
|
||||
fs.ServeHTTP(w, r)
|
||||
}
|
||||
|
||||
func main() {
|
||||
defer storage.Cleanup()
|
||||
|
||||
channelStore = storage.NewChannelStore()
|
||||
sessions = make(map[string]*Session)
|
||||
fs = http.FileServer(BindataFileSystem{})
|
||||
|
||||
files = []File{
|
||||
File{"/bundle.js", "text/javascript"},
|
||||
File{"/css/style.css", "text/css"},
|
||||
File{"/css/fontello.css", "text/css"},
|
||||
File{"/font/fontello.eot", "application/vnd.ms-fontobject"},
|
||||
File{"/font/fontello.svg", "image/svg+xml"},
|
||||
File{"/font/fontello.ttf", "application/x-font-ttf"},
|
||||
File{"/font/fontello.woff", "application/font-woff"},
|
||||
}
|
||||
|
||||
if !args.Development {
|
||||
reconnect()
|
||||
}
|
||||
|
||||
router := httprouter.New()
|
||||
|
||||
router.Handler("GET", "/ws", websocket.Handler(handleWS))
|
||||
router.NotFound = serveFiles
|
||||
|
||||
log.Println("Listening on port 1337")
|
||||
http.ListenAndServe(":1337", router)
|
||||
commands.Execute()
|
||||
}
|
||||
|
@ -1,4 +1,4 @@
|
||||
package main
|
||||
package server
|
||||
|
||||
import (
|
||||
"bytes"
|
@ -1,4 +1,4 @@
|
||||
package main
|
||||
package server
|
||||
|
||||
import (
|
||||
"bytes"
|
@ -1,4 +1,4 @@
|
||||
package main
|
||||
package server
|
||||
|
||||
import (
|
||||
"bufio"
|
@ -1,4 +1,4 @@
|
||||
package main
|
||||
package server
|
||||
|
||||
import (
|
||||
"encoding/json"
|
@ -1,4 +1,4 @@
|
||||
package main
|
||||
package server
|
||||
|
||||
import (
|
||||
"log"
|
124
server/server.go
Normal file
124
server/server.go
Normal file
@ -0,0 +1,124 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"log"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
"github.com/khlieng/name_pending/Godeps/_workspace/src/github.com/julienschmidt/httprouter"
|
||||
"github.com/khlieng/name_pending/Godeps/_workspace/src/golang.org/x/net/websocket"
|
||||
|
||||
"github.com/khlieng/name_pending/storage"
|
||||
)
|
||||
|
||||
var (
|
||||
channelStore *storage.ChannelStore
|
||||
sessions map[string]*Session
|
||||
sessionLock sync.Mutex
|
||||
fs http.Handler
|
||||
files []File
|
||||
)
|
||||
|
||||
type File struct {
|
||||
Path string
|
||||
ContentType string
|
||||
}
|
||||
|
||||
func Run(port int, development bool) {
|
||||
defer storage.Cleanup()
|
||||
|
||||
channelStore = storage.NewChannelStore()
|
||||
sessions = make(map[string]*Session)
|
||||
fs = http.FileServer(BindataFileSystem{})
|
||||
|
||||
files = []File{
|
||||
File{"/bundle.js", "text/javascript"},
|
||||
File{"/css/style.css", "text/css"},
|
||||
File{"/css/fontello.css", "text/css"},
|
||||
File{"/font/fontello.eot", "application/vnd.ms-fontobject"},
|
||||
File{"/font/fontello.svg", "image/svg+xml"},
|
||||
File{"/font/fontello.ttf", "application/x-font-ttf"},
|
||||
File{"/font/fontello.woff", "application/font-woff"},
|
||||
}
|
||||
|
||||
if !development {
|
||||
reconnect()
|
||||
}
|
||||
|
||||
router := httprouter.New()
|
||||
|
||||
router.Handler("GET", "/ws", websocket.Handler(handleWS))
|
||||
router.NotFound = serveFiles
|
||||
|
||||
log.Println("Listening on port", port)
|
||||
log.Fatal(http.ListenAndServe(":"+strconv.Itoa(port), router))
|
||||
}
|
||||
|
||||
func reconnect() {
|
||||
for _, user := range storage.LoadUsers() {
|
||||
session := NewSession()
|
||||
session.user = user
|
||||
sessions[user.UUID] = session
|
||||
go session.write()
|
||||
|
||||
channels := user.GetChannels()
|
||||
|
||||
for _, server := range user.GetServers() {
|
||||
irc := NewIRC(server.Nick, server.Username)
|
||||
irc.TLS = server.TLS
|
||||
irc.Password = server.Password
|
||||
irc.Realname = server.Realname
|
||||
|
||||
go func() {
|
||||
err := irc.Connect(server.Address)
|
||||
if err != nil {
|
||||
log.Println(err)
|
||||
} else {
|
||||
session.setIRC(irc.Host, irc)
|
||||
|
||||
go handleMessages(irc, session)
|
||||
|
||||
var joining []string
|
||||
for _, channel := range channels {
|
||||
if channel.Server == server.Address {
|
||||
joining = append(joining, channel.Name)
|
||||
}
|
||||
}
|
||||
irc.Join(joining...)
|
||||
}
|
||||
}()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func serveFiles(w http.ResponseWriter, r *http.Request) {
|
||||
var ext string
|
||||
|
||||
if strings.Contains(r.Header.Get("Accept-Encoding"), "gzip") {
|
||||
w.Header().Set("Content-Encoding", "gzip")
|
||||
ext = ".gz"
|
||||
}
|
||||
|
||||
if r.URL.Path == "/" {
|
||||
w.Header().Set("Content-Type", "text/html")
|
||||
r.URL.Path = "/index.html" + ext
|
||||
fs.ServeHTTP(w, r)
|
||||
return
|
||||
}
|
||||
|
||||
for _, file := range files {
|
||||
if strings.HasSuffix(r.URL.Path, file.Path) {
|
||||
w.Header().Set("Content-Type", file.ContentType)
|
||||
r.URL.Path = file.Path + ext
|
||||
fs.ServeHTTP(w, r)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "text/html")
|
||||
r.URL.Path = "/index.html" + ext
|
||||
|
||||
fs.ServeHTTP(w, r)
|
||||
}
|
@ -1,4 +1,4 @@
|
||||
package main
|
||||
package server
|
||||
|
||||
import (
|
||||
"encoding/json"
|
@ -1,4 +1,4 @@
|
||||
package main
|
||||
package server
|
||||
|
||||
import (
|
||||
"github.com/khlieng/name_pending/Godeps/_workspace/src/golang.org/x/net/websocket"
|
@ -1,4 +1,4 @@
|
||||
package main
|
||||
package server
|
||||
|
||||
import (
|
||||
"encoding/json"
|
@ -7,8 +7,6 @@ import (
|
||||
"path"
|
||||
|
||||
"github.com/khlieng/name_pending/Godeps/_workspace/src/github.com/boltdb/bolt"
|
||||
|
||||
"github.com/khlieng/name_pending/args"
|
||||
)
|
||||
|
||||
var (
|
||||
@ -22,12 +20,12 @@ var (
|
||||
bucketMessages = []byte("Messages")
|
||||
)
|
||||
|
||||
func init() {
|
||||
func Initialize(clean bool) {
|
||||
var err error
|
||||
currentUser, _ := user.Current()
|
||||
appDir = path.Join(currentUser.HomeDir, ".name_pending")
|
||||
|
||||
if args.Development {
|
||||
if clean {
|
||||
os.RemoveAll(appDir)
|
||||
}
|
||||
|
||||
|
Loading…
Reference in New Issue
Block a user