cli

package module
v1.2.0 Latest Latest
Warning

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

Go to latest
Published: Jul 6, 2023 License: Apache-2.0 Imports: 8 Imported by: 28

README

Go Reference Go Report Card GitHub Release

cli

Reduce boiler plate needed on each new Golang main functions (Command Line Interface) for both tools and servers (use fortio.org/scli ServerMain() for server)

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

You can see real use example in a tool like multicurl or a server like proxy.

It also supports (sub)commands style (where there is a word/command before the flags and remaining arguments, fortio uses that mode).

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() {
	myFlag := flag.String("myflag", "default", "my flag")
	cli.MinArgs = 2
	cli.MaxArgs = 4
	cli.Main() // Will have either called cli.ExitFunction or everything is valid
	// Next line output won't show when passed -quiet
	log.Infof("Info test, -myflag is %q", *myFlag)
	// This always shows
	log.Printf("Hello world, version %s, args %v", cli.ShortVersion, flag.Args())
	// This shows and is colorized and structured, unless loglevel is set to critical.
	log.S(log.Error, "Error test",
		log.Str("myflag", *myFlag),
		log.Attr("num_args", len(flag.Args())),
		log.Attr("args", flag.Args()))
}
$ sampleTool a
sampleTool 1.2.0 usage:
	sampleTool [flags] arg1 arg2 [arg3...arg4]
or 1 of the special arguments
	sampleTool {help|version|buildinfo}
flags:
  -logger-force-color
    	Force color output even if stderr isn't a terminal
  -logger-no-color
    	Prevent colorized output even if stderr is a terminal
  -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 loglevel to Error (quietly) to reduces the output
At least 2 arguments expected, got 1

or normal case (and now in color when on console)

$ sampleTool a b
15:30:50.217 I Info test, -myflag is "default"
15:30:50.217 I Hello world, version dev, args [a b]
15:30:50.217 E Error test, myflag="default", num_args="2", args="[a b]"

Additional builtins

buildinfo

e.g

% go install github.com/fortio/multicurl@latest
go: downloading github.com/fortio/multicurl v1.10.1
% multicurl buildinfo
1.10.1 h1:h9yM3XplwG7JWtVaSS0eJPiDmCJfnxvj3w+yoAMWMo4= go1.19.6 arm64 darwin
go	go1.19.6
path	github.com/fortio/multicurl
mod	github.com/fortio/multicurl	v1.10.1	h1:h9yM3XplwG7JWtVaSS0eJPiDmCJfnxvj3w+yoAMWMo4=
dep	fortio.org/cli	v0.6.1	h1:V9L6ly4oz4fJjeQ5745FulIMsFAwFZvLPSUN+cKUrKk=
dep	fortio.org/log	v1.2.2	h1:vs42JjNwiqbMbacittZjJE9+oi72Za6aekML9gKmILg=
dep	fortio.org/version	v1.0.2	h1:8NwxdX58aoeKx7T5xAPO0xlUu1Hpk42nRz5s6e6eKZ0=
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
% multicurl help
Fortio multicurl 1.10.1 usage:
	multicurl [flags] url
or 1 of the special arguments
	multicurl {help|version|buildinfo}
flags:
[...]
  -logger-force-color
    	Force color output even if stderr isn't a terminal
  -logger-no-color
    	Prevent colorized output even if stderr is a terminal
  -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)

 % multicurl version
1.10.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... Configure using the package variables (at minimum MinArgs unless your binary only accepts flags), setup additional flag before calling Main or fortio.org/scli.ServerMain for configmap and dynamic flags setup. Also supports (sub)commands style, see CommandBeforeFlags and Command.

Index

Constants

This section is empty.

Variables

View Source
var (
	// Out parameters:
	// *Version 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
	Command      string // first argument, if [CommandBeforeFlags] is true.
	// Following can/should be specified.
	ProgramName string // Used at the beginning of Usage()
	// Optional for programs using subcommand, command will be set in [Command].
	CommandBeforeFlags bool
	// 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, not counting (optional) command.
	MaxArgs  int // Maximum number of arguments expected. 0 means same as MinArgs. -1 means no limit.
	// 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
)

Configuration for your Main() or ServerMain() function. These variables is how to setup the arguments, flags and usage parsing for Main and [ServerMain]. At minium set the MinArgs should be set.

Functions

func ErrUsage

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

Show usage and error message on stderr and calls ExitFunction with code 1.

func Main

func Main()

Main handles your commandline and flag parsing. Sets up flags first then call Main. For a server with dynamic flags, call ServerMain instead. Will either have called ExitFunction (defaults to os.Exit) or returned if all validations passed.

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"

Types

This section is empty.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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