flagx

package module
v0.0.1 Latest Latest
Warning

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

Go to latest
Published: Oct 29, 2026 License: MIT Imports: 12 Imported by: 1

README

flagx

Test Status Coverage Status MIT License PkgGoDev

Small helpers for flag aliases and formatted help, built on Go's standard flag.FlagSet. No dependencies or changes to flag parsing.

Synopsis

fs := flag.NewFlagSet("myapp", flag.ExitOnError)

var output string
var verbose bool
var jobs int
var timeout time.Duration

flagx.StringVar(fs, &output, "output|o", "", "write to `file`")
flagx.BoolVar(fs, &verbose, "verbose|v", false, "verbose output")
flagx.IntVar(fs, &jobs, "jobs|j", 4, "number of `workers`")
flagx.DurationVar(fs, &timeout, "timeout|t", 30*time.Second, "timeout after `duration`")

fs.Usage = flagx.Usage(fs, "myapp [options] <input>", "Process input files.")
fs.Parse(os.Args[1:])

Import github.com/Songmu/flagx alongside flag, os, and time. Running myapp --help prints:

Usage: myapp [options] <input>

Process input files.

Options:
  -output, -o file       write to file
  -verbose, -v           verbose output
  -jobs, -j workers      number of workers (default 4)
  -timeout, -t duration  timeout after duration (default 30s)
  -help, -h              Show this help message

Description

StringVar, BoolVar, IntVar, and DurationVar register one or more |-separated names against the same variable. Var does the same for a custom flag.Value. Names omit leading hyphens and are split literally, without trimming whitespace. Empty names panic; duplicate and invalid names otherwise follow the standard library's behavior.

Names are aliases, not a required long/short pair: "output", "output|o", "o|output", "aa|bb", and "output|out|o" are all accepted. Help preserves the specified name order, so "o|output" displays as -o, -output string.

Both -output and --output work, as do -o and --o. Standard flag semantics still apply: parsing stops at the first positional argument, short flags cannot be bundled, and bool flags do not require a value.

Help combines names registered together and also values with the same pointer and concrete type, including flags registered directly through flag.FlagSet. Within each option, flagx-registered names retain their registration order; directly registered names follow, sorted long before short and lexicographically within each kind because their registration order is unavailable. All names have one hyphen.

Options registered through flagx come first, in registration order. Options registered only through FlagSet follow, sorted by their lexicographically smallest long name, or their smallest short name if there is no long name. An option combining both kinds of registration uses its first flagx registration position. The first displayed name supplies the usage and default value when aliases have different metadata.

Pointer-based grouping of separately registered flags is a heuristic. Non-pointer values and pointers to zero-sized values are grouped only when their names are registered together. Backquoted placeholders use flag.UnquoteUsage; bool placeholders are omitted. Nonzero registration-time defaults are shown, with string defaults quoted. Custom values are compared with their type's zero value; if its String method panics, the default is shown without interrupting help output.

help and h are not registered: standard flag handles undefined help names. The option list displays missing help names and preserves explicitly registered ones. An explicitly registered help flag has its normal parsing behavior, so the application is responsible for handling it.

Custom help

Use PrintDefaults to embed just the option list in your own help:

fs.Usage = func() {
    fmt.Fprintln(fs.Output(), "Usage: myapp [options] <input>")
    fmt.Fprintln(fs.Output(), "\nOptions:")
    flagx.PrintDefaults(fs)
}

Usage and PrintDefaults use the current fs.Output(), including later SetOutput changes. PrintUsage(w, fs, synopsis, description) writes a complete help message to an explicit writer without changing the flag set.

flagx does not manage subcommands, groups, required/hidden flags, or Markdown, man page, and shell completion generation.

Installation

% go get github.com/Songmu/flagx

Development

After changing GitHub Actions dependencies, run gh actions-lock and commit .github/workflows/actions.lock with the workflow changes. Install the tool with gh extension install github/gh-actions-lock.

Author

Songmu

Documentation

Overview

Package flagx adds flag aliases and formatted help to the standard library's flag.FlagSet without changing its parsing rules.

Example
package main

import (
	"flag"
	"fmt"
	"os"

	"github.com/Songmu/flagx"
)

func main() {
	fs := flag.NewFlagSet("myapp", flag.ContinueOnError)
	fs.SetOutput(os.Stdout)
	var output string
	var verbose bool
	flagx.StringVar(fs, &output, "output|o", "", "write to `file`")
	flagx.BoolVar(fs, &verbose, "verbose|v", false, "verbose output")
	fs.Usage = flagx.Usage(fs, "myapp [options] <input>", "Process input files.")
	if err := fs.Parse([]string{"-o", "result.txt", "--verbose", "input.txt"}); err != nil {
		return
	}
	fmt.Println(output, verbose, fs.Args())
	fs.Usage()
}
Output:
result.txt true [input.txt]
Usage: myapp [options] <input>

Process input files.

Options:
  -output, -o file  write to file
  -verbose, -v      verbose output
  -help, -h         Show this help message

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func BoolVar

func BoolVar(fs *flag.FlagSet, p *bool, names string, value bool, usage string)

BoolVar registers a boolean flag under the |-separated names, as in Var. All names write to p, which is initialized to value.

func DurationVar

func DurationVar(fs *flag.FlagSet, p *time.Duration, names string, value time.Duration, usage string)

DurationVar registers a duration flag under the |-separated names, as in Var. All names write to p, which is initialized to value.

func IntVar

func IntVar(fs *flag.FlagSet, p *int, names string, value int, usage string)

IntVar registers an integer flag under the |-separated names, as in Var. All names write to p, which is initialized to value.

func PrintDefaults

func PrintDefaults(fs *flag.FlagSet)

PrintDefaults writes only the formatted option list to fs.Output. Names registered together are displayed in their specified order. Options registered through flagx come first, in registration order, followed by directly registered options in lexical order. Pointers to non-zero-sized values with the same type and address are also displayed as aliases. Missing help and h names are included for flag's built-in help handling, not registered.

func PrintUsage

func PrintUsage(w io.Writer, fs *flag.FlagSet, synopsis, description string)

PrintUsage writes a synopsis, an optional description, and an Options section to w. It does not change fs or its output writer.

func StringVar

func StringVar(fs *flag.FlagSet, p *string, names, value, usage string)

StringVar registers a string flag under the |-separated names, as in Var. All names write to p, which is initialized to value.

func Usage

func Usage(fs *flag.FlagSet, synopsis, description string) func()

Usage returns a help function suitable for fs.Usage. It uses fs.Output at call time, including subsequent SetOutput changes.

func Var

func Var(fs *flag.FlagSet, value flag.Value, names, usage string)

Var registers value under each name in the |-separated names string. Names omit leading hyphens and are displayed in the specified order. Empty names panic; duplicate and invalid names follow flag.FlagSet behavior.

Types

This section is empty.

Jump to

Keyboard shortcuts

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