Skip to content

Instantly share code, notes, and snippets.

@magickatt
Last active November 8, 2024 15:35
Show Gist options
  • Save magickatt/b7c650740dad6bf6dd96d2a82f9f5f4b to your computer and use it in GitHub Desktop.
Save magickatt/b7c650740dad6bf6dd96d2a82f9f5f4b to your computer and use it in GitHub Desktop.
Print usage for Cobra sub-commands
package cmd
import (
"fmt"
"os"
"text/tabwriter"
"github.com/you/your-project/cmd/testcmd"
"github.com/spf13/cobra"
)
var testCommand = &cobra.Command{
Use: "test",
Aliases: []string{"t"},
Short: "Testing this, that and t'other",
Long: `Testing various functionality for this application.`,
Run: func(cmd *cobra.Command, args []string) {
// Usage for this command
fmt.Printf(
"%s\n\nUsage:\n %s %s [subcommand]\n\nAvailable Subcommands:\n",
cmd.Long,
cmd.Root().Use,
cmd.Use,
)
// List of sub-commands
writer := tabwriter.NewWriter(os.Stdout, 0, 0, 1, ' ', 0)
for _, command := range cmd.Commands() {
fmt.Fprintf(writer, " %s\t%s\n", command.Use, command.Short)
}
writer.Flush()
},
}
func init() {
rootCommand.AddCommand(testCommand)
// Add any sub-commands under the "test" command
testCommand.AddCommand(testcmd.ReleaseCommand)
testCommand.AddCommand(testcmd.DeleteCommand)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment