This package has all info regarding commands structure. Made using Cobra Commander.
One subpackage per macro command (e.g. arduino lib
- "commands/lib/lib.go" arduino core
- "commands/core/core.go" etc…).
To add subCommands add a new file with a *cobra.Command var into the corresponding
package (e.g. 'arduino lib install' - "commands/lib/install.go").
var subCommand := &cobra.Command{
Use : "commandname [argument1] [argument2]",
Short : "Short description.",
Long : "Long description\n" +
"may be multiline too.",
Args: cobra.ExactArgs(2), // Specify how many arguments are accepted, see https://github.com/spf13/cobra#positional-and-custom-arguments
Run : runSubCommand, // Must be defined outside the struct.
}
func runSubCommand(cmd *cobra.Command, args []string) {
//do something.
}
Then into the init function of that file add the following lines:
func init() {
//....
command.AddCommand(subCommand) // "command" is the main command of the package.
}
It is possible to add flags to commands by using Flags() or GlobalFlags() functions of Cobra Commands.
) Define a struct per command with it’s fields (only one struct for global flags)
// GlobalFlags struct is defined in commands/commands.go.
var GlobalFlags struct {
//.... global flag fields.
Example int,
}
// subcommand.go
// subCommand flags to be defined in the same file as the command itself.
var commandFlags struct {
//.... command flag fields.
example2 int,
}
func init() {
//....
command.AddCommand(subCommand)
// The following lines add global flags and local flags respectively.
// Global flags can be accessed by any command.
subCommand.GlobalFlags().IntvarP(&commands.GlobalFlags.Example, ...)
subCommand.Flags().IntvarP(&commandFlags.example2, ...)
}