add rootCmd alias [spf13/cobra#725]

This commit is contained in:
1138-4EB 2018-08-09 17:20:08 +01:00
parent d1ad79fb9d
commit 7305c6acfe
4 changed files with 54 additions and 6 deletions

View File

@ -9,6 +9,8 @@ import (
// dbCmd represents the db command
var dbCmd = &cobra.Command{
Use: "db",
Version: rootCmd.Version,
Aliases: []string{"database"},
Short: "A brief description of your command",
Long: `A longer description that spans multiple lines and likely contains examples
and usage of using your command. For example:

View File

@ -15,20 +15,18 @@ var cfgFile string
var rootCmd = &cobra.Command{
Use: "filebrowser",
Version: "(untracked)",
Aliases: []string{"serve"},
Short: "A stylish web-based file manager",
Long: `File Browser is static binary composed of a golang backend
and a Vue.js frontend to create, edit, copy, move, download your files
easily, everywhere, every time.`,
/*
Run: func(cmd *cobra.Command, args []string) {
serveCmd.Run(cmd, args)
},
*/
// Run: func(cmd *cobra.Command, args []string) {},
}
// Execute adds all child commands to the root command and sets flags appropriately.
// This is called by main.main(). It only needs to happen once to the rootCmd.
func Execute() {
checkRootAlias()
if err := rootCmd.Execute(); err != nil {
fmt.Println(err)
os.Exit(1)

46
cli/cmd/rootalias.go Normal file
View File

@ -0,0 +1,46 @@
package cmd
import (
"os"
"log"
)
// checkRootAlias compares the first argument provided in the CLI with a list of
// subcmds and aliases. If no match is found, the first alias of rootCmd is added.
func checkRootAlias() {
l := len(rootCmd.Aliases)
if l == 0 {
return
}
if l > 1 {
log.Printf("rootCmd.Aliases should contain a single string. '%s' is used.\n", rootCmd.Aliases[0])
}
if len(os.Args) > 1 {
for _, v := range append(nonRootSubCmds(), []string{"--help", "--version"}...) {
if os.Args[1] == v {
return
}
}
}
os.Args = append([]string{os.Args[0], rootCmd.Aliases[0]}, os.Args[1:]...)
}
// nonRootSubCmds traverses the list of subcommands of rootCmd and returns a string
// slice containing the names and aliases of all the subcmds, except the one defined
// in the Aliases field of rootCmd.
func nonRootSubCmds() (l []string) {
for _, c := range rootCmd.Commands() {
isAlias := false
for _, a := range append(c.Aliases, c.Name()) {
if a == rootCmd.Aliases[0] {
isAlias = true
break
}
}
if !isAlias {
l = append(l, c.Name())
l = append(l, c.Aliases...)
}
}
return
}

View File

@ -9,7 +9,8 @@ import (
// serveCmd represents the serve command
var serveCmd = &cobra.Command{
Use: "serve",
Aliases: []string{"serve","server"},
Version: rootCmd.Version,
Aliases: []string{"server"},
Short: "A brief description of your command",
Long: `A longer description that spans multiple lines and likely contains examples
and usage of using your command. For example:
@ -20,6 +21,7 @@ to quickly create a Cobra application.`,
Run: func(cmd *cobra.Command, args []string) {
Serve()
},
Args: cobra.NoArgs,
}
var (