carapace

package module
v0.29.4 Latest Latest
Warning

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

Go to latest
Published: Dec 26, 2022 License: Apache-2.0 Imports: 29 Imported by: 0

README

carapace

CircleCI PkgGoDev documentation GoReportCard Coverage Status

Command argument completion generator for cobra. You can read more about it here: A pragmatic approach to shell completion.

Supported shells:

Usage

Calling carapace.Gen on the root command is sufficient to enable completion using the hidden command.

import (
    "github.com/rsteube/carapace"
)

carapace.Gen(rootCmd)

Example

An example implementation can be found in the example folder.

Standalone Mode

Carapace can also be used to provide completion for arbitrary commands. See carapace-bin for examples.

Documentation

Overview

Package carapace is a command argument completion generator for spf13/cobra

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ActionExecCommand added in v0.5.8

func ActionExecCommand(name string, arg ...string) func(f func(output []byte) Action) Action

ActionExecCommand invokes given command and transforms its output using given function on success or returns ActionMessage with the first line of stderr if available.

carapace.ActionExecCommand("git", "remote")(func(output []byte) carapace.Action {
  lines := strings.Split(string(output), "\n")
  return carapace.ActionValues(lines[:len(lines)-1]...)
})

func Batch added in v0.8.0

func Batch(actions ...Action) batch

Batch creates a batch of Actions that can be invoked in parallel.

func IsCallback added in v0.0.6

func IsCallback() bool

IsCallback returns true if current program invocation is a callback.

func Override added in v0.7.0

func Override(o Opts)

Override changes completion behaviour for non-posix style flags in standalone mode. Mostly done by patching `os.Args` before command execution and thus must be called before it. These are considered hacks and might undergo changes in future (or replaced by a custom pflag fork).

func Execute() error {
    carapace.Override(carapace.Opts{
        LongShorthand: true,
        OptArgDelimiter: ":",
    })
	return rootCmd.Execute()
}

func Test added in v0.5.0

func Test(t interface{ Error(args ...interface{}) })

Test verifies the configuration (e.g. flag name exists)

func TestCarapace(t *testing.T) {
    carapace.Test(t)
}

Types

type Action

type Action struct {
	// contains filtered or unexported fields
}

Action indicates how to complete a flag or positional argument.

func ActionCallback

func ActionCallback(callback CompletionCallback) Action

ActionCallback invokes a go function during completion.

func ActionDirectories added in v0.0.11

func ActionDirectories() Action

ActionDirectories completes directories.

func ActionExecute

func ActionExecute(cmd *cobra.Command) Action

ActionExecute executes completion on an internal command TODO example

func ActionFiles

func ActionFiles(suffix ...string) Action

ActionFiles completes files with optional suffix filtering.

func ActionImport added in v0.12.7

func ActionImport(output []byte) Action

ActionImport parses the json output from export as Action

carapace.Gen(rootCmd).PositionalAnyCompletion(
	carapace.ActionCallback(func(c carapace.Context) carapace.Action {
		args := []string{"_carapace", "export", ""}
		args = append(args, c.Args...)
		args = append(args, c.CallbackValue)
		return carapace.ActionExecCommand("command", args...)(func(output []byte) carapace.Action {
			return carapace.ActionImport(output)
		})
	}),
)

func ActionMessage

func ActionMessage(msg string, args ...interface{}) Action

ActionMessage displays a help messages in places where no completions can be generated.

func ActionMultiParts

func ActionMultiParts(divider string, callback func(c Context) Action) Action

ActionMultiParts completes multiple parts of words separately where each part is separated by some char (CallbackValue is set to the currently completed part during invocation)

func ActionStyleConfig added in v0.19.0

func ActionStyleConfig() Action

ActionStyleConfig completes style configuration

carapace.Value=blue
carapace.Description=magenta

func ActionStyledValues added in v0.18.0

func ActionStyledValues(values ...string) Action

ActionStyledValues is like ActionValues but also accepts a style.

func ActionStyledValuesDescribed added in v0.18.0

func ActionStyledValuesDescribed(values ...string) Action

ActionStyledValuesDescribed is like ActionValues but also accepts a style.

func ActionStyles added in v0.19.0

func ActionStyles(styles ...string) Action

Actionstyles completes styles

blue
bg-magenta

func ActionValues

func ActionValues(values ...string) Action

ActionValues completes arbitrary keywords (values).

func ActionValuesDescribed

func ActionValuesDescribed(values ...string) Action

ActionValuesDescribed completes arbitrary key (values) with an additional description (value, description pairs).

func (Action) Cache added in v0.2.4

func (a Action) Cache(timeout time.Duration, keys ...pkgcache.Key) Action

Cache cashes values of a CompletionCallback for given duration and keys.

func (Action) Chdir added in v0.8.10

func (a Action) Chdir(dir string) Action

Chdir changes the current working directory to the named directory during invocation.

func (Action) Invoke added in v0.1.1

func (a Action) Invoke(c Context) InvokedAction

Invoke executes the callback of an action if it exists (supports nesting).

func (Action) List added in v0.26.4

func (a Action) List(divider string) Action

List wraps the Action in an ActionMultiParts with given divider.

func (Action) MultiParts added in v0.28.1

func (a Action) MultiParts(dividers ...string) Action

MultiParts splits values of an Action by given dividers and completes each segment separately.

func (Action) NoSpace added in v0.8.1

func (a Action) NoSpace(suffixes ...rune) Action

NoSpace disables space suffix for given characters (or all if none are given).

func (Action) Style added in v0.18.0

func (a Action) Style(style string) Action

Style sets the style

ActionValues("yes").Style(style.Green)
ActionValues("no").Style(style.Red)

func (Action) StyleF added in v0.19.0

func (a Action) StyleF(f func(s string) string) Action

Style sets the style using a function

ActionValues("dir/", "test.txt").StyleF(style.ForPathExt)
ActionValues("true", "false").StyleF(style.ForKeyword)

func (Action) StyleR added in v0.20.0

func (a Action) StyleR(style *string) Action

Style sets the style using a reference

ActionValues("value").StyleR(&style.Carapace.Value)
ActionValues("description").StyleR(&style.Carapace.Value)

func (Action) Suppress added in v0.12.5

func (a Action) Suppress(expr ...string) Action

Suppress suppresses specific error messages using regular expressions.

func (Action) Tag added in v0.26.5

func (a Action) Tag(tag string) Action

Tag sets the tag.

ActionValues("192.168.1.1", "127.0.0.1").Tag("interfaces").

func (Action) TagF added in v0.26.5

func (a Action) TagF(f func(value string) string) Action

Tag sets the tag using a function.

ActionValues("192.168.1.1", "127.0.0.1").TagF(func(value string) string {
	return "interfaces"
})

func (Action) UniqueList added in v0.26.2

func (a Action) UniqueList(divider string) Action

UniqueList wraps the Action in an ActionMultiParts with given divider.

func (Action) Usage added in v0.27.0

func (a Action) Usage(usage string, args ...interface{}) Action

Usage sets the usage.

func (Action) UsageF added in v0.27.0

func (a Action) UsageF(f func() string) Action

Usage sets the usage using a function.

type ActionMap

type ActionMap map[string]Action

ActionMap maps Actions to an identifier.

type Carapace

type Carapace struct {
	// contains filtered or unexported fields
}

Carapace wraps cobra.Command to define completions.

func Gen

func Gen(cmd *cobra.Command) *Carapace

Gen initialized Carapace for given command.

func (Carapace) DashAnyCompletion added in v0.13.0

func (c Carapace) DashAnyCompletion(action Action)

DashAnyCompletion defines completion for any positional arguments after dash (`--`) not already defined.

func (Carapace) DashCompletion added in v0.13.0

func (c Carapace) DashCompletion(action ...Action)

DashCompletion defines completion for positional arguments after dash (`--`) using a list of Actions.

func (Carapace) FlagCompletion

func (c Carapace) FlagCompletion(actions ActionMap)

FlagCompletion defines completion for flags using a map consisting of name and Action.

func (Carapace) PositionalAnyCompletion added in v0.0.14

func (c Carapace) PositionalAnyCompletion(action Action)

PositionalAnyCompletion defines completion for any positional arguments not already defined.

func (Carapace) PositionalCompletion

func (c Carapace) PositionalCompletion(action ...Action)

PositionalCompletion defines completion for positional arguments using a list of Actions.

func (Carapace) PreInvoke added in v0.20.0

func (c Carapace) PreInvoke(f func(cmd *cobra.Command, flag *pflag.Flag, action Action) Action)

PreInvoke sets a function to alter actions before they are invoked (use on rootCmd).

func (Carapace) PreRun added in v0.23.1

func (c Carapace) PreRun(f func(cmd *cobra.Command, args []string))

PreRun sets a function to be run before completion (use on rootCmd).

func (Carapace) Snippet added in v0.0.6

func (c Carapace) Snippet(name string) (string, error)

Snippet creates completion script for given shell.

func (Carapace) Standalone added in v0.0.14

func (c Carapace) Standalone()

Standalone prevents cobra defaults interfering with standalone mode (e.g. implicit help command).

type CompletionCallback

type CompletionCallback func(c Context) Action

CompletionCallback is executed during completion of associated flag or positional argument.

type Context added in v0.4.0

type Context struct {
	// CallbackValue contains the (partial) value (or part of it during an ActionMultiParts) currently being completed
	CallbackValue string
	// Args contains the positional arguments of current (sub)command (exclusive the one currently being completed)
	Args []string
	// Parts contains the splitted CallbackValue during an ActionMultiParts (exclusive the part currently being completed)
	Parts []string
	// Env contains environment variables for current context
	Env []string
	// Dir contains the working directory for current context
	Dir string
}

Context provides information during completion.

func (Context) Abs added in v0.20.0

func (c Context) Abs(s string) (string, error)

func (Context) Command added in v0.20.0

func (c Context) Command(name string, arg ...string) *execabs.Cmd

Command returns the Cmd struct to execute the named program with the given arguments. Env and Dir are set using the Context. See exec.Command for most details.

func (*Context) Envsubst added in v0.20.2

func (c *Context) Envsubst(s string) (string, error)

func (*Context) Getenv added in v0.20.2

func (c *Context) Getenv(key string) string

Getenv retrieves the value of the environment variable named by the key.

func (*Context) LookupEnv added in v0.20.2

func (c *Context) LookupEnv(key string) (string, bool)

LookupEnv retrieves the value of the environment variable named by the key.

func (*Context) Setenv added in v0.16.0

func (c *Context) Setenv(key, value string)

Setenv sets the value of the environment variable named by the key.

type InvokedAction added in v0.1.1

type InvokedAction struct {
	Action
}

InvokedAction is a logical alias for an Action whose (nested) callback was invoked.

func (InvokedAction) Filter added in v0.1.1

func (a InvokedAction) Filter(values []string) InvokedAction

Filter filters given values (this should be done before any call to Prefix/Suffix as those alter the values being filtered)

a := carapace.ActionValues("A", "B", "C").Invoke(c)
b := a.Filter([]string{"B"}) // ["A", "C"]

func (InvokedAction) Merge added in v0.1.8

func (a InvokedAction) Merge(others ...InvokedAction) InvokedAction

Merge merges InvokedActions (existing values are overwritten)

a := carapace.ActionValues("A", "B").Invoke(c)
b := carapace.ActionValues("B", "C").Invoke(c)
c := a.Merge(b) // ["A", "B", "C"]

func (InvokedAction) Prefix added in v0.1.1

func (a InvokedAction) Prefix(prefix string) InvokedAction

Prefix adds a prefix to values (only the ones inserted, not the display values)

a := carapace.ActionValues("melon", "drop", "fall").Invoke(c)
b := a.Prefix("water") // ["watermelon", "waterdrop", "waterfall"] but display still ["melon", "drop", "fall"]

func (InvokedAction) Suffix added in v0.1.1

func (a InvokedAction) Suffix(suffix string) InvokedAction

Suffix adds a suffx to values (only the ones inserted, not the display values)

a := carapace.ActionValues("apple", "melon", "orange").Invoke(c)
b := a.Suffix("juice") // ["applejuice", "melonjuice", "orangejuice"] but display still ["apple", "melon", "orange"]

func (InvokedAction) ToA added in v0.1.1

func (a InvokedAction) ToA() Action

ToA casts an InvokedAction to Action.

func (InvokedAction) ToMultiPartsA added in v0.2.2

func (a InvokedAction) ToMultiPartsA(dividers ...string) Action

ToMultiPartsA create an ActionMultiParts from values with given dividers

a := carapace.ActionValues("A/B/C", "A/C", "B/C", "C").Invoke(c)
b := a.ToMultiPartsA("/") // completes segments separately (first one is ["A/", "B/", "C"])

type Opts added in v0.7.0

type Opts struct {
	// OptArgDelimiter changes the delimiter for optional flag arguments
	//   "=" // tail --verbose=descriptor (default)
	//   ":" // java -verbose:class
	OptArgDelimiter string
	// BridgeCompletion registers carapace completions to cobra's default completion
	BridgeCompletion bool
}

Opts contains overrides for completion behaviour.

Directories

Path Synopsis
cmd
internal
assert
Package assert provides test helpers
Package assert provides test helpers
cache
Package cache provides disk cache for Actions
Package cache provides disk cache for Actions
common
Package common code
Package common code
shell/bash
Package bash provides bash completion
Package bash provides bash completion
shell/bash_ble
Package bash_ble provides bash-ble completion
Package bash_ble provides bash-ble completion
shell/elvish
Package elvish provides elvish completion
Package elvish provides elvish completion
shell/export
Package export provides command structure export
Package export provides command structure export
shell/fish
Package fish provides fish completion
Package fish provides fish completion
shell/ion
Package ion provides Ion completion
Package ion provides Ion completion
shell/nushell
Package nushell provides Nushell completion
Package nushell provides Nushell completion
shell/oil
Package oil provides Oil completion
Package oil provides Oil completion
shell/powershell
Package powershell provides powershell completion
Package powershell provides powershell completion
shell/spec
Package spec provides spec file generation for use with carapace-bin
Package spec provides spec file generation for use with carapace-bin
shell/tcsh
Package tcsh provides tcsh completion
Package tcsh provides tcsh completion
shell/xonsh
Package xonsh provides Xonsh completion
Package xonsh provides Xonsh completion
shell/zsh
Package zsh provides zsh completion
Package zsh provides zsh completion
uid
Package uid provides unique identifiers
Package uid provides unique identifiers
pkg
cache
Package cache provides cache keys
Package cache provides cache keys
ps
Package ps provides shell determination by process name
Package ps provides shell determination by process name
style
Package style provide display coloring
Package style provide display coloring
third_party
github.com/elves/elvish/pkg/cli/lscolors
Package lscolors provides styling of filenames based on file features.
Package lscolors provides styling of filenames based on file features.
github.com/mitchellh/go-ps
ps provides an API for finding and listing processes in a platform-agnostic way.
ps provides an API for finding and listing processes in a platform-agnostic way.
golang.org/x/sys/execabs
Package execabs is a drop-in replacement for os/exec that requires PATH lookups to find absolute paths.
Package execabs is a drop-in replacement for os/exec that requires PATH lookups to find absolute paths.

Jump to

Keyboard shortcuts

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