@@ -53,6 +53,37 @@ type Command struct {
5353 Config * config.Config
5454}
5555
56+ // NewCommandSet creates and initializes a root *Command object. It automatically appends a "version" subcommand to
57+ // the list.
58+ func NewCommandSet (commands []* Command , short , usageLine , long string ) * Command {
59+ cmd := & Command {
60+ Short : short ,
61+ UsageLine : usageLine ,
62+ Long : long ,
63+ }
64+ verifyCommandDocs (cmd )
65+ pkg := strings .Split (cmd .Short , " " )[0 ]
66+ cmd .Commands = append (make ([]* Command , 0 , len (commands )+ 1 ), commands ... )
67+ cmd .Commands = append (cmd .Commands , newCmdVersion (pkg ))
68+
69+ cmd .Init ()
70+ return cmd
71+ }
72+
73+ func newCmdVersion (pkg string ) * Command {
74+ cmdVersion := & Command {
75+ Short : "version prints the version information" ,
76+ UsageLine : fmt .Sprintf ("%s version" , pkg ),
77+ Long : fmt .Sprintf ("Version prints version information for the %s binary." , pkg ),
78+ Action : func (ctx context.Context , cmd * Command ) error {
79+ fmt .Println (Version ())
80+ return nil
81+ },
82+ }
83+ cmdVersion .Init ()
84+ return cmdVersion
85+ }
86+
5687// Run executes the command with the provided arguments.
5788func (c * Command ) Run (ctx context.Context , args []string ) error {
5889 cmd , remaining , err := lookupCommand (c , args )
@@ -87,10 +118,7 @@ func (c *Command) Name() string {
87118}
88119
89120func (c * Command ) usage (w io.Writer ) {
90- if c .Short == "" || c .UsageLine == "" || c .Long == "" {
91- panic (fmt .Sprintf ("command %q is missing documentation" , c .Name ()))
92- }
93-
121+ verifyCommandDocs (c )
94122 fmt .Fprintf (w , "%s\n \n " , c .Long )
95123 fmt .Fprintf (w , "Usage:\n \n %s" , c .UsageLine )
96124 if len (c .Commands ) > 0 {
@@ -129,6 +157,12 @@ func hasFlags(fs *flag.FlagSet) bool {
129157 return visited
130158}
131159
160+ func verifyCommandDocs (c * Command ) {
161+ if c .Short == "" || c .UsageLine == "" || c .Long == "" {
162+ panic (fmt .Sprintf ("command %q is missing documentation" , c .Name ()))
163+ }
164+ }
165+
132166// lookupCommand looks up the command specified by the given arguments.
133167// It returns the command, the remaining arguments, and an error if the command
134168// is not found.
0 commit comments