-
Notifications
You must be signed in to change notification settings - Fork 161
Expand file tree
/
Copy pathenv.go
More file actions
70 lines (60 loc) · 1.83 KB
/
env.go
File metadata and controls
70 lines (60 loc) · 1.83 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
package auth
import (
"encoding/json"
"fmt"
"maps"
"slices"
"strings"
"github.com/databricks/cli/cmd/root"
"github.com/databricks/cli/libs/auth"
"github.com/databricks/cli/libs/cmdctx"
"github.com/databricks/cli/libs/flags"
"github.com/spf13/cobra"
)
func newEnvCommand() *cobra.Command {
cmd := &cobra.Command{
Use: "env",
Short: "Get authentication environment variables for the current CLI context",
Long: `Output the environment variables needed to authenticate as the same identity
the CLI is currently authenticated as. This is useful for configuring downstream
tools that accept Databricks authentication via environment variables.`,
}
cmd.RunE = func(cmd *cobra.Command, args []string) error {
_, err := root.MustAnyClient(cmd, args)
if err != nil {
return err
}
cfg := cmdctx.ConfigUsed(cmd.Context())
envVars := auth.Env(cfg)
// Output KEY=VALUE lines when the user explicitly passes --output text.
if cmd.Flag("output").Changed && root.OutputType(cmd) == flags.OutputText {
w := cmd.OutOrStdout()
keys := slices.Sorted(maps.Keys(envVars))
for _, k := range keys {
fmt.Fprintf(w, "%s=%s\n", k, quoteEnvValue(envVars[k]))
}
return nil
}
raw, err := json.MarshalIndent(envVars, "", " ")
if err != nil {
return err
}
_, _ = cmd.OutOrStdout().Write(raw)
return nil
}
return cmd
}
const shellQuotedSpecialChars = " \t\n\r\"\\$`!#&|;(){}[]<>?*~'"
// quoteEnvValue quotes a value for KEY=VALUE output if it contains spaces or
// shell-special characters. Single quotes prevent shell expansion, and
// embedded single quotes use the POSIX-compatible '\" sequence.
func quoteEnvValue(v string) string {
if v == "" {
return `''`
}
needsQuoting := strings.ContainsAny(v, shellQuotedSpecialChars)
if !needsQuoting {
return v
}
return "'" + strings.ReplaceAll(v, "'", "'\\''") + "'"
}