Skip to content

Commit

Permalink
fix(xcli): 修复了 xcli unknown cmd 路由分发异常的 bug
Browse files Browse the repository at this point in the history
  • Loading branch information
Ccheers committed Oct 17, 2024
1 parent 9a95a18 commit f58ee13
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 3 deletions.
4 changes: 4 additions & 0 deletions xcli/test/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,10 @@ func main() {
err := xcli.NewXCli(
"xtest",
xcli.WithCommandList(xcli.ICommandList{NewT()}),
xcli.WithHandleUnknownCommand(func(ctx context.Context, args []string) error {
log.Println("fallback", args)
return nil
}),
).Run(context.Background())
if err != nil {
panic(err)
Expand Down
25 changes: 22 additions & 3 deletions xcli/xcli.go
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ func NewXCli(name string, opts ...XCliOption) *XCli {
o.apply(options)
}

rootCmd := &cobra.Command{
root := &cobra.Command{
Use: name,
Short: options.short,
Long: options.long,
Expand All @@ -82,12 +82,31 @@ func NewXCli(name string, opts ...XCliOption) *XCli {
},
}

namedCmd := make(map[string]struct{}, len(options.cmdList))
for _, cmd := range options.cmdList {
rootCmd.AddCommand(BuildCobraCommand(cmd))
root.AddCommand(BuildCobraCommand(cmd))
namedCmd[cmd.Use()] = struct{}{}
}

// 实际注入的实例, 包装一层用于将不存在的命令兜底处理
cobraIns := &cobra.Command{
Use: name,
Short: options.short,
Long: options.long,
RunE: func(cmd *cobra.Command, args []string) error {
if options.handleUnknownCommand != nil && len(args) > 0 {
if _, ok := namedCmd[args[0]]; !ok {
return options.handleUnknownCommand(cmd.Context(), args)
}
}
return root.ExecuteContext(cmd.Context())
},
// 这个实例不需要解析 flag , 主要用于 unknown cmd 的路由分发
DisableFlagParsing: true,
}

return &XCli{
rootCmd: rootCmd,
rootCmd: cobraIns,
}
}

Expand Down

0 comments on commit f58ee13

Please sign in to comment.