From f30280b9a710f55a748e66469304a003eda06dcc Mon Sep 17 00:00:00 2001 From: Tobias Melson Date: Wed, 10 Apr 2024 17:23:54 +0200 Subject: [PATCH] Implemented bash completion --- bash_completion.sh | 10 ++++++++++ src/config.go | 40 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 50 insertions(+) create mode 100644 bash_completion.sh diff --git a/bash_completion.sh b/bash_completion.sh new file mode 100644 index 0000000..41fc967 --- /dev/null +++ b/bash_completion.sh @@ -0,0 +1,10 @@ +#!/usr/bin/env bash + +lisst_completion() { + COMPREPLY=($(lisst --completion "$COMP_LINE" "$2")) + if [ "${COMPREPLY[0]}" == "-" ]; then + COMPREPLY=($(compgen -A command "$2")) + fi +} + +complete -F "lisst_completion" lisst diff --git a/src/config.go b/src/config.go index 769f84c..7893e16 100644 --- a/src/config.go +++ b/src/config.go @@ -80,6 +80,11 @@ func NewConfig() *Config { stat, err := os.Stat(p) return err == nil && stat.IsDir() } + case "--completion": + if len(os.Args) > 3 { + printCompletion(os.Args[2], os.Args[3]) + } + os.Exit(0) default: if strings.HasPrefix(arg, "--") { fmt.Fprintln(os.Stderr, "Invalid command-line option " + arg) @@ -124,3 +129,38 @@ func NewConfig() *Config { return config } +func printCompletion(line string, current string) { + if strings.HasPrefix(current, "--") { + printCompletionOption(line, current, []string{"--help", "--filter", "--show-output", "--ignore-error"}) + printExclusiveCompletionOption(line, current, []string{"--sort", "--sort-rev"}) + printExclusiveCompletionOption(line, current, []string{"--line", "--git-commit-hash", "--filename", "--filename-lineno", "--dirname"}) + } else { + hasPattern := false + for _, pattern := range []string{"--line", "--git-commit-hash", "--filename", "--filename-lineno", "--dirname"} { + if strings.Contains(line, pattern + " ") { + hasPattern = true + break + } + } + if hasPattern { + fmt.Println("-") + } + } +} + +func printCompletionOption(line string, current string, options []string) { + for _, option := range options { + if strings.HasPrefix(option, current) && !strings.Contains(line, option + " ") { + fmt.Println(option) + } + } +} + +func printExclusiveCompletionOption(line string, current string, options []string) { + for _, option := range options { + if strings.Contains(line, option + " ") { + return + } + } + printCompletionOption(line, current, options) +}