Skip to content

Commit

Permalink
Added shell completion cobra command
Browse files Browse the repository at this point in the history
  • Loading branch information
eko committed Jul 26, 2019
1 parent 4189386 commit 14c9500
Show file tree
Hide file tree
Showing 3 changed files with 45 additions and 0 deletions.
3 changes: 3 additions & 0 deletions Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,9 @@ help:
build: ## Builds a local version of Monday from sources
go build -ldflags "-X main.Version=sources-$(shell git rev-parse --short=5 HEAD)" -o monday ./cmd && mv monday /usr/local/bin

build-binary: ## Builds a single binary of Monday from sources
/usr/local/bin/go build -ldflags "-X main.Version=sources-$(shell git rev-parse --short=5 HEAD)" -o monday ./cmd

generate-mocks: ## Generate mocks for tests
@echo "> generating mocks..."

Expand Down
41 changes: 41 additions & 0 deletions cmd/completion.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
package main

import (
"fmt"
"os"

"github.com/spf13/cobra"
)

var completionCmd = &cobra.Command{
Use: "completion SHELL",
Args: func(cmd *cobra.Command, args []string) error {
if len(args) != 1 {
return fmt.Errorf("requires 1 arg, found %d", len(args))
}
return cobra.OnlyValidArgs(cmd, args)
},
ValidArgs: []string{"bash", "zsh"},
Short: "Outputs shell completion for the given shell (bash or zsh)",
Long: "Outputs shell completion for the given shell (bash or zsh)",
Run: completion,
}

func completion(cmd *cobra.Command, args []string) {
switch args[0] {
case "bash":
rootCmd(cmd).GenBashCompletion(os.Stdout)
case "zsh":
rootCmd(cmd).GenZshCompletion(os.Stdout)
}
}

func rootCmd(cmd *cobra.Command) *cobra.Command {
parent := cmd

for parent.HasParent() {
parent = parent.Parent()
}

return parent
}
1 change: 1 addition & 0 deletions cmd/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ func main() {
},
}

rootCmd.AddCommand(completionCmd)
rootCmd.AddCommand(editCmd)
rootCmd.AddCommand(initCmd)
rootCmd.AddCommand(runCmd)
Expand Down

0 comments on commit 14c9500

Please sign in to comment.