From 77bd3449e6a96820a141c88b1494e3eefefa13c1 Mon Sep 17 00:00:00 2001 From: Nicolas Zin Date: Fri, 25 Aug 2023 20:49:35 -0400 Subject: [PATCH] addressing linter comments --- Makefile | 14 ++--- internal/entity/entity_ruleset.go | 4 +- internal/entity/repository.go | 6 +- internal/entity/team.go | 4 +- internal/entity/user.go | 2 +- internal/entity/user_test.go | 4 +- internal/entity/utils.go | 4 +- internal/github/client.go | 8 +-- internal/goliac.go | 12 ++-- internal/goliac_server.go | 8 +-- internal/scaffold.go | 2 +- internal/sync/githubsaml.go | 3 + internal/sync/goliac_reconciliator.go | 56 ++++++++++--------- internal/sync/local.go | 21 +++++-- internal/sync/local_test.go | 6 +- internal/sync/remote.go | 32 ++++++++--- internal/sync/remote_test.go | 4 +- .../cmd/goliac-server/main.go | 4 +- .../models/error.go | 0 .../models/health.go | 0 .../restapi/configure_goliac.go | 2 +- .../restapi/doc.go | 0 .../restapi/embedded_spec.go | 0 .../restapi/operations/goliac_api.go | 2 +- .../restapi/operations/health/get_liveness.go | 0 .../health/get_liveness_parameters.go | 0 .../health/get_liveness_responses.go | 2 +- .../health/get_liveness_urlbuilder.go | 0 .../operations/health/get_readiness.go | 0 .../health/get_readiness_parameters.go | 0 .../health/get_readiness_responses.go | 2 +- .../health/get_readiness_urlbuilder.go | 0 .../restapi/server.go | 2 +- 33 files changed, 120 insertions(+), 84 deletions(-) rename {internal/swagger_gen => swagger_gen}/cmd/goliac-server/main.go (90%) rename {internal/swagger_gen => swagger_gen}/models/error.go (100%) rename {internal/swagger_gen => swagger_gen}/models/health.go (100%) rename {internal/swagger_gen => swagger_gen}/restapi/configure_goliac.go (97%) rename {internal/swagger_gen => swagger_gen}/restapi/doc.go (100%) rename {internal/swagger_gen => swagger_gen}/restapi/embedded_spec.go (100%) rename {internal/swagger_gen => swagger_gen}/restapi/operations/goliac_api.go (99%) rename {internal/swagger_gen => swagger_gen}/restapi/operations/health/get_liveness.go (100%) rename {internal/swagger_gen => swagger_gen}/restapi/operations/health/get_liveness_parameters.go (100%) rename {internal/swagger_gen => swagger_gen}/restapi/operations/health/get_liveness_responses.go (97%) rename {internal/swagger_gen => swagger_gen}/restapi/operations/health/get_liveness_urlbuilder.go (100%) rename {internal/swagger_gen => swagger_gen}/restapi/operations/health/get_readiness.go (100%) rename {internal/swagger_gen => swagger_gen}/restapi/operations/health/get_readiness_parameters.go (100%) rename {internal/swagger_gen => swagger_gen}/restapi/operations/health/get_readiness_responses.go (97%) rename {internal/swagger_gen => swagger_gen}/restapi/operations/health/get_readiness_urlbuilder.go (100%) rename {internal/swagger_gen => swagger_gen}/restapi/server.go (99%) diff --git a/Makefile b/Makefile index d399a43..89615fd 100644 --- a/Makefile +++ b/Makefile @@ -6,7 +6,7 @@ rebuild: gen build build: @GO111MODULE=on go build -o goliac ./cmd/goliac -test: +test: verifiers @GO111MODULE=on go test -race -covermode=atomic -coverprofile=coverage.txt ./internal/... @go tool cover -html coverage.txt -o cover.html @@ -28,7 +28,7 @@ verifiers: verify_lint verify_swagger verify_lint: @echo "Running $@" - @golangci-lint run -D errcheck ./pkg/... + @golangci-lint run -D errcheck ./internal/... verify_swagger: @echo "Running $@" @@ -37,8 +37,8 @@ verify_swagger: swagger: verify_swagger @echo "Regenerate swagger files" @rm -f /tmp/configure_goliac.go - @cp ./internal/swagger_gen/restapi/configure_goliac.go /tmp/configure_goliac.go 2>/dev/null || : - @rm -rf ./internal/swagger_gen - @mkdir ./internal/swagger_gen - @swagger generate server -t ./internal/swagger_gen -f ./docs/api_docs/bundle.yaml - @cp /tmp/configure_goliac.go ./internal/swagger_gen/restapi/configure_goliac.go 2>/dev/null || : + @cp ./swagger_gen/restapi/configure_goliac.go /tmp/configure_goliac.go 2>/dev/null || : + @rm -rf ./swagger_gen + @mkdir ./swagger_gen + @swagger generate server -t ./swagger_gen -f ./docs/api_docs/bundle.yaml + @cp /tmp/configure_goliac.go ./swagger_gen/restapi/configure_goliac.go 2>/dev/null || : diff --git a/internal/entity/entity_ruleset.go b/internal/entity/entity_ruleset.go index 0e218fb..1890c4f 100644 --- a/internal/entity/entity_ruleset.go +++ b/internal/entity/entity_ruleset.go @@ -43,7 +43,7 @@ func CompareRulesetParameters(ruletype string, left RuleSetParameters, right Rul } return true case "required_status_checks": - if res, _, _ := StringArrayEquivalent(left.RequiredStatusChecks, right.RequiredStatusChecks); res == false { + if res, _, _ := StringArrayEquivalent(left.RequiredStatusChecks, right.RequiredStatusChecks); !res { return false } if left.StrictRequiredStatusChecksPolicy != right.StrictRequiredStatusChecksPolicy { @@ -111,7 +111,7 @@ func ReadRuleSetDirectory(fs afero.Fs, dirname string) (map[string]*RuleSet, []e errors = append(errors, err) return rulesets, errors, warning } - if exist == false { + if !exist { return rulesets, errors, warning } diff --git a/internal/entity/repository.go b/internal/entity/repository.go index 153bc03..00c48fa 100644 --- a/internal/entity/repository.go +++ b/internal/entity/repository.go @@ -59,7 +59,7 @@ func ReadRepositories(fs afero.Fs, archivedDirname string, teamDirname string, t errors = append(errors, err) return repos, errors, warning } - if exist == true { + if exist { entries, err := afero.ReadDir(fs, archivedDirname) if err != nil { errors = append(errors, err) @@ -91,7 +91,7 @@ func ReadRepositories(fs afero.Fs, archivedDirname string, teamDirname string, t errors = append(errors, err) return repos, errors, warning } - if exist == false { + if !exist { return repos, errors, warning } @@ -174,7 +174,7 @@ func (r *Repository) Validate(filename string, teams map[string]*Team, externalU } if archived != r.Data.IsArchived { - if archived == true { + if archived { return fmt.Errorf("invalid archived: %s is in the archived directory without the `archived` boolean", filename) } else { return fmt.Errorf("invalid archived: %s has `archived` set to true, but isn't in the archived directory", filename) diff --git a/internal/entity/team.go b/internal/entity/team.go index c766bcc..c56de48 100644 --- a/internal/entity/team.go +++ b/internal/entity/team.go @@ -52,7 +52,7 @@ func ReadTeamDirectory(fs afero.Fs, dirname string, users map[string]*User) (map errors = append(errors, err) return teams, errors, warning } - if exist == false { + if !exist { return teams, errors, warning } @@ -146,7 +146,7 @@ func ReadAndAdjustTeamDirectory(fs afero.Fs, dirname string, users map[string]*U if err != nil { return teamschanged, err } - if exist == false { + if !exist { return teamschanged, nil } diff --git a/internal/entity/user.go b/internal/entity/user.go index 759189a..dcf464a 100644 --- a/internal/entity/user.go +++ b/internal/entity/user.go @@ -51,7 +51,7 @@ func ReadUserDirectory(fs afero.Fs, dirname string) (map[string]*User, []error, errors = append(errors, err) return users, errors, warning } - if exist == false { + if !exist { return users, errors, warning } diff --git a/internal/entity/user_test.go b/internal/entity/user_test.go index f34010a..726142d 100644 --- a/internal/entity/user_test.go +++ b/internal/entity/user_test.go @@ -44,7 +44,7 @@ metadata: name: user1 data: githubID: github1 -`), 644) +`), 0644) assert.Nil(t, err) users, errs, warns := ReadUserDirectory(fs, "users") assert.Equal(t, len(errs), 0) @@ -73,7 +73,7 @@ apiVersion: v1 kind: User data: githubID: github1 -`), 644) +`), 0644) assert.Nil(t, err) _, errs, warns := ReadUserDirectory(fs, "users") assert.Equal(t, len(errs), 1) diff --git a/internal/entity/utils.go b/internal/entity/utils.go index 69432ef..a4e5b10 100644 --- a/internal/entity/utils.go +++ b/internal/entity/utils.go @@ -26,13 +26,13 @@ func StringArrayEquivalent(a, b []string) (bool, []string, []string) { result = false } - for r, _ := range rights { + for r := range rights { if _, ok := lefts[r]; !ok { leftOnly = append(leftOnly, r) result = false } } - for l, _ := range lefts { + for l := range lefts { if _, ok := rights[l]; !ok { rightOnly = append(rightOnly, l) result = false diff --git a/internal/github/client.go b/internal/github/client.go index d088710..99607ba 100644 --- a/internal/github/client.go +++ b/internal/github/client.go @@ -5,9 +5,9 @@ import ( "encoding/json" "fmt" "io" - "io/ioutil" "net/http" "net/url" + "os" "strconv" "sync" "time" @@ -82,7 +82,7 @@ func (t *AuthorizedTransport) RoundTrip(req *http.Request) (*http.Response, erro * ) */ func NewGitHubClientImpl(githubServer, organizationName string, appID int, privateKeyFile string) (GitHubClient, error) { - privateKey, err := ioutil.ReadFile(privateKeyFile) + privateKey, err := os.ReadFile(privateKeyFile) if err != nil { return nil, err } @@ -212,7 +212,7 @@ func (client *GitHubClientImpl) QueryGraphQLAPI(query string, variables map[stri // Retry the request. return client.QueryGraphQLAPI(query, variables) } else { - responseBody, err := ioutil.ReadAll(resp.Body) + responseBody, err := io.ReadAll(resp.Body) if err != nil { return nil, err } @@ -269,7 +269,7 @@ func (client *GitHubClientImpl) CallRestAPI(endpoint, method string, body map[st // Retry the request. return client.CallRestAPI(endpoint, method, body) } else { - responseBody, err := ioutil.ReadAll(resp.Body) + responseBody, err := io.ReadAll(resp.Body) if err != nil { return nil, err } diff --git a/internal/goliac.go b/internal/goliac.go index 0b16bbe..425f5f1 100644 --- a/internal/goliac.go +++ b/internal/goliac.go @@ -4,7 +4,6 @@ import ( "context" "fmt" "strings" - gosync "sync" "github.com/Alayacare/goliac/internal/config" "github.com/Alayacare/goliac/internal/entity" @@ -42,7 +41,6 @@ type GoliacImpl struct { remote sync.GoliacRemoteExecutor githubClient github.GitHubClient repoconfig *config.RepositoryConfig - applyMutex gosync.Mutex } func NewGoliacImpl() (Goliac, error) { @@ -70,8 +68,8 @@ func NewGoliacImpl() (Goliac, error) { } func (g *GoliacImpl) LoadAndValidateGoliacOrganization(repositoryUrl, branch string) error { - errs := []error{} - warns := []entity.Warning{} + var errs []error + var warns []entity.Warning if strings.HasPrefix(repositoryUrl, "https://") || strings.HasPrefix(repositoryUrl, "git@") { accessToken, err := g.githubClient.GetAccessToken() if err != nil { @@ -98,7 +96,7 @@ func (g *GoliacImpl) LoadAndValidateGoliacOrganization(repositoryUrl, branch str for _, warn := range warns { logrus.Warn(warn) } - if errs != nil && len(errs) != 0 { + if len(errs) != 0 { for _, err := range errs { logrus.Error(err) } @@ -130,7 +128,7 @@ func (g *GoliacImpl) ApplyToGithub(dryrun bool, teamreponame string, branch stri ga := NewGithubBatchExecutor(g.remote, g.repoconfig.MaxChangesets) reconciliator := sync.NewGoliacReconciliatorImpl(ga, g.repoconfig) - ctx := context.WithValue(context.TODO(), "author", commit.Author.Email) + ctx := context.WithValue(context.TODO(), sync.KeyAuthor, commit.Author.Email) err = reconciliator.Reconciliate(ctx, g.local, g.remote, teamreponame, dryrun) if err != nil { return fmt.Errorf("Error when reconciliating: %v", err) @@ -175,7 +173,7 @@ func (g *GoliacImpl) UsersUpdate(repositoryUrl, branch string) error { } userplugin, found := sync.GetUserSyncPlugin(g.repoconfig.UserSync.Plugin) - if found == false { + if !found { return fmt.Errorf("User Sync Plugin %s not found", g.repoconfig.UserSync.Plugin) } diff --git a/internal/goliac_server.go b/internal/goliac_server.go index 0a87f33..7bcf293 100644 --- a/internal/goliac_server.go +++ b/internal/goliac_server.go @@ -13,10 +13,10 @@ import ( "time" "github.com/Alayacare/goliac/internal/config" - "github.com/Alayacare/goliac/internal/swagger_gen/models" - "github.com/Alayacare/goliac/internal/swagger_gen/restapi" - "github.com/Alayacare/goliac/internal/swagger_gen/restapi/operations" - "github.com/Alayacare/goliac/internal/swagger_gen/restapi/operations/health" + "github.com/Alayacare/goliac/swagger_gen/models" + "github.com/Alayacare/goliac/swagger_gen/restapi" + "github.com/Alayacare/goliac/swagger_gen/restapi/operations" + "github.com/Alayacare/goliac/swagger_gen/restapi/operations/health" "github.com/go-openapi/loads" "github.com/go-openapi/runtime/middleware" "github.com/sirupsen/logrus" diff --git a/internal/scaffold.go b/internal/scaffold.go index 752bd78..e7e8faf 100644 --- a/internal/scaffold.go +++ b/internal/scaffold.go @@ -241,7 +241,7 @@ func (s *Scaffold) generateUsers(fs afero.Fs, userspath string) (map[string]stri } } else { // fail back on github id - for githubid, _ := range s.remote.Users() { + for githubid := range s.remote.Users() { usermap[githubid] = githubid user := entity.User{} user.ApiVersion = "v1" diff --git a/internal/sync/githubsaml.go b/internal/sync/githubsaml.go index 74cfb12..01e8423 100644 --- a/internal/sync/githubsaml.go +++ b/internal/sync/githubsaml.go @@ -87,6 +87,9 @@ func LoadUsersFromGithubOrgSaml(client github.GitHubClient) (map[string]*entity. count := 0 for hasNextPage { data, err := client.QueryGraphQLAPI(listUsersFromGithubOrgSaml, variables) + if err != nil { + return users, err + } var gResult GraplQLUsersFromGithubOrgSaml // parse first page diff --git a/internal/sync/goliac_reconciliator.go b/internal/sync/goliac_reconciliator.go index 8c6fd04..f254e01 100644 --- a/internal/sync/goliac_reconciliator.go +++ b/internal/sync/goliac_reconciliator.go @@ -12,6 +12,12 @@ import ( "github.com/sirupsen/logrus" ) +type key string + +const ( + KeyAuthor key = "author" +) + /* * GoliacReconciliator is here to sync the local state to the remote state */ @@ -135,7 +141,7 @@ func (r *GoliacReconciliatorImpl) reconciliateTeams(ctx context.Context, local G Slug: "everyone", Members: []string{}, } - for u, _ := range local.Users() { + for u := range local.Users() { everyone.Members = append(everyone.Members, u) } slugTeams["everyone"] = &everyone @@ -271,11 +277,11 @@ func (r *GoliacReconciliatorImpl) reconciliateRepositories(ctx context.Context, return false } - if res, _, _ := entity.StringArrayEquivalent(lRepo.Readers, rRepo.Readers); res == false { + if res, _, _ := entity.StringArrayEquivalent(lRepo.Readers, rRepo.Readers); !res { return false } - if res, _, _ := entity.StringArrayEquivalent(lRepo.Writers, rRepo.Writers); res == false { + if res, _, _ := entity.StringArrayEquivalent(lRepo.Writers, rRepo.Writers); !res { return false } return true @@ -303,7 +309,7 @@ func (r *GoliacReconciliatorImpl) reconciliateRepositories(ctx context.Context, r.UpdateRepositoryUpdateArchived(ctx, dryrun, remote, reponame, lRepo.IsArchived) } - if res, readToRemove, readToAdd := entity.StringArrayEquivalent(lRepo.Readers, rRepo.Readers); res == false { + if res, readToRemove, readToAdd := entity.StringArrayEquivalent(lRepo.Readers, rRepo.Readers); !res { for _, teamSlug := range readToAdd { r.UpdateRepositoryAddTeamAccess(ctx, dryrun, remote, reponame, teamSlug, "pull") } @@ -312,7 +318,7 @@ func (r *GoliacReconciliatorImpl) reconciliateRepositories(ctx context.Context, } } - if res, writeToRemove, writeToAdd := entity.StringArrayEquivalent(lRepo.Writers, rRepo.Writers); res == false { + if res, writeToRemove, writeToAdd := entity.StringArrayEquivalent(lRepo.Writers, rRepo.Writers); !res { for _, teamSlug := range writeToAdd { r.UpdateRepositoryAddTeamAccess(ctx, dryrun, remote, reponame, teamSlug, "push") } @@ -382,21 +388,21 @@ func (r *GoliacReconciliatorImpl) reconciliateRulesets(ctx context.Context, loca return false } } - if res, _, _ := entity.StringArrayEquivalent(lrs.OnInclude, rrs.OnInclude); res == false { + if res, _, _ := entity.StringArrayEquivalent(lrs.OnInclude, rrs.OnInclude); !res { return false } - if res, _, _ := entity.StringArrayEquivalent(lrs.OnExclude, rrs.OnExclude); res == false { + if res, _, _ := entity.StringArrayEquivalent(lrs.OnExclude, rrs.OnExclude); !res { return false } if len(lrs.Rules) != len(rrs.Rules) { return false } for k, v := range lrs.Rules { - if entity.CompareRulesetParameters(k, v, rrs.Rules[k]) == false { + if !entity.CompareRulesetParameters(k, v, rrs.Rules[k]) { return false } } - if res, _, _ := entity.StringArrayEquivalent(lrs.Repositories, rrs.Repositories); res == false { + if res, _, _ := entity.StringArrayEquivalent(lrs.Repositories, rrs.Repositories); !res { return false } @@ -427,7 +433,7 @@ func (r *GoliacReconciliatorImpl) reconciliateRulesets(ctx context.Context, loca func (r *GoliacReconciliatorImpl) AddUserToOrg(ctx context.Context, dryrun bool, remote *MutableGoliacRemoteImpl, ghuserid string) { author := "unknown" - if a := ctx.Value("author"); a != nil { + if a := ctx.Value(KeyAuthor); a != nil { author = a.(string) } logrus.WithFields(map[string]interface{}{"dryrun": dryrun, "author": author, "command": "add_user_to_org"}).Infof("ghusername: %s", ghuserid) @@ -441,7 +447,7 @@ func (r *GoliacReconciliatorImpl) AddUserToOrg(ctx context.Context, dryrun bool, func (r *GoliacReconciliatorImpl) RemoveUserFromOrg(ctx context.Context, dryrun bool, remote *MutableGoliacRemoteImpl, ghuserid string) { author := "unknown" - if a := ctx.Value("author"); a != nil { + if a := ctx.Value(KeyAuthor); a != nil { author = a.(string) } logrus.WithFields(map[string]interface{}{"dryrun": dryrun, "author": author, "command": "remove_user_from_org"}).Infof("ghusername: %s", ghuserid) @@ -457,7 +463,7 @@ func (r *GoliacReconciliatorImpl) RemoveUserFromOrg(ctx context.Context, dryrun func (r *GoliacReconciliatorImpl) CreateTeam(ctx context.Context, dryrun bool, remote *MutableGoliacRemoteImpl, teamname string, description string, members []string) { author := "unknown" - if a := ctx.Value("author"); a != nil { + if a := ctx.Value(KeyAuthor); a != nil { author = a.(string) } logrus.WithFields(map[string]interface{}{"dryrun": dryrun, "author": author, "command": "create_team"}).Infof("teamname: %s, members: %s", teamname, strings.Join(members, ",")) @@ -470,7 +476,7 @@ func (r *GoliacReconciliatorImpl) CreateTeam(ctx context.Context, dryrun bool, r } func (r *GoliacReconciliatorImpl) UpdateTeamAddMember(ctx context.Context, dryrun bool, remote *MutableGoliacRemoteImpl, teamslug string, username string, role string) { author := "unknown" - if a := ctx.Value("author"); a != nil { + if a := ctx.Value(KeyAuthor); a != nil { author = a.(string) } logrus.WithFields(map[string]interface{}{"dryrun": dryrun, "author": author, "command": "update_team_add_member"}).Infof("teamslug: %s, username: %s, role: %s", teamslug, username, role) @@ -483,7 +489,7 @@ func (r *GoliacReconciliatorImpl) UpdateTeamAddMember(ctx context.Context, dryru } func (r *GoliacReconciliatorImpl) UpdateTeamRemoveMember(ctx context.Context, dryrun bool, remote *MutableGoliacRemoteImpl, teamslug string, username string) { author := "unknown" - if a := ctx.Value("author"); a != nil { + if a := ctx.Value(KeyAuthor); a != nil { author = a.(string) } logrus.WithFields(map[string]interface{}{"dryrun": dryrun, "author": author, "command": "update_team_remove_member"}).Infof("teamslug: %s, username: %s", teamslug, username) @@ -496,7 +502,7 @@ func (r *GoliacReconciliatorImpl) UpdateTeamRemoveMember(ctx context.Context, dr } func (r *GoliacReconciliatorImpl) DeleteTeam(ctx context.Context, dryrun bool, remote *MutableGoliacRemoteImpl, teamslug string) { author := "unknown" - if a := ctx.Value("author"); a != nil { + if a := ctx.Value(KeyAuthor); a != nil { author = a.(string) } if r.repoconfig.DestructiveOperations.AllowDestructiveTeams { @@ -511,7 +517,7 @@ func (r *GoliacReconciliatorImpl) DeleteTeam(ctx context.Context, dryrun bool, r } func (r *GoliacReconciliatorImpl) CreateRepository(ctx context.Context, dryrun bool, remote *MutableGoliacRemoteImpl, reponame string, descrition string, writers []string, readers []string, public bool) { author := "unknown" - if a := ctx.Value("author"); a != nil { + if a := ctx.Value(KeyAuthor); a != nil { author = a.(string) } logrus.WithFields(map[string]interface{}{"dryrun": dryrun, "author": author, "command": "create_repository"}).Infof("repositoryname: %s, readers: %s, writers: %s, public: %v", reponame, strings.Join(readers, ","), strings.Join(writers, ","), public) @@ -524,7 +530,7 @@ func (r *GoliacReconciliatorImpl) CreateRepository(ctx context.Context, dryrun b } func (r *GoliacReconciliatorImpl) UpdateRepositoryAddTeamAccess(ctx context.Context, dryrun bool, remote *MutableGoliacRemoteImpl, reponame string, teamslug string, permission string) { author := "unknown" - if a := ctx.Value("author"); a != nil { + if a := ctx.Value(KeyAuthor); a != nil { author = a.(string) } logrus.WithFields(map[string]interface{}{"dryrun": dryrun, "author": author, "command": "update_repository_add_team"}).Infof("repositoryname: %s, teamslug: %s, permission: %s", reponame, teamslug, permission) @@ -538,7 +544,7 @@ func (r *GoliacReconciliatorImpl) UpdateRepositoryAddTeamAccess(ctx context.Cont func (r *GoliacReconciliatorImpl) UpdateRepositoryUpdateTeamAccess(ctx context.Context, dryrun bool, remote *MutableGoliacRemoteImpl, reponame string, teamslug string, permission string) { author := "unknown" - if a := ctx.Value("author"); a != nil { + if a := ctx.Value(KeyAuthor); a != nil { author = a.(string) } logrus.WithFields(map[string]interface{}{"dryrun": dryrun, "author": author, "command": "update_repository_update_team"}).Infof("repositoryname: %s, teamslug:%s, permission: %s", reponame, teamslug, permission) @@ -551,7 +557,7 @@ func (r *GoliacReconciliatorImpl) UpdateRepositoryUpdateTeamAccess(ctx context.C } func (r *GoliacReconciliatorImpl) UpdateRepositoryRemoveTeamAccess(ctx context.Context, dryrun bool, remote *MutableGoliacRemoteImpl, reponame string, teamslug string) { author := "unknown" - if a := ctx.Value("author"); a != nil { + if a := ctx.Value(KeyAuthor); a != nil { author = a.(string) } logrus.WithFields(map[string]interface{}{"dryrun": dryrun, "author": author, "command": "update_repository_remove_team"}).Infof("repositoryname: %s, teamslug:%s", reponame, teamslug) @@ -565,7 +571,7 @@ func (r *GoliacReconciliatorImpl) UpdateRepositoryRemoveTeamAccess(ctx context.C func (r *GoliacReconciliatorImpl) DeleteRepository(ctx context.Context, dryrun bool, remote *MutableGoliacRemoteImpl, reponame string) { author := "unknown" - if a := ctx.Value("author"); a != nil { + if a := ctx.Value(KeyAuthor); a != nil { author = a.(string) } if r.repoconfig.DestructiveOperations.AllowDestructiveRepositories { @@ -580,7 +586,7 @@ func (r *GoliacReconciliatorImpl) DeleteRepository(ctx context.Context, dryrun b } func (r *GoliacReconciliatorImpl) UpdateRepositoryUpdatePrivate(ctx context.Context, dryrun bool, remote *MutableGoliacRemoteImpl, reponame string, private bool) { author := "unknown" - if a := ctx.Value("author"); a != nil { + if a := ctx.Value(KeyAuthor); a != nil { author = a.(string) } logrus.WithFields(map[string]interface{}{"dryrun": dryrun, "author": author, "command": "update_repository_update_private"}).Infof("repositoryname: %s private:%v", reponame, private) @@ -593,7 +599,7 @@ func (r *GoliacReconciliatorImpl) UpdateRepositoryUpdatePrivate(ctx context.Cont } func (r *GoliacReconciliatorImpl) UpdateRepositoryUpdateArchived(ctx context.Context, dryrun bool, remote *MutableGoliacRemoteImpl, reponame string, archived bool) { author := "unknown" - if a := ctx.Value("author"); a != nil { + if a := ctx.Value(KeyAuthor); a != nil { author = a.(string) } logrus.WithFields(map[string]interface{}{"dryrun": dryrun, "author": author, "command": "update_repository_update_archived"}).Infof("repositoryname: %s archived:%v", reponame, archived) @@ -606,7 +612,7 @@ func (r *GoliacReconciliatorImpl) UpdateRepositoryUpdateArchived(ctx context.Con } func (r *GoliacReconciliatorImpl) AddRuleset(ctx context.Context, dryrun bool, ruleset *GithubRuleSet) { author := "unknown" - if a := ctx.Value("author"); a != nil { + if a := ctx.Value(KeyAuthor); a != nil { author = a.(string) } logrus.WithFields(map[string]interface{}{"dryrun": dryrun, "author": author, "command": "add_ruleset"}).Infof("ruleset: %s (id: %d) enforcement: %s", ruleset.Name, ruleset.Id, ruleset.Enforcement) @@ -618,7 +624,7 @@ func (r *GoliacReconciliatorImpl) AddRuleset(ctx context.Context, dryrun bool, r } func (r *GoliacReconciliatorImpl) UpdateRuleset(ctx context.Context, dryrun bool, ruleset *GithubRuleSet) { author := "unknown" - if a := ctx.Value("author"); a != nil { + if a := ctx.Value(KeyAuthor); a != nil { author = a.(string) } logrus.WithFields(map[string]interface{}{"dryrun": dryrun, "author": author, "command": "update_ruleset"}).Infof("ruleset: %s (id: %d) enforcement: %s", ruleset.Name, ruleset.Id, ruleset.Enforcement) @@ -630,7 +636,7 @@ func (r *GoliacReconciliatorImpl) UpdateRuleset(ctx context.Context, dryrun bool } func (r *GoliacReconciliatorImpl) DeleteRuleset(ctx context.Context, dryrun bool, rulesetid int) { author := "unknown" - if a := ctx.Value("author"); a != nil { + if a := ctx.Value(KeyAuthor); a != nil { author = a.(string) } if r.repoconfig.DestructiveOperations.AllowDestructiveRulesets { diff --git a/internal/sync/local.go b/internal/sync/local.go index 9b8589c..a71bff2 100644 --- a/internal/sync/local.go +++ b/internal/sync/local.go @@ -3,7 +3,7 @@ package sync import ( "errors" "fmt" - "io/ioutil" + "io" "os" "path" "path/filepath" @@ -103,7 +103,7 @@ func (g *GoliacLocalImpl) Clone(accesstoken, repositoryUrl, branch string) error g.Close() } // create a temp directory - tmpDir, err := ioutil.TempDir("", "goliac") + tmpDir, err := os.MkdirTemp("", "goliac") if err != nil { return err } @@ -258,9 +258,12 @@ func (g *GoliacLocalImpl) LoadRepoConfig() (error, *config.RepositoryConfig) { var repoconfig config.RepositoryConfig file, err := os.Open(path.Join(w.Filesystem.Root(), "goliac.yaml")) + if err != nil { + return fmt.Errorf("not able to open the /goliac.yaml configuration file: %v", err), nil + } defer file.Close() - content, err := ioutil.ReadAll(file) + content, err := io.ReadAll(file) if err != nil { return fmt.Errorf("not able to find the /goliac.yaml configuration file: %v", err), nil } @@ -280,7 +283,7 @@ func (g *GoliacLocalImpl) codeowners_regenerate(adminteam string) string { for _, t := range g.teams { teamsnames = append(teamsnames, t.Metadata.Name) } - sort.Sort(sort.StringSlice(teamsnames)) + sort.Strings(teamsnames) for _, t := range teamsnames { codeowners += fmt.Sprintf("/teams/%s/* @%s/%s-owners @%s/%s\n", t, config.Config.GithubAppOrganization, slugify.Make(t), config.Config.GithubAppOrganization, slugify.Make(adminteam)) @@ -313,9 +316,12 @@ func (g *GoliacLocalImpl) UpdateAndCommitCodeOwners(repoconfig *config.Repositor info, err := os.Stat(codeownerpath) if err == nil && !info.IsDir() { file, err := os.Open(codeownerpath) + if err != nil { + return fmt.Errorf("not able to open .github/CODEOWNERS file: %v", err) + } defer file.Close() - content, err = ioutil.ReadAll(file) + content, err = io.ReadAll(file) if err != nil { return fmt.Errorf("Not able to open .github/CODEOWNERS file: %v", err) } @@ -333,8 +339,11 @@ func (g *GoliacLocalImpl) UpdateAndCommitCodeOwners(repoconfig *config.Repositor // Get the HEAD reference headRef, err := g.repo.Head() + if err != nil { + return err + } - ioutil.WriteFile(path.Join(w.Filesystem.Root(), ".github", "CODEOWNERS"), []byte(newContent), 0644) + os.WriteFile(path.Join(w.Filesystem.Root(), ".github", "CODEOWNERS"), []byte(newContent), 0644) _, err = w.Add(path.Join(".github", "CODEOWNERS")) if err != nil { diff --git a/internal/sync/local_test.go b/internal/sync/local_test.go index 654915c..e8bb25c 100644 --- a/internal/sync/local_test.go +++ b/internal/sync/local_test.go @@ -2,7 +2,6 @@ package sync import ( "fmt" - "io/ioutil" "os" "path/filepath" "testing" @@ -25,6 +24,9 @@ func createBasicStructure(fs afero.Fs, path string) error { err = afero.WriteFile(fs, filepath.Join(path, "goliac.yaml"), []byte(` `), 0644) + if err != nil { + return err + } // Create users err = fs.MkdirAll(filepath.Join(path, "users/org"), 0755) if err != nil { @@ -102,7 +104,7 @@ func TestRepository(t *testing.T) { }) t.Run("happy path: local repository", func(t *testing.T) { - tmpDirectory, err := ioutil.TempDir("", "goliac") + tmpDirectory, err := os.MkdirTemp("", "goliac") assert.Nil(t, err) defer os.RemoveAll(tmpDirectory) diff --git a/internal/sync/remote.go b/internal/sync/remote.go index 40cae06..39d48c7 100644 --- a/internal/sync/remote.go +++ b/internal/sync/remote.go @@ -108,10 +108,12 @@ func (g *GoliacRemoteImpl) FlushCache() { func (g *GoliacRemoteImpl) RuleSets() map[string]*GithubRuleSet { if time.Now().After(g.ttlExpireRulesets) { err := g.Load() - rulesets, err := g.loadRulesets() if err == nil { - g.rulesets = rulesets - g.ttlExpireRulesets = time.Now().Add(time.Duration(config.Config.GithubCacheTTL)) + rulesets, err := g.loadRulesets() + if err == nil { + g.rulesets = rulesets + g.ttlExpireRulesets = time.Now().Add(time.Duration(config.Config.GithubCacheTTL)) + } } } return g.rulesets @@ -239,6 +241,9 @@ func (g *GoliacRemoteImpl) loadOrgUsers() (map[string]string, error) { count := 0 for hasNextPage { data, err := g.client.QueryGraphQLAPI(listAllOrgMembers, variables) + if err != nil { + return users, err + } var gResult GraplQLUsers // parse first page @@ -331,6 +336,9 @@ func (g *GoliacRemoteImpl) loadRepositories() (map[string]*GithubRepository, map count := 0 for hasNextPage { data, err := g.client.QueryGraphQLAPI(listAllReposInOrg, variables) + if err != nil { + return repositories, repositoriesByRefId, err + } var gResult GraplQLRepositories // parse first page @@ -645,6 +653,9 @@ func (g *GoliacRemoteImpl) loadTeamRepos(teamSlug string) (map[string]*GithubTea count := 0 for hasNextPage { data, err := g.client.QueryGraphQLAPI(listAllTeamsReposInOrg, variables) + if err != nil { + return nil, err + } var gResult GraplQLTeamsRepos // parse first page @@ -739,6 +750,9 @@ func (g *GoliacRemoteImpl) loadTeams() (map[string]*GithubTeam, map[string]strin count := 0 for hasNextPage { data, err := g.client.QueryGraphQLAPI(listAllTeamsInOrg, variables) + if err != nil { + return teams, teamSlugByName, err + } var gResult GraplQLTeams // parse first page @@ -778,6 +792,9 @@ func (g *GoliacRemoteImpl) loadTeams() (map[string]*GithubTeam, map[string]strin count := 0 for hasNextPage { data, err := g.client.QueryGraphQLAPI(listAllTeamMembersInOrg, variables) + if err != nil { + return teams, teamSlugByName, err + } var gResult GraplQLTeamMembers // parse first page @@ -1009,6 +1026,9 @@ func (g *GoliacRemoteImpl) loadRulesets() (map[string]*GithubRuleSet, error) { count := 0 for hasNextPage { data, err := g.client.QueryGraphQLAPI(listRulesets, variables) + if err != nil { + return rulesets, err + } var gResult GraplQLRuleSets // parse first page @@ -1083,7 +1103,6 @@ func (g *GoliacRemoteImpl) prepareRuleset(ruleset *GithubRuleSet) map[string]int rules = append(rules, map[string]interface{}{ "type": "required_signatures", }) - break case "pull_request": rules = append(rules, map[string]interface{}{ "type": "pull_request", @@ -1095,7 +1114,6 @@ func (g *GoliacRemoteImpl) prepareRuleset(ruleset *GithubRuleSet) map[string]int "require_last_push_approval": rule.RequireLastPushApproval, }, }) - break } } @@ -1260,7 +1278,7 @@ func (g *GoliacRemoteImpl) UpdateTeamAddMember(teamslug string, username string, found = true } } - if found == false { + if !found { members = append(members, username) g.teams[teamslug].Members = members } @@ -1287,7 +1305,7 @@ func (g *GoliacRemoteImpl) UpdateTeamRemoveMember(teamslug string, username stri members = append(members[:i], members[i+1:]...) } } - if found == true { + if found { g.teams[teamslug].Members = members } } diff --git a/internal/sync/remote_test.go b/internal/sync/remote_test.go index bff5f75..226055c 100644 --- a/internal/sync/remote_test.go +++ b/internal/sync/remote_test.go @@ -3,7 +3,7 @@ package sync import ( "encoding/json" "fmt" - "io/ioutil" + "io" "math/rand" "net/http" "strconv" @@ -21,7 +21,7 @@ func GetGithubGraphqlSchema() (string, error) { return "", err } else { defer response.Body.Close() - content, err := ioutil.ReadAll(response.Body) + content, err := io.ReadAll(response.Body) return string(content), err } } diff --git a/internal/swagger_gen/cmd/goliac-server/main.go b/swagger_gen/cmd/goliac-server/main.go similarity index 90% rename from internal/swagger_gen/cmd/goliac-server/main.go rename to swagger_gen/cmd/goliac-server/main.go index 33c7f60..21b18ee 100644 --- a/internal/swagger_gen/cmd/goliac-server/main.go +++ b/swagger_gen/cmd/goliac-server/main.go @@ -9,8 +9,8 @@ import ( "github.com/go-openapi/loads" flags "github.com/jessevdk/go-flags" - "github.com/Alayacare/goliac/internal/swagger_gen/restapi" - "github.com/Alayacare/goliac/internal/swagger_gen/restapi/operations" + "github.com/Alayacare/goliac/swagger_gen/restapi" + "github.com/Alayacare/goliac/swagger_gen/restapi/operations" ) // This file was generated by the swagger tool. diff --git a/internal/swagger_gen/models/error.go b/swagger_gen/models/error.go similarity index 100% rename from internal/swagger_gen/models/error.go rename to swagger_gen/models/error.go diff --git a/internal/swagger_gen/models/health.go b/swagger_gen/models/health.go similarity index 100% rename from internal/swagger_gen/models/health.go rename to swagger_gen/models/health.go diff --git a/internal/swagger_gen/restapi/configure_goliac.go b/swagger_gen/restapi/configure_goliac.go similarity index 97% rename from internal/swagger_gen/restapi/configure_goliac.go rename to swagger_gen/restapi/configure_goliac.go index 08e85b8..d7af297 100644 --- a/internal/swagger_gen/restapi/configure_goliac.go +++ b/swagger_gen/restapi/configure_goliac.go @@ -11,7 +11,7 @@ import ( "github.com/go-openapi/runtime" "github.com/sirupsen/logrus" - "github.com/Alayacare/goliac/internal/swagger_gen/restapi/operations" + "github.com/Alayacare/goliac/swagger_gen/restapi/operations" ) //go:generate swagger generate server --target ../../swagger_gen --name Goliac --spec ../../../docs/api_docs/bundle.yaml --principal interface{} diff --git a/internal/swagger_gen/restapi/doc.go b/swagger_gen/restapi/doc.go similarity index 100% rename from internal/swagger_gen/restapi/doc.go rename to swagger_gen/restapi/doc.go diff --git a/internal/swagger_gen/restapi/embedded_spec.go b/swagger_gen/restapi/embedded_spec.go similarity index 100% rename from internal/swagger_gen/restapi/embedded_spec.go rename to swagger_gen/restapi/embedded_spec.go diff --git a/internal/swagger_gen/restapi/operations/goliac_api.go b/swagger_gen/restapi/operations/goliac_api.go similarity index 99% rename from internal/swagger_gen/restapi/operations/goliac_api.go rename to swagger_gen/restapi/operations/goliac_api.go index bf5724b..0b9a677 100644 --- a/internal/swagger_gen/restapi/operations/goliac_api.go +++ b/swagger_gen/restapi/operations/goliac_api.go @@ -19,7 +19,7 @@ import ( "github.com/go-openapi/strfmt" "github.com/go-openapi/swag" - "github.com/Alayacare/goliac/internal/swagger_gen/restapi/operations/health" + "github.com/Alayacare/goliac/swagger_gen/restapi/operations/health" ) // NewGoliacAPI creates a new Goliac instance diff --git a/internal/swagger_gen/restapi/operations/health/get_liveness.go b/swagger_gen/restapi/operations/health/get_liveness.go similarity index 100% rename from internal/swagger_gen/restapi/operations/health/get_liveness.go rename to swagger_gen/restapi/operations/health/get_liveness.go diff --git a/internal/swagger_gen/restapi/operations/health/get_liveness_parameters.go b/swagger_gen/restapi/operations/health/get_liveness_parameters.go similarity index 100% rename from internal/swagger_gen/restapi/operations/health/get_liveness_parameters.go rename to swagger_gen/restapi/operations/health/get_liveness_parameters.go diff --git a/internal/swagger_gen/restapi/operations/health/get_liveness_responses.go b/swagger_gen/restapi/operations/health/get_liveness_responses.go similarity index 97% rename from internal/swagger_gen/restapi/operations/health/get_liveness_responses.go rename to swagger_gen/restapi/operations/health/get_liveness_responses.go index 6431e4d..5bd57fe 100644 --- a/internal/swagger_gen/restapi/operations/health/get_liveness_responses.go +++ b/swagger_gen/restapi/operations/health/get_liveness_responses.go @@ -10,7 +10,7 @@ import ( "github.com/go-openapi/runtime" - "github.com/Alayacare/goliac/internal/swagger_gen/models" + "github.com/Alayacare/goliac/swagger_gen/models" ) // GetLivenessOKCode is the HTTP code returned for type GetLivenessOK diff --git a/internal/swagger_gen/restapi/operations/health/get_liveness_urlbuilder.go b/swagger_gen/restapi/operations/health/get_liveness_urlbuilder.go similarity index 100% rename from internal/swagger_gen/restapi/operations/health/get_liveness_urlbuilder.go rename to swagger_gen/restapi/operations/health/get_liveness_urlbuilder.go diff --git a/internal/swagger_gen/restapi/operations/health/get_readiness.go b/swagger_gen/restapi/operations/health/get_readiness.go similarity index 100% rename from internal/swagger_gen/restapi/operations/health/get_readiness.go rename to swagger_gen/restapi/operations/health/get_readiness.go diff --git a/internal/swagger_gen/restapi/operations/health/get_readiness_parameters.go b/swagger_gen/restapi/operations/health/get_readiness_parameters.go similarity index 100% rename from internal/swagger_gen/restapi/operations/health/get_readiness_parameters.go rename to swagger_gen/restapi/operations/health/get_readiness_parameters.go diff --git a/internal/swagger_gen/restapi/operations/health/get_readiness_responses.go b/swagger_gen/restapi/operations/health/get_readiness_responses.go similarity index 97% rename from internal/swagger_gen/restapi/operations/health/get_readiness_responses.go rename to swagger_gen/restapi/operations/health/get_readiness_responses.go index a25eb4f..6929333 100644 --- a/internal/swagger_gen/restapi/operations/health/get_readiness_responses.go +++ b/swagger_gen/restapi/operations/health/get_readiness_responses.go @@ -10,7 +10,7 @@ import ( "github.com/go-openapi/runtime" - "github.com/Alayacare/goliac/internal/swagger_gen/models" + "github.com/Alayacare/goliac/swagger_gen/models" ) // GetReadinessOKCode is the HTTP code returned for type GetReadinessOK diff --git a/internal/swagger_gen/restapi/operations/health/get_readiness_urlbuilder.go b/swagger_gen/restapi/operations/health/get_readiness_urlbuilder.go similarity index 100% rename from internal/swagger_gen/restapi/operations/health/get_readiness_urlbuilder.go rename to swagger_gen/restapi/operations/health/get_readiness_urlbuilder.go diff --git a/internal/swagger_gen/restapi/server.go b/swagger_gen/restapi/server.go similarity index 99% rename from internal/swagger_gen/restapi/server.go rename to swagger_gen/restapi/server.go index 414b976..817d37e 100644 --- a/internal/swagger_gen/restapi/server.go +++ b/swagger_gen/restapi/server.go @@ -24,7 +24,7 @@ import ( flags "github.com/jessevdk/go-flags" "golang.org/x/net/netutil" - "github.com/Alayacare/goliac/internal/swagger_gen/restapi/operations" + "github.com/Alayacare/goliac/swagger_gen/restapi/operations" ) const (