or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

advanced-features.mdflag-access.mdflag-definition.mdflag-types.mdflagset-methods.mdgo-integration.mdindex.mdusage-help.md
tile.json

tessl/golang-github-com-spf13--pflag

Drop-in replacement for Go's flag package implementing POSIX/GNU-style command-line flags with extensive type support and advanced features

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
golangpkg:golang/github.com/spf13/pflag@v1.0.10

To install, run

npx @tessl/cli install tessl/golang-github-com-spf13--pflag@1.0.0

index.mddocs/

pflag

pflag is a drop-in replacement for Go's flag package, implementing POSIX/GNU-style --flags. It provides comprehensive command-line flag parsing with support for both short (-f) and long (--flag) forms, extensive type support, and advanced features like flag normalization, deprecation, and hidden flags.

Package Information

  • Package Name: github.com/spf13/pflag
  • Package Type: golang
  • Language: Go
  • Installation: go get github.com/spf13/pflag
  • Version: v1.0.10

Core Imports

import "github.com/spf13/pflag"

Or as drop-in replacement for standard flag package:

import flag "github.com/spf13/pflag"

Basic Usage

package main

import (
	"fmt"
	"github.com/spf13/pflag"
)

func main() {
	// Define flags
	var name = pflag.String("name", "World", "name to greet")
	var verbose = pflag.BoolP("verbose", "v", false, "enable verbose output")
	var count = pflag.Int("count", 1, "number of times to greet")

	// Parse command line
	pflag.Parse()

	// Use flag values
	for i := 0; i < *count; i++ {
		if *verbose {
			fmt.Printf("Greeting %d: ", i+1)
		}
		fmt.Printf("Hello, %s!\n", *name)
	}
}

Architecture

pflag organizes command-line parsing around several core concepts:

FlagSet

A FlagSet represents a set of defined flags. The package provides a global CommandLine FlagSet for simple use cases, but applications can create multiple FlagSets to implement subcommands or independent flag scopes.

Flags and Values

Each flag is represented by a Flag struct containing metadata (name, shorthand, usage text, default value) and a Value interface implementation that handles type-specific parsing and storage. pflag provides built-in Value implementations for all common types.

Flag Definition Patterns

pflag provides four function variants for each supported type:

  • Type(name, value, usage) - Returns pointer to value
  • TypeP(name, shorthand, value, usage) - Returns pointer with shorthand
  • TypeVar(p, name, value, usage) - Binds to existing variable
  • TypeVarP(p, name, shorthand, value, usage) - Binds to existing variable with shorthand

Capabilities

Flag Definition and Parsing

Define and parse command-line flags with extensive type support.

// Parse command-line flags from os.Args[1:]
func Parse()

// Parse with custom handler called for each flag
func ParseAll(fn func(flag *Flag, value string) error)

// Check if flags have been parsed
func Parsed() bool

Flag Definition and Parsing

Type-Specific Flag Definers

Define flags for various types including primitives, slices, maps, network types, and more.

// Boolean flags
func Bool(name string, value bool, usage string) *bool
func BoolP(name, shorthand string, value bool, usage string) *bool

// Integer flags
func Int(name string, value int, usage string) *int
func IntP(name, shorthand string, value int, usage string) *int

// String flags
func String(name string, value string, usage string) *string
func StringP(name, shorthand string, value string, usage string) *string

// Slice flags
func StringSlice(name string, value []string, usage string) *[]string
func IntSlice(name string, value []int, usage string) *[]int

// Map flags
func StringToString(name string, value map[string]string, usage string) *map[string]string

Complete Type Reference

FlagSet Operations

Create and manage independent sets of flags for implementing subcommands.

// Create new flag set
func NewFlagSet(name string, errorHandling ErrorHandling) *FlagSet

// FlagSet parsing methods
func (f *FlagSet) Parse(arguments []string) error
func (f *FlagSet) ParseAll(arguments []string, fn func(*Flag, string) error) error
func (f *FlagSet) Parsed() bool

// Flag lookup
func (f *FlagSet) Lookup(name string) *Flag
func (f *FlagSet) ShorthandLookup(name string) *Flag

// Argument access
func (f *FlagSet) Args() []string
func (f *FlagSet) Arg(i int) string
func (f *FlagSet) NArg() int
func (f *FlagSet) NFlag() int

FlagSet Methods

Flag Value Access

Retrieve typed values from flags with error checking.

// Access flag values
func Lookup(name string) *Flag
func Args() []string
func Arg(i int) string
func NArg() int
func NFlag() int

// Set flag programmatically
func Set(name, value string) error

Flag Value Access

Advanced Features

Customize flag behavior with normalization, deprecation, hidden flags, and more.

// Normalize flag names
func (f *FlagSet) SetNormalizeFunc(n func(*FlagSet, string) NormalizedName)

// Mark flags as deprecated or hidden
func (f *FlagSet) MarkDeprecated(name string, usageMessage string) error
func (f *FlagSet) MarkShorthandDeprecated(name string, usageMessage string) error
func (f *FlagSet) MarkHidden(name string) error

// Flag annotations for bash completion and metadata
func (f *FlagSet) SetAnnotation(name, key string, values []string) error

Advanced Features

Go Flag Integration

Integrate with Go's standard library flag package.

// Add Go flags to pflag FlagSet
func (f *FlagSet) AddGoFlag(goflag *goflag.Flag)
func (f *FlagSet) AddGoFlagSet(newSet *goflag.FlagSet)

// Parse skipped go test flags
func ParseSkippedFlags(osArgs []string, goFlagSet *goflag.FlagSet) error

// Convert between flag types
func PFlagFromGoFlag(goflag *goflag.Flag) *Flag

Go Flag Integration

Usage and Help

Generate and customize help messages.

// Print help messages
func PrintDefaults()
func (f *FlagSet) PrintDefaults()

// Get usage strings
func (f *FlagSet) FlagUsages() string
func (f *FlagSet) FlagUsagesWrapped(cols int) string

// Customize usage function
var Usage func()

Usage and Help

Types

// Flag represents state of a flag
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
}

// FlagSet represents a set of defined flags
type FlagSet struct {
	Usage                func()
	SortFlags            bool
	ParseErrorsAllowlist ParseErrorsAllowlist
	ParseErrorsWhitelist ParseErrorsAllowlist // Deprecated
}

// Value interface for dynamic flag values
type Value interface {
	String() string
	Set(string) error
	Type() string
}

// SliceValue interface for list-based flags
type SliceValue interface {
	Append(string) error
	Replace([]string) error
	GetSlice() []string
}

// ErrorHandling defines error handling behavior
type ErrorHandling int

const (
	ContinueOnError ErrorHandling = iota
	ExitOnError
	PanicOnError
)

// ParseErrorsAllowlist configures allowlist of errors
type ParseErrorsAllowlist struct {
	UnknownFlags bool
}

// NormalizedName is a normalized flag name
type NormalizedName string

Error Types

// NotExistError returned when flag does not exist
type NotExistError struct { /* ... */ }

func (e *NotExistError) Error() string
func (e *NotExistError) GetSpecifiedName() string
func (e *NotExistError) GetSpecifiedShortnames() string

// ValueRequiredError returned when flag requires value
type ValueRequiredError struct { /* ... */ }

func (e *ValueRequiredError) Error() string
func (e *ValueRequiredError) GetFlag() *Flag
func (e *ValueRequiredError) GetSpecifiedName() string
func (e *ValueRequiredError) GetSpecifiedShortnames() string

// InvalidValueError returned when flag value invalid
type InvalidValueError struct { /* ... */ }

func (e *InvalidValueError) Error() string
func (e *InvalidValueError) Unwrap() error
func (e *InvalidValueError) GetFlag() *Flag
func (e *InvalidValueError) GetValue() string

// InvalidSyntaxError returned when flag syntax invalid
type InvalidSyntaxError struct { /* ... */ }

func (e *InvalidSyntaxError) Error() string
func (e *InvalidSyntaxError) GetSpecifiedFlag() string

Global Variables

// ErrHelp returned if -help invoked but not defined
var ErrHelp error

// Usage function for printing usage message
var Usage func()

// CommandLine is default set of command-line flags
var CommandLine *FlagSet