cobra のソースコードを読んで 調査をしてみた

- Golang cobra

概要

調査内容

  1. CLI アプリケーションが実行されるまでの流れに関して
  2. rootCmd.RunrootCmd.RunE の違いに関して
  3. cobra がデフォルトで出すエラーメッセージを出さない方法に関して

調査内容 1 (cobra の内部実装)

cobra-flow.png

調査内容 2 (rootCmd.Run と rootCmd.RunE の違いに関して)

var rootCmd = &cobra.Command{
	Use:           "gngc",
	Short:         "Get and Notify GitHub Contributions",
	Long:          "A simple command line application to get GitHub contributions from GraphQL API and notify them to IFTTT.",
	SilenceErrors: true,
	// SilenceUsage:  true,

	RunE: runCommand,
}
func (c *Command) execute(a []string) (err error) {
...
	if !c.Runnable() {
		return flag.ErrHelp
	}
...
	if c.RunE != nil {
		if err := c.RunE(c, argWoFlags); err != nil {
			return err
		}
	} else {
		c.Run(c, argWoFlags)
	}
...
}

func (c *Command) Runnable() bool {
	return c.Run != nil || c.RunE != nil
}

調査内容 3 (cobra がデフォルト出すエラーメッセージを出さない方法に関して)

> go run main.go -g
Error: unknown shorthand flag: 'g' in -g
Usage:
  gngc [flags]

Flags:
      --config string   config file (default is $HOME/.gngc.toml)
  -h, --help            help for gngc
  -n, --notify          Get GitHub contributions and notify them to IFTTT.

Error: unknown shorthand flag: 'g' in -g
exit status 1
func (c *Command) ExecuteC() (cmd *Command, err error) {
...
	err = cmd.execute(flags)
	if err != nil {
		// Always show help if requested, even if SilenceErrors is in
		// effect
		if err == flag.ErrHelp {
			cmd.HelpFunc()(cmd, args)
			return cmd, nil
		}

		// If root command has SilenceErrors flagged,
		// all subcommands should respect it
		if !cmd.SilenceErrors && !c.SilenceErrors {
			c.PrintErrln("Error:", err.Error())
		}

		// If root command has SilenceUsage flagged,
		// all subcommands should respect it
		if !cmd.SilenceUsage && !c.SilenceUsage {
			c.Println(cmd.UsageString())
		}
	}
	return cmd, err
}
type Command struct {
...
	// SilenceErrors is an option to quiet errors down stream.
	SilenceErrors bool

	// SilenceUsage is an option to silence usage when an error occurs.
	SilenceUsage bool
...
}

結論

参考