flagpole

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Sep 22, 2025 License: Apache-2.0 Imports: 8 Imported by: 1

README

Flagpole

GoDoc Latest Version Go Report Card

Flagpole is an intelligent, configurable replacement for stdlib flag.Flaset.

Rather than confusing, imperative (and limited) calls to fs.String(...), fs.Bool(...) etc. - expected flags are defined as a struct, e.g.

type Flags struct {
    Help *bool `name:"help" alias:"h" usage:"Show help"`
    Port int   `name:"port" alias:"p" default:"80" usage:"Port number"`
}

Flags are then read directly into a struct by defining a parser and then parsing, e.g.

package main

import (
    "fmt"
    "github.com/go-andiamo/flagpole"
    "os"
)

type Flags struct {
    Help *bool `name:"help" alias:"h" usage:"Show help"`
    Port int   `name:"port" alias:"p" usage:"Port number"`
}

var flagParser = flagpole.MustNewParser[Flags](flagpole.StopOnHelp(true))

func main() {
    flags, err := flagParser.Parse(os.Args[1:])
    if err != nil || (flags.Help != nil && *flags.Help) {
        out := os.Stdout
        if err != nil {
            out = os.Stderr
        }
        flagParser.Usage(out, err, "myCli")
        if err != nil {
            os.Exit(2)
        }
        os.Exit(0)
    }
    // all good...
    fmt.Printf("Using port: %d\n", flags.Port)
}

Features/Advantages

  • Supports common native field types: string,bool,int,int8,int16,int32,int64,uint,uint8,uint16,uint32,uint64,float32,float64
  • Other field types supported if the type implements encoding.TextUnmarshaler
  • Supports pointer types for optional flags (and parsed field value is only non-nil when the flag is actually present - no more guessing at zero values!)
  • Supports slice field types (of common native type or elements implementing encoding.TextUnmarshaler)
  • Flag sets can be composed (using embedded or nested structs)
  • Optional error handling (allowing errors to be recorded but parsing continue)
  • Usage display completely under your control - and display formatting is replaceable
  • Minimal reflection use
    • Field reflection only at parser create time
    • Efficient field setters at parse time

Tags

Flagpole supports the following tags on struct fields:

  • name

    is the flag name (if not present, the field name is used)

  • alias

    is an alias name for the flag (can also be comma separated list of multiple aliases)

  • usage

    is the usage description for the flag

  • required

    e.g. required:"true" | required:"false"

    specifies whether the flag is required - if this tag is omitted, required is determined by whether the field is a non-pointer type

  • default

    is the default value to use if the flag is required but not present

  • example

    is the example of the flag usage (as used by single usage line example)

Installation

Use get:

go get github.com/go-andiamo/flagpole

Get to update to the latest version:

go get -u github.com/go-andiamo/flagpole

Documentation

Overview

Package flagpole - Go package for reading CLI flags into a struct

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type CheckRequiredFlags

type CheckRequiredFlags bool

CheckRequiredFlags is a type that can be passed as an option to NewParser or Parser.Parse and instructs the parser whether to check that required flags were specified (the default is true)

type DefaultedOptionals

type DefaultedOptionals bool

DefaultedOptionals is a type that can be passed as an option to NewParser or Parser.Parse and instructs the parser to fill optional flags with their default value (if present) when the flag was not specified (default is false)

type DuplicateFlag

type DuplicateFlag int

DuplicateFlag is a type that can be passed as an option to NewParser or Parser.Parse and instructs the parser how to deal with duplicate fields (the default is DuplicateFlagOverwrite)

const (
	DuplicateFlagOverwrite DuplicateFlag = iota
	DuplicateFlagIgnore
	DuplicateFlagError
)

type Flag

type Flag struct {
	Name       string   // name as it appears on command line
	Usage      string   // help message
	HasDefault bool     // whether the flag has a default value (DefValue)
	DefValue   string   // default value (as text); for usage message
	IsBool     bool     // denotes if the flag is a bool
	Required   bool     // denotes the flag is required
	Aliases    []string // denotes alias names for the flag
	Example    string   // example; for usage message
}

Flag represents a flag extracted from a struct

type IgnoreUnknownFlags

type IgnoreUnknownFlags bool

IgnoreUnknownFlags is a type that can be passed as an option to NewParser or Parser.Parse and determines whether the parser should ignore unknown flags (default is false)

type ParseErrorHandler

type ParseErrorHandler interface {
	// HandleError is called with errors during parsing
	//
	//  - name is the flag name
	//  - flag is the flag information (if known)
	//  - err is the error encountered
	//
	// return true if parsing is to continue, otherwise parsing halts with the error
	HandleError(name string, flag *Flag, err error) (cont bool)
}

ParseErrorHandler is an interface that can be passed as an option to NewParser or Parser.Parse and is called with all errors during parsing - and allows continuation after error

type Parser

type Parser[T any] interface {
	// Parse parses the supplied arguments as flags and returns the crated struct for those flags
	//
	// any options supplied override the options for the parser
	Parse(arguments []string, options ...any) (T, error)
	// Flags returns the flags found in the struct
	Flags() []Flag
	// Usage prints the usage information about flags to the supplied out (e.g. os.Stdout, os.Stderr)
	Usage(out io.Writer, err error, commandPrefixes ...string)
}

Parser is the flags parser - use NewParser / MustNewParser to create a new one

func MustNewParser

func MustNewParser[T any](options ...any) Parser[T]

MustNewParser is the same as NewParser, except it panics on error

func NewParser

func NewParser[T any](options ...any) (Parser[T], error)

NewParser creates a new flags parser for the specified T (which must be a struct)

options can be any of IgnoreUnknownFlags, ParseErrorHandler, StopOnFlag, StopOnHelp, DuplicateFlag, CheckRequiredFlags, DefaultedOptionals or UsageDisplay

type StopOnFlag

type StopOnFlag string

StopOnFlag is a type that can be passed as an option to NewParser or Parser.Parse and instructs the parser to stop on seeing the specified flag

Multiple of these can be passed as options - they become additive

type StopOnHelp

type StopOnHelp bool

StopOnHelp is a type that can be passed as an option to NewParser or Parser.Parse and instructs the parser to stop on encountering flag "-help" / "-h"

type UsageDisplay

type UsageDisplay interface {
	Usage(out io.Writer, err error, flags []Flag, commandPrefixes ...string)
}

UsageDisplay is an interface that can be passed as an option to NewParser and replaces the default usage display used by Parser.Usage

Directories

Path Synopsis
_examples

Jump to

Keyboard shortcuts

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