oh-my-posh/src/segment_az.go

104 lines
2.1 KiB
Go
Raw Normal View History

package main
import (
"encoding/json"
"strings"
)
type az struct {
2021-11-26 01:37:33 -08:00
props properties
env environmentInfo
2021-11-09 10:52:02 -08:00
EnvironmentName string `json:"environmentName"`
HomeTenantID string `json:"homeTenantId"`
ID string `json:"id"`
IsDefault bool `json:"isDefault"`
Name string `json:"name"`
State string `json:"state"`
TenantID string `json:"tenantId"`
User *AzureUser `json:"user"`
}
const (
updateConsentNeeded = "Do you want to continue?"
updateMessage = "AZ CLI: Update needed!"
updateForeground = "#ffffff"
updateBackground = "#ff5349"
)
type AzureUser struct {
Name string `json:"name"`
}
func (a *az) string() string {
2021-11-09 10:52:02 -08:00
if a != nil && a.Name == updateMessage {
return updateMessage
2021-05-21 10:56:31 -07:00
}
segmentTemplate := a.props.getString(SegmentTemplate, "{{.Name}}")
template := &textTemplate{
Template: segmentTemplate,
2021-11-09 10:52:02 -08:00
Context: a,
Env: a.env,
2021-05-21 10:56:31 -07:00
}
text, err := template.render()
if err != nil {
return err.Error()
}
return text
}
2021-11-26 01:37:33 -08:00
func (a *az) init(props properties, env environmentInfo) {
a.props = props
a.env = env
}
func (a *az) enabled() bool {
2021-05-21 10:56:31 -07:00
if a.getFromEnvVars() {
return true
2021-03-27 06:52:27 -07:00
}
2021-05-21 10:56:31 -07:00
return a.getFromAzCli()
2021-03-27 06:52:27 -07:00
}
2021-05-21 10:56:31 -07:00
func (a *az) getFromEnvVars() bool {
environmentName := a.env.getenv("AZ_ENVIRONMENT_NAME")
userName := a.env.getenv("AZ_USER_NAME")
id := a.env.getenv("AZ_SUBSCRIPTION_ID")
accountName := a.env.getenv("AZ_ACCOUNT_NAME")
2021-03-27 06:52:27 -07:00
if userName == "" && environmentName == "" {
2021-05-21 10:56:31 -07:00
return false
2021-03-27 06:52:27 -07:00
}
2021-11-09 10:52:02 -08:00
a.EnvironmentName = environmentName
a.Name = accountName
a.ID = id
a.User = &AzureUser{
Name: userName,
}
2021-05-21 10:56:31 -07:00
return true
2021-03-27 06:52:27 -07:00
}
2021-05-21 10:56:31 -07:00
func (a *az) getFromAzCli() bool {
cmd := "az"
2021-05-21 10:56:31 -07:00
if !a.env.hasCommand(cmd) {
return false
}
output, _ := a.env.runCommand(cmd, "account", "show")
2021-05-21 10:56:31 -07:00
if len(output) == 0 {
return false
}
if strings.Contains(output, updateConsentNeeded) {
2021-11-26 01:37:33 -08:00
a.props[ForegroundOverride] = updateForeground
a.props[BackgroundOverride] = updateBackground
2021-11-09 10:52:02 -08:00
a.Name = updateMessage
2021-05-21 10:56:31 -07:00
return true
}
2021-11-09 10:52:02 -08:00
err := json.Unmarshal([]byte(output), a)
return err == nil
}