command argument completion generator for spf13/cobra

Overview

carapace

CircleCI PkgGoDev documentation GoReportCard codecov

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 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=[[email protected]paths (pwd)]
eval (example _carapace elvish | slurp)

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

# nushell [needs fork: https://github.com/rsteube/nushell]
example _carapace nushell | save example.nu ; nu -c 'source example.nu'

# 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
$COMPLETION_QUERY_LIMIT = 500 # increase limit
$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

  • carapace-bin multi-shell multi-command argument completer
  • go-jira-cli simple jira command line client
  • knoxite A data storage & backup system
  • lab cli client for GitLab
Comments
  • global `ActionMap` caching / completion initialization

    global `ActionMap` caching / completion initialization

    I have a json that holds all the information necessary to compose completion. Launching the command that generates that json takes up to 3 seconds in extreme cases (yeah, bad).

    [{"cell":"std","organelles":[{"clade":"runnables","organelle":"cli","readme":"/nix/store/0v43f20l1n9i2gcwrx7k7aab2wfz9qlg-cells/std/cli/Readme.md","targets":[{"actions":[{"description":"exec this target","name":"run"}],"deps":[],"description":"A tui for projects that conform to Standard","name":"default","readme":"/nix/store/0v43f20l1n9i2gcwrx7k7aab2wfz9qlg-cells/std/cli/default.md"}]},{"clade":"functions","organelle":"lib","readme":"/nix/store/0v43f20l1n9i2gcwrx7k7aab2wfz9qlg-cells/std/lib/Readme.md","targets":[{"actions":[],"deps":[],"description":"n/a","name":"fromMakesWith","readme":"/nix/store/0v43f20l1n9i2gcwrx7k7aab2wfz9qlg-cells/std/lib/fromMakesWith.md"},{"actions":[],"deps":[],"description":"n/a","name":"mkShell","readme":""}]},{"clade":"functions","organelle":"devshellProfiles","readme":"/nix/store/0v43f20l1n9i2gcwrx7k7aab2wfz9qlg-cells/std/devshellProfiles/Readme.md","targets":[{"actions":[],"deps":[],"description":"n/a","namestd/devshellProfiles/default.md"}]},{"clade":"devshells","organelle":"devshells","readme":"","targets":[{"actions":[{"description":"enter this devshell","name":"enter"}],"deps":[],"description":"n/a","name":"default","readme":""}]},{}],"readme":"/nix/store/0v43f20l1n9i2gcwrx7k7aab2wfz9qlg-cells/std/Readme.md"}]
    

    After transforming this into an ActionMap of carapace.ActionValues() I want to cache the entire ActionMap for ~30 sec, so that subsequent completions during the same completion "session" don't take 3 seconds each.

    What can I do?

    opened by blaggacao 10
  • Alias completion support

    Alias completion support

    I was looking to add support for git aliases in carapace-bin but I'm hitting a wall. To clarify, I don't want it to be able to autocomplete the names of aliases as git subcommands, but I want it to actually resolve the alias into whatever it is and continue autocompletion from there.

    So for example, if I have a git alias po = push origin, not only do I want git p<TAB> to suggest git po but I want git po <TAB> to autocomplete branches as if I typed git push origin <TAB>. I looked into the docs to and the closest thing that seemed relevant was PreInvoke but even then that didn't work when I tried it.

    Currently, I'm working around this by resolving the alias in my shell and then calling carapace to complete it but it would be great if this can be built in to carapace itself.

    opened by thatsmydoing 4
  • ActionMultiparts: support all divider variants

    ActionMultiparts: support all divider variants

    Not all dividers from the example are working in each shell. This is mostly due to how the shell is handling argument splitting.

    bash:

    • [x] @
    • [x] :
    • [x] ,
    • [x] .
    • [x] ...
    • [x] =
    • [x] (none)
    • [x] /

    elvish:

    • [x] @
    • [x] :
    • [x] ,
    • [x] .
    • [x] ...
    • [x] =
    • [x] (none)
    • [x] /

    fish:

    • [x] @
    • [x] :
    • [x] ,
    • [x] .
    • [x] ...
    • [x] =
    • [x] (none)
    • [x] /

    ion:

    • [x] @
    • [x] :
    • [x] ,
    • [x] .
    • [x] ...
    • [x] =
    • [x] (none)
    • [x] /

    nushell:

    • [x] @
    • [x] :
    • [x] ,
    • [x] .
    • [x] ...
    • [x] =
    • [x] (none)
    • [x] /

    oil:

    • [x] @
    • [x] :
    • [x] ,
    • [x] .
    • [x] ...
    • [x] =
    • [x] (none)
    • [x] /

    powershell:

    • [x] @
    • [x] :
    • [x] ,
    • [x] .
    • [x] ...
    • [x] =
    • [x] (none)
    • [x] /

    xonsh:

    • [x] @
    • [x] :
    • [x] ,
    • [x] .
    • [x] ...
    • [x] =
    • [x] (none)
    • [x] /

    zsh:

    • [x] @
    • [x] :
    • [x] ,
    • [x] .
    • [x] ...
    • [x] =
    • [x] (none)
    • [x] /
    bash fish zsh powershell elvish oil xonsh nushell ion 
    opened by rsteube 3
  • elvish: should default to `edit:complete-filename` if no match is found by carapace

    elvish: should default to `edit:complete-filename` if no match is found by carapace

    Currently, a lot of the completers feel broken in elvish because it prints an error if carapace cannot find a completion.

    Simple example:

    # navigate to carapace git project
    hx action.go # nake some changes
    # check changes
    git diff a<TAB>
    

    Expected: autocomplete to action, then a new tab will show:

     COMPLETING argument  
    action.go  action_test.go
    

    This would happen if the snippet defaults to edit:complete-filename if carapace fails the match:

    https://github.com/rsteube/carapace/blob/e961a1d209980f253febf405dfdd63ded9786b8c/internal/shell/elvish/snippet.go#L12-L21

    question elvish 
    opened by AlexanderBrevig 2
  • Error running tests on NixOS

    Error running tests on NixOS

    I'm trying to package carapace 0.12.3 for NixOS, but I get this:

    == RUN   TestActionDirectories
        assert.go:21:
            1c1
            < {Action:{rawValues:[{Value:docs/ Display:docs/ Description:} {Value:example/ Display:example/ Description:} {Value:internal/ Display:internal/ Description:} {Value:pkg/ Display:pkg/ Description:}] callback:<nil> nospace:true skipcache:false}}
            ---
            > {Action:{rawValues:[{Value:docs/ Display:docs/ Description:} {Value:example/ Display:example/ Description:} {Value:internal/ Display:internal/ Description:} {Value:pkg/ Display:pkg/ Description:} {Value:vendor/ Display:vendor/ Description:}] callback:<nil> nospace:true skipcache:false}}
    
        assert.go:21:
            1c1
            < {Action:{rawValues:[{Value:./docs/ Display:docs/ Description:} {Value:./example/ Display:example/ Description:} {Value:./internal/ Display:internal/ Description:} {Value:./pkg/ Display:pkg/ Description:}] callback:<nil> nospace:true skipcache:false}}
            ---
            > {Action:{rawValues:[{Value:./docs/ Display:docs/ Description:} {Value:./example/ Display:example/ Description:} {Value:./internal/ Display:internal/ Description:} {Value:./pkg/ Display:pkg/ Description:} {Value:./vendor/ Display:vendor/ Description:}] callback:<nil> nospace:true skipcache:false}}
    
    --- FAIL: TestActionDirectories (0.00s)
    === RUN   TestActionFiles
        assert.go:21:
            1c1
            < {Action:{rawValues:[{Value:README.md Display:README.md Description:} {Value:docs/ Display:docs/ Description:} {Value:example/ Display:example/ Description:} {Value:internal/ Display:internal/ Description:} {Value:pkg/ Display:pkg/ Description:}] callback:<nil> nospace:true skipcache:false}}
            ---
            > {Action:{rawValues:[{Value:README.md Display:README.md Description:} {Value:docs/ Display:docs/ Description:} {Value:example/ Display:example/ Description:} {Value:internal/ Display:internal/ Description:} {Value:pkg/ Display:pkg/ Description:} {Value:vendor/ Display:vendor/ Description:}] callback:<nil> nospace:true skipcache:false}}
    

    My go is not good enough to understand the problem, though. Can you help?

    opened by mredaelli 2
  • zsh: don't promote sourcing completion file

    zsh: don't promote sourcing completion file

    https://medium.com/@jzelinskie/please-dont-ship-binaries-with-shell-completion-as-commands-a8b1bcb8a0d0

    Sourcing completion files in zsh is common antipattern. Regular completion file should contain only code of completion function (source of _command), there is no need to declare function itself. Especially there shouldn't be any calls from compdef, this breaks completion if you you want to install completion file properly under $fpath, where it can be autoloaded on call. Usually it's task for package manager to put _command file under correct path.

    documentation zsh 
    opened by z0rc 2
  • ActionInvoke: locking mutex

    ActionInvoke: locking mutex

    ActionInvoke cannot be used in Batch as it is changing os.Stdout. either change it that os.Stdout is not needed or somehow ensure concurrency is not a problem (locking mutex - though that would contradict the parallel execution in Batch)

    bug 
    opened by rsteube 1
  • support multipart completion for flag names

    support multipart completion for flag names

    Some commands like gum have a large amount of flags that are grouped using a delimiter. MultiPart completion should be supported here for better overview with a configurable delimiter (. enabled as default?). This implicitly sets nospace though which is inconvenient so supporting conditional nospace would be good.

    2022-11-19T12:05:26,773138006+01:00

    2022-11-19T12:05:38,567836840+01:00

    enhancement 
    opened by rsteube 0
  • ZSH grouped/aliased completions

    ZSH grouped/aliased completions

    arguments options

    Features and enhancements

    This PR enhances ZSH completion with multiple new features. Most of them rely on using the _describe helper rather than compadd.

    ZSH specific

    • Completions can now be grouped together under a description, with action.Group(name).
    • Completions being aliases of each other (-f/--files, or command aliases) are now displayed together in completion listings.
    • Zstyle coloring has been adapted to still work despite those changes.
    • Padding dynamically and smartly computed, depending on the current "profile" of the completions.
    • Messages are now displayed through the _message ZSH helper, which now allows us to pass messages of arbitrary length, and with arbitrary color formatting within them (therefore, and provided left at the discretion of the library user).
    • Better suffix autoremoval, with patterns passed to the compadd calls, for instance autoremoval of a space suffix when another space is entered, or when a non-nil character is typed (with NoOptDefVal flags). Also used in list completions.

    Other/all shells

    • Flags that are marked repeatable (slices and maps) now use a default multiparts completer with a comma list item separator.

    Major changes to the code

    • The ZSH snippet has been modified so as to loop over an arbitrary number of groups, and generate their completions accordingly. It does also parses a header for each group, containing its tag and group description.
    • The ZSH Go code has been rewritten (entirely), in order to account for all the changes and cases to be considered. The code is heavily commented, so as to ease understanding the logic involved, the constraints faced, etc. I pretend this code to be shielded from most edge cases. See below.
    • The action used to generate command completions has been modified to structure them by groups, if there are any (takes advantage of this new cobra v.1.6.0 feature).
    • The ActionMessage() has been rewritten, because I had to find a way to pass messages to the final ActionRawValues() functions, while preserving compatibility with other shells. See below as well. A corresponding function call has been added in all shells Go code, except for ZSH which does different.
    • The common.RawValue type now has a Tag and a Group field. This is so that people can still generate as many actions from a base one (shoutouts to how you devised this library). See this file for an example where I make use of these groups (as well as of the old and new carapace features)
    • Merge() has been slightly modified to preserve the order in which completions (therefore groups) were added.
    • ZSH sanitizers have been very slightly modified, in order to acomodate for the changes, and placed into a file of their own.
    opened by maxlandon 4
  • Code refactoring (main functions)

    Code refactoring (main functions)

    This PR aims to refactor the main functions/entrypoints in carapace code. First of all, thanks a huge lot for this amazing library, much needed. Wish it all the success.

    Note that tests fail on my machine, because I apparently don't have the infrastructure to run them (a bunch of executables not present)

    Completion functions

    The completion functions have been refactored in order to eliminate the nested branchings, add comments to the code so that it is easier to follow for non-initiated, and refactor the various helper functions (finding target actions, producing completions, etc)

    As well, all of these functions related to completion have been moved in the file complete.go, which I unfortunately had to push in the first commit.

    Commands

    The addCompletion() function, binding the _carapace hidden command, has been moved to a file of its own.

    Context

    The context.go file now has a small constructor, for initializing the context with working directories. This is only for the sake of clearing the main completion entrypoint code.

    Others

    The net result is that carapace.go is now stripped from any completion logic code, and command binding. Only remain most of the public functions, and the logging code.

    opened by maxlandon 7
  • support PreRun on any command

    support PreRun on any command

    This will need a fundamental different approach as to how parsing/completion determination is executed. Currently this is done backwards by first letting cobra parse the args and then trying to identify a possible flags from the end. To achieve this thus it needs to be done forward on each command at time similar to how it is done in the pflag package.

    So:

    1. Invoke PreRun on a cmd
    2. Parse flags for cmd (which will consume args)
    3. Identify subcommand / completion position
    4. Repeat from (1) if subcommand

    This will also enable https://github.com/rsteube/carapace-pflag/issues/7

    opened by rsteube 0
Releases(v0.26.4)
bash completion written in go + bash completion for go command

complete Package complete is everything for bash completion and Go. The main development is done on the master branch, please follow the link to see a

Eyal Posener 868 Nov 24, 2022
minigli is a tiny command argument parser for Go.

minigli is a tiny command argument parser for Go.

hitoshi44 0 Jan 29, 2022
Fully featured Go (golang) command line option parser with built-in auto-completion support.

go-getoptions Go option parser inspired on the flexibility of Perl’s GetOpt::Long. Table of Contents Quick overview Examples Simple script Program wit

David Gamba 46 Sep 26, 2022
Pure Go command line prompt with history, kill-ring, and tab completion

Prompt Prompt is a command line prompt editor with history, kill-ring, and tab completion. It was inspired by linenoise and derivatives which eschew u

Peter Mattis 1 Nov 20, 2021
This project is used to get familiar with GoLang cli apps, along with cobra generator.

SecretCTL SecretCTL About the project Status Getting started Layout Notes About the project This project is used to get familiar with GoLang cli apps,

Milos Folic 0 Jan 11, 2022
A collection of CLI argument types for the Go `flag` package.

flagvar A collection of CLI argument types for the flag package. import "github.com/sgreben/flagvar" Or just copy & paste what you need. It's public d

Sergey Grebenshchikov 41 Sep 26, 2022
Struct-based argument parsing in Go

go-arg Struct-based argument parsing for Go Declare command line arguments for your program by defining a struct. var args struct { Foo string Bar b

Alex Flint 1.5k Nov 27, 2022
The blackbean is a command tool for elasticsearch operations by using cobra.

The blackbean is a command tool for elasticsearch operations by using cobra. Besides, blackbean is the name of my lovely French bulldog.

null 23 Mar 3, 2022
cod is a completion daemon for bash/fish/zsh

Cod is a completion daemon for {bash,fish,zsh}. It detects usage of --help commands parses their output and generates auto-completions for your shell.

Dmitry Ermolov 439 Nov 23, 2022
Simple trie based auto-completion engine implementation in golang.

Simple auto-complete engine implementation in golang. Quick start $ git clone https://github.com/benbarron/trie-auto-completion-engine $ cd trie-auto-

Ben Barron 1 Jul 12, 2022
Build an interactive CLI application with Go, Cobra and promptui. Video tutorial available on the Div Rhino YouTube channel.

Build an interactive CLI app with Go, Cobra and promptui Text tutorial: https://divrhino.com/articles/build-interactive-cli-app-with-go-cobra-promptui

Div Rhino Dev 15 Nov 4, 2022
Prompts users to enter values for required flags in Cobra CLI applications

Cobra Flag Prompt Cobra Flag Prompt prompts users to enter values for required flags. It is an extension of Cobra, and requires that you use Cobra to

null 1 Nov 13, 2021
Generate an interactive, autocompleting shell for any Cobra CLI

cobra-shell Description Leverages the Cobra completion API to generate an interactive shell for any Cobra CLI, powered by go-prompt. On-the-fly autoco

Brian Strauch 29 Aug 31, 2022
A cli client-server app with cobra

cli-client-server-calculator a cli client-server app with cobra overview this project is a cli client-server app in which client gives a bunch of numb

mohammad-hossein zeynal zadeh 5 Dec 7, 2021
Cobra CLI challenge Segsalerty

Banking app done using Cobra CLI - Segsalerty challenge c/o Segun Mustafa It uses a database.json file as datastore for queries - createCustomer, Upda

Oladapo Olawale Sunday 0 Dec 14, 2021
Reusable golang-migrate library using cobra utility

shift Reusable golang-migrate library using cobra utility Example Usage package main import ( "sql/db" "github.com/purwandi/shift" "github.com

purwandi 0 Dec 16, 2021
CLI to run a docker image with R. CLI built using cobra library in go.

BlueBeak Installation Guide Task 1: Building the CLI The directory structure looks like Fastest process: 1)cd into bbtools 2)cd into bbtools/bin 3)I h

Aniruddha Chattopadhyay 0 Dec 20, 2021
Go-file-downloader-ftctl - A file downloader cli built using golang. Makes use of cobra for building the cli and go concurrent feature to download files.

ftctl This is a file downloader cli written in Golang which uses the concurrent feature of go to download files. The cli is built using cobra. How to

Dipto Chakrabarty 2 Jan 2, 2022