-
Notifications
You must be signed in to change notification settings - Fork 153
Expand file tree
/
Copy pathroot.go
More file actions
221 lines (184 loc) · 6.28 KB
/
root.go
File metadata and controls
221 lines (184 loc) · 6.28 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
package root
import (
"context"
"errors"
"fmt"
"log/slog"
"os"
"runtime"
"runtime/debug"
"strings"
"time"
"github.com/databricks/cli/internal/build"
"github.com/databricks/cli/libs/auth"
"github.com/databricks/cli/libs/cmdctx"
"github.com/databricks/cli/libs/cmdio"
"github.com/databricks/cli/libs/dbr"
"github.com/databricks/cli/libs/log"
"github.com/databricks/cli/libs/telemetry"
"github.com/databricks/cli/libs/telemetry/protos"
"github.com/spf13/cobra"
)
func New(ctx context.Context) *cobra.Command {
cmd := &cobra.Command{
Use: "databricks",
Short: "Databricks CLI",
Version: build.GetInfo().Version,
// Cobra prints the usage string to stderr if a command returns an error.
// This usage string should only be displayed if an invalid combination of flags
// is specified and not when runtime errors occur (e.g. resource not found).
// The usage string is include in [flagErrorFunc] for flag errors only.
SilenceUsage: true,
// Silence error printing by cobra. Errors are printed through cmdio.
SilenceErrors: true,
}
// Pass the context along through the command during initialization.
// It will be overwritten when the command is executed.
cmd.SetContext(ctx)
// Initialize flags
logFlags := initLogFlags(cmd)
outputFlag := initOutputFlag(cmd)
initProfileFlag(cmd)
initEnvironmentFlag(cmd)
initTargetFlag(cmd)
// Deprecated flag. Warn if it is specified.
initProgressLoggerFlag(cmd, logFlags)
cmd.PersistentPreRunE = func(cmd *cobra.Command, args []string) error {
var err error
ctx := cmd.Context()
// Configure command IO
ctx, err = outputFlag.initializeIO(ctx, cmd)
if err != nil {
return err
}
// Configure default logger.
ctx, err = logFlags.initializeContext(ctx)
if err != nil {
return err
}
logger := log.GetLogger(ctx)
logger.Info("start",
slog.String("version", build.GetInfo().Version),
slog.String("args", strings.Join(os.Args, ", ")))
// Configure our user agent with the command that's about to be executed.
ctx = withCommandInUserAgent(ctx, cmd)
ctx = withCommandExecIdInUserAgent(ctx)
ctx = withUpstreamInUserAgent(ctx)
ctx = withInteractiveModeInUserAgent(ctx)
ctx = InjectTestPidToUserAgent(ctx)
cmd.SetContext(ctx)
return nil
}
cmd.PersistentPostRunE = func(cmd *cobra.Command, args []string) error {
// Wait for any active Bubble Tea programs to finish and restore terminal state
cmdio.Wait(cmd.Context())
return nil
}
cmd.SetFlagErrorFunc(flagErrorFunc)
cmd.SetVersionTemplate("Databricks CLI v{{.Version}}\n")
return cmd
}
// flagErrorFunc wraps flag errors to include the usage string and, for unknown
// flags, a "Did you mean" suggestion based on Levenshtein distance.
func flagErrorFunc(c *cobra.Command, err error) error {
err = suggestFlagFromError(c, err)
return fmt.Errorf("%w\n\n%s", err, c.UsageString())
}
// Execute adds all child commands to the root command and sets flags appropriately.
// This is called by main.main(). It only needs to happen once to the rootCmd.
func Execute(ctx context.Context, cmd *cobra.Command) (err error) {
defer func() {
r := recover()
// No panic. Return normally.
if r == nil {
return
}
version := build.GetInfo().Version
trace := debug.Stack()
// Set the error so that the CLI exits with a non-zero exit code.
err = fmt.Errorf("panic: %v", r)
fmt.Fprintf(cmd.ErrOrStderr(), `The Databricks CLI unexpectedly had a fatal error.
Please report this issue to Databricks in the form of a GitHub issue at:
https://github.com/databricks/cli
CLI Version: %s
Panic Payload: %v
Stack Trace:
%s`, version, r, string(trace))
}()
// Configure a telemetry logger and store it in the context.
ctx = telemetry.WithNewLogger(ctx)
// Detect if the CLI is running on DBR and store this on the context.
ctx = dbr.DetectRuntime(ctx)
// Set a command execution ID value in the context
ctx = cmdctx.GenerateExecId(ctx)
startTime := time.Now()
// Run the command
cmd, err = cmd.ExecuteContextC(ctx)
if err != nil && !errors.Is(err, ErrAlreadyPrinted) {
if cmdctx.HasConfigUsed(cmd.Context()) {
cfg := cmdctx.ConfigUsed(cmd.Context())
err = auth.EnrichAuthError(cmd.Context(), cfg, err)
}
fmt.Fprintf(cmd.ErrOrStderr(), "Error: %s\n", err.Error())
}
// Log exit status and error
// We only log if logger initialization succeeded and is stored in command
// context
if logger, ok := log.FromContext(cmd.Context()); ok {
if err == nil {
logger.Info("completed execution",
slog.String("exit_code", "0"))
} else if errors.Is(err, ErrAlreadyPrinted) {
logger.Debug("failed execution",
slog.String("exit_code", "1"),
)
} else {
logger.Info("failed execution",
slog.String("exit_code", "1"),
slog.String("error", err.Error()),
)
}
}
exitCode := 0
if err != nil {
exitCode = 1
}
commandStr := commandString(cmd)
ctx = cmd.Context()
// Log bundle deploy failures. Only log if we have successfully configured
// an authenticated Databricks client. We cannot log unauthenticated telemetry
// from the CLI yet.
if cmdctx.HasConfigUsed(ctx) && commandStr == "bundle_deploy" && exitCode != 0 {
telemetry.Log(ctx, protos.DatabricksCliLog{
BundleDeployEvent: &protos.BundleDeployEvent{},
})
}
telemetryErr := telemetry.Upload(cmd.Context(), protos.ExecutionContext{
CmdExecID: cmdctx.ExecId(ctx),
Version: build.GetInfo().Version,
Command: commandStr,
OperatingSystem: runtime.GOOS,
DbrVersion: dbr.RuntimeVersion(ctx).String(),
ExecutionTimeMs: time.Since(startTime).Milliseconds(),
ExitCode: int64(exitCode),
})
if telemetryErr != nil {
log.Infof(ctx, "telemetry upload failed: %s", telemetryErr)
}
return err
}
// This function is used to report an unknown subcommand.
// It is used in the [cobra.Command.RunE] field of commands that have subcommands.
// If user provided a valid subcommand, RunE for the
// If there are any arguments, it means the user has provided an unknown subcommand.
// If there are no arguments, it means the user has not provided any subcommand, and the help
// command should be displayed.
func ReportUnknownSubcommand(cmd *cobra.Command, args []string) error {
if len(args) > 0 {
return &InvalidArgsError{
Message: fmt.Sprintf("unknown command %q for %q", args[0], cmd.CommandPath()),
Command: cmd,
}
}
return cmd.Help()
}