Avatar Ilya Mateyko

go.astrophena.name/base Module

GitHub repository | Commit (eb6910d)

Base Go packages for my projects.

package cli

import "go.astrophena.name/base/cli"

Package cli provides helpers for creating simple, single-command command-line applications.

Index

Variables

var ErrExitVersion = &unprintableError{errors.New("version flag exit")}

ErrExitVersion signals that the application should exit successfully after printing the version information.

var ErrInvalidArgs = errors.New("invalid arguments")

ErrInvalidArgs indicates that the user provided invalid command-line arguments. It should be wrapped with more specific context about the error.

Functions

func Main

func Main(app App)

Main runs an application, handling signal-based cancellation and printing errors to stderr. It is intended to be called directly from a program's main function.

func Run

func Run(ctx context.Context, app App) error

Run executes an application. It parses flags, handles standard flags like -version and -cpuprofile, and then runs the app.

func SetDocComment

func SetDocComment(src []byte)

SetDocComment sets the main documentation for the application, which is displayed when a user passes the -help flag. It is intended to be used with Go's //go:embed directive.

Example:

//go:embed doc.go
var doc []byte

func init() { cli.SetDocComment(doc) }

func WithEnv

func WithEnv(ctx context.Context, e *Env) context.Context

WithEnv returns a new context that carries the provided application environment.

Types

type App

type App interface {
	// Run executes the application's primary logic.
	Run(context.Context) error
}

App represents a runnable command-line application.

type AppFunc

type AppFunc func(context.Context) error

AppFunc is an adapter to allow the use of ordinary functions as an App.

func (AppFunc) Run

func (f AppFunc) Run(ctx context.Context) error

Run calls the underlying function.

type Env

type Env struct {
	Args   []string
	Getenv func(string) string
	Stdin  io.Reader
	Stdout io.Writer
	Stderr io.Writer
	// contains filtered or unexported fields
}

Env encapsulates the application's environment, including arguments, standard I/O streams, and environment variables.

func GetEnv

func GetEnv(ctx context.Context) *Env

GetEnv retrieves the application's environment from a context. If the context has no environment, it returns one based on the current OS.

func OSEnv

func OSEnv() *Env

OSEnv creates an Env based on the current operating system environment.

func (*Env) Logf

func (e *Env) Logf(format string, args ...any)

Logf prints a formatted message to the environment's standard error.

type HasFlags

type HasFlags interface {
	App

	// Flags registers flags with the given FlagSet.
	Flags(*flag.FlagSet)
}

HasFlags is an App that can define its own command-line flags.

Directories

clitest Package clitest provides utilities for testing command-line applications.