cli

package module
v0.4.0 Latest Latest
Warning

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

Go to latest
Published: Feb 19, 2023 License: Apache-2.0 Imports: 12 Imported by: 28

README

cli

Reduce boiler plate needed on each new Golang main functions (Command Line Interface) for both tool and servers

It abstracts the repetitive parts of a main() command line tool, flag parsing, usage, etc...

Tool Example

Client/Tool example (no dynamic flag url or config) sampleTool

Code as simple as

import (
	"flag"
	"os"

	"fortio.org/cli"
	"fortio.org/log"
)

func main() { os.Exit(Main()) }

func Main() int {
	myFlag := flag.String("myflag", "default", "my flag")
	cli.Config.MinArgs = 2
	cli.Config.MaxArgs = 4
	if !cli.Main() {
		return 1
	}
	log.Infof("Info test, -myflag is %q", *myFlag) // won't show with -quiet
	log.Printf("Hello world, version %s, args %v", cli.Config.ShortVersion, flag.Args())
	return 0
}
$ sampleTool a
sampleTool 1.0.0 usage:
	sampleTool [flags] arg1 arg2 [arg3...arg4]
or 1 of the special arguments
	sampleTool {help|version|buildinfo}
flags:
  -loglevel level
    	log level, one of [Debug Verbose Info Warning Error Critical Fatal] (default Info)
  -myflag string
    	my flag (default "default")
  -quiet
    	Quiet mode, sets log level to warning
At least 2 arguments expected, got 1

or normal case

$ sampleTool a b
15:42:17 I Info test, -myflag is "default"
15:42:17 Hello world, version dev, args [a b]

Server Example

Server example sampleServer

% go run . -config-dir ./config -config-port 8888 a b
15:45:20 I updater.go:47> Configmap flag value watching on ./config
15:45:20 I updater.go:156> updating loglevel to "verbose\n"
15:45:20 I logger.go:183> Log level is now 1 Verbose (was 2 Info)
15:45:20 I updater.go:97> Now watching . and config
15:45:20 I updater.go:162> Background thread watching config now running
15:45:20 Fortio 1.50.1 config server listening on tcp [::]:8888
15:45:20 Starting sampleServer dev  go1.19.6 arm64 darwin
# When visiting the UI
15:46:20 ListFlags: GET / HTTP/1.1 [::1]:52406 ()  "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/110.0.0.0 Safari/537.36"

With the flags ui on http://localhost:8888

flags UI

Additional builtins

buildinfo

e.g

$ go install fortio.org/cli/sampleServer@latest
go: downloading fortio.org/cli v0.1.0
$ sampleServer buildinfo
0.1.0 h1:M+coC8So/41xSyGiiJ/6RS+XhnshNUslZuaB6H8z9GI= go1.19.6 arm64 darwin
go	go1.19.6
path	fortio.org/cli/sampleServer
mod	fortio.org/cli	v0.1.0	h1:M+coC8So/41xSyGiiJ/6RS+XhnshNUslZuaB6H8z9GI=
dep	fortio.org/dflag	v1.4.1	h1:WDhlHMh3yrQFrvspyN5YEyr8WATdKM2dUJlTxsjCDtI=
dep	fortio.org/fortio	v1.50.1	h1:5FSttAHQsyAsi3dzxDmSByfzDYByrWY/yw53bqOg+Kc=
dep	fortio.org/log	v1.2.2	h1:vs42JjNwiqbMbacittZjJE9+oi72Za6aekML9gKmILg=
dep	fortio.org/version	v1.0.2	h1:8NwxdX58aoeKx7T5xAPO0xlUu1Hpk42nRz5s6e6eKZ0=
dep	github.com/fsnotify/fsnotify	v1.6.0	h1:n+5WquG0fcWoWp6xPWfHdbskMCQaFnG6PfBrh1Ky4HY=
dep	github.com/google/uuid	v1.3.0	h1:t6JiXgmwXMjEs8VusXIJk2BXHsn+wx8BZdTaoZ5fu7I=
dep	golang.org/x/exp	v0.0.0-20230213192124-5e25df0256eb	h1:PaBZQdo+iSDyHT053FjUCgZQ/9uqVwPOcl7KSWhKn6w=
dep	golang.org/x/net	v0.7.0	h1:rJrUqqhjsgNp7KqAIc25s9pZnjU7TUcSY7HcVZjdn1g=
dep	golang.org/x/sys	v0.5.0	h1:MUK/U/4lj1t1oPg0HfuXDN/Z1wv31ZJ/YcPiGccS4DU=
dep	golang.org/x/text	v0.7.0	h1:4BRB4x83lYWy72KwLD/qYDuTu7q9PjSagHvijDw7cLo=
build	-compiler=gc
build	CGO_ENABLED=1
build	CGO_CFLAGS=
build	CGO_CPPFLAGS=
build	CGO_CXXFLAGS=
build	CGO_LDFLAGS=
build	GOARCH=arm64
build	GOOS=darwin
help
$ sampleServer help
sampleServer 0.1.0 usage:
	sampleServer [flags] arg1 arg2 [arg3...arg4]
or 1 of the special arguments
	sampleServer {help|version|buildinfo}
flags:
  -config-dir directory
    	Config directory to watch for dynamic flag changes
  -config-port port
    	Config port to open for dynamic flag UI/api
  -loglevel level
    	log level, one of [Debug Verbose Info Warning Error Critical Fatal] (default Info)
  -quiet
    	Quiet mode, sets log level to warning
version

Short 'numeric' version (v skipped, useful for docker image tags etc)

$ sampleServer version
0.1.1

Documentation

Overview

Package cli contains utilities for command line tools and server main()s to handle flags, arguments, version, logging (fortio.org/log), etc... And for ServerMain the setup of a confimap/directory watch for flags and a config endpoint (uses fortio.org/dflag). Configure Config (Configuration fields), setup additional [flag]s before calling Main or ServerMain.

Index

Constants

This section is empty.

Variables

View Source
var (
	// Config is how to setup the arguments, flags and usage parsing for [Main] and [ServerMain].
	// At minium set the MinArgs and MaxArgs fields. See [Configuration] for the fields.
	Config    Configuration
	QuietFlag = flag.Bool("quiet", false, "Quiet mode, sets log level to warning")
	// If not set to true, will setup static loglevel flag and logger output for client tools.
	ServerMode = false
	// Override this to change the exit function (for testing), will be applied to log.Fatalf too.
	ExitFunction = os.Exit
)

Functions

func ErrArgCount added in v0.3.0

func ErrArgCount(prefix string, expected, actual int) bool

func ErrUsage

func ErrUsage(msg string, args ...any) bool

Show usage and error message on stderr and exit with code 1 or returns false.

func Main

func Main() bool

Main handles your commandline and flag parsing. Sets up flags first then call Main. For a server with dynamic flags, call ServerMain instead. returns true if there was no error. Might not return and have already exited for help/usage/etc...

func Plural added in v0.3.0

func Plural(i int, noun string) string

Plural adds an "s" to the noun if i is not 1.

func PluralExt added in v0.3.0

func PluralExt(i int, noun string, ext string) string

PluralExt returns the noun with an extension if i is not 1. Eg: PluralExt(1, "address", "es") -> "address" PluralExt(3 /* or 0 */, "address", "es") -> "addresses"

func ServerMain

func ServerMain() bool

ServerMain returns true if a config port server has been started caller needs to select {} after its own code is ready. Will have exited if there are usage errors (wrong number of arguments, bad flags etc...). It sets up (optional) config-dir to watch and listen on config-port for dynamic flag changes and UI/api.

func Usage

func Usage(w io.Writer, msg string, args ...any)

Types

type Configuration added in v0.2.0

type Configuration struct {
	// Will be filled automatically by the cli package, using fortio.org/version FromBuildInfo().
	ShortVersion string // x.y.z from tag/install
	LongVersion  string // version plus go version plus OS/arch
	FullVersion  string // LongVersion plus build date and git sha
	// Following should be specified.
	ProgramName string // Used at the beginning of Usage()
	// Cli usage/arguments example, ie "url1..." program name and "[flags]" will be added"
	// can include \n for additional details in the Usage() before the flags are dumped.
	ArgsHelp string
	MinArgs  int // Minimum number of arguments expected
	MaxArgs  int // Maximum number of arguments expected. 0 means same as MinArgs. -1 means no limit.
	// contains filtered or unexported fields
}

Configuration for your Main() or ServerMain() function.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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