-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
104 lines (87 loc) · 2.07 KB
/
main.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
97
98
99
100
101
102
103
104
package main
import (
"bytes"
"context"
"fmt"
"os"
"os/exec"
resourcemanager "cloud.google.com/go/resourcemanager/apiv3"
"cloud.google.com/go/resourcemanager/apiv3/resourcemanagerpb"
log "github.com/sirupsen/logrus"
"google.golang.org/api/iterator"
)
func main() {
if err := run(); err != nil {
log.Errorf("run: %v", err)
os.Exit(1)
}
}
func run() error {
ctx := context.Background()
projectsClient, err := resourcemanager.NewProjectsClient(ctx)
if err != nil {
return err
}
projectsIt := projectsClient.SearchProjects(ctx, &resourcemanagerpb.SearchProjectsRequest{})
tenantProjects := make(map[string]map[string]*resourcemanagerpb.Project)
for project, err := projectsIt.Next(); err != iterator.Done; project, err = projectsIt.Next() {
if err != nil {
return err
}
tenant := project.GetLabels()["tenant"]
if tenant == "" {
tenant = "no tenant label"
}
if tenantProjects[tenant] == nil {
tenantProjects[tenant] = make(map[string]*resourcemanagerpb.Project)
}
tenantProjects[tenant][project.GetProjectId()] = project
}
tenants := make([]string, len(tenantProjects))
i := 0
for tenant := range tenantProjects {
tenants[i] = tenant
i++
}
tenant := fzf(tenants)
project := fzf(keys(tenantProjects[tenant]))
url := productUrls[fzf(keys(productUrls))]
if url == "custom://launch-ssh" {
return ssh(project)
} else {
fmt.Printf("https://console.cloud.google.com%s?project=%s\n", url, project)
}
return nil
}
func fzf(l []string) string {
shell := os.Getenv("SHELL")
if len(shell) == 0 {
shell = "sh"
}
cmd := exec.Command(shell, "-c", "fzf")
cmd.Stderr = os.Stderr
stdin, err := cmd.StdinPipe()
if err != nil {
log.Error("fzf: get stdin pipe: %w", err)
return ""
}
for _, el := range l {
fmt.Fprintln(stdin, el)
}
stdin.Close()
result, err := cmd.Output()
if err != nil {
log.Error("fzf: get stdout output: %w", err)
return ""
}
return string(bytes.TrimSpace(result))
}
func keys[T any](m map[string]T) []string {
keys := make([]string, len(m))
i := 0
for key := range m {
keys[i] = key
i++
}
return keys
}