cli

package
v0.0.14 Latest Latest
Warning

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

Go to latest
Published: Jun 28, 2025 License: BSD-3-Clause Imports: 8 Imported by: 0

Documentation

Overview

Package cli provides a simple command-line interface framework.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Command

type Command[T any, M any] struct {
	Name        string                                                      // name used to invoke the command.
	Usage       string                                                      // short usage text
	Help        string                                                      // long help text
	Flags       func(flags *flag.FlagSet, target T)                         // function for defining flags
	Vars        map[string]string                                           // map of flag names -> environment variables
	Action      func(ctx context.Context, env *Env[M], target T) ExitStatus // command action
	Subcommands []*Command[T, M]                                            // command subcommands
	// contains filtered or unexported fields
}

A Command represents a CLI command.

T is the type of the target value for configuration storage. M is the type of the metadata provided by the execution Env.

Example
package main

import (
	"context"
	"flag"
	"fmt"

	"github.com/jonathonwebb/x/cli"
)

func main() {
	type meta struct {
		build string
	}

	type values struct {
		env  string
		addr string
	}

	serveCmd := cli.Command[*values, meta]{
		Name:  "serve",
		Usage: "serve [flags]",
		Help:  "flags:\n  -addr",
		Flags: func(flags *flag.FlagSet, target *values) {
			flags.StringVar(&target.addr, "addr", "", "")
		},
		Vars: map[string]string{
			"addr": "FOO_ADDR",
		},
		Action: func(ctx context.Context, env *cli.Env[meta], target *values) cli.ExitStatus {
			fmt.Printf("env=%s\n", target.env)
			fmt.Printf("addr=%s\n", target.addr)
			return cli.ExitSuccess
		},
	}

	rootCmd := cli.Command[*values, meta]{
		Name:  "foo",
		Usage: "usage: foo [flags] command",
		Help:  "commands:\n  serve\n\nflags:\n  -env",
		Flags: func(flags *flag.FlagSet, target *values) {
			flags.StringVar(&target.env, "env", "", "")
		},
		Subcommands: []*cli.Command[*values, meta]{&serveCmd},
	}

	v := values{}
	status := rootCmd.Execute(context.Background(), &cli.Env[meta]{
		Args: []string{"foo", "-env=dev", "serve"},
		Vars: map[string]string{
			"FOO_ADDR": "localhost:8000",
		},
	}, &v)

	fmt.Printf("status=%d", status)

}
Output:
env=dev
addr=localhost:8000
status=0

func (*Command[T, M]) Execute

func (c *Command[T, M]) Execute(ctx context.Context, env *Env[M], target T) ExitStatus

Execute parses command-line arguments from the environment, then either calls the command's action or defers to the specified subcommand's Execute method.

type Env

type Env[M any] struct {
	Err  io.Writer         // error output stream
	Out  io.Writer         // standard output stream
	Args []string          // command-line arguments
	Vars map[string]string // environment variables
	Meta M                 // custom metadata
}

An Env represents the execution environment for a Command.

M is the type of custom metadata that will be available to Command actions.

func DefaultEnv

func DefaultEnv[M any](meta M) Env[M]

DefaultEnv returns an Env using the current process's environment.

The returned Env will use the os.Stderr and os.Stdout streams, os.Args, and environment variables from os.Environ.

func (Env[M]) Errorf

func (e Env[M]) Errorf(format string, args ...any)

Errorf formats and writes an error message to the error output stream.

func (Env[M]) ExecMetaTmpl added in v0.0.7

func (e Env[M]) ExecMetaTmpl(s string) (string, error)

func (Env[M]) Printf

func (e Env[M]) Printf(format string, args ...any)

Printf formats and writes a message to the standard output stream.

type ExitStatus

type ExitStatus int

An ExitStatus is the result of command execution.

const (
	ExitSuccess ExitStatus = 0 // execution succeeded
	ExitFailure ExitStatus = 1 // execution failed due to an error
	ExitUsage   ExitStatus = 2 // execution failed due to invalid user input
)

Jump to

Keyboard shortcuts

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