3
\$\begingroup\$

Didn't post on the Codereview for a while but trying to learn Golang now and wrote my first utility a few days ago and will be glad to see what I did wrong here and what can be done better.

This tool is used to check public repositories in out GitHub organization and compare such a list with another list which contains repositories that are allowed to be public. If any differences will be found between both lists - it will send an alarm to Slack.

I googled and tried a lot of solutions to make slices comparison but finally had to write own loop.

The main thing I'm thinking about now is to use map[] instead of two for loops and working about it now.

The main() function:

func main() {

    client := github.NewClient(nil)

    opt := &github.RepositoryListByOrgOptions{Type: "public"}
    // get our public repositories list to the repos variable
    repos, _, _ := client.Repositories.ListByOrg(context.Background(), os.Getenv("GITHUB_ORG_NAME"), opt)

    // the list of repositories that are expected to be public
    allowedRepos := strings.Fields(os.Getenv("ALLOWED_REPOS"))

    for _, repo := range repos {
        fmt.Printf("\nChecking %s\n", *repo.Name)
        if isAllowedRepo(*repo.Name, allowedRepos) {
            fmt.Printf("OK: repo %s found in Allowed\n", *repo.Name)
        } else {
            fmt.Printf("ALARM: repo %s was NOT found in Allowed!\n", *repo.Name)
            sendSlackAlarm(*repo.Name, *repo.HTMLURL)
        }
    }
}

And it uses isAllowedRepo() to check if values are identical:

func isAllowedRepo(repoName string, allowedRepos []string) bool {

    // and just iterate the repoName over the allowedRepos list
    for _, i := range allowedRepos {
        if i == repoName {
            return true
        }
    }

    return false
}

Te full code can be seen here.

\$\endgroup\$
  • 1
    \$\begingroup\$ You can transform the allowed repos list into a regex expression and lose one of the loops. \$\endgroup\$ – Eyal May 7 at 14:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.