github.com/nguyentm83/docker@v1.5.0/utils/flags.go (about)

     1  package utils
     2  
     3  import (
     4  	"fmt"
     5  	"os"
     6  
     7  	flag "github.com/docker/docker/pkg/mflag"
     8  )
     9  
    10  // ParseFlags is a utility function that adds a help flag if withHelp is true,
    11  // calls cmd.Parse(args) and prints a relevant error message if there are
    12  // incorrect number of arguments. It returns error only if error handling is
    13  // set to ContinueOnError and parsing fails. If error handling is set to
    14  // ExitOnError, it's safe to ignore the return value.
    15  // TODO: move this to a better package than utils
    16  func ParseFlags(cmd *flag.FlagSet, args []string, withHelp bool) error {
    17  	var help *bool
    18  	if withHelp {
    19  		help = cmd.Bool([]string{"#help", "-help"}, false, "Print usage")
    20  	}
    21  	if err := cmd.Parse(args); err != nil {
    22  		return err
    23  	}
    24  	if help != nil && *help {
    25  		cmd.Usage()
    26  		// just in case Usage does not exit
    27  		os.Exit(0)
    28  	}
    29  	if str := cmd.CheckArgs(); str != "" {
    30  		ReportError(cmd, str, withHelp)
    31  	}
    32  	return nil
    33  }
    34  
    35  func ReportError(cmd *flag.FlagSet, str string, withHelp bool) {
    36  	if withHelp {
    37  		if os.Args[0] == cmd.Name() {
    38  			str += ". See '" + os.Args[0] + " --help'"
    39  		} else {
    40  			str += ". See '" + os.Args[0] + " " + cmd.Name() + " --help'"
    41  		}
    42  	}
    43  	fmt.Fprintf(cmd.Out(), "docker: %s.\n", str)
    44  	os.Exit(1)
    45  }