Skip to content

Commit

Permalink
Merge pull request #56 from IdlePhysicist/completion
Browse files Browse the repository at this point in the history
Adding tab completion functionality for Bash and Zsh
  • Loading branch information
lwahlmeier committed Jun 19, 2020
2 parents f7573a5 + 6066bf6 commit 5dedfad
Show file tree
Hide file tree
Showing 3 changed files with 75 additions and 0 deletions.
2 changes: 2 additions & 0 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package main
import (
"github.com/PremiereGlobal/stim/stim"
"github.com/PremiereGlobal/stim/stimpacks/aws"
"github.com/PremiereGlobal/stim/stimpacks/completion"
"github.com/PremiereGlobal/stim/stimpacks/deploy"
"github.com/PremiereGlobal/stim/stimpacks/kubernetes"
"github.com/PremiereGlobal/stim/stimpacks/pagerduty"
Expand All @@ -14,6 +15,7 @@ import (
func main() {
stim := stim.New()
stim.AddStimpack(aws.New())
stim.AddStimpack(completion.New())
stim.AddStimpack(deploy.New())
stim.AddStimpack(kubernetes.New())
stim.AddStimpack(pagerduty.New())
Expand Down
21 changes: 21 additions & 0 deletions stim/completion.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
package stim

import (
"fmt"
"io"
"os"
)

func (stim *Stim) GetCompletion(shell string) error {
switch shell {
case `bash`:
stim.rootCmd.GenBashCompletion(os.Stdout)
case `zsh`:
stim.rootCmd.GenZshCompletion(os.Stdout)
io.WriteString(os.Stdout, "\ncompdef _stim stim\n")
default:
return fmt.Errorf("Unknown shell: %s", shell)
}

return nil
}
52 changes: 52 additions & 0 deletions stimpacks/completion/completion.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
package completion

import (
"fmt"
"github.com/PremiereGlobal/stim/stim"
"github.com/spf13/cobra"
"github.com/spf13/viper"
)

type Completion struct {
name string
stim *stim.Stim
}

func New() *Completion {
return &Completion{name: "completion"}
}

func (c *Completion) Name() string {
return c.name
}

func (c *Completion) BindStim(s *stim.Stim) {
c.stim = s
}

func (c *Completion) Command(viper *viper.Viper) *cobra.Command {

var cmd = &cobra.Command{
Use: "completion SHELL",
Short: "Output shell completion for the given shell (bash or zsh)",
Long: `Output shell completion for the given shell (bash or zsh)
The following ought to suffice for loading the Bash completions:
source <(stim completion bash)
Zsh is more complicated because there is more than one completion engine for
Zsh. Try putting the completion output into a script (in your $fpath) and
loading it with compinit.
stim completion zsh > /path/to/script
`,
ValidArgs: []string{"bash", "zsh"},
Args: cobra.ExactArgs(1),
Run: func(cmd *cobra.Command, args []string) {
if err := c.stim.GetCompletion(args[0]); err != nil {
fmt.Println(err)
}
},
}

return cmd
}

0 comments on commit 5dedfad

Please sign in to comment.