| 445 | } |
| 446 | |
| 447 | func (c *Command) execute(a []string) (err error) { |
| 448 | if c == nil { |
| 449 | return fmt.Errorf("Called Execute() on a nil Command") |
| 450 | } |
| 451 | |
| 452 | if len(c.Deprecated) > 0 { |
| 453 | c.Printf("Command %q is deprecated, %s\n", c.Name(), c.Deprecated) |
| 454 | } |
| 455 | |
| 456 | err = c.ParseFlags(a) |
| 457 | if err == flag.ErrHelp { |
| 458 | c.Help() |
| 459 | return nil |
| 460 | } |
| 461 | if err != nil { |
| 462 | // We're writing subcommand usage to root command's error buffer to have it displayed to the user |
| 463 | r := c.Root() |
| 464 | if r.cmdErrorBuf == nil { |
| 465 | r.cmdErrorBuf = new(bytes.Buffer) |
| 466 | } |
| 467 | // for writing the usage to the buffer we need to switch the output temporarily |
| 468 | // since Out() returns root output, you also need to revert that on root |
| 469 | out := r.Out() |
| 470 | r.SetOutput(r.cmdErrorBuf) |
| 471 | c.Usage() |
| 472 | r.SetOutput(out) |
| 473 | return err |
| 474 | } |
| 475 | // If help is called, regardless of other flags, we print that. |
| 476 | // Print help also if c.Run is nil. |
| 477 | if c.helpFlagVal || !c.Runnable() { |
| 478 | c.Help() |
| 479 | return nil |
| 480 | } |
| 481 | |
| 482 | c.preRun() |
| 483 | argWoFlags := c.Flags().Args() |
| 484 | |
| 485 | for p := c; p != nil; p = p.Parent() { |
| 486 | if p.PersistentPreRun != nil { |
| 487 | p.PersistentPreRun(c, argWoFlags) |
| 488 | break |
| 489 | } |
| 490 | } |
| 491 | if c.PreRun != nil { |
| 492 | c.PreRun(c, argWoFlags) |
| 493 | } |
| 494 | |
| 495 | c.Run(c, argWoFlags) |
| 496 | |
| 497 | if c.PostRun != nil { |
| 498 | c.PostRun(c, argWoFlags) |
| 499 | } |
| 500 | for p := c; p != nil; p = p.Parent() { |
| 501 | if p.PersistentPostRun != nil { |
| 502 | p.PersistentPostRun(c, argWoFlags) |
| 503 | break |
| 504 | } |