cli

package module
v0.0.5 Latest Latest
Warning

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

Go to latest
Published: Jan 17, 2026 License: MIT Imports: 12 Imported by: 2

README

cli

cli is a small helper package for building command-line interfaces in Go. It wraps the standard flag package with a consistent model for:

  • registering flags and positional arguments
  • reading values from environment variables
  • generating structured, wrapped usage text
  • documenting env-only inputs

The API is intentionally small and dependency-free so it can be embedded in libraries or applications without heavy setup.

Install

go get zuern.dev/cli

Quick start

package main

import (
	"flag"
	"fmt"
	"log"
	"os"

	"zuern.dev/cli"
)

type Config struct {
	Port int
	Env  string
	Path string
}

func main() {
	var cfg Config
	flagSet := flag.NewFlagSet("example", flag.ExitOnError)

	c := cli.New(
		"example",
		"Example program that shows flags, env vars, and args.",
		"example [options] <path>",
		"v1.0.0",
		[]cli.Opt{
			{Name: "port", Env: "EXAMPLE_PORT", Desc: "Port to listen on", Ptr: &cfg.Port},
			{Name: "env", Env: "EXAMPLE_ENV", Desc: "Runtime environment", Ptr: &cfg.Env},
		},
		[]cli.Arg{
			{Name: "path", Desc: "Path to process", Ptr: &cfg.Path},
		},
		cli.UseFlagSet(flagSet),
	)

	if err := c.ReadEnv(); err != nil {
		log.Fatal(err)
	}
	if err := c.ParseArgs(os.Args[1:]); err != nil {
		log.Fatal(err)
	}

	fmt.Printf("%+v\n", cfg)
}

Usage output

CLI.Usage() returns a fully formatted usage string that includes your description, usage line, args, options, and environment variables. The output is line-wrapped at 80 columns for readability in standard terminals.

To use the default flag package behavior, rely on Create / Parse or set flag.Usage = cli.Usage() yourself. When you use UseFlagSet, the usage function is set on that FlagSet.

Options

Options are modeled with cli.Opt:

  • Name registers a flag (empty name means env-only)
  • Env specifies the environment variable to read
  • Ptr points to the destination value
  • Desc and TypeName control usage text

Supported pointer targets are *string, *bool, *int, *time.Duration, or anything that implements flag.Value.

DocumentationOnly can be used to include an env var in usage without parsing it (useful for external libraries).

Arguments

Positional arguments are modeled with cli.Arg and are read in order after flag parsing. Missing args return cli.ErrMissingArgs from ParseArgs.

Environment variables and .env

Call ReadEnv to load values from environment variables into the same pointers as your flags.

To optionally load a local .env file before parsing, call:

if err := cli.ApplyEnvFileIfExists(); err != nil {
	log.Fatal(err)
}

The .env parser ignores blank lines, # or // comments, and lines without key=value format.

Error handling

There are two common flows:

  • Create / New + Parse uses the global flag package and exits the program on parse or missing-args errors.
  • New + UseFlagSet + ParseArgs returns errors for your application to handle and avoids os.Exit.

Use CreateCLI for the short path that does NewCLI, ReadEnv, and Parse in one call (note this still exits on missing args because it calls Parse).

Example

See the runnable example in example/:

cd example
go run . -h

Documentation

Overview

Package cli provides small, dependency-free helpers for building CLIs with flags, positional arguments, and environment variables. It focuses on:

  • registering flags and env vars against shared pointers
  • formatted usage output with wrapped descriptions
  • optional support for custom flag.FlagSet values

Typical usage is to define []Opt and []Arg, call New or CreateCLI, then parse environment variables and arguments.

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrMissingArgs is returned when required arguments are missing when parsing program args.
	ErrMissingArgs = errors.New("required arguments were not provided")
	// ErrInvalidArg is returned when a provided program argument was invalid.
	ErrInvalidArg = errors.New("invalid argument")
	// ErrInvalidEnv is returned when the value of an environment variable was invalid.
	ErrInvalidEnv = errors.New("invalid environment variable value")
)

Functions

func ApplyEnvFileIfExists added in v0.0.4

func ApplyEnvFileIfExists() error

ApplyEnvFileIfExists looks in the working directory for a ".env" file and, if present, applies all lines in the format key=value with os.Setenv. Lines starting with "#" or "//" (after trimming whitespace) are treated as comments and skipped. Lines that cannot be parsed into a key-value pair are ignored. An error is returned only when there is an error reading the file.

Types

type Arg

type Arg struct {
	// Name of the program argument.
	Name string
	// Desc is the description of the argument.
	Desc string
	// Ptr is a pointer to the value to set. Supported types are string, int,
	// bool, and flag.Value.
	Ptr any
}

Arg describes a positional argument parsed after flags.

type CLI

type CLI struct {
	// contains filtered or unexported fields
}

CLI represents a configured command-line interface with options, args, and environment bindings.

func Create

func Create(
	name string,
	description string,
	usage string,
	version string,
	options []Opt,
	arguments []Arg,
	cliOpts ...CLIOpt,
) *CLI

Create behaves like CreateCLI but prints the error to stderr and exits the program when initialization fails.

func CreateCLI added in v0.0.2

func CreateCLI(
	name string,
	description string,
	usage string,
	version string,
	options []Opt,
	arguments []Arg,
	cliOpts ...CLIOpt,
) (*CLI, error)

CreateCLI creates a new CLI, reads environment variables, and parses program flags all at once. This is equivalent to calling NewCLI, CLI.ReadEnv, and CLI.Parse. Note that CLI.Parse will exit the program on missing required args.

func New

func New(
	name string,
	description string,
	usage string,
	version string,
	options []Opt,
	arguments []Arg,
	cliOpts ...CLIOpt,
) *CLI

New behaves like NewCLI but prints the error to stderr and exits the program when initialization fails.

func NewCLI added in v0.0.2

func NewCLI(
	name string,
	description string,
	usage string,
	version string,
	options []Opt,
	arguments []Arg,
	cliOptions ...CLIOpt,
) (*CLI, error)

NewCLI registers environment variables and program flags according to the provided options, and installs a usage func on the flag set. Call CLI.ReadEnv to load environment variables and CLI.Parse or CLI.ParseArgs to parse flags.

func (*CLI) Parse

func (cli *CLI) Parse() *CLI

Parse reads the program flags into the values pointed to by the options using the global flag set. It exits the program on missing required args.

func (*CLI) ParseArgs added in v0.0.2

func (cli *CLI) ParseArgs(arguments []string) error

ParseArgs parses flags from the provided argument list, which should not include the command name. The return value will be flag.ErrHelp if -help or -h were set but not defined. ErrMissingArgs is returned if there are missing required args.

func (*CLI) ReadEnv

func (cli *CLI) ReadEnv() error

ReadEnv reads any non-empty environment variables into the values pointed to by the options.

func (*CLI) Usage added in v0.0.2

func (cli *CLI) Usage() string

Usage returns the formatted usage string for the CLI.

type CLIOpt added in v0.0.2

type CLIOpt func(c *CLI)

CLIOpt is an option that is applied to a CLI to configure behavior such as where to direct output or how to fetch environment variables.

func GetEnv added in v0.0.2

func GetEnv(getEnv func(key string) string) CLIOpt

GetEnv configures a CLI to get environment variables using the provided func.

func UseFlagSet added in v0.0.2

func UseFlagSet(flagSet ...*flag.FlagSet) CLIOpt

UseFlagSet configures the CLI to use a specific flag.FlagSet. If no argument is provided, a new FlagSet is created. This function panics if more than one FlagSet is provided or the provided FlagSet is nil.

func WriteErr added in v0.0.2

func WriteErr(w io.Writer) CLIOpt

WriteErr configures a CLI to write error to the provided writer.

func WriteOut added in v0.0.2

func WriteOut(w io.Writer) CLIOpt

WriteOut configures a CLI to write output to the provided writer.

type Opt

type Opt struct {
	// Name of the program flag. If empty, no program flag is registered.
	Name string
	// Desc is the description of the option.
	Desc string
	// Env is an optional environment variable to register.
	Env string
	// Ptr is a pointer to the value to set. Supported types are string, int,
	// bool, time.Duration, and flag.Value. If the value being pointed to is
	// non-zero it will be used as the default value for the option.
	Ptr any
	// DocumentationOnly is set to document environment variables which are not
	// parsed through this package. It is permitted only on Opts where both Name
	// and Ptr fields are unspecified.
	DocumentationOnly bool
	// TypeName is an optional hint to the user about the option's type.
	// If unset, the type name implied by Ptr will be used.
	TypeName string
	// contains filtered or unexported fields
}

Opt is a program option configurable by user input or environment variables.

func (Opt) String added in v0.0.4

func (o Opt) String() string

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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