From a59238e39372a68cc704a9a63f1d6df3acb22ded Mon Sep 17 00:00:00 2001 From: Patrick Joyce Date: Thu, 27 Jun 2024 20:15:04 -0400 Subject: [PATCH] use ini pkg, rm regex trim --- go.mod | 1 + go.sum | 2 ++ src/utils/aws.go | 45 +++++++++++++++++---------------------------- 3 files changed, 20 insertions(+), 28 deletions(-) diff --git a/go.mod b/go.mod index 406fd67..8251494 100644 --- a/go.mod +++ b/go.mod @@ -12,4 +12,5 @@ require ( github.com/inconshreveable/mousetrap v1.1.0 // indirect github.com/spf13/pflag v1.0.5 // indirect golang.org/x/sys v0.12.0 // indirect + gopkg.in/ini.v1 v1.67.0 // indirect ) diff --git a/go.sum b/go.sum index 62134d5..e5e4e2c 100644 --- a/go.sum +++ b/go.sum @@ -28,4 +28,6 @@ golang.org/x/sys v0.0.0-20220310020820-b874c991c1a5/go.mod h1:oPkhp1MJrh7nUepCBc golang.org/x/sys v0.12.0 h1:CM0HF96J0hcLAwsHPJZjfdNzs0gftsLfgKt57wWHJ0o= golang.org/x/sys v0.12.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/ini.v1 v1.67.0 h1:Dgnx+6+nfE+IfzjUEISNeydPJh9AXNNsWbGP9KzCsOA= +gopkg.in/ini.v1 v1.67.0/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/src/utils/aws.go b/src/utils/aws.go index b30c320..d8e7087 100644 --- a/src/utils/aws.go +++ b/src/utils/aws.go @@ -1,44 +1,33 @@ package utils import ( - "bufio" + "gopkg.in/ini.v1" "log" - "os" - "regexp" "sort" + "strings" +) + +const ( + profilePrefix = "profile" + defaultProfile = "default" ) func GetProfiles() []string { profileFileLocation := GetCurrentProfileFile() - profiles := make([]string, 0) - - file, err := os.Open(profileFileLocation) + cfg, err := ini.Load(profileFileLocation) if err != nil { - log.Fatal(err) + log.Fatalf("Failed to load profiles: %v", err) } - defer file.Close() - - scanner := bufio.NewScanner(file) - r, err := regexp.Compile(`\[profile .*]`) - - if err != nil { - log.Fatal(err) - } - - for scanner.Scan() { - if r.MatchString(scanner.Text()) { - s := scanner.Text() - reg := regexp.MustCompile(`(\[profile )|(])`) - res := reg.ReplaceAllString(s, "") - profiles = append(profiles, res) + sections := cfg.SectionStrings() + profiles := make([]string, 0, len(sections)+1) + for _, section := range sections { + if strings.HasPrefix(section, profilePrefix) { + trimmedProfile := strings.TrimPrefix(section, profilePrefix) + trimmedProfile = strings.TrimSpace(trimmedProfile) + profiles = append(profiles, trimmedProfile) } } - - if err := scanner.Err(); err != nil { - log.Fatal(err) - } - - profiles = AppendIfNotExists(profiles, "default") + profiles = AppendIfNotExists(profiles, defaultProfile) sort.Strings(profiles) return profiles }