Skip to content

Instantly share code, notes, and snippets.

@skyzyx
Created November 16, 2020 02:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save skyzyx/149caddbf0c949da58618cb03b08e4d9 to your computer and use it in GitHub Desktop.
Save skyzyx/149caddbf0c949da58618cb03b08e4d9 to your computer and use it in GitHub Desktop.
An implementation of Bash and Zsh autocompletion.

Copyright 2020 Ryan Parman

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

// https://github.com/jawher/mow.cli/issues/104
package main
import (
"fmt"
"os"
"strings"
cli "github.com/jawher/mow.cli"
model "github.com/jawher/mow.cli/model"
)
// shellComplete performs bash command line completion for defined flags.
func shellComplete(definition *cli.Cli) {
// When shell calls the command to perform completion it will set several
// environment variables including COMP_LINE. If this variable is not set,
// then command is being invoked normally and we can return.
compLine, ok := os.LookupEnv("COMP_LINE")
if !ok {
return
}
root := make(map[string][]string)
defModel := definition.Model()
var parentNames []string
// Iterate over the nodes and create a map of commands → completion options.
handleComplete(parentNames, &defModel.Command, root)
// At this point, `root` contains a mapping of previously-typed (complete)
// commands, and the next possible choices. Now, we'll do some fancy string
// munging to handle the fuzzy completion stuff.
args := normalizeArgs(compLine)
toComplete := args[2]
lastCompletedWord := args[3]
idx := strings.Index(compLine, lastCompletedWord) + len(lastCompletedWord)
key := compLine[:idx]
if allChoices, ok := root[key]; ok {
for i := range allChoices {
choice := allChoices[i]
if strings.HasPrefix(choice, toComplete) {
fmt.Println(choice)
}
}
}
os.Exit(0)
}
// Recurse over the object and return non-hidden completion options.
func handleComplete(parentNames []string, cmd *model.Command, mmap map[string][]string) {
parentNames = append(parentNames, cmd.Name)
key := strings.TrimSpace(strings.Join(parentNames, " "))
for k := range cmd.Commands {
command := cmd.Commands[k]
if !command.Hidden {
mmap[key] = append(mmap[key], command.Name)
}
handleComplete(parentNames, &command, mmap)
}
for i := range cmd.Options {
option := cmd.Options[i]
for j := range option.LongNames {
if !option.HideValue {
mmap[key] = append(mmap[key], option.LongNames[j])
}
}
}
for i := range cmd.Arguments {
argument := cmd.Arguments[i]
if !argument.HideValue {
mmap[key] = append(mmap[key], argument.DefaultValue)
}
}
}
// Normalize how arguments come in from the shell.
func normalizeArgs(compLine string) []string {
// This is Bash. We're good.
if len(os.Args) == 4 { // lint:allow_raw_number
return os.Args
}
// -------------------------------------------------------------------------
//
// Bash programmable completion
// https://www.gnu.org/software/bash/manual/html_node/Programmable-Completion.html
//
// When supporting autocomplete, os.Args gives us 4 values:
// [0]: The name of the root command being run. (Usually the same as [1].)
// [1]: The name of the root command for which we want auto-complete. (Usually the same as [0].)
// [2]: The "partial" string that we want to complete.
// [3]: The last command/sub-command that was completed.
//
// -------------------------------------------------------------------------
// Emulate what Bash gives us for Zsh and anything else.
soFar := strings.Split(compLine, " ")
args := []string{
os.Args[0],
os.Args[0],
func() string {
idx := max(len(soFar)-1, 0) // lint:allow_raw_number
if idx == 0 {
return ""
}
return soFar[idx]
}(),
func() string {
idx := max(len(soFar)-2, 0) // lint:allow_raw_number
if idx == 0 {
return os.Args[0]
}
return soFar[idx]
}(),
}
return args
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment