(parent *cobra.Command, name string, fn func(*cobra.Command))
| 251 | } |
| 252 | |
| 253 | func NewCmd[T UIer](parent *cobra.Command, name string, fn func(*cobra.Command)) *cobra.Command { |
| 254 | var def, parentDef *CmdDef |
| 255 | if parent != nil { |
| 256 | var ok bool |
| 257 | if parentDef, ok = cmdDefByCommands[parent]; !ok { |
| 258 | panic("unregistered parent command") |
| 259 | } |
| 260 | for _, sub := range parentDef.SubDefs { |
| 261 | if sub.Name == name { |
| 262 | def = &sub |
| 263 | break |
| 264 | } |
| 265 | } |
| 266 | if def == nil { |
| 267 | panic("missing subcommand definition") |
| 268 | } |
| 269 | } else { |
| 270 | def = &rootDef |
| 271 | } |
| 272 | |
| 273 | constructor := func() *cobra.Command { |
| 274 | cmd := &cobra.Command{ |
| 275 | Aliases: def.Aliases, |
| 276 | Args: def.Args, |
| 277 | Long: def.Long, |
| 278 | Short: def.Short, |
| 279 | Use: def.Use, |
| 280 | SilenceUsage: true, |
| 281 | } |
| 282 | |
| 283 | cmd.SetErrPrefix(ui.Danger("Error!")) |
| 284 | |
| 285 | ctx := ContextWithConfig(context.Background(), defaultConfig()) |
| 286 | cmd.SetContext(ctx) |
| 287 | |
| 288 | fn(cmd) |
| 289 | |
| 290 | cmd.RunE = func(cmd *cobra.Command, args []string) (returnedError error) { |
| 291 | ctx := cmd.Context() |
| 292 | |
| 293 | cfg := new(Config) |
| 294 | if err := cfg.Load(ctx); err != nil { |
| 295 | return err |
| 296 | } |
| 297 | |
| 298 | if cfg.Test.SkipRunE { |
| 299 | return nil |
| 300 | } |
| 301 | |
| 302 | ctx = ContextWithConfig(cmd.Context(), cfg) |
| 303 | cmd.SetContext(ctx) |
| 304 | |
| 305 | var t T |
| 306 | |
| 307 | switch any(t).(type) { |
| 308 | case ShowHelp: |
| 309 | cmd.HelpFunc()(cmd, args) |
| 310 | return nil |
no test coverage detected