oh-my-posh/src/segments/aws.go

90 lines
1.9 KiB
Go
Raw Normal View History

2022-01-26 06:54:36 -08:00
package segments
2021-02-07 01:55:09 -08:00
import (
"fmt"
"oh-my-posh/environment"
"oh-my-posh/properties"
2021-02-07 01:55:09 -08:00
"strings"
)
2022-01-26 05:10:18 -08:00
type Aws struct {
props properties.Properties
env environment.Environment
2021-02-07 01:55:09 -08:00
Profile string
Region string
}
const (
defaultUser = "default"
)
func (a *Aws) Template() string {
2022-02-01 05:07:58 -08:00
return " {{ .Profile }}{{ if .Region }}@{{ .Region }}{{ end }} "
}
func (a *Aws) Init(props properties.Properties, env environment.Environment) {
2021-02-07 01:55:09 -08:00
a.props = props
a.env = env
}
func (a *Aws) Enabled() bool {
2021-02-07 01:55:09 -08:00
getEnvFirstMatch := func(envs ...string) string {
for _, env := range envs {
value := a.env.Getenv(env)
2021-02-07 01:55:09 -08:00
if value != "" {
return value
}
}
return ""
}
displayDefaultUser := a.props.GetBool(properties.DisplayDefault, true)
2021-02-07 01:55:09 -08:00
a.Profile = getEnvFirstMatch("AWS_VAULT", "AWS_PROFILE")
if !displayDefaultUser && a.Profile == defaultUser {
return false
}
a.Region = getEnvFirstMatch("AWS_REGION", "AWS_DEFAULT_REGION")
2021-02-07 01:55:09 -08:00
if a.Profile != "" && a.Region != "" {
return true
}
if a.Profile == "" && a.Region != "" && displayDefaultUser {
2021-02-07 01:55:09 -08:00
a.Profile = defaultUser
return true
}
a.getConfigFileInfo()
if !displayDefaultUser && a.Profile == defaultUser {
return false
}
2021-02-07 01:55:09 -08:00
return a.Profile != ""
}
2022-01-26 05:10:18 -08:00
func (a *Aws) getConfigFileInfo() {
configPath := a.env.Getenv("AWS_CONFIG_FILE")
2021-02-07 01:55:09 -08:00
if configPath == "" {
configPath = fmt.Sprintf("%s/.aws/config", a.env.Home())
2021-02-07 01:55:09 -08:00
}
config := a.env.FileContent(configPath)
2021-02-07 01:55:09 -08:00
configSection := "[default]"
if a.Profile != "" {
configSection = fmt.Sprintf("[profile %s]", a.Profile)
}
configLines := strings.Split(config, "\n")
var sectionActive bool
for _, line := range configLines {
if strings.HasPrefix(line, configSection) {
sectionActive = true
continue
}
if sectionActive && strings.HasPrefix(line, "region") {
2021-12-18 10:30:31 -08:00
splitted := strings.Split(line, "=")
if len(splitted) >= 2 {
a.Region = strings.TrimSpace(splitted[1])
break
}
2021-02-07 01:55:09 -08:00
}
}
if a.Profile == "" && a.Region != "" {
a.Profile = defaultUser
}
}