Documentation
¶
Overview ¶
Package cli exposes helpers to build command-line binaries with cobra and viper.
Example (ChildCmd) ¶
package main
import (
"fmt"
"log"
"github.com/fredbi/go-cli/cli"
"github.com/spf13/cobra"
"github.com/spf13/pflag"
"github.com/spf13/viper"
)
// config key mappings
const (
keyLog = "app.log.level"
keyURL = "app.url"
keyParallel = "app.parallel"
keyUser = "app.user"
keyWorkers = "app.child.workers"
keyDry = "run.dryRun"
)
// globalFlags captures CLI flags.
//
// In this example, we prefer to control over where the flag values are stored.
//
// This is not needed if all configuration is bound to viper.
var globalFlags cliFlags
type (
cliFlags struct {
DryRun bool
URL string
Parallel int
User string
LogLevel string
Child childFlags
}
childFlags struct {
Workers int
}
)
// Default values for flags.
func (f cliFlags) Defaults() cliFlags {
return cliFlags{
URL: "https://www.example.com",
Parallel: 2,
LogLevel: "info",
Child: childFlags{
Workers: 5,
},
}
}
// applyDefaults set default values for the config. It is consistent with flag defaults.
func (f cliFlags) applyDefaults(cfg *viper.Viper) {
cfg.SetDefault(keyURL, globalFlags.Defaults().URL)
cfg.SetDefault(keyParallel, globalFlags.Defaults().Parallel)
cfg.SetDefault(keyLog, globalFlags.Defaults().LogLevel)
cfg.SetDefault(keyWorkers, globalFlags.Defaults().Child.Workers)
}
// root command execution
func rootRunFunc(c *cobra.Command, _ []string) error {
cfg := cli.ConfigFromContext(c.Context())
if cfg == nil {
cli.Die("failed to retrieve config")
}
fmt.Println(
"example called\n",
fmt.Sprintf("URL config: %s\n", cfg.GetString(keyURL)),
fmt.Sprintf("log level config: %s\n", cfg.GetString(keyLog)),
fmt.Sprintf("parallel config: %d\n", cfg.GetInt(keyParallel)),
fmt.Sprintf("user config: %s\n", cfg.GetString(keyUser)),
)
fmt.Println(
"global flags values evaluated by root\n",
fmt.Sprintf("%#v", globalFlags),
)
return nil
}
// child command execution
func childRunFunc(c *cobra.Command, _ []string) error {
cfg := cli.ConfigFromContext(c.Context())
fmt.Println(
"subcommand called\n",
fmt.Sprintf("URL config: %s\n", cfg.GetString(keyURL)),
fmt.Sprintf("parallel config: %d\n", cfg.GetInt(keyParallel)),
fmt.Sprintf("user config: %s\n", cfg.GetString(keyUser)),
fmt.Sprintf("workers config: %s\n", cfg.GetString(keyWorkers)),
)
fmt.Println(
"global flags values evaluated by child\n",
fmt.Sprintf("%#v", globalFlags),
)
return nil
}
func emptyRunFunc(c *cobra.Command, _ []string) error {
cfg := cli.ConfigFromContext(c.Context())
fmt.Println("command called:", c.Name())
fmt.Println("injected config:", cfg.AllSettings())
return nil
}
/*
target:
func Execute() error {
return cli.NewCommand(
&cobra.Command{},
cli.WithConfigurator(
cli.Config(globalFlags.applyDefaults),
),
cli.WithTypedFlag(...),
cli.WithTypedPersistentFlag(&globalFlags.LogLevel, "log-level", globalFlags.Default().LogLevel, "Controls logging verbosity"),
cli.WithSubCommands(
cli.NewComand(
&cobra.Command{
...
},
cli.WithTypedFlags(...),
),
),
).Execute()
}
*/
func RootCmd() *cli.Command {
return cli.NewCommand(
&cobra.Command{
Use: "example",
Short: "examplifies a cobra command",
Long: "...",
RunE: rootRunFunc,
},
cli.WithFlag(&globalFlags.DryRun, "dry-run", globalFlags.Defaults().DryRun, "Dry run",
cli.BindFlagToConfig(keyDry),
),
cli.WithPersistentFlag(&globalFlags.LogLevel, "log-level", globalFlags.Defaults().LogLevel, "Controls logging verbosity",
cli.BindFlagToConfig(keyLog),
),
cli.WithPersistentFlag(&globalFlags.URL, "url", globalFlags.Defaults().URL, "The URL to connect to",
cli.BindFlagToConfig(keyURL),
),
cli.WithPersistentFlagP(&globalFlags.Parallel, "parallel", "p", globalFlags.Defaults().Parallel, "Degree of parallelism",
cli.BindFlagToConfig(keyParallel),
),
cli.WithPersistentFlagFunc(func(flags *pflag.FlagSet) string {
const userFlag = "user"
flags.StringVar(&globalFlags.User, userFlag, globalFlags.Defaults().User, "Originating user")
return userFlag
},
cli.FlagIsRequired(), cli.BindFlagToConfig(keyUser),
),
cli.WithSubCommands(
cli.NewCommand(
&cobra.Command{
Use: "child",
Short: "sub-command example",
Long: "...",
RunE: childRunFunc,
},
cli.WithFlag(&globalFlags.Child.Workers, "workers", globalFlags.Defaults().Child.Workers, "Number of workers threads",
cli.FlagIsRequired(),
cli.BindFlagToConfig(keyWorkers),
),
cli.WithSubCommands(
cli.NewCommand(
&cobra.Command{
Use: "grandchild",
Short: "sub-sub-command example",
Long: "...",
RunE: emptyRunFunc,
},
),
),
),
cli.NewCommand(
&cobra.Command{
Use: "version",
Short: "another sub-command example",
Long: "...",
RunE: emptyRunFunc,
},
),
),
cli.WithConfig(cli.Config(globalFlags.applyDefaults)),
)
}
func main() {
rootCmd := RootCmd()
if err := rootCmd.ExecuteWithArgs(
"child",
"--parallel",
"20",
"--url",
"https://www.zorg.com",
"--user",
"zorg",
"--workers",
"12",
); err != nil {
log.Fatal("executing:", err)
}
fmt.Println("done")
}
Output: subcommand called URL config: https://www.zorg.com parallel config: 20 user config: zorg workers config: 12 global flags values evaluated by child cli_test.cliFlags{DryRun:false, URL:"https://www.zorg.com", Parallel:20, User:"zorg", LogLevel:"info", Child:cli_test.childFlags{Workers:12}} done
Example (Help) ¶
package main
import (
"fmt"
"log"
"github.com/fredbi/go-cli/cli"
"github.com/spf13/cobra"
"github.com/spf13/pflag"
"github.com/spf13/viper"
)
// config key mappings
const (
keyLog = "app.log.level"
keyURL = "app.url"
keyParallel = "app.parallel"
keyUser = "app.user"
keyWorkers = "app.child.workers"
keyDry = "run.dryRun"
)
// globalFlags captures CLI flags.
//
// In this example, we prefer to control over where the flag values are stored.
//
// This is not needed if all configuration is bound to viper.
var globalFlags cliFlags
type (
cliFlags struct {
DryRun bool
URL string
Parallel int
User string
LogLevel string
Child childFlags
}
childFlags struct {
Workers int
}
)
// Default values for flags.
func (f cliFlags) Defaults() cliFlags {
return cliFlags{
URL: "https://www.example.com",
Parallel: 2,
LogLevel: "info",
Child: childFlags{
Workers: 5,
},
}
}
// applyDefaults set default values for the config. It is consistent with flag defaults.
func (f cliFlags) applyDefaults(cfg *viper.Viper) {
cfg.SetDefault(keyURL, globalFlags.Defaults().URL)
cfg.SetDefault(keyParallel, globalFlags.Defaults().Parallel)
cfg.SetDefault(keyLog, globalFlags.Defaults().LogLevel)
cfg.SetDefault(keyWorkers, globalFlags.Defaults().Child.Workers)
}
// root command execution
func rootRunFunc(c *cobra.Command, _ []string) error {
cfg := cli.ConfigFromContext(c.Context())
if cfg == nil {
cli.Die("failed to retrieve config")
}
fmt.Println(
"example called\n",
fmt.Sprintf("URL config: %s\n", cfg.GetString(keyURL)),
fmt.Sprintf("log level config: %s\n", cfg.GetString(keyLog)),
fmt.Sprintf("parallel config: %d\n", cfg.GetInt(keyParallel)),
fmt.Sprintf("user config: %s\n", cfg.GetString(keyUser)),
)
fmt.Println(
"global flags values evaluated by root\n",
fmt.Sprintf("%#v", globalFlags),
)
return nil
}
// child command execution
func childRunFunc(c *cobra.Command, _ []string) error {
cfg := cli.ConfigFromContext(c.Context())
fmt.Println(
"subcommand called\n",
fmt.Sprintf("URL config: %s\n", cfg.GetString(keyURL)),
fmt.Sprintf("parallel config: %d\n", cfg.GetInt(keyParallel)),
fmt.Sprintf("user config: %s\n", cfg.GetString(keyUser)),
fmt.Sprintf("workers config: %s\n", cfg.GetString(keyWorkers)),
)
fmt.Println(
"global flags values evaluated by child\n",
fmt.Sprintf("%#v", globalFlags),
)
return nil
}
func emptyRunFunc(c *cobra.Command, _ []string) error {
cfg := cli.ConfigFromContext(c.Context())
fmt.Println("command called:", c.Name())
fmt.Println("injected config:", cfg.AllSettings())
return nil
}
/*
target:
func Execute() error {
return cli.NewCommand(
&cobra.Command{},
cli.WithConfigurator(
cli.Config(globalFlags.applyDefaults),
),
cli.WithTypedFlag(...),
cli.WithTypedPersistentFlag(&globalFlags.LogLevel, "log-level", globalFlags.Default().LogLevel, "Controls logging verbosity"),
cli.WithSubCommands(
cli.NewComand(
&cobra.Command{
...
},
cli.WithTypedFlags(...),
),
),
).Execute()
}
*/
func RootCmd() *cli.Command {
return cli.NewCommand(
&cobra.Command{
Use: "example",
Short: "examplifies a cobra command",
Long: "...",
RunE: rootRunFunc,
},
cli.WithFlag(&globalFlags.DryRun, "dry-run", globalFlags.Defaults().DryRun, "Dry run",
cli.BindFlagToConfig(keyDry),
),
cli.WithPersistentFlag(&globalFlags.LogLevel, "log-level", globalFlags.Defaults().LogLevel, "Controls logging verbosity",
cli.BindFlagToConfig(keyLog),
),
cli.WithPersistentFlag(&globalFlags.URL, "url", globalFlags.Defaults().URL, "The URL to connect to",
cli.BindFlagToConfig(keyURL),
),
cli.WithPersistentFlagP(&globalFlags.Parallel, "parallel", "p", globalFlags.Defaults().Parallel, "Degree of parallelism",
cli.BindFlagToConfig(keyParallel),
),
cli.WithPersistentFlagFunc(func(flags *pflag.FlagSet) string {
const userFlag = "user"
flags.StringVar(&globalFlags.User, userFlag, globalFlags.Defaults().User, "Originating user")
return userFlag
},
cli.FlagIsRequired(), cli.BindFlagToConfig(keyUser),
),
cli.WithSubCommands(
cli.NewCommand(
&cobra.Command{
Use: "child",
Short: "sub-command example",
Long: "...",
RunE: childRunFunc,
},
cli.WithFlag(&globalFlags.Child.Workers, "workers", globalFlags.Defaults().Child.Workers, "Number of workers threads",
cli.FlagIsRequired(),
cli.BindFlagToConfig(keyWorkers),
),
cli.WithSubCommands(
cli.NewCommand(
&cobra.Command{
Use: "grandchild",
Short: "sub-sub-command example",
Long: "...",
RunE: emptyRunFunc,
},
),
),
),
cli.NewCommand(
&cobra.Command{
Use: "version",
Short: "another sub-command example",
Long: "...",
RunE: emptyRunFunc,
},
),
),
cli.WithConfig(cli.Config(globalFlags.applyDefaults)),
)
}
func main() {
rootCmd := RootCmd()
rootCmd.SetArgs([]string{
"--help",
})
if err := rootCmd.Execute(); err != nil {
log.Fatal("executing:", err)
}
fmt.Println("done")
}
Output: ... Usage: example [flags] example [command] Available Commands: child sub-command example completion Generate the autocompletion script for the specified shell help Help about any command version another sub-command example Flags: --dry-run Dry run -h, --help help for example --log-level string Controls logging verbosity (default "info") -p, --parallel int Degree of parallelism (default 2) --url string The URL to connect to (default "https://www.example.com") --user string Originating user Use "example [command] --help" for more information about a command. done
Example (PrintCmd) ¶
package main
import (
"fmt"
"github.com/fredbi/go-cli/cli"
"github.com/spf13/cobra"
"github.com/spf13/pflag"
"github.com/spf13/viper"
)
// config key mappings
const (
keyLog = "app.log.level"
keyURL = "app.url"
keyParallel = "app.parallel"
keyUser = "app.user"
keyWorkers = "app.child.workers"
keyDry = "run.dryRun"
)
// globalFlags captures CLI flags.
//
// In this example, we prefer to control over where the flag values are stored.
//
// This is not needed if all configuration is bound to viper.
var globalFlags cliFlags
type (
cliFlags struct {
DryRun bool
URL string
Parallel int
User string
LogLevel string
Child childFlags
}
childFlags struct {
Workers int
}
)
// Default values for flags.
func (f cliFlags) Defaults() cliFlags {
return cliFlags{
URL: "https://www.example.com",
Parallel: 2,
LogLevel: "info",
Child: childFlags{
Workers: 5,
},
}
}
// applyDefaults set default values for the config. It is consistent with flag defaults.
func (f cliFlags) applyDefaults(cfg *viper.Viper) {
cfg.SetDefault(keyURL, globalFlags.Defaults().URL)
cfg.SetDefault(keyParallel, globalFlags.Defaults().Parallel)
cfg.SetDefault(keyLog, globalFlags.Defaults().LogLevel)
cfg.SetDefault(keyWorkers, globalFlags.Defaults().Child.Workers)
}
// root command execution
func rootRunFunc(c *cobra.Command, _ []string) error {
cfg := cli.ConfigFromContext(c.Context())
if cfg == nil {
cli.Die("failed to retrieve config")
}
fmt.Println(
"example called\n",
fmt.Sprintf("URL config: %s\n", cfg.GetString(keyURL)),
fmt.Sprintf("log level config: %s\n", cfg.GetString(keyLog)),
fmt.Sprintf("parallel config: %d\n", cfg.GetInt(keyParallel)),
fmt.Sprintf("user config: %s\n", cfg.GetString(keyUser)),
)
fmt.Println(
"global flags values evaluated by root\n",
fmt.Sprintf("%#v", globalFlags),
)
return nil
}
// child command execution
func childRunFunc(c *cobra.Command, _ []string) error {
cfg := cli.ConfigFromContext(c.Context())
fmt.Println(
"subcommand called\n",
fmt.Sprintf("URL config: %s\n", cfg.GetString(keyURL)),
fmt.Sprintf("parallel config: %d\n", cfg.GetInt(keyParallel)),
fmt.Sprintf("user config: %s\n", cfg.GetString(keyUser)),
fmt.Sprintf("workers config: %s\n", cfg.GetString(keyWorkers)),
)
fmt.Println(
"global flags values evaluated by child\n",
fmt.Sprintf("%#v", globalFlags),
)
return nil
}
func emptyRunFunc(c *cobra.Command, _ []string) error {
cfg := cli.ConfigFromContext(c.Context())
fmt.Println("command called:", c.Name())
fmt.Println("injected config:", cfg.AllSettings())
return nil
}
/*
target:
func Execute() error {
return cli.NewCommand(
&cobra.Command{},
cli.WithConfigurator(
cli.Config(globalFlags.applyDefaults),
),
cli.WithTypedFlag(...),
cli.WithTypedPersistentFlag(&globalFlags.LogLevel, "log-level", globalFlags.Default().LogLevel, "Controls logging verbosity"),
cli.WithSubCommands(
cli.NewComand(
&cobra.Command{
...
},
cli.WithTypedFlags(...),
),
),
).Execute()
}
*/
func RootCmd() *cli.Command {
return cli.NewCommand(
&cobra.Command{
Use: "example",
Short: "examplifies a cobra command",
Long: "...",
RunE: rootRunFunc,
},
cli.WithFlag(&globalFlags.DryRun, "dry-run", globalFlags.Defaults().DryRun, "Dry run",
cli.BindFlagToConfig(keyDry),
),
cli.WithPersistentFlag(&globalFlags.LogLevel, "log-level", globalFlags.Defaults().LogLevel, "Controls logging verbosity",
cli.BindFlagToConfig(keyLog),
),
cli.WithPersistentFlag(&globalFlags.URL, "url", globalFlags.Defaults().URL, "The URL to connect to",
cli.BindFlagToConfig(keyURL),
),
cli.WithPersistentFlagP(&globalFlags.Parallel, "parallel", "p", globalFlags.Defaults().Parallel, "Degree of parallelism",
cli.BindFlagToConfig(keyParallel),
),
cli.WithPersistentFlagFunc(func(flags *pflag.FlagSet) string {
const userFlag = "user"
flags.StringVar(&globalFlags.User, userFlag, globalFlags.Defaults().User, "Originating user")
return userFlag
},
cli.FlagIsRequired(), cli.BindFlagToConfig(keyUser),
),
cli.WithSubCommands(
cli.NewCommand(
&cobra.Command{
Use: "child",
Short: "sub-command example",
Long: "...",
RunE: childRunFunc,
},
cli.WithFlag(&globalFlags.Child.Workers, "workers", globalFlags.Defaults().Child.Workers, "Number of workers threads",
cli.FlagIsRequired(),
cli.BindFlagToConfig(keyWorkers),
),
cli.WithSubCommands(
cli.NewCommand(
&cobra.Command{
Use: "grandchild",
Short: "sub-sub-command example",
Long: "...",
RunE: emptyRunFunc,
},
),
),
),
cli.NewCommand(
&cobra.Command{
Use: "version",
Short: "another sub-command example",
Long: "...",
RunE: emptyRunFunc,
},
),
),
cli.WithConfig(cli.Config(globalFlags.applyDefaults)),
)
}
func main() {
rootCmd := RootCmd()
fmt.Println(rootCmd.String())
}
Output: example child grandchild version
Example (RootCmd) ¶
package main
import (
"fmt"
"log"
"github.com/fredbi/go-cli/cli"
"github.com/spf13/cobra"
"github.com/spf13/pflag"
"github.com/spf13/viper"
)
// config key mappings
const (
keyLog = "app.log.level"
keyURL = "app.url"
keyParallel = "app.parallel"
keyUser = "app.user"
keyWorkers = "app.child.workers"
keyDry = "run.dryRun"
)
// globalFlags captures CLI flags.
//
// In this example, we prefer to control over where the flag values are stored.
//
// This is not needed if all configuration is bound to viper.
var globalFlags cliFlags
type (
cliFlags struct {
DryRun bool
URL string
Parallel int
User string
LogLevel string
Child childFlags
}
childFlags struct {
Workers int
}
)
// Default values for flags.
func (f cliFlags) Defaults() cliFlags {
return cliFlags{
URL: "https://www.example.com",
Parallel: 2,
LogLevel: "info",
Child: childFlags{
Workers: 5,
},
}
}
// applyDefaults set default values for the config. It is consistent with flag defaults.
func (f cliFlags) applyDefaults(cfg *viper.Viper) {
cfg.SetDefault(keyURL, globalFlags.Defaults().URL)
cfg.SetDefault(keyParallel, globalFlags.Defaults().Parallel)
cfg.SetDefault(keyLog, globalFlags.Defaults().LogLevel)
cfg.SetDefault(keyWorkers, globalFlags.Defaults().Child.Workers)
}
// root command execution
func rootRunFunc(c *cobra.Command, _ []string) error {
cfg := cli.ConfigFromContext(c.Context())
if cfg == nil {
cli.Die("failed to retrieve config")
}
fmt.Println(
"example called\n",
fmt.Sprintf("URL config: %s\n", cfg.GetString(keyURL)),
fmt.Sprintf("log level config: %s\n", cfg.GetString(keyLog)),
fmt.Sprintf("parallel config: %d\n", cfg.GetInt(keyParallel)),
fmt.Sprintf("user config: %s\n", cfg.GetString(keyUser)),
)
fmt.Println(
"global flags values evaluated by root\n",
fmt.Sprintf("%#v", globalFlags),
)
return nil
}
// child command execution
func childRunFunc(c *cobra.Command, _ []string) error {
cfg := cli.ConfigFromContext(c.Context())
fmt.Println(
"subcommand called\n",
fmt.Sprintf("URL config: %s\n", cfg.GetString(keyURL)),
fmt.Sprintf("parallel config: %d\n", cfg.GetInt(keyParallel)),
fmt.Sprintf("user config: %s\n", cfg.GetString(keyUser)),
fmt.Sprintf("workers config: %s\n", cfg.GetString(keyWorkers)),
)
fmt.Println(
"global flags values evaluated by child\n",
fmt.Sprintf("%#v", globalFlags),
)
return nil
}
func emptyRunFunc(c *cobra.Command, _ []string) error {
cfg := cli.ConfigFromContext(c.Context())
fmt.Println("command called:", c.Name())
fmt.Println("injected config:", cfg.AllSettings())
return nil
}
/*
target:
func Execute() error {
return cli.NewCommand(
&cobra.Command{},
cli.WithConfigurator(
cli.Config(globalFlags.applyDefaults),
),
cli.WithTypedFlag(...),
cli.WithTypedPersistentFlag(&globalFlags.LogLevel, "log-level", globalFlags.Default().LogLevel, "Controls logging verbosity"),
cli.WithSubCommands(
cli.NewComand(
&cobra.Command{
...
},
cli.WithTypedFlags(...),
),
),
).Execute()
}
*/
func RootCmd() *cli.Command {
return cli.NewCommand(
&cobra.Command{
Use: "example",
Short: "examplifies a cobra command",
Long: "...",
RunE: rootRunFunc,
},
cli.WithFlag(&globalFlags.DryRun, "dry-run", globalFlags.Defaults().DryRun, "Dry run",
cli.BindFlagToConfig(keyDry),
),
cli.WithPersistentFlag(&globalFlags.LogLevel, "log-level", globalFlags.Defaults().LogLevel, "Controls logging verbosity",
cli.BindFlagToConfig(keyLog),
),
cli.WithPersistentFlag(&globalFlags.URL, "url", globalFlags.Defaults().URL, "The URL to connect to",
cli.BindFlagToConfig(keyURL),
),
cli.WithPersistentFlagP(&globalFlags.Parallel, "parallel", "p", globalFlags.Defaults().Parallel, "Degree of parallelism",
cli.BindFlagToConfig(keyParallel),
),
cli.WithPersistentFlagFunc(func(flags *pflag.FlagSet) string {
const userFlag = "user"
flags.StringVar(&globalFlags.User, userFlag, globalFlags.Defaults().User, "Originating user")
return userFlag
},
cli.FlagIsRequired(), cli.BindFlagToConfig(keyUser),
),
cli.WithSubCommands(
cli.NewCommand(
&cobra.Command{
Use: "child",
Short: "sub-command example",
Long: "...",
RunE: childRunFunc,
},
cli.WithFlag(&globalFlags.Child.Workers, "workers", globalFlags.Defaults().Child.Workers, "Number of workers threads",
cli.FlagIsRequired(),
cli.BindFlagToConfig(keyWorkers),
),
cli.WithSubCommands(
cli.NewCommand(
&cobra.Command{
Use: "grandchild",
Short: "sub-sub-command example",
Long: "...",
RunE: emptyRunFunc,
},
),
),
),
cli.NewCommand(
&cobra.Command{
Use: "version",
Short: "another sub-command example",
Long: "...",
RunE: emptyRunFunc,
},
),
),
cli.WithConfig(cli.Config(globalFlags.applyDefaults)),
)
}
func main() {
rootCmd := RootCmd()
rootCmd.SetArgs([]string{
"--dry-run",
"--log-level",
"debug",
"--parallel",
"15",
"--user",
"fred",
},
)
if err := rootCmd.Execute(); err != nil {
log.Fatal("executing:", err)
}
fmt.Println("done")
}
Output: example called URL config: https://www.example.com log level config: debug parallel config: 15 user config: fred global flags values evaluated by root cli_test.cliFlags{DryRun:true, URL:"https://www.example.com", Parallel:15, User:"fred", LogLevel:"debug", Child:cli_test.childFlags{Workers:5}} done
Index ¶
- Variables
- func Config(defaulters ...func(*viper.Viper)) *viper.Viper
- func ConfigForEnv(env string, defaulters ...func(*viper.Viper)) *viper.Viper
- func ConfigFromContext(ctx context.Context) *viper.Viper
- func ContextWithConfig(ctx context.Context, cfg *viper.Viper) context.Context
- func Die(format string, args ...any)
- func Must(err error)
- func MustBindFromFlagSet(cfg *viper.Viper, key, flagName string, flags *pflag.FlagSet)
- func MustBindPFlag(cfg *viper.Viper, key string, flag *pflag.Flag)
- func SetConfigOptions(opts ...config.Option)
- func SetDie(fatalFunc func(string, ...any))
- type Command
- func (c *Command) AddCommand(subs ...*Command)
- func (c *Command) BindFlags()
- func (c *Command) Commands() []*Command
- func (c *Command) Config() *viper.Viper
- func (c *Command) ExecuteContext(ctx context.Context) error
- func (c *Command) ExecuteWithArgs(args ...string) error
- func (c *Command) RegisterFlags()
- func (c *Command) String() string
- type FlagOption
- type Option
- func WithConfig(cfg *viper.Viper) Option
- func WithFlag[T gflag.FlaggablePrimitives | gflag.FlaggableTypes](addr *T, name string, defaultValue T, usage string, opts ...FlagOption) Option
- func WithFlagFunc(regFunc RegisterFunc, opts ...FlagOption) Option
- func WithFlagP[T gflag.FlaggablePrimitives | gflag.FlaggableTypes](addr *T, name, short string, defaultValue T, usage string, opts ...FlagOption) Option
- func WithPersistentFlag[T gflag.FlaggablePrimitives | gflag.FlaggableTypes](addr *T, name string, defaultValue T, usage string, opts ...FlagOption) Option
- func WithPersistentFlagFunc(regFunc RegisterFunc, opts ...FlagOption) Option
- func WithPersistentFlagP[T gflag.FlaggablePrimitives | gflag.FlaggableTypes](addr *T, name, short string, defaultValue T, usage string, opts ...FlagOption) Option
- func WithPersistentSliceFlag[T gflag.FlaggablePrimitives | gflag.FlaggableTypes](addr *[]T, name string, defaultValue []T, usage string, opts ...FlagOption) Option
- func WithPersistentSliceFlagP[T gflag.FlaggablePrimitives | gflag.FlaggableTypes](addr *[]T, name, short string, defaultValue []T, usage string, ...) Option
- func WithSliceFlag[T gflag.FlaggablePrimitives | gflag.FlaggableTypes](addr *[]T, name string, defaultValue []T, usage string, opts ...FlagOption) Option
- func WithSliceFlagP[T gflag.FlaggablePrimitives | gflag.FlaggableTypes](addr *[]T, name, short string, defaultValue []T, usage string, ...) Option
- func WithSubCommands(subs ...*Command) Option
- type RegisterFunc
Examples ¶
Constants ¶
This section is empty.
Variables ¶
var ( // ConfigEnv defines the environment variable used by the Config() function // to find the current environment. ConfigEnv = "CONFIG_ENV" // ConfigDebugEnv defines the environment variable used to instruct the config loader // to dump all config keys for debugging. ConfigDebugEnv = "DEBUG_CONFIG" )
Functions ¶
func Config ¶
Config calls ConfigForEnv, with the current environment resolved from the variable "CONFIG_ENV".
func ConfigForEnv ¶
ConfigForEnv loads and merge a set of config files for a given environment and applies some defaults,
It assumes that config files follow the conventions defined by "github.com/fredbi/go-cli/config".
It dies upon failure.
Environment variable settings
- If the environment variable "DEBUG_CONFIG" is set, the loaded settings are dumped to standard output as JSON.
- The environment variable "CONFIG_DIR" defines the folder where the root configuration is located.
func ConfigFromContext ¶
ConfigFromContext retrieves a configuration registry from the context.
func ContextWithConfig ¶
ContextWithConfig puts a configuration registry in the context.
func Die ¶
Die exits the current process with some final croak.
This wraps log.Fatal for convenient testing.
func MustBindFromFlagSet ¶
MustBindFromFlagSet binds a key in a *viper.Viper registry to command-line flag found in a flag set (*pflag.FlagSet).
Dies on error. This happens if the flag set is nil or if the requested flag has not been registered in the flag set yet.
func MustBindPFlag ¶
MustBindPlag binds a key in a *viper.Viper registry to a command-line flag (*pflag.Flag).
Dies on error. This happens if the flag is nil.
func SetConfigOptions ¶
SetConfigOption defines package-level defaults for config options, when using ConfigForEnv or Config.
By default, this package sets no option and uses all defaults from the config package.
Types ¶
type Command ¶
Command wraps a *cobra.Command with some options to register and bind flags and config more easily.
func NewCommand ¶
NewCommand builds a new Command wrapping a *cobra.Command.
func (*Command) AddCommand ¶
AddCommand adds child command(s).
func (*Command) BindFlags ¶
func (c *Command) BindFlags()
BindFlags binds the command-line flags marked as such to the configuration registry.
This applies recursively to all sub-commands.
It doesn't perform anything if no flags or no config are set for the command (use the options WithFlag() and WithConfig())
func (*Command) ExecuteContext ¶
ExecuteContext wraps cobra.Command.ExecuteContext() by ensuring the config is in the context.
func (*Command) ExecuteWithArgs ¶
ExecuteWithArgs is a convenience wrapper to execute a command with preset args.
This is primarily intended for testing commands.
func (*Command) RegisterFlags ¶
func (c *Command) RegisterFlags()
Register command-line flags for this command.
type FlagOption ¶
type FlagOption func(*flagOption)
func BindFlagToConfig ¶
func BindFlagToConfig(key string) FlagOption
BindFlagToConfig declares the flag as bound to a configuration key in the viper registry.
func FlagIsRequired ¶
func FlagIsRequired() FlagOption
FlagIsRequired declares the flag as required for the command.
type Option ¶
type Option func(*options)
Option configures a Command.
func WithConfig ¶
WithConfig adds a viper.Viper configuration to the command tree.
func WithFlag ¶
func WithFlag[T gflag.FlaggablePrimitives | gflag.FlaggableTypes](addr *T, name string, defaultValue T, usage string, opts ...FlagOption) Option
TODO: with/without flag address WithFlag declares a flag of any type supported by gflag, with some options.
func WithFlagFunc ¶
func WithFlagFunc(regFunc RegisterFunc, opts ...FlagOption) Option
WithFlagFunc declares a command flag using a RegisterFunc function and some flag options.
func WithFlagP ¶
func WithFlagP[T gflag.FlaggablePrimitives | gflag.FlaggableTypes](addr *T, name, short string, defaultValue T, usage string, opts ...FlagOption) Option
WithFlagP declares a flag of any type supported by gflag, with a short name and some options.
func WithPersistentFlag ¶
func WithPersistentFlag[T gflag.FlaggablePrimitives | gflag.FlaggableTypes](addr *T, name string, defaultValue T, usage string, opts ...FlagOption) Option
WithPersistentFlag declares a persistent flag of any type supported by gflag, with some options.
func WithPersistentFlagFunc ¶
func WithPersistentFlagFunc(regFunc RegisterFunc, opts ...FlagOption) Option
WithPersistentFlagFunc declares a persistent flag for the command using a RegisterFunc function and some flag options.
func WithPersistentFlagP ¶
func WithPersistentFlagP[T gflag.FlaggablePrimitives | gflag.FlaggableTypes](addr *T, name, short string, defaultValue T, usage string, opts ...FlagOption) Option
WithPersistentFlagP declares a persistent flag of any type supported by gflag, with a short name and some options.
func WithPersistentSliceFlag ¶
func WithPersistentSliceFlag[T gflag.FlaggablePrimitives | gflag.FlaggableTypes](addr *[]T, name string, defaultValue []T, usage string, opts ...FlagOption) Option
WithPersistentSliceFlag declares a persistent flag of any slice type supported by gflag, with some options.
func WithPersistentSliceFlagP ¶
func WithPersistentSliceFlagP[T gflag.FlaggablePrimitives | gflag.FlaggableTypes](addr *[]T, name, short string, defaultValue []T, usage string, opts ...FlagOption) Option
WithPersistentSliceFlagP declares a persistent flag of any type supported by gflag, with a short name and some options.
func WithSliceFlag ¶
func WithSliceFlag[T gflag.FlaggablePrimitives | gflag.FlaggableTypes](addr *[]T, name string, defaultValue []T, usage string, opts ...FlagOption) Option
WithSliceFlag declares a flag of any slice type supported by gflag, with some options.
func WithSliceFlagP ¶
func WithSliceFlagP[T gflag.FlaggablePrimitives | gflag.FlaggableTypes](addr *[]T, name, short string, defaultValue []T, usage string, opts ...FlagOption) Option
WithSliceFlagP declares a flag of any slice type supported by gflag, with a short name and some options.
func WithSubCommands ¶
WithSubCommands adds child commands.
type RegisterFunc ¶
RegisterFunc registers a flag to a provided pflag.FlagSet and returns the flag name.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package gflag exposes generic types to deal with flags.
|
Package gflag exposes generic types to deal with flags. |
|
extensions
Package extensions provides extensions to the github.com/spf13/pflag package.
|
Package extensions provides extensions to the github.com/spf13/pflag package. |