yunion.io/x/cloudmux@v0.3.10-0-alpha.1/cmd/cmx/main.go (about)

     1  package main
     2  
     3  import (
     4  	"fmt"
     5  	"os"
     6  
     7  	"yunion.io/x/pkg/errors"
     8  	"yunion.io/x/structarg"
     9  
    10  	"yunion.io/x/cloudmux/cmd/cmx/shell"
    11  	_ "yunion.io/x/cloudmux/pkg/multicloud/loader"
    12  )
    13  
    14  func getSubcommandParser() (*structarg.ArgumentParser, error) {
    15  	parse, err := structarg.NewArgumentParserWithHelp(&shell.GlobalOptions{},
    16  		"cmuxcli",
    17  		"Command-line interface to cloudmux API.",
    18  		`See "cmuxcli COMMAND --help" for help on a specific command.`)
    19  	if err != nil {
    20  		return nil, err
    21  	}
    22  
    23  	subcmd := parse.GetSubcommand()
    24  	if subcmd == nil {
    25  		return nil, errors.Errorf("No subcommand argument.")
    26  	}
    27  
    28  	for _, v := range *shell.CommandTable {
    29  		if _, err := subcmd.AddSubParserWithHelp(v.Options, v.Command, v.Desc, v.Callback); err != nil {
    30  			return nil, err
    31  		}
    32  	}
    33  
    34  	return parse, nil
    35  }
    36  
    37  func showErrorAndExit(e error) {
    38  	fmt.Fprintf(os.Stderr, "%s", e)
    39  	fmt.Fprintln(os.Stderr)
    40  	os.Exit(1)
    41  }
    42  
    43  func main() {
    44  	parser, e := getSubcommandParser()
    45  	if e != nil {
    46  		showErrorAndExit(e)
    47  	}
    48  	e = parser.ParseArgs(os.Args[1:], false)
    49  	options := parser.Options().(*shell.GlobalOptions)
    50  
    51  	if parser.IsHelpSet() {
    52  		fmt.Print(parser.HelpString())
    53  		return
    54  	}
    55  	subcmd := parser.GetSubcommand()
    56  	subparser := subcmd.GetSubParser()
    57  	if e != nil || subparser == nil {
    58  		if subparser != nil {
    59  			fmt.Print(subparser.Usage())
    60  		} else {
    61  			fmt.Print(parser.Usage())
    62  		}
    63  		showErrorAndExit(e)
    64  		return
    65  	}
    66  	suboptions := subparser.Options()
    67  	if subparser.IsHelpSet() {
    68  		fmt.Print(subparser.HelpString())
    69  		return
    70  	}
    71  	provider, e := shell.NewCloudProvider(options)
    72  	if e != nil {
    73  		showErrorAndExit(e)
    74  	}
    75  
    76  	if e := subcmd.Invoke(provider, suboptions); e != nil {
    77  		showErrorAndExit(e)
    78  	}
    79  }