flaggroup

package module
v0.2.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 3, 2026 License: MIT Imports: 4 Imported by: 0

README

flaggroup

Grouped flag display for cobra commands. Organizes flags by functional groups for better help readability.

中文文档

Features

  • Grouped flag display
    • Use Add to define groups, use Patch to patch the template for grouped rendering
    • Groups display in Add call order; flags within a group display in add order, no re-sorting
    • Ungrouped flags are collected into an "Additional Flags" section (renameable), after all groups
  • Persistent flag support
    • Local flags, own persistent flags, and parent persistent flags can be mixed in the same group
    • No separate "Global Flags" section after patching; all flags are displayed in groups
  • Repeated calls
    • Multiple Add calls with the same group name merge automatically; flags append in add order
    • Adding the same flag to the same group is skipped (idempotent)
    • Assigning the same flag to a different group returns an error; a flag can only belong to one group
    • Non-existent flags return an error, preventing typos from being silently ignored

Installation

go get github.com/vvfock3r/cobra-flaggroup

Example

package main

import (
	"fmt"
	"os"
	"strings"

	"github.com/spf13/cobra"
	"github.com/vvfock3r/cobra-flaggroup"
)

var rootCmd = &cobra.Command{
	Use:   "app",
	Short: "My CLI application",
}

var addCmd = &cobra.Command{
	Use:   "add [flags] profile",
	Short: "Add something",
	Args:  cobra.MinimumNArgs(1),
	Run: func(cmd *cobra.Command, args []string) {
		fmt.Println("Add: " + strings.Join(args, " "))
	},
}

func init() {
	rootCmd.AddCommand(addCmd)

	// Persistent flags
	rootCmd.PersistentFlags().StringP("env", "e", "dev", "Environment")
	rootCmd.PersistentFlags().BoolP("verbose", "v", false, "Verbose output")

	// Input flags
	addCmd.Flags().StringP("file", "F", "", "Input file")
	addCmd.Flags().StringP("dir", "D", "", "Input directory")
	addCmd.Flags().StringArrayP("tags", "T", []string{}, "Tags")

	// Output flags
	addCmd.Flags().StringP("format", "f", "json", "Output format")
	addCmd.Flags().StringP("output", "o", "", "Output path")
	addCmd.Flags().BoolP("quiet", "q", false, "Quiet mode")

	// --------------------------------------------------------------------------------------

	// Root command grouping (InitDefaultHelpFlag registers the help flag for Add)
	rootCmd.InitDefaultHelpFlag()
	flaggroup.MustAdd(rootCmd, "My Flags", "env", "verbose", "help")
	flaggroup.MustPatch(rootCmd)

	// --------------------------------------------------------------------------------------

	// addCmd grouping (env is a persistent flag from root)
	flaggroup.MustAdd(addCmd, "Input Flags", "file", "dir", "tags")
	flaggroup.MustAdd(addCmd, "Output Flags", "format", "output", "quiet")
	flaggroup.MustAdd(addCmd, "Input Flags", "env")
	flaggroup.MustPatch(addCmd)
}

func main() {
	if err := rootCmd.Execute(); err != nil {
		os.Exit(1)
	}
}

Output:

$ go run . -h
My CLI application

Usage:
  app [command]

Available Commands:
  add         Add something
  completion  Generate the autocompletion script for the specified shell
  help        Help about any command

My Flags:
  -e, --env string   Environment (default "dev")
  -v, --verbose      Verbose output
  -h, --help         help for app

Use "app [command] --help" for more information about a command.
$ go run . add -h
Add something

Usage:
  app add [flags] profile

Input Flags:
  -F, --file string        Input file
  -D, --dir string         Input directory
  -T, --tags stringArray   Tags
  -e, --env string         Environment (default "dev")

Output Flags:
  -f, --format string      Output format (default "json")
  -o, --output string      Output path
  -q, --quiet              Quiet mode

Additional Flags:
  -h, --help               help for add
  -v, --verbose            Verbose output

API

Add(cmd *cobra.Command, groupName string, flags ...string) error /

MustAdd(cmd *cobra.Command, groupName string, flags ...string)

Add adds a flag group to a command. Same-name groups merge; duplicate flags within the same group are skipped (idempotent).

MustAdd panics on error, suitable for use in init().

Error conditions:

  • Flag does not exist on the command

  • Flag is already assigned to another group

flaggroup.MustAdd(cmd, "Network Options", "host", "port", "timeout")
flaggroup.MustAdd(cmd, "Output Options", "format", "output", "verbose")

// Non-existent flag — returns error
err := flaggroup.Add(cmd, "Group", "config", "nonexistent", "output")
// err: flaggroup: flag "nonexistent" not found on command "app"

// Flag assigned to a different group — returns error
flaggroup.Add(cmd, "Input Options", "config")
flaggroup.Add(cmd, "Output Options", "config")
// err: flaggroup: flag "config" already in group "Input Options"

// Same group, same flag — idempotent, returns nil
flaggroup.Add(cmd, "Input Options", "config")
flaggroup.Add(cmd, "Input Options", "config") // nil

Patch(cmd *cobra.Command) error /

MustPatch(cmd *cobra.Command)

Patches the command's usage template for grouped flag display. MustPatch panics on error, and also panics if no groups are defined. Calling multiple times on the same command is safe. MustPatch must be called after all Add calls.

Error conditions:

  1. Custom template missing the Flags: section
  2. Cobra version changed the default template structure
flaggroup.MustPatch(cmd)

// Graceful error handling
if err := flaggroup.Patch(cmd); err != nil {
    // handle error
}

SetDefaultGroupName(name string)

Sets the name for ungrouped flags. Default is "Additional Flags".

flaggroup.SetDefaultGroupName("Other Options")

License

MIT

Documentation

Overview

Package flaggroup provides grouped flag display for cobra commands.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Add

func Add(cmd *cobra.Command, groupName string, flags ...string) error

Add adds flags to a named group on cmd. Same-name groups merge; same-group duplicates are skipped. Returns error if a flag doesn't exist or is already in another group.

func MustAdd

func MustAdd(cmd *cobra.Command, groupName string, flags ...string)

MustAdd is like Add but panics on error.

func MustPatch

func MustPatch(cmd *cobra.Command)

MustPatch is like Patch but panics on error or if no groups are defined.

func Patch

func Patch(cmd *cobra.Command) error

Patch patches cmd's usage template to render grouped flags. Returns error if template cannot be patched.

func SetDefaultGroupName

func SetDefaultGroupName(name string)

SetDefaultGroupName sets the name for ungrouped flags. Default is "Additional Flags".

Types

This section is empty.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL