Upgrade server dependencies, manage them with govendor
This commit is contained in:
parent
ebee2746d6
commit
971278e7e5
1748 changed files with 196165 additions and 194500 deletions
52
vendor/github.com/spf13/cobra/README.md
generated
vendored
52
vendor/github.com/spf13/cobra/README.md
generated
vendored
|
@ -8,6 +8,7 @@ Many of the most widely used Go projects are built using Cobra including:
|
|||
* [Hugo](http://gohugo.io)
|
||||
* [rkt](https://github.com/coreos/rkt)
|
||||
* [etcd](https://github.com/coreos/etcd)
|
||||
* [Docker](https://github.com/docker/docker)
|
||||
* [Docker (distribution)](https://github.com/docker/distribution)
|
||||
* [OpenShift](https://www.openshift.com/)
|
||||
* [Delve](https://github.com/derekparker/delve)
|
||||
|
@ -22,6 +23,7 @@ Many of the most widely used Go projects are built using Cobra including:
|
|||
|
||||
[](https://travis-ci.org/spf13/cobra)
|
||||
[](https://circleci.com/gh/spf13/cobra)
|
||||
[](https://godoc.org/github.com/spf13/cobra)
|
||||
|
||||

|
||||
|
||||
|
@ -156,12 +158,17 @@ In a Cobra app, typically the main.go file is very bare. It serves, one purpose,
|
|||
```go
|
||||
package main
|
||||
|
||||
import "{pathToYourApp}/cmd"
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
|
||||
"{pathToYourApp}/cmd"
|
||||
)
|
||||
|
||||
func main() {
|
||||
if err := cmd.RootCmd.Execute(); err != nil {
|
||||
fmt.Println(err)
|
||||
os.Exit(-1)
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
@ -171,6 +178,12 @@ func main() {
|
|||
Cobra provides its own program that will create your application and add any
|
||||
commands you want. It's the easiest way to incorporate Cobra into your application.
|
||||
|
||||
In order to use the cobra command, compile it using the following command:
|
||||
|
||||
> go install github.com/spf13/cobra/cobra
|
||||
|
||||
This will create the cobra executable under your go path bin directory!
|
||||
|
||||
### cobra init
|
||||
|
||||
The `cobra init [yourApp]` command will create your initial application code
|
||||
|
@ -226,13 +239,27 @@ The cobra generator will be easier to use if you provide a simple configuration
|
|||
file which will help you eliminate providing a bunch of repeated information in
|
||||
flags over and over.
|
||||
|
||||
an example ~/.cobra.yaml file:
|
||||
An example ~/.cobra.yaml file:
|
||||
|
||||
```yaml
|
||||
author: Steve Francia <spf@spf13.com>
|
||||
license: MIT
|
||||
```
|
||||
|
||||
You can specify no license by setting `license` to `none` or you can specify
|
||||
a custom license:
|
||||
|
||||
```yaml
|
||||
license:
|
||||
header: This file is part of {{ .appName }}.
|
||||
text: |
|
||||
{{ .copyright }}
|
||||
|
||||
This is my license. There are many like it, but this one is mine.
|
||||
My license is my best friend. It is my life. I must master it as I must
|
||||
master my life.
|
||||
```
|
||||
|
||||
## Manually implementing Cobra
|
||||
|
||||
To manually implement cobra you need to create a bare main.go file and a RootCmd file.
|
||||
|
@ -292,12 +319,17 @@ In a Cobra app, typically the main.go file is very bare. It serves, one purpose,
|
|||
```go
|
||||
package main
|
||||
|
||||
import "{pathToYourApp}/cmd"
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
|
||||
"{pathToYourApp}/cmd"
|
||||
)
|
||||
|
||||
func main() {
|
||||
if err := cmd.RootCmd.Execute(); err != nil {
|
||||
fmt.Println(err)
|
||||
os.Exit(-1)
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
```
|
||||
|
@ -316,6 +348,7 @@ package cmd
|
|||
|
||||
import (
|
||||
"github.com/spf13/cobra"
|
||||
"fmt"
|
||||
)
|
||||
|
||||
func init() {
|
||||
|
@ -642,7 +675,7 @@ command.SetUsageTemplate(s string)
|
|||
|
||||
## PreRun or PostRun Hooks
|
||||
|
||||
It is possible to run functions before or after the main `Run` function of your command. The `PersistentPreRun` and `PreRun` functions will be executed before `Run`. `PersistentPostRun` and `PostRun` will be executed after `Run`. The `Persistent*Run` functions will be inherrited by children if they do not declare their own. These function are run in the following order:
|
||||
It is possible to run functions before or after the main `Run` function of your command. The `PersistentPreRun` and `PreRun` functions will be executed before `Run`. `PersistentPostRun` and `PostRun` will be executed after `Run`. The `Persistent*Run` functions will be inherited by children if they do not declare their own. These functions are run in the following order:
|
||||
|
||||
- `PersistentPreRun`
|
||||
- `PreRun`
|
||||
|
@ -713,7 +746,8 @@ func main() {
|
|||
|
||||
## Alternative Error Handling
|
||||
|
||||
Cobra also has functions where the return signature is an error. This allows for errors to bubble up to the top, providing a way to handle the errors in one location. The current list of functions that return an error is:
|
||||
Cobra also has functions where the return signature is an error. This allows for errors to bubble up to the top,
|
||||
providing a way to handle the errors in one location. The current list of functions that return an error is:
|
||||
|
||||
* PersistentPreRunE
|
||||
* PreRunE
|
||||
|
@ -721,6 +755,10 @@ Cobra also has functions where the return signature is an error. This allows for
|
|||
* PostRunE
|
||||
* PersistentPostRunE
|
||||
|
||||
If you would like to silence the default `error` and `usage` output in favor of your own, you can set `SilenceUsage`
|
||||
and `SilenceErrors` to `true` on the command. A child command respects these flags if they are set on the parent
|
||||
command.
|
||||
|
||||
**Example Usage using RunE:**
|
||||
|
||||
```go
|
||||
|
|
167
vendor/github.com/spf13/cobra/bash_completions.go
generated
vendored
167
vendor/github.com/spf13/cobra/bash_completions.go
generated
vendored
|
@ -10,8 +10,10 @@ import (
|
|||
"github.com/spf13/pflag"
|
||||
)
|
||||
|
||||
// Annotations for Bash completion.
|
||||
const (
|
||||
BashCompFilenameExt = "cobra_annotation_bash_completion_filename_extentions"
|
||||
BashCompFilenameExt = "cobra_annotation_bash_completion_filename_extensions"
|
||||
BashCompCustom = "cobra_annotation_bash_completion_custom"
|
||||
BashCompOneRequiredFlag = "cobra_annotation_bash_completion_one_required_flag"
|
||||
BashCompSubdirsInDir = "cobra_annotation_bash_completion_subdirs_in_dir"
|
||||
)
|
||||
|
@ -21,7 +23,7 @@ func preamble(out io.Writer, name string) error {
|
|||
if err != nil {
|
||||
return err
|
||||
}
|
||||
_, err = fmt.Fprintf(out, `
|
||||
preamStr := `
|
||||
__debug()
|
||||
{
|
||||
if [[ -n ${BASH_COMP_DEBUG_FILE} ]]; then
|
||||
|
@ -34,7 +36,7 @@ __debug()
|
|||
__my_init_completion()
|
||||
{
|
||||
COMPREPLY=()
|
||||
_get_comp_words_by_ref cur prev words cword
|
||||
_get_comp_words_by_ref "$@" cur prev words cword
|
||||
}
|
||||
|
||||
__index_of_word()
|
||||
|
@ -60,7 +62,7 @@ __contains_word()
|
|||
|
||||
__handle_reply()
|
||||
{
|
||||
__debug "${FUNCNAME}"
|
||||
__debug "${FUNCNAME[0]}"
|
||||
case $cur in
|
||||
-*)
|
||||
if [[ $(type -t compopt) = "builtin" ]]; then
|
||||
|
@ -74,7 +76,28 @@ __handle_reply()
|
|||
fi
|
||||
COMPREPLY=( $(compgen -W "${allflags[*]}" -- "$cur") )
|
||||
if [[ $(type -t compopt) = "builtin" ]]; then
|
||||
[[ $COMPREPLY == *= ]] || compopt +o nospace
|
||||
[[ "${COMPREPLY[0]}" == *= ]] || compopt +o nospace
|
||||
fi
|
||||
|
||||
# complete after --flag=abc
|
||||
if [[ $cur == *=* ]]; then
|
||||
if [[ $(type -t compopt) = "builtin" ]]; then
|
||||
compopt +o nospace
|
||||
fi
|
||||
|
||||
local index flag
|
||||
flag="${cur%%=*}"
|
||||
__index_of_word "${flag}" "${flags_with_completion[@]}"
|
||||
COMPREPLY=()
|
||||
if [[ ${index} -ge 0 ]]; then
|
||||
PREFIX=""
|
||||
cur="${cur#*=}"
|
||||
${flags_completion[${index}]}
|
||||
if [ -n "${ZSH_VERSION}" ]; then
|
||||
# zfs completion needs --flag= prefix
|
||||
eval "COMPREPLY=( \"\${COMPREPLY[@]/#/${flag}=}\" )"
|
||||
fi
|
||||
fi
|
||||
fi
|
||||
return 0;
|
||||
;;
|
||||
|
@ -94,15 +117,19 @@ __handle_reply()
|
|||
fi
|
||||
|
||||
local completions
|
||||
if [[ ${#must_have_one_flag[@]} -ne 0 ]]; then
|
||||
completions=("${must_have_one_flag[@]}")
|
||||
elif [[ ${#must_have_one_noun[@]} -ne 0 ]]; then
|
||||
completions=("${commands[@]}")
|
||||
if [[ ${#must_have_one_noun[@]} -ne 0 ]]; then
|
||||
completions=("${must_have_one_noun[@]}")
|
||||
else
|
||||
completions=("${commands[@]}")
|
||||
fi
|
||||
if [[ ${#must_have_one_flag[@]} -ne 0 ]]; then
|
||||
completions+=("${must_have_one_flag[@]}")
|
||||
fi
|
||||
COMPREPLY=( $(compgen -W "${completions[*]}" -- "$cur") )
|
||||
|
||||
if [[ ${#COMPREPLY[@]} -eq 0 && ${#noun_aliases[@]} -gt 0 && ${#must_have_one_noun[@]} -ne 0 ]]; then
|
||||
COMPREPLY=( $(compgen -W "${noun_aliases[*]}" -- "$cur") )
|
||||
fi
|
||||
|
||||
if [[ ${#COMPREPLY[@]} -eq 0 ]]; then
|
||||
declare -F __custom_func >/dev/null && __custom_func
|
||||
fi
|
||||
|
@ -125,7 +152,7 @@ __handle_subdirs_in_dir_flag()
|
|||
|
||||
__handle_flag()
|
||||
{
|
||||
__debug "${FUNCNAME}: c is $c words[c] is ${words[c]}"
|
||||
__debug "${FUNCNAME[0]}: c is $c words[c] is ${words[c]}"
|
||||
|
||||
# if a command required a flag, and we found it, unset must_have_one_flag()
|
||||
local flagname=${words[c]}
|
||||
|
@ -136,15 +163,20 @@ __handle_flag()
|
|||
flagname=${flagname%%=*} # strip everything after the =
|
||||
flagname="${flagname}=" # but put the = back
|
||||
fi
|
||||
__debug "${FUNCNAME}: looking for ${flagname}"
|
||||
__debug "${FUNCNAME[0]}: looking for ${flagname}"
|
||||
if __contains_word "${flagname}" "${must_have_one_flag[@]}"; then
|
||||
must_have_one_flag=()
|
||||
fi
|
||||
|
||||
# if you set a flag which only applies to this command, don't show subcommands
|
||||
if __contains_word "${flagname}" "${local_nonpersistent_flags[@]}"; then
|
||||
commands=()
|
||||
fi
|
||||
|
||||
# keep flag value with flagname as flaghash
|
||||
if [ ${flagvalue} ] ; then
|
||||
if [ -n "${flagvalue}" ] ; then
|
||||
flaghash[${flagname}]=${flagvalue}
|
||||
elif [ ${words[ $((c+1)) ]} ] ; then
|
||||
elif [ -n "${words[ $((c+1)) ]}" ] ; then
|
||||
flaghash[${flagname}]=${words[ $((c+1)) ]}
|
||||
else
|
||||
flaghash[${flagname}]="true" # pad "true" for bool flag
|
||||
|
@ -165,10 +197,12 @@ __handle_flag()
|
|||
|
||||
__handle_noun()
|
||||
{
|
||||
__debug "${FUNCNAME}: c is $c words[c] is ${words[c]}"
|
||||
__debug "${FUNCNAME[0]}: c is $c words[c] is ${words[c]}"
|
||||
|
||||
if __contains_word "${words[c]}" "${must_have_one_noun[@]}"; then
|
||||
must_have_one_noun=()
|
||||
elif __contains_word "${words[c]}" "${noun_aliases[@]}"; then
|
||||
must_have_one_noun=()
|
||||
fi
|
||||
|
||||
nouns+=("${words[c]}")
|
||||
|
@ -177,21 +211,21 @@ __handle_noun()
|
|||
|
||||
__handle_command()
|
||||
{
|
||||
__debug "${FUNCNAME}: c is $c words[c] is ${words[c]}"
|
||||
__debug "${FUNCNAME[0]}: c is $c words[c] is ${words[c]}"
|
||||
|
||||
local next_command
|
||||
if [[ -n ${last_command} ]]; then
|
||||
next_command="_${last_command}_${words[c]//:/__}"
|
||||
else
|
||||
if [[ $c -eq 0 ]]; then
|
||||
next_command="_$(basename ${words[c]//:/__})"
|
||||
next_command="_$(basename "${words[c]//:/__}")"
|
||||
else
|
||||
next_command="_${words[c]//:/__}"
|
||||
fi
|
||||
fi
|
||||
c=$((c+1))
|
||||
__debug "${FUNCNAME}: looking for ${next_command}"
|
||||
declare -F $next_command >/dev/null && $next_command
|
||||
__debug "${FUNCNAME[0]}: looking for ${next_command}"
|
||||
declare -F "$next_command" >/dev/null && $next_command
|
||||
}
|
||||
|
||||
__handle_word()
|
||||
|
@ -200,12 +234,12 @@ __handle_word()
|
|||
__handle_reply
|
||||
return
|
||||
fi
|
||||
__debug "${FUNCNAME}: c is $c words[c] is ${words[c]}"
|
||||
__debug "${FUNCNAME[0]}: c is $c words[c] is ${words[c]}"
|
||||
if [[ "${words[c]}" == -* ]]; then
|
||||
__handle_flag
|
||||
elif __contains_word "${words[c]}" "${commands[@]}"; then
|
||||
__handle_command
|
||||
elif [[ $c -eq 0 ]] && __contains_word "$(basename ${words[c]})" "${commands[@]}"; then
|
||||
elif [[ $c -eq 0 ]] && __contains_word "$(basename "${words[c]}")" "${commands[@]}"; then
|
||||
__handle_command
|
||||
else
|
||||
__handle_noun
|
||||
|
@ -213,7 +247,8 @@ __handle_word()
|
|||
__handle_word
|
||||
}
|
||||
|
||||
`)
|
||||
`
|
||||
_, err = fmt.Fprint(out, preamStr)
|
||||
return err
|
||||
}
|
||||
|
||||
|
@ -229,12 +264,13 @@ func postscript(w io.Writer, name string) error {
|
|||
if declare -F _init_completion >/dev/null 2>&1; then
|
||||
_init_completion -s || return
|
||||
else
|
||||
__my_init_completion || return
|
||||
__my_init_completion -n "=" || return
|
||||
fi
|
||||
|
||||
local c=0
|
||||
local flags=()
|
||||
local two_word_flags=()
|
||||
local local_nonpersistent_flags=()
|
||||
local flags_with_completion=()
|
||||
local flags_completion=()
|
||||
local commands=("%s")
|
||||
|
@ -299,6 +335,20 @@ func writeFlagHandler(name string, annotations map[string][]string, w io.Writer)
|
|||
if err != nil {
|
||||
return err
|
||||
}
|
||||
case BashCompCustom:
|
||||
_, err := fmt.Fprintf(w, " flags_with_completion+=(%q)\n", name)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if len(value) > 0 {
|
||||
handlers := strings.Join(value, "; ")
|
||||
_, err = fmt.Fprintf(w, " flags_completion+=(%q)\n", handlers)
|
||||
} else {
|
||||
_, err = fmt.Fprintf(w, " flags_completion+=(:)\n")
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
case BashCompSubdirsInDir:
|
||||
_, err := fmt.Fprintf(w, " flags_with_completion+=(%q)\n", name)
|
||||
|
||||
|
@ -318,7 +368,7 @@ func writeFlagHandler(name string, annotations map[string][]string, w io.Writer)
|
|||
}
|
||||
|
||||
func writeShortFlag(flag *pflag.Flag, w io.Writer) error {
|
||||
b := (flag.Value.Type() == "bool")
|
||||
b := (len(flag.NoOptDefVal) > 0)
|
||||
name := flag.Shorthand
|
||||
format := " "
|
||||
if !b {
|
||||
|
@ -332,7 +382,7 @@ func writeShortFlag(flag *pflag.Flag, w io.Writer) error {
|
|||
}
|
||||
|
||||
func writeFlag(flag *pflag.Flag, w io.Writer) error {
|
||||
b := (flag.Value.Type() == "bool")
|
||||
b := (len(flag.NoOptDefVal) > 0)
|
||||
name := flag.Name
|
||||
format := " flags+=(\"--%s"
|
||||
if !b {
|
||||
|
@ -345,9 +395,22 @@ func writeFlag(flag *pflag.Flag, w io.Writer) error {
|
|||
return writeFlagHandler("--"+name, flag.Annotations, w)
|
||||
}
|
||||
|
||||
func writeLocalNonPersistentFlag(flag *pflag.Flag, w io.Writer) error {
|
||||
b := (len(flag.NoOptDefVal) > 0)
|
||||
name := flag.Name
|
||||
format := " local_nonpersistent_flags+=(\"--%s"
|
||||
if !b {
|
||||
format += "="
|
||||
}
|
||||
format += "\")\n"
|
||||
_, err := fmt.Fprintf(w, format, name)
|
||||
return err
|
||||
}
|
||||
|
||||
func writeFlags(cmd *Command, w io.Writer) error {
|
||||
_, err := fmt.Fprintf(w, ` flags=()
|
||||
two_word_flags=()
|
||||
local_nonpersistent_flags=()
|
||||
flags_with_completion=()
|
||||
flags_completion=()
|
||||
|
||||
|
@ -355,8 +418,12 @@ func writeFlags(cmd *Command, w io.Writer) error {
|
|||
if err != nil {
|
||||
return err
|
||||
}
|
||||
localNonPersistentFlags := cmd.LocalNonPersistentFlags()
|
||||
var visitErr error
|
||||
cmd.NonInheritedFlags().VisitAll(func(flag *pflag.Flag) {
|
||||
if nonCompletableFlag(flag) {
|
||||
return
|
||||
}
|
||||
if err := writeFlag(flag, w); err != nil {
|
||||
visitErr = err
|
||||
return
|
||||
|
@ -367,11 +434,20 @@ func writeFlags(cmd *Command, w io.Writer) error {
|
|||
return
|
||||
}
|
||||
}
|
||||
if localNonPersistentFlags.Lookup(flag.Name) != nil {
|
||||
if err := writeLocalNonPersistentFlag(flag, w); err != nil {
|
||||
visitErr = err
|
||||
return
|
||||
}
|
||||
}
|
||||
})
|
||||
if visitErr != nil {
|
||||
return visitErr
|
||||
}
|
||||
cmd.InheritedFlags().VisitAll(func(flag *pflag.Flag) {
|
||||
if nonCompletableFlag(flag) {
|
||||
return
|
||||
}
|
||||
if err := writeFlag(flag, w); err != nil {
|
||||
visitErr = err
|
||||
return
|
||||
|
@ -398,6 +474,9 @@ func writeRequiredFlag(cmd *Command, w io.Writer) error {
|
|||
flags := cmd.NonInheritedFlags()
|
||||
var visitErr error
|
||||
flags.VisitAll(func(flag *pflag.Flag) {
|
||||
if nonCompletableFlag(flag) {
|
||||
return
|
||||
}
|
||||
for key := range flag.Annotations {
|
||||
switch key {
|
||||
case BashCompOneRequiredFlag:
|
||||
|
@ -424,7 +503,7 @@ func writeRequiredFlag(cmd *Command, w io.Writer) error {
|
|||
return visitErr
|
||||
}
|
||||
|
||||
func writeRequiredNoun(cmd *Command, w io.Writer) error {
|
||||
func writeRequiredNouns(cmd *Command, w io.Writer) error {
|
||||
if _, err := fmt.Fprintf(w, " must_have_one_noun=()\n"); err != nil {
|
||||
return err
|
||||
}
|
||||
|
@ -437,6 +516,19 @@ func writeRequiredNoun(cmd *Command, w io.Writer) error {
|
|||
return nil
|
||||
}
|
||||
|
||||
func writeArgAliases(cmd *Command, w io.Writer) error {
|
||||
if _, err := fmt.Fprintf(w, " noun_aliases=()\n"); err != nil {
|
||||
return err
|
||||
}
|
||||
sort.Sort(sort.StringSlice(cmd.ArgAliases))
|
||||
for _, value := range cmd.ArgAliases {
|
||||
if _, err := fmt.Fprintf(w, " noun_aliases+=(%q)\n", value); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func gen(cmd *Command, w io.Writer) error {
|
||||
for _, c := range cmd.Commands() {
|
||||
if !c.IsAvailableCommand() || c == cmd.helpCommand {
|
||||
|
@ -464,7 +556,10 @@ func gen(cmd *Command, w io.Writer) error {
|
|||
if err := writeRequiredFlag(cmd, w); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := writeRequiredNoun(cmd, w); err != nil {
|
||||
if err := writeRequiredNouns(cmd, w); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := writeArgAliases(cmd, w); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := fmt.Fprintf(w, "}\n\n"); err != nil {
|
||||
|
@ -473,6 +568,7 @@ func gen(cmd *Command, w io.Writer) error {
|
|||
return nil
|
||||
}
|
||||
|
||||
// GenBashCompletion generates bash completion file and writes to the passed writer.
|
||||
func (cmd *Command) GenBashCompletion(w io.Writer) error {
|
||||
if err := preamble(w, cmd.Name()); err != nil {
|
||||
return err
|
||||
|
@ -488,6 +584,11 @@ func (cmd *Command) GenBashCompletion(w io.Writer) error {
|
|||
return postscript(w, cmd.Name())
|
||||
}
|
||||
|
||||
func nonCompletableFlag(flag *pflag.Flag) bool {
|
||||
return flag.Hidden || len(flag.Deprecated) > 0
|
||||
}
|
||||
|
||||
// GenBashCompletionFile generates bash completion file.
|
||||
func (cmd *Command) GenBashCompletionFile(filename string) error {
|
||||
outFile, err := os.Create(filename)
|
||||
if err != nil {
|
||||
|
@ -519,6 +620,12 @@ func (cmd *Command) MarkFlagFilename(name string, extensions ...string) error {
|
|||
return MarkFlagFilename(cmd.Flags(), name, extensions...)
|
||||
}
|
||||
|
||||
// MarkFlagCustom adds the BashCompCustom annotation to the named flag, if it exists.
|
||||
// Generated bash autocompletion will call the bash function f for the flag.
|
||||
func (cmd *Command) MarkFlagCustom(name string, f string) error {
|
||||
return MarkFlagCustom(cmd.Flags(), name, f)
|
||||
}
|
||||
|
||||
// MarkPersistentFlagFilename adds the BashCompFilenameExt annotation to the named persistent flag, if it exists.
|
||||
// Generated bash autocompletion will select filenames for the flag, limiting to named extensions if provided.
|
||||
func (cmd *Command) MarkPersistentFlagFilename(name string, extensions ...string) error {
|
||||
|
@ -530,3 +637,9 @@ func (cmd *Command) MarkPersistentFlagFilename(name string, extensions ...string
|
|||
func MarkFlagFilename(flags *pflag.FlagSet, name string, extensions ...string) error {
|
||||
return flags.SetAnnotation(name, BashCompFilenameExt, extensions)
|
||||
}
|
||||
|
||||
// MarkFlagCustom adds the BashCompCustom annotation to the named flag in the flag set, if it exists.
|
||||
// Generated bash autocompletion will call the bash function f for the flag.
|
||||
func MarkFlagCustom(flags *pflag.FlagSet, name string, f string) error {
|
||||
return flags.SetAnnotation(name, BashCompCustom, []string{f})
|
||||
}
|
||||
|
|
63
vendor/github.com/spf13/cobra/bash_completions.md
generated
vendored
63
vendor/github.com/spf13/cobra/bash_completions.md
generated
vendored
|
@ -18,7 +18,7 @@ func main() {
|
|||
}
|
||||
```
|
||||
|
||||
That will get you completions of subcommands and flags. If you make additional annotations to your code, you can get even more intelligent and flexible behavior.
|
||||
`out.sh` will get you completions of subcommands and flags. Copy it to `/etc/bash_completion.d/` as described [here](https://debian-administration.org/article/316/An_introduction_to_bash_completion_part_1) and reset your terminal to use autocompletion. If you make additional annotations to your code, you can get even more intelligent and flexible behavior.
|
||||
|
||||
## Creating your own custom functions
|
||||
|
||||
|
@ -80,7 +80,7 @@ The `BashCompletionFunction` option is really only valid/useful on the root comm
|
|||
In the above example "pod" was assumed to already be typed. But if you want `kubectl get [tab][tab]` to show a list of valid "nouns" you have to set them. Simplified code from `kubectl get` looks like:
|
||||
|
||||
```go
|
||||
validArgs []string = { "pods", "nodes", "services", "replicationControllers" }
|
||||
validArgs []string = { "pod", "node", "service", "replicationcontroller" }
|
||||
|
||||
cmd := &cobra.Command{
|
||||
Use: "get [(-o|--output=)json|yaml|template|...] (RESOURCE [NAME] | RESOURCE/NAME ...)",
|
||||
|
@ -99,9 +99,34 @@ Notice we put the "ValidArgs" on the "get" subcommand. Doing so will give result
|
|||
|
||||
```bash
|
||||
# kubectl get [tab][tab]
|
||||
nodes pods replicationControllers services
|
||||
node pod replicationcontroller service
|
||||
```
|
||||
|
||||
## Plural form and shortcuts for nouns
|
||||
|
||||
If your nouns have a number of aliases, you can define them alongside `ValidArgs` using `ArgAliases`:
|
||||
|
||||
```go`
|
||||
argAliases []string = { "pods", "nodes", "services", "svc", "replicationcontrollers", "rc" }
|
||||
|
||||
cmd := &cobra.Command{
|
||||
...
|
||||
ValidArgs: validArgs,
|
||||
ArgAliases: argAliases
|
||||
}
|
||||
```
|
||||
|
||||
The aliases are not shown to the user on tab completion, but they are accepted as valid nouns by
|
||||
the completion algorithm if entered manually, e.g. in:
|
||||
|
||||
```bash
|
||||
# kubectl get rc [tab][tab]
|
||||
backend frontend database
|
||||
```
|
||||
|
||||
Note that without declaring `rc` as an alias, the completion algorithm would show the list of nouns
|
||||
in this example again instead of the replication controllers.
|
||||
|
||||
## Mark flags as required
|
||||
|
||||
Most of the time completions will only show subcommands. But if a flag is required to make a subcommand work, you probably want it to show up when the user types [tab][tab]. Marking a flag as 'Required' is incredibly easy.
|
||||
|
@ -147,3 +172,35 @@ hello.yml test.json
|
|||
```
|
||||
|
||||
So while there are many other files in the CWD it only shows me subdirs and those with valid extensions.
|
||||
|
||||
# Specifiy custom flag completion
|
||||
|
||||
Similar to the filename completion and filtering using cobra.BashCompFilenameExt, you can specifiy
|
||||
a custom flag completion function with cobra.BashCompCustom:
|
||||
|
||||
```go
|
||||
annotation := make(map[string][]string)
|
||||
annotation[cobra.BashCompFilenameExt] = []string{"__kubectl_get_namespaces"}
|
||||
|
||||
flag := &pflag.Flag{
|
||||
Name: "namespace",
|
||||
Usage: usage,
|
||||
Annotations: annotation,
|
||||
}
|
||||
cmd.Flags().AddFlag(flag)
|
||||
```
|
||||
|
||||
In addition add the `__handle_namespace_flag` implementation in the `BashCompletionFunction`
|
||||
value, e.g.:
|
||||
|
||||
```bash
|
||||
__kubectl_get_namespaces()
|
||||
{
|
||||
local template
|
||||
template="{{ range .items }}{{ .metadata.name }} {{ end }}"
|
||||
local kubectl_out
|
||||
if kubectl_out=$(kubectl get -o template --template="${template}" namespace 2>/dev/null); then
|
||||
COMPREPLY=( $( compgen -W "${kubectl_out}[*]" -- "$cur" ) )
|
||||
fi
|
||||
}
|
||||
```
|
||||
|
|
95
vendor/github.com/spf13/cobra/bash_completions_test.go
generated
vendored
95
vendor/github.com/spf13/cobra/bash_completions_test.go
generated
vendored
|
@ -1,95 +0,0 @@
|
|||
package cobra
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"os"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
var _ = fmt.Println
|
||||
var _ = os.Stderr
|
||||
|
||||
func checkOmit(t *testing.T, found, unexpected string) {
|
||||
if strings.Contains(found, unexpected) {
|
||||
t.Errorf("Unexpected response.\nGot: %q\nBut should not have!\n", unexpected)
|
||||
}
|
||||
}
|
||||
|
||||
func check(t *testing.T, found, expected string) {
|
||||
if !strings.Contains(found, expected) {
|
||||
t.Errorf("Unexpected response.\nExpecting to contain: \n %q\nGot:\n %q\n", expected, found)
|
||||
}
|
||||
}
|
||||
|
||||
// World worst custom function, just keep telling you to enter hello!
|
||||
const (
|
||||
bash_completion_func = `__custom_func() {
|
||||
COMPREPLY=( "hello" )
|
||||
}
|
||||
`
|
||||
)
|
||||
|
||||
func TestBashCompletions(t *testing.T) {
|
||||
c := initializeWithRootCmd()
|
||||
cmdEcho.AddCommand(cmdTimes)
|
||||
c.AddCommand(cmdEcho, cmdPrint, cmdDeprecated, cmdColon)
|
||||
|
||||
// custom completion function
|
||||
c.BashCompletionFunction = bash_completion_func
|
||||
|
||||
// required flag
|
||||
c.MarkFlagRequired("introot")
|
||||
|
||||
// valid nouns
|
||||
validArgs := []string{"pods", "nodes", "services", "replicationControllers"}
|
||||
c.ValidArgs = validArgs
|
||||
|
||||
// filename
|
||||
var flagval string
|
||||
c.Flags().StringVar(&flagval, "filename", "", "Enter a filename")
|
||||
c.MarkFlagFilename("filename", "json", "yaml", "yml")
|
||||
|
||||
// persistent filename
|
||||
var flagvalPersistent string
|
||||
c.PersistentFlags().StringVar(&flagvalPersistent, "persistent-filename", "", "Enter a filename")
|
||||
c.MarkPersistentFlagFilename("persistent-filename")
|
||||
c.MarkPersistentFlagRequired("persistent-filename")
|
||||
|
||||
// filename extensions
|
||||
var flagvalExt string
|
||||
c.Flags().StringVar(&flagvalExt, "filename-ext", "", "Enter a filename (extension limited)")
|
||||
c.MarkFlagFilename("filename-ext")
|
||||
|
||||
// subdirectories in a given directory
|
||||
var flagvalTheme string
|
||||
c.Flags().StringVar(&flagvalTheme, "theme", "", "theme to use (located in /themes/THEMENAME/)")
|
||||
c.Flags().SetAnnotation("theme", BashCompSubdirsInDir, []string{"themes"})
|
||||
|
||||
out := new(bytes.Buffer)
|
||||
c.GenBashCompletion(out)
|
||||
str := out.String()
|
||||
|
||||
check(t, str, "_cobra-test")
|
||||
check(t, str, "_cobra-test_echo")
|
||||
check(t, str, "_cobra-test_echo_times")
|
||||
check(t, str, "_cobra-test_print")
|
||||
check(t, str, "_cobra-test_cmd__colon")
|
||||
|
||||
// check for required flags
|
||||
check(t, str, `must_have_one_flag+=("--introot=")`)
|
||||
check(t, str, `must_have_one_flag+=("--persistent-filename=")`)
|
||||
// check for custom completion function
|
||||
check(t, str, `COMPREPLY=( "hello" )`)
|
||||
// check for required nouns
|
||||
check(t, str, `must_have_one_noun+=("pods")`)
|
||||
// check for filename extension flags
|
||||
check(t, str, `flags_completion+=("_filedir")`)
|
||||
// check for filename extension flags
|
||||
check(t, str, `flags_completion+=("__handle_filename_extension_flag json|yaml|yml")`)
|
||||
// check for subdirs_in_dir flags
|
||||
check(t, str, `flags_completion+=("__handle_subdirs_in_dir_flag themes")`)
|
||||
|
||||
checkOmit(t, str, cmdDeprecated.Name())
|
||||
}
|
58
vendor/github.com/spf13/cobra/cobra.go
generated
vendored
58
vendor/github.com/spf13/cobra/cobra.go
generated
vendored
|
@ -26,44 +26,48 @@ import (
|
|||
"unicode"
|
||||
)
|
||||
|
||||
var templateFuncs template.FuncMap = template.FuncMap{
|
||||
"trim": strings.TrimSpace,
|
||||
"trimRightSpace": trimRightSpace,
|
||||
"rpad": rpad,
|
||||
"gt": Gt,
|
||||
"eq": Eq,
|
||||
var templateFuncs = template.FuncMap{
|
||||
"trim": strings.TrimSpace,
|
||||
"trimRightSpace": trimRightSpace,
|
||||
"appendIfNotPresent": appendIfNotPresent,
|
||||
"rpad": rpad,
|
||||
"gt": Gt,
|
||||
"eq": Eq,
|
||||
}
|
||||
|
||||
var initializers []func()
|
||||
|
||||
// automatic prefix matching can be a dangerous thing to automatically enable in CLI tools.
|
||||
// Set this to true to enable it
|
||||
var EnablePrefixMatching bool = false
|
||||
// EnablePrefixMatching allows to set automatic prefix matching. Automatic prefix matching can be a dangerous thing
|
||||
// to automatically enable in CLI tools.
|
||||
// Set this to true to enable it.
|
||||
var EnablePrefixMatching = false
|
||||
|
||||
//AddTemplateFunc adds a template function that's available to Usage and Help
|
||||
//template generation.
|
||||
// EnableCommandSorting controls sorting of the slice of commands, which is turned on by default.
|
||||
// To disable sorting, set it to false.
|
||||
var EnableCommandSorting = true
|
||||
|
||||
// AddTemplateFunc adds a template function that's available to Usage and Help
|
||||
// template generation.
|
||||
func AddTemplateFunc(name string, tmplFunc interface{}) {
|
||||
templateFuncs[name] = tmplFunc
|
||||
}
|
||||
|
||||
//AddTemplateFuncs adds multiple template functions availalble to Usage and
|
||||
//Help template generation.
|
||||
// AddTemplateFuncs adds multiple template functions that are available to Usage and
|
||||
// Help template generation.
|
||||
func AddTemplateFuncs(tmplFuncs template.FuncMap) {
|
||||
for k, v := range tmplFuncs {
|
||||
templateFuncs[k] = v
|
||||
}
|
||||
}
|
||||
|
||||
//OnInitialize takes a series of func() arguments and appends them to a slice of func().
|
||||
// OnInitialize takes a series of func() arguments and appends them to a slice of func().
|
||||
func OnInitialize(y ...func()) {
|
||||
for _, x := range y {
|
||||
initializers = append(initializers, x)
|
||||
}
|
||||
initializers = append(initializers, y...)
|
||||
}
|
||||
|
||||
//Gt takes two types and checks whether the first type is greater than the second. In case of types Arrays, Chans,
|
||||
//Maps and Slices, Gt will compare their lengths. Ints are compared directly while strings are first parsed as
|
||||
//ints and then compared.
|
||||
// Gt takes two types and checks whether the first type is greater than the second. In case of types Arrays, Chans,
|
||||
// Maps and Slices, Gt will compare their lengths. Ints are compared directly while strings are first parsed as
|
||||
// ints and then compared.
|
||||
func Gt(a interface{}, b interface{}) bool {
|
||||
var left, right int64
|
||||
av := reflect.ValueOf(a)
|
||||
|
@ -91,7 +95,7 @@ func Gt(a interface{}, b interface{}) bool {
|
|||
return left > right
|
||||
}
|
||||
|
||||
//Eq takes two types and checks whether they are equal. Supported types are int and string. Unsupported types will panic.
|
||||
// Eq takes two types and checks whether they are equal. Supported types are int and string. Unsupported types will panic.
|
||||
func Eq(a interface{}, b interface{}) bool {
|
||||
av := reflect.ValueOf(a)
|
||||
bv := reflect.ValueOf(b)
|
||||
|
@ -111,7 +115,15 @@ func trimRightSpace(s string) string {
|
|||
return strings.TrimRightFunc(s, unicode.IsSpace)
|
||||
}
|
||||
|
||||
//rpad adds padding to the right of a string
|
||||
// appendIfNotPresent will append stringToAppend to the end of s, but only if it's not yet present in s.
|
||||
func appendIfNotPresent(s, stringToAppend string) string {
|
||||
if strings.Contains(s, stringToAppend) {
|
||||
return s
|
||||
}
|
||||
return s + " " + stringToAppend
|
||||
}
|
||||
|
||||
// rpad adds padding to the right of a string.
|
||||
func rpad(s string, padding int) string {
|
||||
template := fmt.Sprintf("%%-%ds", padding)
|
||||
return fmt.Sprintf(template, s)
|
||||
|
@ -125,7 +137,7 @@ func tmpl(w io.Writer, text string, data interface{}) error {
|
|||
return t.Execute(w, data)
|
||||
}
|
||||
|
||||
// ld compares two strings and returns the levenshtein distance between them
|
||||
// ld compares two strings and returns the levenshtein distance between them.
|
||||
func ld(s, t string, ignoreCase bool) int {
|
||||
if ignoreCase {
|
||||
s = strings.ToLower(s)
|
||||
|
|
128
vendor/github.com/spf13/cobra/cobra/cmd/add.go
generated
vendored
128
vendor/github.com/spf13/cobra/cobra/cmd/add.go
generated
vendored
|
@ -1,128 +0,0 @@
|
|||
// Copyright © 2015 Steve Francia <spf@spf13.com>.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
"github.com/spf13/viper"
|
||||
)
|
||||
|
||||
func init() {
|
||||
RootCmd.AddCommand(addCmd)
|
||||
}
|
||||
|
||||
var pName string
|
||||
|
||||
// initialize Command
|
||||
var addCmd = &cobra.Command{
|
||||
Use: "add [command name]",
|
||||
Aliases: []string{"command"},
|
||||
Short: "Add a command to a Cobra Application",
|
||||
Long: `Add (cobra add) will create a new command, with a license and
|
||||
the appropriate structure for a Cobra-based CLI application,
|
||||
and register it to its parent (default RootCmd).
|
||||
|
||||
If you want your command to be public, pass in the command name
|
||||
with an initial uppercase letter.
|
||||
|
||||
Example: cobra add server -> resulting in a new cmd/server.go
|
||||
`,
|
||||
|
||||
Run: func(cmd *cobra.Command, args []string) {
|
||||
if len(args) != 1 {
|
||||
er("add needs a name for the command")
|
||||
}
|
||||
guessProjectPath()
|
||||
createCmdFile(args[0])
|
||||
},
|
||||
}
|
||||
|
||||
func init() {
|
||||
addCmd.Flags().StringVarP(&pName, "parent", "p", "RootCmd", "name of parent command for this command")
|
||||
}
|
||||
|
||||
func parentName() string {
|
||||
if !strings.HasSuffix(strings.ToLower(pName), "cmd") {
|
||||
return pName + "Cmd"
|
||||
}
|
||||
|
||||
return pName
|
||||
}
|
||||
|
||||
func createCmdFile(cmdName string) {
|
||||
lic := getLicense()
|
||||
|
||||
template := `{{ comment .copyright }}
|
||||
{{ comment .license }}
|
||||
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
// {{.cmdName}}Cmd represents the {{.cmdName}} command
|
||||
var {{ .cmdName }}Cmd = &cobra.Command{
|
||||
Use: "{{ .cmdName }}",
|
||||
Short: "A brief description of your command",
|
||||
Long: ` + "`" + `A longer description that spans multiple lines and likely contains examples
|
||||
and usage of using your command. For example:
|
||||
|
||||
Cobra is a CLI library for Go that empowers applications.
|
||||
This application is a tool to generate the needed files
|
||||
to quickly create a Cobra application.` + "`" + `,
|
||||
Run: func(cmd *cobra.Command, args []string) {
|
||||
// TODO: Work your own magic here
|
||||
fmt.Println("{{ .cmdName }} called")
|
||||
},
|
||||
}
|
||||
|
||||
func init() {
|
||||
{{ .parentName }}.AddCommand({{ .cmdName }}Cmd)
|
||||
|
||||
// Here you will define your flags and configuration settings.
|
||||
|
||||
// Cobra supports Persistent Flags which will work for this command
|
||||
// and all subcommands, e.g.:
|
||||
// {{.cmdName}}Cmd.PersistentFlags().String("foo", "", "A help for foo")
|
||||
|
||||
// Cobra supports local flags which will only run when this command
|
||||
// is called directly, e.g.:
|
||||
// {{.cmdName}}Cmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
|
||||
|
||||
}
|
||||
`
|
||||
|
||||
var data map[string]interface{}
|
||||
data = make(map[string]interface{})
|
||||
|
||||
data["copyright"] = copyrightLine()
|
||||
data["license"] = lic.Header
|
||||
data["appName"] = projectName()
|
||||
data["viper"] = viper.GetBool("useViper")
|
||||
data["parentName"] = parentName()
|
||||
data["cmdName"] = cmdName
|
||||
|
||||
err := writeTemplateToFile(filepath.Join(ProjectPath(), guessCmdDir()), cmdName+".go", template, data)
|
||||
if err != nil {
|
||||
er(err)
|
||||
}
|
||||
fmt.Println(cmdName, "created at", filepath.Join(ProjectPath(), guessCmdDir(), cmdName+".go"))
|
||||
}
|
347
vendor/github.com/spf13/cobra/cobra/cmd/helpers.go
generated
vendored
347
vendor/github.com/spf13/cobra/cobra/cmd/helpers.go
generated
vendored
|
@ -1,347 +0,0 @@
|
|||
// Copyright © 2015 Steve Francia <spf@spf13.com>.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"text/template"
|
||||
"time"
|
||||
|
||||
"github.com/spf13/viper"
|
||||
)
|
||||
|
||||
// var BaseDir = ""
|
||||
// var AppName = ""
|
||||
// var CommandDir = ""
|
||||
|
||||
var funcMap template.FuncMap
|
||||
var projectPath = ""
|
||||
var inputPath = ""
|
||||
var projectBase = ""
|
||||
|
||||
// for testing only
|
||||
var testWd = ""
|
||||
|
||||
var cmdDirs = []string{"cmd", "cmds", "command", "commands"}
|
||||
|
||||
func init() {
|
||||
funcMap = template.FuncMap{
|
||||
"comment": commentifyString,
|
||||
}
|
||||
}
|
||||
|
||||
func er(msg interface{}) {
|
||||
fmt.Println("Error:", msg)
|
||||
os.Exit(-1)
|
||||
}
|
||||
|
||||
// Check if a file or directory exists.
|
||||
func exists(path string) (bool, error) {
|
||||
_, err := os.Stat(path)
|
||||
if err == nil {
|
||||
return true, nil
|
||||
}
|
||||
if os.IsNotExist(err) {
|
||||
return false, nil
|
||||
}
|
||||
return false, err
|
||||
}
|
||||
|
||||
func ProjectPath() string {
|
||||
if projectPath == "" {
|
||||
guessProjectPath()
|
||||
}
|
||||
|
||||
return projectPath
|
||||
}
|
||||
|
||||
// wrapper of the os package so we can test better
|
||||
func getWd() (string, error) {
|
||||
if testWd == "" {
|
||||
return os.Getwd()
|
||||
}
|
||||
return testWd, nil
|
||||
}
|
||||
|
||||
func guessCmdDir() string {
|
||||
guessProjectPath()
|
||||
if b, _ := isEmpty(projectPath); b {
|
||||
return "cmd"
|
||||
}
|
||||
|
||||
files, _ := filepath.Glob(projectPath + string(os.PathSeparator) + "c*")
|
||||
for _, f := range files {
|
||||
for _, c := range cmdDirs {
|
||||
if f == c {
|
||||
return c
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return "cmd"
|
||||
}
|
||||
|
||||
func guessImportPath() string {
|
||||
guessProjectPath()
|
||||
|
||||
if !strings.HasPrefix(projectPath, getSrcPath()) {
|
||||
er("Cobra only supports project within $GOPATH")
|
||||
}
|
||||
|
||||
return filepath.ToSlash(filepath.Clean(strings.TrimPrefix(projectPath, getSrcPath())))
|
||||
}
|
||||
|
||||
func getSrcPath() string {
|
||||
return filepath.Join(os.Getenv("GOPATH"), "src") + string(os.PathSeparator)
|
||||
}
|
||||
|
||||
func projectName() string {
|
||||
return filepath.Base(ProjectPath())
|
||||
}
|
||||
|
||||
func guessProjectPath() {
|
||||
// if no path is provided... assume CWD.
|
||||
if inputPath == "" {
|
||||
x, err := getWd()
|
||||
if err != nil {
|
||||
er(err)
|
||||
}
|
||||
|
||||
// inspect CWD
|
||||
base := filepath.Base(x)
|
||||
|
||||
// if we are in the cmd directory.. back up
|
||||
for _, c := range cmdDirs {
|
||||
if base == c {
|
||||
projectPath = filepath.Dir(x)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
if projectPath == "" {
|
||||
projectPath = filepath.Clean(x)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
srcPath := getSrcPath()
|
||||
// if provided, inspect for logical locations
|
||||
if strings.ContainsRune(inputPath, os.PathSeparator) {
|
||||
if filepath.IsAbs(inputPath) || filepath.HasPrefix(inputPath, string(os.PathSeparator)) {
|
||||
// if Absolute, use it
|
||||
projectPath = filepath.Clean(inputPath)
|
||||
return
|
||||
}
|
||||
// If not absolute but contains slashes,
|
||||
// assuming it means create it from $GOPATH
|
||||
count := strings.Count(inputPath, string(os.PathSeparator))
|
||||
|
||||
switch count {
|
||||
// If only one directory deep, assume "github.com"
|
||||
case 1:
|
||||
projectPath = filepath.Join(srcPath, "github.com", inputPath)
|
||||
return
|
||||
case 2:
|
||||
projectPath = filepath.Join(srcPath, inputPath)
|
||||
return
|
||||
default:
|
||||
er("Unknown directory")
|
||||
}
|
||||
} else {
|
||||
// hardest case.. just a word.
|
||||
if projectBase == "" {
|
||||
x, err := getWd()
|
||||
if err == nil {
|
||||
projectPath = filepath.Join(x, inputPath)
|
||||
return
|
||||
}
|
||||
er(err)
|
||||
} else {
|
||||
projectPath = filepath.Join(srcPath, projectBase, inputPath)
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// isEmpty checks if a given path is empty.
|
||||
func isEmpty(path string) (bool, error) {
|
||||
if b, _ := exists(path); !b {
|
||||
return false, fmt.Errorf("%q path does not exist", path)
|
||||
}
|
||||
fi, err := os.Stat(path)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
if fi.IsDir() {
|
||||
f, err := os.Open(path)
|
||||
// FIX: Resource leak - f.close() should be called here by defer or is missed
|
||||
// if the err != nil branch is taken.
|
||||
defer f.Close()
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
list, err := f.Readdir(-1)
|
||||
// f.Close() - see bug fix above
|
||||
return len(list) == 0, nil
|
||||
}
|
||||
return fi.Size() == 0, nil
|
||||
}
|
||||
|
||||
// isDir checks if a given path is a directory.
|
||||
func isDir(path string) (bool, error) {
|
||||
fi, err := os.Stat(path)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
return fi.IsDir(), nil
|
||||
}
|
||||
|
||||
// dirExists checks if a path exists and is a directory.
|
||||
func dirExists(path string) (bool, error) {
|
||||
fi, err := os.Stat(path)
|
||||
if err == nil && fi.IsDir() {
|
||||
return true, nil
|
||||
}
|
||||
if os.IsNotExist(err) {
|
||||
return false, nil
|
||||
}
|
||||
return false, err
|
||||
}
|
||||
|
||||
func writeTemplateToFile(path string, file string, template string, data interface{}) error {
|
||||
filename := filepath.Join(path, file)
|
||||
|
||||
r, err := templateToReader(template, data)
|
||||
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
err = safeWriteToDisk(filename, r)
|
||||
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func writeStringToFile(path, file, text string) error {
|
||||
filename := filepath.Join(path, file)
|
||||
|
||||
r := strings.NewReader(text)
|
||||
err := safeWriteToDisk(filename, r)
|
||||
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func templateToReader(tpl string, data interface{}) (io.Reader, error) {
|
||||
tmpl := template.New("")
|
||||
tmpl.Funcs(funcMap)
|
||||
tmpl, err := tmpl.Parse(tpl)
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
buf := new(bytes.Buffer)
|
||||
err = tmpl.Execute(buf, data)
|
||||
|
||||
return buf, err
|
||||
}
|
||||
|
||||
// Same as WriteToDisk but checks to see if file/directory already exists.
|
||||
func safeWriteToDisk(inpath string, r io.Reader) (err error) {
|
||||
dir, _ := filepath.Split(inpath)
|
||||
ospath := filepath.FromSlash(dir)
|
||||
|
||||
if ospath != "" {
|
||||
err = os.MkdirAll(ospath, 0777) // rwx, rw, r
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
ex, err := exists(inpath)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
if ex {
|
||||
return fmt.Errorf("%v already exists", inpath)
|
||||
}
|
||||
|
||||
file, err := os.Create(inpath)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
defer file.Close()
|
||||
|
||||
_, err = io.Copy(file, r)
|
||||
return
|
||||
}
|
||||
|
||||
func getLicense() License {
|
||||
l := whichLicense()
|
||||
if l != "" {
|
||||
if x, ok := Licenses[l]; ok {
|
||||
return x
|
||||
}
|
||||
}
|
||||
|
||||
return Licenses["apache"]
|
||||
}
|
||||
|
||||
func whichLicense() string {
|
||||
// if explicitly flagged, use that
|
||||
if userLicense != "" {
|
||||
return matchLicense(userLicense)
|
||||
}
|
||||
|
||||
// if already present in the project, use that
|
||||
// TODO: Inspect project for existing license
|
||||
|
||||
// default to viper's setting
|
||||
|
||||
return matchLicense(viper.GetString("license"))
|
||||
}
|
||||
|
||||
func copyrightLine() string {
|
||||
author := viper.GetString("author")
|
||||
year := time.Now().Format("2006")
|
||||
|
||||
return "Copyright © " + year + " " + author
|
||||
}
|
||||
|
||||
func commentifyString(in string) string {
|
||||
var newlines []string
|
||||
lines := strings.Split(in, "\n")
|
||||
for _, x := range lines {
|
||||
if !strings.HasPrefix(x, "//") {
|
||||
if x != "" {
|
||||
newlines = append(newlines, "// "+x)
|
||||
} else {
|
||||
newlines = append(newlines, "//")
|
||||
}
|
||||
} else {
|
||||
newlines = append(newlines, x)
|
||||
}
|
||||
}
|
||||
return strings.Join(newlines, "\n")
|
||||
}
|
40
vendor/github.com/spf13/cobra/cobra/cmd/helpers_test.go
generated
vendored
40
vendor/github.com/spf13/cobra/cobra/cmd/helpers_test.go
generated
vendored
|
@ -1,40 +0,0 @@
|
|||
package cmd
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
)
|
||||
|
||||
var _ = fmt.Println
|
||||
var _ = os.Stderr
|
||||
|
||||
func checkGuess(t *testing.T, wd, input, expected string) {
|
||||
testWd = wd
|
||||
inputPath = input
|
||||
guessProjectPath()
|
||||
|
||||
if projectPath != expected {
|
||||
t.Errorf("Unexpected Project Path. \n Got: %q\nExpected: %q\n", projectPath, expected)
|
||||
}
|
||||
|
||||
reset()
|
||||
}
|
||||
|
||||
func reset() {
|
||||
testWd = ""
|
||||
inputPath = ""
|
||||
projectPath = ""
|
||||
}
|
||||
|
||||
func TestProjectPath(t *testing.T) {
|
||||
checkGuess(t, "", filepath.Join("github.com", "spf13", "hugo"), filepath.Join(getSrcPath(), "github.com", "spf13", "hugo"))
|
||||
checkGuess(t, "", filepath.Join("spf13", "hugo"), filepath.Join(getSrcPath(), "github.com", "spf13", "hugo"))
|
||||
checkGuess(t, "", filepath.Join("/", "bar", "foo"), filepath.Join("/", "bar", "foo"))
|
||||
checkGuess(t, "/bar/foo", "baz", filepath.Join("/", "bar", "foo", "baz"))
|
||||
checkGuess(t, "/bar/foo/cmd", "", filepath.Join("/", "bar", "foo"))
|
||||
checkGuess(t, "/bar/foo/command", "", filepath.Join("/", "bar", "foo"))
|
||||
checkGuess(t, "/bar/foo/commands", "", filepath.Join("/", "bar", "foo"))
|
||||
checkGuess(t, "github.com/spf13/hugo/../hugo", "", filepath.Join("github.com", "spf13", "hugo"))
|
||||
}
|
226
vendor/github.com/spf13/cobra/cobra/cmd/init.go
generated
vendored
226
vendor/github.com/spf13/cobra/cobra/cmd/init.go
generated
vendored
|
@ -1,226 +0,0 @@
|
|||
// Copyright © 2015 Steve Francia <spf@spf13.com>.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"strings"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
"github.com/spf13/viper"
|
||||
)
|
||||
|
||||
func init() {
|
||||
RootCmd.AddCommand(initCmd)
|
||||
}
|
||||
|
||||
// initialize Command
|
||||
var initCmd = &cobra.Command{
|
||||
Use: "init [name]",
|
||||
Aliases: []string{"initialize", "initialise", "create"},
|
||||
Short: "Initialize a Cobra Application",
|
||||
Long: `Initialize (cobra init) will create a new application, with a license
|
||||
and the appropriate structure for a Cobra-based CLI application.
|
||||
|
||||
* If a name is provided, it will be created in the current directory;
|
||||
* If no name is provided, the current directory will be assumed;
|
||||
* If a relative path is provided, it will be created inside $GOPATH
|
||||
(e.g. github.com/spf13/hugo);
|
||||
* If an absolute path is provided, it will be created;
|
||||
* If the directory already exists but is empty, it will be used.
|
||||
|
||||
Init will not use an existing directory with contents.`,
|
||||
|
||||
Run: func(cmd *cobra.Command, args []string) {
|
||||
switch len(args) {
|
||||
case 0:
|
||||
inputPath = ""
|
||||
|
||||
case 1:
|
||||
inputPath = args[0]
|
||||
|
||||
default:
|
||||
er("init doesn't support more than 1 parameter")
|
||||
}
|
||||
guessProjectPath()
|
||||
initializePath(projectPath)
|
||||
},
|
||||
}
|
||||
|
||||
func initializePath(path string) {
|
||||
b, err := exists(path)
|
||||
if err != nil {
|
||||
er(err)
|
||||
}
|
||||
|
||||
if !b { // If path doesn't yet exist, create it
|
||||
err := os.MkdirAll(path, os.ModePerm)
|
||||
if err != nil {
|
||||
er(err)
|
||||
}
|
||||
} else { // If path exists and is not empty don't use it
|
||||
empty, err := exists(path)
|
||||
if err != nil {
|
||||
er(err)
|
||||
}
|
||||
if !empty {
|
||||
er("Cobra will not create a new project in a non empty directory")
|
||||
}
|
||||
}
|
||||
// We have a directory and it's empty.. Time to initialize it.
|
||||
|
||||
createLicenseFile()
|
||||
createMainFile()
|
||||
createRootCmdFile()
|
||||
}
|
||||
|
||||
func createLicenseFile() {
|
||||
lic := getLicense()
|
||||
|
||||
template := lic.Text
|
||||
|
||||
var data map[string]interface{}
|
||||
data = make(map[string]interface{})
|
||||
|
||||
// Try to remove the email address, if any
|
||||
data["copyright"] = strings.Split(copyrightLine(), " <")[0]
|
||||
|
||||
err := writeTemplateToFile(ProjectPath(), "LICENSE", template, data)
|
||||
_ = err
|
||||
// if err != nil {
|
||||
// er(err)
|
||||
// }
|
||||
}
|
||||
|
||||
func createMainFile() {
|
||||
lic := getLicense()
|
||||
|
||||
template := `{{ comment .copyright }}
|
||||
{{ comment .license }}
|
||||
|
||||
package main
|
||||
|
||||
import "{{ .importpath }}"
|
||||
|
||||
func main() {
|
||||
cmd.Execute()
|
||||
}
|
||||
`
|
||||
var data map[string]interface{}
|
||||
data = make(map[string]interface{})
|
||||
|
||||
data["copyright"] = copyrightLine()
|
||||
data["license"] = lic.Header
|
||||
data["importpath"] = guessImportPath() + "/" + guessCmdDir()
|
||||
|
||||
err := writeTemplateToFile(ProjectPath(), "main.go", template, data)
|
||||
_ = err
|
||||
// if err != nil {
|
||||
// er(err)
|
||||
// }
|
||||
}
|
||||
|
||||
func createRootCmdFile() {
|
||||
lic := getLicense()
|
||||
|
||||
template := `{{ comment .copyright }}
|
||||
{{ comment .license }}
|
||||
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
{{ if .viper }} "github.com/spf13/viper"
|
||||
{{ end }})
|
||||
{{if .viper}}
|
||||
var cfgFile string
|
||||
{{ end }}
|
||||
// This represents the base command when called without any subcommands
|
||||
var RootCmd = &cobra.Command{
|
||||
Use: "{{ .appName }}",
|
||||
Short: "A brief description of your application",
|
||||
Long: ` + "`" + `A longer description that spans multiple lines and likely contains
|
||||
examples and usage of using your application. For example:
|
||||
|
||||
Cobra is a CLI library for Go that empowers applications.
|
||||
This application is a tool to generate the needed files
|
||||
to quickly create a Cobra application.` + "`" + `,
|
||||
// Uncomment the following line if your bare application
|
||||
// has an action associated with it:
|
||||
// Run: func(cmd *cobra.Command, args []string) { },
|
||||
}
|
||||
|
||||
// Execute adds all child commands to the root command sets flags appropriately.
|
||||
// This is called by main.main(). It only needs to happen once to the rootCmd.
|
||||
func Execute() {
|
||||
if err := RootCmd.Execute(); err != nil {
|
||||
fmt.Println(err)
|
||||
os.Exit(-1)
|
||||
}
|
||||
}
|
||||
|
||||
func init() {
|
||||
{{ if .viper }} cobra.OnInitialize(initConfig)
|
||||
|
||||
{{ end }} // Here you will define your flags and configuration settings.
|
||||
// Cobra supports Persistent Flags, which, if defined here,
|
||||
// will be global for your application.
|
||||
{{ if .viper }}
|
||||
RootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.{{ .appName }}.yaml)")
|
||||
{{ else }}
|
||||
// RootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.{{ .appName }}.yaml)")
|
||||
{{ end }} // Cobra also supports local flags, which will only run
|
||||
// when this action is called directly.
|
||||
RootCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
|
||||
}
|
||||
{{ if .viper }}
|
||||
// initConfig reads in config file and ENV variables if set.
|
||||
func initConfig() {
|
||||
if cfgFile != "" { // enable ability to specify config file via flag
|
||||
viper.SetConfigFile(cfgFile)
|
||||
}
|
||||
|
||||
viper.SetConfigName(".{{ .appName }}") // name of config file (without extension)
|
||||
viper.AddConfigPath("$HOME") // adding home directory as first search path
|
||||
viper.AutomaticEnv() // read in environment variables that match
|
||||
|
||||
// If a config file is found, read it in.
|
||||
if err := viper.ReadInConfig(); err == nil {
|
||||
fmt.Println("Using config file:", viper.ConfigFileUsed())
|
||||
}
|
||||
}
|
||||
{{ end }}`
|
||||
|
||||
var data map[string]interface{}
|
||||
data = make(map[string]interface{})
|
||||
|
||||
data["copyright"] = copyrightLine()
|
||||
data["license"] = lic.Header
|
||||
data["appName"] = projectName()
|
||||
data["viper"] = viper.GetBool("useViper")
|
||||
|
||||
err := writeTemplateToFile(ProjectPath()+string(os.PathSeparator)+guessCmdDir(), "root.go", template, data)
|
||||
if err != nil {
|
||||
er(err)
|
||||
}
|
||||
|
||||
fmt.Println("Your Cobra application is ready at")
|
||||
fmt.Println(ProjectPath())
|
||||
fmt.Println("Give it a try by going there and running `go run main.go`")
|
||||
fmt.Println("Add commands to it by running `cobra add [cmdname]`")
|
||||
}
|
1133
vendor/github.com/spf13/cobra/cobra/cmd/licenses.go
generated
vendored
1133
vendor/github.com/spf13/cobra/cobra/cmd/licenses.go
generated
vendored
File diff suppressed because it is too large
Load diff
84
vendor/github.com/spf13/cobra/cobra/cmd/root.go
generated
vendored
84
vendor/github.com/spf13/cobra/cobra/cmd/root.go
generated
vendored
|
@ -1,84 +0,0 @@
|
|||
// Copyright © 2015 Steve Francia <spf@spf13.com>.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
"github.com/spf13/viper"
|
||||
)
|
||||
|
||||
var cfgFile string
|
||||
var userLicense string
|
||||
|
||||
// This represents the base command when called without any subcommands
|
||||
var RootCmd = &cobra.Command{
|
||||
Use: "cobra",
|
||||
Short: "A generator for Cobra based Applications",
|
||||
Long: `Cobra is a CLI library for Go that empowers applications.
|
||||
This application is a tool to generate the needed files
|
||||
to quickly create a Cobra application.`,
|
||||
}
|
||||
|
||||
//Execute adds all child commands to the root command sets flags appropriately.
|
||||
func Execute() {
|
||||
if err := RootCmd.Execute(); err != nil {
|
||||
fmt.Println(err)
|
||||
os.Exit(-1)
|
||||
}
|
||||
}
|
||||
|
||||
func init() {
|
||||
cobra.OnInitialize(initConfig)
|
||||
RootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.cobra.yaml)")
|
||||
RootCmd.PersistentFlags().StringVarP(&projectBase, "projectbase", "b", "", "base project directory, e.g. github.com/spf13/")
|
||||
RootCmd.PersistentFlags().StringP("author", "a", "YOUR NAME", "Author name for copyright attribution")
|
||||
RootCmd.PersistentFlags().StringVarP(&userLicense, "license", "l", "", "Name of license for the project (can provide `licensetext` in config)")
|
||||
RootCmd.PersistentFlags().Bool("viper", true, "Use Viper for configuration")
|
||||
viper.BindPFlag("author", RootCmd.PersistentFlags().Lookup("author"))
|
||||
viper.BindPFlag("projectbase", RootCmd.PersistentFlags().Lookup("projectbase"))
|
||||
viper.BindPFlag("useViper", RootCmd.PersistentFlags().Lookup("viper"))
|
||||
viper.SetDefault("author", "NAME HERE <EMAIL ADDRESS>")
|
||||
viper.SetDefault("license", "apache")
|
||||
viper.SetDefault("licenseText", `
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
`)
|
||||
}
|
||||
|
||||
// Read in config file and ENV variables if set.
|
||||
func initConfig() {
|
||||
if cfgFile != "" { // enable ability to specify config file via flag
|
||||
viper.SetConfigFile(cfgFile)
|
||||
}
|
||||
|
||||
viper.SetConfigName(".cobra") // name of config file (without extension)
|
||||
viper.AddConfigPath("$HOME") // adding home directory as first search path
|
||||
viper.AutomaticEnv() // read in environment variables that match
|
||||
|
||||
// If a config file is found, read it in.
|
||||
if err := viper.ReadInConfig(); err == nil {
|
||||
fmt.Println("Using config file:", viper.ConfigFileUsed())
|
||||
}
|
||||
}
|
20
vendor/github.com/spf13/cobra/cobra/main.go
generated
vendored
20
vendor/github.com/spf13/cobra/cobra/main.go
generated
vendored
|
@ -1,20 +0,0 @@
|
|||
// Copyright © 2015 Steve Francia <spf@spf13.com>.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package main
|
||||
|
||||
import "github.com/spf13/cobra/cobra/cmd"
|
||||
|
||||
func main() {
|
||||
cmd.Execute()
|
||||
}
|
1169
vendor/github.com/spf13/cobra/cobra_test.go
generated
vendored
1169
vendor/github.com/spf13/cobra/cobra_test.go
generated
vendored
File diff suppressed because it is too large
Load diff
426
vendor/github.com/spf13/cobra/command.go
generated
vendored
426
vendor/github.com/spf13/cobra/command.go
generated
vendored
|
@ -21,6 +21,7 @@ import (
|
|||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sort"
|
||||
"strings"
|
||||
|
||||
flag "github.com/spf13/pflag"
|
||||
|
@ -45,14 +46,20 @@ type Command struct {
|
|||
Long string
|
||||
// Examples of how to use the command
|
||||
Example string
|
||||
// List of all valid non-flag arguments, used for bash completions *TODO* actually validate these
|
||||
// List of all valid non-flag arguments that are accepted in bash completions
|
||||
ValidArgs []string
|
||||
// List of aliases for ValidArgs. These are not suggested to the user in the bash
|
||||
// completion, but accepted if entered manually.
|
||||
ArgAliases []string
|
||||
// Custom functions used by the bash autocompletion generator
|
||||
BashCompletionFunction string
|
||||
// Is this command deprecated and should print this string when used?
|
||||
Deprecated string
|
||||
// Is this command hidden and should NOT show up in the list of available commands?
|
||||
Hidden bool
|
||||
// Annotations are key/value pairs that can be used by applications to identify or
|
||||
// group commands
|
||||
Annotations map[string]string
|
||||
// Full set of flags
|
||||
flags *flag.FlagSet
|
||||
// Set of flags childrens of this command will inherit
|
||||
|
@ -100,13 +107,16 @@ type Command struct {
|
|||
commandsMaxUseLen int
|
||||
commandsMaxCommandPathLen int
|
||||
commandsMaxNameLen int
|
||||
// is commands slice are sorted or not
|
||||
commandsAreSorted bool
|
||||
|
||||
flagErrorBuf *bytes.Buffer
|
||||
|
||||
args []string // actual args parsed from flags
|
||||
output *io.Writer // nil means stderr; use Out() method instead
|
||||
usageFunc func(*Command) error // Usage can be defined by application
|
||||
usageTemplate string // Can be defined by Application
|
||||
args []string // actual args parsed from flags
|
||||
output io.Writer // out writer if set in SetOutput(w)
|
||||
usageFunc func(*Command) error // Usage can be defined by application
|
||||
usageTemplate string // Can be defined by Application
|
||||
flagErrorFunc func(*Command, error) error
|
||||
helpTemplate string // Can be defined by Application
|
||||
helpFunc func(*Command, []string) // Help can be defined by application
|
||||
helpCommand *Command // The help command
|
||||
|
@ -117,60 +127,50 @@ type Command struct {
|
|||
DisableSuggestions bool
|
||||
// If displaying suggestions, allows to set the minimum levenshtein distance to display, must be > 0
|
||||
SuggestionsMinimumDistance int
|
||||
|
||||
// Disable the flag parsing. If this is true all flags will be passed to the command as arguments.
|
||||
DisableFlagParsing bool
|
||||
}
|
||||
|
||||
// os.Args[1:] by default, if desired, can be overridden
|
||||
// SetArgs sets arguments for the command. It is set to os.Args[1:] by default, if desired, can be overridden
|
||||
// particularly useful when testing.
|
||||
func (c *Command) SetArgs(a []string) {
|
||||
c.args = a
|
||||
}
|
||||
|
||||
func (c *Command) getOut(def io.Writer) io.Writer {
|
||||
if c.output != nil {
|
||||
return *c.output
|
||||
}
|
||||
|
||||
if c.HasParent() {
|
||||
return c.parent.Out()
|
||||
} else {
|
||||
return def
|
||||
}
|
||||
}
|
||||
|
||||
func (c *Command) Out() io.Writer {
|
||||
return c.getOut(os.Stderr)
|
||||
}
|
||||
|
||||
func (c *Command) getOutOrStdout() io.Writer {
|
||||
return c.getOut(os.Stdout)
|
||||
}
|
||||
|
||||
// SetOutput sets the destination for usage and error messages.
|
||||
// If output is nil, os.Stderr is used.
|
||||
func (c *Command) SetOutput(output io.Writer) {
|
||||
c.output = &output
|
||||
c.output = output
|
||||
}
|
||||
|
||||
// Usage can be defined by application
|
||||
// SetUsageFunc sets usage function. Usage can be defined by application.
|
||||
func (c *Command) SetUsageFunc(f func(*Command) error) {
|
||||
c.usageFunc = f
|
||||
}
|
||||
|
||||
// Can be defined by Application
|
||||
// SetUsageTemplate sets usage template. Can be defined by Application.
|
||||
func (c *Command) SetUsageTemplate(s string) {
|
||||
c.usageTemplate = s
|
||||
}
|
||||
|
||||
// Can be defined by Application
|
||||
// SetFlagErrorFunc sets a function to generate an error when flag parsing
|
||||
// fails.
|
||||
func (c *Command) SetFlagErrorFunc(f func(*Command, error) error) {
|
||||
c.flagErrorFunc = f
|
||||
}
|
||||
|
||||
// SetHelpFunc sets help function. Can be defined by Application.
|
||||
func (c *Command) SetHelpFunc(f func(*Command, []string)) {
|
||||
c.helpFunc = f
|
||||
}
|
||||
|
||||
// SetHelpCommand sets help command.
|
||||
func (c *Command) SetHelpCommand(cmd *Command) {
|
||||
c.helpCommand = cmd
|
||||
}
|
||||
|
||||
// Can be defined by Application
|
||||
// SetHelpTemplate sets help template to be used. Application can use it to set custom template.
|
||||
func (c *Command) SetHelpTemplate(s string) {
|
||||
c.helpTemplate = s
|
||||
}
|
||||
|
@ -187,6 +187,28 @@ func (c *Command) SetGlobalNormalizationFunc(n func(f *flag.FlagSet, name string
|
|||
}
|
||||
}
|
||||
|
||||
// OutOrStdout returns output to stdout.
|
||||
func (c *Command) OutOrStdout() io.Writer {
|
||||
return c.getOut(os.Stdout)
|
||||
}
|
||||
|
||||
// OutOrStderr returns output to stderr
|
||||
func (c *Command) OutOrStderr() io.Writer {
|
||||
return c.getOut(os.Stderr)
|
||||
}
|
||||
|
||||
func (c *Command) getOut(def io.Writer) io.Writer {
|
||||
if c.output != nil {
|
||||
return c.output
|
||||
}
|
||||
if c.HasParent() {
|
||||
return c.parent.getOut(def)
|
||||
}
|
||||
return def
|
||||
}
|
||||
|
||||
// UsageFunc returns either the function set by SetUsageFunc for this command
|
||||
// or a parent, or it returns a default usage function.
|
||||
func (c *Command) UsageFunc() (f func(*Command) error) {
|
||||
if c.usageFunc != nil {
|
||||
return c.usageFunc
|
||||
|
@ -194,66 +216,118 @@ func (c *Command) UsageFunc() (f func(*Command) error) {
|
|||
|
||||
if c.HasParent() {
|
||||
return c.parent.UsageFunc()
|
||||
} else {
|
||||
return func(c *Command) error {
|
||||
err := tmpl(c.Out(), c.UsageTemplate(), c)
|
||||
if err != nil {
|
||||
fmt.Print(err)
|
||||
}
|
||||
return err
|
||||
}
|
||||
return func(c *Command) error {
|
||||
c.mergePersistentFlags()
|
||||
err := tmpl(c.OutOrStderr(), c.UsageTemplate(), c)
|
||||
if err != nil {
|
||||
c.Println(err)
|
||||
}
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
// Usage puts out the usage for the command.
|
||||
// Used when a user provides invalid input.
|
||||
// Can be defined by user by overriding UsageFunc.
|
||||
func (c *Command) Usage() error {
|
||||
return c.UsageFunc()(c)
|
||||
}
|
||||
|
||||
// HelpFunc returns either the function set by SetHelpFunc for this command
|
||||
// or a parent, or it returns a function which calls c.Help()
|
||||
// or a parent, or it returns a function with default help behavior.
|
||||
func (c *Command) HelpFunc() func(*Command, []string) {
|
||||
cmd := c
|
||||
for cmd != nil {
|
||||
if cmd.helpFunc != nil {
|
||||
return cmd.helpFunc
|
||||
}
|
||||
cmd = cmd.parent
|
||||
if helpFunc := c.checkHelpFunc(); helpFunc != nil {
|
||||
return helpFunc
|
||||
}
|
||||
return func(*Command, []string) {
|
||||
err := c.Help()
|
||||
c.mergePersistentFlags()
|
||||
err := tmpl(c.OutOrStdout(), c.HelpTemplate(), c)
|
||||
if err != nil {
|
||||
c.Println(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var minUsagePadding int = 25
|
||||
// checkHelpFunc checks if there is helpFunc in ancestors of c.
|
||||
func (c *Command) checkHelpFunc() func(*Command, []string) {
|
||||
if c == nil {
|
||||
return nil
|
||||
}
|
||||
if c.helpFunc != nil {
|
||||
return c.helpFunc
|
||||
}
|
||||
if c.HasParent() {
|
||||
return c.parent.checkHelpFunc()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Help puts out the help for the command.
|
||||
// Used when a user calls help [command].
|
||||
// Can be defined by user by overriding HelpFunc.
|
||||
func (c *Command) Help() error {
|
||||
c.HelpFunc()(c, []string{})
|
||||
return nil
|
||||
}
|
||||
|
||||
// UsageString return usage string.
|
||||
func (c *Command) UsageString() string {
|
||||
tmpOutput := c.output
|
||||
bb := new(bytes.Buffer)
|
||||
c.SetOutput(bb)
|
||||
c.Usage()
|
||||
c.output = tmpOutput
|
||||
return bb.String()
|
||||
}
|
||||
|
||||
// FlagErrorFunc returns either the function set by SetFlagErrorFunc for this
|
||||
// command or a parent, or it returns a function which returns the original
|
||||
// error.
|
||||
func (c *Command) FlagErrorFunc() (f func(*Command, error) error) {
|
||||
if c.flagErrorFunc != nil {
|
||||
return c.flagErrorFunc
|
||||
}
|
||||
|
||||
if c.HasParent() {
|
||||
return c.parent.FlagErrorFunc()
|
||||
}
|
||||
return func(c *Command, err error) error {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
var minUsagePadding = 25
|
||||
|
||||
// UsagePadding return padding for the usage.
|
||||
func (c *Command) UsagePadding() int {
|
||||
if c.parent == nil || minUsagePadding > c.parent.commandsMaxUseLen {
|
||||
return minUsagePadding
|
||||
} else {
|
||||
return c.parent.commandsMaxUseLen
|
||||
}
|
||||
return c.parent.commandsMaxUseLen
|
||||
}
|
||||
|
||||
var minCommandPathPadding int = 11
|
||||
var minCommandPathPadding = 11
|
||||
|
||||
//
|
||||
// CommandPathPadding return padding for the command path.
|
||||
func (c *Command) CommandPathPadding() int {
|
||||
if c.parent == nil || minCommandPathPadding > c.parent.commandsMaxCommandPathLen {
|
||||
return minCommandPathPadding
|
||||
} else {
|
||||
return c.parent.commandsMaxCommandPathLen
|
||||
}
|
||||
return c.parent.commandsMaxCommandPathLen
|
||||
}
|
||||
|
||||
var minNamePadding int = 11
|
||||
var minNamePadding = 11
|
||||
|
||||
// NamePadding returns padding for the name.
|
||||
func (c *Command) NamePadding() int {
|
||||
if c.parent == nil || minNamePadding > c.parent.commandsMaxNameLen {
|
||||
return minNamePadding
|
||||
} else {
|
||||
return c.parent.commandsMaxNameLen
|
||||
}
|
||||
return c.parent.commandsMaxNameLen
|
||||
}
|
||||
|
||||
// UsageTemplate returns usage template for the command.
|
||||
func (c *Command) UsageTemplate() string {
|
||||
if c.usageTemplate != "" {
|
||||
return c.usageTemplate
|
||||
|
@ -261,35 +335,34 @@ func (c *Command) UsageTemplate() string {
|
|||
|
||||
if c.HasParent() {
|
||||
return c.parent.UsageTemplate()
|
||||
} else {
|
||||
return `Usage:{{if .Runnable}}
|
||||
{{.UseLine}}{{if .HasFlags}} [flags]{{end}}{{end}}{{if .HasSubCommands}}
|
||||
}
|
||||
return `Usage:{{if .Runnable}}
|
||||
{{if .HasAvailableFlags}}{{appendIfNotPresent .UseLine "[flags]"}}{{else}}{{.UseLine}}{{end}}{{end}}{{if .HasAvailableSubCommands}}
|
||||
{{ .CommandPath}} [command]{{end}}{{if gt .Aliases 0}}
|
||||
|
||||
Aliases:
|
||||
{{.NameAndAliases}}
|
||||
{{end}}{{if .HasExample}}
|
||||
{{.NameAndAliases}}{{end}}{{if .HasExample}}
|
||||
|
||||
Examples:
|
||||
{{ .Example }}{{end}}{{ if .HasAvailableSubCommands}}
|
||||
{{ .Example }}{{end}}{{if .HasAvailableSubCommands}}
|
||||
|
||||
Available Commands:{{range .Commands}}{{if .IsAvailableCommand}}
|
||||
{{rpad .Name .NamePadding }} {{.Short}}{{end}}{{end}}{{end}}{{ if .HasLocalFlags}}
|
||||
Available Commands:{{range .Commands}}{{if (or .IsAvailableCommand (eq .Name "help"))}}
|
||||
{{rpad .Name .NamePadding }} {{.Short}}{{end}}{{end}}{{end}}{{if .HasAvailableLocalFlags}}
|
||||
|
||||
Flags:
|
||||
{{.LocalFlags.FlagUsages | trimRightSpace}}{{end}}{{ if .HasInheritedFlags}}
|
||||
{{.LocalFlags.FlagUsages | trimRightSpace}}{{end}}{{if .HasAvailableInheritedFlags}}
|
||||
|
||||
Global Flags:
|
||||
{{.InheritedFlags.FlagUsages | trimRightSpace}}{{end}}{{if .HasHelpSubCommands}}
|
||||
|
||||
Additional help topics:{{range .Commands}}{{if .IsHelpCommand}}
|
||||
{{rpad .CommandPath .CommandPathPadding}} {{.Short}}{{end}}{{end}}{{end}}{{ if .HasSubCommands }}
|
||||
Additional help topics:{{range .Commands}}{{if .IsAdditionalHelpTopicCommand}}
|
||||
{{rpad .CommandPath .CommandPathPadding}} {{.Short}}{{end}}{{end}}{{end}}{{if .HasAvailableSubCommands}}
|
||||
|
||||
Use "{{.CommandPath}} [command] --help" for more information about a command.{{end}}
|
||||
`
|
||||
}
|
||||
}
|
||||
|
||||
// HelpTemplate return help template for the command.
|
||||
func (c *Command) HelpTemplate() string {
|
||||
if c.helpTemplate != "" {
|
||||
return c.helpTemplate
|
||||
|
@ -297,34 +370,31 @@ func (c *Command) HelpTemplate() string {
|
|||
|
||||
if c.HasParent() {
|
||||
return c.parent.HelpTemplate()
|
||||
} else {
|
||||
return `{{with or .Long .Short }}{{. | trim}}
|
||||
}
|
||||
return `{{with or .Long .Short }}{{. | trim}}
|
||||
|
||||
{{end}}{{if or .Runnable .HasSubCommands}}{{.UsageString}}{{end}}`
|
||||
}
|
||||
}
|
||||
|
||||
// Really only used when casting a command to a commander
|
||||
// Really only used when casting a command to a commander.
|
||||
func (c *Command) resetChildrensParents() {
|
||||
for _, x := range c.commands {
|
||||
x.parent = c
|
||||
}
|
||||
}
|
||||
|
||||
// Test if the named flag is a boolean flag.
|
||||
func isBooleanFlag(name string, f *flag.FlagSet) bool {
|
||||
func hasNoOptDefVal(name string, f *flag.FlagSet) bool {
|
||||
flag := f.Lookup(name)
|
||||
if flag == nil {
|
||||
return false
|
||||
}
|
||||
return flag.Value.Type() == "bool"
|
||||
return len(flag.NoOptDefVal) > 0
|
||||
}
|
||||
|
||||
// Test if the named flag is a boolean flag.
|
||||
func isBooleanShortFlag(name string, f *flag.FlagSet) bool {
|
||||
func shortHasNoOptDefVal(name string, fs *flag.FlagSet) bool {
|
||||
result := false
|
||||
f.VisitAll(func(f *flag.Flag) {
|
||||
if f.Shorthand == name && f.Value.Type() == "bool" {
|
||||
fs.VisitAll(func(flag *flag.Flag) {
|
||||
if flag.Shorthand == name && len(flag.NoOptDefVal) > 0 {
|
||||
result = true
|
||||
}
|
||||
})
|
||||
|
@ -350,13 +420,13 @@ func stripFlags(args []string, c *Command) []string {
|
|||
inQuote = true
|
||||
case strings.HasPrefix(y, "--") && !strings.Contains(y, "="):
|
||||
// TODO: this isn't quite right, we should really check ahead for 'true' or 'false'
|
||||
inFlag = !isBooleanFlag(y[2:], c.Flags())
|
||||
case strings.HasPrefix(y, "-") && !strings.Contains(y, "=") && len(y) == 2 && !isBooleanShortFlag(y[1:], c.Flags()):
|
||||
inFlag = !hasNoOptDefVal(y[2:], c.Flags())
|
||||
case strings.HasPrefix(y, "-") && !strings.Contains(y, "=") && len(y) == 2 && !shortHasNoOptDefVal(y[1:], c.Flags()):
|
||||
inFlag = true
|
||||
case inFlag:
|
||||
inFlag = false
|
||||
case y == "":
|
||||
// strip empty commands, as the go tests expect this to be ok....
|
||||
// strip empty commands, as the go tests expect this to be ok....
|
||||
case !strings.HasPrefix(y, "-"):
|
||||
commands = append(commands, y)
|
||||
inFlag = false
|
||||
|
@ -385,7 +455,7 @@ func argsMinusFirstX(args []string, x string) []string {
|
|||
return args
|
||||
}
|
||||
|
||||
// find the target command given the args and command tree
|
||||
// Find the target command given the args and command tree
|
||||
// Meant to be run on the highest node. Only searches down.
|
||||
func (c *Command) Find(args []string) (*Command, []string, error) {
|
||||
if c == nil {
|
||||
|
@ -453,6 +523,7 @@ func (c *Command) Find(args []string) (*Command, []string, error) {
|
|||
return commandFound, a, nil
|
||||
}
|
||||
|
||||
// SuggestionsFor provides suggestions for the typedName.
|
||||
func (c *Command) SuggestionsFor(typedName string) []string {
|
||||
suggestions := []string{}
|
||||
for _, cmd := range c.commands {
|
||||
|
@ -473,6 +544,7 @@ func (c *Command) SuggestionsFor(typedName string) []string {
|
|||
return suggestions
|
||||
}
|
||||
|
||||
// VisitParents visits all parents of the command and invokes fn on each parent.
|
||||
func (c *Command) VisitParents(fn func(*Command)) {
|
||||
var traverse func(*Command) *Command
|
||||
|
||||
|
@ -488,6 +560,7 @@ func (c *Command) VisitParents(fn func(*Command)) {
|
|||
traverse(c)
|
||||
}
|
||||
|
||||
// Root finds root command.
|
||||
func (c *Command) Root() *Command {
|
||||
var findRoot func(*Command) *Command
|
||||
|
||||
|
@ -524,7 +597,7 @@ func (c *Command) execute(a []string) (err error) {
|
|||
|
||||
err = c.ParseFlags(a)
|
||||
if err != nil {
|
||||
return err
|
||||
return c.FlagErrorFunc()(c, err)
|
||||
}
|
||||
// If help is called, regardless of other flags, return we want help
|
||||
// Also say we need help if the command isn't runnable.
|
||||
|
@ -535,12 +608,17 @@ func (c *Command) execute(a []string) (err error) {
|
|||
c.Println("\"help\" flag declared as non-bool. Please correct your code")
|
||||
return err
|
||||
}
|
||||
|
||||
if helpVal || !c.Runnable() {
|
||||
return flag.ErrHelp
|
||||
}
|
||||
|
||||
c.preRun()
|
||||
|
||||
argWoFlags := c.Flags().Args()
|
||||
if c.DisableFlagParsing {
|
||||
argWoFlags = a
|
||||
}
|
||||
|
||||
for p := c; p != nil; p = p.Parent() {
|
||||
if p.PersistentPreRunE != nil {
|
||||
|
@ -603,12 +681,11 @@ func (c *Command) errorMsgFromParse() string {
|
|||
|
||||
if len(x) > 0 {
|
||||
return x[0]
|
||||
} else {
|
||||
return ""
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// Call execute to use the args (os.Args[1:] by default)
|
||||
// Execute Call execute to use the args (os.Args[1:] by default)
|
||||
// and run through the command tree finding appropriate matches
|
||||
// for commands and then corresponding flags.
|
||||
func (c *Command) Execute() error {
|
||||
|
@ -616,8 +693,8 @@ func (c *Command) Execute() error {
|
|||
return err
|
||||
}
|
||||
|
||||
// ExecuteC executes the command.
|
||||
func (c *Command) ExecuteC() (cmd *Command, err error) {
|
||||
|
||||
// Regardless of what command execute is called on, run on Root only
|
||||
if c.HasParent() {
|
||||
return c.Root().ExecuteC()
|
||||
|
@ -679,6 +756,7 @@ func (c *Command) ExecuteC() (cmd *Command, err error) {
|
|||
}
|
||||
|
||||
func (c *Command) initHelpFlag() {
|
||||
c.mergePersistentFlags()
|
||||
if c.Flags().Lookup("help") == nil {
|
||||
c.Flags().BoolP("help", "h", false, "help for "+c.Name())
|
||||
}
|
||||
|
@ -701,26 +779,38 @@ func (c *Command) initHelpCmd() {
|
|||
Run: func(c *Command, args []string) {
|
||||
cmd, _, e := c.Root().Find(args)
|
||||
if cmd == nil || e != nil {
|
||||
c.Printf("Unknown help topic %#q.", args)
|
||||
c.Printf("Unknown help topic %#q\n", args)
|
||||
c.Root().Usage()
|
||||
} else {
|
||||
helpFunc := cmd.HelpFunc()
|
||||
helpFunc(cmd, args)
|
||||
cmd.Help()
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
c.RemoveCommand(c.helpCommand)
|
||||
c.AddCommand(c.helpCommand)
|
||||
}
|
||||
|
||||
// Used for testing
|
||||
// ResetCommands used for testing.
|
||||
func (c *Command) ResetCommands() {
|
||||
c.commands = nil
|
||||
c.helpCommand = nil
|
||||
}
|
||||
|
||||
//Commands returns a slice of child commands.
|
||||
// Sorts commands by their names.
|
||||
type commandSorterByName []*Command
|
||||
|
||||
func (c commandSorterByName) Len() int { return len(c) }
|
||||
func (c commandSorterByName) Swap(i, j int) { c[i], c[j] = c[j], c[i] }
|
||||
func (c commandSorterByName) Less(i, j int) bool { return c[i].Name() < c[j].Name() }
|
||||
|
||||
// Commands returns a sorted slice of child commands.
|
||||
func (c *Command) Commands() []*Command {
|
||||
// do not sort commands if it already sorted or sorting was disabled
|
||||
if EnableCommandSorting && !c.commandsAreSorted {
|
||||
sort.Sort(commandSorterByName(c.commands))
|
||||
c.commandsAreSorted = true
|
||||
}
|
||||
return c.commands
|
||||
}
|
||||
|
||||
|
@ -749,10 +839,11 @@ func (c *Command) AddCommand(cmds ...*Command) {
|
|||
x.SetGlobalNormalizationFunc(c.globNormFunc)
|
||||
}
|
||||
c.commands = append(c.commands, x)
|
||||
c.commandsAreSorted = false
|
||||
}
|
||||
}
|
||||
|
||||
// AddCommand removes one or more commands from a parent command.
|
||||
// RemoveCommand removes one or more commands from a parent command.
|
||||
func (c *Command) RemoveCommand(cmds ...*Command) {
|
||||
commands := []*Command{}
|
||||
main:
|
||||
|
@ -786,50 +877,23 @@ main:
|
|||
}
|
||||
}
|
||||
|
||||
// Convenience method to Print to the defined output
|
||||
// Print is a convenience method to Print to the defined output, fallback to Stderr if not set.
|
||||
func (c *Command) Print(i ...interface{}) {
|
||||
fmt.Fprint(c.Out(), i...)
|
||||
fmt.Fprint(c.OutOrStderr(), i...)
|
||||
}
|
||||
|
||||
// Convenience method to Println to the defined output
|
||||
// Println is a convenience method to Println to the defined output, fallback to Stderr if not set.
|
||||
func (c *Command) Println(i ...interface{}) {
|
||||
str := fmt.Sprintln(i...)
|
||||
c.Print(str)
|
||||
}
|
||||
|
||||
// Convenience method to Printf to the defined output
|
||||
// Printf is a convenience method to Printf to the defined output, fallback to Stderr if not set.
|
||||
func (c *Command) Printf(format string, i ...interface{}) {
|
||||
str := fmt.Sprintf(format, i...)
|
||||
c.Print(str)
|
||||
}
|
||||
|
||||
// Output the usage for the command
|
||||
// Used when a user provides invalid input
|
||||
// Can be defined by user by overriding UsageFunc
|
||||
func (c *Command) Usage() error {
|
||||
c.mergePersistentFlags()
|
||||
err := c.UsageFunc()(c)
|
||||
return err
|
||||
}
|
||||
|
||||
// Output the help for the command
|
||||
// Used when a user calls help [command]
|
||||
// by the default HelpFunc in the commander
|
||||
func (c *Command) Help() error {
|
||||
c.mergePersistentFlags()
|
||||
err := tmpl(c.getOutOrStdout(), c.HelpTemplate(), c)
|
||||
return err
|
||||
}
|
||||
|
||||
func (c *Command) UsageString() string {
|
||||
tmpOutput := c.output
|
||||
bb := new(bytes.Buffer)
|
||||
c.SetOutput(bb)
|
||||
c.Usage()
|
||||
c.output = tmpOutput
|
||||
return bb.String()
|
||||
}
|
||||
|
||||
// CommandPath returns the full path to this command.
|
||||
func (c *Command) CommandPath() string {
|
||||
str := c.Name()
|
||||
|
@ -841,7 +905,7 @@ func (c *Command) CommandPath() string {
|
|||
return str
|
||||
}
|
||||
|
||||
//The full usage for a given command (including parents)
|
||||
// UseLine puts out the full usage for a given command (including parents).
|
||||
func (c *Command) UseLine() string {
|
||||
str := ""
|
||||
if c.HasParent() {
|
||||
|
@ -850,8 +914,8 @@ func (c *Command) UseLine() string {
|
|||
return str + c.Use
|
||||
}
|
||||
|
||||
// For use in determining which flags have been assigned to which commands
|
||||
// and which persist
|
||||
// DebugFlags used to determine which flags have been assigned to which commands
|
||||
// and which persist.
|
||||
func (c *Command) DebugFlags() {
|
||||
c.Println("DebugFlags called on", c.Name())
|
||||
var debugflags func(*Command)
|
||||
|
@ -905,10 +969,11 @@ func (c *Command) Name() string {
|
|||
if i >= 0 {
|
||||
name = name[:i]
|
||||
}
|
||||
return name
|
||||
c.name = name
|
||||
return c.name
|
||||
}
|
||||
|
||||
// Determine if a given string is an alias of the command.
|
||||
// HasAlias determines if a given string is an alias of the command.
|
||||
func (c *Command) HasAlias(s string) bool {
|
||||
for _, a := range c.Aliases {
|
||||
if a == s {
|
||||
|
@ -918,26 +983,28 @@ func (c *Command) HasAlias(s string) bool {
|
|||
return false
|
||||
}
|
||||
|
||||
// NameAndAliases returns string containing name and all aliases
|
||||
func (c *Command) NameAndAliases() string {
|
||||
return strings.Join(append([]string{c.Name()}, c.Aliases...), ", ")
|
||||
}
|
||||
|
||||
// HasExample determines if the command has example.
|
||||
func (c *Command) HasExample() bool {
|
||||
return len(c.Example) > 0
|
||||
}
|
||||
|
||||
// Determine if the command is itself runnable
|
||||
// Runnable determines if the command is itself runnable.
|
||||
func (c *Command) Runnable() bool {
|
||||
return c.Run != nil || c.RunE != nil
|
||||
}
|
||||
|
||||
// Determine if the command has children commands
|
||||
// HasSubCommands determines if the command has children commands.
|
||||
func (c *Command) HasSubCommands() bool {
|
||||
return len(c.commands) > 0
|
||||
}
|
||||
|
||||
// IsAvailableCommand determines if a command is available as a non-help command
|
||||
// (this includes all non deprecated/hidden commands)
|
||||
// (this includes all non deprecated/hidden commands).
|
||||
func (c *Command) IsAvailableCommand() bool {
|
||||
if len(c.Deprecated) != 0 || c.Hidden {
|
||||
return false
|
||||
|
@ -954,11 +1021,12 @@ func (c *Command) IsAvailableCommand() bool {
|
|||
return false
|
||||
}
|
||||
|
||||
// IsHelpCommand determines if a command is a 'help' command; a help command is
|
||||
// determined by the fact that it is NOT runnable/hidden/deprecated, and has no
|
||||
// sub commands that are runnable/hidden/deprecated
|
||||
func (c *Command) IsHelpCommand() bool {
|
||||
|
||||
// IsAdditionalHelpTopicCommand determines if a command is an additional
|
||||
// help topic command; additional help topic command is determined by the
|
||||
// fact that it is NOT runnable/hidden/deprecated, and has no sub commands that
|
||||
// are runnable/hidden/deprecated.
|
||||
// Concrete example: https://github.com/spf13/cobra/issues/393#issuecomment-282741924.
|
||||
func (c *Command) IsAdditionalHelpTopicCommand() bool {
|
||||
// if a command is runnable, deprecated, or hidden it is not a 'help' command
|
||||
if c.Runnable() || len(c.Deprecated) != 0 || c.Hidden {
|
||||
return false
|
||||
|
@ -966,7 +1034,7 @@ func (c *Command) IsHelpCommand() bool {
|
|||
|
||||
// if any non-help sub commands are found, the command is not a 'help' command
|
||||
for _, sub := range c.commands {
|
||||
if !sub.IsHelpCommand() {
|
||||
if !sub.IsAdditionalHelpTopicCommand() {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
@ -975,14 +1043,13 @@ func (c *Command) IsHelpCommand() bool {
|
|||
return true
|
||||
}
|
||||
|
||||
// HasHelpSubCommands determines if a command has any avilable 'help' sub commands
|
||||
// HasHelpSubCommands determines if a command has any available 'help' sub commands
|
||||
// that need to be shown in the usage/help default template under 'additional help
|
||||
// topics'
|
||||
// topics'.
|
||||
func (c *Command) HasHelpSubCommands() bool {
|
||||
|
||||
// return true on the first found available 'help' sub command
|
||||
for _, sub := range c.commands {
|
||||
if sub.IsHelpCommand() {
|
||||
if sub.IsAdditionalHelpTopicCommand() {
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
@ -992,9 +1059,8 @@ func (c *Command) HasHelpSubCommands() bool {
|
|||
}
|
||||
|
||||
// HasAvailableSubCommands determines if a command has available sub commands that
|
||||
// need to be shown in the usage/help default template under 'available commands'
|
||||
// need to be shown in the usage/help default template under 'available commands'.
|
||||
func (c *Command) HasAvailableSubCommands() bool {
|
||||
|
||||
// return true on the first found available (non deprecated/help/hidden)
|
||||
// sub command
|
||||
for _, sub := range c.commands {
|
||||
|
@ -1008,17 +1074,18 @@ func (c *Command) HasAvailableSubCommands() bool {
|
|||
return false
|
||||
}
|
||||
|
||||
// Determine if the command is a child command
|
||||
// HasParent determines if the command is a child command.
|
||||
func (c *Command) HasParent() bool {
|
||||
return c.parent != nil
|
||||
}
|
||||
|
||||
// GlobalNormalizationFunc returns the global normalization function or nil if doesn't exists
|
||||
// GlobalNormalizationFunc returns the global normalization function or nil if doesn't exists.
|
||||
func (c *Command) GlobalNormalizationFunc() func(f *flag.FlagSet, name string) flag.NormalizedName {
|
||||
return c.globNormFunc
|
||||
}
|
||||
|
||||
// Get the complete FlagSet that applies to this command (local and persistent declared here and by all parents)
|
||||
// Flags returns the complete FlagSet that applies
|
||||
// to this command (local and persistent declared here and by all parents).
|
||||
func (c *Command) Flags() *flag.FlagSet {
|
||||
if c.flags == nil {
|
||||
c.flags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)
|
||||
|
@ -1030,7 +1097,20 @@ func (c *Command) Flags() *flag.FlagSet {
|
|||
return c.flags
|
||||
}
|
||||
|
||||
// Get the local FlagSet specifically set in the current command
|
||||
// LocalNonPersistentFlags are flags specific to this command which will NOT persist to subcommands.
|
||||
func (c *Command) LocalNonPersistentFlags() *flag.FlagSet {
|
||||
persistentFlags := c.PersistentFlags()
|
||||
|
||||
out := flag.NewFlagSet(c.Name(), flag.ContinueOnError)
|
||||
c.LocalFlags().VisitAll(func(f *flag.Flag) {
|
||||
if persistentFlags.Lookup(f.Name) == nil {
|
||||
out.AddFlag(f)
|
||||
}
|
||||
})
|
||||
return out
|
||||
}
|
||||
|
||||
// LocalFlags returns the local FlagSet specifically set in the current command.
|
||||
func (c *Command) LocalFlags() *flag.FlagSet {
|
||||
c.mergePersistentFlags()
|
||||
|
||||
|
@ -1048,7 +1128,7 @@ func (c *Command) LocalFlags() *flag.FlagSet {
|
|||
return local
|
||||
}
|
||||
|
||||
// All Flags which were inherited from parents commands
|
||||
// InheritedFlags returns all flags which were inherited from parents commands.
|
||||
func (c *Command) InheritedFlags() *flag.FlagSet {
|
||||
c.mergePersistentFlags()
|
||||
|
||||
|
@ -1077,12 +1157,12 @@ func (c *Command) InheritedFlags() *flag.FlagSet {
|
|||
return inherited
|
||||
}
|
||||
|
||||
// All Flags which were not inherited from parent commands
|
||||
// NonInheritedFlags returns all flags which were not inherited from parent commands.
|
||||
func (c *Command) NonInheritedFlags() *flag.FlagSet {
|
||||
return c.LocalFlags()
|
||||
}
|
||||
|
||||
// Get the Persistent FlagSet specifically set in the current command
|
||||
// PersistentFlags returns the persistent FlagSet specifically set in the current command.
|
||||
func (c *Command) PersistentFlags() *flag.FlagSet {
|
||||
if c.pflags == nil {
|
||||
c.pflags = flag.NewFlagSet(c.Name(), flag.ContinueOnError)
|
||||
|
@ -1094,7 +1174,7 @@ func (c *Command) PersistentFlags() *flag.FlagSet {
|
|||
return c.pflags
|
||||
}
|
||||
|
||||
// For use in testing
|
||||
// ResetFlags is used in testing.
|
||||
func (c *Command) ResetFlags() {
|
||||
c.flagErrorBuf = new(bytes.Buffer)
|
||||
c.flagErrorBuf.Reset()
|
||||
|
@ -1104,26 +1184,50 @@ func (c *Command) ResetFlags() {
|
|||
c.pflags.SetOutput(c.flagErrorBuf)
|
||||
}
|
||||
|
||||
// Does the command contain any flags (local plus persistent from the entire structure)
|
||||
// HasFlags checks if the command contains any flags (local plus persistent from the entire structure).
|
||||
func (c *Command) HasFlags() bool {
|
||||
return c.Flags().HasFlags()
|
||||
}
|
||||
|
||||
// Does the command contain persistent flags
|
||||
// HasPersistentFlags checks if the command contains persistent flags.
|
||||
func (c *Command) HasPersistentFlags() bool {
|
||||
return c.PersistentFlags().HasFlags()
|
||||
}
|
||||
|
||||
// Does the command has flags specifically declared locally
|
||||
// HasLocalFlags checks if the command has flags specifically declared locally.
|
||||
func (c *Command) HasLocalFlags() bool {
|
||||
return c.LocalFlags().HasFlags()
|
||||
}
|
||||
|
||||
// HasInheritedFlags checks if the command has flags inherited from its parent command.
|
||||
func (c *Command) HasInheritedFlags() bool {
|
||||
return c.InheritedFlags().HasFlags()
|
||||
}
|
||||
|
||||
// Climbs up the command tree looking for matching flag
|
||||
// HasAvailableFlags checks if the command contains any flags (local plus persistent from the entire
|
||||
// structure) which are not hidden or deprecated.
|
||||
func (c *Command) HasAvailableFlags() bool {
|
||||
return c.Flags().HasAvailableFlags()
|
||||
}
|
||||
|
||||
// HasAvailablePersistentFlags checks if the command contains persistent flags which are not hidden or deprecated.
|
||||
func (c *Command) HasAvailablePersistentFlags() bool {
|
||||
return c.PersistentFlags().HasAvailableFlags()
|
||||
}
|
||||
|
||||
// HasAvailableLocalFlags checks if the command has flags specifically declared locally which are not hidden
|
||||
// or deprecated.
|
||||
func (c *Command) HasAvailableLocalFlags() bool {
|
||||
return c.LocalFlags().HasAvailableFlags()
|
||||
}
|
||||
|
||||
// HasAvailableInheritedFlags checks if the command has flags inherited from its parent command which are
|
||||
// not hidden or deprecated.
|
||||
func (c *Command) HasAvailableInheritedFlags() bool {
|
||||
return c.InheritedFlags().HasAvailableFlags()
|
||||
}
|
||||
|
||||
// Flag climbs up the command tree looking for matching flag.
|
||||
func (c *Command) Flag(name string) (flag *flag.Flag) {
|
||||
flag = c.Flags().Lookup(name)
|
||||
|
||||
|
@ -1134,7 +1238,7 @@ func (c *Command) Flag(name string) (flag *flag.Flag) {
|
|||
return
|
||||
}
|
||||
|
||||
// recursively find matching persistent flag
|
||||
// Recursively find matching persistent flag.
|
||||
func (c *Command) persistentFlag(name string) (flag *flag.Flag) {
|
||||
if c.HasPersistentFlags() {
|
||||
flag = c.PersistentFlags().Lookup(name)
|
||||
|
@ -1146,13 +1250,17 @@ func (c *Command) persistentFlag(name string) (flag *flag.Flag) {
|
|||
return
|
||||
}
|
||||
|
||||
// Parses persistent flag tree & local flags
|
||||
// ParseFlags parses persistent flag tree and local flags.
|
||||
func (c *Command) ParseFlags(args []string) (err error) {
|
||||
if c.DisableFlagParsing {
|
||||
return nil
|
||||
}
|
||||
c.mergePersistentFlags()
|
||||
err = c.Flags().Parse(args)
|
||||
return
|
||||
}
|
||||
|
||||
// Parent returns a commands parent command.
|
||||
func (c *Command) Parent() *Command {
|
||||
return c.parent
|
||||
}
|
||||
|
|
2
vendor/github.com/spf13/cobra/command_notwin.go
generated
vendored
2
vendor/github.com/spf13/cobra/command_notwin.go
generated
vendored
|
@ -2,4 +2,4 @@
|
|||
|
||||
package cobra
|
||||
|
||||
var preExecHookFn func(*Command) = nil
|
||||
var preExecHookFn func(*Command)
|
||||
|
|
114
vendor/github.com/spf13/cobra/command_test.go
generated
vendored
114
vendor/github.com/spf13/cobra/command_test.go
generated
vendored
|
@ -1,114 +0,0 @@
|
|||
package cobra
|
||||
|
||||
import (
|
||||
"reflect"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// test to ensure hidden commands run as intended
|
||||
func TestHiddenCommandExecutes(t *testing.T) {
|
||||
|
||||
// ensure that outs does not already equal what the command will be setting it
|
||||
// to, if it did this test would not actually be testing anything...
|
||||
if outs == "hidden" {
|
||||
t.Errorf("outs should NOT EQUAL hidden")
|
||||
}
|
||||
|
||||
cmdHidden.Execute()
|
||||
|
||||
// upon running the command, the value of outs should now be 'hidden'
|
||||
if outs != "hidden" {
|
||||
t.Errorf("Hidden command failed to run!")
|
||||
}
|
||||
}
|
||||
|
||||
// test to ensure hidden commands do not show up in usage/help text
|
||||
func TestHiddenCommandIsHidden(t *testing.T) {
|
||||
if cmdHidden.IsAvailableCommand() {
|
||||
t.Errorf("Hidden command found!")
|
||||
}
|
||||
}
|
||||
|
||||
func TestStripFlags(t *testing.T) {
|
||||
tests := []struct {
|
||||
input []string
|
||||
output []string
|
||||
}{
|
||||
{
|
||||
[]string{"foo", "bar"},
|
||||
[]string{"foo", "bar"},
|
||||
},
|
||||
{
|
||||
[]string{"foo", "--bar", "-b"},
|
||||
[]string{"foo"},
|
||||
},
|
||||
{
|
||||
[]string{"-b", "foo", "--bar", "bar"},
|
||||
[]string{},
|
||||
},
|
||||
{
|
||||
[]string{"-i10", "echo"},
|
||||
[]string{"echo"},
|
||||
},
|
||||
{
|
||||
[]string{"-i=10", "echo"},
|
||||
[]string{"echo"},
|
||||
},
|
||||
{
|
||||
[]string{"--int=100", "echo"},
|
||||
[]string{"echo"},
|
||||
},
|
||||
{
|
||||
[]string{"-ib", "echo", "-bfoo", "baz"},
|
||||
[]string{"echo", "baz"},
|
||||
},
|
||||
{
|
||||
[]string{"-i=baz", "bar", "-i", "foo", "blah"},
|
||||
[]string{"bar", "blah"},
|
||||
},
|
||||
{
|
||||
[]string{"--int=baz", "-bbar", "-i", "foo", "blah"},
|
||||
[]string{"blah"},
|
||||
},
|
||||
{
|
||||
[]string{"--cat", "bar", "-i", "foo", "blah"},
|
||||
[]string{"bar", "blah"},
|
||||
},
|
||||
{
|
||||
[]string{"-c", "bar", "-i", "foo", "blah"},
|
||||
[]string{"bar", "blah"},
|
||||
},
|
||||
{
|
||||
[]string{"--persist", "bar"},
|
||||
[]string{"bar"},
|
||||
},
|
||||
{
|
||||
[]string{"-p", "bar"},
|
||||
[]string{"bar"},
|
||||
},
|
||||
}
|
||||
|
||||
cmdPrint := &Command{
|
||||
Use: "print [string to print]",
|
||||
Short: "Print anything to the screen",
|
||||
Long: `an utterly useless command for testing.`,
|
||||
Run: func(cmd *Command, args []string) {
|
||||
tp = args
|
||||
},
|
||||
}
|
||||
|
||||
var flagi int
|
||||
var flagstr string
|
||||
var flagbool bool
|
||||
cmdPrint.PersistentFlags().BoolVarP(&flagbool, "persist", "p", false, "help for persistent one")
|
||||
cmdPrint.Flags().IntVarP(&flagi, "int", "i", 345, "help message for flag int")
|
||||
cmdPrint.Flags().StringVarP(&flagstr, "bar", "b", "bar", "help message for flag string")
|
||||
cmdPrint.Flags().BoolVarP(&flagbool, "cat", "c", false, "help message for flag bool")
|
||||
|
||||
for _, test := range tests {
|
||||
output := stripFlags(test.input, cmdPrint)
|
||||
if !reflect.DeepEqual(test.output, output) {
|
||||
t.Errorf("expected: %v, got: %v", test.output, output)
|
||||
}
|
||||
}
|
||||
}
|
145
vendor/github.com/spf13/cobra/doc/cmd_test.go
generated
vendored
145
vendor/github.com/spf13/cobra/doc/cmd_test.go
generated
vendored
|
@ -1,145 +0,0 @@
|
|||
package doc
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"runtime"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
var flagb1, flagb2, flagb3, flagbr, flagbp bool
|
||||
var flags1, flags2a, flags2b, flags3 string
|
||||
var flagi1, flagi2, flagi3, flagir int
|
||||
|
||||
const strtwoParentHelp = "help message for parent flag strtwo"
|
||||
const strtwoChildHelp = "help message for child flag strtwo"
|
||||
|
||||
var cmdEcho = &cobra.Command{
|
||||
Use: "echo [string to echo]",
|
||||
Aliases: []string{"say"},
|
||||
Short: "Echo anything to the screen",
|
||||
Long: `an utterly useless command for testing.`,
|
||||
Example: "Just run cobra-test echo",
|
||||
}
|
||||
|
||||
var cmdEchoSub = &cobra.Command{
|
||||
Use: "echosub [string to print]",
|
||||
Short: "second sub command for echo",
|
||||
Long: `an absolutely utterly useless command for testing gendocs!.`,
|
||||
Run: func(cmd *cobra.Command, args []string) {},
|
||||
}
|
||||
|
||||
var cmdDeprecated = &cobra.Command{
|
||||
Use: "deprecated [can't do anything here]",
|
||||
Short: "A command which is deprecated",
|
||||
Long: `an absolutely utterly useless command for testing deprecation!.`,
|
||||
Deprecated: "Please use echo instead",
|
||||
}
|
||||
|
||||
var cmdTimes = &cobra.Command{
|
||||
Use: "times [# times] [string to echo]",
|
||||
SuggestFor: []string{"counts"},
|
||||
Short: "Echo anything to the screen more times",
|
||||
Long: `a slightly useless command for testing.`,
|
||||
PersistentPreRun: func(cmd *cobra.Command, args []string) {},
|
||||
Run: func(cmd *cobra.Command, args []string) {},
|
||||
}
|
||||
|
||||
var cmdPrint = &cobra.Command{
|
||||
Use: "print [string to print]",
|
||||
Short: "Print anything to the screen",
|
||||
Long: `an absolutely utterly useless command for testing.`,
|
||||
}
|
||||
|
||||
var cmdRootNoRun = &cobra.Command{
|
||||
Use: "cobra-test",
|
||||
Short: "The root can run its own function",
|
||||
Long: "The root description for help",
|
||||
}
|
||||
|
||||
var cmdRootSameName = &cobra.Command{
|
||||
Use: "print",
|
||||
Short: "Root with the same name as a subcommand",
|
||||
Long: "The root description for help",
|
||||
}
|
||||
|
||||
var cmdRootWithRun = &cobra.Command{
|
||||
Use: "cobra-test",
|
||||
Short: "The root can run its own function",
|
||||
Long: "The root description for help",
|
||||
}
|
||||
|
||||
var cmdSubNoRun = &cobra.Command{
|
||||
Use: "subnorun",
|
||||
Short: "A subcommand without a Run function",
|
||||
Long: "A long output about a subcommand without a Run function",
|
||||
}
|
||||
|
||||
var cmdVersion1 = &cobra.Command{
|
||||
Use: "version",
|
||||
Short: "Print the version number",
|
||||
Long: `First version of the version command`,
|
||||
}
|
||||
|
||||
var cmdVersion2 = &cobra.Command{
|
||||
Use: "version",
|
||||
Short: "Print the version number",
|
||||
Long: `Second version of the version command`,
|
||||
}
|
||||
|
||||
func flagInit() {
|
||||
cmdEcho.ResetFlags()
|
||||
cmdPrint.ResetFlags()
|
||||
cmdTimes.ResetFlags()
|
||||
cmdRootNoRun.ResetFlags()
|
||||
cmdRootSameName.ResetFlags()
|
||||
cmdRootWithRun.ResetFlags()
|
||||
cmdSubNoRun.ResetFlags()
|
||||
cmdRootNoRun.PersistentFlags().StringVarP(&flags2a, "strtwo", "t", "two", strtwoParentHelp)
|
||||
cmdEcho.Flags().IntVarP(&flagi1, "intone", "i", 123, "help message for flag intone")
|
||||
cmdTimes.Flags().IntVarP(&flagi2, "inttwo", "j", 234, "help message for flag inttwo")
|
||||
cmdPrint.Flags().IntVarP(&flagi3, "intthree", "i", 345, "help message for flag intthree")
|
||||
cmdEcho.PersistentFlags().StringVarP(&flags1, "strone", "s", "one", "help message for flag strone")
|
||||
cmdEcho.PersistentFlags().BoolVarP(&flagbp, "persistentbool", "p", false, "help message for flag persistentbool")
|
||||
cmdTimes.PersistentFlags().StringVarP(&flags2b, "strtwo", "t", "2", strtwoChildHelp)
|
||||
cmdPrint.PersistentFlags().StringVarP(&flags3, "strthree", "s", "three", "help message for flag strthree")
|
||||
cmdEcho.Flags().BoolVarP(&flagb1, "boolone", "b", true, "help message for flag boolone")
|
||||
cmdTimes.Flags().BoolVarP(&flagb2, "booltwo", "c", false, "help message for flag booltwo")
|
||||
cmdPrint.Flags().BoolVarP(&flagb3, "boolthree", "b", true, "help message for flag boolthree")
|
||||
cmdVersion1.ResetFlags()
|
||||
cmdVersion2.ResetFlags()
|
||||
}
|
||||
|
||||
func initializeWithRootCmd() *cobra.Command {
|
||||
cmdRootWithRun.ResetCommands()
|
||||
flagInit()
|
||||
cmdRootWithRun.Flags().BoolVarP(&flagbr, "boolroot", "b", false, "help message for flag boolroot")
|
||||
cmdRootWithRun.Flags().IntVarP(&flagir, "introot", "i", 321, "help message for flag introot")
|
||||
return cmdRootWithRun
|
||||
}
|
||||
|
||||
func checkStringContains(t *testing.T, found, expected string) {
|
||||
if !strings.Contains(found, expected) {
|
||||
logErr(t, found, expected)
|
||||
}
|
||||
}
|
||||
|
||||
func checkStringOmits(t *testing.T, found, expected string) {
|
||||
if strings.Contains(found, expected) {
|
||||
logErr(t, found, expected)
|
||||
}
|
||||
}
|
||||
|
||||
func logErr(t *testing.T, found, expected string) {
|
||||
out := new(bytes.Buffer)
|
||||
|
||||
_, _, line, ok := runtime.Caller(2)
|
||||
if ok {
|
||||
fmt.Fprintf(out, "Line: %d ", line)
|
||||
}
|
||||
fmt.Fprintf(out, "Unexpected response.\nExpecting to contain: \n %q\nGot:\n %q\n", expected, found)
|
||||
t.Errorf(out.String())
|
||||
}
|
218
vendor/github.com/spf13/cobra/doc/man_docs.go
generated
vendored
218
vendor/github.com/spf13/cobra/doc/man_docs.go
generated
vendored
|
@ -1,218 +0,0 @@
|
|||
// Copyright 2015 Red Hat Inc. All rights reserved.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package doc
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
mangen "github.com/cpuguy83/go-md2man/md2man"
|
||||
"github.com/spf13/cobra"
|
||||
"github.com/spf13/pflag"
|
||||
)
|
||||
|
||||
// GenManTree will generate a man page for this command and all decendants
|
||||
// in the directory given. The header may be nil. This function may not work
|
||||
// correctly if your command names have - in them. If you have `cmd` with two
|
||||
// subcmds, `sub` and `sub-third`. And `sub` has a subcommand called `third`
|
||||
// it is undefined which help output will be in the file `cmd-sub-third.1`.
|
||||
func GenManTree(cmd *cobra.Command, header *GenManHeader, dir string) error {
|
||||
if header == nil {
|
||||
header = &GenManHeader{}
|
||||
}
|
||||
for _, c := range cmd.Commands() {
|
||||
if !c.IsAvailableCommand() || c.IsHelpCommand() {
|
||||
continue
|
||||
}
|
||||
if err := GenManTree(c, header, dir); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
needToResetTitle := header.Title == ""
|
||||
|
||||
basename := strings.Replace(cmd.CommandPath(), " ", "_", -1) + ".1"
|
||||
filename := filepath.Join(dir, basename)
|
||||
f, err := os.Create(filename)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer f.Close()
|
||||
|
||||
if err := GenMan(cmd, header, f); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if needToResetTitle {
|
||||
header.Title = ""
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// GenManHeader is a lot like the .TH header at the start of man pages. These
|
||||
// include the title, section, date, source, and manual. We will use the
|
||||
// current time if Date if unset and will use "Auto generated by spf13/cobra"
|
||||
// if the Source is unset.
|
||||
type GenManHeader struct {
|
||||
Title string
|
||||
Section string
|
||||
Date *time.Time
|
||||
date string
|
||||
Source string
|
||||
Manual string
|
||||
}
|
||||
|
||||
// GenMan will generate a man page for the given command and write it to
|
||||
// w. The header argument may be nil, however obviously w may not.
|
||||
func GenMan(cmd *cobra.Command, header *GenManHeader, w io.Writer) error {
|
||||
if header == nil {
|
||||
header = &GenManHeader{}
|
||||
}
|
||||
b := genMan(cmd, header)
|
||||
final := mangen.Render(b)
|
||||
_, err := w.Write(final)
|
||||
return err
|
||||
}
|
||||
|
||||
func fillHeader(header *GenManHeader, name string) {
|
||||
if header.Title == "" {
|
||||
header.Title = strings.ToUpper(strings.Replace(name, " ", "\\-", -1))
|
||||
}
|
||||
if header.Section == "" {
|
||||
header.Section = "1"
|
||||
}
|
||||
if header.Date == nil {
|
||||
now := time.Now()
|
||||
header.Date = &now
|
||||
}
|
||||
header.date = (*header.Date).Format("Jan 2006")
|
||||
if header.Source == "" {
|
||||
header.Source = "Auto generated by spf13/cobra"
|
||||
}
|
||||
}
|
||||
|
||||
func manPreamble(out io.Writer, header *GenManHeader, name, short, long string) {
|
||||
dashName := strings.Replace(name, " ", "-", -1)
|
||||
fmt.Fprintf(out, `%% %s(%s)%s
|
||||
%% %s
|
||||
%% %s
|
||||
# NAME
|
||||
`, header.Title, header.Section, header.date, header.Source, header.Manual)
|
||||
fmt.Fprintf(out, "%s \\- %s\n\n", dashName, short)
|
||||
fmt.Fprintf(out, "# SYNOPSIS\n")
|
||||
fmt.Fprintf(out, "**%s** [OPTIONS]\n\n", name)
|
||||
fmt.Fprintf(out, "# DESCRIPTION\n")
|
||||
fmt.Fprintf(out, "%s\n\n", long)
|
||||
}
|
||||
|
||||
func manPrintFlags(out io.Writer, flags *pflag.FlagSet) {
|
||||
flags.VisitAll(func(flag *pflag.Flag) {
|
||||
if len(flag.Deprecated) > 0 || flag.Hidden {
|
||||
return
|
||||
}
|
||||
format := ""
|
||||
if len(flag.Shorthand) > 0 {
|
||||
format = "**-%s**, **--%s**"
|
||||
} else {
|
||||
format = "%s**--%s**"
|
||||
}
|
||||
if len(flag.NoOptDefVal) > 0 {
|
||||
format = format + "["
|
||||
}
|
||||
if flag.Value.Type() == "string" {
|
||||
// put quotes on the value
|
||||
format = format + "=%q"
|
||||
} else {
|
||||
format = format + "=%s"
|
||||
}
|
||||
if len(flag.NoOptDefVal) > 0 {
|
||||
format = format + "]"
|
||||
}
|
||||
format = format + "\n\t%s\n\n"
|
||||
fmt.Fprintf(out, format, flag.Shorthand, flag.Name, flag.DefValue, flag.Usage)
|
||||
})
|
||||
}
|
||||
|
||||
func manPrintOptions(out io.Writer, command *cobra.Command) {
|
||||
flags := command.NonInheritedFlags()
|
||||
if flags.HasFlags() {
|
||||
fmt.Fprintf(out, "# OPTIONS\n")
|
||||
manPrintFlags(out, flags)
|
||||
fmt.Fprintf(out, "\n")
|
||||
}
|
||||
flags = command.InheritedFlags()
|
||||
if flags.HasFlags() {
|
||||
fmt.Fprintf(out, "# OPTIONS INHERITED FROM PARENT COMMANDS\n")
|
||||
manPrintFlags(out, flags)
|
||||
fmt.Fprintf(out, "\n")
|
||||
}
|
||||
}
|
||||
|
||||
func genMan(cmd *cobra.Command, header *GenManHeader) []byte {
|
||||
// something like `rootcmd subcmd1 subcmd2`
|
||||
commandName := cmd.CommandPath()
|
||||
// something like `rootcmd-subcmd1-subcmd2`
|
||||
dashCommandName := strings.Replace(commandName, " ", "-", -1)
|
||||
|
||||
fillHeader(header, commandName)
|
||||
|
||||
buf := new(bytes.Buffer)
|
||||
|
||||
short := cmd.Short
|
||||
long := cmd.Long
|
||||
if len(long) == 0 {
|
||||
long = short
|
||||
}
|
||||
|
||||
manPreamble(buf, header, commandName, short, long)
|
||||
manPrintOptions(buf, cmd)
|
||||
if len(cmd.Example) > 0 {
|
||||
fmt.Fprintf(buf, "# EXAMPLE\n")
|
||||
fmt.Fprintf(buf, "```\n%s\n```\n", cmd.Example)
|
||||
}
|
||||
if hasSeeAlso(cmd) {
|
||||
fmt.Fprintf(buf, "# SEE ALSO\n")
|
||||
if cmd.HasParent() {
|
||||
parentPath := cmd.Parent().CommandPath()
|
||||
dashParentPath := strings.Replace(parentPath, " ", "-", -1)
|
||||
fmt.Fprintf(buf, "**%s(%s)**", dashParentPath, header.Section)
|
||||
cmd.VisitParents(func(c *cobra.Command) {
|
||||
if c.DisableAutoGenTag {
|
||||
cmd.DisableAutoGenTag = c.DisableAutoGenTag
|
||||
}
|
||||
})
|
||||
}
|
||||
children := cmd.Commands()
|
||||
sort.Sort(byName(children))
|
||||
for i, c := range children {
|
||||
if !c.IsAvailableCommand() || c.IsHelpCommand() {
|
||||
continue
|
||||
}
|
||||
if cmd.HasParent() || i > 0 {
|
||||
fmt.Fprintf(buf, ", ")
|
||||
}
|
||||
fmt.Fprintf(buf, "**%s-%s(%s)**", dashCommandName, c.Name(), header.Section)
|
||||
}
|
||||
fmt.Fprintf(buf, "\n")
|
||||
}
|
||||
if !cmd.DisableAutoGenTag {
|
||||
fmt.Fprintf(buf, "# HISTORY\n%s Auto generated by spf13/cobra\n", header.Date.Format("2-Jan-2006"))
|
||||
}
|
||||
return buf.Bytes()
|
||||
}
|
26
vendor/github.com/spf13/cobra/doc/man_docs.md
generated
vendored
26
vendor/github.com/spf13/cobra/doc/man_docs.md
generated
vendored
|
@ -1,26 +0,0 @@
|
|||
# Generating Man Pages For Your Own cobra.Command
|
||||
|
||||
Generating man pages from a cobra command is incredibly easy. An example is as follows:
|
||||
|
||||
```go
|
||||
package main
|
||||
|
||||
import (
|
||||
"github.com/spf13/cobra"
|
||||
"github.com/spf13/cobra/doc"
|
||||
)
|
||||
|
||||
func main() {
|
||||
cmd := &cobra.Command{
|
||||
Use: "test",
|
||||
Short: "my test program",
|
||||
}
|
||||
header := &cobra.GenManHeader{
|
||||
Title: "MINE",
|
||||
Section: "3",
|
||||
}
|
||||
doc.GenManTree(cmd, header, "/tmp")
|
||||
}
|
||||
```
|
||||
|
||||
That will get you a man page `/tmp/test.1`
|
97
vendor/github.com/spf13/cobra/doc/man_docs_test.go
generated
vendored
97
vendor/github.com/spf13/cobra/doc/man_docs_test.go
generated
vendored
|
@ -1,97 +0,0 @@
|
|||
package doc
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"os"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
var _ = fmt.Println
|
||||
var _ = os.Stderr
|
||||
|
||||
func translate(in string) string {
|
||||
return strings.Replace(in, "-", "\\-", -1)
|
||||
}
|
||||
|
||||
func TestGenManDoc(t *testing.T) {
|
||||
c := initializeWithRootCmd()
|
||||
// Need two commands to run the command alphabetical sort
|
||||
cmdEcho.AddCommand(cmdTimes, cmdEchoSub, cmdDeprecated)
|
||||
c.AddCommand(cmdPrint, cmdEcho)
|
||||
cmdRootWithRun.PersistentFlags().StringVarP(&flags2a, "rootflag", "r", "two", strtwoParentHelp)
|
||||
|
||||
out := new(bytes.Buffer)
|
||||
|
||||
header := &GenManHeader{
|
||||
Title: "Project",
|
||||
Section: "2",
|
||||
}
|
||||
// We generate on a subcommand so we have both subcommands and parents
|
||||
if err := GenMan(cmdEcho, header, out); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
found := out.String()
|
||||
|
||||
// Make sure parent has - in CommandPath() in SEE ALSO:
|
||||
parentPath := cmdEcho.Parent().CommandPath()
|
||||
dashParentPath := strings.Replace(parentPath, " ", "-", -1)
|
||||
expected := translate(dashParentPath)
|
||||
expected = expected + "(" + header.Section + ")"
|
||||
checkStringContains(t, found, expected)
|
||||
|
||||
// Our description
|
||||
expected = translate(cmdEcho.Name())
|
||||
checkStringContains(t, found, expected)
|
||||
|
||||
// Better have our example
|
||||
expected = translate(cmdEcho.Name())
|
||||
checkStringContains(t, found, expected)
|
||||
|
||||
// A local flag
|
||||
expected = "boolone"
|
||||
checkStringContains(t, found, expected)
|
||||
|
||||
// persistent flag on parent
|
||||
expected = "rootflag"
|
||||
checkStringContains(t, found, expected)
|
||||
|
||||
// We better output info about our parent
|
||||
expected = translate(cmdRootWithRun.Name())
|
||||
checkStringContains(t, found, expected)
|
||||
|
||||
// And about subcommands
|
||||
expected = translate(cmdEchoSub.Name())
|
||||
checkStringContains(t, found, expected)
|
||||
|
||||
unexpected := translate(cmdDeprecated.Name())
|
||||
checkStringOmits(t, found, unexpected)
|
||||
|
||||
// auto generated
|
||||
expected = translate("Auto generated")
|
||||
checkStringContains(t, found, expected)
|
||||
}
|
||||
|
||||
func TestGenManNoGenTag(t *testing.T) {
|
||||
c := initializeWithRootCmd()
|
||||
// Need two commands to run the command alphabetical sort
|
||||
cmdEcho.AddCommand(cmdTimes, cmdEchoSub, cmdDeprecated)
|
||||
c.AddCommand(cmdPrint, cmdEcho)
|
||||
cmdRootWithRun.PersistentFlags().StringVarP(&flags2a, "rootflag", "r", "two", strtwoParentHelp)
|
||||
cmdEcho.DisableAutoGenTag = true
|
||||
out := new(bytes.Buffer)
|
||||
|
||||
header := &GenManHeader{
|
||||
Title: "Project",
|
||||
Section: "2",
|
||||
}
|
||||
// We generate on a subcommand so we have both subcommands and parents
|
||||
if err := GenMan(cmdEcho, header, out); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
found := out.String()
|
||||
|
||||
unexpected := translate("#HISTORY")
|
||||
checkStringOmits(t, found, unexpected)
|
||||
}
|
35
vendor/github.com/spf13/cobra/doc/man_examples_test.go
generated
vendored
35
vendor/github.com/spf13/cobra/doc/man_examples_test.go
generated
vendored
|
@ -1,35 +0,0 @@
|
|||
package doc_test
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
"github.com/spf13/cobra/doc"
|
||||
)
|
||||
|
||||
func ExampleCommand_GenManTree() {
|
||||
cmd := &cobra.Command{
|
||||
Use: "test",
|
||||
Short: "my test program",
|
||||
}
|
||||
header := &doc.GenManHeader{
|
||||
Title: "MINE",
|
||||
Section: "3",
|
||||
}
|
||||
doc.GenManTree(cmd, header, "/tmp")
|
||||
}
|
||||
|
||||
func ExampleCommand_GenMan() {
|
||||
cmd := &cobra.Command{
|
||||
Use: "test",
|
||||
Short: "my test program",
|
||||
}
|
||||
header := &doc.GenManHeader{
|
||||
Title: "MINE",
|
||||
Section: "3",
|
||||
}
|
||||
out := new(bytes.Buffer)
|
||||
doc.GenMan(cmd, header, out)
|
||||
fmt.Print(out.String())
|
||||
}
|
175
vendor/github.com/spf13/cobra/doc/md_docs.go
generated
vendored
175
vendor/github.com/spf13/cobra/doc/md_docs.go
generated
vendored
|
@ -1,175 +0,0 @@
|
|||
//Copyright 2015 Red Hat Inc. All rights reserved.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package doc
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
func printOptions(w io.Writer, cmd *cobra.Command, name string) error {
|
||||
flags := cmd.NonInheritedFlags()
|
||||
flags.SetOutput(w)
|
||||
if flags.HasFlags() {
|
||||
if _, err := fmt.Fprintf(w, "### Options\n\n```\n"); err != nil {
|
||||
return err
|
||||
}
|
||||
flags.PrintDefaults()
|
||||
if _, err := fmt.Fprintf(w, "```\n\n"); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
parentFlags := cmd.InheritedFlags()
|
||||
parentFlags.SetOutput(w)
|
||||
if parentFlags.HasFlags() {
|
||||
if _, err := fmt.Fprintf(w, "### Options inherited from parent commands\n\n```\n"); err != nil {
|
||||
return err
|
||||
}
|
||||
parentFlags.PrintDefaults()
|
||||
if _, err := fmt.Fprintf(w, "```\n\n"); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func GenMarkdown(cmd *cobra.Command, w io.Writer) error {
|
||||
return GenMarkdownCustom(cmd, w, func(s string) string { return s })
|
||||
}
|
||||
|
||||
func GenMarkdownCustom(cmd *cobra.Command, w io.Writer, linkHandler func(string) string) error {
|
||||
name := cmd.CommandPath()
|
||||
|
||||
short := cmd.Short
|
||||
long := cmd.Long
|
||||
if len(long) == 0 {
|
||||
long = short
|
||||
}
|
||||
|
||||
if _, err := fmt.Fprintf(w, "## %s\n\n", name); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := fmt.Fprintf(w, "%s\n\n", short); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := fmt.Fprintf(w, "### Synopsis\n\n"); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := fmt.Fprintf(w, "\n%s\n\n", long); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if cmd.Runnable() {
|
||||
if _, err := fmt.Fprintf(w, "```\n%s\n```\n\n", cmd.UseLine()); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
if len(cmd.Example) > 0 {
|
||||
if _, err := fmt.Fprintf(w, "### Examples\n\n"); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := fmt.Fprintf(w, "```\n%s\n```\n\n", cmd.Example); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
if err := printOptions(w, cmd, name); err != nil {
|
||||
return err
|
||||
}
|
||||
if hasSeeAlso(cmd) {
|
||||
if _, err := fmt.Fprintf(w, "### SEE ALSO\n"); err != nil {
|
||||
return err
|
||||
}
|
||||
if cmd.HasParent() {
|
||||
parent := cmd.Parent()
|
||||
pname := parent.CommandPath()
|
||||
link := pname + ".md"
|
||||
link = strings.Replace(link, " ", "_", -1)
|
||||
if _, err := fmt.Fprintf(w, "* [%s](%s)\t - %s\n", pname, linkHandler(link), parent.Short); err != nil {
|
||||
return err
|
||||
}
|
||||
cmd.VisitParents(func(c *cobra.Command) {
|
||||
if c.DisableAutoGenTag {
|
||||
cmd.DisableAutoGenTag = c.DisableAutoGenTag
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
children := cmd.Commands()
|
||||
sort.Sort(byName(children))
|
||||
|
||||
for _, child := range children {
|
||||
if !child.IsAvailableCommand() || child.IsHelpCommand() {
|
||||
continue
|
||||
}
|
||||
cname := name + " " + child.Name()
|
||||
link := cname + ".md"
|
||||
link = strings.Replace(link, " ", "_", -1)
|
||||
if _, err := fmt.Fprintf(w, "* [%s](%s)\t - %s\n", cname, linkHandler(link), child.Short); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if _, err := fmt.Fprintf(w, "\n"); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if !cmd.DisableAutoGenTag {
|
||||
if _, err := fmt.Fprintf(w, "###### Auto generated by spf13/cobra on %s\n", time.Now().Format("2-Jan-2006")); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func GenMarkdownTree(cmd *cobra.Command, dir string) error {
|
||||
identity := func(s string) string { return s }
|
||||
emptyStr := func(s string) string { return "" }
|
||||
return GenMarkdownTreeCustom(cmd, dir, emptyStr, identity)
|
||||
}
|
||||
|
||||
func GenMarkdownTreeCustom(cmd *cobra.Command, dir string, filePrepender, linkHandler func(string) string) error {
|
||||
for _, c := range cmd.Commands() {
|
||||
if !c.IsAvailableCommand() || c.IsHelpCommand() {
|
||||
continue
|
||||
}
|
||||
if err := GenMarkdownTreeCustom(c, dir, filePrepender, linkHandler); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
basename := strings.Replace(cmd.CommandPath(), " ", "_", -1) + ".md"
|
||||
filename := filepath.Join(dir, basename)
|
||||
f, err := os.Create(filename)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer f.Close()
|
||||
|
||||
if _, err := io.WriteString(f, filePrepender(filename)); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := GenMarkdownCustom(cmd, f, linkHandler); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
104
vendor/github.com/spf13/cobra/doc/md_docs.md
generated
vendored
104
vendor/github.com/spf13/cobra/doc/md_docs.md
generated
vendored
|
@ -1,104 +0,0 @@
|
|||
# Generating Markdown Docs For Your Own cobra.Command
|
||||
|
||||
Generating man pages from a cobra command is incredibly easy. An example is as follows:
|
||||
|
||||
```go
|
||||
package main
|
||||
|
||||
import (
|
||||
"github.com/spf13/cobra"
|
||||
"github.com/spf13/cobra/doc"
|
||||
)
|
||||
|
||||
func main() {
|
||||
cmd := &cobra.Command{
|
||||
Use: "test",
|
||||
Short: "my test program",
|
||||
}
|
||||
doc.GenMarkdownTree(cmd, "/tmp")
|
||||
}
|
||||
```
|
||||
|
||||
That will get you a Markdown document `/tmp/test.md`
|
||||
|
||||
## Generate markdown docs for the entire command tree
|
||||
|
||||
This program can actually generate docs for the kubectl command in the kubernetes project
|
||||
|
||||
```go
|
||||
package main
|
||||
|
||||
import (
|
||||
"io/ioutil"
|
||||
"os"
|
||||
|
||||
kubectlcmd "k8s.io/kubernetes/pkg/kubectl/cmd"
|
||||
cmdutil "k8s.io/kubernetes/pkg/kubectl/cmd/util"
|
||||
|
||||
"github.com/spf13/cobra/doc"
|
||||
)
|
||||
|
||||
func main() {
|
||||
cmd := kubectlcmd.NewKubectlCommand(cmdutil.NewFactory(nil), os.Stdin, ioutil.Discard, ioutil.Discard)
|
||||
doc.GenMarkdownTree(cmd, "./")
|
||||
}
|
||||
```
|
||||
|
||||
This will generate a whole series of files, one for each command in the tree, in the directory specified (in this case "./")
|
||||
|
||||
## Generate markdown docs for a single command
|
||||
|
||||
You may wish to have more control over the output, or only generate for a single command, instead of the entire command tree. If this is the case you may prefer to `GenMarkdown` instead of `GenMarkdownTree`
|
||||
|
||||
```go
|
||||
out := new(bytes.Buffer)
|
||||
doc.GenMarkdown(cmd, out)
|
||||
```
|
||||
|
||||
This will write the markdown doc for ONLY "cmd" into the out, buffer.
|
||||
|
||||
## Customize the output
|
||||
|
||||
Both `GenMarkdown` and `GenMarkdownTree` have alternate versions with callbacks to get some control of the output:
|
||||
|
||||
```go
|
||||
func GenMarkdownTreeCustom(cmd *Command, dir string, filePrepender, linkHandler func(string) string) error {
|
||||
//...
|
||||
}
|
||||
```
|
||||
|
||||
```go
|
||||
func GenMarkdownCustom(cmd *Command, out *bytes.Buffer, linkHandler func(string) string) error {
|
||||
//...
|
||||
}
|
||||
```
|
||||
|
||||
The `filePrepender` will prepend the return value given the full filepath to the rendered Markdown file. A common use case is to add front matter to use the generated documentation with [Hugo](http://gohugo.io/):
|
||||
|
||||
```go
|
||||
const fmTemplate = `---
|
||||
date: %s
|
||||
title: "%s"
|
||||
slug: %s
|
||||
url: %s
|
||||
---
|
||||
`
|
||||
|
||||
filePrepender := func(filename string) string {
|
||||
now := time.Now().Format(time.RFC3339)
|
||||
name := filepath.Base(filename)
|
||||
base := strings.TrimSuffix(name, path.Ext(name))
|
||||
url := "/commands/" + strings.ToLower(base) + "/"
|
||||
return fmt.Sprintf(fmTemplate, now, strings.Replace(base, "_", " ", -1), base, url)
|
||||
}
|
||||
```
|
||||
|
||||
The `linkHandler` can be used to customize the rendered internal links to the commands, given a filename:
|
||||
|
||||
```go
|
||||
linkHandler := func(name string) string {
|
||||
base := strings.TrimSuffix(name, path.Ext(name))
|
||||
return "/commands/" + strings.ToLower(base) + "/"
|
||||
}
|
||||
```
|
||||
|
88
vendor/github.com/spf13/cobra/doc/md_docs_test.go
generated
vendored
88
vendor/github.com/spf13/cobra/doc/md_docs_test.go
generated
vendored
|
@ -1,88 +0,0 @@
|
|||
package doc
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"os"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
var _ = fmt.Println
|
||||
var _ = os.Stderr
|
||||
|
||||
func TestGenMdDoc(t *testing.T) {
|
||||
c := initializeWithRootCmd()
|
||||
// Need two commands to run the command alphabetical sort
|
||||
cmdEcho.AddCommand(cmdTimes, cmdEchoSub, cmdDeprecated)
|
||||
c.AddCommand(cmdPrint, cmdEcho)
|
||||
cmdRootWithRun.PersistentFlags().StringVarP(&flags2a, "rootflag", "r", "two", strtwoParentHelp)
|
||||
|
||||
out := new(bytes.Buffer)
|
||||
|
||||
// We generate on s subcommand so we have both subcommands and parents
|
||||
if err := GenMarkdown(cmdEcho, out); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
found := out.String()
|
||||
|
||||
// Our description
|
||||
expected := cmdEcho.Long
|
||||
if !strings.Contains(found, expected) {
|
||||
t.Errorf("Unexpected response.\nExpecting to contain: \n %q\nGot:\n %q\n", expected, found)
|
||||
}
|
||||
|
||||
// Better have our example
|
||||
expected = cmdEcho.Example
|
||||
if !strings.Contains(found, expected) {
|
||||
t.Errorf("Unexpected response.\nExpecting to contain: \n %q\nGot:\n %q\n", expected, found)
|
||||
}
|
||||
|
||||
// A local flag
|
||||
expected = "boolone"
|
||||
if !strings.Contains(found, expected) {
|
||||
t.Errorf("Unexpected response.\nExpecting to contain: \n %q\nGot:\n %q\n", expected, found)
|
||||
}
|
||||
|
||||
// persistent flag on parent
|
||||
expected = "rootflag"
|
||||
if !strings.Contains(found, expected) {
|
||||
t.Errorf("Unexpected response.\nExpecting to contain: \n %q\nGot:\n %q\n", expected, found)
|
||||
}
|
||||
|
||||
// We better output info about our parent
|
||||
expected = cmdRootWithRun.Short
|
||||
if !strings.Contains(found, expected) {
|
||||
t.Errorf("Unexpected response.\nExpecting to contain: \n %q\nGot:\n %q\n", expected, found)
|
||||
}
|
||||
|
||||
// And about subcommands
|
||||
expected = cmdEchoSub.Short
|
||||
if !strings.Contains(found, expected) {
|
||||
t.Errorf("Unexpected response.\nExpecting to contain: \n %q\nGot:\n %q\n", expected, found)
|
||||
}
|
||||
|
||||
unexpected := cmdDeprecated.Short
|
||||
if strings.Contains(found, unexpected) {
|
||||
t.Errorf("Unexpected response.\nFound: %v\nBut should not have!!\n", unexpected)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGenMdNoTag(t *testing.T) {
|
||||
c := initializeWithRootCmd()
|
||||
// Need two commands to run the command alphabetical sort
|
||||
cmdEcho.AddCommand(cmdTimes, cmdEchoSub, cmdDeprecated)
|
||||
c.AddCommand(cmdPrint, cmdEcho)
|
||||
c.DisableAutoGenTag = true
|
||||
cmdRootWithRun.PersistentFlags().StringVarP(&flags2a, "rootflag", "r", "two", strtwoParentHelp)
|
||||
out := new(bytes.Buffer)
|
||||
|
||||
if err := GenMarkdown(c, out); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
found := out.String()
|
||||
|
||||
unexpected := "Auto generated"
|
||||
checkStringOmits(t, found, unexpected)
|
||||
|
||||
}
|
38
vendor/github.com/spf13/cobra/doc/util.go
generated
vendored
38
vendor/github.com/spf13/cobra/doc/util.go
generated
vendored
|
@ -1,38 +0,0 @@
|
|||
// Copyright 2015 Red Hat Inc. All rights reserved.
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package doc
|
||||
|
||||
import "github.com/spf13/cobra"
|
||||
|
||||
// Test to see if we have a reason to print See Also information in docs
|
||||
// Basically this is a test for a parent commend or a subcommand which is
|
||||
// both not deprecated and not the autogenerated help command.
|
||||
func hasSeeAlso(cmd *cobra.Command) bool {
|
||||
if cmd.HasParent() {
|
||||
return true
|
||||
}
|
||||
for _, c := range cmd.Commands() {
|
||||
if !c.IsAvailableCommand() || c.IsHelpCommand() {
|
||||
continue
|
||||
}
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
type byName []*cobra.Command
|
||||
|
||||
func (s byName) Len() int { return len(s) }
|
||||
func (s byName) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
|
||||
func (s byName) Less(i, j int) bool { return s[i].Name() < s[j].Name() }
|
Loading…
Add table
Add a link
Reference in a new issue