3.1 KiB
3.1 KiB
go-pkg/cli
Lightweight, dependency-free command-line argument and option parsing library for Go.
Overview
This package provides a small, composable CLI parser with support for:
- boolean, string, int, and array/map options
- positional arguments (single and repeating)
- aliases, short flags, defaults and hidden options
- validation for incompatible options and custom "special" values
- automatic usage and version printing
See the core parser implementation in parser.go and the high-level API in cli.go.
Features
- Option types:
AddBoolOpt,AddStringOpt,AddIntOpt,AddStringArrayOpt,AddIntArrayOpt,AddStringMapOpt - Positional args:
AddStringArg,AddStringArrayArg - Usage & version output:
CliParser.Usage,CliParser.PrintVersion - Option tracing via
CliParser.TraceOptionsandSimpleOptionTracer - Programmatic option setting:
SetOptionValue
Quick start
Example: define options and parse argv
package main
import (
"fmt"
"git.portale-stac.it/go-pkg/cli"
)
func main() {
var parser cli.CliParser
parser.Init([]string{"prog", "--debug", "--config", "app.yaml", "input.txt"}, "$VER:prog,0.1.0,2025,email:$")
// define target variables and options
var debug bool
var config string
var inputs []string
parser.AddBoolOpt("debug", "d", &debug, "Enable debug")
parser.AddStringOpt("config", "c", &config, "app.yaml", "Config file")
parser.AddStringArrayArg("files", true, &inputs, "Input files")
// print usage: parser.Usage() - see [`CliParser.Usage`](cli-usage.go)
if err := parser.Parse(); err != nil {
fmt.Println("parse error:", err)
return
}
fmt.Println("debug:", debug)
fmt.Println("config:", config)
fmt.Println("inputs:", inputs)
}
Refer to the unit test for a realistic example: cli_test.go.
API Reference
Key types and methods:
CliParser— main parser typeCliParser.Init— initialize with argv and versionCliParser.Parse— run parsing- Option constructors:
AddBoolOpt,AddStringOpt,AddIntOpt,AddStringArrayOpt,AddIntArrayOpt,AddStringMapOpt - Arg constructors:
AddStringArg,AddStringArrayArg - Utilities:
TraceOptions,SetOptionValue,SimpleOptionTracer
For implementation details, consult:
- parser internals:
parser.go - option base helpers:
opt-base.go - usage/version printing:
cli-usage.go,cli-version.go
License
This project is licensed under the terms in LICENSE.
Contributing
Open issues or pull requests are welcome. Run and extend the tests in cli_test.go when making changes.