Giter Club home page Giter Club logo

cobra's Introduction

@spf13 👋

GitHub Twitter LinkedIn Reddit User Karma

Go on GitHub Hugo on GitHub Cobra on Github Viper on GitHub spf13-vim on GitHub

Former: Moby on GitHub MongoDB on GitHub

cobra's People

Contributors

anthonyfok avatar apriendeau avatar babysnakes avatar bep avatar bruceadowns avatar dependabot[bot] avatar dixudx avatar dnephin avatar dohzya avatar eparis avatar fabianofranz avatar garthk avatar jharshman avatar jleni avatar johananl avatar jpmcb avatar luap99 avatar marckhouzam avatar mvdan avatar n10v avatar nirs avatar nmiyake avatar rajatjindal avatar scop avatar spf13 avatar sttts avatar tamird avatar tummychow avatar umarcor avatar wfernandes avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

cobra's Issues

Suggestion: "did you mean" for misspelled commands

In git, if you execute git commt, you'll get the following message:

git: 'commt' is not a git command. See 'git --help'.

Did you mean this?
    commit

It would be a very useful (and simple to implement) feature for Cobra to have. Thoughts?

Usage output should default to stdout not stderr for subcommands too

#71 fixed #31, making command --help | grep something work as expected, however it doesn't work for subcommands like command subcmd --help | grep something.

This can be reproduced by compiling the example program from the README, and:

$ go run main.go echo --help | grep help        # won't work
$ go run main.go echo --help 2>&1 | grep help   # hack

Match on everything else

First, thank you for this package.

I wondered if there was a way of being redirected on commands or something else when the first parameter is not known as a command?
For example:

$ todo add 'work on project#1'

redirected on command add.

$ todo list

redirected on command list.

$ todo 'work on project#1'

redirected on a command matching with everything except the existing commands (add and list) instead of raising an error.

Expose annotations in the Cobra API

Ref. the bashcompletion sample:

 annotations := []string{"json", "yaml", "yml"}
    annotation := make(map[string][]string)
    annotation[cobra.BashCompFilenameExt] = annotations

    flag := &pflag.Flag{
        Name:        "filename",
        Shorthand:   "f",
        Usage:       usage,
        Value:       value,
        DefValue:    value.String(),
        Annotations: annotation,
    }
    cmd.Flags().AddFlag(flag)

There are a couple of issues with this:

  1. It's incomplete. What is value?

  2. It's kind of missing the point of Cobra being the abstraction it is.

  3. would maybe be fine if the Value types in pflag were exported.

Root command's Help() doesn't print Usage

As pointed out by @jcelliott in #3, running the root command without any arguments, or running the root command with <command> help does not print the Command.Long description.[1] Given that the help command is the only venue in which you can see the Long description, this is a bug. (The README indicates that the Long description should be printed as well.)

The issue is that Command.Usage() doesn't print the Long description, only Command.Help() does. This would be fine if Command.Help() always printed Usage. But instead, Command.Help() only prints Usage if the Command is Runnable, which the root command typically is not. Instead, Command.Help() should print Usage if the command is Runnable OR if the command HasSubCommands.

When Help() is fixed to print Usage in those cases, Help is often the preferred thing to print, not Usage.

I am submitting a PR which fixes the Help() behavior and changes a few Usage() references to use Help() instead.

[1] As an aside, if you go get the latest cobra release, this behavior is visible on Hugo right now.

Better error messages on subcommands

Considering this example code:

package main

import (
    "fmt"
    "github.com/spf13/cobra"
)

func main() {
    rootCmd := &cobra.Command{
        Run: func(rootCmd *cobra.Command, args []string) {
            fmt.Println("okay")
        },
    }
    var serverPort int
    serverCmd := &cobra.Command{
        Use: "server",
        Run: func(rootCmd *cobra.Command, args []string) {
            fmt.Printf("start server at %d\n", serverPort)
        },
    }
    serverCmd.Flags().IntVarP(&serverPort, "port", "p", 8080, "The port   number to bind the http server to.")
    rootCmd.AddCommand(serverCmd)

    err := rootCmd.Execute()
    if err != nil {
        fmt.Printf("ERROR: %s\n", err)
    }
}

When running this program using invalid number value for port option prints an awkward message as follow:

ERROR: unknown shorthand flag: 'p' in -p
Usage of :

But, this behavior only happens when using subcommands. For root commands the following message could be printed:

ERROR: invalid argument "1io" for -p: strconv.ParseInt: parsing "1io": invalid syntax
Usage of :
  -p, --port=8080: The port number to bind the http server to.

The last one is more useful (self-explanatory) for end-users.

Command.Run should return error

The error handling in general confuses me.

  • There is no obvious way to propagate errors from Command.Run upwards, consider changing signature to return error
  • If Command.Run fails with an error, exit with exit code != 0

Reports an error for flags placed after the '--' flag terminator.

Firstly, thanks for building this package.

One of the commands I am trying to build with this is an exec command.

it works as follows:

rootCmd exec --booleanFlag1 arg1 -- python abc.py -u jondoe

so while I have listed booleanFlag1 as a flag in the exec command it still parses the -u flag and reports an unknown flag error.

The exec command's run function right now just prints the args that are passed to it.

If i pass in arguments without - or -- after the flag terminator everything works fine.

Here is a sample output: [/key python abc.py thingie python abc.py thingie]

So the command used here was rootCmd exec /key -- python abc.py thingie

Another question is why is the stuff after the terminator included twice in the args.

I thought the flags and pflags library accounted for the flag terminator , am I missing something or not using the library correctly ?

#32 erroneously omits long description as well for <command> help

Trying out @spf13's tutorial at http://spf13.com/presentation/first-go-app/ (step 1) I discovered that when there is no subcommand added, default help fails:

k4rtik at PlatiniumAir in ~/Projects/go/src/github.com/k4rtik/planet
$ go run main.go help

Usage:
  dagobah [flags]

 Available Flags:
  -h, --help=false: help for dagobah
Error: unknown command "help"
Run 'help' for usage.

dagobah: invalid command [`help`]
Run 'dagobah help' for usage
unknown command "help"
Run 'help' for usage.

exit status 255

This seems to have originated from the merge of #32

Question: See if a flag was set by the user

Is there a way that I can see if a user set a flag, vs. just used the default?

Desired behavior:

  1. If no config file is specified, use default flag value.
  2. If config file is specified, and the user did not set the flag, use the value in the config file
  3. If config file is specified, but the user did set the flag, use the value specified by the user, even if it's just the default flag value.

I'm trying to avoid the situation where a non-default is set in the config, but the user wants to force the program to use the default.

I have a hacky solution that involves parsing the flags twice using different defaults, is there a better approach?

provide preRun/postRun hooks

It would be really cool if cobra provides hooks for the commands Run function. That way things could happen right before/after the Run function is executed. For the PreRun hook it would be cool when flags are already parsed and usable inside the hooks.

Opinions?

Invalid flag handling message needs work

When specifying an invalid flag on the openshift cli, there are three problems:

  1. it reports all flags as invalid, not just the invalid flag
  2. for each invalid flag, it refers the user to the help. it should only do this once, at the end.
  3. it reports an unknown flag, then gives usage, then reports a bunch of invalid flags.

here's an example (only "ectdBADDir" is an invalid flag):

$ openshift start --help

Usage: 
  openshift start [flags]

 Available Flags:
      --etcdDir="openshift.local.etcd": The etcd data directory.
      --help=false: help for start
      --listenAddr="127.0.0.1:8080": The server listen address.
      --volumeDir="openshift.local.volumes": The volume storage directory.


Use "openshift help [command]" for more information about that command.

then

$ openshift start --listenAddr="0.0.0.0:8080" --volumeDir=mktemp --etcdBADDir=mktemp
unknown flag: --listenAddr

Usage: 
  openshift [flags]
  openshift [command]

Available Commands: 
  start                     Launch in all-in-one mode
  kube                      The Kubernetes command line client
  version                   Display version
  help [command]            Help about any command

 Available Flags:
      --help=false: help for openshift

Use "openshift help [command]" for more information about that command.
Error: unknown flag: --listenAddr
Usage of openshift:
      --help=false: help for openshift
unknown flag: --volumeDir
Usage of openshift:
      --help=false: help for openshift
unknown flag: --etcdBADDir
Usage of openshift:
      --help=false: help for openshift
ffranz@localhost origin$ 

Unknown commands '-h' and '--help'

Using the default example with 'Short' & 'Long' added to rootCmd:

package main

import (
    "fmt"
    "github.com/spf13/cobra"
    "strings"
)

func main() {

    var echoTimes int

    var cmdPrint = &cobra.Command{
        Use:   "print [string to print]",
        Short: "Print anything to the screen",
        Long: `print is for printing anything back to the screen.
        For many years people have printed back to the screen.
        `,
        Run: func(cmd *cobra.Command, args []string) {
            fmt.Println("Print: " + strings.Join(args, " "))
        },
    }

    var cmdEcho = &cobra.Command{
        Use:   "echo [string to echo]",
        Short: "Echo anything to the screen",
        Long: `echo is for echoing anything back.
        Echo works a lot like print, except it has a child command.
        `,
        Run: func(cmd *cobra.Command, args []string) {
            fmt.Println("Print: " + strings.Join(args, " "))
        },
    }

    var cmdTimes = &cobra.Command{
        Use:   "times [# times] [string to echo]",
        Short: "Echo anything to the screen more times",
        Long: `echo things multiple times back to the user by providing
        a count and a string.`,
        Run: func(cmd *cobra.Command, args []string) {
            for i := 0; i < echoTimes; i++ {
                fmt.Println("Echo: " + strings.Join(args, " "))
            }
        },
    }

    cmdTimes.Flags().IntVarP(&echoTimes, "times", "t", 1, "times to echo the input")

    var rootCmd = &cobra.Command{
        Use:   "usage string",
        Short: "short string",
        Long:  "long string",
    }

    rootCmd.AddCommand(cmdPrint, cmdEcho)
    cmdEcho.AddCommand(cmdTimes)
    rootCmd.Execute()
}

Output of app and app help is correct and lists '-h' and '--help' as global flags:

jbaker: )➤ app                                                                                                                                                                 
long string

Usage:
  usage [command]

Available Commands:
  print [string to print]   Print anything to the screen
  echo [string to echo]     Echo anything to the screen
  help [command]            Help about any command


Global Flags:
  -h, --help=false: help for usage

Use "usage help [command]" for more information about a command.
jbaker: )➤ app help                                                                                                                                                                 
long string

Usage:
  usage [command]

Available Commands:
  print [string to print]   Print anything to the screen
  echo [string to echo]     Echo anything to the screen
  help [command]            Help about any command


Global Flags:
  -h, --help=false: help for usage

Use "usage help [command]" for more information about a command.

jbaker: )➤

app -h and app --help fail with 'unknown command':

jbaker: )➤ app -h                                                                                                                                                                    
Error: unknown command "-h"
Run 'help' for usage.

usage: invalid command [`-h`]
Run 'usage help' for usage
jbaker: )➤ app --help                                                                                                                                                              
Error: unknown command "--help"
Run 'help' for usage.

usage: invalid command [`--help`]
Run 'usage help' for usage

Short Flag for help not printing

Sample output, when running program --help or program -h

Available Flags:
 -c, --config="": Description
     --help=false: Help for program

Shouldn't it look like this:

Available Flags:
 -c, --config="": Description
 -h, --help=false: Help for program

Since it might matter, I have my root command set to executable.

How to "wrap" command line arguments so they won't be interpreted as commands?

Here's my use case:

I want to have a command "Run" that will launch another application (along with that applications arguments, something like this:

go run myLauncher --run="myApp --startup-args=a, b, c"

In other words, the 'myApp' process also uses the -- / - argument syntax for it's arguments - when I try this, I can launch myApp if I give it no arguments, but if I include arguments, then cobra tries to parse them out as if they were the "myLauncher" arguments

If no subcommand, how to get args?

example:

package main

import (
    "fmt"
    "github.com/spf13/cobra"
)

func main() {
    var echo = &cobra.Command{
        Use:    "echo [string...]",
        Short:  "echo all strings",
        Long:   "echo string string string string...",
        Run:    func(cmd *cobra.Command, args []string) {
            fmt.Printf("%v\n", args)
        },
    }

    echo.Execute()
}
[bash]# go run echo.go aa bb cc dd

Usage:
  echo [string...] [flags]

 Available Flags:
  -h, --help=false: help for echo
Error: unknown command "aa"
Run 'help' for usage.

echo: invalid command [`aa` `bb` `cc` `dd`]
Run 'echo help' for usage
[bash]# go run echo.go echo aa bb cc dd
[echo aa bb cc dd]
[bash]# go run echo.go
[]

Thanks!

panic: shorthand redefinition when using PersistentFlags

I'm getting a panic error when using PersistentFlags. I guess this is caused due to a bad closing in a goroutine process

flags := cmd.PersistentFlags()
flags.StringVarP(&host, "host", "h", "127.0.0.1", "path to config file")
flags.StringVarP(&port, "port", "p", "8000", "port to listen")
flags.StringVarP(&forward, "forward", "f", "http://httpbin.org:80", "port to listen")
flags.StringVarP(&config, "config", "c", "", "path to config file")
flags.BoolVarP(&verbose, "verbose", "v", false, "verbose output")
panic: shorthand redefinition

goroutine 1 [running]:
github.com/spf13/pflag.(*FlagSet).AddFlag(0xc208068100, 0xc20800a3c0)
    /Users/h2non/go/src/github.com/spf13/pflag/flag.go:391 +0xb03
github.com/spf13/pflag.(*FlagSet).VarP(0xc208068100, 0x7c41a0, 0xc208000fa8, 0x4a7970, 0x4, 0x4a7590, 0x1, 0xc20802ad80, 0xf)
    /Users/h2non/go/src/github.com/spf13/pflag/flag.go:362 +0x162
github.com/spf13/pflag.(*FlagSet).BoolVarP(0xc208068100, 0xc208000fa8, 0x4a7970, 0x4, 0x4a7590, 0x1, 0x0, 0xc20802ad80, 0xf)
    /Users/h2non/go/src/github.com/spf13/pflag/bool.go:45 +0xae
github.com/spf13/cobra.(*Command).Flags(0xc208000ea0, 0x0)
    /Users/h2non/go/src/github.com/spf13/cobra/command.go:695 +0x299
github.com/spf13/cobra.func·011(0xc20800a300)
    /Users/h2non/go/src/github.com/spf13/cobra/command.go:830 +0x2f
github.com/spf13/pflag.(*FlagSet).VisitAll(0xc208068100, 0xc2080b3b18)
    /Users/h2non/go/src/github.com/spf13/pflag/flag.go:193 +0x88
github.com/spf13/cobra.func·012(0xc208000ea0)
    /Users/h2non/go/src/github.com/spf13/cobra/command.go:833 +0xab
github.com/spf13/cobra.(*Command).mergePersistentFlags(0xc208000ea0)
    /Users/h2non/go/src/github.com/spf13/cobra/command.go:840 +0x77
github.com/spf13/cobra.(*Command).ParseFlags(0xc208000ea0, 0xc20800a010, 0x5, 0x5, 0x0, 0x0)
    /Users/h2non/go/src/github.com/spf13/cobra/command.go:806 +0x4b
github.com/spf13/cobra.(*Command).execute(0xc208000ea0, 0xc20800a010, 0x5, 0x5, 0x0, 0x0)
    /Users/h2non/go/src/github.com/spf13/cobra/command.go:358 +0xd1
github.com/spf13/cobra.(*Command).findAndExecute(0xc208000ea0, 0xc20800a010, 0x5, 0x5, 0x0, 0x0)
    /Users/h2non/go/src/github.com/spf13/cobra/command.go:350 +0xd4
github.com/spf13/cobra.(*Command).Execute(0xc208000ea0, 0x0, 0x0)
    /Users/h2non/go/src/github.com/spf13/cobra/command.go:436 +0xab3
main.NewCmd()
    /Users/h2non/projects/vinci/cli.go:44 +0x4bd

Test fails on Linux / Go 1.4.2

--- FAIL: TestChildCommandFlags (0.00s)
    cobra_test.go:382: invalid flag should generate error
    cobra_test.go:386: Wrong error message displayed, 

Confirmation before action

Hello,

Problem

I would like to know how to have a confirmation before the action.
For example if my command is dangerous because i delete resources, maybe i would like to have a simple question to answer.

Example

shell> myCommand delete /home/nicolas/images
[Warning] are you sure to do that ? Yes / No
yes
ok.
shell>

Ideas

Would you be interested by a Pull Request to have a dedicated flag for this question ?

Thanks a lot and sorry for my bad speaking english.
Best regards,
Nicolas

Invalid Command error output repeated

This appears to be related to #28

An invalid command error resulst in the repeating of error output. Resolving this would resolve repeated error messages with Hugo (no current issue) and other applications relying on Cobra.

Using a Cobra based cli template, running it with an invalid command results in the following:

spf13template  hellp

Usage: 
  spf13template [flags]
  spf13template [command]

Available Commands: 
  hello [phrase to use]     Returns 'Hello ' with what you entered after the command
  version                   Print spf13template version
  help [command]            Help about any command

 Available Flags:
  -h, --help=false: help for spf13template
  -l, --log=false: Enable/disable logging
  -f, --logfile="application.log": Logfile location. Enables logging when this flag is passed with a value
  -t, --loglevel="info": Max logging level to ouput. Enables logging when this flag is passed with a value
      --lower=false: lowercase output
  -s, --stdoutlevel="warn": Max logging level for stdout output

Use "spf13template help [command]" for more information about that command.
Error: unknown command "hellp"
Run 'help' for usage.

spf13template: invalid command [`hellp`]
Run 'spf13template help' for usage

The output comes from Cobra, the spf13template does not output the returned error message, only doing an os.Exit(-1) when the error is not nil.

A combination of the two messages would probably be the preferred output.

Are negative numbers possible as arguments?

Can I use negative numbers as arguments for a command? Currently this happens:

$ cmd -123 
Failed running command ["cmd" "-123"]: unknown shorthand flag: '1' in -123

It is possible to run the command like this: cmd -- -123.

Is this usage possible with the current version of cobra or could a Command have a field AllowNegativeArgs: true to allow such a usage?

Enable the specification of the Help flag's shorthand character and usage value

I would like to be able to specify the value used for the help flag's shorthand character so that when there's a global "host" flag, it can use the "h" for its shorthand and the help flag can use "?". Additionally, the ability to format the help flag's usage value would also be nice for applications with different casing standards for help output.

It appears that the help flag is automatically generated as part of the core cobra package (when a flag set is nil), so I am submitting a patch that should make it easy for this routine to take into account user preference.

Autocompletion does not work

Tried to generate Bash autocompletion for Hugo, but gets:

__start_hugo:3: command not found: _init_completion

I don't see _init_completion anywhere in the source.

zsh autocompletion generator

There are desires among users (see gohugoio/hugo#1088) for an auto-completion generator for zsh, similar to what @eparis has made available for bash in his excellent work in #69.

So, here is a reminder so perhaps someone could use @eparis's excellent work for bash as the basis for the same for zsh. :-)

Usage output should default to stdout not stderr

It is very common to want to command --help | grep $something but since we default all help and usage to stderr this becomes a user annoyance.

I'm not the only person who is annoyed (even though I filed that one too):
kubernetes/kubernetes#2177

I started poking this just a bit today but was hoping you might have suggestions on a good way to solve the problem...

Replace os.Args[1:] to args

File: cobra/command.go, 459 line

    -    c.Printf("%v: invalid command %#q\n", c.Root().Name(), os.Args[1:])
    +    c.Printf("%v: invalid command %#q\n", c.Root().Name(), args)

Output (with args []string{"help hh", "77"}):

    Output before:    testapp: invalid command []
    Output after:    testapp: invalid command [`help hh` `77`]

Shorthand flag redefinition doesn't print out error message before panic

When I (accidentally) do a shorthand flag redefinition I get:

$ go run cmd/kubectl/kubectl.go get rc
panic: shorthand redefinition

goroutine 16 [running]:
runtime.panic(0x30d4a0, 0xc2080017a0)
        /usr/local/Cellar/go/1.3/libexec/src/pkg/runtime/panic.c:279 +0xf5

But in the code I see it's supposed to print out a message first:

if alreadythere {
        fmt.Fprintf(f.out(), "%s shorthand reused: %q for %s already used for %s\n", f.name, c, flag.Name, old.Name)
        panic("shorthand redefinition")
}

But the message isn't appearing. I think f.out() must not be flushing in time. If I change it to fmt.Printf(...), I get the correct behavior.

$ go run cmd/kubectl/kubectl.go get rc
get shorthand reused: 'h' for host already used for help
panic: shorthand redefinition

goroutine 16 [running]:
runtime.panic(0x30d3c0, 0xc208001520)
        /usr/local/Cellar/go/1.3/libexec/src/pkg/runtime/panic.c:279 +0xf5

"invalid memory address or nil pointer dereference" when c.Run is nil

When hugo convert or hugo list is run as is without a sub-command, hugo would panic with an error as follows:

$ hugo convert
panic: runtime error: invalid memory address or nil pointer dereference
[signal 0xb code=0x1 addr=0x0 pc=0x43e027]

goroutine 16 [running]:
runtime.panic(0x9a1820, 0xd57bd3)
    /usr/lib/go/src/pkg/runtime/panic.c:279 +0xf5
github.com/spf13/cobra.(*Command).execute(0xd55ca0, 0xd65038, 0x0, 0x0, 0x0, 0x0)
    /tmp/go/src/github.com/spf13/cobra/command.go:368 +0x177
github.com/spf13/cobra.(*Command).findAndExecute(0xd56120, 0xc20800e010, 0x1, 0x1, 0x0, 0x0)
    /tmp/go/src/github.com/spf13/cobra/command.go:347 +0xd3
github.com/spf13/cobra.(*Command).Execute(0xd56120, 0x0, 0x0)
    /tmp/go/src/github.com/spf13/cobra/command.go:421 +0x7b3
github.com/spf13/hugo/commands.Execute()
    /tmp/go/src/github.com/spf13/hugo/commands/hugo.go:60 +0x2f
main.main()
    /tmp/go/src/github.com/spf13/hugo/main.go:24 +0x30

goroutine 19 [finalizer wait]:
runtime.park(0x4131c0, 0xd63c70, 0xd5ccc9)
    /usr/lib/go/src/pkg/runtime/proc.c:1369 +0x89
runtime.parkunlock(0xd63c70, 0xd5ccc9)
    /usr/lib/go/src/pkg/runtime/proc.c:1385 +0x3b
runfinq()
    /usr/lib/go/src/pkg/runtime/mgc0.c:2644 +0xcf
runtime.goexit()
    /usr/lib/go/src/pkg/runtime/proc.c:1445

It appears that once we reach err = c.findAndExecute(args) in command.go, there was no further c.Runnable() check down the path, until the program tries to run c.Run(c, argWoFlags) even when c.Run is nil.

Global flags aren't used/parsed

If someone creates a flag into the pflag.CommandLine flag set, it isn't imported/used/parsed. It should instead be merged with the rest of the persistent flags.

global flags

I have a global flag, setting this on root command show the help, but there is no way to run it if I have sub command.

root := root := &cobra.Command{
        Use:   "tmass",
    }
root.Flags().StringVar(
        &tmuxCmd,
        "tmux",
        "tmux",
        `The tmux command to use, just if tmux is not in the $PATH`,
    )
root.AddCommand(x,y,z)
root.Execute()

How I can set the tmux flag? tmas x --tmux=abc or tmass --tmux=abc x both return error.

Cannot go get cobra

piyush:dev [] $ go get github.com/spf13/cobra
# github.com/spf13/cobra
GOPATH/src/github.com/spf13/cobra/bash_completions.go:259: flag.Annotations undefined (type *pflag.Flag has no field or method Annotations)
GOPATH/src/github.com/spf13/cobra/bash_completions.go:271: flag.Annotations undefined (type *pflag.Flag has no field or method Annotations)
GOPATH/src/github.com/spf13/cobra/bash_completions.go:295: flag.Annotations undefined (type *pflag.Flag has no field or method Annotations)
GOPATH/src/github.com/spf13/cobra/bash_completions.go:374: flags.SetAnnotation undefined (type *pflag.FlagSet has no field or method SetAnnotation)
GOPATH/src/github.com/spf13/cobra/bash_completions.go:386: flags.SetAnnotation undefined (type *pflag.FlagSet has no field or method SetAnnotation)
GOPATH/src/github.com/spf13/cobra/command.go:97: undefined: pflag.NormalizedName
GOPATH/src/github.com/spf13/cobra/command.go:158: undefined: pflag.NormalizedName
GOPATH/src/github.com/spf13/cobra/command.go:159: c.Flags().SetNormalizeFunc undefined (type *pflag.FlagSet has no field or method SetNormalizeFunc)
GOPATH/src/github.com/spf13/cobra/command.go:160: c.PersistentFlags().SetNormalizeFunc undefined (type *pflag.FlagSet has no field or method SetNormalizeFunc)
GOPATH/src/github.com/spf13/cobra/command.go:850: undefined: pflag.NormalizedName
GOPATH/src/github.com/spf13/cobra/command.go:160: too many errors

Using sucommand invalid flag shows global usage

With following command structure:

$ sti help
(...)
Available Commands: 
  version                      Display version
  build <source> <image> <tag> Build a new image
  usage <image>                Print usage of the assemble script associated with the image
  help [command]               Help about any command

When I invoke subcommand with invalid flag cobra returns me a root command usage, eg.:

$ sti usage --unknown
unknown flag: --unknown

Usage: 
  sti [flags]
  sti [command]

Available Commands: 
  version                      Display version
  build <source> <image> <tag> Build a new image
  usage <image>                Print usage of the assemble script associated with the image
  help [command]               Help about any command

 Available Flags:
  -h, --help=false: help for sti
      --loglevel=0: Set the level of log output (0-3)
      --savetempdir=false: Save the temporary directory used by STI instead of deleting it
  -U, --url="unix:///var/run/docker.sock": Set the url of the docker socket to use

Use "sti help [command]" for more information about that command.

Where it should, if it's possible, return specific command usage.

Are commands with un-runnable parents deliberately undiscoverable?

In a program with a command structure such as ./program section command -flags, why do un-runnable sections not appear in the program's "Available Commands?"

You can list the child commands with program help section, but there's no way to find out that section exists. Is this intentional for some reason?

Thank you :)

Command aliases

How would one go about creating a command that is an alias of another command with given flags?

for instance
program subcommand1 --flag1 --flag2 --flag3
can become
program subcommand2

pflag / viper / cobra: Allow ENV to default flag values

There are cases (running in Docker containers, bash scripts) where ENV vars are easier to set and pass down to a command than generating flag arguments on the fly. It would be nice in the flags definition (or in a related mechanism) to attach an env var name to a flag such that in the absence of a flag, the env var is checked and used. The var would probably be considered as "set" if detected as non-empty.

Since pflags doesn't allow issues I'm raising it here - is there any interest in a pull that added the ability to map an ENV var to a flag? Adding one *Var / *VarP / *P variant for each env option doesn't seem like a good idea - I was considering an ENV map that could be applied after flag checking:

cmd := &Command{}
// ... add flag "foo"
cmd.SetEnvironmentFlags(map[string]string{
   "foo": "MY_FOO_ENV_VAR_NAME",
})

When you ran a command after flag parsing the environment would be used to set unspecified values (or to prime the values of flags).

I can pull together a pull if this isn't seen as out of scope for cobra.

Invoke $PAGER for help output if connected to a TTY

If the output is a terminal, help output should go to a pager, perhaps only if it is longer than number of lines the terminal can display.

Further enhancements: add a default pager, and allow API clients to specify a default pager, and a $CLIENT_APP_PAGER env var that, precedence:

  • $CLIENT_APP_PAGER
  • $PAGER
  • client app specified default pager

This is what man does, at leastr on Debian-based systems.

Related: kubernetes/kubernetes#13522

Spelling mistake in readme file.

I know this is minor, but I believe its still is a mistake.

Under the example section describing the root example not being able executable, the description says "executible" instead of "executable". Hope it helps!

Thnx for your library btw. :)

Allow command aliases

It'd be nice with an easy way to give a command several names (for example "status" and "show" I'd like to do the same in my program).

Parse commands and flags irregardless of order

Suppose I have a ToDo command line application which affects a todo list stored in a .txt file and some actions this application can do (such as add, list, etc...).

I would like to have a flag which would say which .txt file to read to or write from. To make it easy to alias I would like this flag to be the associated with the root cobra command. Everything works very well up to the point when I want to run commands like

$ todo --file="somefile.txt" add "some todo"

Cobra now says:

 todo: invalid command [`--filename=somefile.txt` `add` `some todo`]

Would it be possible to make cobra look for flags before looking for commands?

No way to use echo/times examples

Hello,

Sorry for my silly question about your example but no way to use it .
What is the syntax please ? I use Hugo without problem and it is wonderful. Octopress was fun, Hugo is awesome ^_^

./client echo --times 10 "hello world" ?

Best regards,
Nicolas

Color Command?

This is a feature request. Maybe the commands will look better if we can add certain colors to each command. Something like this..

2015-03-01_22-25-59

Maybe use something like colors lib used in nodejs

User input

I am trying out cobra. It is going pretty well. One question.

I wanted to get some input from the user after a command started. I tried to use fmt.Scanf but it never blocked. I am guessing that the command run in a go routine.

My use case:

I have Search Command that queries and AIP and list out all search results in short form. I want to present a prompt to the user to be able to drill into one of the search results if they desire. This would basically be taking data from one of the search results and calling another command.

so I would ask what search result they want to drill into..

Is this possible. Maybe I am doing something wrong.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.