English
Adding Option Groups to pflag: From a 30‑line Helper to a Reusable Library

Starting with an unreadable --help output
taggler is a YARA‑rule scanning tool. It is a single‑command application with no subcommands and fairly limited feature set. Once we reached ten command‑line options, its --help output looked like this:
Usage of taggler:
--config string Configuration file (default "config.json")
--exclude string Exclude pattern
--format string Output format (default "text")
--output string Output file (default "result.txt")
--recursive Walk directories recursively
--rules string Additional rules file
--threads int Number of concurrent workers (default 4)
--verbose Enable verbose mode
--yara-dir string Specify the YARA file in directory (default "yara")
--yara-name string Specify the YARA filename (default "global.yar")Ten flags, flattened in alphabetical order. The real problem is not the sheer count — it mixes three unrelated categories into one sort: YARA rule location, output configuration, and concurrency tuning. Users have to perform manual visual classification just to locate a single switch.
Here is what the grouped version looks like, with identical information content but vastly improved readability:
Usage: taggler [options] <target>
YARA Options:
--yara-dir string Specify the YARA file in directory (default: "yara")
--yara-name string Specify the YARA filename (default: "global.yar")
Output Options:
--output string Output file (default: "result.txt")
--verbose Enable verbose mode
Other Options:
--version Show version infoCobra developers may be familiar with grouping, but note: Cobra’s AddGroup groups subcommands, not individual flags. Under the hood, pflag is the flag‑parsing library powering Cobra. While pflag provides a field for grouping metadata, it implements zero grouping‑aware rendering logic itself.
pflag already leaves an extension point — no one consumes it
Examine the Flag struct, and you will spot a revealing final field:
type Flag struct {
Name string
Shorthand string
Usage string
Value Value
DefValue string
Changed bool
NoOptDefVal string
Deprecated string
Hidden bool
ShorthandDeprecated string
Annotations map[string][]string // Annotate flags with metadata
}Annotations is a map[string][]string. One key maps to multiple string values, making it naturally suited for assigning one flag into multiple groups. pflag exposes an API to write annotations:
flagSet.SetAnnotation("yara-dir", "group", []string{"YARA RULES"})If you inspect pflag’s rendering code, however: pflag never reads this field. FlagUsages() simply prints flags flat, ordered by SortFlags. Annotations has zero effect on built‑in help output.
This is a classic upstream‑provided extension slot: the data schema exists, but semantic interpretation is left for downstream consumers. Our task is to implement that consumer.
Minimal working implementation: 30 lines of code
The approach has two simple steps: tag flags with group metadata, then re‑render the usage text respecting those tags.
First, implement a helper method that prints flags per‑group:
package pflagshelper
import (
"fmt"
"os"
"sort"
flag "github.com/spf13/pflag"
)
type PFlagHelper struct {
spacing int
}
func NewPFlagHelper(spacing int) *PFlagHelper {
return &PFlagHelper{spacing: spacing}
}
// PrintFlagGroup prints all flags belonging to a specified group
func (f *PFlagHelper) PrintFlagGroup(flagSet *flag.FlagSet, groupName, title string) {
fmt.Fprintf(os.Stderr, "%s:\n", title)
var groupFlags []*flag.Flag
flagSet.VisitAll(func(flag *flag.Flag) {
if groups, ok := flag.Annotations["group"]; ok {
for _, g := range groups {
if g == groupName {
groupFlags = append(groupFlags, flag)
break
}
}
}
})
sort.Slice(groupFlags, func(i, j int) bool {
return groupFlags[i].Name < groupFlags[j].Name
})
for _, groupFlag := range groupFlags {
flagName := "--" + groupFlag.Name
if groupFlag.Value.Type() != "bool" {
flagName += " " + groupFlag.Value.Type()
}
defaultStr := ""
if groupFlag.DefValue != "" && groupFlag.DefValue != "false" && groupFlag.DefValue != "[]" {
if groupFlag.Value.Type() == "string" {
defaultStr = fmt.Sprintf(" (default: %q)", groupFlag.DefValue)
} else {
defaultStr = fmt.Sprintf(" (default: %v)", groupFlag.DefValue)
}
}
fmt.Fprintf(os.Stderr, " %-*s%s%s\n", f.spacing, flagName, groupFlag.Usage, defaultStr)
}
}Then assign group tags in your main program and override Usage:
const (
yaraGroup = "YARA RULES"
outputGroup = "OUTPUT OPTIONS"
otherGroup = "OTHER OPTIONS"
)
func main() {
flagSet := flag.NewFlagSet(os.Args[0], flag.ExitOnError)
helper := pflagshelper.NewPFlagHelper(25)
yaraDir := flagSet.String("yara-dir", "yara", "Specify the YARA file in directory")
yaraName := flagSet.String("yara-name", "global.yar", "Specify the YARA filename")
output := flagSet.String("output", "result.txt", "Output file")
verbose := flagSet.Bool("verbose", false, "Enable verbose mode")
showVersion := flagSet.Bool("version", false, "Show version info")
// Critical step: assign group annotations to flags
flagSet.SetAnnotation("yara-dir", "group", []string{yaraGroup})
flagSet.SetAnnotation("yara-name", "group", []string{yaraGroup})
flagSet.SetAnnotation("output", "group", []string{outputGroup})
flagSet.SetAnnotation("verbose", "group", []string{outputGroup})
flagSet.SetAnnotation("version", "group", []string{otherGroup})
flagSet.Usage = func() {
fmt.Fprintf(os.Stderr, "Usage: %s [options]\n\n", os.Args[0])
helper.PrintFlagGroup(flagSet, yaraGroup, "YARA Options")
helper.PrintFlagGroup(flagSet, outputGroup, "Output Options")
helper.PrintFlagGroup(flagSet, otherGroup, "Other Options")
fmt.Fprintf(os.Stderr, "\nGlobal Flags:\n -h, --help help for this command\n")
}
flagSet.Parse(os.Args[1:])
_, _, _, _, _ = yaraDir, yaraName, output, verbose, showVersion
}At this point you have working functionality. We use VisitAll to iterate all flags, filter by the Annotations["group"] tag, and apply column alignment via %-*s. That is roughly thirty lines of practical code。
Why use VisitAll instead of manually maintaining a flag list
VisitAll iterates over the complete internal flag collection of the FlagSet. This guarantees you will never accidentally omit a defined flag. The trade‑off is iteration order is locked to pflag’s lexicographical sorting. We will revisit this limitation later.
Seven missing pieces before production‑ready adoption
This minimal helper worked fine inside taggler. Problems surfaced only after copying it into a second and third project. Every item below reflects real‑world bugs encountered in practice.
1. Output writer hard‑coded to os.Stderr
Hard‑coded fmt.Fprintf(os.Stderr, …) creates two major pain points: you cannot easily write unit tests (capturing stderr is awkward), and you cannot send help output to stdout for workflows like myapp help > usage.txt.
The standard fix: inject an io.Writer as configuration:
type Renderer struct {
w io.Writer
}
func WithWriter(w io.Writer) Option {
return func(r *Renderer) { r.w = w }
}Testing becomes straightforward: instantiate with var buf bytes.Buffer; New(fs, WithWriter(&buf)), then assert against buf.String().
2. Short flag aliases get discarded
Our minimal implementation builds flag labels using only -- plus flag name. A flag defined as -v, --verbose would render as just --verbose. Users seeing -v in documentation but getting an error when using it creates a frustrating user experience。
func flagLabel(f *flag.Flag) string {
var b strings.Builder
if f.Shorthand != "" {
b.WriteString("-" + f.Shorthand + ", ")
}
b.WriteString("--" + f.Name)
if t := f.Value.Type(); t != "bool" {
b.WriteString(" " + t)
}
return b.String()
}3. Fixed column width breaks with long flag names
A hard‑coded WithSpacing(25) works fine for short flags like --yara-dir. Once you add something such as --exclude-pattern-file, alignment collapses completely。 The proper approach: scan all visible flags at render‑time to compute an adaptive maximum column width, while keeping a sensible minimum (24 in this implementation) to avoid cramped layouts for short flags。
width := MinColumnWidth
if auto {
for _, f := range visibleFlags {
if n := len(flagLabel(f)); n > width {
width = n
}
}
}You can still use WithColumnWidth(n) to enforce fixed width when stable cross‑version output is required。
4. Flags with no assigned group vanish silently from --help
This is the most dangerous pitfall。Our minimal renderer filters flags strictly by group name。Any flag missing a group annotation parses correctly at runtime but disappears entirely from help text。
These bugs produce zero visible failures in application behavior and often slip past test suites。Users will file GitHub issues asking “Where is the --stdout flag?”
Add safety with a catch‑all bucket: collect every flag not explicitly assigned into a fallback ungrouped section。
r.Group("yara", "YARA Options").Add("yara-dir", "yara-name")
r.Ungrouped("Other Options") // Flags without explicit groups land here instead of disappearing5. Misspelled flag names in SetAnnotation fail silently
pflag’s SetAnnotation internally calls Lookup。If you pass an unknown flag name, it simply returns without returning an error:
flagSet.SetAnnotation("yara-drr", "group", []string{yaraGroup}) // Typo: silent failureCombined with issue #4, misspelled assignments cause flags to disappear from help output。Our wrapper must add explicit validation:
func SetGroup(fs *flag.FlagSet, group string, names ...string) error {
for _, name := range names {
if fs.Lookup(name) == nil {
return fmt.Errorf("flaggroup: cannot annotate unknown flag %q (group %q)", name, group)
}
fs.SetAnnotation(name, AnnotationKey, []string{group})
}
return nil
}Pair this with WithStrictValidation() to validate flag existence and duplicate group assignments before rendering, shifting errors from runtime to development time。
6. Hidden and Deprecated flags are not respected
Internal debug flags like --profile or --pprof-addr are commonly marked MarkHidden。However, VisitAll iterates over hidden flags unconditionally。Our minimal renderer would print hidden flags, defeating the purpose of MarkHidden。
Similarly, pflag appends (DEPRECATED, …) notices for deprecated flags in its native output; custom rendering discards these warnings。Both behaviors must be re‑implemented in our renderer:
if f.Hidden {
continue // Skip hidden flags during resolution / rendering
}
if f.Deprecated != "" {
line += fmt.Sprintf(" (DEPRECATED: %s)", f.Deprecated)
}7. Default‑value detection relies on magic string literals
Original snippet:
if groupFlag.DefValue != "" && groupFlag.DefValue != "false" && groupFlag.DefValue != "[]" {DefValue is always a string。Comparing against literal strings to guess value type is error‑prone。A string flag whose legitimate default value is literally "false" or "[]" would have its default value incorrectly suppressed。 Inspect Value.Type() instead of raw string content:
switch typ := f.Value.Type(); typ {
case "bool":
if dv == "false" {
return ""
}
case "stringSlice", "stringArray":
if dv == "[]" {
return ""
}
}An easy‑to‑miss detail
pflag.FlagSet.VisitAll traverses flags in the ordering defined by SortFlags (enabled by default: alphabetical order), not the order flags are defined in source code。You cannot render flags in declaration order purely via pflag APIs。To achieve custom ordering within groups, explicitly supply flag member lists in your group API — which is why flaggroup’s Add preserves input sequence rather than re‑sorting。
flaggroup: package all learnings into a reusable library
After resolving these seven pitfalls, the helper graduates into a standalone library。I have open‑sourced it as flaggroup。It has zero transitive dependencies and only builds on top of pflag itself。The core API is concise。
Basic Usage
flaggroup.New(fs).
Group("input", "Input Options", "input").
Group("output", "Output Options").Add("output", "verbose").
Ungrouped("Other Options").
Apply()Apply() overrides fs.Usage。After calling it, --help output and usage messages triggered on parse errors will render with flag grouping automatically。
Two grouping patterns for different project structures
Pattern one: explicitly enumerate flag members at render time。 Best when flags are all defined in one file。The order you pass into Add determines display order:
r := flaggroup.New(fs)
r.Group("yara", "YARA Options").Add("yara-dir", "yara-name")
r.Group("output", "Output Options").Add("output", "workers", "verbose")Pattern two: assign annotations at flag‑definition time。 Useful for modular projects where flags are registered across multiple packages。Each module assigns group membership locally, and the renderer only declares group titles without enumerating members:
// Inside each module’s flag‑registration function
flaggroup.MustSetGroup(fs, "yara", "yara-dir", "yara-name")
// Rendering site: group without explicit members auto‑collects from annotations
r.Group("yara", "YARA Options")Both patterns can be mixed。Groups with explicit Add() members use that list; groups without member lists automatically collect flags by annotation。
Configuration Options
| Option | Purpose |
|---|---|
WithWriter(w) | Set output target; defaults to os.Stderr |
WithColumnWidth(n) | Force fixed column width, disables auto‑sizing |
WithHeading(text) | Custom top‑level usage header text |
WithFooter(text) | Append footer content (documentation links, feedback information) |
WithStrictValidation() | Validate flag names and group assignments before rendering |
Integrate into existing projects
Pure pflag‑based applications
Three‑step workflow: create your FlagSet, define groups, call Apply()。Minimal intrusion to existing code: only insert one chained call before Parse()。Your existing flag‑definition statements remain untouched。
fs := flag.NewFlagSet("myapp", flag.ExitOnError)
input := fs.String("input", "", "Input file path")
output := fs.String("output", "out.txt", "Output file")
verbose := fs.BoolP("verbose", "v", false, "Enable verbose mode")
flaggroup.New(fs,
flaggroup.WithHeading("Usage: myapp [options] <target>"),
flaggroup.WithFooter("Docs: [https://example.com/docs](https://example.com/docs)"),
).
Group("io", "I/O Options", "input", "output").
Ungrouped("Other Options").
Apply()
fs.Parse(os.Args[1:])Cobra‑based applications
Cobra’s built‑in Group works for subcommands only。To group flags, replace SetUsageFunc。Use c.Flags() which merges local flags and persistent flags:
rootCmd.SetUsageFunc(func(c *cobra.Command) error {
return flaggroup.New(c.Flags(),
flaggroup.WithHeading(fmt.Sprintf("Usage: %s [flags] [args]", c.CommandPath())),
).
Group("main", "Main Options", "yara-dir", "output").
Ungrouped("Other Options").
Render()
})Preserve native Cobra sections like command lists and Examples
SetUsageFunc replaces the complete usage template。If you assign it globally, you lose built‑in sections such as subcommand listings, Examples blocks, and environment‑variable documentation。Two mitigation strategies: override SetUsageFunc only for leaf commands that need grouped flags; alternatively keep the original template but inject a custom template function to render grouped flags alongside the original template content。
Unit‑testing grouped help output
Because the output writer is injectable, you avoid capturing stderr in tests:
func TestUngroupedFallback(t *testing.T) {
fs := newTestFlagSet()
var buf bytes.Buffer
err := New(fs, WithWriter(&buf)).
Group("yara", "YARA Options", "yara-dir").
Ungrouped("Other Options").
Render()
if err != nil {
t.Fatalf("Render() error = %v", err)
}
for _, name := range []string{"--stdout", "--verbose", "--workers"} {
if !strings.Contains(buf.String(), name) {
t.Errorf("ungrouped flag %s missing", name)
}
}
}Key design decisions
Why not fork pflag or send a PR upstream? pflag’s scope is a POSIX/GNU‑compliant flag parser。The existence of Annotations demonstrates upstream’s stance: store metadata, let downstream define semantics。Merging complex help‑rendering logic into pflag would add formatting maintenance burden to the parser library。A thin downstream wrapper keeps component boundaries clean。
Why does Render() return error instead of panicking? Cobra’s SetUsageFunc signature is func(*cobra.Command) error。Returning errors enables seamless integration with Cobra’s error flow。For pure pflag usages, use Apply() which discards the error return value。
Why skip printing group headers for empty groups? Displaying a section title with zero flags underneath is confusing for end‑users。Empty groups are omitted entirely。Combined with Ungrouped fallback logic, help output never contains empty placeholder sections。
Why avoid one‑shot fluent builder calls? Group configuration is often assembled across multiple source files and modules。Group() returns a *Group supporting incremental Add() calls; Ungrouped() returns the top‑level *Renderer to continue chaining configuration。Both granularities are supported。
Summary
pflag lacks native flag grouping support, yet all required data structures already exist: Annotations acts as a reserved metadata slot for downstream consumers。Enabling grouping consists of two high‑level steps:
- Assign metadata tags: use
SetAnnotation(name, "group", []string{group})or the wrappedSetGroupAPI to get proper error feedback。 - Take over help rendering: override
FlagSet.Usageand produce output ordered by your group tags。
The non‑trivial engineering effort lies not in those two steps, but handling all edge‑cases: injectable output writers, preserving short‑flag aliases, adaptive column width, fallback for ungrouped flags, validation for invalid flag references, respecting hidden and deprecated flags, and correct default‑value formatting。These details seem minor until you reuse your helper in a second project。
If you maintain a CLI tool with a growing number of flags, give flaggroup a try。If you prefer maintaining your own minimal helper, work through these seven gotchas in your implementation。