cmd: fix complete flags name

This commit is contained in:
Eyal Posener 2017-05-20 22:15:37 +03:00
parent bc002bd8a7
commit 5ba73666ab
2 changed files with 18 additions and 13 deletions

View File

@ -13,7 +13,9 @@ import (
// CLI for command line
type CLI struct {
Name string
Name string
InstallName string
UninstallName string
install bool
uninstall bool
@ -30,10 +32,11 @@ const (
// install it or uninstall it.
func (f *CLI) Run() bool {
fs := flag.NewFlagSet(f.Name, 0)
// add flags and parse them in case they were not added and parsed
// by the main program
f.AddFlags(nil, "", "")
flag.Parse()
f.AddFlags(fs)
fs.Parse(os.Args[1:])
err := f.validate()
if err != nil {
@ -86,24 +89,24 @@ func (f *CLI) prompt() {
// If flags is nil, the default command line flags will be taken.
// Pass non-empty strings as installName and uninstallName to override the default
// flag names.
func (f *CLI) AddFlags(flags *flag.FlagSet, installName, uninstallName string) {
func (f *CLI) AddFlags(flags *flag.FlagSet) {
if flags == nil {
flags = flag.CommandLine
}
if installName == "" {
installName = defaultInstallName
if f.InstallName == "" {
f.InstallName = defaultInstallName
}
if uninstallName == "" {
uninstallName = defaultUninstallName
if f.UninstallName == "" {
f.UninstallName = defaultUninstallName
}
if flags.Lookup(installName) == nil {
flags.BoolVar(&f.install, installName, false,
if flags.Lookup(f.InstallName) == nil {
flags.BoolVar(&f.install, f.InstallName, false,
fmt.Sprintf("Install completion for %s command", f.Name))
}
if flags.Lookup(uninstallName) == nil {
flags.BoolVar(&f.uninstall, uninstallName, false,
if flags.Lookup(f.UninstallName) == nil {
flags.BoolVar(&f.uninstall, f.UninstallName, false,
fmt.Sprintf("Uninstall completion for %s command", f.Name))
}
if flags.Lookup("y") == nil {

View File

@ -28,7 +28,9 @@ func main() {
// it is possible to set custom flags name
// so when one will type 'self -h', he will see '-complete' to install the
// completion and -uncomplete to uninstall it.
cmp.AddFlags(nil, "complete", "uncomplete")
cmp.CLI.InstallName = "complete"
cmp.CLI.UninstallName = "uncomplete"
cmp.AddFlags(nil)
// parse the flags - both the program's flags and the completion flags
flag.Parse()