Skip to content

Commit

Permalink
feat(cmd): shell completion subcommand (#576)
Browse files Browse the repository at this point in the history
Co-authored-by: Sumire (菫) <[email protected]>
  • Loading branch information
zzzsyyy and sumire88 authored Jul 23, 2024
1 parent 54df978 commit 4717fa2
Show file tree
Hide file tree
Showing 2 changed files with 60 additions and 1 deletion.
59 changes: 59 additions & 0 deletions cmd/completion.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
/*
* SPDX-License-Identifier: AGPL-3.0-only
* Copyright (c) 2022-2024, daeuniverse Organization <[email protected]>
*/

package cmd

import (
"bytes"
"errors"
"fmt"

"github.com/spf13/cobra"
)

var (
completionCmd = &cobra.Command{
Use: "completion [bash|zsh|fish]",
Short: "Output shell completion code for the specified shell (bash, zsh or fish)",
Long: "Output shell completion code for the specified shell (bash, zsh or fish).",
Args: cobra.ExactArgs(1),
ValidArgs: []string{"bash", "zsh", "fish"},
Hidden: true,
RunE: func(cmd *cobra.Command, args []string) error {
out, err := getCompletion(args[0], cmd.Parent())
if err != nil {
return err
}

fmt.Print(out)
return nil
},
}
)

// return the auto completion shell script, if supported
func getCompletion(sh string, parent *cobra.Command) (string, error) {
var err error
var buf bytes.Buffer

switch sh {
case "bash":
err = parent.GenBashCompletion(&buf)
case "zsh":
err = parent.GenZshCompletion(&buf)
case "fish":
err = parent.GenFishCompletion(&buf, true)
default:
err = errors.New("unsupported shell type (must be bash, zsh or fish): " + sh)
}

if err != nil {
return "", err
}
return buf.String(), nil
}
func init() {
rootCmd.AddCommand(completionCmd)
}
2 changes: 1 addition & 1 deletion cmd/run.go
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ var (
)

func init() {
runCmd.PersistentFlags().StringVarP(&cfgFile, "config", "c", "", "Config file of dae.")
runCmd.PersistentFlags().StringVarP(&cfgFile, "config", "c", "", "Config file of dae.(required)")
runCmd.PersistentFlags().StringVar(&logFile, "logfile", "", "Log file to write. Empty means writing to stdout and stderr.")
runCmd.PersistentFlags().IntVar(&logFileMaxSize, "logfile-maxsize", 30, "Unit: MB. The maximum size in megabytes of the log file before it gets rotated.")
runCmd.PersistentFlags().IntVar(&logFileMaxBackups, "logfile-maxbackups", 3, "The maximum number of old log files to retain.")
Expand Down

0 comments on commit 4717fa2

Please sign in to comment.