carapace

package module
v0.8.11 Latest Latest
Warning

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

Go to latest
Published: Oct 9, 2021 License: Apache-2.0 Imports: 30 Imported by: 0

README

carapace

CircleCI PkgGoDev documentation GoReportCard codecov

Command-line completion generator for cobra with support for:

Status

WIP: works, but expect some api changes and small hiccups like a special character not yet escaped

Usage

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

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

carapace.Gen(rootCmd)

Standalone Mode

Carapace can also be used to provide completion for arbitrary commands as well (similar to aws_completer). See rsteube/carapace-bin for examples. There is also a binary to parse flags from gnu help pages at caraparse.

Example

An example implementation can be found in the example folder.

cd example
go build .

# bash
PATH=$PATH:$(pwd)
source <(example _carapace bash)

# elvish
paths=[$@paths (pwd)]
eval (example _carapace elvish | slurp)

# fish
set PATH $PATH (pwd) 
example _carapace fish | source

# oil
PATH=$PATH:$(pwd)
source <(example _carapace oil)

# powershell
Set-PSReadlineKeyHandler -Key Tab -Function MenuComplete
$env:PATH += ":$pwd"
example _carapace powershell | out-string | Invoke-Expression

# tcsh
set autolist
eval `example _carapace tcsh`

# xonsh
$PATH.append($(pwd))
exec($(example _carapace xonsh))

# zsh
PATH=$PATH:$(pwd)
source <(example _carapace zsh)

example <TAB>

or use docker-compose:

docker-compose pull
docker-compose run --rm build
docker-compose run --rm [bash|elvish|fish|ion|nushell|oil|powershell|tcsh|xonsh|zsh]

example <TAB>

Projects

Documentation

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 testingT)

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 ActionFiles

func ActionFiles(suffix ...string) Action

ActionFiles completes files with optional suffix filtering

func ActionMessage

func ActionMessage(msg string) 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 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) NoSpace added in v0.8.1

func (a Action) NoSpace() Action

NoSpace disables space suffix

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) 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 argument 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) Snippet added in v0.0.6

func (c Carapace) Snippet(shell 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
}

Context provides information during completion

type InvokedAction added in v0.1.1

type InvokedAction 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(divider string) Action

ToMultiPartsA create an ActionMultiParts from values with given divider

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 {
	// LongShorthand forces flag names to use non-posix single `-` style
	// No shorthand flags should be used in this mode (thus no shorthand chaining).
	//   false // chown --verbose (default)
	//   true  // java -classpath
	LongShorthand bool
	// OptArgDelimiter changes the delimiter for optional flag arguments
	//   "=" // tail --verbose=descriptor (default)
	//   ":" // java -verbose:class
	OptArgDelimiter string
}

Opts contains overrides for completion behaviour

Directories

Path Synopsis
cmd
internal
ion
oil
uid
zsh
pkg
ps

Jump to

Keyboard shortcuts

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