Example #1
0
// Call execute to use the args (os.Args[1:] by default)
// and run through the command tree finding appropriate matches
// for commands and then corresponding flags.
func (c *Command) Execute() (err error) {

	// Regardless of what command execute is called on, run on Root only
	if c.HasParent() {
		return c.Root().Execute()
	}

	if EnableWindowsMouseTrap && runtime.GOOS == "windows" {
		if mousetrap.StartedByExplorer() {
			c.Print(MousetrapHelpText)
			time.Sleep(5 * time.Second)
			os.Exit(1)
		}
	}

	// initialize help as the last point possible to allow for user
	// overriding
	c.initHelp()

	var args []string

	if len(c.args) == 0 {
		args = os.Args[1:]
	} else {
		args = c.args
	}

	cmd, flags, err := c.Find(args)
	if err == nil {
		err = cmd.execute(flags)
	}

	if err != nil {
		if err == flag.ErrHelp {
			c.Help()

		} else {
			c.Println("Error:", err.Error())
			c.Printf("Run '%v help' for usage.\n", c.Root().Name())
		}
	}

	return
}
Example #2
0
func (c *Command) ExecuteC() (cmd *Command, err error) {

	// Regardless of what command execute is called on, run on Root only
	if c.HasParent() {
		return c.Root().ExecuteC()
	}

	if EnableWindowsMouseTrap && runtime.GOOS == "windows" {
		if mousetrap.StartedByExplorer() {
			c.Print(MousetrapHelpText)
			time.Sleep(5 * time.Second)
			os.Exit(1)
		}
	}

	// initialize help as the last point possible to allow for user
	// overriding
	c.initHelpCmd()

	var args []string

	// Workaround FAIL with "go test -v" or "cobra.test -test.v", see #155
	if len(c.args) == 0 && filepath.Base(os.Args[0]) != "cobra.test" {
		args = os.Args[1:]
	} else {
		args = c.args
	}

	cmd, flags, err := c.Find(args)
	if err != nil {
		// If found parse to a subcommand and then failed, talk about the subcommand
		if cmd != nil {
			c = cmd
		}
		if !c.SilenceErrors {
			c.Println("Error:", err.Error())
			c.Printf("Run '%v --help' for usage.\n", c.CommandPath())
		}
		return c, err
	}
	err = cmd.execute(flags)
	if err != nil {
		// If root command has SilentErrors flagged,
		// all subcommands should respect it
		if !cmd.SilenceErrors && !c.SilenceErrors {
			if err == flag.ErrHelp {
				cmd.HelpFunc()(cmd, args)
				return cmd, nil
			}
			c.Println("Error:", err.Error())
		}

		// If root command has SilentUsage flagged,
		// all subcommands should respect it
		if !cmd.SilenceUsage && !c.SilenceUsage {
			c.Println(cmd.UsageString())
		}
		return cmd, err
	}
	return cmd, nil
}