-
Notifications
You must be signed in to change notification settings - Fork 0
/
gcloud-select.go
96 lines (83 loc) · 2.41 KB
/
gcloud-select.go
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
package main
import (
"encoding/json"
"flag"
"fmt"
"os/exec"
"github.com/manifoldco/promptui"
_ "github.com/Harwayne/kubectl-select/pkg/removebell"
)
var (
gcloud = flag.String("gcloud", "gcloud", "gcloud command")
)
func main() {
flag.Parse()
configs := listConfigs()
displayAndChooseConfig(configs)
}
type gcloudConfig struct {
IsActive bool `json:"is_active"`
Name string `json:"name"`
Properties gcloudConfigProperties `json:"properties"`
}
type gcloudConfigProperties struct {
ApiEndpointOverrides gcloudConfigApiEndpointOverrides `json:"api_endpoint_overrides"`
Core gcloudConfigCore `json:"core"`
}
type gcloudConfigApiEndpointOverrides struct {
Dataproc string `json:"dataproc"`
}
type gcloudConfigCore struct {
Account string `json:"account"`
Project string `json:"project"`
}
func listConfigs() []gcloudConfig {
b, err := exec.Command(*gcloud, "config", "configurations", "list", "--format=json").CombinedOutput()
if err != nil {
panic(fmt.Errorf("listing configurations: %w", err))
}
var configs []gcloudConfig
if err := json.Unmarshal(b, &configs); err != nil {
panic(fmt.Errorf("json unmarshalling bytes: %q, %w", string(b), err))
}
return configs
}
func useConfig(c gcloudConfig) []byte {
b, err := exec.Command(*gcloud, "config", "configurations", "activate", c.Name).CombinedOutput()
if err != nil {
panic(fmt.Errorf("activating configuration: %q, %w", string(b), err))
}
return b
}
func displayAndChooseConfig(configs []gcloudConfig) {
var activeIndex int
for i, c := range configs {
if c.IsActive {
activeIndex = i
break
}
}
prompt := promptui.Select{
Label: "gcloud configuration",
Items: configs,
Templates: &promptui.SelectTemplates{
Active: "{{ .Name | cyan | underline }}" +
"{{ if .IsActive }} {{- \" (Active)\" | cyan | underline }} {{ end }}",
Inactive: "{{ .Name }}{{ if .IsActive }} {{- \" (Active)\" }} {{ end }}",
Details: "Account: {{ .Properties.Core.Account }}\t" +
"Project: {{ .Properties.Core.Project }}" +
"{{- if .Properties.ApiEndpointOverrides.Dataproc }} " +
"\tDataproc: {{ .Properties.ApiEndpointOverrides.Dataproc }} " +
"{{ end }}",
},
Size: len(configs),
HideSelected: true,
}
i, _, err := prompt.RunCursorAt(activeIndex, 0)
if err != nil {
fmt.Printf("Prompt failed: %v\n", err)
return
}
b := useConfig(configs[i])
fmt.Print(string(b))
}