Execute is the primary entrypoint of the CLI app.
()
| 51 | |
| 52 | // Execute is the primary entrypoint of the CLI app. |
| 53 | func Execute() { |
| 54 | cli := &cli{ |
| 55 | renderer: display.NewRenderer(), |
| 56 | tracker: analytics.NewTracker(), |
| 57 | } |
| 58 | |
| 59 | // Prevent sorting of commands. |
| 60 | cobra.EnableCommandSorting = false |
| 61 | |
| 62 | rootCmd := buildRootCmd(cli) |
| 63 | rootCmd.SetUsageTemplate(namespaceUsageTemplate()) |
| 64 | |
| 65 | addPersistentFlags(rootCmd, cli) |
| 66 | addSubCommands(rootCmd, cli) |
| 67 | |
| 68 | overrideHelpAndVersionFlagText(rootCmd) |
| 69 | |
| 70 | defer func() { |
| 71 | if v := recover(); v != nil { |
| 72 | err := fmt.Errorf("panic: %v", v) |
| 73 | |
| 74 | if instrumentation.ReportException(err) { |
| 75 | fmt.Print(panicMessage) // If we're in development mode, we should throw the panic for so we have less surprises. |
| 76 | } else { |
| 77 | panic(v) // For non-developers, we'll swallow the panics. |
| 78 | } |
| 79 | } |
| 80 | }() |
| 81 | |
| 82 | // Platform specific terminal initialization: |
| 83 | // this should run for all commands, |
| 84 | // for most of the architectures there's no requirements. |
| 85 | ansi.InitConsole() |
| 86 | |
| 87 | cancelCtx := contextWithCancel() |
| 88 | err := rootCmd.ExecuteContext(cancelCtx) |
| 89 | trackCommandOutcome(cli, err) |
| 90 | |
| 91 | timeoutCtx, cancel := context.WithTimeout(cancelCtx, 3*time.Second) |
| 92 | defer cancel() |
| 93 | cli.tracker.Wait(timeoutCtx) // No event should be tracked after this has run. |
| 94 | |
| 95 | if err != nil { |
| 96 | renderErrorMessage(cli.renderer, err.Error()) |
| 97 | |
| 98 | instrumentation.ReportException(err) |
| 99 | os.Exit(1) // nolint:gocritic |
| 100 | } |
| 101 | } |
| 102 | |
| 103 | func buildRootCmd(cli *cli) *cobra.Command { |
| 104 | rootCmd := &cobra.Command{ |
no test coverage detected