github.com/jduhamel/gcli@v0.2.4-0.20151019142748-0d5307cd7e21/skeleton/resource/tmpl/flag/cli.go.tmpl (about) 1 package main 2 3 import ( 4 "fmt" 5 "io" 6 "flag" 7 ) 8 9 // Exit codes are int values that represent an exit code for a particular error. 10 const ( 11 ExitCodeOK int = 0 12 ExitCodeError int = 1 + iota 13 ) 14 15 // CLI is the command line object 16 type CLI struct { 17 // outStream and errStream are the stdout and stderr 18 // to write message from the CLI. 19 outStream, errStream io.Writer 20 } 21 22 // Run invokes the CLI with the given arguments. 23 func (cli *CLI) Run(args []string) int { 24 var ( 25 {{ range .Flags }}{{ .VariableName }} {{ .TypeString }} 26 {{ end }} 27 version bool 28 ) 29 30 // Define option flag parse 31 flags := flag.NewFlagSet(Name, flag.ContinueOnError) 32 flags.SetOutput(cli.errStream) 33 34 {{ range .Flags }}{{ if eq .TypeString "string" }}flags.{{ title .TypeString}}Var(&{{ .VariableName }}, "{{ .LongName }}", "{{ .Default }}", "{{ .Description }}") 35 flags.{{ title .TypeString}}Var(&{{ .VariableName }}, "{{ .ShortName }}", "{{ .Default }}", "{{ .Description }}(Short)") 36 {{ else }}flags.{{ title .TypeString}}Var(&{{ .VariableName }}, "{{ .LongName }}", {{ .Default }}, "{{ .Description }}") 37 flags.{{ title .TypeString}}Var(&{{ .VariableName }}, "{{ .ShortName }}", {{ .Default }}, "{{ .Description }}(Short)"){{ end }} 38 {{ end }} 39 flags.BoolVar(&version, "version", false, "Print version information and quit.") 40 41 // Parse commandline flag 42 if err := flags.Parse(args[1:]); err != nil { 43 return ExitCodeError 44 } 45 46 // Show version 47 if version { 48 fmt.Fprintf(cli.errStream, "%s version %s\n", Name, Version) 49 return ExitCodeOK 50 } 51 52 {{ range .Flags }} 53 _ = {{ .VariableName }} 54 {{ end }} 55 56 return ExitCodeOK 57 }