Skip to content

Commit

Permalink
Fix more golint errors
Browse files Browse the repository at this point in the history
 * add `lint` make target
 * fix workflow for golangci-lint
 * fix more golangci-lint errors

Refs: #124
  • Loading branch information
synfinatic committed Nov 13, 2021
1 parent 7ff25df commit 715c12a
Show file tree
Hide file tree
Showing 14 changed files with 48 additions and 56 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/golangci-lint.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ jobs:
uses: golangci/golangci-lint-action@v2
with:
# Optional: version of golangci-lint to use in form of v1.2 or v1.2.3 or `latest` to use the latest version
version: v2.5.2
version: v1.43.0

# Optional: working directory, useful for monorepos
# working-directory: somedir
Expand Down
4 changes: 3 additions & 1 deletion Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -171,8 +171,10 @@ test-tidy: ## Test to make sure go.mod is tidy
exit -1 ; \
fi

precheck: test test-fmt test-tidy ## Run all tests that happen in a PR
precheck: test test-fmt test-tidy lint ## Run all tests that happen in a PR

lint:
golangci-lint run

# Build targets for our supported plaforms
windows: $(WINDOWS_BIN) ## Build 64bit x86 Windows binary
Expand Down
5 changes: 4 additions & 1 deletion cmd/console_cmd.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ import (
"strconv"

"github.com/c-bata/go-prompt"
log "github.com/sirupsen/logrus"
"github.com/synfinatic/aws-sso-cli/sso"
"github.com/synfinatic/aws-sso-cli/storage"
"github.com/synfinatic/aws-sso-cli/utils"
Expand Down Expand Up @@ -123,7 +124,9 @@ func (cc *ConsoleCmd) Run(ctx *RunContext) error {
// opens the AWS console or just prints the URL
func openConsole(ctx *RunContext, awssso *sso.AWSSSO, accountid int64, role, region string) error {
ctx.Settings.Cache.AddHistory(utils.MakeRoleARN(accountid, role), ctx.Settings.HistoryLimit)
ctx.Settings.Cache.Save(false)
if err := ctx.Settings.Cache.Save(false); err != nil {
log.WithError(err).Warnf("Unable to update cache")
}

creds := GetRoleCredentials(ctx, awssso, accountid, role)

Expand Down
16 changes: 9 additions & 7 deletions cmd/exec_cmd.go
Original file line number Diff line number Diff line change
Expand Up @@ -108,11 +108,9 @@ const (
)

func emptyString(str string) bool {
if str == "" {
return true
}
return false
return str == ""
}

func firstItem(items []string) string {
for _, v := range items {
if v != "" {
Expand All @@ -129,7 +127,9 @@ func accountIdToStr(id int64) string {
// Executes Cmd+Args in the context of the AWS Role creds
func execCmd(ctx *RunContext, awssso *sso.AWSSSO, accountid int64, role, region string) error {
ctx.Settings.Cache.AddHistory(utils.MakeRoleARN(accountid, role), ctx.Settings.HistoryLimit)
ctx.Settings.Cache.Save(false)
if err := ctx.Settings.Cache.Save(false); err != nil {
log.WithError(err).Warnf("Unable to update cache")
}

// ready our command and connect everything up
cmd := exec.Command(ctx.Cli.Exec.Cmd, ctx.Cli.Exec.Args...)
Expand Down Expand Up @@ -191,7 +191,9 @@ func execShellEnvs(ctx *RunContext, awssso *sso.AWSSSO, accountid int64, role, r
buf := new(bytes.Buffer)
log.Tracef("RoleInfo: %s", spew.Sdump(roleInfo))
log.Tracef("Template: %s", spew.Sdump(templ))
templ.Execute(buf, roleInfo)
if err := templ.Execute(buf, roleInfo); err != nil {
log.WithError(err).Errorf("Unable to generate AWS_SSO_PROFILE")
}
shellVars["AWS_SSO_PROFILE"] = buf.String()
}

Expand All @@ -202,7 +204,7 @@ func execShellEnvs(ctx *RunContext, awssso *sso.AWSSSO, accountid int64, role, r
func checkAwsEnvironment() error {
checkVars := []string{"AWS_ACCESS_KEY_ID", "AWS_SECRET_ACCESS_KEY", "AWS_PROFILE"}
for _, envVar := range checkVars {
if _, exist := os.LookupEnv(envVar); exist == true {
if _, ok := os.LookupEnv(envVar); ok {
return fmt.Errorf("Conflicting environment variable '%s' is set", envVar)
}
}
Expand Down
8 changes: 6 additions & 2 deletions cmd/list_cmd.go
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,9 @@ func printRoles(ctx *RunContext, fields []string) {
}
}

gotable.GenerateTable(tr, fields)
if err := gotable.GenerateTable(tr, fields); err != nil {
log.WithError(err).Fatalf("Unable to generate report")
}
fmt.Printf("\n")
}

Expand Down Expand Up @@ -146,6 +148,8 @@ func listAllFields() {
}

fields := []string{"Field", "Description"}
gotable.GenerateTable(ts, fields)
if err := gotable.GenerateTable(ts, fields); err != nil {
log.WithError(err).Fatalf("Unable to generate report")
}
fmt.Printf("\n")
}
4 changes: 3 additions & 1 deletion cmd/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -258,6 +258,8 @@ func doAuth(ctx *RunContext) *sso.AWSSSO {
if err != nil {
log.WithError(err).Fatalf("Unable to authenticate")
}
ctx.Settings.Cache.Refresh(AwsSSO, s)
if err := ctx.Settings.Cache.Refresh(AwsSSO, s); err != nil {
log.WithError(err).Fatalf("Unable to refresh cache")
}
return AwsSSO
}
1 change: 0 additions & 1 deletion cmd/select.go
Original file line number Diff line number Diff line change
Expand Up @@ -112,7 +112,6 @@ func (tc *TagsCompleter) Executor(args string) {
if err != nil {
log.Fatalf("Unable to exec: %s", err.Error())
}
return
}

// completeExitChecker implements prompt.ExitChecker
Expand Down
13 changes: 6 additions & 7 deletions sso/cache.go
Original file line number Diff line number Diff line change
Expand Up @@ -52,15 +52,17 @@ func OpenCache(f string, s *Settings) (*Cache, error) {
Accounts: map[int64]*AWSAccount{},
},
}
var err error
var cacheBytes []byte
if f != "" {
cacheBytes, err := ioutil.ReadFile(f)
cacheBytes, err = ioutil.ReadFile(f)
if err != nil {
log.WithError(err).Errorf("Unable to open CacheStore: %s", f)
return &cache, nil // return empty struct
}
json.Unmarshal(cacheBytes, &cache)
err = json.Unmarshal(cacheBytes, &cache)
}
return &cache, nil
return &cache, err
}

// Expired returns if our Roles cache data is too old.
Expand Down Expand Up @@ -555,10 +557,7 @@ func (r *AWSRoleFlat) IsExpired() bool {
return true
}
d := time.Until(time.Unix(r.Expires, 0))
if d <= 0 {
return true
}
return false
return d <= 0
}

// ExpiresIn returns how long until this role expires as a string
Expand Down
17 changes: 0 additions & 17 deletions sso/role_tags.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,7 @@ package sso
*/

import (
"fmt"
"sort"
"strings"
)

// RoleTags provides an interface to find roles which match a set of tags
Expand Down Expand Up @@ -123,18 +121,3 @@ func (r *RoleTags) UsefulTags(tags map[string]string) []string {
func (r *RoleTags) GetMatchCount(tags map[string]string) int {
return len(r.GetMatchingRoles(tags))
}

// takes a role ARN and returns the accountid & rolename
func getAccountRole(arn string) (string, string, error) {
s := strings.Split(arn, ":")
if len(s) != 5 {
return "", "", fmt.Errorf("Invalid Role ARN: %s", arn)
}
account := s[3]
s = strings.Split(arn, "/")
if len(s) != 2 {
return "", "", fmt.Errorf("Invalid Role ARN: %s", arn)
}
role := s[1]
return account, role, nil
}
1 change: 1 addition & 0 deletions sso/role_tags_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,7 @@ func (suite *RoleTagsTestSuite) TestGetMatchCount() {

func (suite *RoleTagsTestSuite) TestGetRoleTags() {
t := suite.T()

f := (*suite).File
for testName, test := range *f.GetRoleTags {
ret := test.RoleTags.GetRoleTags(test.Query)
Expand Down
10 changes: 8 additions & 2 deletions sso/settings.go
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,6 @@ type Settings struct {
LogLevel string `koanf:"LogLevel" yaml:"LogLevel,omitempty"`
LogLines bool `koanf:"LogLines" yaml:"LogLines,omitempty"`
HistoryLimit int `koanf:"HistoryLimit" yaml:"HistoryLimit,omitempty"`
ssoName string // SSO name passed in via CLI
ListFields []string `koanf:"ListFields" yaml:"ListFields,omitempty"`
}

Expand Down Expand Up @@ -124,7 +123,9 @@ func LoadSettings(configFile, cacheFile string, defaults map[string]interface{},

// default values. Can be overridden using:
// https://pkg.go.dev/github.com/c-bata/go-prompt?utm_source=godoc#Color
konf.Load(confmap.Provider(defaults, "."), nil)
if err := konf.Load(confmap.Provider(defaults, "."), nil); err != nil {
return s, fmt.Errorf("Unable to load default settings: %s", err.Error())
}

if err := konf.Load(file.Provider(configFile), yaml.Parser()); err != nil {
return s, fmt.Errorf("Unable to open config file %s: %s", configFile, err.Error())
Expand Down Expand Up @@ -250,6 +251,7 @@ func (s *Settings) GetSelectedSSO(name string) (*SSOConfig, error) {
// to update the Role -> Account references
func (c *SSOConfig) Refresh(s *Settings) {
for accountId, a := range c.Accounts {
a.SetParentConfig(c)
for roleName, r := range a.Roles {
r.SetParentAccount(a)
r.ARN = utils.MakeRoleARN(accountId, roleName)
Expand Down Expand Up @@ -353,6 +355,10 @@ func (r *SSORole) SetParentAccount(a *SSOAccount) {
r.account = a
}

func (a *SSOAccount) SetParentConfig(c *SSOConfig) {
a.config = c
}

// GetAllTags returns all of the user defined and calculated tags for this role
func (r *SSORole) GetAllTags() map[string]string {
tags := map[string]string{}
Expand Down
4 changes: 2 additions & 2 deletions sso/tags_list.go
Original file line number Diff line number Diff line change
Expand Up @@ -91,15 +91,15 @@ func (t *TagsList) UniqueKeys(picked []string) []string {
keys = append(keys, key)
}
}
sort.Sort(sort.StringSlice(keys))
sort.Strings(keys)
return keys
}

// Returns a sorted unique list of tag values for the given key
func (t *TagsList) UniqueValues(key string) []string {
x := *t
if values, ok := x[key]; ok {
sort.Sort(sort.StringSlice(values))
sort.Strings(values)
return values
}

Expand Down
4 changes: 2 additions & 2 deletions storage/json_store.go
Original file line number Diff line number Diff line change
Expand Up @@ -51,10 +51,10 @@ func OpenJsonStore(fileName string) (*JsonStore, error) {
if err != nil {
log.Warnf("Creating new cache file: %s", fileName)
} else {
json.Unmarshal(cacheBytes, &cache)
err = json.Unmarshal(cacheBytes, &cache)
}

return &cache, nil
return &cache, err
}

// save writes the JSON store file, creating the directory if necessary
Expand Down
15 changes: 3 additions & 12 deletions storage/storage.go
Original file line number Diff line number Diff line change
Expand Up @@ -36,10 +36,7 @@ type RegisterClientData struct {

func (r *RegisterClientData) Expired() bool {
// XXX: I think an hour buffer here is fine?
if r.ClientSecretExpiresAt > time.Now().Add(time.Hour).Unix() {
return false
}
return true
return r.ClientSecretExpiresAt <= time.Now().Add(time.Hour).Unix()
}

type StartDeviceAuthData struct {
Expand All @@ -62,10 +59,7 @@ type CreateTokenResponse struct {

func (t *CreateTokenResponse) Expired() bool {
// XXX: I think an minute buffer here is fine?
if t.ExpiresAt > time.Now().Add(time.Minute).Unix() {
return false
}
return true
return t.ExpiresAt <= time.Now().Add(time.Minute).Unix()
}

type RoleCredentials struct { // Cache
Expand Down Expand Up @@ -93,10 +87,7 @@ func (r *RoleCredentials) ExpireString() string {

func (r *RoleCredentials) IsExpired() bool {
now := time.Now().Add(time.Minute).Unix()
if r.Expiration/1000 > now {
return false
}
return true
return r.Expiration/1000 <= now
}

// AccountIdStr returns our AccountId as a string
Expand Down

0 comments on commit 715c12a

Please sign in to comment.