Created
November 2, 2021 15:56
-
-
Save bjjb/dc65525d63eff7103b264a6149918644 to your computer and use it in GitHub Desktop.
spf13/cobta completion example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Package main is an example of using dynamic command-line completion with | |
// github.com/spf13/cobra. | |
package main | |
import ( | |
"fmt" | |
"os" | |
"time" | |
"github.com/spf13/cobra" | |
) | |
// C is a cobra.Command | |
type C = cobra.Command | |
// ValidShells are the shells for which we can generate completion | |
var ValidShells = []string{"bash", "zsh", "fish", "powershell"} | |
func completion() *C { | |
cmd := &C{ | |
Use: "completion", | |
Short: "Complete a programme", | |
Long: `An awesome completer`, | |
Args: cobra.ExactValidArgs(1), | |
ValidArgs: ValidShells, | |
Run: func(c *C, a []string) { | |
if len(a) != 1 { | |
panic("too many args") | |
} | |
switch a[0] { | |
case "bash": | |
c.Root().GenBashCompletion(c.OutOrStdout()) | |
case "zsh": | |
c.Root().GenZshCompletion(c.OutOrStdout()) | |
case "fish": | |
c.Root().GenFishCompletion(c.OutOrStdout(), true) | |
case "powershell": | |
c.Root().GenPowerShellCompletion(os.Stdout) | |
} | |
}, | |
} | |
return cmd | |
} | |
var validFoos = func() func(*C, []string, string) ([]string, cobra.ShellCompDirective) { | |
return func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { | |
return []string{"foo", "bar", time.Now().String()}, cobra.ShellCompDirectiveNoFileComp | |
} | |
} | |
func foo() *C { | |
cmd := &C{ | |
Use: "foo", | |
Short: "A foo", | |
Long: `An awesome foo`, | |
Args: cobra.ExactValidArgs(1), | |
ValidArgsFunction: validFoos(), | |
Run: func(c *C, a []string) { | |
fmt.Fprintf(c.OutOrStdout(), "Foo! %v\n", a) | |
}, | |
} | |
return cmd | |
} | |
func cmd() *C { | |
cmd := &C{ | |
Use: "snake", | |
Version: "0.0.1", | |
Short: "A programme", | |
Long: `An awesome programme`, | |
Run: func(c *C, a []string) { | |
fmt.Fprintf(c.OutOrStdout(), "Hello!\n") | |
}, | |
} | |
cmd.AddCommand(completion(), foo()) | |
return cmd | |
} | |
func main() { | |
cmd().Execute() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment