Documentation
¶
Overview ¶
Package cobrax collects the cobra and pflag wiring command-line tools keep rewriting: a --color[=WHEN] flag and other flags that take auto, always or never (AddModeFlag), enumerated flags that complete their values, older spellings of flags kept as hidden switches (AddFlagAlias), file completion switched off where no file is expected, a hardened completion command that can install its scripts for the current user or write them to a path of the tool's choice, completion candidates cached on disk, filtered by prefix (CompletePrefix) and kept free of control characters (SafeCompletions), 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.AddCompletionInstall(cobrax.HardenCompletion(root))
root.SetArgs(cobrax.JoinSpacedBoolValues(root, os.Args[1:]))
Index ¶
- Constants
- func AddCompletionInstall(completion *cobra.Command)
- func AddFlagAlias(cmd *cobra.Command, flags *pflag.FlagSet, alias FlagAlias)
- func AllowSpacedBool(flags *pflag.FlagSet, names ...string)
- func CachedCompletion(app, scope string, ttl, timeout time.Duration, ...) cobra.CompletionFunc
- func CompletePrefix(candidates []cobra.Completion, typed string) ([]cobra.Completion, cobra.ShellCompDirective)
- func CompleteValues(values ...string) cobra.CompletionFunc
- func CompletionInstallPath(program, shell string) (string, error)
- 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 SafeCompletions(values []cobra.Completion) []cobra.Completion
- func SetVersion(root *cobra.Command, info buildinfo.Info)
- func WriteCompletionScript(root *cobra.Command, shell, path string) error
- type ColorOption
- 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 FlagAlias
- type ModeOption
- type ModeValue
- 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 AddCompletionInstall ¶ added in v0.8.0
AddCompletionInstall gives the bash, zsh and fish commands of completion, the command HardenCompletion returned, an --install flag. With it the command writes the script to the file CompletionInstallPath names for the shell, instead of to its output, and says where it went:
example completion bash --install Installed bash completion to /home/me/.local/share/bash-completion/completions/example
The file is replaced atomically: it is written next to its place and renamed, so a shell starting meanwhile reads the old script or the new one, never half of one. Missing directories are created. The script can be read by its owner only, which is all a shell running as that user needs. A symbolic link where the file belongs is refused rather than replaced, as fsx.WriteFile refuses it. --no-descriptions applies as it does to a script that is printed. A failure to write the file is returned as a *ScriptError.
The flag is opt-in, so a tool decides whether its completion command writes files; without AddCompletionInstall the commands do what HardenCompletion made them do. A nil completion is ignored, so the result of HardenCompletion can be passed as it is. PowerShell gets no flag: it has no directory it loads scripts from, only a profile to source them in.
func AddFlagAlias ¶ added in v0.9.0
AddFlagAlias registers alias.Old as a hidden switch on flags, which is cmd.Flags() or cmd.PersistentFlags() and must hold the flag alias.New. Giving the switch sets alias.New to alias.Value, as if --New=Value had been given, so the value is checked as that flag checks it and the flag counts as changed. --Old=false is accepted and does nothing, and any other value than a boolean is an error.
Unless alias.Silent is set, the first use of the switch writes a note to the error stream of cmd, cmd.ErrOrStderr():
WARNING: --no-colors is deprecated, use --color=never
The note is written once per registration, also when the switch is given twice. The switch is left out of help and of completion, so it keeps working without being offered.
AddFlagAlias panics when alias.New is not a flag of flags, and when a flag named alias.Old is already defined, as pflag does for any redefined flag.
Example ¶
An older spelling keeps working, says what to use instead, and is not shown in help.
package main
import (
"fmt"
"os"
"github.com/spf13/cobra"
"github.com/mittwald/cli-kit/cobrax"
)
func main() {
root := &cobra.Command{Use: "example", Run: func(*cobra.Command, []string) {}}
links := cobrax.AddModeFlag(root, "links", "when to make links: auto, always or never")
cobrax.AddFlagAlias(root, root.PersistentFlags(), cobrax.FlagAlias{Old: "no-links", New: "links", Value: "never"})
root.SetErr(os.Stdout)
root.SetArgs([]string{"--no-links"})
_ = root.Execute()
fmt.Println(links.Mode())
}
Output: WARNING: --no-links is deprecated, use --links=never never
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.
What load returns usually comes from elsewhere, such as names a remote service lists, and the shell shows it as it is. The candidates therefore go through SafeCompletions, which leaves out every candidate that holds a control character, an escape sequence among them.
func CompletePrefix ¶ added in v0.9.0
func CompletePrefix(candidates []cobra.Completion, typed string) ([]cobra.Completion, cobra.ShellCompDirective)
CompletePrefix returns the candidates whose value starts with typed, the word being completed, for a completion function to return. Candidates may carry a description after a tab; only the value is matched. They go through SafeCompletions first.
The directive switches off file names, and when every match ends in "=", such as a key that wants its value, it also tells the shell not to add a space after the completed word, so the value can be typed straight after it:
func(_ *cobra.Command, _ []string, typed string) ([]cobra.Completion, cobra.ShellCompDirective) {
return cobrax.CompletePrefix([]cobra.Completion{"name=", "status=", "limit="}, typed)
}
Example ¶
Filter keys complete without a space after them, so the value can follow.
package main
import (
"fmt"
"github.com/spf13/cobra"
"github.com/mittwald/cli-kit/cobrax"
)
func main() {
keys := []cobra.Completion{"name=\tfilter by name", "namespace=", "limit"}
matches, directive := cobrax.CompletePrefix(keys, "na")
fmt.Printf("%q %v\n", matches, directive&cobra.ShellCompDirectiveNoSpace != 0)
}
Output: ["name=\tfilter by name" "namespace="] true
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 CompletionInstallPath ¶ added in v0.8.0
CompletionInstallPath returns the file a completion script for program is installed to for shell, for the current user:
- bash: program in the completions directory of bash-completion, under the first absolute directory BASH_COMPLETION_USER_DIR lists, or else under $XDG_DATA_HOME/bash-completion. bash-completion 2 loads it from there the first time program is completed.
- zsh: _program in $XDG_DATA_HOME/zsh/site-functions. zsh loads it from there only when that directory is on its fpath, before compinit runs.
- fish: program.fish in $XDG_CONFIG_HOME/fish/completions, which fish loads from.
XDG_DATA_HOME defaults to ~/.local/share and XDG_CONFIG_HOME to ~/.config; a value that is not an absolute path is ignored, as the XDG Base Directory specification asks. Any other shell, and a program name that is empty or holds a path separator, is an error.
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, nor is the value of another flag: in "--name --stable false" the flag --name is given the value "--stable". 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 SafeCompletions ¶ added in v0.9.0
func SafeCompletions(values []cobra.Completion) []cobra.Completion
SafeCompletions returns the candidates of values that are safe to hand a shell, in their order, in a new slice. A candidate is cobra's "value\tdescription": a value, and optionally a tab and a description, as cobra.CompletionWithDesc builds it. That one tab is kept. A candidate is left out when its value is empty, when its value or its description holds a control character (C0, DEL or C1, among them a newline, a further tab or the ESC that starts an escape sequence), or when it is not valid UTF-8, whose stray bytes a terminal may read as C1 controls.
Use it for candidates that come from elsewhere, such as names a remote service lists: the shell writes them to the terminal as they are, and a candidate holding a control character could not be completed to the name it stands for anyway. CachedCompletion and CompletePrefix apply it.
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
func WriteCompletionScript ¶ added in v0.9.0
WriteCompletionScript writes the completion script of root for shell, one of bash, zsh, fish and powershell, to path. It is for a tool that keeps its script where an earlier version put it, such as a file in its configuration directory that the user's shell profile sources; AddCompletionInstall writes to the directory the shell loads scripts from by itself.
The script carries descriptions unless root.CompletionOptions.DisableDescriptions is set. The file is replaced atomically, as AddCompletionInstall replaces it, and can be read by its owner only. Missing directories are created for their owner only (mode 0700), since the directory may be one the tool keeps other files in. A symbolic link at path is refused, as fsx.WriteFile refuses it.
An unknown shell is an error; a failure to generate or write the script is returned as a *ScriptError.
Types ¶
type ColorOption ¶ added in v0.6.0
type ColorOption func(*colorFlag)
ColorOption changes how a --color flag registered with AddColorFlagWith reads its value.
func BareColor ¶ added in v0.6.0
func BareColor(mode term.ColorMode) ColorOption
BareColor sets the mode a bare --color means, and with it --color= and --color=true, the other spellings of a bare flag. The default is term.ColorAlways, the way ls reads a bare --color; term.ColorAuto is the way grep reads it.
func ColorAliases ¶ added in v0.6.0
func ColorAliases(names ...string) ColorOption
ColorAliases registers the flag under further names, such as the British spelling, all sharing one value.
func ColorError ¶ added in v0.6.0
func ColorError(invalid func(value string) error) ColorOption
ColorError words the error for a value the flag rejects: invalid is called with the value as given and returns the error. pflag still puts its own words in front, naming the value and the flag.
func StrictColor ¶ added in v0.6.0
func StrictColor() ColorOption
StrictColor accepts auto, always and never alone, in any case, besides the spellings of a bare --color. The other spellings term.ParseColorMode reads, such as yes, none or tty, are rejected.
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.
The zero ColorValue reads values as AddColorFlag does; AddColorFlagWith and its options change that.
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; AddColorFlagWith and BareColor give the grep reading, "auto". Values are read with term.ParseColorMode. 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 AddColorFlagWith ¶ added in v0.6.0
func AddColorFlagWith(cmd *cobra.Command, usage string, opts ...ColorOption) *ColorValue
AddColorFlagWith is AddColorFlag with options: aliases, the reading of a bare --color, which values are accepted, and the wording of the error. A tool that reads a bare --color as auto and takes nothing but auto, always and never registers its flag as
cobrax.AddColorFlagWith(root, "when to use color: auto, always or never", cobrax.BareColor(term.ColorAuto), cobrax.StrictColor())
Without options it registers the flag AddColorFlag does, and it panics in the same case.
Example ¶
A --color flag read the way grep reads it: a bare --color means auto, and only auto, always and never are accepted.
package main
import (
"fmt"
"github.com/spf13/cobra"
"github.com/mittwald/cli-kit/cobrax"
"github.com/mittwald/cli-kit/term"
)
func main() {
defer term.SetColorMode(term.CurrentColorMode())
root := &cobra.Command{Use: "example", SilenceErrors: true, SilenceUsage: true, Run: func(*cobra.Command, []string) {}}
color := cobrax.AddColorFlagWith(root, "when to use color: auto, always or never",
cobrax.BareColor(term.ColorAuto), cobrax.StrictColor())
root.SetArgs([]string{"--color"})
_ = root.Execute()
fmt.Println(color.Mode())
root.SetArgs([]string{"--color=yes"})
fmt.Println(root.Execute())
}
Output: auto invalid argument "yes" for "--color" flag: invalid color mode "yes": want one of auto, always, never
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. An empty value and "true", the spellings of a bare --color, mean the mode BareColor chose, term.ColorAlways unless it chose another.
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. Where // neither is available, values are loaded uncached. 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, and where there is no cache directory, such as without $HOME, Get calls load every time.
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 FlagAlias ¶ added in v0.9.0
type FlagAlias struct {
// Old is the name of the switch, without dashes.
Old string
// New is the name of the flag it stands for, without dashes.
New string
// Value is the value it gives that flag.
Value string
// Silent keeps the user from being told about the replacement, for a
// spelling that is as good as the new one.
Silent bool
}
FlagAlias is an older spelling of a flag: a switch that stands for a flag with a value, as --no-colors stands for --color=never. AddFlagAlias registers it.
type ModeOption ¶ added in v0.9.0
type ModeOption func(*modeFlag)
ModeOption changes how a flag registered with AddModeFlag reads its value. The options are those of AddColorFlagWith, for a flag of any name.
func BareMode ¶ added in v0.9.0
func BareMode(mode term.ColorMode) ModeOption
BareMode sets the mode the bare flag means, and with it --name= and --name=true, the other spellings of a bare flag. The default is term.ColorAlways.
func ModeAliases ¶ added in v0.9.0
func ModeAliases(names ...string) ModeOption
ModeAliases registers the flag under further names, all sharing one value.
func ModeError ¶ added in v0.9.0
func ModeError(invalid func(value string) error) ModeOption
ModeError words the error for a value the flag rejects: invalid is called with the value as given and returns the error. pflag still puts its own words in front, naming the value and the flag.
func StrictMode ¶ added in v0.9.0
func StrictMode() ModeOption
StrictMode accepts auto, always and never alone, in any case, besides the spellings of a bare flag. The other spellings term.ParseColorMode reads, such as yes, none or tty, are rejected.
type ModeValue ¶ added in v0.9.0
type ModeValue struct {
// contains filtered or unexported fields
}
ModeValue is a pflag.Value for a flag that takes auto, always or never, such as --links[=WHEN] or --pager[=WHEN]. Unlike a ColorValue it records nothing for the process: the program asks ModeValue.Mode and decides, for a link with term.ShouldLink, for example.
The zero ModeValue reads values as AddModeFlag without options does.
func AddModeFlag ¶ added in v0.9.0
func AddModeFlag(cmd *cobra.Command, name, usage string, opts ...ModeOption) *ModeValue
AddModeFlag registers --name[=WHEN] as a persistent flag of cmd: a flag that takes auto, always or never, as --color does, for a choice other than color. A bare --name means always unless BareMode says otherwise, a value that is not accepted fails the command line as it is parsed, and completion offers auto, always and never. The flag is auto until it is given.
A tool that makes links of its table's first column registers
links := cobrax.AddModeFlag(root, "links", "when to make links: auto, always or never")
and asks term.ShouldLink(links.Mode(), os.Stdout) before it writes one.
AddModeFlag panics when a flag of that name is already defined, as pflag does for any redefined flag.
func (*ModeValue) IsBoolFlag ¶ added in v0.9.0
IsBoolFlag lets the flag stand alone when it is used with the standard library's flag package. pflag reads NoOptDefVal instead, which AddModeFlag sets.
func (*ModeValue) Mode ¶ added in v0.9.0
Mode returns the mode the flag was last set to, term.ColorAuto when it was not given.
func (*ModeValue) Set ¶ added in v0.9.0
Set reads a value with term.ParseColorMode, or only auto, always and never under StrictMode, and records it. An empty value and "true", the spellings of a bare flag, mean the mode BareMode chose, term.ColorAlways unless it chose another. A value that is not accepted is an error, so the command line is rejected as it is parsed.
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.