Skip to content

Commit ed469dc

Browse files
caelaxiesteinliber
authored andcommitted
fix: avoid flag name colision in viper
Signed-off-by: Kaitian Xie <kaitian96@outlook.com>
1 parent 4769329 commit ed469dc

2 files changed

Lines changed: 31 additions & 1 deletion

File tree

cmd/devstream/develop.go

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import (
44
"github.com/spf13/cobra"
55

66
"github.com/devstream-io/devstream/internal/pkg/develop"
7+
"github.com/devstream-io/devstream/pkg/util/cli"
78
"github.com/devstream-io/devstream/pkg/util/log"
89
)
910

@@ -12,6 +13,11 @@ var (
1213
all bool
1314
)
1415

16+
var validatePluginFlagNames = []string{
17+
"name",
18+
"all",
19+
}
20+
1521
var developCMD = &cobra.Command{
1622
Use: "develop",
1723
Short: "Develop is used for develop a new plugin",
@@ -33,7 +39,8 @@ var developValidatePluginCMD = &cobra.Command{
3339
Examples:
3440
dtm develop validate-plugin --name=YOUR-PLUGIN-NAME,
3541
dtm develop validate-plugin --all`,
36-
Run: developValidateCMDFunc,
42+
Run: developValidateCMDFunc,
43+
PreRun: cli.BindPFlags(validatePluginFlagNames),
3744
}
3845

3946
func developCreateCMDFunc(cmd *cobra.Command, args []string) {

pkg/util/cli/viper.go

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
package cli
2+
3+
import (
4+
"log"
5+
6+
"github.com/spf13/cobra"
7+
"github.com/spf13/viper"
8+
)
9+
10+
type PreRunFunc func(cmd *cobra.Command, args []string)
11+
12+
// BindPFlags accepts a list of flag names and binds the corresponding flags to Viper. This function servers
13+
// as a workaround to a known bug in Viper, in which two commands can't share the same flag name.
14+
// To learn more about the bug, see: https://github.com/spf13/viper/issues/233
15+
func BindPFlags(flagNames []string) PreRunFunc {
16+
return func(cmd *cobra.Command, args []string) {
17+
for _, name := range flagNames {
18+
if err := viper.BindPFlag(name, cmd.Flags().Lookup(name)); err != nil {
19+
log.Fatalf("Failed to bind flag %s: %s", name, err)
20+
}
21+
}
22+
}
23+
}

0 commit comments

Comments
 (0)