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

83 lines
1.7 KiB
Go
Raw Normal View History

2022-08-17 09:12:18 -07:00
package segments
import (
"errors"
"path"
"github.com/jandedobbeleer/oh-my-posh/src/platform"
"github.com/jandedobbeleer/oh-my-posh/src/properties"
2022-12-28 08:30:48 -08:00
2022-08-17 09:12:18 -07:00
"gopkg.in/ini.v1"
)
const (
GCPNOACTIVECONFIG = "NO ACTIVE CONFIG FOUND"
)
2022-08-17 09:12:18 -07:00
type Gcp struct {
props properties.Properties
2022-11-09 11:27:54 -08:00
env platform.Environment
2022-08-17 09:12:18 -07:00
Account string
Project string
Region string
}
func (g *Gcp) Template() string {
return " {{ .Project }} "
2022-08-17 09:12:18 -07:00
}
2022-11-09 11:27:54 -08:00
func (g *Gcp) Init(props properties.Properties, env platform.Environment) {
2022-08-17 09:12:18 -07:00
g.props = props
g.env = env
}
func (g *Gcp) Enabled() bool {
cfgDir := g.getConfigDirectory()
configFile, err := g.getActiveConfig(cfgDir)
if err != nil {
g.env.Error("Gcp.Enabled()", err)
return false
2022-08-17 09:12:18 -07:00
}
cfgpath := path.Join(cfgDir, "configurations", "config_"+configFile)
cfg := g.env.FileContent(cfgpath)
if len(cfg) == 0 {
g.env.Error("Gcp.Enabled()", errors.New("config file is empty"))
return false
}
2022-08-17 09:12:18 -07:00
data, err := ini.Load([]byte(cfg))
2022-08-17 09:12:18 -07:00
if err != nil {
g.env.Error("Gcp.Enabled()", err)
return false
2022-08-17 09:12:18 -07:00
}
g.Project = data.Section("core").Key("project").String()
g.Account = data.Section("core").Key("account").String()
g.Region = data.Section("compute").Key("region").String()
2022-08-17 09:12:18 -07:00
return true
}
func (g *Gcp) getActiveConfig(cfgDir string) (string, error) {
ap := path.Join(cfgDir, "active_config")
fileContent := g.env.FileContent(ap)
2022-08-17 09:12:18 -07:00
if len(fileContent) == 0 {
return "", errors.New(GCPNOACTIVECONFIG)
2022-08-17 09:12:18 -07:00
}
return fileContent, nil
}
func (g *Gcp) getConfigDirectory() string {
cfgDir := g.env.Getenv("CLOUDSDK_CONFIG")
if len(cfgDir) != 0 {
return cfgDir
2022-08-17 09:12:18 -07:00
}
2022-11-09 11:27:54 -08:00
if g.env.GOOS() == platform.WINDOWS {
return path.Join(g.env.Getenv("APPDATA"), "gcloud")
}
return path.Join(g.env.Home(), ".config", "gcloud")
2022-08-17 09:12:18 -07:00
}