main.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. // Copyright 2019 Yunion
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package main
  15. import (
  16. "fmt"
  17. "os"
  18. "yunion.io/x/pkg/util/shellutils"
  19. "yunion.io/x/structarg"
  20. _ "yunion.io/x/onecloud/cmd/isocli/shell"
  21. )
  22. type BaseOptions struct {
  23. Debug bool `help:"debug mode"`
  24. SUBCOMMAND string `help:"aliyuncli subcommand" subcommand:"true"`
  25. }
  26. func getSubcommandParser() (*structarg.ArgumentParser, error) {
  27. parse, e := structarg.NewArgumentParserWithHelp(&BaseOptions{},
  28. "isocli",
  29. "Command-line ISO tools.",
  30. `See "isocli COMMAND --help" for help on a specific command.`)
  31. if e != nil {
  32. return nil, e
  33. }
  34. subcmd := parse.GetSubcommand()
  35. if subcmd == nil {
  36. return nil, fmt.Errorf("No subcommand argument.")
  37. }
  38. for _, v := range shellutils.CommandTable {
  39. _, e := subcmd.AddSubParserWithHelp(v.Options, v.Command, v.Desc, v.Callback)
  40. if e != nil {
  41. return nil, e
  42. }
  43. }
  44. return parse, nil
  45. }
  46. func showErrorAndExit(e error) {
  47. fmt.Fprintf(os.Stderr, "%s", e)
  48. fmt.Fprintln(os.Stderr)
  49. os.Exit(1)
  50. }
  51. func main() {
  52. parser, e := getSubcommandParser()
  53. if e != nil {
  54. showErrorAndExit(e)
  55. }
  56. e = parser.ParseArgs(os.Args[1:], false)
  57. if parser.IsHelpSet() {
  58. fmt.Print(parser.HelpString())
  59. return
  60. }
  61. subcmd := parser.GetSubcommand()
  62. subparser := subcmd.GetSubParser()
  63. if e != nil || subparser == nil {
  64. if subparser != nil {
  65. fmt.Print(subparser.Usage())
  66. } else {
  67. fmt.Print(parser.Usage())
  68. }
  69. showErrorAndExit(e)
  70. }
  71. suboptions := subparser.Options()
  72. e = subcmd.Invoke(suboptions)
  73. if e != nil {
  74. showErrorAndExit(e)
  75. }
  76. }