From fd378c772c6bda7f89a4070b0f576e3455ba2c5a Mon Sep 17 00:00:00 2001 From: Glenn Lewis <6598971+gmlewis@users.noreply.github.com> Date: Thu, 24 Mar 2022 10:34:13 -0400 Subject: [PATCH 01/10] Clean up method return consistency --- github/actions_artifacts.go | 11 +++++++- github/actions_workflow_jobs.go | 13 +++++++-- github/activity_star.go | 9 ++++++- github/billing.go | 14 +++++----- github/gists.go | 10 ++++++- github/git_blobs.go | 19 ++++++++++--- github/git_tags.go | 12 +++++++-- github/github.go | 6 +++++ github/issues_assignees.go | 20 +++++++++++--- github/issues_timeline.go | 6 ++++- github/orgs_actions_allowed.go | 7 ++++- github/orgs_actions_permissions.go | 7 ++++- github/orgs_hooks.go | 16 +++++++++-- github/orgs_members.go | 15 +++++++++-- github/orgs_users_blocking.go | 6 ++++- github/pulls.go | 6 ++++- github/repos.go | 29 +++++++++++++++----- github/repos_collaborators.go | 10 ++++++- github/repos_contents.go | 36 +++++++++++++++++++++++-- github/repos_stats.go | 10 +++++-- github/search.go | 43 +++++++++++++++++++++++++----- github/teams.go | 7 +++-- github/users_blocking.go | 6 ++++- github/users_followers.go | 6 ++++- 24 files changed, 272 insertions(+), 52 deletions(-) diff --git a/github/actions_artifacts.go b/github/actions_artifacts.go index 4aa7dc4404..97d6c5e9df 100644 --- a/github/actions_artifacts.go +++ b/github/actions_artifacts.go @@ -118,7 +118,12 @@ func (s *ActionsService) DownloadArtifact(ctx context.Context, owner, repo strin if resp.StatusCode != http.StatusFound { return nil, newResponse(resp), fmt.Errorf("unexpected status code: %s", resp.Status) } + parsedURL, err := url.Parse(resp.Header.Get("Location")) + if err != nil { + return nil, newResponse(resp), err + } + return parsedURL, newResponse(resp), nil } @@ -145,8 +150,12 @@ func (s *ActionsService) getDownloadArtifactFromURL(ctx context.Context, u strin if followRedirects && resp.StatusCode == http.StatusMovedPermanently { u = resp.Header.Get("Location") resp, err = s.getDownloadArtifactFromURL(ctx, u, false) + if err != nil { + return resp, err + } } - return resp, err + + return resp, nil } // DeleteArtifact deletes a workflow run artifact. diff --git a/github/actions_workflow_jobs.go b/github/actions_workflow_jobs.go index 66b8ff6edb..085f6bba60 100644 --- a/github/actions_workflow_jobs.go +++ b/github/actions_workflow_jobs.go @@ -122,8 +122,13 @@ func (s *ActionsService) GetWorkflowJobLogs(ctx context.Context, owner, repo str if resp.StatusCode != http.StatusFound { return nil, newResponse(resp), fmt.Errorf("unexpected status code: %s", resp.Status) } + parsedURL, err := url.Parse(resp.Header.Get("Location")) - return parsedURL, newResponse(resp), err + if err != nil { + return nil, newResponse(resp), err + } + + return parsedURL, newResponse(resp), nil } func (s *ActionsService) getWorkflowLogsFromURL(ctx context.Context, u string, followRedirects bool) (*http.Response, error) { @@ -149,6 +154,10 @@ func (s *ActionsService) getWorkflowLogsFromURL(ctx context.Context, u string, f if followRedirects && resp.StatusCode == http.StatusMovedPermanently { u = resp.Header.Get("Location") resp, err = s.getWorkflowLogsFromURL(ctx, u, false) + if err != nil { + return resp, err + } } - return resp, err + + return resp, nil } diff --git a/github/activity_star.go b/github/activity_star.go index ad07aac752..e38d559cff 100644 --- a/github/activity_star.go +++ b/github/activity_star.go @@ -108,9 +108,14 @@ func (s *ActivityService) IsStarred(ctx context.Context, owner, repo string) (bo if err != nil { return false, nil, err } + resp, err := s.client.Do(ctx, req, nil) starred, err := parseBoolResponse(err) - return starred, resp, err + if err != nil { + return false, resp, err + } + + return starred, resp, nil } // Star a repository as the authenticated user. @@ -122,6 +127,7 @@ func (s *ActivityService) Star(ctx context.Context, owner, repo string) (*Respon if err != nil { return nil, err } + return s.client.Do(ctx, req, nil) } @@ -134,5 +140,6 @@ func (s *ActivityService) Unstar(ctx context.Context, owner, repo string) (*Resp if err != nil { return nil, err } + return s.client.Do(ctx, req, nil) } diff --git a/github/billing.go b/github/billing.go index 8921833bdb..dea4677beb 100644 --- a/github/billing.go +++ b/github/billing.go @@ -79,7 +79,7 @@ func (s *BillingService) GetActionsBillingOrg(ctx context.Context, org string) ( return nil, resp, err } - return actionsOrgBilling, resp, err + return actionsOrgBilling, resp, nil } // GetPackagesBillingOrg returns the free and paid storage used for GitHub Packages in gigabytes for an Org. @@ -98,7 +98,7 @@ func (s *BillingService) GetPackagesBillingOrg(ctx context.Context, org string) return nil, resp, err } - return packagesOrgBilling, resp, err + return packagesOrgBilling, resp, nil } // GetStorageBillingOrg returns the estimated paid and estimated total storage used for GitHub Actions @@ -118,7 +118,7 @@ func (s *BillingService) GetStorageBillingOrg(ctx context.Context, org string) ( return nil, resp, err } - return storageOrgBilling, resp, err + return storageOrgBilling, resp, nil } // GetAdvancedSecurityActiveCommittersOrg returns the GitHub Advanced Security active committers for an organization per repository. @@ -137,7 +137,7 @@ func (s *BillingService) GetAdvancedSecurityActiveCommittersOrg(ctx context.Cont return nil, resp, err } - return activeOrgCommitters, resp, err + return activeOrgCommitters, resp, nil } // GetActionsBillingUser returns the summary of the free and paid GitHub Actions minutes used for a user. @@ -156,7 +156,7 @@ func (s *BillingService) GetActionsBillingUser(ctx context.Context, user string) return nil, resp, err } - return actionsUserBilling, resp, err + return actionsUserBilling, resp, nil } // GetPackagesBillingUser returns the free and paid storage used for GitHub Packages in gigabytes for a user. @@ -175,7 +175,7 @@ func (s *BillingService) GetPackagesBillingUser(ctx context.Context, user string return nil, resp, err } - return packagesUserBilling, resp, err + return packagesUserBilling, resp, nil } // GetStorageBillingUser returns the estimated paid and estimated total storage used for GitHub Actions @@ -195,5 +195,5 @@ func (s *BillingService) GetStorageBillingUser(ctx context.Context, user string) return nil, resp, err } - return storageUserBilling, resp, err + return storageUserBilling, resp, nil } diff --git a/github/gists.go b/github/gists.go index 4971c6bf54..d022b2722c 100644 --- a/github/gists.go +++ b/github/gists.go @@ -279,6 +279,7 @@ func (s *GistsService) Delete(ctx context.Context, id string) (*Response, error) if err != nil { return nil, err } + return s.client.Do(ctx, req, nil) } @@ -291,6 +292,7 @@ func (s *GistsService) Star(ctx context.Context, id string) (*Response, error) { if err != nil { return nil, err } + return s.client.Do(ctx, req, nil) } @@ -303,6 +305,7 @@ func (s *GistsService) Unstar(ctx context.Context, id string) (*Response, error) if err != nil { return nil, err } + return s.client.Do(ctx, req, nil) } @@ -315,9 +318,14 @@ func (s *GistsService) IsStarred(ctx context.Context, id string) (bool, *Respons if err != nil { return false, nil, err } + resp, err := s.client.Do(ctx, req, nil) starred, err := parseBoolResponse(err) - return starred, resp, err + if err != nil { + return false, resp, err + } + + return starred, resp, nil } // Fork a gist. diff --git a/github/git_blobs.go b/github/git_blobs.go index 6bc59c6f88..7cbd411ca7 100644 --- a/github/git_blobs.go +++ b/github/git_blobs.go @@ -33,7 +33,11 @@ func (s *GitService) GetBlob(ctx context.Context, owner string, repo string, sha blob := new(Blob) resp, err := s.client.Do(ctx, req, blob) - return blob, resp, err + if err != nil { + return nil, resp, err + } + + return blob, resp, nil } // GetBlobRaw fetches a blob's contents from a repo. @@ -46,11 +50,16 @@ func (s *GitService) GetBlobRaw(ctx context.Context, owner, repo, sha string) ([ if err != nil { return nil, nil, err } + req.Header.Set("Accept", "application/vnd.github.v3.raw") var buf bytes.Buffer resp, err := s.client.Do(ctx, req, &buf) - return buf.Bytes(), resp, err + if err != nil { + return nil, resp, err + } + + return buf.Bytes(), resp, nil } // CreateBlob creates a blob object. @@ -65,5 +74,9 @@ func (s *GitService) CreateBlob(ctx context.Context, owner string, repo string, t := new(Blob) resp, err := s.client.Do(ctx, req, t) - return t, resp, err + if err != nil { + return nil, resp, err + } + + return t, resp, nil } diff --git a/github/git_tags.go b/github/git_tags.go index 10029c4549..12cfc1b3ef 100644 --- a/github/git_tags.go +++ b/github/git_tags.go @@ -45,7 +45,11 @@ func (s *GitService) GetTag(ctx context.Context, owner string, repo string, sha tag := new(Tag) resp, err := s.client.Do(ctx, req, tag) - return tag, resp, err + if err != nil { + return nil, resp, err + } + + return tag, resp, nil } // CreateTag creates a tag object. @@ -72,5 +76,9 @@ func (s *GitService) CreateTag(ctx context.Context, owner string, repo string, t t := new(Tag) resp, err := s.client.Do(ctx, req, t) - return t, resp, err + if err != nil { + return nil, resp, err + } + + return t, resp, nil } diff --git a/github/github.go b/github/github.go index 164b2d0678..85edacb64d 100644 --- a/github/github.go +++ b/github/github.go @@ -353,6 +353,7 @@ func NewEnterpriseClient(baseURL, uploadURL string, httpClient *http.Client) (*C if err != nil { return nil, err } + if !strings.HasSuffix(baseEndpoint.Path, "/") { baseEndpoint.Path += "/" } @@ -366,6 +367,7 @@ func NewEnterpriseClient(baseURL, uploadURL string, httpClient *http.Client) (*C if err != nil { return nil, err } + if !strings.HasSuffix(uploadEndpoint.Path, "/") { uploadEndpoint.Path += "/" } @@ -390,6 +392,7 @@ func (c *Client) NewRequest(method, urlStr string, body interface{}) (*http.Requ if !strings.HasSuffix(c.BaseURL.Path, "/") { return nil, fmt.Errorf("BaseURL must have a trailing slash, but %q does not", c.BaseURL) } + u, err := c.BaseURL.Parse(urlStr) if err != nil { return nil, err @@ -437,6 +440,7 @@ func (c *Client) NewUploadRequest(urlStr string, reader io.Reader, size int64, m if err != nil { return nil, err } + req.ContentLength = size if mediaType == "" { @@ -621,6 +625,7 @@ func (c *Client) BareDo(ctx context.Context, req *http.Request) (*Response, erro if ctx == nil { return nil, errNonNilContext } + req = withContext(ctx, req) rateLimitCategory := category(req.URL.Path) @@ -996,6 +1001,7 @@ func CheckResponse(r *http.Response) error { if c := r.StatusCode; 200 <= c && c <= 299 { return nil } + errorResponse := &ErrorResponse{Response: r} data, err := ioutil.ReadAll(r.Body) if err == nil && data != nil { diff --git a/github/issues_assignees.go b/github/issues_assignees.go index 9f15aea43f..662dde87bd 100644 --- a/github/issues_assignees.go +++ b/github/issues_assignees.go @@ -25,6 +25,7 @@ func (s *IssuesService) ListAssignees(ctx context.Context, owner, repo string, o if err != nil { return nil, nil, err } + var assignees []*User resp, err := s.client.Do(ctx, req, &assignees) if err != nil { @@ -43,9 +44,14 @@ func (s *IssuesService) IsAssignee(ctx context.Context, owner, repo, user string if err != nil { return false, nil, err } + resp, err := s.client.Do(ctx, req, nil) assignee, err := parseBoolResponse(err) - return assignee, resp, err + if err != nil { + return false, resp, err + } + + return assignee, resp, nil } // AddAssignees adds the provided GitHub users as assignees to the issue. @@ -63,7 +69,11 @@ func (s *IssuesService) AddAssignees(ctx context.Context, owner, repo string, nu issue := &Issue{} resp, err := s.client.Do(ctx, req, issue) - return issue, resp, err + if err != nil { + return nil, resp, err + } + + return issue, resp, nil } // RemoveAssignees removes the provided GitHub users as assignees from the issue. @@ -81,5 +91,9 @@ func (s *IssuesService) RemoveAssignees(ctx context.Context, owner, repo string, issue := &Issue{} resp, err := s.client.Do(ctx, req, issue) - return issue, resp, err + if err != nil { + return nil, resp, err + } + + return issue, resp, nil } diff --git a/github/issues_timeline.go b/github/issues_timeline.go index 845e3f767c..d0ee0a78f2 100644 --- a/github/issues_timeline.go +++ b/github/issues_timeline.go @@ -180,5 +180,9 @@ func (s *IssuesService) ListIssueTimeline(ctx context.Context, owner, repo strin var events []*Timeline resp, err := s.client.Do(ctx, req, &events) - return events, resp, err + if err != nil { + return nil, resp, err + } + + return events, resp, nil } diff --git a/github/orgs_actions_allowed.go b/github/orgs_actions_allowed.go index 9032d033b6..f78a20bc15 100644 --- a/github/orgs_actions_allowed.go +++ b/github/orgs_actions_allowed.go @@ -52,7 +52,12 @@ func (s *OrganizationsService) EditActionsAllowed(ctx context.Context, org strin if err != nil { return nil, nil, err } + p := new(ActionsAllowed) resp, err := s.client.Do(ctx, req, p) - return p, resp, err + if err != nil { + return nil, resp, err + } + + return p, resp, nil } diff --git a/github/orgs_actions_permissions.go b/github/orgs_actions_permissions.go index b8a10b2520..fc1fe31361 100644 --- a/github/orgs_actions_permissions.go +++ b/github/orgs_actions_permissions.go @@ -52,7 +52,12 @@ func (s *OrganizationsService) EditActionsPermissions(ctx context.Context, org s if err != nil { return nil, nil, err } + p := new(ActionsPermissions) resp, err := s.client.Do(ctx, req, p) - return p, resp, err + if err != nil { + return nil, resp, err + } + + return p, resp, nil } diff --git a/github/orgs_hooks.go b/github/orgs_hooks.go index dc90656878..26687e565b 100644 --- a/github/orgs_hooks.go +++ b/github/orgs_hooks.go @@ -43,9 +43,14 @@ func (s *OrganizationsService) GetHook(ctx context.Context, org string, id int64 if err != nil { return nil, nil, err } + hook := new(Hook) resp, err := s.client.Do(ctx, req, hook) - return hook, resp, err + if err != nil { + return nil, resp, err + } + + return hook, resp, nil } // CreateHook creates a Hook for the specified org. @@ -88,9 +93,14 @@ func (s *OrganizationsService) EditHook(ctx context.Context, org string, id int6 if err != nil { return nil, nil, err } + h := new(Hook) resp, err := s.client.Do(ctx, req, h) - return h, resp, err + if err != nil { + return nil, resp, err + } + + return h, resp, nil } // PingHook triggers a 'ping' event to be sent to the Hook. @@ -102,6 +112,7 @@ func (s *OrganizationsService) PingHook(ctx context.Context, org string, id int6 if err != nil { return nil, err } + return s.client.Do(ctx, req, nil) } @@ -114,5 +125,6 @@ func (s *OrganizationsService) DeleteHook(ctx context.Context, org string, id in if err != nil { return nil, err } + return s.client.Do(ctx, req, nil) } diff --git a/github/orgs_members.go b/github/orgs_members.go index f3a2f17c08..eacb978e1f 100644 --- a/github/orgs_members.go +++ b/github/orgs_members.go @@ -111,7 +111,11 @@ func (s *OrganizationsService) IsMember(ctx context.Context, org, user string) ( resp, err := s.client.Do(ctx, req, nil) member, err := parseBoolResponse(err) - return member, resp, err + if err != nil { + return false, resp, err + } + + return member, resp, nil } // IsPublicMember checks if a user is a public member of an organization. @@ -126,7 +130,11 @@ func (s *OrganizationsService) IsPublicMember(ctx context.Context, org, user str resp, err := s.client.Do(ctx, req, nil) member, err := parseBoolResponse(err) - return member, resp, err + if err != nil { + return false, resp, err + } + + return member, resp, nil } // RemoveMember removes a user from all teams of an organization. @@ -295,6 +303,7 @@ func (s *OrganizationsService) ListPendingOrgInvitations(ctx context.Context, or if err != nil { return nil, resp, err } + return pendingInvitations, resp, nil } @@ -336,6 +345,7 @@ func (s *OrganizationsService) CreateOrgInvitation(ctx context.Context, org stri if err != nil { return nil, resp, err } + return invitation, resp, nil } @@ -360,6 +370,7 @@ func (s *OrganizationsService) ListOrgInvitationTeams(ctx context.Context, org, if err != nil { return nil, resp, err } + return orgInvitationTeams, resp, nil } diff --git a/github/orgs_users_blocking.go b/github/orgs_users_blocking.go index 2773344c9f..74d34dde82 100644 --- a/github/orgs_users_blocking.go +++ b/github/orgs_users_blocking.go @@ -53,7 +53,11 @@ func (s *OrganizationsService) IsBlocked(ctx context.Context, org string, user s resp, err := s.client.Do(ctx, req, nil) isBlocked, err := parseBoolResponse(err) - return isBlocked, resp, err + if err != nil { + return false, resp, err + } + + return isBlocked, resp, nil } // BlockUser blocks specified user from an organization. diff --git a/github/pulls.go b/github/pulls.go index 37fb7413a4..277a5f3b1e 100644 --- a/github/pulls.go +++ b/github/pulls.go @@ -423,7 +423,11 @@ func (s *PullRequestsService) IsMerged(ctx context.Context, owner string, repo s resp, err := s.client.Do(ctx, req, nil) merged, err := parseBoolResponse(err) - return merged, resp, err + if err != nil { + return false, resp, err + } + + return merged, resp, nil } // PullRequestMergeResult represents the result of merging a pull request. diff --git a/github/repos.go b/github/repos.go index b1ce079691..114f4d1dea 100644 --- a/github/repos.go +++ b/github/repos.go @@ -616,9 +616,16 @@ func (s *RepositoriesService) GetVulnerabilityAlerts(ctx context.Context, owner, req.Header.Set("Accept", mediaTypeRequiredVulnerabilityAlertsPreview) resp, err := s.client.Do(ctx, req, nil) + if err != nil { + return false, resp, err + } + vulnerabilityAlertsEnabled, err := parseBoolResponse(err) + if err != nil { + return false, resp, err + } - return vulnerabilityAlertsEnabled, resp, err + return vulnerabilityAlertsEnabled, resp, nil } // EnableVulnerabilityAlerts enables vulnerability alerts and the dependency graph for a repository. @@ -1073,7 +1080,11 @@ func (s *RepositoriesService) GetBranch(ctx context.Context, owner, repo, branch b := new(Branch) err = json.NewDecoder(resp.Body).Decode(b) - return b, newResponse(resp), err + if err != nil { + return nil, newResponse(resp), err + } + + return b, newResponse(resp), nil } func (s *RepositoriesService) getBranchFromURL(ctx context.Context, u string, followRedirects bool) (*http.Response, error) { @@ -1099,8 +1110,12 @@ func (s *RepositoriesService) getBranchFromURL(ctx context.Context, u string, fo resp.Body.Close() u = resp.Header.Get("Location") resp, err = s.getBranchFromURL(ctx, u, false) + if err != nil { + return nil, err + } } - return resp, err + + return resp, nil } // renameBranchRequest represents a request to rename a branch. @@ -1276,7 +1291,7 @@ func (s *RepositoriesService) RequireSignaturesOnProtectedBranch(ctx context.Con return nil, resp, err } - return r, resp, err + return r, resp, nil } // OptionalSignaturesOnProtectedBranch removes required signed commits on a given branch. @@ -1388,7 +1403,7 @@ func (s *RepositoriesService) UpdatePullRequestReviewEnforcement(ctx context.Con return nil, resp, err } - return r, resp, err + return r, resp, nil } // DisableDismissalRestrictions disables dismissal restrictions of a protected branch. @@ -1416,7 +1431,7 @@ func (s *RepositoriesService) DisableDismissalRestrictions(ctx context.Context, return nil, resp, err } - return r, resp, err + return r, resp, nil } // RemovePullRequestReviewEnforcement removes pull request enforcement of a protected branch. @@ -1468,7 +1483,7 @@ func (s *RepositoriesService) AddAdminEnforcement(ctx context.Context, owner, re return nil, resp, err } - return r, resp, err + return r, resp, nil } // RemoveAdminEnforcement removes admin enforcement from a protected branch. diff --git a/github/repos_collaborators.go b/github/repos_collaborators.go index ccb97a192a..802163243d 100644 --- a/github/repos_collaborators.go +++ b/github/repos_collaborators.go @@ -78,7 +78,11 @@ func (s *RepositoriesService) IsCollaborator(ctx context.Context, owner, repo, u resp, err := s.client.Do(ctx, req, nil) isCollab, err := parseBoolResponse(err) - return isCollab, resp, err + if err != nil { + return false, resp, err + } + + return isCollab, resp, nil } // RepositoryPermissionLevel represents the permission level an organization @@ -104,6 +108,7 @@ func (s *RepositoriesService) GetPermissionLevel(ctx context.Context, owner, rep if err != nil { return nil, resp, err } + return rpl, resp, nil } @@ -132,11 +137,13 @@ func (s *RepositoriesService) AddCollaborator(ctx context.Context, owner, repo, if err != nil { return nil, nil, err } + acr := new(CollaboratorInvitation) resp, err := s.client.Do(ctx, req, acr) if err != nil { return nil, resp, err } + return acr, resp, nil } @@ -150,5 +157,6 @@ func (s *RepositoriesService) RemoveCollaborator(ctx context.Context, owner, rep if err != nil { return nil, err } + return s.client.Do(ctx, req, nil) } diff --git a/github/repos_contents.go b/github/repos_contents.go index 86e11c0a75..860cad526c 100644 --- a/github/repos_contents.go +++ b/github/repos_contents.go @@ -102,15 +102,18 @@ func (s *RepositoriesService) GetReadme(ctx context.Context, owner, repo string, if err != nil { return nil, nil, err } + req, err := s.client.NewRequest("GET", u, nil) if err != nil { return nil, nil, err } + readme := new(RepositoryContent) resp, err := s.client.Do(ctx, req, readme) if err != nil { return nil, resp, err } + return readme, resp, nil } @@ -129,18 +132,22 @@ func (s *RepositoriesService) DownloadContents(ctx context.Context, owner, repo, if err != nil { return nil, resp, err } + for _, contents := range dirContents { if *contents.Name == filename { if contents.DownloadURL == nil || *contents.DownloadURL == "" { return nil, resp, fmt.Errorf("no download link found for %s", filepath) } + dlResp, err := s.client.client.Get(*contents.DownloadURL) if err != nil { return nil, &Response{Response: dlResp}, err } + return dlResp.Body, &Response{Response: dlResp}, nil } } + return nil, resp, fmt.Errorf("no file named %s found in %s", filename, dir) } @@ -159,18 +166,22 @@ func (s *RepositoriesService) DownloadContentsWithMeta(ctx context.Context, owne if err != nil { return nil, nil, resp, err } + for _, contents := range dirContents { if *contents.Name == filename { if contents.DownloadURL == nil || *contents.DownloadURL == "" { return nil, contents, resp, fmt.Errorf("no download link found for %s", filepath) } + dlResp, err := s.client.client.Get(*contents.DownloadURL) if err != nil { return nil, contents, &Response{Response: dlResp}, err } + return dlResp.Body, contents, &Response{Response: dlResp}, nil } } + return nil, nil, resp, fmt.Errorf("no file named %s found in %s", filename, dir) } @@ -189,23 +200,28 @@ func (s *RepositoriesService) GetContents(ctx context.Context, owner, repo, path if err != nil { return nil, nil, nil, err } + req, err := s.client.NewRequest("GET", u, nil) if err != nil { return nil, nil, nil, err } + var rawJSON json.RawMessage resp, err = s.client.Do(ctx, req, &rawJSON) if err != nil { return nil, nil, resp, err } + fileUnmarshalError := json.Unmarshal(rawJSON, &fileContent) if fileUnmarshalError == nil { return fileContent, nil, resp, nil } + directoryUnmarshalError := json.Unmarshal(rawJSON, &directoryContent) if directoryUnmarshalError == nil { return nil, directoryContent, resp, nil } + return nil, nil, resp, fmt.Errorf("unmarshalling failed for both file and directory content: %s and %s", fileUnmarshalError, directoryUnmarshalError) } @@ -219,11 +235,13 @@ func (s *RepositoriesService) CreateFile(ctx context.Context, owner, repo, path if err != nil { return nil, nil, err } + createResponse := new(RepositoryContentResponse) resp, err := s.client.Do(ctx, req, createResponse) if err != nil { return nil, resp, err } + return createResponse, resp, nil } @@ -237,11 +255,13 @@ func (s *RepositoriesService) UpdateFile(ctx context.Context, owner, repo, path if err != nil { return nil, nil, err } + updateResponse := new(RepositoryContentResponse) resp, err := s.client.Do(ctx, req, updateResponse) if err != nil { return nil, resp, err } + return updateResponse, resp, nil } @@ -255,11 +275,13 @@ func (s *RepositoriesService) DeleteFile(ctx context.Context, owner, repo, path if err != nil { return nil, nil, err } + deleteResponse := new(RepositoryContentResponse) resp, err := s.client.Do(ctx, req, deleteResponse) if err != nil { return nil, resp, err } + return deleteResponse, resp, nil } @@ -288,11 +310,17 @@ func (s *RepositoriesService) GetArchiveLink(ctx context.Context, owner, repo st if err != nil { return nil, nil, err } + if resp.StatusCode != http.StatusFound { return nil, newResponse(resp), fmt.Errorf("unexpected status code: %s", resp.Status) } + parsedURL, err := url.Parse(resp.Header.Get("Location")) - return parsedURL, newResponse(resp), err + if err != nil { + return nil, newResponse(resp), err + } + + return parsedURL, newResponse(resp), nil } func (s *RepositoriesService) getArchiveLinkFromURL(ctx context.Context, u string, followRedirects bool) (*http.Response, error) { @@ -318,6 +346,10 @@ func (s *RepositoriesService) getArchiveLinkFromURL(ctx context.Context, u strin if followRedirects && resp.StatusCode == http.StatusMovedPermanently { u = resp.Header.Get("Location") resp, err = s.getArchiveLinkFromURL(ctx, u, false) + if err != nil { + return resp, err + } } - return resp, err + + return resp, nil } diff --git a/github/repos_stats.go b/github/repos_stats.go index 73f0a6768a..756dbc21b6 100644 --- a/github/repos_stats.go +++ b/github/repos_stats.go @@ -121,6 +121,9 @@ func (s *RepositoriesService) ListCodeFrequency(ctx context.Context, owner, repo var weeks [][]int resp, err := s.client.Do(ctx, req, &weeks) + if err != nil { + return nil, resp, err + } // convert int slices into WeeklyStats var stats []*WeeklyStats @@ -136,7 +139,7 @@ func (s *RepositoriesService) ListCodeFrequency(ctx context.Context, owner, repo stats = append(stats, stat) } - return stats, resp, err + return stats, resp, nil } // RepositoryParticipation is the number of commits by everyone @@ -207,6 +210,9 @@ func (s *RepositoriesService) ListPunchCard(ctx context.Context, owner, repo str var results [][]int resp, err := s.client.Do(ctx, req, &results) + if err != nil { + return nil, resp, err + } // convert int slices into Punchcards var cards []*PunchCard @@ -222,5 +228,5 @@ func (s *RepositoriesService) ListPunchCard(ctx context.Context, owner, repo str cards = append(cards, card) } - return cards, resp, err + return cards, resp, nil } diff --git a/github/search.go b/github/search.go index 19aa892798..a3da304c51 100644 --- a/github/search.go +++ b/github/search.go @@ -73,7 +73,11 @@ type RepositoriesSearchResult struct { func (s *SearchService) Repositories(ctx context.Context, query string, opts *SearchOptions) (*RepositoriesSearchResult, *Response, error) { result := new(RepositoriesSearchResult) resp, err := s.search(ctx, "repositories", &searchParameters{Query: query}, opts, result) - return result, resp, err + if err != nil { + return nil, resp, err + } + + return result, resp, nil } // TopicsSearchResult represents the result of a topics search. @@ -104,7 +108,11 @@ type TopicResult struct { func (s *SearchService) Topics(ctx context.Context, query string, opts *SearchOptions) (*TopicsSearchResult, *Response, error) { result := new(TopicsSearchResult) resp, err := s.search(ctx, "topics", &searchParameters{Query: query}, opts, result) - return result, resp, err + if err != nil { + return nil, resp, err + } + + return result, resp, nil } // CommitsSearchResult represents the result of a commits search. @@ -135,7 +143,11 @@ type CommitResult struct { func (s *SearchService) Commits(ctx context.Context, query string, opts *SearchOptions) (*CommitsSearchResult, *Response, error) { result := new(CommitsSearchResult) resp, err := s.search(ctx, "commits", &searchParameters{Query: query}, opts, result) - return result, resp, err + if err != nil { + return nil, resp, err + } + + return result, resp, nil } // IssuesSearchResult represents the result of an issues search. @@ -151,7 +163,11 @@ type IssuesSearchResult struct { func (s *SearchService) Issues(ctx context.Context, query string, opts *SearchOptions) (*IssuesSearchResult, *Response, error) { result := new(IssuesSearchResult) resp, err := s.search(ctx, "issues", &searchParameters{Query: query}, opts, result) - return result, resp, err + if err != nil { + return nil, resp, err + } + + return result, resp, nil } // UsersSearchResult represents the result of a users search. @@ -167,7 +183,11 @@ type UsersSearchResult struct { func (s *SearchService) Users(ctx context.Context, query string, opts *SearchOptions) (*UsersSearchResult, *Response, error) { result := new(UsersSearchResult) resp, err := s.search(ctx, "users", &searchParameters{Query: query}, opts, result) - return result, resp, err + if err != nil { + return nil, resp, err + } + + return result, resp, nil } // Match represents a single text match. @@ -216,7 +236,11 @@ func (c CodeResult) String() string { func (s *SearchService) Code(ctx context.Context, query string, opts *SearchOptions) (*CodeSearchResult, *Response, error) { result := new(CodeSearchResult) resp, err := s.search(ctx, "code", &searchParameters{Query: query}, opts, result) - return result, resp, err + if err != nil { + return nil, resp, err + } + + return result, resp, nil } // LabelsSearchResult represents the result of a code search. @@ -247,7 +271,11 @@ func (l LabelResult) String() string { func (s *SearchService) Labels(ctx context.Context, repoID int64, query string, opts *SearchOptions) (*LabelsSearchResult, *Response, error) { result := new(LabelsSearchResult) resp, err := s.search(ctx, "labels", &searchParameters{RepositoryID: &repoID, Query: query}, opts, result) - return result, resp, err + if err != nil { + return nil, resp, err + } + + return result, resp, nil } // Helper function that executes search queries against different @@ -260,6 +288,7 @@ func (s *SearchService) search(ctx context.Context, searchType string, parameter if err != nil { return nil, err } + if parameters.RepositoryID != nil { params.Set("repository_id", strconv.FormatInt(*parameters.RepositoryID, 10)) } diff --git a/github/teams.go b/github/teams.go index 82d4093b47..5b1096ea29 100644 --- a/github/teams.go +++ b/github/teams.go @@ -771,6 +771,7 @@ func (s *TeamsService) ListIDPGroupsInOrganization(ctx context.Context, org stri if err != nil { return nil, resp, err } + return groups, resp, nil } @@ -791,7 +792,8 @@ func (s *TeamsService) ListIDPGroupsForTeamByID(ctx context.Context, orgID, team if err != nil { return nil, resp, err } - return groups, resp, err + + return groups, resp, nil } // ListIDPGroupsForTeamBySlug lists IDP groups connected to a team on GitHub @@ -811,7 +813,8 @@ func (s *TeamsService) ListIDPGroupsForTeamBySlug(ctx context.Context, org, slug if err != nil { return nil, resp, err } - return groups, resp, err + + return groups, resp, nil } // CreateOrUpdateIDPGroupConnectionsByID creates, updates, or removes a connection diff --git a/github/users_blocking.go b/github/users_blocking.go index cdbc2c2532..f494dfbe8c 100644 --- a/github/users_blocking.go +++ b/github/users_blocking.go @@ -53,7 +53,11 @@ func (s *UsersService) IsBlocked(ctx context.Context, user string) (bool, *Respo resp, err := s.client.Do(ctx, req, nil) isBlocked, err := parseBoolResponse(err) - return isBlocked, resp, err + if err != nil { + return false, resp, err + } + + return isBlocked, resp, nil } // BlockUser blocks specified user for the authenticated user. diff --git a/github/users_followers.go b/github/users_followers.go index f26392b6e2..41a696514e 100644 --- a/github/users_followers.go +++ b/github/users_followers.go @@ -92,7 +92,11 @@ func (s *UsersService) IsFollowing(ctx context.Context, user, target string) (bo resp, err := s.client.Do(ctx, req, nil) following, err := parseBoolResponse(err) - return following, resp, err + if err != nil { + return false, resp, err + } + + return following, resp, nil } // Follow will cause the authenticated user to follow the specified user. From 623aa3603820d1917e12d8388f2b2984b236ee59 Mon Sep 17 00:00:00 2001 From: Glenn Lewis <6598971+gmlewis@users.noreply.github.com> Date: Thu, 24 Mar 2022 13:18:01 -0400 Subject: [PATCH 02/10] Fix golangci-lint code duplication errors --- github/actions_artifacts.go | 33 +------------------------------ github/actions_workflow_jobs.go | 34 ++------------------------------ github/actions_workflow_runs.go | 3 ++- github/github.go | 31 +++++++++++++++++++++++++++++ github/repos_contents.go | 35 +++------------------------------ 5 files changed, 39 insertions(+), 97 deletions(-) diff --git a/github/actions_artifacts.go b/github/actions_artifacts.go index 97d6c5e9df..c18e69e00a 100644 --- a/github/actions_artifacts.go +++ b/github/actions_artifacts.go @@ -110,7 +110,7 @@ func (s *ActionsService) GetArtifact(ctx context.Context, owner, repo string, ar func (s *ActionsService) DownloadArtifact(ctx context.Context, owner, repo string, artifactID int64, followRedirects bool) (*url.URL, *Response, error) { u := fmt.Sprintf("repos/%v/%v/actions/artifacts/%v/zip", owner, repo, artifactID) - resp, err := s.getDownloadArtifactFromURL(ctx, u, followRedirects) + resp, err := s.client.getDownloadArtifactFromURL(ctx, u, followRedirects) if err != nil { return nil, nil, err } @@ -127,37 +127,6 @@ func (s *ActionsService) DownloadArtifact(ctx context.Context, owner, repo strin return parsedURL, newResponse(resp), nil } -func (s *ActionsService) getDownloadArtifactFromURL(ctx context.Context, u string, followRedirects bool) (*http.Response, error) { - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, err - } - - var resp *http.Response - // Use http.DefaultTransport if no custom Transport is configured - req = withContext(ctx, req) - if s.client.client.Transport == nil { - resp, err = http.DefaultTransport.RoundTrip(req) - } else { - resp, err = s.client.client.Transport.RoundTrip(req) - } - if err != nil { - return nil, err - } - resp.Body.Close() - - // If redirect response is returned, follow it - if followRedirects && resp.StatusCode == http.StatusMovedPermanently { - u = resp.Header.Get("Location") - resp, err = s.getDownloadArtifactFromURL(ctx, u, false) - if err != nil { - return resp, err - } - } - - return resp, nil -} - // DeleteArtifact deletes a workflow run artifact. // // GitHub API docs: https://docs.github.com/en/free-pro-team@latest/rest/reference/actions/#delete-an-artifact diff --git a/github/actions_workflow_jobs.go b/github/actions_workflow_jobs.go index 085f6bba60..808d36dcd7 100644 --- a/github/actions_workflow_jobs.go +++ b/github/actions_workflow_jobs.go @@ -114,7 +114,8 @@ func (s *ActionsService) GetWorkflowJobByID(ctx context.Context, owner, repo str func (s *ActionsService) GetWorkflowJobLogs(ctx context.Context, owner, repo string, jobID int64, followRedirects bool) (*url.URL, *Response, error) { u := fmt.Sprintf("repos/%v/%v/actions/jobs/%v/logs", owner, repo, jobID) - resp, err := s.getWorkflowLogsFromURL(ctx, u, followRedirects) + // The DownloadArtifact in this case are the workflow logs. + resp, err := s.client.getDownloadArtifactFromURL(ctx, u, followRedirects) if err != nil { return nil, nil, err } @@ -130,34 +131,3 @@ func (s *ActionsService) GetWorkflowJobLogs(ctx context.Context, owner, repo str return parsedURL, newResponse(resp), nil } - -func (s *ActionsService) getWorkflowLogsFromURL(ctx context.Context, u string, followRedirects bool) (*http.Response, error) { - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, err - } - - var resp *http.Response - // Use http.DefaultTransport if no custom Transport is configured - req = withContext(ctx, req) - if s.client.client.Transport == nil { - resp, err = http.DefaultTransport.RoundTrip(req) - } else { - resp, err = s.client.client.Transport.RoundTrip(req) - } - if err != nil { - return nil, err - } - resp.Body.Close() - - // If redirect response is returned, follow it - if followRedirects && resp.StatusCode == http.StatusMovedPermanently { - u = resp.Header.Get("Location") - resp, err = s.getWorkflowLogsFromURL(ctx, u, false) - if err != nil { - return resp, err - } - } - - return resp, nil -} diff --git a/github/actions_workflow_runs.go b/github/actions_workflow_runs.go index 273d2cc466..2571252ba8 100644 --- a/github/actions_workflow_runs.go +++ b/github/actions_workflow_runs.go @@ -231,7 +231,8 @@ func (s *ActionsService) CancelWorkflowRunByID(ctx context.Context, owner, repo func (s *ActionsService) GetWorkflowRunLogs(ctx context.Context, owner, repo string, runID int64, followRedirects bool) (*url.URL, *Response, error) { u := fmt.Sprintf("repos/%v/%v/actions/runs/%v/logs", owner, repo, runID) - resp, err := s.getWorkflowLogsFromURL(ctx, u, followRedirects) + // The DownloadArtifact in this case are the workflow logs. + resp, err := s.client.getDownloadArtifactFromURL(ctx, u, followRedirects) if err != nil { return nil, nil, err } diff --git a/github/github.go b/github/github.go index 85edacb64d..afa90b0ed6 100644 --- a/github/github.go +++ b/github/github.go @@ -1285,6 +1285,37 @@ func formatRateReset(d time.Duration) string { return fmt.Sprintf("[rate reset in %v]", timeString) } +func (c *Client) getDownloadArtifactFromURL(ctx context.Context, u string, followRedirects bool) (*http.Response, error) { + req, err := c.NewRequest("GET", u, nil) + if err != nil { + return nil, err + } + + var resp *http.Response + // Use http.DefaultTransport if no custom Transport is configured + req = withContext(ctx, req) + if c.client.Transport == nil { + resp, err = http.DefaultTransport.RoundTrip(req) + } else { + resp, err = c.client.Transport.RoundTrip(req) + } + if err != nil { + return nil, err + } + resp.Body.Close() + + // If redirect response is returned, follow it + if followRedirects && resp.StatusCode == http.StatusMovedPermanently { + u = resp.Header.Get("Location") + resp, err = c.getDownloadArtifactFromURL(ctx, u, false) + if err != nil { + return resp, err + } + } + + return resp, nil +} + // Bool is a helper routine that allocates a new bool value // to store v and returns a pointer to it. func Bool(v bool) *bool { return &v } diff --git a/github/repos_contents.go b/github/repos_contents.go index 860cad526c..a98f2ae866 100644 --- a/github/repos_contents.go +++ b/github/repos_contents.go @@ -306,7 +306,9 @@ func (s *RepositoriesService) GetArchiveLink(ctx context.Context, owner, repo st if opts != nil && opts.Ref != "" { u += fmt.Sprintf("/%s", opts.Ref) } - resp, err := s.getArchiveLinkFromURL(ctx, u, followRedirects) + + // the DownloadArtifact in this case is the archive link. + resp, err := s.client.getDownloadArtifactFromURL(ctx, u, followRedirects) if err != nil { return nil, nil, err } @@ -322,34 +324,3 @@ func (s *RepositoriesService) GetArchiveLink(ctx context.Context, owner, repo st return parsedURL, newResponse(resp), nil } - -func (s *RepositoriesService) getArchiveLinkFromURL(ctx context.Context, u string, followRedirects bool) (*http.Response, error) { - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, err - } - - var resp *http.Response - // Use http.DefaultTransport if no custom Transport is configured - req = withContext(ctx, req) - if s.client.client.Transport == nil { - resp, err = http.DefaultTransport.RoundTrip(req) - } else { - resp, err = s.client.client.Transport.RoundTrip(req) - } - if err != nil { - return nil, err - } - resp.Body.Close() - - // If redirect response is returned, follow it - if followRedirects && resp.StatusCode == http.StatusMovedPermanently { - u = resp.Header.Get("Location") - resp, err = s.getArchiveLinkFromURL(ctx, u, false) - if err != nil { - return resp, err - } - } - - return resp, nil -} From dccbb8f9542cd668f9d2099befde90667555b0f6 Mon Sep 17 00:00:00 2001 From: Glenn Lewis <6598971+gmlewis@users.noreply.github.com> Date: Thu, 24 Mar 2022 13:58:59 -0400 Subject: [PATCH 03/10] Remove unwanted test --- github/repos.go | 4 ---- 1 file changed, 4 deletions(-) diff --git a/github/repos.go b/github/repos.go index 114f4d1dea..a0193f816b 100644 --- a/github/repos.go +++ b/github/repos.go @@ -616,10 +616,6 @@ func (s *RepositoriesService) GetVulnerabilityAlerts(ctx context.Context, owner, req.Header.Set("Accept", mediaTypeRequiredVulnerabilityAlertsPreview) resp, err := s.client.Do(ctx, req, nil) - if err != nil { - return false, resp, err - } - vulnerabilityAlertsEnabled, err := parseBoolResponse(err) if err != nil { return false, resp, err From 7e9b95ac46f6a92d9931e5679646ec2b5ff135c3 Mon Sep 17 00:00:00 2001 From: Glenn Lewis <6598971+gmlewis@users.noreply.github.com> Date: Thu, 24 Mar 2022 14:36:29 -0400 Subject: [PATCH 04/10] Improve code coverage --- github/actions_artifacts_test.go | 16 +++++++++++++++ github/git_blobs_test.go | 16 +++++++++++++++ github/git_tags_test.go | 26 +++++++++++++++++++------ github/github_test.go | 6 ++++++ github/issues_assignees_test.go | 16 +++++++++++++++ github/orgs_actions_allowed_test.go | 8 ++++++++ github/orgs_actions_permissions_test.go | 8 ++++++++ github/orgs_hooks_test.go | 16 +++++++++++++++ github/repos_contents_test.go | 14 +++++++++++++ github/repos_test.go | 17 +++++++++++++++- 10 files changed, 136 insertions(+), 7 deletions(-) diff --git a/github/actions_artifacts_test.go b/github/actions_artifacts_test.go index e526e05971..bab6836943 100644 --- a/github/actions_artifacts_test.go +++ b/github/actions_artifacts_test.go @@ -340,6 +340,22 @@ func TestActionsService_DownloadArtifact_StatusMovedPermanently_dontFollowRedire } } +func TestActionsService_DownloadArtifact_StatusMovedPermanently_missingLocation(t *testing.T) { + client, mux, _, teardown := setup() + defer teardown() + + mux.HandleFunc("/repos/o/r/actions/artifacts/1/zip", func(w http.ResponseWriter, r *http.Request) { + testMethod(t, r, "GET") + http.Redirect(w, r, "", http.StatusMovedPermanently) + }) + + ctx := context.Background() + _, resp, _ := client.Actions.DownloadArtifact(ctx, "o", "r", 1, false) + if resp.StatusCode != http.StatusMovedPermanently { + t.Errorf("Actions.DownloadArtifact return status %d, want %d", resp.StatusCode, http.StatusMovedPermanently) + } +} + func TestActionsService_DownloadArtifact_StatusMovedPermanently_followRedirects(t *testing.T) { client, mux, serverURL, teardown := setup() defer teardown() diff --git a/github/git_blobs_test.go b/github/git_blobs_test.go index f2e2457b7c..c2cc455ab8 100644 --- a/github/git_blobs_test.go +++ b/github/git_blobs_test.go @@ -49,6 +49,14 @@ func TestGitService_GetBlob(t *testing.T) { _, _, err = client.Git.GetBlob(ctx, "\n", "\n", "\n") return err }) + + testNewRequestAndDoFailure(t, methodName, client, func() (*Response, error) { + got, resp, err := client.Git.GetBlob(ctx, "o", "r", "s") + if got != nil { + t.Errorf("testNewRequestAndDoFailure %v = %#v, want nil", methodName, got) + } + return resp, err + }) } func TestGitService_GetBlob_invalidOwner(t *testing.T) { @@ -144,6 +152,14 @@ func TestGitService_CreateBlob(t *testing.T) { _, _, err = client.Git.CreateBlob(ctx, "\n", "\n", input) return err }) + + testNewRequestAndDoFailure(t, methodName, client, func() (*Response, error) { + got, resp, err := client.Git.CreateBlob(ctx, "o", "r", input) + if got != nil { + t.Errorf("testNewRequestAndDoFailure %v = %#v, want nil", methodName, got) + } + return resp, err + }) } func TestGitService_CreateBlob_invalidOwner(t *testing.T) { diff --git a/github/git_tags_test.go b/github/git_tags_test.go index 3962f49118..2d13722aba 100644 --- a/github/git_tags_test.go +++ b/github/git_tags_test.go @@ -40,6 +40,14 @@ func TestGitService_GetTag(t *testing.T) { _, _, err = client.Git.GetTag(ctx, "\n", "\n", "\n") return err }) + + testNewRequestAndDoFailure(t, methodName, client, func() (*Response, error) { + got, resp, err := client.Git.GetTag(ctx, "o", "r", "s") + if got != nil { + t.Errorf("testNewRequestAndDoFailure %v = %#v, want nil", methodName, got) + } + return resp, err + }) } func TestGitService_CreateTag(t *testing.T) { @@ -61,10 +69,11 @@ func TestGitService_CreateTag(t *testing.T) { }) ctx := context.Background() - tag, _, err := client.Git.CreateTag(ctx, "o", "r", &Tag{ + inputTag := &Tag{ Tag: input.Tag, Object: &GitObject{SHA: input.Object}, - }) + } + tag, _, err := client.Git.CreateTag(ctx, "o", "r", inputTag) if err != nil { t.Errorf("Git.CreateTag returned error: %v", err) } @@ -76,12 +85,17 @@ func TestGitService_CreateTag(t *testing.T) { const methodName = "CreateTag" testBadOptions(t, methodName, func() (err error) { - _, _, err = client.Git.CreateTag(ctx, "\n", "\n", &Tag{ - Tag: input.Tag, - Object: &GitObject{SHA: input.Object}, - }) + _, _, err = client.Git.CreateTag(ctx, "\n", "\n", inputTag) return err }) + + testNewRequestAndDoFailure(t, methodName, client, func() (*Response, error) { + got, resp, err := client.Git.CreateTag(ctx, "o", "r", inputTag) + if got != nil { + t.Errorf("testNewRequestAndDoFailure %v = %#v, want nil", methodName, got) + } + return resp, err + }) } func TestTag_Marshal(t *testing.T) { diff --git a/github/github_test.go b/github/github_test.go index aa030d4f44..475eb9d820 100644 --- a/github/github_test.go +++ b/github/github_test.go @@ -594,6 +594,12 @@ func TestNewUploadRequest_badURL(t *testing.T) { c := NewClient(nil) _, err := c.NewUploadRequest(":", nil, 0, "") testURLParseError(t, err) + + const methodName = "NewUploadRequest" + testBadOptions(t, methodName, func() (err error) { + _, err = c.NewUploadRequest("\n", nil, -1, "\n") + return err + }) } func TestNewUploadRequest_errorForNoTrailingSlash(t *testing.T) { diff --git a/github/issues_assignees_test.go b/github/issues_assignees_test.go index ced7bfcd2c..26773b1154 100644 --- a/github/issues_assignees_test.go +++ b/github/issues_assignees_test.go @@ -202,6 +202,14 @@ func TestIssuesService_AddAssignees(t *testing.T) { _, _, err = client.Issues.AddAssignees(ctx, "\n", "\n", -1, []string{"\n", "\n"}) return err }) + + testNewRequestAndDoFailure(t, methodName, client, func() (*Response, error) { + got, resp, err := client.Issues.AddAssignees(ctx, "o", "r", 1, []string{"user1", "user2"}) + if got != nil { + t.Errorf("testNewRequestAndDoFailure %v = %#v, want nil", methodName, got) + } + return resp, err + }) } func TestIssuesService_RemoveAssignees(t *testing.T) { @@ -238,4 +246,12 @@ func TestIssuesService_RemoveAssignees(t *testing.T) { _, _, err = client.Issues.RemoveAssignees(ctx, "\n", "\n", -1, []string{"\n", "\n"}) return err }) + + testNewRequestAndDoFailure(t, methodName, client, func() (*Response, error) { + got, resp, err := client.Issues.RemoveAssignees(ctx, "o", "r", 1, []string{"user1", "user2"}) + if got != nil { + t.Errorf("testNewRequestAndDoFailure %v = %#v, want nil", methodName, got) + } + return resp, err + }) } diff --git a/github/orgs_actions_allowed_test.go b/github/orgs_actions_allowed_test.go index 0525b1defb..6af0521352 100644 --- a/github/orgs_actions_allowed_test.go +++ b/github/orgs_actions_allowed_test.go @@ -82,6 +82,14 @@ func TestOrganizationsService_EditActionsAllowed(t *testing.T) { _, _, err = client.Organizations.EditActionsAllowed(ctx, "\n", *input) return err }) + + testNewRequestAndDoFailure(t, methodName, client, func() (*Response, error) { + got, resp, err := client.Organizations.EditActionsAllowed(ctx, "o", *input) + if got != nil { + t.Errorf("testNewRequestAndDoFailure %v = %#v, want nil", methodName, got) + } + return resp, err + }) } func TestActionsAllowed_Marshal(t *testing.T) { diff --git a/github/orgs_actions_permissions_test.go b/github/orgs_actions_permissions_test.go index eff0d4c4ff..9664c79eda 100644 --- a/github/orgs_actions_permissions_test.go +++ b/github/orgs_actions_permissions_test.go @@ -83,4 +83,12 @@ func TestOrganizationsService_EditActionsPermissions(t *testing.T) { _, _, err = client.Organizations.EditActionsPermissions(ctx, "\n", *input) return err }) + + testNewRequestAndDoFailure(t, methodName, client, func() (*Response, error) { + got, resp, err := client.Organizations.EditActionsPermissions(ctx, "o", *input) + if got != nil { + t.Errorf("testNewRequestAndDoFailure %v = %#v, want nil", methodName, got) + } + return resp, err + }) } diff --git a/github/orgs_hooks_test.go b/github/orgs_hooks_test.go index be6c7bb8ad..d4d4c54ebb 100644 --- a/github/orgs_hooks_test.go +++ b/github/orgs_hooks_test.go @@ -132,6 +132,14 @@ func TestOrganizationsService_GetHook(t *testing.T) { _, _, err = client.Organizations.GetHook(ctx, "\n", -1) return err }) + + testNewRequestAndDoFailure(t, methodName, client, func() (*Response, error) { + got, resp, err := client.Organizations.GetHook(ctx, "o", 1) + if got != nil { + t.Errorf("testNewRequestAndDoFailure %v = %#v, want nil", methodName, got) + } + return resp, err + }) } func TestOrganizationsService_GetHook_invalidOrg(t *testing.T) { @@ -177,6 +185,14 @@ func TestOrganizationsService_EditHook(t *testing.T) { _, _, err = client.Organizations.EditHook(ctx, "\n", -1, input) return err }) + + testNewRequestAndDoFailure(t, methodName, client, func() (*Response, error) { + got, resp, err := client.Organizations.EditHook(ctx, "o", 1, input) + if got != nil { + t.Errorf("testNewRequestAndDoFailure %v = %#v, want nil", methodName, got) + } + return resp, err + }) } func TestOrganizationsService_EditHook_invalidOrg(t *testing.T) { diff --git a/github/repos_contents_test.go b/github/repos_contents_test.go index befb2fadff..fc0a256533 100644 --- a/github/repos_contents_test.go +++ b/github/repos_contents_test.go @@ -717,6 +717,20 @@ func TestRepositoriesService_GetArchiveLink_StatusMovedPermanently_dontFollowRed } } +func TestRepositoriesService_GetArchiveLink_StatusMovedPermanently_missingLocation(t *testing.T) { + client, mux, _, teardown := setup() + defer teardown() + mux.HandleFunc("/repos/o/r/tarball", func(w http.ResponseWriter, r *http.Request) { + testMethod(t, r, "GET") + http.Redirect(w, r, "", http.StatusMovedPermanently) + }) + ctx := context.Background() + _, resp, _ := client.Repositories.GetArchiveLink(ctx, "o", "r", Tarball, &RepositoryContentGetOptions{}, false) + if resp.StatusCode != http.StatusMovedPermanently { + t.Errorf("Repositories.GetArchiveLink returned status: %d, want %d", resp.StatusCode, http.StatusMovedPermanently) + } +} + func TestRepositoriesService_GetArchiveLink_StatusMovedPermanently_followRedirects(t *testing.T) { client, mux, serverURL, teardown := setup() defer teardown() diff --git a/github/repos_test.go b/github/repos_test.go index 5739c10b6f..cbf56a2f7c 100644 --- a/github/repos_test.go +++ b/github/repos_test.go @@ -915,6 +915,21 @@ func TestRepositoriesService_GetBranch(t *testing.T) { }) } +func TestRepositoriesService_GetBranch_BadJSONResponse(t *testing.T) { + client, mux, _, teardown := setup() + defer teardown() + + mux.HandleFunc("/repos/o/r/branches/b", func(w http.ResponseWriter, r *http.Request) { + testMethod(t, r, "GET") + fmt.Fprint(w, `{"name":"n", "commit":{"sha":...truncated`) + }) + + ctx := context.Background() + if _, _, err := client.Repositories.GetBranch(ctx, "o", "r", "b", false); err == nil { + t.Error("Repositories.GetBranch returned no error; wanted JSON error") + } +} + func TestRepositoriesService_GetBranch_StatusMovedPermanently_followRedirects(t *testing.T) { client, mux, serverURL, teardown := setup() defer teardown() @@ -976,7 +991,7 @@ func TestRepositoriesService_GetBranch_notFound(t *testing.T) { const methodName = "GetBranch" testBadOptions(t, methodName, func() (err error) { - _, _, err = client.Repositories.GetBranch(ctx, "o", "r", "b", true) + _, _, err = client.Repositories.GetBranch(ctx, "\n", "\n", "\n", true) return err }) } From a3a5a8a94abc6139f2d4f3fa6dd7029938a479d4 Mon Sep 17 00:00:00 2001 From: Glenn Lewis <6598971+gmlewis@users.noreply.github.com> Date: Thu, 24 Mar 2022 15:01:09 -0400 Subject: [PATCH 05/10] Remove more code duplication --- github/github.go | 2 +- github/repos.go | 34 ++-------------------------------- 2 files changed, 3 insertions(+), 33 deletions(-) diff --git a/github/github.go b/github/github.go index afa90b0ed6..ac2d9d8b51 100644 --- a/github/github.go +++ b/github/github.go @@ -1302,10 +1302,10 @@ func (c *Client) getDownloadArtifactFromURL(ctx context.Context, u string, follo if err != nil { return nil, err } - resp.Body.Close() // If redirect response is returned, follow it if followRedirects && resp.StatusCode == http.StatusMovedPermanently { + resp.Body.Close() u = resp.Header.Get("Location") resp, err = c.getDownloadArtifactFromURL(ctx, u, false) if err != nil { diff --git a/github/repos.go b/github/repos.go index a0193f816b..517271ffe6 100644 --- a/github/repos.go +++ b/github/repos.go @@ -1064,7 +1064,8 @@ func (s *RepositoriesService) ListBranches(ctx context.Context, owner string, re func (s *RepositoriesService) GetBranch(ctx context.Context, owner, repo, branch string, followRedirects bool) (*Branch, *Response, error) { u := fmt.Sprintf("repos/%v/%v/branches/%v", owner, repo, branch) - resp, err := s.getBranchFromURL(ctx, u, followRedirects) + // the DownloadArtifact in this case is the branch. + resp, err := s.client.getDownloadArtifactFromURL(ctx, u, followRedirects) if err != nil { return nil, nil, err } @@ -1083,37 +1084,6 @@ func (s *RepositoriesService) GetBranch(ctx context.Context, owner, repo, branch return b, newResponse(resp), nil } -func (s *RepositoriesService) getBranchFromURL(ctx context.Context, u string, followRedirects bool) (*http.Response, error) { - req, err := s.client.NewRequest("GET", u, nil) - if err != nil { - return nil, err - } - - var resp *http.Response - // Use http.DefaultTransport if no custom Transport is configured - req = withContext(ctx, req) - if s.client.client.Transport == nil { - resp, err = http.DefaultTransport.RoundTrip(req) - } else { - resp, err = s.client.client.Transport.RoundTrip(req) - } - if err != nil { - return nil, err - } - - // If redirect response is returned, follow it - if followRedirects && resp.StatusCode == http.StatusMovedPermanently { - resp.Body.Close() - u = resp.Header.Get("Location") - resp, err = s.getBranchFromURL(ctx, u, false) - if err != nil { - return nil, err - } - } - - return resp, nil -} - // renameBranchRequest represents a request to rename a branch. type renameBranchRequest struct { NewName string `json:"new_name"` From ac6273e62a3691985f2d2cc31dfa07fea0e342c7 Mon Sep 17 00:00:00 2001 From: Glenn Lewis <6598971+gmlewis@users.noreply.github.com> Date: Thu, 24 Mar 2022 17:50:18 -0400 Subject: [PATCH 06/10] Improve code coverage --- github/actions_artifacts.go | 6 +- github/actions_artifacts_test.go | 20 +----- github/actions_workflow_jobs.go | 8 +-- github/actions_workflow_runs.go | 1 + github/activity_notifications_test.go | 4 +- github/gen-stringify-test.go | 53 ++++++++++++++- github/git_commits_test.go | 13 +++- github/github-stringify_test.go | 96 ++++++++++++++++++++++----- github/issue_import_test.go | 17 +++++ github/issues_test.go | 9 +++ github/orgs_packages_test.go | 2 +- github/repos_contents.go | 6 +- github/repos_contents_test.go | 14 ---- 13 files changed, 181 insertions(+), 68 deletions(-) diff --git a/github/actions_artifacts.go b/github/actions_artifacts.go index c18e69e00a..0350a2899d 100644 --- a/github/actions_artifacts.go +++ b/github/actions_artifacts.go @@ -120,11 +120,7 @@ func (s *ActionsService) DownloadArtifact(ctx context.Context, owner, repo strin } parsedURL, err := url.Parse(resp.Header.Get("Location")) - if err != nil { - return nil, newResponse(resp), err - } - - return parsedURL, newResponse(resp), nil + return parsedURL, newResponse(resp), err } // DeleteArtifact deletes a workflow run artifact. diff --git a/github/actions_artifacts_test.go b/github/actions_artifacts_test.go index bab6836943..e35a873bc0 100644 --- a/github/actions_artifacts_test.go +++ b/github/actions_artifacts_test.go @@ -25,7 +25,7 @@ func TestActionsService_ListArtifacts(t *testing.T) { testFormValues(t, r, values{"page": "2"}) fmt.Fprint(w, `{ - "total_count":1, + "total_count":1, "artifacts":[{"id":1}] }`, ) @@ -107,7 +107,7 @@ func TestActionsService_ListWorkflowRunArtifacts(t *testing.T) { testFormValues(t, r, values{"page": "2"}) fmt.Fprint(w, `{ - "total_count":1, + "total_count":1, "artifacts":[{"id":1}] }`, ) @@ -340,22 +340,6 @@ func TestActionsService_DownloadArtifact_StatusMovedPermanently_dontFollowRedire } } -func TestActionsService_DownloadArtifact_StatusMovedPermanently_missingLocation(t *testing.T) { - client, mux, _, teardown := setup() - defer teardown() - - mux.HandleFunc("/repos/o/r/actions/artifacts/1/zip", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - http.Redirect(w, r, "", http.StatusMovedPermanently) - }) - - ctx := context.Background() - _, resp, _ := client.Actions.DownloadArtifact(ctx, "o", "r", 1, false) - if resp.StatusCode != http.StatusMovedPermanently { - t.Errorf("Actions.DownloadArtifact return status %d, want %d", resp.StatusCode, http.StatusMovedPermanently) - } -} - func TestActionsService_DownloadArtifact_StatusMovedPermanently_followRedirects(t *testing.T) { client, mux, serverURL, teardown := setup() defer teardown() diff --git a/github/actions_workflow_jobs.go b/github/actions_workflow_jobs.go index 808d36dcd7..631ef1feb1 100644 --- a/github/actions_workflow_jobs.go +++ b/github/actions_workflow_jobs.go @@ -114,7 +114,7 @@ func (s *ActionsService) GetWorkflowJobByID(ctx context.Context, owner, repo str func (s *ActionsService) GetWorkflowJobLogs(ctx context.Context, owner, repo string, jobID int64, followRedirects bool) (*url.URL, *Response, error) { u := fmt.Sprintf("repos/%v/%v/actions/jobs/%v/logs", owner, repo, jobID) - // The DownloadArtifact in this case are the workflow logs. + // The DownloadArtifact in this case are the workflow logs URL. resp, err := s.client.getDownloadArtifactFromURL(ctx, u, followRedirects) if err != nil { return nil, nil, err @@ -125,9 +125,5 @@ func (s *ActionsService) GetWorkflowJobLogs(ctx context.Context, owner, repo str } parsedURL, err := url.Parse(resp.Header.Get("Location")) - if err != nil { - return nil, newResponse(resp), err - } - - return parsedURL, newResponse(resp), nil + return parsedURL, newResponse(resp), err } diff --git a/github/actions_workflow_runs.go b/github/actions_workflow_runs.go index 2571252ba8..fe49fcd219 100644 --- a/github/actions_workflow_runs.go +++ b/github/actions_workflow_runs.go @@ -240,6 +240,7 @@ func (s *ActionsService) GetWorkflowRunLogs(ctx context.Context, owner, repo str if resp.StatusCode != http.StatusFound { return nil, newResponse(resp), fmt.Errorf("unexpected status code: %s", resp.Status) } + parsedURL, err := url.Parse(resp.Header.Get("Location")) return parsedURL, newResponse(resp), err } diff --git a/github/activity_notifications_test.go b/github/activity_notifications_test.go index f46a12f474..fcd1cc3adc 100644 --- a/github/activity_notifications_test.go +++ b/github/activity_notifications_test.go @@ -59,7 +59,7 @@ func TestActivityService_ListNotification(t *testing.T) { }) } -func TestActivityService_ListRepositoryNotification(t *testing.T) { +func TestActivityService_ListRepositoryNotifications(t *testing.T) { client, mux, _, teardown := setup() defer teardown() @@ -81,7 +81,7 @@ func TestActivityService_ListRepositoryNotification(t *testing.T) { const methodName = "ListRepositoryNotifications" testBadOptions(t, methodName, func() (err error) { - _, _, err = client.Activity.ListRepositoryNotifications(ctx, "\n", "\n", nil) + _, _, err = client.Activity.ListRepositoryNotifications(ctx, "\n", "\n", &NotificationListOptions{}) return err }) diff --git a/github/gen-stringify-test.go b/github/gen-stringify-test.go index 0bd1f120be..b78edad97b 100644 --- a/github/gen-stringify-test.go +++ b/github/gen-stringify-test.go @@ -68,6 +68,12 @@ var ( return "github.Timestamp{0001-01-01 00:00:00 +0000 UTC}" case "nil": return "map[]" + case `[]int{0}`: + return `[0]` + case `[]string{""}`: + return `[""]` + case "[]Scope{ScopeNone}": + return `["(no scope)"]` } log.Fatalf("Unhandled zero value: %q", v) return "" @@ -144,7 +150,18 @@ func (t *templateData) processAST(f *ast.File) error { logf("Got FuncDecl: Name=%q, id.Name=%#v", fn.Name.Name, id.Name) t.StringFuncs[id.Name] = true } else { - logf("Ignoring FuncDecl: Name=%q, Type=%T", fn.Name.Name, fn.Recv.List[0].Type) + star, ok := fn.Recv.List[0].Type.(*ast.StarExpr) + if ok && fn.Name.Name == "String" { + id, ok := star.X.(*ast.Ident) + if ok { + logf("Got FuncDecl: Name=%q, id.Name=%#v", fn.Name.Name, id.Name) + t.StringFuncs[id.Name] = true + } else { + logf("Ignoring FuncDecl: Name=%q, Type=%T", fn.Name.Name, fn.Recv.List[0].Type) + } + } else { + logf("Ignoring FuncDecl: Name=%q, Type=%T", fn.Name.Name, fn.Recv.List[0].Type) + } } } else { logf("Ignoring FuncDecl: Name=%q, fn=%#v", fn.Name.Name, fn) @@ -157,6 +174,7 @@ func (t *templateData) processAST(f *ast.File) error { logf("Ignoring AST decl type %T", decl) continue } + for _, spec := range gd.Specs { ts, ok := spec.(*ast.TypeSpec) if !ok { @@ -188,6 +206,13 @@ func (t *templateData) processAST(f *ast.File) error { continue } + if at, ok := field.Type.(*ast.ArrayType); ok { + if id, ok := at.Elt.(*ast.Ident); ok { + t.addIdentSlice(id, ts.Name.String(), fieldName.String()) + continue + } + } + se, ok := field.Type.(*ast.StarExpr) if !ok { logf("Ignoring type %T for Name=%q, FieldName=%q", field.Type, ts.Name.String(), fieldName.String()) @@ -272,6 +297,32 @@ func (t *templateData) addIdentPtr(x *ast.Ident, receiverType, fieldName string) t.StructFields[receiverType] = append(t.StructFields[receiverType], newStructField(receiverType, fieldName, x.String(), zeroValue, namedStruct)) } +func (t *templateData) addIdentSlice(x *ast.Ident, receiverType, fieldName string) { + var zeroValue string + var namedStruct = false + switch x.String() { + case "int": + zeroValue = "[]int{0}" + case "int64": + zeroValue = "[]int64{0}" + case "float64": + zeroValue = "[]float64{0}" + case "string": + zeroValue = `[]string{""}` + case "bool": + zeroValue = "[]bool{false}" + case "Scope": + zeroValue = "[]Scope{ScopeNone}" + // case "Timestamp": + // zeroValue = "&Timestamp{}" + default: + zeroValue = "nil" + namedStruct = true + } + + t.StructFields[receiverType] = append(t.StructFields[receiverType], newStructField(receiverType, fieldName, x.String(), zeroValue, namedStruct)) +} + func (t *templateData) dump() error { if len(t.StructFields) == 0 { logf("No StructFields for %v; skipping.", t.filename) diff --git a/github/git_commits_test.go b/github/git_commits_test.go index c73ff09a01..cc9cc3fcbd 100644 --- a/github/git_commits_test.go +++ b/github/git_commits_test.go @@ -285,7 +285,18 @@ func TestGitService_CreateSignedCommitWithInvalidParams(t *testing.T) { ctx := context.Background() _, _, err := client.Git.CreateCommit(ctx, "o", "r", input) if err == nil { - t.Errorf("Expected error to be returned because invalid params was passed") + t.Errorf("Expected error to be returned because invalid params were passed") + } +} + +func TestGitService_CreateSignedCommitWithNilCommit(t *testing.T) { + client, _, _, teardown := setup() + defer teardown() + + ctx := context.Background() + _, _, err := client.Git.CreateCommit(ctx, "o", "r", nil) + if err == nil { + t.Errorf("Expected error to be returned because commit=nil") } } diff --git a/github/github-stringify_test.go b/github/github-stringify_test.go index c5bbca9d9e..62af2a34fd 100644 --- a/github/github-stringify_test.go +++ b/github/github-stringify_test.go @@ -17,8 +17,9 @@ func TestActionsAllowed_String(t *testing.T) { v := ActionsAllowed{ GithubOwnedAllowed: Bool(false), VerifiedAllowed: Bool(false), + PatternsAllowed: []string{""}, } - want := `github.ActionsAllowed{GithubOwnedAllowed:false, VerifiedAllowed:false}` + want := `github.ActionsAllowed{GithubOwnedAllowed:false, VerifiedAllowed:false, PatternsAllowed:[""]}` if got := v.String(); got != want { t.Errorf("ActionsAllowed.String = %v, want %v", got, want) } @@ -69,6 +70,7 @@ func TestAuthorization_String(t *testing.T) { v := Authorization{ ID: Int64(0), URL: String(""), + Scopes: []Scope{ScopeNone}, Token: String(""), TokenLastEight: String(""), HashedToken: String(""), @@ -80,7 +82,7 @@ func TestAuthorization_String(t *testing.T) { Fingerprint: String(""), User: &User{}, } - want := `github.Authorization{ID:0, URL:"", Token:"", TokenLastEight:"", HashedToken:"", App:github.AuthorizationApp{}, Note:"", NoteURL:"", UpdatedAt:github.Timestamp{0001-01-01 00:00:00 +0000 UTC}, CreatedAt:github.Timestamp{0001-01-01 00:00:00 +0000 UTC}, Fingerprint:"", User:github.User{}}` + want := `github.Authorization{ID:0, URL:"", Scopes:["(no scope)"], Token:"", TokenLastEight:"", HashedToken:"", App:github.AuthorizationApp{}, Note:"", NoteURL:"", UpdatedAt:github.Timestamp{0001-01-01 00:00:00 +0000 UTC}, CreatedAt:github.Timestamp{0001-01-01 00:00:00 +0000 UTC}, Fingerprint:"", User:github.User{}}` if got := v.String(); got != want { t.Errorf("Authorization.String = %v, want %v", got, want) } @@ -100,13 +102,14 @@ func TestAuthorizationApp_String(t *testing.T) { func TestAuthorizationRequest_String(t *testing.T) { v := AuthorizationRequest{ + Scopes: []Scope{ScopeNone}, Note: String(""), NoteURL: String(""), ClientID: String(""), ClientSecret: String(""), Fingerprint: String(""), } - want := `github.AuthorizationRequest{Note:"", NoteURL:"", ClientID:"", ClientSecret:"", Fingerprint:""}` + want := `github.AuthorizationRequest{Scopes:["(no scope)"], Note:"", NoteURL:"", ClientID:"", ClientSecret:"", Fingerprint:""}` if got := v.String(); got != want { t.Errorf("AuthorizationRequest.String = %v, want %v", got, want) } @@ -114,11 +117,14 @@ func TestAuthorizationRequest_String(t *testing.T) { func TestAuthorizationUpdateRequest_String(t *testing.T) { v := AuthorizationUpdateRequest{ - Note: String(""), - NoteURL: String(""), - Fingerprint: String(""), + Scopes: []string{""}, + AddScopes: []string{""}, + RemoveScopes: []string{""}, + Note: String(""), + NoteURL: String(""), + Fingerprint: String(""), } - want := `github.AuthorizationUpdateRequest{Note:"", NoteURL:"", Fingerprint:""}` + want := `github.AuthorizationUpdateRequest{Scopes:[""], AddScopes:[""], RemoveScopes:[""], Note:"", NoteURL:"", Fingerprint:""}` if got := v.String(); got != want { t.Errorf("AuthorizationUpdateRequest.String = %v, want %v", got, want) } @@ -171,6 +177,19 @@ func TestCheckSuite_String(t *testing.T) { } } +func TestCodeOfConduct_String(t *testing.T) { + v := CodeOfConduct{ + Name: String(""), + Key: String(""), + URL: String(""), + Body: String(""), + } + want := `github.CodeOfConduct{Name:"", Key:"", URL:"", Body:""}` + if got := v.String(); got != want { + t.Errorf("CodeOfConduct.String = %v, want %v", got, want) + } +} + func TestCodeResult_String(t *testing.T) { v := CodeResult{ Name: String(""), @@ -516,8 +535,9 @@ func TestGrant_String(t *testing.T) { App: &AuthorizationApp{}, CreatedAt: &Timestamp{}, UpdatedAt: &Timestamp{}, + Scopes: []string{""}, } - want := `github.Grant{ID:0, URL:"", App:github.AuthorizationApp{}, CreatedAt:github.Timestamp{0001-01-01 00:00:00 +0000 UTC}, UpdatedAt:github.Timestamp{0001-01-01 00:00:00 +0000 UTC}}` + want := `github.Grant{ID:0, URL:"", App:github.AuthorizationApp{}, CreatedAt:github.Timestamp{0001-01-01 00:00:00 +0000 UTC}, UpdatedAt:github.Timestamp{0001-01-01 00:00:00 +0000 UTC}, Scopes:[""]}` if got := v.String(); got != want { t.Errorf("Grant.String = %v, want %v", got, want) } @@ -534,8 +554,11 @@ func TestHeadCommit_String(t *testing.T) { TreeID: String(""), Timestamp: &Timestamp{}, Committer: &CommitAuthor{}, + Added: []string{""}, + Removed: []string{""}, + Modified: []string{""}, } - want := `github.HeadCommit{Message:"", Author:github.CommitAuthor{}, URL:"", Distinct:false, SHA:"", ID:"", TreeID:"", Timestamp:github.Timestamp{0001-01-01 00:00:00 +0000 UTC}, Committer:github.CommitAuthor{}}` + want := `github.HeadCommit{Message:"", Author:github.CommitAuthor{}, URL:"", Distinct:false, SHA:"", ID:"", TreeID:"", Timestamp:github.Timestamp{0001-01-01 00:00:00 +0000 UTC}, Committer:github.CommitAuthor{}, Added:[""], Removed:[""], Modified:[""]}` if got := v.String(); got != want { t.Errorf("HeadCommit.String = %v, want %v", got, want) } @@ -549,9 +572,10 @@ func TestHook_String(t *testing.T) { Name: String(""), TestURL: String(""), PingURL: String(""), + Events: []string{""}, Active: Bool(false), } - want := `github.Hook{URL:"", ID:0, Type:"", Name:"", TestURL:"", PingURL:"", Active:false}` + want := `github.Hook{URL:"", ID:0, Type:"", Name:"", TestURL:"", PingURL:"", Events:[""], Active:false}` if got := v.String(); got != want { t.Errorf("Hook.String = %v, want %v", got, want) } @@ -636,6 +660,8 @@ func TestInstallation_String(t *testing.T) { TargetType: String(""), SingleFileName: String(""), RepositorySelection: String(""), + Events: []string{""}, + SingleFilePaths: []string{""}, Permissions: &InstallationPermissions{}, CreatedAt: &Timestamp{}, UpdatedAt: &Timestamp{}, @@ -643,7 +669,7 @@ func TestInstallation_String(t *testing.T) { SuspendedBy: &User{}, SuspendedAt: &Timestamp{}, } - want := `github.Installation{ID:0, NodeID:"", AppID:0, AppSlug:"", TargetID:0, Account:github.User{}, AccessTokensURL:"", RepositoriesURL:"", HTMLURL:"", TargetType:"", SingleFileName:"", RepositorySelection:"", Permissions:github.InstallationPermissions{}, CreatedAt:github.Timestamp{0001-01-01 00:00:00 +0000 UTC}, UpdatedAt:github.Timestamp{0001-01-01 00:00:00 +0000 UTC}, HasMultipleSingleFiles:false, SuspendedBy:github.User{}, SuspendedAt:github.Timestamp{0001-01-01 00:00:00 +0000 UTC}}` + want := `github.Installation{ID:0, NodeID:"", AppID:0, AppSlug:"", TargetID:0, Account:github.User{}, AccessTokensURL:"", RepositoriesURL:"", HTMLURL:"", TargetType:"", SingleFileName:"", RepositorySelection:"", Events:[""], SingleFilePaths:[""], Permissions:github.InstallationPermissions{}, CreatedAt:github.Timestamp{0001-01-01 00:00:00 +0000 UTC}, UpdatedAt:github.Timestamp{0001-01-01 00:00:00 +0000 UTC}, HasMultipleSingleFiles:false, SuspendedBy:github.User{}, SuspendedAt:github.Timestamp{0001-01-01 00:00:00 +0000 UTC}}` if got := v.String(); got != want { t.Errorf("Installation.String = %v, want %v", got, want) } @@ -878,12 +904,14 @@ func TestNewTeam_String(t *testing.T) { v := NewTeam{ Name: "", Description: String(""), + Maintainers: []string{""}, + RepoNames: []string{""}, ParentTeamID: Int64(0), Permission: String(""), Privacy: String(""), LDAPDN: String(""), } - want := `github.NewTeam{Name:"", Description:"", ParentTeamID:0, Permission:"", Privacy:"", LDAPDN:""}` + want := `github.NewTeam{Name:"", Description:"", Maintainers:[""], RepoNames:[""], ParentTeamID:0, Permission:"", Privacy:"", LDAPDN:""}` if got := v.String(); got != want { t.Errorf("NewTeam.String = %v, want %v", got, want) } @@ -990,6 +1018,16 @@ func TestPackage_String(t *testing.T) { } } +func TestPackageContainerMetadata_String(t *testing.T) { + v := PackageContainerMetadata{ + Tags: []string{""}, + } + want := `github.PackageContainerMetadata{Tags:[""]}` + if got := v.String(); got != want { + t.Errorf("PackageContainerMetadata.String = %v, want %v", got, want) + } +} + func TestPackageFile_String(t *testing.T) { v := PackageFile{ DownloadURL: String(""), @@ -1458,6 +1496,7 @@ func TestRepository_String(t *testing.T) { AllowAutoMerge: Bool(false), AllowForking: Bool(false), DeleteBranchOnMerge: Bool(false), + Topics: []string{""}, Archived: Bool(false), Disabled: Bool(false), License: &License{}, @@ -1511,7 +1550,7 @@ func TestRepository_String(t *testing.T) { TeamsURL: String(""), Visibility: String(""), } - want := `github.Repository{ID:0, NodeID:"", Owner:github.User{}, Name:"", FullName:"", Description:"", Homepage:"", CodeOfConduct:github.CodeOfConduct{}, DefaultBranch:"", MasterBranch:"", CreatedAt:github.Timestamp{0001-01-01 00:00:00 +0000 UTC}, PushedAt:github.Timestamp{0001-01-01 00:00:00 +0000 UTC}, UpdatedAt:github.Timestamp{0001-01-01 00:00:00 +0000 UTC}, HTMLURL:"", CloneURL:"", GitURL:"", MirrorURL:"", SSHURL:"", SVNURL:"", Language:"", Fork:false, ForksCount:0, NetworkCount:0, OpenIssuesCount:0, OpenIssues:0, StargazersCount:0, SubscribersCount:0, WatchersCount:0, Watchers:0, Size:0, AutoInit:false, Parent:github.Repository{}, Source:github.Repository{}, TemplateRepository:github.Repository{}, Organization:github.Organization{}, AllowRebaseMerge:false, AllowUpdateBranch:false, AllowSquashMerge:false, AllowMergeCommit:false, AllowAutoMerge:false, AllowForking:false, DeleteBranchOnMerge:false, Archived:false, Disabled:false, License:github.License{}, Private:false, HasIssues:false, HasWiki:false, HasPages:false, HasProjects:false, HasDownloads:false, IsTemplate:false, LicenseTemplate:"", GitignoreTemplate:"", SecurityAndAnalysis:github.SecurityAndAnalysis{}, TeamID:0, URL:"", ArchiveURL:"", AssigneesURL:"", BlobsURL:"", BranchesURL:"", CollaboratorsURL:"", CommentsURL:"", CommitsURL:"", CompareURL:"", ContentsURL:"", ContributorsURL:"", DeploymentsURL:"", DownloadsURL:"", EventsURL:"", ForksURL:"", GitCommitsURL:"", GitRefsURL:"", GitTagsURL:"", HooksURL:"", IssueCommentURL:"", IssueEventsURL:"", IssuesURL:"", KeysURL:"", LabelsURL:"", LanguagesURL:"", MergesURL:"", MilestonesURL:"", NotificationsURL:"", PullsURL:"", ReleasesURL:"", StargazersURL:"", StatusesURL:"", SubscribersURL:"", SubscriptionURL:"", TagsURL:"", TreesURL:"", TeamsURL:"", Visibility:""}` + want := `github.Repository{ID:0, NodeID:"", Owner:github.User{}, Name:"", FullName:"", Description:"", Homepage:"", CodeOfConduct:github.CodeOfConduct{}, DefaultBranch:"", MasterBranch:"", CreatedAt:github.Timestamp{0001-01-01 00:00:00 +0000 UTC}, PushedAt:github.Timestamp{0001-01-01 00:00:00 +0000 UTC}, UpdatedAt:github.Timestamp{0001-01-01 00:00:00 +0000 UTC}, HTMLURL:"", CloneURL:"", GitURL:"", MirrorURL:"", SSHURL:"", SVNURL:"", Language:"", Fork:false, ForksCount:0, NetworkCount:0, OpenIssuesCount:0, OpenIssues:0, StargazersCount:0, SubscribersCount:0, WatchersCount:0, Watchers:0, Size:0, AutoInit:false, Parent:github.Repository{}, Source:github.Repository{}, TemplateRepository:github.Repository{}, Organization:github.Organization{}, AllowRebaseMerge:false, AllowUpdateBranch:false, AllowSquashMerge:false, AllowMergeCommit:false, AllowAutoMerge:false, AllowForking:false, DeleteBranchOnMerge:false, Topics:[""], Archived:false, Disabled:false, License:github.License{}, Private:false, HasIssues:false, HasWiki:false, HasPages:false, HasProjects:false, HasDownloads:false, IsTemplate:false, LicenseTemplate:"", GitignoreTemplate:"", SecurityAndAnalysis:github.SecurityAndAnalysis{}, TeamID:0, URL:"", ArchiveURL:"", AssigneesURL:"", BlobsURL:"", BranchesURL:"", CollaboratorsURL:"", CommentsURL:"", CommitsURL:"", CompareURL:"", ContentsURL:"", ContributorsURL:"", DeploymentsURL:"", DownloadsURL:"", EventsURL:"", ForksURL:"", GitCommitsURL:"", GitRefsURL:"", GitTagsURL:"", HooksURL:"", IssueCommentURL:"", IssueEventsURL:"", IssuesURL:"", KeysURL:"", LabelsURL:"", LanguagesURL:"", MergesURL:"", MilestonesURL:"", NotificationsURL:"", PullsURL:"", ReleasesURL:"", StargazersURL:"", StatusesURL:"", SubscribersURL:"", SubscriptionURL:"", TagsURL:"", TreesURL:"", TeamsURL:"", Visibility:""}` if got := v.String(); got != want { t.Errorf("Repository.String = %v, want %v", got, want) } @@ -1596,6 +1635,17 @@ func TestRepositoryLicense_String(t *testing.T) { } } +func TestRepositoryParticipation_String(t *testing.T) { + v := RepositoryParticipation{ + All: []int{0}, + Owner: []int{0}, + } + want := `github.RepositoryParticipation{All:[0], Owner:[0]}` + if got := v.String(); got != want { + t.Errorf("RepositoryParticipation.String = %v, want %v", got, want) + } +} + func TestRepositoryRelease_String(t *testing.T) { v := RepositoryRelease{ TagName: String(""), @@ -1645,6 +1695,18 @@ func TestSecurityAndAnalysis_String(t *testing.T) { } } +func TestServiceHook_String(t *testing.T) { + v := ServiceHook{ + Name: String(""), + Events: []string{""}, + SupportedEvents: []string{""}, + } + want := `github.ServiceHook{Name:"", Events:[""], SupportedEvents:[""]}` + if got := v.String(); got != want { + t.Errorf("ServiceHook.String = %v, want %v", got, want) + } +} + func TestSourceImportAuthor_String(t *testing.T) { v := SourceImportAuthor{ ID: Int64(0), @@ -1891,13 +1953,16 @@ func TestWebHookAuthor_String(t *testing.T) { func TestWebHookCommit_String(t *testing.T) { v := WebHookCommit{ + Added: []string{""}, Author: &WebHookAuthor{}, Committer: &WebHookAuthor{}, Distinct: Bool(false), ID: String(""), Message: String(""), + Modified: []string{""}, + Removed: []string{""}, } - want := `github.WebHookCommit{Author:github.WebHookAuthor{}, Committer:github.WebHookAuthor{}, Distinct:false, ID:"", Message:""}` + want := `github.WebHookCommit{Added:[""], Author:github.WebHookAuthor{}, Committer:github.WebHookAuthor{}, Distinct:false, ID:"", Message:"", Modified:[""], Removed:[""]}` if got := v.String(); got != want { t.Errorf("WebHookCommit.String = %v, want %v", got, want) } @@ -1928,10 +1993,11 @@ func TestWebHookPayload_String(t *testing.T) { func TestWeeklyCommitActivity_String(t *testing.T) { v := WeeklyCommitActivity{ + Days: []int{0}, Total: Int(0), Week: &Timestamp{}, } - want := `github.WeeklyCommitActivity{Total:0, Week:github.Timestamp{0001-01-01 00:00:00 +0000 UTC}}` + want := `github.WeeklyCommitActivity{Days:[0], Total:0, Week:github.Timestamp{0001-01-01 00:00:00 +0000 UTC}}` if got := v.String(); got != want { t.Errorf("WeeklyCommitActivity.String = %v, want %v", got, want) } diff --git a/github/issue_import_test.go b/github/issue_import_test.go index 82b9f9c2d7..3533b3ab4b 100644 --- a/github/issue_import_test.go +++ b/github/issue_import_test.go @@ -167,6 +167,23 @@ func TestIssueImportService_CheckStatusSince(t *testing.T) { }) } +func TestIssueImportService_CheckStatusSince_badResponse(t *testing.T) { + client, mux, _, teardown := setup() + defer teardown() + + mux.HandleFunc("/repos/o/r/import/issues", func(w http.ResponseWriter, r *http.Request) { + testMethod(t, r, "GET") + testHeader(t, r, "Accept", mediaTypeIssueImportAPI) + w.WriteHeader(http.StatusOK) + w.Write([]byte("{badly-formed JSON")) + }) + + ctx := context.Background() + if _, _, err := client.IssueImport.CheckStatusSince(ctx, "o", "r", time.Now()); err == nil { + t.Errorf("CheckStatusSince returned no error, want JSON err") + } +} + func TestIssueImportService_CheckStatusSince_invalidOwner(t *testing.T) { client, _, _, teardown := setup() defer teardown() diff --git a/github/issues_test.go b/github/issues_test.go index 3ed7390f5f..e2cf063914 100644 --- a/github/issues_test.go +++ b/github/issues_test.go @@ -129,6 +129,15 @@ func TestIssuesService_ListByOrg_invalidOrg(t *testing.T) { testURLParseError(t, err) } +func TestIssuesService_ListByOrg_badOrg(t *testing.T) { + client, _, _, teardown := setup() + defer teardown() + + ctx := context.Background() + _, _, err := client.Issues.ListByOrg(ctx, "\n", nil) + testURLParseError(t, err) +} + func TestIssuesService_ListByRepo(t *testing.T) { client, mux, _, teardown := setup() defer teardown() diff --git a/github/orgs_packages_test.go b/github/orgs_packages_test.go index bbe223b8de..f8c8701d30 100644 --- a/github/orgs_packages_test.go +++ b/github/orgs_packages_test.go @@ -181,7 +181,7 @@ func TestOrganizationsService_DeletePackage(t *testing.T) { const methodName = "DeletePackage" testBadOptions(t, methodName, func() (err error) { - _, _, err = client.Organizations.GetPackage(ctx, "\n", "", "") + _, _, err = client.Organizations.GetPackage(ctx, "\n", "\n", "\n") return err }) diff --git a/github/repos_contents.go b/github/repos_contents.go index a98f2ae866..eaf18d8630 100644 --- a/github/repos_contents.go +++ b/github/repos_contents.go @@ -318,9 +318,5 @@ func (s *RepositoriesService) GetArchiveLink(ctx context.Context, owner, repo st } parsedURL, err := url.Parse(resp.Header.Get("Location")) - if err != nil { - return nil, newResponse(resp), err - } - - return parsedURL, newResponse(resp), nil + return parsedURL, newResponse(resp), err } diff --git a/github/repos_contents_test.go b/github/repos_contents_test.go index fc0a256533..befb2fadff 100644 --- a/github/repos_contents_test.go +++ b/github/repos_contents_test.go @@ -717,20 +717,6 @@ func TestRepositoriesService_GetArchiveLink_StatusMovedPermanently_dontFollowRed } } -func TestRepositoriesService_GetArchiveLink_StatusMovedPermanently_missingLocation(t *testing.T) { - client, mux, _, teardown := setup() - defer teardown() - mux.HandleFunc("/repos/o/r/tarball", func(w http.ResponseWriter, r *http.Request) { - testMethod(t, r, "GET") - http.Redirect(w, r, "", http.StatusMovedPermanently) - }) - ctx := context.Background() - _, resp, _ := client.Repositories.GetArchiveLink(ctx, "o", "r", Tarball, &RepositoryContentGetOptions{}, false) - if resp.StatusCode != http.StatusMovedPermanently { - t.Errorf("Repositories.GetArchiveLink returned status: %d, want %d", resp.StatusCode, http.StatusMovedPermanently) - } -} - func TestRepositoriesService_GetArchiveLink_StatusMovedPermanently_followRedirects(t *testing.T) { client, mux, serverURL, teardown := setup() defer teardown() From a15634eccbfe0a746fac1e36d569939e8322652f Mon Sep 17 00:00:00 2001 From: Glenn Lewis <6598971+gmlewis@users.noreply.github.com> Date: Thu, 24 Mar 2022 22:56:54 -0400 Subject: [PATCH 07/10] Remove unused method --- github/github.go | 31 ------------------------------- 1 file changed, 31 deletions(-) diff --git a/github/github.go b/github/github.go index 73d2fc7413..080a8794dd 100644 --- a/github/github.go +++ b/github/github.go @@ -1285,37 +1285,6 @@ func formatRateReset(d time.Duration) string { return fmt.Sprintf("[rate reset in %v]", timeString) } -func (c *Client) getDownloadArtifactFromURL(ctx context.Context, u string, followRedirects bool) (*http.Response, error) { - req, err := c.NewRequest("GET", u, nil) - if err != nil { - return nil, err - } - - var resp *http.Response - // Use http.DefaultTransport if no custom Transport is configured - req = withContext(ctx, req) - if c.client.Transport == nil { - resp, err = http.DefaultTransport.RoundTrip(req) - } else { - resp, err = c.client.Transport.RoundTrip(req) - } - if err != nil { - return nil, err - } - - // If redirect response is returned, follow it - if followRedirects && resp.StatusCode == http.StatusMovedPermanently { - resp.Body.Close() - u = resp.Header.Get("Location") - resp, err = c.getDownloadArtifactFromURL(ctx, u, false) - if err != nil { - return resp, err - } - } - - return resp, nil -} - // When using roundTripWithOptionalFollowRedirect, note that it // is the responsibility of the caller to close the response body. func (c *Client) roundTripWithOptionalFollowRedirect(ctx context.Context, u string, followRedirects bool) (*http.Response, error) { From 40cf2af12f3b9dd7da12d2693f4393b735f9267e Mon Sep 17 00:00:00 2001 From: Glenn Lewis <6598971+gmlewis@users.noreply.github.com> Date: Thu, 24 Mar 2022 23:04:55 -0400 Subject: [PATCH 08/10] Revert parseBoolResponse changes --- github/activity_star.go | 6 +----- github/gists.go | 6 +----- github/issues_assignees.go | 6 +----- github/orgs_members.go | 12 ++---------- github/orgs_users_blocking.go | 6 +----- github/pulls.go | 6 +----- github/repos.go | 6 +----- 7 files changed, 8 insertions(+), 40 deletions(-) diff --git a/github/activity_star.go b/github/activity_star.go index e38d559cff..d17ea9c3f2 100644 --- a/github/activity_star.go +++ b/github/activity_star.go @@ -111,11 +111,7 @@ func (s *ActivityService) IsStarred(ctx context.Context, owner, repo string) (bo resp, err := s.client.Do(ctx, req, nil) starred, err := parseBoolResponse(err) - if err != nil { - return false, resp, err - } - - return starred, resp, nil + return starred, resp, err } // Star a repository as the authenticated user. diff --git a/github/gists.go b/github/gists.go index d022b2722c..40a4aaf581 100644 --- a/github/gists.go +++ b/github/gists.go @@ -321,11 +321,7 @@ func (s *GistsService) IsStarred(ctx context.Context, id string) (bool, *Respons resp, err := s.client.Do(ctx, req, nil) starred, err := parseBoolResponse(err) - if err != nil { - return false, resp, err - } - - return starred, resp, nil + return starred, resp, err } // Fork a gist. diff --git a/github/issues_assignees.go b/github/issues_assignees.go index 662dde87bd..34e0bb506f 100644 --- a/github/issues_assignees.go +++ b/github/issues_assignees.go @@ -47,11 +47,7 @@ func (s *IssuesService) IsAssignee(ctx context.Context, owner, repo, user string resp, err := s.client.Do(ctx, req, nil) assignee, err := parseBoolResponse(err) - if err != nil { - return false, resp, err - } - - return assignee, resp, nil + return assignee, resp, err } // AddAssignees adds the provided GitHub users as assignees to the issue. diff --git a/github/orgs_members.go b/github/orgs_members.go index eacb978e1f..dd4845441f 100644 --- a/github/orgs_members.go +++ b/github/orgs_members.go @@ -111,11 +111,7 @@ func (s *OrganizationsService) IsMember(ctx context.Context, org, user string) ( resp, err := s.client.Do(ctx, req, nil) member, err := parseBoolResponse(err) - if err != nil { - return false, resp, err - } - - return member, resp, nil + return member, resp, err } // IsPublicMember checks if a user is a public member of an organization. @@ -130,11 +126,7 @@ func (s *OrganizationsService) IsPublicMember(ctx context.Context, org, user str resp, err := s.client.Do(ctx, req, nil) member, err := parseBoolResponse(err) - if err != nil { - return false, resp, err - } - - return member, resp, nil + return member, resp, err } // RemoveMember removes a user from all teams of an organization. diff --git a/github/orgs_users_blocking.go b/github/orgs_users_blocking.go index 74d34dde82..2773344c9f 100644 --- a/github/orgs_users_blocking.go +++ b/github/orgs_users_blocking.go @@ -53,11 +53,7 @@ func (s *OrganizationsService) IsBlocked(ctx context.Context, org string, user s resp, err := s.client.Do(ctx, req, nil) isBlocked, err := parseBoolResponse(err) - if err != nil { - return false, resp, err - } - - return isBlocked, resp, nil + return isBlocked, resp, err } // BlockUser blocks specified user from an organization. diff --git a/github/pulls.go b/github/pulls.go index 277a5f3b1e..37fb7413a4 100644 --- a/github/pulls.go +++ b/github/pulls.go @@ -423,11 +423,7 @@ func (s *PullRequestsService) IsMerged(ctx context.Context, owner string, repo s resp, err := s.client.Do(ctx, req, nil) merged, err := parseBoolResponse(err) - if err != nil { - return false, resp, err - } - - return merged, resp, nil + return merged, resp, err } // PullRequestMergeResult represents the result of merging a pull request. diff --git a/github/repos.go b/github/repos.go index b6a7e63b87..49a64ee730 100644 --- a/github/repos.go +++ b/github/repos.go @@ -617,11 +617,7 @@ func (s *RepositoriesService) GetVulnerabilityAlerts(ctx context.Context, owner, resp, err := s.client.Do(ctx, req, nil) vulnerabilityAlertsEnabled, err := parseBoolResponse(err) - if err != nil { - return false, resp, err - } - - return vulnerabilityAlertsEnabled, resp, nil + return vulnerabilityAlertsEnabled, resp, err } // EnableVulnerabilityAlerts enables vulnerability alerts and the dependency graph for a repository. From 5bf4843dcc394afccd03b095749c095b686dfe36 Mon Sep 17 00:00:00 2001 From: Glenn Lewis <6598971+gmlewis@users.noreply.github.com> Date: Thu, 24 Mar 2022 23:09:22 -0400 Subject: [PATCH 09/10] Revert parseBoolResponse changes --- github/repos_collaborators.go | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/github/repos_collaborators.go b/github/repos_collaborators.go index 802163243d..dcb97b5ed2 100644 --- a/github/repos_collaborators.go +++ b/github/repos_collaborators.go @@ -78,11 +78,7 @@ func (s *RepositoriesService) IsCollaborator(ctx context.Context, owner, repo, u resp, err := s.client.Do(ctx, req, nil) isCollab, err := parseBoolResponse(err) - if err != nil { - return false, resp, err - } - - return isCollab, resp, nil + return isCollab, resp, err } // RepositoryPermissionLevel represents the permission level an organization From 977aa72ba4f0f748854ead6aed86302d352b45dd Mon Sep 17 00:00:00 2001 From: Glenn Lewis <6598971+gmlewis@users.noreply.github.com> Date: Thu, 24 Mar 2022 23:12:37 -0400 Subject: [PATCH 10/10] Revert parseBoolResponse changes --- github/users_blocking.go | 6 +----- github/users_followers.go | 6 +----- 2 files changed, 2 insertions(+), 10 deletions(-) diff --git a/github/users_blocking.go b/github/users_blocking.go index f494dfbe8c..cdbc2c2532 100644 --- a/github/users_blocking.go +++ b/github/users_blocking.go @@ -53,11 +53,7 @@ func (s *UsersService) IsBlocked(ctx context.Context, user string) (bool, *Respo resp, err := s.client.Do(ctx, req, nil) isBlocked, err := parseBoolResponse(err) - if err != nil { - return false, resp, err - } - - return isBlocked, resp, nil + return isBlocked, resp, err } // BlockUser blocks specified user for the authenticated user. diff --git a/github/users_followers.go b/github/users_followers.go index 41a696514e..f26392b6e2 100644 --- a/github/users_followers.go +++ b/github/users_followers.go @@ -92,11 +92,7 @@ func (s *UsersService) IsFollowing(ctx context.Context, user, target string) (bo resp, err := s.client.Do(ctx, req, nil) following, err := parseBoolResponse(err) - if err != nil { - return false, resp, err - } - - return following, resp, nil + return following, resp, err } // Follow will cause the authenticated user to follow the specified user.