-
Notifications
You must be signed in to change notification settings - Fork 152
Expand file tree
/
Copy pathbundle.go
More file actions
257 lines (224 loc) · 7.42 KB
/
bundle.go
File metadata and controls
257 lines (224 loc) · 7.42 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
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
package root
import (
"context"
"errors"
"fmt"
"strings"
"github.com/databricks/cli/bundle"
"github.com/databricks/cli/bundle/env"
"github.com/databricks/cli/bundle/phases"
"github.com/databricks/cli/libs/cmdctx"
"github.com/databricks/cli/libs/cmdio"
"github.com/databricks/cli/libs/databrickscfg"
"github.com/databricks/cli/libs/databrickscfg/profile"
envlib "github.com/databricks/cli/libs/env"
"github.com/databricks/cli/libs/logdiag"
"github.com/spf13/cobra"
"golang.org/x/exp/maps"
)
// getTarget returns the name of the target to operate in.
func getTarget(cmd *cobra.Command) (value string) {
target, isFlagSet := targetFlagValue(cmd)
if isFlagSet {
return target
}
// If it's not set, use the environment variable.
target, _ = env.Target(cmd.Context())
return target
}
func targetFlagValue(cmd *cobra.Command) (string, bool) {
// The command line flag takes precedence.
flag := cmd.Flag("target")
if flag != nil {
value := flag.Value.String()
if value != "" {
return value, true
}
}
oldFlag := cmd.Flag("environment")
if oldFlag != nil {
value := oldFlag.Value.String()
if value != "" {
return value, true
}
}
return "", false
}
func getProfile(cmd *cobra.Command) (value string) {
// The command line flag takes precedence.
flag := cmd.Flag("profile")
if flag != nil {
value = flag.Value.String()
if value != "" {
return value
}
}
// If it's not set, use the environment variable.
return envlib.Get(cmd.Context(), "DATABRICKS_CONFIG_PROFILE")
}
// configureProfile applies the profile flag to the bundle.
func configureProfile(cmd *cobra.Command, b *bundle.Bundle) {
profile := getProfile(cmd)
if profile == "" {
return
}
bundle.ApplyFuncContext(cmd.Context(), b, func(ctx context.Context, b *bundle.Bundle) {
b.Config.Workspace.Profile = profile
})
}
// resolveProfileAmbiguity resolves a multi-profile match by filtering to
// workspace-compatible profiles and either auto-selecting, prompting, or
// returning a guidance error.
func resolveProfileAmbiguity(cmd *cobra.Command, b *bundle.Bundle, originalErr error, names []string) (string, error) {
ctx := cmd.Context()
namesMatcher := profile.MatchProfileNames(names...)
profiler := profile.GetProfiler(ctx)
profiles, err := profiler.LoadProfiles(ctx, func(p profile.Profile) bool {
return namesMatcher(p) && profile.MatchWorkspaceProfiles(p)
})
if err != nil {
if errors.Is(err, profile.ErrNoConfiguration) {
return "", originalErr
}
return "", err
}
switch len(profiles) {
case 0:
return "", originalErr
case 1:
// Exactly one workspace-compatible profile — auto-select.
// This happens when multiple profiles match a host but only one
// is workspace-compatible (the rest are account-only).
return profiles[0].Name, nil
}
// Multiple workspace-compatible profiles — need interactive selection.
_, hasProfileFlag := profileFlagValue(cmd)
allowPrompt := !hasProfileFlag && !shouldSkipPrompt(ctx)
if !allowPrompt || !cmdio.IsPromptSupported(ctx) {
return "", fmt.Errorf(
"%w\n\nMatching workspace profiles: %s\n\n"+
"Fix (pick one):\n"+
" 1. Set profile in databricks.yml:\n"+
" workspace:\n"+
" profile: %s\n"+
" 2. Pass a flag:\n"+
" %s --profile %s\n"+
" 3. Set env var:\n"+
" DATABRICKS_CONFIG_PROFILE=%s",
originalErr,
strings.Join(profiles.Names(), ", "),
profiles[0].Name,
cmd.CommandPath(),
profiles[0].Name,
profiles[0].Name,
)
}
return profile.SelectProfile(ctx, profile.SelectConfig{
Label: "Multiple profiles match host " + b.Config.Workspace.Host,
Profiles: profiles,
StartInSearchMode: true,
ActiveTemplate: `{{.Name | bold}}{{if .AccountID}} (account: {{.AccountID|faint}}){{end}}{{if .WorkspaceID}} (workspace: {{.WorkspaceID|faint}}){{end}}`,
InactiveTemplate: `{{.Name}}{{if .AccountID}} (account: {{.AccountID}}){{end}}{{if .WorkspaceID}} (workspace: {{.WorkspaceID}}){{end}}`,
SelectedTemplate: `{{ "Using profile" | faint }}: {{ .Name | bold }}`,
})
}
// configureBundle loads the bundle configuration and configures flag values, if any.
func configureBundle(cmd *cobra.Command, b *bundle.Bundle) {
// Load bundle and select target.
ctx := cmd.Context()
if target := getTarget(cmd); target == "" {
phases.LoadDefaultTarget(ctx, b)
} else {
phases.LoadNamedTarget(ctx, b, target)
}
if logdiag.HasError(ctx) {
return
}
// Configure the workspace profile if the flag has been set.
configureProfile(cmd, b)
// Set the auth configuration in the command context. This can be used
// downstream to initialize a API client.
//
// Note that just initializing a workspace client and loading auth configuration
// is a fast operation. It does not perform network I/O or invoke processes (for example the Azure CLI).
client, err := b.WorkspaceClientE()
if err != nil {
names, isMulti := databrickscfg.AsMultipleProfiles(err)
if !isMulti {
logdiag.LogError(ctx, err)
return
}
selected, resolveErr := resolveProfileAmbiguity(cmd, b, err, names)
if resolveErr != nil {
logdiag.LogError(ctx, resolveErr)
return
}
b.Config.Workspace.Profile = selected
b.ClearWorkspaceClient()
client, err = b.WorkspaceClientE()
if err != nil {
logdiag.LogError(ctx, err)
return
}
}
ctx = cmdctx.SetConfigUsed(ctx, client.Config)
cmd.SetContext(ctx)
}
// MustConfigureBundle configures a bundle on the command context.
func MustConfigureBundle(cmd *cobra.Command) *bundle.Bundle {
// A bundle may be configured on the context when testing.
// If it is, return it immediately.
b := bundle.GetOrNil(cmd.Context())
if b != nil {
return b
}
b = bundle.MustLoad(cmd.Context())
if b != nil {
configureBundle(cmd, b)
}
return b
}
// TryConfigureBundle configures a bundle on the command context
// if there is one, but doesn't fail if there isn't one.
func TryConfigureBundle(cmd *cobra.Command) *bundle.Bundle {
// A bundle may be configured on the context when testing.
// If it is, return it immediately.
b := bundle.GetOrNil(cmd.Context())
if b != nil {
return b
}
ctx := cmd.Context()
b = bundle.TryLoad(ctx)
// No bundle is fine in this case.
if b == nil || logdiag.HasError(ctx) {
return nil
}
configureBundle(cmd, b)
return b
}
// targetCompletion executes to autocomplete the argument to the target flag.
func targetCompletion(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
ctx := cmd.Context()
b := bundle.MustLoad(ctx)
if b == nil || logdiag.HasError(ctx) {
return nil, cobra.ShellCompDirectiveError
}
// Load bundle but don't select a target (we're completing those).
phases.Load(ctx, b)
if logdiag.HasError(ctx) {
return nil, cobra.ShellCompDirectiveError
}
return maps.Keys(b.Config.Targets), cobra.ShellCompDirectiveDefault
}
func initTargetFlag(cmd *cobra.Command) {
// To operate in the context of a bundle, all commands must take an "target" parameter.
cmd.PersistentFlags().StringP("target", "t", "", "bundle target to use (if applicable)")
cmd.RegisterFlagCompletionFunc("target", targetCompletion)
}
// DEPRECATED flag
func initEnvironmentFlag(cmd *cobra.Command) {
// To operate in the context of a bundle, all commands must take an "environment" parameter.
cmd.PersistentFlags().StringP("environment", "e", "", "bundle target to use (if applicable)")
cmd.PersistentFlags().MarkDeprecated("environment", "use --target flag instead")
cmd.RegisterFlagCompletionFunc("environment", targetCompletion)
}