diff --git a/internal/github/org.go b/internal/github/org.go index ce13ee0..64d69c6 100644 --- a/internal/github/org.go +++ b/internal/github/org.go @@ -7,12 +7,6 @@ import ( ) func OrgExist(cli *gh.Client, ctx context.Context, name string) (bool, error) { - _, rsp, err := cli.Organizations.Get(ctx, name) - if err != nil { - return false, err - } - if rsp.StatusCode == 404 { - return false, nil - } - return true, nil + _, _, err := cli.Organizations.Get(ctx, name) + return resolveResponseByErr(err) } diff --git a/internal/github/repo.go b/internal/github/repo.go index 346dc25..b3b91ca 100644 --- a/internal/github/repo.go +++ b/internal/github/repo.go @@ -7,12 +7,6 @@ import ( ) func RepoExist(cli *gh.Client, ctx context.Context, owner, name string) (bool, error) { - _, rsp, err := cli.Repositories.Get(ctx, owner, name) - if err != nil { - return false, err - } - if rsp.StatusCode == 404 { - return false, nil - } - return true, nil + _, _, err := cli.Repositories.Get(ctx, owner, name) + return resolveResponseByErr(err) } diff --git a/internal/github/team.go b/internal/github/team.go index fc8fea7..7c163fc 100644 --- a/internal/github/team.go +++ b/internal/github/team.go @@ -7,12 +7,6 @@ import ( ) func TeamExist(cli *gh.Client, ctx context.Context, org, slug string) (bool, error) { - _, rsp, err := cli.Teams.GetTeamBySlug(ctx, org, slug) - if err != nil { - return false, err - } - if rsp.StatusCode == 404 { - return false, nil - } - return true, nil + _, _, err := cli.Teams.GetTeamBySlug(ctx, org, slug) + return resolveResponseByErr(err) } diff --git a/internal/github/utils.go b/internal/github/utils.go new file mode 100644 index 0000000..4f1cd76 --- /dev/null +++ b/internal/github/utils.go @@ -0,0 +1,27 @@ +package github + +import ( + "net/http" + + gh "github.com/google/go-github/v33/github" +) + +// resolveResponseByErr determines the result from a GitHub API response. +// In some cases it is necessary to interpret the "404" response +// as "false" condition e.g. response on get repositoty request. +// Also several GitHub API methods return boolean responses indicated by the HTTP +// status code in the response (true indicated by a 204, false indicated by a +// 404). This helper function will determine that result and hide the 404 +// error if present. Any other error will be returned through as-is. +func resolveResponseByErr(err error) (bool, error) { + if err == nil { + return true, nil + } + if err, ok := err.(*gh.ErrorResponse); ok && err.Response.StatusCode == http.StatusNotFound { + // Simply false. In this one case, we do not pass the error through. + return false, nil + } + + // some other real error occurred + return false, err +}