Documentation
¶
Overview ¶
Package cobrax collects the cobra and pflag wiring command-line tools keep rewriting: a --color[=WHEN] flag, enumerated flags that complete their values, file completion switched off where no file is expected, a hardened completion command, completion candidates cached on disk, the "--flag false" spelling of boolean flags, and version output.
A typical root command:
root := &cobra.Command{Use: "example", SilenceUsage: true}
cobrax.AddColorFlag(root, "when to use color: auto, always or never")
output := cobrax.AddEnumFlag(root, root.PersistentFlags(), "output", "o",
"text", "output format", "text", "json", "yaml")
cobrax.SetVersion(root, buildinfo.Get())
root.AddCommand(listCmd, showCmd)
cobrax.NoFileCompletions(root)
cobrax.HardenCompletion(root)
root.SetArgs(cobrax.JoinSpacedBoolValues(root, os.Args[1:]))
Index ¶
- Constants
- func AllowSpacedBool(flags *pflag.FlagSet, names ...string)
- func CachedCompletion(app, scope string, ttl, timeout time.Duration, ...) cobra.CompletionFunc
- func CompleteValues(values ...string) cobra.CompletionFunc
- func HardenCompletion(root *cobra.Command) *cobra.Command
- func JoinSpacedBoolValues(root *cobra.Command, args []string) []string
- func NewVersionCommand(info buildinfo.Info) *cobra.Command
- func NoFileArgs(cmd *cobra.Command)
- func NoFileCompletions(cmd *cobra.Command, names ...string)
- func SetVersion(root *cobra.Command, info buildinfo.Info)
- type ColorValue
- type CompletionCache
- type Enum
- func (e *Enum) Allowed() []string
- func (e *Enum) Complete(cmd *cobra.Command, args []string, toComplete string) ([]cobra.Completion, cobra.ShellCompDirective)
- func (e *Enum) Set(value string) error
- func (e *Enum) String() string
- func (e *Enum) Type() string
- func (e *Enum) Value() string
- func (e *Enum) WithType(name string) *Enum
- type ScriptError
Examples ¶
Constants ¶
const ( // DefaultCompletionTTL is how long cached candidates are offered. DefaultCompletionTTL = time.Hour // DefaultCompletionTimeout bounds a load on a cold cache: a tab press that // hangs is worse than one that offers nothing. DefaultCompletionTimeout = 10 * time.Second )
Defaults for CompletionCache.
const SpacedBoolAnnotation = "cobrax_spaced_bool"
SpacedBoolAnnotation is the flag annotation AllowSpacedBool sets and JoinSpacedBoolValues looks for.
Variables ¶
This section is empty.
Functions ¶
func AllowSpacedBool ¶
AllowSpacedBool lets the named boolean flags take their value after a space, as in "--stable false", once JoinSpacedBoolValues rewrites the arguments. It suits tri-state settings where clearing a flag is as normal as setting it. It panics when a flag is missing or not boolean.
func CachedCompletion ¶
func CachedCompletion(app, scope string, ttl, timeout time.Duration, load func(context.Context) ([]string, error)) cobra.CompletionFunc
CachedCompletion returns a completion function that offers the strings load returns, cached per scope for ttl under the cache directory of app. load runs at most timeout long; zero ttl or timeout use the defaults. An empty result is not cached. A failing load completes nothing; the error is written to cobra's completion debug log.
func CompleteValues ¶
func CompleteValues(values ...string) cobra.CompletionFunc
CompleteValues returns a completion function that offers values and no file names. A value may carry a description after a tab, as cobra.CompletionWithDesc builds it.
func HardenCompletion ¶
HardenCompletion adds cobra's default completion command to root now, rather than when the command runs, and fixes three of its rough edges:
- "completion" with an unknown shell ("completion tcsh") fails instead of printing help with a successful exit status;
- scripts are written to the command's output writer at the time they are generated, so SetOut called after HardenCompletion still applies;
- a failure to write a script is returned as a *ScriptError.
Call it after every subcommand is added: cobra only adds the completion command to a root that has subcommands. It returns the completion command, or nil when there is none (no subcommands, or root.CompletionOptions.DisableDefaultCmd set).
func JoinSpacedBoolValues ¶
JoinSpacedBoolValues rewrites "--flag false" into "--flag=false" for the boolean flags that AllowSpacedBool marked, so the space form parses. Pass the result to root.SetArgs.
pflag gives a boolean flag NoOptDefVal "true", which lets "--flag" stand alone and leaves a following "false" behind as a positional argument. Only long flags are joined, and only when the command the arguments select has a marked flag of that name, its own or inherited: an unmarked flag of the same name on another command keeps its meaning. The next argument must be exactly "true" or "false" (in any case), and nothing after "--" is touched. For a shell completion request the word being completed is left alone.
Example ¶
package main
import (
"fmt"
"github.com/spf13/cobra"
"github.com/mittwald/cli-kit/cobrax"
)
func main() {
root := &cobra.Command{Use: "example", Run: func(*cobra.Command, []string) {}}
root.Flags().Bool("stable", true, "mark the release stable")
cobrax.AllowSpacedBool(root.Flags(), "stable")
fmt.Println(cobrax.JoinSpacedBoolValues(root, []string{"--stable", "false", "release-1"}))
}
Output: [--stable=false release-1]
func NewVersionCommand ¶
NewVersionCommand returns a "version" command that prints info in detail: the version, the revision, the build date and the Go release.
func NoFileArgs ¶
NoFileArgs switches off file-name completion for the positional arguments of cmd and its subcommands that complete nothing of their own: commands without ValidArgs or ValidArgsFunction.
func NoFileCompletions ¶
NoFileCompletions switches off file-name completion for flags of cmd, which shells otherwise offer for any flag that takes a value. With names it covers those flags; without, every value-taking flag of cmd and of its subcommands that has no completion function of its own. Call it after all flags and completion functions are registered.
It panics when a named flag does not exist.
func SetVersion ¶
SetVersion sets root.Version from info, which turns on cobra's --version flag, and makes it print "name version" on one line.
Example ¶
package main
import (
"github.com/spf13/cobra"
"github.com/mittwald/cli-kit/buildinfo"
"github.com/mittwald/cli-kit/cobrax"
)
func main() {
root := &cobra.Command{Use: "example", Run: func(*cobra.Command, []string) {}}
cobrax.SetVersion(root, buildinfo.Info{Version: "v1.4.0"})
root.SetArgs([]string{"--version"})
_ = root.Execute()
}
Output: example 1.4.0
Types ¶
type ColorValue ¶
type ColorValue struct {
// contains filtered or unexported fields
}
ColorValue is a pflag.Value for --color[=WHEN]. Setting it records the mode for the whole process with term.SetColorMode, so every package that asks term.Colored follows the flag.
func AddColorFlag ¶
func AddColorFlag(cmd *cobra.Command, usage string, aliases ...string) *ColorValue
AddColorFlag registers --color[=WHEN] as a persistent flag of cmd, plus any aliases (such as the British spelling), all sharing one value. A bare --color means "always", the way ls reads it; set the flag's NoOptDefVal to "auto" for the grep reading. Completion offers auto, always and never.
AddColorFlag panics when a flag of that name is already defined, as pflag does for any redefined flag.
func (*ColorValue) IsBoolFlag ¶
func (v *ColorValue) IsBoolFlag() bool
IsBoolFlag lets the flag stand alone, as a bare --color, when it is used with the standard library's flag package. pflag reads NoOptDefVal instead, which AddColorFlag sets.
func (*ColorValue) Mode ¶
func (v *ColorValue) Mode() term.ColorMode
Mode returns the mode the flag was last set to, term.ColorAuto when it was not given.
func (*ColorValue) Set ¶
func (v *ColorValue) Set(value string) error
Set parses a --color value with term.ParseColorMode and records it.
func (*ColorValue) String ¶
func (v *ColorValue) String() string
String returns the current mode's flag spelling.
type CompletionCache ¶
type CompletionCache[T any] struct { // App names the directory under the cache directory, usually the // command's name. It is required. App string // TTL is how long a cached value is used; zero means // [DefaultCompletionTTL]. TTL time.Duration // Timeout bounds one load; zero means [DefaultCompletionTimeout]. Timeout time.Duration // Dir overrides the base directory, os.UserCacheDir by default. Dir string // Keep decides whether a loaded value is worth caching. An empty answer // often means "not signed in yet" rather than "nothing exists", and // caching it would keep completion silent until the TTL runs out. Nil // caches every value. Keep func(T) bool }
CompletionCache keeps completion candidates that are slow to load, such as names fetched from a remote service, in a file under the user's cache directory, so a tab press answers from disk. Candidates are a hint for the shell, never what a command acts on, so a stale list costs little.
func (CompletionCache[T]) Get ¶
func (c CompletionCache[T]) Get(ctx context.Context, scope string, load func(context.Context) (T, error)) (T, error)
Get returns the value cached for scope while it is younger than the TTL, and otherwise calls load, bounded by the timeout, and caches its result. scope identifies what the value answers, such as a repository URL; it is hashed into the file name. Failing to write the cache is not an error.
type Enum ¶
type Enum struct {
// contains filtered or unexported fields
}
Enum is a pflag.Value that accepts one of a fixed set of strings, such as the formats an --output flag offers. Matching ignores case; the value keeps the allowed spelling.
func AddEnumFlag ¶
func AddEnumFlag(cmd *cobra.Command, flags *pflag.FlagSet, name, shorthand, value, usage string, allowed ...string) *Enum
AddEnumFlag defines an Enum flag on flags, which is cmd.Flags() or cmd.PersistentFlags(), and registers its completion on cmd. shorthand may be empty. It panics when the flag is already defined, as pflag does.
Example ¶
package main
import (
"fmt"
"github.com/spf13/cobra"
"github.com/mittwald/cli-kit/cobrax"
)
func main() {
root := &cobra.Command{
Use: "example",
RunE: func(cmd *cobra.Command, _ []string) error {
format, _ := cmd.Flags().GetString("output")
fmt.Println("format:", format)
return nil
},
}
cobrax.AddEnumFlag(root, root.Flags(), "output", "o", "text", "output format", "text", "json", "yaml")
root.SetArgs([]string{"--output", "YAML"})
_ = root.Execute()
}
Output: format: yaml
func NewEnum ¶
NewEnum returns an Enum holding value and accepting the allowed strings. value need not be one of them, so an empty default can mean "not given".
func (*Enum) Complete ¶
func (e *Enum) Complete(cmd *cobra.Command, args []string, toComplete string) ([]cobra.Completion, cobra.ShellCompDirective)
Complete is a cobra completion function offering the allowed strings.
type ScriptError ¶
type ScriptError struct {
// Shell is the shell the script was generated for.
Shell string
// Err is the underlying write error.
Err error
}
ScriptError reports that writing a completion script failed, as opposed to the command line being wrong. A caller that prints usage for bad input can skip it for this error: the command was right, its output failed.
func (*ScriptError) Unwrap ¶
func (e *ScriptError) Unwrap() error
Unwrap returns the underlying error.