Skip to content

Commit

Permalink
fix: avoid flag name colision in viper
Browse files Browse the repository at this point in the history
Signed-off-by: Kaitian Xie <kaitian96@outlook.com>
  • Loading branch information
algobot76 committed Oct 12, 2022
1 parent 4769329 commit be877d9
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 1 deletion.
9 changes: 8 additions & 1 deletion cmd/devstream/develop.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"github.com/spf13/cobra"

"github.com/devstream-io/devstream/internal/pkg/develop"
"github.com/devstream-io/devstream/pkg/util/cli"
"github.com/devstream-io/devstream/pkg/util/log"
)

Expand All @@ -12,6 +13,11 @@ var (
all bool
)

var validatePluginFlagNames = []string{
"name",
"all",
}

var developCMD = &cobra.Command{
Use: "develop",
Short: "Develop is used for develop a new plugin",
Expand All @@ -33,7 +39,8 @@ var developValidatePluginCMD = &cobra.Command{
Examples:
dtm develop validate-plugin --name=YOUR-PLUGIN-NAME,
dtm develop validate-plugin --all`,
Run: developValidateCMDFunc,
Run: developValidateCMDFunc,
PreRun: cli.BindPFlags(validatePluginFlagNames),
}

func developCreateCMDFunc(cmd *cobra.Command, args []string) {
Expand Down
23 changes: 23 additions & 0 deletions pkg/util/cli/viper.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
package cli

import (
"log"

"github.com/spf13/cobra"
"github.com/spf13/viper"
)

type PreRunFunc func(cmd *cobra.Command, args []string)

// BindPFlags accepts a list of flag names and binds the corresponding flags to Viper. This function servers
// as a workaround to a known bug in Viper, in which two commands can't share the same flag name.
// To learn more about the bug, see: https://github.com/spf13/viper/issues/233
func BindPFlags(flagNames []string) PreRunFunc {
return func(cmd *cobra.Command, args []string) {
for _, name := range flagNames {
if err := viper.BindPFlag(name, cmd.Flags().Lookup(name)); err != nil {
log.Fatalf("Failed to bind flag %s: %s", name, err)
}
}
}
}

0 comments on commit be877d9

Please sign in to comment.