Merge pull request #11893 from runcom/11892-refactor-utils-flags

Refactor utils/flags.go
This commit is contained in:
Michael Crosby 2015-03-30 13:35:40 -07:00
commit f7cc7614c9

View file

@ -1054,6 +1054,42 @@ func (f *FlagSet) Parse(arguments []string) error {
return nil
}
// ParseFlags is a utility function that adds a help flag if withHelp is true,
// calls cmd.Parse(args) and prints a relevant error message if there are
// incorrect number of arguments. It returns error only if error handling is
// set to ContinueOnError and parsing fails. If error handling is set to
// ExitOnError, it's safe to ignore the return value.
func (cmd *FlagSet) ParseFlags(args []string, withHelp bool) error {
var help *bool
if withHelp {
help = cmd.Bool([]string{"#help", "-help"}, false, "Print usage")
}
if err := cmd.Parse(args); err != nil {
return err
}
if help != nil && *help {
cmd.Usage()
// just in case Usage does not exit
os.Exit(0)
}
if str := cmd.CheckArgs(); str != "" {
cmd.ReportError(str, withHelp)
}
return nil
}
func (cmd *FlagSet) ReportError(str string, withHelp bool) {
if withHelp {
if os.Args[0] == cmd.Name() {
str += ". See '" + os.Args[0] + " --help'"
} else {
str += ". See '" + os.Args[0] + " " + cmd.Name() + " --help'"
}
}
fmt.Fprintf(cmd.Out(), "docker: %s.\n", str)
os.Exit(1)
}
// Parsed reports whether f.Parse has been called.
func (f *FlagSet) Parsed() bool {
return f.parsed