()
| 293 | } |
| 294 | |
| 295 | func (scb *structCommandBuilder) build() *command { |
| 296 | var ( |
| 297 | cmd = newCommand(scb.t().Name(), scb.md, nil) |
| 298 | opts = &options{ |
| 299 | scb.reflection, |
| 300 | scb.parent, |
| 301 | cmd.delegate.PersistentFlags(), |
| 302 | scb.md, |
| 303 | } |
| 304 | ) |
| 305 | opts.declare() |
| 306 | for i := 0; i < scb.ptr.v().NumMethod(); i++ { |
| 307 | var ( |
| 308 | m = scb.ptr.t().Method(i) |
| 309 | v = scb.ptr.v().Method(i) |
| 310 | fcb = &funcCommandBuilder{ |
| 311 | m.Name, |
| 312 | reflection{ov: &v}, |
| 313 | scb.md.Child(m.Name), |
| 314 | } |
| 315 | ) |
| 316 | // TODO: maybe provide an option to default to a subcommand. |
| 317 | cmd.addCommand(fcb.build()) |
| 318 | } |
| 319 | // This should ideally be as simple as setting cobra.NoArgs, but for |
| 320 | // whatever reason, Cobra doesn't really honor that for subcommands |
| 321 | // (see spf13/cobra#706, spf13/cobra#981) -- so, we do it ourselves. |
| 322 | cmd.delegate.RunE = validateNoArgs |
| 323 | // We only make this command "runnable" to validate NoArgs, so hack the |
| 324 | // usage template and pretend it's not really runnable. |
| 325 | // Note: Cobra subcommands will inherit any custom attributes set on the |
| 326 | // parent command, so we need to be careful here to only apply the changes |
| 327 | // to the parent command and not any subcommands. |
| 328 | defaultHelpFunc := cmd.delegate.HelpFunc() |
| 329 | cmd.delegate.SetHelpFunc(func(c *cobra.Command, _ []string) { |
| 330 | if c == &cmd.delegate { |
| 331 | t := cmd.delegate.UsageTemplate() |
| 332 | t = strings.ReplaceAll(t, "{{if .Runnable}}", "{{if false}}") |
| 333 | c.SetUsageTemplate(t) |
| 334 | } |
| 335 | defaultHelpFunc(c, nil) |
| 336 | }) |
| 337 | return cmd |
| 338 | } |
no test coverage detected