flaggy

package module
v1.8.0 Latest Latest
Warning

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

Go to latest
Published: Oct 4, 2025 License: Unlicense Imports: 17 Imported by: 203

README


Sensible and fast command-line flag parsing with excellent support for subcommands and positional values. Flags can be at any position. Flaggy has no required project or package layout like Cobra requires, and no external dependencies!

Check out the go doc, examples directory, and examples in this readme to get started quickly. You can also read the Flaggy introduction post with helpful examples on my weblog.

Installation

go get -u github.com/integrii/flaggy

Key Features

  • Very easy to use (see examples below)
  • 35 different flag types supported
  • Any flag can be at any position
  • Pretty and readable help output by default
  • Positional subcommands
  • Positional parameters
  • Suggested subcommands when a subcommand is typo'd
  • Nested subcommands
  • Both global and subcommand specific flags
  • Both global and subcommand specific positional parameters
  • Customizable help templates for both the global command and subcommands
  • Customizable appended/prepended help messages for both the global command and subcommands
  • Simple function that displays help followed by a custom message string
  • Flags and subcommands may have both a short and long name
  • Unlimited trailing arguments after a --
  • Flags can use a single dash or double dash (--flag, -flag, -f, --f)
  • Flags can have = assignment operators, or use a space (--flag=value, --flag value)
  • Flags support single quote globs with spaces (--flag 'this is all one value')
  • Flags of slice types can be passed multiple times (-f one -f two -f three).
  • Optional but default version output with --version
  • Optional but default help output with -h or --help
  • Optional but default help output when any invalid or unknown parameter is passed
  • bash, zsh, fish, PowerShell, and Nushell shell completion generation by default
  • It's fast. All flag and subcommand parsing takes less than 1ms in most programs.

Example Help Output

testCommand - Description goes here.  Get more information at http://flaggy.
This is a prepend for help

  Usage:
    testCommand [subcommandA|subcommandB|subcommandC] [testPositionalA] [testPositionalB]

  Positional Variables:
    testPositionalA   Test positional A does some things with a positional value. (Required)
    testPositionalB   Test positional B does some less than serious things with a positional value.

  Subcommands:
    subcommandA (a)   Subcommand A is a command that does stuff
    subcommandB (b)   Subcommand B is a command that does other stuff
    subcommandC (c)   Subcommand C is a command that does SERIOUS stuff

  Flags:
       --version        Displays the program version string.
    -h --help           Displays help with available flag, subcommand, and positional value parameters.
    -s --stringFlag     This is a test string flag that does some stringy string stuff.
    -i --intFlg         This is a test int flag that does some interesting int stuff. (default: 5)
    -b --boolFlag       This is a test bool flag that does some booly bool stuff. (default: true)
    -d --durationFlag   This is a test duration flag that does some untimely stuff. (default: 1h23s)

This is an append for help
This is a help add-on message

Super Simple Example

./yourApp -f test

// Declare variables and their defaults
var stringFlag = "defaultValue"

// Add a flag
flaggy.String(&stringFlag, "f", "flag", "A test string flag")

// Parse the flag
flaggy.Parse()

// Use the flag
print(stringFlag)

Example with Subcommand

./yourApp subcommandExample -f test

// Declare variables and their defaults
var stringFlag = "defaultValue"

// Create the subcommand
subcommand := flaggy.NewSubcommand("subcommandExample")

// Add a flag to the subcommand
subcommand.String(&stringFlag, "f", "flag", "A test string flag")

// Add the subcommand to the parser at position 1
flaggy.AttachSubcommand(subcommand, 1)

// Parse the subcommand and all flags
flaggy.Parse()

// Use the flag
print(stringFlag)

Example with Nested Subcommands, Various Flags and Trailing Arguments

./yourApp subcommandExample --flag=5 nestedSubcommand -t test -y -- trailingArg

// Declare variables and their defaults
var stringFlagF = "defaultValueF"
var intFlagT = 3
var boolFlagB bool

// Create the subcommands
subcommandExample := flaggy.NewSubcommand("subcommandExample")
nestedSubcommand := flaggy.NewSubcommand("nestedSubcommand")

// Add a flag to both subcommands
subcommandExample.String(&stringFlagF, "t", "testFlag", "A test string flag")
nestedSubcommand.Int(&intFlagT, "f", "flag", "A test int flag")

// add a global bool flag for fun
flaggy.Bool(&boolFlagB, "y", "yes", "A sample boolean flag")

// attach the nested subcommand to the parent subcommand at position 1
subcommandExample.AttachSubcommand(nestedSubcommand, 1)
// attach the base subcommand to the parser at position 1
flaggy.AttachSubcommand(subcommandExample, 1)

// Parse everything, then use the flags and trailing arguments
flaggy.Parse()
print(stringFlagF)
print(intFlagT)
print(boolFlagB)
print(flaggy.TrailingArguments[0])

Supported Flag Types

Flaggy has specific flag types for all basic Go types as well as slice variants, plus a selection of helpful standard library structures. You can target any of the following assignments when defining a flag:

  • Text and truthy values: string, []string, bool, []bool
  • Signed integers: int, int64, int32, int16, int8, and a slice form for each type
  • Unsigned integers: uint, uint64, uint32, uint16, uint8 (aka byte), and slice forms for each type
  • Floating point numbers: float64, float32, and slices of both precisions
  • Time utilities: time.Duration, []time.Duration, time.Time, time.Location, time.Month, time.Weekday
  • Network primitives: net.IP, []net.IP, net.HardwareAddr, []net.HardwareAddr, net.IPMask, []net.IPMask, net.IPNet, net.TCPAddr, net.UDPAddr
  • Modern IP types: netip.Addr, netip.Prefix, netip.AddrPort
  • URLs and filesystem helpers: url.URL, os.FileMode
  • Pattern and math types: regexp.Regexp, big.Int, big.Rat
  • Encoded byte helpers: Base64Bytes (a base64-decoded []byte)

Shell Completion

Flaggy generates bash, zsh, fish, PowerShell, and Nushell completion scripts automatically.

# Bash
source <(./app completion bash)

# Zsh
source <(./app completion zsh)

# Fish
./app completion fish | source

# PowerShell
./app completion powershell | Out-String | Invoke-Expression

# Nushell
./app completion nushell | save --force ~/.cache/app-completions.nu
source ~/.cache/app-completions.nu

An Example Program

Best practice when using flaggy includes setting your program's name, description, and version (at build time) as shown in this example program.

package main

import "github.com/integrii/flaggy"

// Make a variable for the version which will be set at build time.
var version = "unknown"

// Keep subcommands as globals so you can easily check if they were used later on.
var mySubcommand *flaggy.Subcommand

// Setup the variables you want your incoming flags to set.
var testVar string

// If you would like an environment variable as the default for a value, just populate the flag
// with the value of the environment by default.  If the flag corresponding to this value is not
// used, then it will not be changed.
var myVar = os.Getenv("MY_VAR")


func init() {
  // Set your program's name and description.  These appear in help output.
  flaggy.SetName("Test Program")
  flaggy.SetDescription("A little example program")

  // You can disable various things by changing bools on the default parser
  // (or your own parser if you have created one).
  flaggy.DefaultParser.ShowHelpOnUnexpected = false

  // You can set a help prepend or append on the default parser.
  flaggy.DefaultParser.AdditionalHelpPrepend = "http://github.com/integrii/flaggy"
  
  // Add a flag to the main program (this will be available in all subcommands as well).
  flaggy.String(&testVar, "tv", "testVariable", "A variable just for testing things!")

  // Create any subcommands and set their parameters.
  mySubcommand = flaggy.NewSubcommand("mySubcommand")
  mySubcommand.Description = "My great subcommand!"
  
  // Add a flag to the subcommand.
  mySubcommand.String(&myVar, "mv", "myVariable", "A variable just for me!")

  // Set the version and parse all inputs into variables.
  flaggy.SetVersion(version)
  flaggy.Parse()
}

func main(){
    if mySubcommand.Used {
      ...
    }
}

Then, you can use the following build command to set the version variable in the above program at build time.

# build your app and set the version string
$ go build -ldflags='-X main.version=1.0.3-a3db3'
$ ./yourApp version
Version: 1.0.3-a3db3
$ ./yourApp --help
Test Program - A little example program
http://github.com/integrii/flaggy

Contributions

Please feel free to open an issue if you find any bugs or see any features that make sense. Pull requests will be reviewed and accepted if they make sense, but it is always wise to submit a proposal issue before any major changes.

Documentation

Overview

Package flaggy is a input flag parsing package that supports recursive subcommands, positional values, and any-position flags without unnecessary complexeties.

For a getting started tutorial and full feature list, check out the readme at https://github.com/integrii/flaggy.

Example

Example shows how to add string flags in your program.

package main

import (
	"fmt"
	"os"

	"github.com/integrii/flaggy"
)

func main() {

	// Simulate some input from the CLI.  Don't do this in your program.
	flaggy.ResetParser()
	os.Args = []string{"binaryName", "-f", "flagName"}

	// Imagine the following program usage:
	//
	// ./binaryName -f flagName
	// or
	// ./binaryName --flag=flagName

	// add a string flag at the global level
	var stringFlag string
	flaggy.String(&stringFlag, "f", "flag", "A test string flag")

	// Parse the input arguments from the OS (os.Args)
	flaggy.Parse()

	// see if our flag was set properly
	if stringFlag == "flagName" {
		fmt.Println("Flag set to:", stringFlag)
	}
}
Output:

Flag set to: flagName

Index

Examples

Constants

This section is empty.

Variables

View Source
var DebugMode bool

DebugMode indicates that debug output should be enabled

View Source
var DefaultHelpTemplate = defaultHelpTemplate

DefaultHelpTemplate is the help template that will be used for newly created subcommands and commands

View Source
var PanicInsteadOfExit bool

PanicInsteadOfExit is used when running tests

View Source
var TrailingArguments []string

TrailingArguments holds trailing arguments in the main parser after parsing has been run.

Functions

func AddPositionalValue

func AddPositionalValue(assignmentVar *string, name string, relativePosition int, required bool, description string)

AddPositionalValue adds a positional value to the main parser at the global context

func AttachSubcommand

func AttachSubcommand(subcommand *Subcommand, relativePosition int)

AttachSubcommand adds a subcommand for parsing

func BigInt added in v1.6.0

func BigInt(assignmentVar *big.Int, shortName string, longName string, description string)

BigInt adds a new big.Int flag.

func BigRat added in v1.6.0

func BigRat(assignmentVar *big.Rat, shortName string, longName string, description string)

BigRat adds a new big.Rat flag.

func Bool

func Bool(assignmentVar *bool, shortName string, longName string, description string)

Bool adds a new bool flag

Example

ExampleBoolFlag shows how to global bool flags in your program.

package main

import (
	"fmt"
	"os"

	"github.com/integrii/flaggy"
)

func main() {

	// Simulate some input from the CLI.  Don't do these two lines in your program.
	flaggy.ResetParser()
	os.Args = []string{"binaryName", "-f"}

	// Imagine the following program usage:
	//
	// ./binaryName -f
	// or
	// ./binaryName --flag=true

	// add a bool flag at the global level
	var boolFlag bool
	flaggy.Bool(&boolFlag, "f", "flag", "A test bool flag")

	// Parse the input arguments from the OS (os.Args)
	flaggy.Parse()

	// see if our flag was set properly
	if boolFlag == true {
		fmt.Println("Flag set")
	}
}
Output:

Flag set

func BoolSlice

func BoolSlice(assignmentVar *[]bool, shortName string, longName string, description string)

BoolSlice adds a new slice of bools flag Specify the flag multiple times to fill the slice

func ByteSlice

func ByteSlice(assignmentVar *[]byte, shortName string, longName string, description string)

ByteSlice adds a new slice of bytes flag Specify the flag multiple times to fill the slice. Takes hex as input.

func BytesBase64 added in v1.6.0

func BytesBase64(assignmentVar *Base64Bytes, shortName string, longName string, description string)

BytesBase64 adds a new []byte flag parsed from base64 input.

func DisableCompletion added in v1.6.0

func DisableCompletion()

DisableCompletion disallows shell autocomplete outputs to be generated.

func Duration

func Duration(assignmentVar *time.Duration, shortName string, longName string, description string)

Duration adds a new time.Duration flag. Input format is described in time.ParseDuration(). Example values: 1h, 1h50m, 32s

func DurationSlice

func DurationSlice(assignmentVar *[]time.Duration, shortName string, longName string, description string)

DurationSlice adds a new time.Duration flag. Input format is described in time.ParseDuration(). Example values: 1h, 1h50m, 32s Specify the flag multiple times to fill the slice.

func EnableCompletion added in v1.6.0

func EnableCompletion()

EnableCompletion enables shell autocomplete outputs to be generated.

func FileMode added in v1.6.0

func FileMode(assignmentVar *os.FileMode, shortName string, longName string, description string)

FileMode adds a new os.FileMode flag parsed from octal/decimal (base auto-detected).

func Float32

func Float32(assignmentVar *float32, shortName string, longName string, description string)

Float32 adds a new float32 flag.

func Float32Slice

func Float32Slice(assignmentVar *[]float32, shortName string, longName string, description string)

Float32Slice adds a new float32 flag. Specify the flag multiple times to fill the slice.

func Float64

func Float64(assignmentVar *float64, shortName string, longName string, description string)

Float64 adds a new float64 flag.

func Float64Slice

func Float64Slice(assignmentVar *[]float64, shortName string, longName string, description string)

Float64Slice adds a new float64 flag. Specify the flag multiple times to fill the slice.

func GenerateBashCompletion added in v1.6.0

func GenerateBashCompletion(p *Parser) string

GenerateBashCompletion returns a bash completion script for the parser.

func GenerateFishCompletion added in v1.8.0

func GenerateFishCompletion(p *Parser) string

GenerateFishCompletion returns a fish completion script for the parser.

func GenerateNushellCompletion added in v1.8.0

func GenerateNushellCompletion(p *Parser) string

GenerateNushellCompletion returns a Nushell completion script for the parser.

func GeneratePowerShellCompletion added in v1.8.0

func GeneratePowerShellCompletion(p *Parser) string

GeneratePowerShellCompletion returns a PowerShell completion script for the parser.

func GenerateZshCompletion added in v1.6.0

func GenerateZshCompletion(p *Parser) string

GenerateZshCompletion returns a zsh completion script for the parser.

func HardwareAddr

func HardwareAddr(assignmentVar *net.HardwareAddr, shortName string, longName string, description string)

HardwareAddr adds a new net.HardwareAddr flag.

func HardwareAddrSlice

func HardwareAddrSlice(assignmentVar *[]net.HardwareAddr, shortName string, longName string, description string)

HardwareAddrSlice adds a new net.HardwareAddr slice flag. Specify the flag multiple times to fill the slice.

func IP

func IP(assignmentVar *net.IP, shortName string, longName string, description string)

IP adds a new net.IP flag.

func IPMask

func IPMask(assignmentVar *net.IPMask, shortName string, longName string, description string)

IPMask adds a new net.IPMask flag. IPv4 Only.

func IPMaskSlice

func IPMaskSlice(assignmentVar *[]net.IPMask, shortName string, longName string, description string)

IPMaskSlice adds a new net.HardwareAddr slice flag. IPv4 only. Specify the flag multiple times to fill the slice.

func IPNet added in v1.6.0

func IPNet(assignmentVar *net.IPNet, shortName string, longName string, description string)

IPNet adds a new net.IPNet flag parsed from CIDR.

func IPSlice

func IPSlice(assignmentVar *[]net.IP, shortName string, longName string, description string)

IPSlice adds a new int8 slice flag. Specify the flag multiple times to fill the slice.

func Int

func Int(assignmentVar *int, shortName string, longName string, description string)

Int adds a new int flag

Example

ExampleIntFlag shows how to global int flags in your program.

package main

import (
	"fmt"
	"os"

	"github.com/integrii/flaggy"
)

func main() {

	// Simulate some input from the CLI.  Don't do these two lines in your program.
	flaggy.ResetParser()
	os.Args = []string{"binaryName", "-f", "5"}

	// Imagine the following program usage:
	//
	// ./binaryName -f 5
	// or
	// ./binaryName --flag=5

	// add a int flag at the global level
	var intFlag int
	flaggy.Int(&intFlag, "f", "flag", "A test int flag")

	// Parse the input arguments from the OS (os.Args)
	flaggy.Parse()

	// see if our flag was set properly
	if intFlag == 5 {
		fmt.Println("Flag set to:", intFlag)
	}
}
Output:

Flag set to: 5

func Int8

func Int8(assignmentVar *int8, shortName string, longName string, description string)

Int8 adds a new int8 flag

func Int8Slice

func Int8Slice(assignmentVar *[]int8, shortName string, longName string, description string)

Int8Slice adds a new int8 slice flag. Specify the flag multiple times to fill the slice.

func Int16

func Int16(assignmentVar *int16, shortName string, longName string, description string)

Int16 adds a new int16 flag

func Int16Slice

func Int16Slice(assignmentVar *[]int16, shortName string, longName string, description string)

Int16Slice adds a new int16 slice flag. Specify the flag multiple times to fill the slice.

func Int32

func Int32(assignmentVar *int32, shortName string, longName string, description string)

Int32 adds a new int32 flag

func Int32Slice

func Int32Slice(assignmentVar *[]int32, shortName string, longName string, description string)

Int32Slice adds a new int32 slice flag. Specify the flag multiple times to fill the slice.

func Int64

func Int64(assignmentVar *int64, shortName string, longName string, description string)

Int64 adds a new int64 flag

func Int64Slice

func Int64Slice(assignmentVar *[]int64, shortName string, longName string, description string)

Int64Slice adds a new int64 slice flag. Specify the flag multiple times to fill the slice.

func IntSlice

func IntSlice(assignmentVar *[]int, shortName string, longName string, description string)

IntSlice adds a new int slice flag. Specify the flag multiple times to fill the slice.

func Location added in v1.6.0

func Location(assignmentVar *time.Location, shortName string, longName string, description string)

Location adds a new time.Location flag.

func Month added in v1.6.0

func Month(assignmentVar *time.Month, shortName string, longName string, description string)

Month adds a new time.Month flag.

func NetipAddr added in v1.6.0

func NetipAddr(assignmentVar *netip.Addr, shortName string, longName string, description string)

NetipAddr adds a new netip.Addr flag.

func NetipAddrPort added in v1.6.0

func NetipAddrPort(assignmentVar *netip.AddrPort, shortName string, longName string, description string)

NetipAddrPort adds a new netip.AddrPort flag.

func NetipPrefix added in v1.6.0

func NetipPrefix(assignmentVar *netip.Prefix, shortName string, longName string, description string)

NetipPrefix adds a new netip.Prefix flag.

func Parse

func Parse()

Parse parses flags as requested in the default package parser. All trailing arguments that result from parsing are placed in the global TrailingArguments variable.

func ParseArgs

func ParseArgs(args []string)

ParseArgs parses the passed args as if they were the arguments to the running binary. Targets the default main parser for the package. All trailing arguments are set in the global TrailingArguments variable.

func Regexp added in v1.6.0

func Regexp(assignmentVar *regexp.Regexp, shortName string, longName string, description string)

Regexp adds a new regexp.Regexp flag.

func ResetParser

func ResetParser()

ResetParser resets the default parser to a fresh instance. Uses the name of the binary executing as the program name by default.

func SetDescription

func SetDescription(description string)

SetDescription sets the description of the default package command parser

func SetName

func SetName(name string)

SetName sets the name of the default package command parser

func SetVersion

func SetVersion(version string)

SetVersion sets the version of the default package command parser

func ShowHelp

func ShowHelp(message string)

ShowHelp shows parser help

func ShowHelpAndExit

func ShowHelpAndExit(message string)

ShowHelpAndExit shows parser help and exits with status code 2

func ShowHelpOnUnexpectedDisable added in v1.4.0

func ShowHelpOnUnexpectedDisable()

ShowHelpOnUnexpectedDisable disables the ShowHelpOnUnexpected behavior on the default parser. This causes unknown inputs to error out.

func ShowHelpOnUnexpectedEnable added in v1.4.0

func ShowHelpOnUnexpectedEnable()

ShowHelpOnUnexpectedEnable enables the ShowHelpOnUnexpected behavior on the default parser. This causes unknown inputs to error out.

func SortFlagsByLongName added in v1.6.0

func SortFlagsByLongName()

SortFlagsByLongName enables alphabetical sorting of flags by long name in help output on the default parser.

func SortFlagsByLongNameReversed added in v1.6.0

func SortFlagsByLongNameReversed()

SortFlagsByLongNameReversed enables reverse alphabetical sorting of flags by long name in help output on the default parser.

func String

func String(assignmentVar *string, shortName string, longName string, description string)

String adds a new string flag

func StringSlice

func StringSlice(assignmentVar *[]string, shortName string, longName string, description string)

StringSlice adds a new slice of strings flag Specify the flag multiple times to fill the slice

Example

ExampleStringSlice shows how to gather repeated flag values into a slice of strings. This example fulfills the "ExampleSliceString" request by showing how repeated string flags build a slice of values.

package main

import (
	"fmt"
	"os"

	"github.com/integrii/flaggy"
)

func main() {

	// Reset the parser and describe the command so that --help output is clear
	// for new users experimenting with the example.
	flaggy.ResetParser()
	flaggy.DefaultParser.Description = "Stores every -a/--add value in a slice."
	flaggy.DefaultParser.AdditionalHelpPrepend = "Usage: ./app -a <value> [-a <value> ...]"
	flaggy.DefaultParser.AdditionalHelpAppend = "Example: ./app -a test -a another -a again"

	// Simulate invoking the binary as `./app -a test -a another -a again`.
	os.Args = []string{"app", "-a", "test", "-a", "another", "-a", "again"}

	var sliceFlag []string
	flaggy.StringSlice(&sliceFlag, "a", "add", "Collect values for this slice")

	flaggy.Parse()

	fmt.Printf("String slice has %d items:\n", len(sliceFlag))
	for index, value := range sliceFlag {
		fmt.Printf("  %d. %s\n", index+1, value)
	}
}
Output:

String slice has 3 items:
  1. test
  2. another
  3. again

func TCPAddr added in v1.6.0

func TCPAddr(assignmentVar *net.TCPAddr, shortName string, longName string, description string)

TCPAddr adds a new net.TCPAddr flag parsed from host:port.

func Time added in v1.6.0

func Time(assignmentVar *time.Time, shortName string, longName string, description string)

Time adds a new time.Time flag. Supports RFC3339/RFC3339Nano, RFC1123, and unix seconds.

func UDPAddr added in v1.6.0

func UDPAddr(assignmentVar *net.UDPAddr, shortName string, longName string, description string)

UDPAddr adds a new net.UDPAddr flag parsed from host:port.

func UInt

func UInt(assignmentVar *uint, shortName string, longName string, description string)

UInt adds a new uint flag

func UInt8

func UInt8(assignmentVar *uint8, shortName string, longName string, description string)

UInt8 adds a new uint8 flag

func UInt8Slice

func UInt8Slice(assignmentVar *[]uint8, shortName string, longName string, description string)

UInt8Slice adds a new uint8 slice flag. Specify the flag multiple times to fill the slice.

func UInt16

func UInt16(assignmentVar *uint16, shortName string, longName string, description string)

UInt16 adds a new uint16 flag

func UInt16Slice

func UInt16Slice(assignmentVar *[]uint16, shortName string, longName string, description string)

UInt16Slice adds a new uint16 slice flag. Specify the flag multiple times to fill the slice.

func UInt32

func UInt32(assignmentVar *uint32, shortName string, longName string, description string)

UInt32 adds a new uint32 flag

func UInt32Slice

func UInt32Slice(assignmentVar *[]uint32, shortName string, longName string, description string)

UInt32Slice adds a new uint32 slice flag. Specify the flag multiple times to fill the slice.

func UInt64

func UInt64(assignmentVar *uint64, shortName string, longName string, description string)

UInt64 adds a new uint64 flag

func UInt64Slice

func UInt64Slice(assignmentVar *[]uint64, shortName string, longName string, description string)

UInt64Slice adds a new uint64 slice flag. Specify the flag multiple times to fill the slice.

func UIntSlice

func UIntSlice(assignmentVar *[]uint, shortName string, longName string, description string)

UIntSlice adds a new uint slice flag. Specify the flag multiple times to fill the slice.

func URL added in v1.6.0

func URL(assignmentVar *url.URL, shortName string, longName string, description string)

URL adds a new url.URL flag.

func Weekday added in v1.6.0

func Weekday(assignmentVar *time.Weekday, shortName string, longName string, description string)

Weekday adds a new time.Weekday flag.

Types

type ArgumentParser

type ArgumentParser interface {
	SetValueForKey(key string, value string) (bool, error)
}

ArgumentParser represents a parser or subcommand

type Base64Bytes added in v1.6.0

type Base64Bytes []byte

Base64Bytes is a []byte interpreted as base64 when parsed from flags.

type Flag

type Flag struct {
	ShortName   string
	LongName    string
	Description string

	Hidden        bool // indicates this flag should be hidden from help and suggestions
	AssignmentVar interface{}
	// contains filtered or unexported fields
}

Flag holds the base methods for all flag types

func (*Flag) HasName

func (f *Flag) HasName(name string) bool

HasName indicates that this flag's short or long name matches the supplied name string

type Help

type Help struct {
	Subcommands    []HelpSubcommand
	Positionals    []HelpPositional
	Flags          []HelpFlag
	GlobalFlags    []HelpFlag
	UsageString    string
	CommandName    string
	PrependMessage string
	AppendMessage  string
	ShowCompletion bool
	Message        string
	Description    string
	Lines          []string
}

Help represents the values needed to render a Help page

func (*Help) ExtractValues

func (h *Help) ExtractValues(p *Parser, message string)

ExtractValues extracts Help template values from a subcommand and its parent parser. The parser is required in order to detect default flag settings for help and version output.

type HelpFlag

type HelpFlag struct {
	ShortName    string
	LongName     string
	Description  string
	DefaultValue string
	ShortDisplay string
	LongDisplay  string
}

HelpFlag is used to template string flag Help output

type HelpPositional

type HelpPositional struct {
	Name         string
	Description  string
	Required     bool
	Position     int
	DefaultValue string
	Spacer       string
}

HelpPositional is used to template positional Help output

type HelpSubcommand

type HelpSubcommand struct {
	ShortName   string
	LongName    string
	Description string
	Position    int
	Spacer      string
}

HelpSubcommand is used to template subcommand Help output

type Parser

type Parser struct {
	Subcommand
	Version                    string             // the optional version of the parser.
	ShowHelpWithHFlag          bool               // display help when -h or --help passed
	ShowVersionWithVersionFlag bool               // display the version when --version passed
	ShowHelpOnUnexpected       bool               // display help when an unexpected flag or subcommand is passed
	TrailingArguments          []string           // everything after a -- is placed here
	HelpTemplate               *template.Template // template for Help output

	ShowCompletion   bool // indicates that bash and zsh completion output is possible
	SortFlags        bool // when true, help output flags are sorted alphabetically
	SortFlagsReverse bool // when true with SortFlags, sort order is reversed (Z..A)
	// contains filtered or unexported fields
}

Parser represents the set of flags and subcommands we are expecting from our input arguments. Parser is the top level struct responsible for parsing an entire set of subcommands and flags.

var DefaultParser *Parser

DefaultParser is the default parser that is used with the package-level public functions

func NewParser

func NewParser(name string) *Parser

NewParser creates a new ArgumentParser ready to parse inputs

func (*Parser) Completion added in v1.6.0

func (p *Parser) Completion(completionType string)

Completion takes in a shell type and outputs the completion script for that shell.

func (*Parser) DisableShowVersionWithVersion

func (p *Parser) DisableShowVersionWithVersion()

DisableShowVersionWithVersion disables the showing of version information with --version. It is enabled by default.

func (*Parser) Parse

func (p *Parser) Parse() error

Parse calculates all flags and subcommands

func (*Parser) ParseArgs

func (p *Parser) ParseArgs(args []string) error

ParseArgs parses as if the passed args were the os.Args, but without the binary at the 0 position in the array. An error is returned if there is a low level issue converting flags to their proper type. No error is returned for invalid arguments or missing require subcommands.

func (*Parser) SetHelpTemplate

func (p *Parser) SetHelpTemplate(tmpl string) error

SetHelpTemplate sets the go template this parser will use when rendering Help.

func (*Parser) ShowHelp

func (p *Parser) ShowHelp()

ShowHelp shows Help without an error message

func (*Parser) ShowHelpAndExit

func (p *Parser) ShowHelpAndExit(message string)

ShowHelpAndExit shows parser help and exits with status code 2

func (*Parser) ShowHelpWithMessage

func (p *Parser) ShowHelpWithMessage(message string)

ShowHelpWithMessage shows the Help for this parser with an optional string error message as a header. The supplied subcommand will be the context of Help displayed to the user.

func (*Parser) ShowVersionAndExit

func (p *Parser) ShowVersionAndExit()

ShowVersionAndExit shows the version of this parser

func (*Parser) SortFlagsByLongName added in v1.6.0

func (p *Parser) SortFlagsByLongName()

SortFlagsByLongName enables alphabetical sorting by long flag name (case-insensitive) for help output on this parser.

func (*Parser) SortFlagsByLongNameReversed added in v1.6.0

func (p *Parser) SortFlagsByLongNameReversed()

SortFlagsByLongNameReversed enables reverse alphabetical sorting by long flag name (case-insensitive) for help output on this parser.

func (*Parser) TrailingSubcommand added in v1.5.1

func (p *Parser) TrailingSubcommand() *Subcommand

TrailingSubcommand returns the last and most specific subcommand invoked.

type PositionalValue

type PositionalValue struct {
	Name          string // used in documentation only
	Description   string
	AssignmentVar *string // the var that will get this variable
	Position      int     // the position, not including switches, of this variable
	Required      bool    // this subcommand must always be specified
	Found         bool    // was this positional found during parsing?
	Hidden        bool    // indicates this positional value should be hidden from help
	// contains filtered or unexported fields
}

PositionalValue represents a value which is determined by its position relative to where a subcommand was detected.

Example

ExamplePositionalValue shows how to add positional variables at the global level.

package main

import (
	"fmt"
	"os"

	"github.com/integrii/flaggy"
)

func main() {

	// Simulate some input from the CLI.  Don't do this in your program.
	flaggy.ResetParser()
	os.Args = []string{"binaryName", "positionalValue"}

	// Imagine the following program usage:
	//
	// ./binaryName positionalValue

	// add a bool flag at the global level
	var stringVar string
	flaggy.AddPositionalValue(&stringVar, "positionalVar", 1, false, "A test positional flag")

	// Parse the input arguments from the OS (os.Args)
	flaggy.Parse()

	// see if our flag was set properly
	if stringVar == "positionalValue" {
		fmt.Println("Flag set to", stringVar)
	}
}
Output:

Flag set to positionalValue

type Subcommand

type Subcommand struct {
	Name                  string
	ShortName             string
	Description           string
	Position              int // the position of this subcommand, not including flags
	Subcommands           []*Subcommand
	Flags                 []*Flag
	PositionalFlags       []*PositionalValue
	ParsedValues          []parsedValue // a list of values and positionals parsed
	AdditionalHelpPrepend string        // additional prepended message when Help is displayed
	AdditionalHelpAppend  string        // additional appended message when Help is displayed
	Used                  bool          // indicates this subcommand was found and parsed
	Hidden                bool          // indicates this subcommand should be hidden from help
}

Subcommand represents a subcommand which contains a set of child subcommands along with a set of flags relevant to it. Parsing runs until a subcommand is detected by matching its name and position. Once a matching subcommand is found, the next set of parsing occurs within that matched subcommand.

Example

ExampleSubcommand shows usage of subcommands in flaggy.

package main

import (
	"fmt"
	"os"

	"github.com/integrii/flaggy"
)

func main() {

	// Do not include the following two lines in your real program, it is for this
	// example only:
	flaggy.ResetParser()
	os.Args = []string{"programName", "-v", "VariableHere", "subcommandName", "subcommandPositional", "--", "trailingVar"}

	// Imagine the input to this program is as follows:
	//
	// ./programName subcommandName -v VariableHere subcommandPositional -- trailingVar
	//   or
	// ./programName subcommandName subcommandPositional --variable VariableHere -- trailingVar
	//   or
	// ./programName subcommandName --variable=VariableHere subcommandPositional -- trailingVar
	//   or even
	// ./programName subcommandName subcommandPositional -v=VariableHere -- trailingVar
	//

	// Create a new subcommand to attach flags and other subcommands to.  It must be attached
	// to something before being used.
	newSC := flaggy.NewSubcommand("subcommandName")

	// Attach a string variable to the subcommand
	var subcommandVariable string
	newSC.String(&subcommandVariable, "v", "variable", "A test variable.")

	var subcommandPositional string
	newSC.AddPositionalValue(&subcommandPositional, "testPositionalVar", 1, false, "A test positional variable to a subcommand.")

	// Attach the subcommand to the parser. This will panic if another
	// positional value or subcommand is already present at the depth supplied.
	// Later you can check if this command was used with a simple bool (newSC.Used).
	flaggy.AttachSubcommand(newSC, 1)

	// Parse the input arguments from the OS (os.Args)
	flaggy.Parse()

	// see if the subcommand was found during parsing:
	if newSC.Used {
		// Do subcommand operations here
		fmt.Println("Subcommand used")

		// check the input on your subcommand variable
		if subcommandVariable == "VariableHere" {
			fmt.Println("Subcommand variable set correctly")
		}

		// Print the subcommand positional value
		fmt.Println("Subcommand Positional:", subcommandPositional)

		// Print the first trailing argument
		fmt.Println("Trailing variable 1:", flaggy.TrailingArguments[0])
	}
}
Output:

Subcommand used
Subcommand variable set correctly
Subcommand Positional: subcommandPositional
Trailing variable 1: trailingVar

func NewSubcommand

func NewSubcommand(name string) *Subcommand

NewSubcommand creates a new subcommand that can have flags or PositionalFlags added to it. The position starts with 1, not 0

func (*Subcommand) AddPositionalValue

func (sc *Subcommand) AddPositionalValue(assignmentVar *string, name string, relativePosition int, required bool, description string)

AddPositionalValue adds a positional value to the subcommand. the relativePosition starts at 1 and is relative to the subcommand it belongs to

Example

ExampleSubcommand_AddPositionalValue adds two levels of subcommands with a positional value on the second level one

package main

import (
	"fmt"
	"os"

	"github.com/integrii/flaggy"
)

func main() {

	// Simulate some input from the CLI.  Don't do this in your program.
	flaggy.ResetParser()
	os.Args = []string{"binaryName", "subcommandA", "subcommandB", "subcommandBPositionalValue"}

	// Imagine the following program usage:
	//
	// ./binaryName subcommandA subcommandB subcommandBPositional
	//

	var subcommandBPositional string

	// create a subcommand
	subcommandA := flaggy.NewSubcommand("subcommandA")
	// add the subcommand at relative position 1 within the default root parser
	flaggy.AttachSubcommand(subcommandA, 1)

	// create a second subcommand
	subcommandB := flaggy.NewSubcommand("subcommandB")
	// add the second subcommand to the first subcommand as a child at relative
	// position 1
	subcommandA.AttachSubcommand(subcommandB, 1)
	// add a positional to the second subcommand with a relative position of 1
	subcommandB.AddPositionalValue(&subcommandBPositional, "subcommandTestPositonalValue", 1, false, "A test positional input variable")

	// Parse the input arguments from the OS (os.Args) using the default parser
	flaggy.Parse()

	// see if our flag was set properly
	fmt.Println("Positional flag set to", subcommandBPositional)
}
Output:

Positional flag set to subcommandBPositionalValue

func (*Subcommand) AttachSubcommand

func (sc *Subcommand) AttachSubcommand(newSC *Subcommand, relativePosition int)

AttachSubcommand adds a possible subcommand to the Parser.

func (*Subcommand) BigInt added in v1.6.0

func (sc *Subcommand) BigInt(assignmentVar *big.Int, shortName string, longName string, description string)

BigInt adds a new big.Int flag.

func (*Subcommand) BigRat added in v1.6.0

func (sc *Subcommand) BigRat(assignmentVar *big.Rat, shortName string, longName string, description string)

BigRat adds a new big.Rat flag.

func (*Subcommand) Bool

func (sc *Subcommand) Bool(assignmentVar *bool, shortName string, longName string, description string)

Bool adds a new bool flag

func (*Subcommand) BoolSlice

func (sc *Subcommand) BoolSlice(assignmentVar *[]bool, shortName string, longName string, description string)

BoolSlice adds a new slice of bools flag Specify the flag multiple times to fill the slice

func (*Subcommand) ByteSlice

func (sc *Subcommand) ByteSlice(assignmentVar *[]byte, shortName string, longName string, description string)

ByteSlice adds a new slice of bytes flag Specify the flag multiple times to fill the slice. Takes hex as input.

func (*Subcommand) BytesBase64 added in v1.6.0

func (sc *Subcommand) BytesBase64(assignmentVar *Base64Bytes, shortName string, longName string, description string)

BytesBase64 adds a new []byte flag parsed from base64 input.

func (*Subcommand) Duration

func (sc *Subcommand) Duration(assignmentVar *time.Duration, shortName string, longName string, description string)

Duration adds a new time.Duration flag. Input format is described in time.ParseDuration(). Example values: 1h, 1h50m, 32s

func (*Subcommand) DurationSlice

func (sc *Subcommand) DurationSlice(assignmentVar *[]time.Duration, shortName string, longName string, description string)

DurationSlice adds a new time.Duration flag. Input format is described in time.ParseDuration(). Example values: 1h, 1h50m, 32s Specify the flag multiple times to fill the slice.

func (*Subcommand) FileMode added in v1.6.0

func (sc *Subcommand) FileMode(assignmentVar *os.FileMode, shortName string, longName string, description string)

FileMode adds a new os.FileMode flag parsed from octal/decimal (base auto-detected).

func (*Subcommand) FlagExists

func (sc *Subcommand) FlagExists(name string) bool

FlagExists lets you know if the flag name exists as either a short or long name in the (sub)command

func (*Subcommand) Float32

func (sc *Subcommand) Float32(assignmentVar *float32, shortName string, longName string, description string)

Float32 adds a new float32 flag.

func (*Subcommand) Float32Slice

func (sc *Subcommand) Float32Slice(assignmentVar *[]float32, shortName string, longName string, description string)

Float32Slice adds a new float32 flag. Specify the flag multiple times to fill the slice.

func (*Subcommand) Float64

func (sc *Subcommand) Float64(assignmentVar *float64, shortName string, longName string, description string)

Float64 adds a new float64 flag.

func (*Subcommand) Float64Slice

func (sc *Subcommand) Float64Slice(assignmentVar *[]float64, shortName string, longName string, description string)

Float64Slice adds a new float64 flag. Specify the flag multiple times to fill the slice.

func (*Subcommand) HardwareAddr

func (sc *Subcommand) HardwareAddr(assignmentVar *net.HardwareAddr, shortName string, longName string, description string)

HardwareAddr adds a new net.HardwareAddr flag.

func (*Subcommand) HardwareAddrSlice

func (sc *Subcommand) HardwareAddrSlice(assignmentVar *[]net.HardwareAddr, shortName string, longName string, description string)

HardwareAddrSlice adds a new net.HardwareAddr slice flag. Specify the flag multiple times to fill the slice.

func (*Subcommand) IP

func (sc *Subcommand) IP(assignmentVar *net.IP, shortName string, longName string, description string)

IP adds a new net.IP flag.

func (*Subcommand) IPMask

func (sc *Subcommand) IPMask(assignmentVar *net.IPMask, shortName string, longName string, description string)

IPMask adds a new net.IPMask flag. IPv4 Only.

func (*Subcommand) IPMaskSlice

func (sc *Subcommand) IPMaskSlice(assignmentVar *[]net.IPMask, shortName string, longName string, description string)

IPMaskSlice adds a new net.HardwareAddr slice flag. IPv4 only. Specify the flag multiple times to fill the slice.

func (*Subcommand) IPNet added in v1.6.0

func (sc *Subcommand) IPNet(assignmentVar *net.IPNet, shortName string, longName string, description string)

IPNet adds a new net.IPNet flag parsed from CIDR.

func (*Subcommand) IPSlice

func (sc *Subcommand) IPSlice(assignmentVar *[]net.IP, shortName string, longName string, description string)

IPSlice adds a new int8 slice flag. Specify the flag multiple times to fill the slice.

func (*Subcommand) Int

func (sc *Subcommand) Int(assignmentVar *int, shortName string, longName string, description string)

Int adds a new int flag

func (*Subcommand) Int8

func (sc *Subcommand) Int8(assignmentVar *int8, shortName string, longName string, description string)

Int8 adds a new int8 flag

func (*Subcommand) Int8Slice

func (sc *Subcommand) Int8Slice(assignmentVar *[]int8, shortName string, longName string, description string)

Int8Slice adds a new int8 slice flag. Specify the flag multiple times to fill the slice.

func (*Subcommand) Int16

func (sc *Subcommand) Int16(assignmentVar *int16, shortName string, longName string, description string)

Int16 adds a new int16 flag

func (*Subcommand) Int16Slice

func (sc *Subcommand) Int16Slice(assignmentVar *[]int16, shortName string, longName string, description string)

Int16Slice adds a new int16 slice flag. Specify the flag multiple times to fill the slice.

func (*Subcommand) Int32

func (sc *Subcommand) Int32(assignmentVar *int32, shortName string, longName string, description string)

Int32 adds a new int32 flag

func (*Subcommand) Int32Slice

func (sc *Subcommand) Int32Slice(assignmentVar *[]int32, shortName string, longName string, description string)

Int32Slice adds a new int32 slice flag. Specify the flag multiple times to fill the slice.

func (*Subcommand) Int64

func (sc *Subcommand) Int64(assignmentVar *int64, shortName string, longName string, description string)

Int64 adds a new int64 flag.

func (*Subcommand) Int64Slice

func (sc *Subcommand) Int64Slice(assignmentVar *[]int64, shortName string, longName string, description string)

Int64Slice adds a new int64 slice flag. Specify the flag multiple times to fill the slice.

func (*Subcommand) IntSlice

func (sc *Subcommand) IntSlice(assignmentVar *[]int, shortName string, longName string, description string)

IntSlice adds a new int slice flag. Specify the flag multiple times to fill the slice.

func (*Subcommand) Location added in v1.6.0

func (sc *Subcommand) Location(assignmentVar *time.Location, shortName string, longName string, description string)

Location adds a new time.Location flag.

func (*Subcommand) Month added in v1.6.0

func (sc *Subcommand) Month(assignmentVar *time.Month, shortName string, longName string, description string)

Month adds a new time.Month flag.

func (*Subcommand) NetipAddr added in v1.6.0

func (sc *Subcommand) NetipAddr(assignmentVar *netip.Addr, shortName string, longName string, description string)

NetipAddr adds a new netip.Addr flag.

func (*Subcommand) NetipAddrPort added in v1.6.0

func (sc *Subcommand) NetipAddrPort(assignmentVar *netip.AddrPort, shortName string, longName string, description string)

NetipAddrPort adds a new netip.AddrPort flag.

func (*Subcommand) NetipPrefix added in v1.6.0

func (sc *Subcommand) NetipPrefix(assignmentVar *netip.Prefix, shortName string, longName string, description string)

NetipPrefix adds a new netip.Prefix flag.

func (*Subcommand) Regexp added in v1.6.0

func (sc *Subcommand) Regexp(assignmentVar *regexp.Regexp, shortName string, longName string, description string)

Regexp adds a new regexp.Regexp flag.

func (*Subcommand) SetValueForKey

func (sc *Subcommand) SetValueForKey(key string, value string) (bool, error)

SetValueForKey sets the value for the specified key. If setting a bool value, then send "true" or "false" as strings. The returned bool indicates that a value was set.

func (*Subcommand) String

func (sc *Subcommand) String(assignmentVar *string, shortName string, longName string, description string)

String adds a new string flag

func (*Subcommand) StringSlice

func (sc *Subcommand) StringSlice(assignmentVar *[]string, shortName string, longName string, description string)

StringSlice adds a new slice of strings flag Specify the flag multiple times to fill the slice

func (*Subcommand) TCPAddr added in v1.6.0

func (sc *Subcommand) TCPAddr(assignmentVar *net.TCPAddr, shortName string, longName string, description string)

TCPAddr adds a new net.TCPAddr flag parsed from host:port.

func (*Subcommand) Time added in v1.6.0

func (sc *Subcommand) Time(assignmentVar *time.Time, shortName string, longName string, description string)

Time adds a new time.Time flag. Supports RFC3339/RFC3339Nano, RFC1123, and unix seconds.

func (*Subcommand) UDPAddr added in v1.6.0

func (sc *Subcommand) UDPAddr(assignmentVar *net.UDPAddr, shortName string, longName string, description string)

UDPAddr adds a new net.UDPAddr flag parsed from host:port.

func (*Subcommand) UInt

func (sc *Subcommand) UInt(assignmentVar *uint, shortName string, longName string, description string)

UInt adds a new uint flag

func (*Subcommand) UInt8

func (sc *Subcommand) UInt8(assignmentVar *uint8, shortName string, longName string, description string)

UInt8 adds a new uint8 flag

func (*Subcommand) UInt8Slice

func (sc *Subcommand) UInt8Slice(assignmentVar *[]uint8, shortName string, longName string, description string)

UInt8Slice adds a new uint8 slice flag. Specify the flag multiple times to fill the slice.

func (*Subcommand) UInt16

func (sc *Subcommand) UInt16(assignmentVar *uint16, shortName string, longName string, description string)

UInt16 adds a new uint16 flag

func (*Subcommand) UInt16Slice

func (sc *Subcommand) UInt16Slice(assignmentVar *[]uint16, shortName string, longName string, description string)

UInt16Slice adds a new uint16 slice flag. Specify the flag multiple times to fill the slice.

func (*Subcommand) UInt32

func (sc *Subcommand) UInt32(assignmentVar *uint32, shortName string, longName string, description string)

UInt32 adds a new uint32 flag

func (*Subcommand) UInt32Slice

func (sc *Subcommand) UInt32Slice(assignmentVar *[]uint32, shortName string, longName string, description string)

UInt32Slice adds a new uint32 slice flag. Specify the flag multiple times to fill the slice.

func (*Subcommand) UInt64

func (sc *Subcommand) UInt64(assignmentVar *uint64, shortName string, longName string, description string)

UInt64 adds a new uint64 flag

func (*Subcommand) UInt64Slice

func (sc *Subcommand) UInt64Slice(assignmentVar *[]uint64, shortName string, longName string, description string)

UInt64Slice adds a new uint64 slice flag. Specify the flag multiple times to fill the slice.

func (*Subcommand) UIntSlice

func (sc *Subcommand) UIntSlice(assignmentVar *[]uint, shortName string, longName string, description string)

UIntSlice adds a new uint slice flag. Specify the flag multiple times to fill the slice.

func (*Subcommand) URL added in v1.6.0

func (sc *Subcommand) URL(assignmentVar *url.URL, shortName string, longName string, description string)

URL adds a new url.URL flag.

func (*Subcommand) Weekday added in v1.6.0

func (sc *Subcommand) Weekday(assignmentVar *time.Weekday, shortName string, longName string, description string)

Weekday adds a new time.Weekday flag.

Directories

Path Synopsis
examples
complex command
customParser command
customTemplate command
positionalValue command
simple command
sliceFlag command
subcommand command

Jump to

Keyboard shortcuts

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