From 921da63e2ec60f485e9081953c1ea5aecc2b010a Mon Sep 17 00:00:00 2001 From: Jeremy Saenz Date: Sun, 14 Jul 2013 19:16:30 -0700 Subject: [PATCH] Support for global flags in help text --- cli.go | 7 ++++++- flag.go | 27 +++++++++++++++++++++++++++ help.go | 9 +++++++-- 3 files changed, 40 insertions(+), 3 deletions(-) create mode 100644 flag.go diff --git a/cli.go b/cli.go index d7c7628..419d342 100644 --- a/cli.go +++ b/cli.go @@ -1,6 +1,7 @@ package cli import "os" +import "flag" // The name of the program. Defaults to os.Args[0] var Name = os.Args[0] @@ -12,8 +13,11 @@ var Usage = "" var Version = "0.0.0" // List of commands to execute -var Commands []Command = nil +var Commands []Command +var Flags []Flag + +// The action to execute when no subcommands are specified var DefaultAction = ShowHelp func Run(args []string) { @@ -37,6 +41,7 @@ type Command struct { Usage string Description string Action Action + Flags flag.FlagSet } type Action func(name string) diff --git a/flag.go b/flag.go new file mode 100644 index 0000000..c619453 --- /dev/null +++ b/flag.go @@ -0,0 +1,27 @@ +package cli + +import "fmt" + +type Flag interface { + fmt.Stringer +} + +type BoolFlag struct { + Name string + Value bool + Usage string +} + +type StringFlag struct { + Name string + Value string + Usage string +} + +func (f StringFlag) String() string { + return fmt.Sprintf("--%v 'string'\t%v", f.Name, f.Usage) +} + +func (f BoolFlag) String() string { + return fmt.Sprintf("--%v\t%v", f.Name, f.Usage) +} diff --git a/help.go b/help.go index 55a3a7f..4acb6fa 100644 --- a/help.go +++ b/help.go @@ -7,8 +7,9 @@ import "text/template" type HelpData struct { Name string Usage string - Commands []Command Version string + Commands []Command + Flags []Flag } var HelpCommand = Command{ @@ -34,12 +35,16 @@ VERSION: COMMANDS: {{range .Commands}}{{.Name}}{{with .ShortName}}, {{.}}{{end}}{{ "\t" }}{{.Usage}} {{end}} +GLOBAL OPTIONS + {{range .Flags}}{{.}} + {{end}} ` data := HelpData{ Name, Usage, - append(Commands, HelpCommand), Version, + append(Commands, HelpCommand), + Flags, } w := tabwriter.NewWriter(os.Stdout, 0, 8, 1, '\t', 0)