| 62 | } |
| 63 | |
| 64 | func NewCmdRoot(f *cmdutil.Factory, telemetry ghtelemetry.CommandRecorder, version, buildDate string) (*cobra.Command, error) { |
| 65 | io := f.IOStreams |
| 66 | cfg, err := f.Config() |
| 67 | if err != nil { |
| 68 | return nil, fmt.Errorf("failed to read configuration: %s\n", err) |
| 69 | } |
| 70 | |
| 71 | cmd := &cobra.Command{ |
| 72 | Use: "gh <command> <subcommand> [flags]", |
| 73 | Short: "GitHub CLI", |
| 74 | Long: `Work seamlessly with GitHub from the command line.`, |
| 75 | Example: heredoc.Doc(` |
| 76 | $ gh issue create |
| 77 | $ gh repo clone cli/cli |
| 78 | $ gh pr checkout 321 |
| 79 | `), |
| 80 | Annotations: map[string]string{ |
| 81 | "versionInfo": versionCmd.Format(version, buildDate), |
| 82 | }, |
| 83 | PersistentPreRunE: func(cmd *cobra.Command, args []string) error { |
| 84 | // require that the user is authenticated before running most commands |
| 85 | if cmdutil.IsAuthCheckEnabled(cmd) && !cmdutil.CheckAuth(cfg) { |
| 86 | parent := cmd.Parent() |
| 87 | if parent != nil && parent.Use == "codespace" { |
| 88 | fmt.Fprintln(io.ErrOut, "To get started with GitHub CLI, please run: gh auth login -s codespace") |
| 89 | } else { |
| 90 | fmt.Fprint(io.ErrOut, authHelp()) |
| 91 | } |
| 92 | return &AuthError{} |
| 93 | } |
| 94 | |
| 95 | return nil |
| 96 | }, |
| 97 | } |
| 98 | |
| 99 | // cmd.SetOut(f.IOStreams.Out) // can't use due to https://github.com/spf13/cobra/issues/1708 |
| 100 | // cmd.SetErr(f.IOStreams.ErrOut) // just let it default to os.Stderr instead |
| 101 | |
| 102 | cmd.PersistentFlags().Bool("help", false, "Show help for command") |
| 103 | |
| 104 | // override Cobra's default behaviors unless an opt-out has been set |
| 105 | if os.Getenv("GH_COBRA") == "" { |
| 106 | cmd.SilenceErrors = true |
| 107 | cmd.SilenceUsage = true |
| 108 | |
| 109 | // this --version flag is checked in rootHelpFunc |
| 110 | cmd.Flags().Bool("version", false, "Show gh version") |
| 111 | |
| 112 | cmd.SetHelpFunc(func(c *cobra.Command, args []string) { |
| 113 | rootHelpFunc(f, c, args) |
| 114 | }) |
| 115 | cmd.SetUsageFunc(func(c *cobra.Command) error { |
| 116 | return rootUsageFunc(f.IOStreams.ErrOut, c) |
| 117 | }) |
| 118 | cmd.SetFlagErrorFunc(rootFlagErrorFunc) |
| 119 | } |
| 120 | |
| 121 | cmd.AddGroup(&cobra.Group{ |