-
Notifications
You must be signed in to change notification settings - Fork 280
Expand file tree
/
Copy pathsegment-azure.go
More file actions
128 lines (104 loc) · 2.4 KB
/
segment-azure.go
File metadata and controls
128 lines (104 loc) · 2.4 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
package main
import (
"bytes"
"encoding/json"
"os"
"path/filepath"
"strings"
pwl "github.com/justjanne/powerline-go/powerline"
)
// utf8BOM is the UTF-8 byte order mark that Azure CLI may add to JSON files
var utf8BOM = []byte{0xEF, 0xBB, 0xBF}
type azureSubscription struct {
ID string `json:"id"`
Name string `json:"name"`
State string `json:"state"`
IsDefault bool `json:"isDefault"`
}
type azureProfile struct {
Subscriptions []azureSubscription `json:"subscriptions"`
}
func getAzureSubscription() string {
envSubID := os.Getenv("AZURE_SUBSCRIPTION_ID")
home, err := os.UserHomeDir()
if err != nil {
return envSubID
}
data, err := os.ReadFile(filepath.Join(home, ".azure", "azureProfile.json"))
if err != nil {
return envSubID
}
data = bytes.TrimPrefix(data, utf8BOM)
var profile azureProfile
if err := json.Unmarshal(data, &profile); err != nil {
return envSubID
}
if envSubID != "" {
for _, sub := range profile.Subscriptions {
if sub.ID == envSubID {
return sub.Name
}
}
return envSubID
}
var firstEnabled string
for _, sub := range profile.Subscriptions {
if sub.State != "Enabled" {
continue
}
if sub.IsDefault {
return sub.Name
}
if firstEnabled == "" {
firstEnabled = sub.Name
}
}
return firstEnabled
}
func getAzureResourceGroup() string {
if rg := os.Getenv("AZURE_DEFAULTS_GROUP"); rg != "" {
return rg
}
home, err := os.UserHomeDir()
if err != nil {
return ""
}
data, err := os.ReadFile(filepath.Join(home, ".azure", "config"))
if err != nil {
return ""
}
inDefaults := false
for _, line := range strings.Split(string(data), "\n") {
line = strings.TrimSpace(line)
if line == "[defaults]" {
inDefaults = true
continue
}
if strings.HasPrefix(line, "[") {
inDefaults = false
continue
}
if inDefaults && (strings.HasPrefix(line, "group ") || strings.HasPrefix(line, "group=")) {
if parts := strings.SplitN(line, "=", 2); len(parts) == 2 {
return strings.TrimSpace(parts[1])
}
}
}
return ""
}
func segmentAzure(p *powerline) []pwl.Segment {
subscription := getAzureSubscription()
if subscription == "" {
return []pwl.Segment{}
}
content := subscription
if rg := getAzureResourceGroup(); rg != "" {
content += " (" + rg + ")"
}
return []pwl.Segment{{
Name: "azure",
Content: content,
Foreground: p.theme.AzureFg,
Background: p.theme.AzureBg,
}}
}