-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #21 from Ccheers/dev
feat(xcli): 提供 cobra 支持
- Loading branch information
Showing
3 changed files
with
77 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,66 @@ | ||
package xcli | ||
|
||
import ( | ||
"context" | ||
"flag" | ||
|
||
"github.com/spf13/cobra" | ||
"github.com/spf13/pflag" | ||
) | ||
|
||
type ICommandList []ICommand | ||
|
||
type ICommand interface { | ||
Use() string | ||
Short() string | ||
Long() string | ||
Run(ctx context.Context, args []string) error | ||
Flags() *flag.FlagSet | ||
} | ||
|
||
type pflagValueAdapter struct { | ||
value flag.Value | ||
} | ||
|
||
func newPflagValueAdapter(value flag.Value) *pflagValueAdapter { | ||
return &pflagValueAdapter{value: value} | ||
} | ||
|
||
func (x *pflagValueAdapter) String() string { | ||
return x.value.String() | ||
} | ||
|
||
func (x *pflagValueAdapter) Set(s string) error { | ||
return x.value.Set(s) | ||
} | ||
|
||
func (x *pflagValueAdapter) Type() string { | ||
return "string" | ||
} | ||
|
||
func InitRootCommand(root ICommand, cmds ...ICommand) *cobra.Command { | ||
rootCmd := BuildCobraCommand(root) | ||
for _, sudCmd := range cmds { | ||
rootCmd.AddCommand(BuildCobraCommand(sudCmd)) | ||
} | ||
return rootCmd | ||
} | ||
|
||
func BuildCobraCommand(icmd ICommand) *cobra.Command { | ||
c := &cobra.Command{ | ||
Use: icmd.Use(), | ||
Short: icmd.Short(), | ||
Long: icmd.Long(), | ||
RunE: func(cmd *cobra.Command, args []string) error { | ||
return icmd.Run(cmd.Context(), args) | ||
}, | ||
} | ||
ConvFlag2Pflag(icmd.Flags(), c.Flags()) | ||
return c | ||
} | ||
|
||
func ConvFlag2Pflag(src *flag.FlagSet, dst *pflag.FlagSet) { | ||
src.VisitAll(func(f *flag.Flag) { | ||
dst.Var(newPflagValueAdapter(f.Value), f.Name, f.Usage) | ||
}) | ||
} |