flags

package module
v0.11.1 Latest Latest
Warning

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

Go to latest
Published: Aug 1, 2025 License: BSD-3-Clause Imports: 10 Imported by: 1

README


Flags

Generate cobra commands from structs

jessevdk/go-flags, urfave/sflags and alecthomas/kong compliant tags.

Advanced related CLI features (validations, completions and more), at a minimum cost.

Github Actions (workflows) Go module version GoDoc reference Go Report Card codecov

reeflective/flags lets you effortlessly build powerful, feature-rich spf13/cobra command-line applications directly from Go structs. Stop writing boilerplate for flags, commands, and argument parsing. Instead, define your entire CLI structure declaratively and let flags handle the generation.

Features

Overview

  • Declarative & Simple: Define your entire CLI—commands, subcommands, flags, and positional arguments—using simple Go struct tags.
  • Powerful Completions: Instantly generate rich, context-aware shell completions for 9 shells, powered by a single call to carapace.
  • Built-in Validation: Add validation rules (required, min, max, oneof, etc.) directly in your struct tags using the validate tag.
  • Seamless Cobra Integration: Generates a standard cobra.Command, so you can still use the full power of the Cobra ecosystem.
  • High Compatibility: Offers a familiar experience for developers coming from jessevdk/go-flags, alecthomas/kong or octago/sflags by supporting their tag formats.
  • Focus on Your Logic: Spend less time on CLI boilerplate and more time on what your application actually does.

Commands, flags & positionals

  • Various ways to structure the command trees in groups (tagged, or encapsulated in structs).
  • Almost entirely retrocompatible with go-flags, sflags and kong with a ported and enlarged test suite.
  • Advanced and versatile positional arguments declaration, with automatic binding to cobra.Args.
  • Large array of native types supported as flags or positional arguments.
  • Easily declare validations on command flags or positional arguments, with go-validator tags.
  • Generate advanced completions with the carapace completion engine in a single call.
  • Implement completers on positional/flag types, or declare builtin completers via struct tags.
  • Generated completions include commands/flags groups, descriptions, usage strings.
  • Live validation of command-line input with completers running flags' validations.

Discovering the Library

A good way to introduce you to this library is to install and use the example application binary. This example application will give you a taste of the behavior and supported features.

Quick Start

Go beyond simple flags. Define commands, grouped flags, positional arguments with validation, and shell completions—all from a single struct.

package main

import (
	"fmt"
	"os"

	"github.comcom/reeflective/flags"
)

// Define the root command structure.
var opts struct {
	Verbose bool     `short:"v" long:"verbose" desc:"Show verbose debug information"`
	Hello   HelloCmd `command:"hello" description:"A command to say hello"`
}

// Define the 'hello' subcommand.
type HelloCmd struct {
	// Add a required positional argument with shell completion for usernames.
	Name string `arg:"" required:"true" description:"The name to greet" complete:"users"`

	// Add an optional positional argument with a default value.
	Greeting string `arg:"" help:"An optional, custom greeting"`

	// Group flags together for better --help output.
	Output struct {
		Formal bool   `long:"formal" description:"Use a more formal greeting"`
		Color  string `long:"color" default:"auto" description:"When to use color output" choice:"auto always never"`
	} `group:"Output Settings"`
}

// Execute will be automatically discovered and used as the handler for the 'hello' command.
func (c *HelloCmd) Execute(args []string) error {
	greeting := c.Greeting
	if c.Output.Formal {
		greeting = "Greetings"
	}

	message := fmt.Sprintf("%s, %s!", greeting, c.Name)

	// A real app would check if stdout is a TTY for "auto"
	if c.Output.Color == "always" || c.Output.Color == "auto" {
		message = "\033[32m" + message + "\033[0m" // Green text
	}

	fmt.Println(message)

	if opts.Verbose {
		fmt.Println("(Executed with verbose flag)")
	}

	return nil
}

func main() {
	// Generate the cobra.Command from your struct.
    // Completions will be automatically generated.
	cmd, err := flags.Parse(&opts)
	if err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}

	// Execute the application.
	if err := cmd.Execute(); err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}
}

Advanced Usage & Wiki

Development

Coming from other libraries

Status

This library is approaching v1.0 status: it has been under a big refactoring and has seen many improvements in many aspects (Compatibility, completions, validations, failure safety, etc). However, it has not been much tested outside of its test suite: there might be bugs, or behavior inconsistencies that I might have missed.

Please open a PR or an issue if you wish to bring enhancements to it. For newer features, please consider if there is a large number of people who might benefit from it, or if it has a chance of impairing on future development. If everything is fine, please propose ! Other contributions, as well as bug fixes and reviews are also welcome.

Documentation

Overview

Package flags provides a powerful, reflection-based way to generate modern command-line interfaces (CLIs) from Go structs. It uses spf13/cobra for command execution and rsteube/carapace for advanced shell completion.

The primary workflow is to define your CLI structure (commands, flags, positional arguments) using Go structs and field tags, and then call flags.ParseCommands() to create a fully configured *cobra.Command tree, complete with shell completions, ready for execution.

For useful, pre-built flag types like Counter or HexBytes, see the subpackage at "github.com/reeflective/flags/types".

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrParse is a general error used to wrap more specific parsing errors.
	ErrParse = errors.ErrParse

	// ErrNotPointerToStruct indicates that a provided data container is not
	// a pointer to a struct.
	ErrNotPointerToStruct = errors.ErrNotPointerToStruct

	// ErrNotCommander is returned when a struct is tagged as a command but
	// does not implement a command interface (e.g., Commander).
	ErrNotCommander = errors.ErrNotCommander

	// ErrInvalidTag indicates an invalid tag or invalid use of an existing tag.
	ErrInvalidTag = errors.ErrInvalidTag

	// ErrNotValue indicates that a struct field type for a flag does not
	// implement the flags.Value interface.
	ErrNotValue = errors.ErrNotValue
)

Functions

func Bind added in v0.11.0

func Bind(cmd *cobra.Command, data any, opts ...Option) error

Bind parses a struct and binds its commands, flags, and positional arguments to an existing *cobra.Command. This is useful for integrating flags with a command tree that is partially managed manually.

Shell completions for the bound components are generated and attached automatically.

func Parse added in v0.11.0

func Parse(data any, opts ...Option) (*cobra.Command, error)

Generate parses a struct and creates a new, fully configured *cobra.Command. The provided `data` argument must be a pointer to a struct. Struct fields tagged with `command:"..."` become subcommands, and other tagged fields become flags. A struct implementing one of the Runner interfaces becomes an executable command.

Shell completions are generated and attached automatically.

This is the primary entry point for creating a new CLI application.

Types

type Commander

type Commander = interfaces.Commander

Commander is the primary interface for a struct to be recognized as an executable command. Its Execute method is bound to cobra.Command.RunE.

type Completer added in v0.11.0

type Completer = interfaces.Completer

Completer is the interface for types that can provide their own shell completion suggestions.

type Marshaler added in v0.11.0

type Marshaler = interfaces.Marshaler

Marshaler is the interface implemented by types that can marshal themselves to a string representation of the flag. Retroported from jessevdk/go-flags.

type Option added in v0.11.0

type Option func(o *parser.Opts)

Option is a functional option for configuring command and flag generation.

func WithCompleter added in v0.11.0

func WithCompleter(name string, completer carapace.CompletionCallback) Option

WithCompleter adds a custom completer function to the parser options. You can use this completer by tagging flag or positional arg struct fields with `complete:"custom-completer-name"`, and bind this completer under the same name in this function.

func WithEnvDivider added in v0.11.0

func WithEnvDivider(divider string) Option

WithEnvDivider sets the character used to separate words in environment variable names.

func WithEnvPrefix added in v0.11.0

func WithEnvPrefix(prefix string) Option

WithEnvPrefix sets a prefix for all environment variables.

func WithFlagDivider added in v0.11.0

func WithFlagDivider(divider string) Option

WithFlagDivider sets the character used to separate words in long flag names.

func WithPrefix added in v0.11.0

func WithPrefix(prefix string) Option

WithPrefix sets a prefix that will be applied to all long flag names.

func WithValidation added in v0.11.0

func WithValidation() Option

WithValidation adds field validation for fields with the "validate" tag. This makes use of go-playground/validator internally, refer to their docs for an exhaustive list of valid tag validations.

func WithValidator added in v0.11.0

func WithValidator(v *validator.Validate) Option

WithValidator registers a custom validation function for flags and arguments. It is required to pass a go-playground/validator object for customization. The latter library has been chosen because it supports most of the validation one would want in CLI, and because there are vast possibilities for registering and using custom validations through the *Validate type.

func WithVars added in v0.11.0

func WithVars(vars map[string]string) Option

WithVars adds a map of variables that can be used for expansion in tags.

type PostRunner added in v0.9.1

type PostRunner = interfaces.PostRunner

PostRunner is the equivalent of cobra.Command.PostRun.

type PostRunnerE added in v0.9.1

type PostRunnerE = interfaces.PostRunnerE

PostRunnerE is the equivalent of cobra.Command.PostRunE.

type PreRunner added in v0.9.1

type PreRunner = interfaces.PreRunner

PreRunner is the equivalent of cobra.Command.PreRun.

type PreRunnerE added in v0.9.1

type PreRunnerE = interfaces.PreRunnerE

PreRunnerE is the equivalent of cobra.Command.PreRunE.

type Runner added in v0.9.1

type Runner = interfaces.Runner

Runner is a simpler command interface bound to cobra.Command.Run. It is ignored if the struct also implements Commander.

type Unmarshaler added in v0.11.0

type Unmarshaler = interfaces.Unmarshaler

Unmarshaler is the interface implemented by types that can unmarshal a flag argument to themselves. The provided value is directly passed from the command line. Retroported from jessevdk/go-flags.

type ValidateFunc

type ValidateFunc = validation.ValidateFunc

ValidateFunc is the core validation function type. It takes the actual Go value to validate, the validation tag string, and the field name for error reporting. This is the simplified interface the user wants to implement.

type Value

type Value = values.Value

Value is the interface for custom flag types.

Directories

Path Synopsis
internal
gen
Package flags (github.com/reeflective/flags/gen/flags) provides the entrypoints to command trees and flags generation for arbitrary structures.
Package flags (github.com/reeflective/flags/gen/flags) provides the entrypoints to command trees and flags generation for arbitrary structures.
tag
values/genvalues command
This generator is for internal usage only.
This generator is for internal usage only.
Package types provides useful, pre-built implementations of the flags.Value interface for common use cases.
Package types provides useful, pre-built implementations of the flags.Value interface for common use cases.

Jump to

Keyboard shortcuts

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