Skip to content

Commit

Permalink
fix: get user teams with GitHub GraphQL API (runatlantis#2045)
Browse files Browse the repository at this point in the history
  • Loading branch information
raymondchen625 authored and krrrr38 committed Dec 16, 2022
1 parent 096f06f commit 99338a1
Showing 1 changed file with 29 additions and 16 deletions.
45 changes: 29 additions & 16 deletions server/events/vcs/github_client.go
Original file line number Diff line number Diff line change
Expand Up @@ -407,30 +407,43 @@ func (g *GithubClient) MarkdownPullLink(pull models.PullRequest) (string, error)
}

// GetTeamNamesForUser returns the names of the teams or groups that the user belongs to (in the organization the repository belongs to).
// https://developer.github.com/v3/teams/members/#get-team-membership
// https://docs.github.com/en/graphql/reference/objects#organization
func (g *GithubClient) GetTeamNamesForUser(repo models.Repo, user models.User) ([]string, error) {
orgName := repo.Owner
variables := map[string]interface{}{
"orgName": githubv4.String(orgName),
"userLogins": []githubv4.String{githubv4.String(user.Username)},
"teamCursor": (*githubv4.String)(nil),
}
var q struct {
Organization struct {
Teams struct {
Edges []struct {
Node struct {
Name string
}
}
PageInfo struct {
EndCursor githubv4.String
HasNextPage bool
}
} `graphql:"teams(first:100, after: $teamCursor, userLogins: $userLogins)"`
} `graphql:"organization(login: $orgName)"`
}
var teamNames []string
opts := &github.ListOptions{}
org := repo.Owner
ctx := context.Background()
for {
teams, resp, err := g.client.Teams.ListTeams(g.ctx, org, opts)
err := g.v4MutateClient.Query(ctx, &q, variables)
if err != nil {
return nil, errors.Wrap(err, "retrieving GitHub teams")
return nil, err
}
for _, t := range teams {
membership, _, err := g.client.Teams.GetTeamMembershipBySlug(g.ctx, org, *t.Slug, user.Username)
if err != nil {
g.logger.Err("Failed to get team membership from GitHub: %s", err)
} else if membership != nil {
if *membership.State == "active" && (*membership.Role == "member" || *membership.Role == "maintainer") {
teamNames = append(teamNames, t.GetName())
}
}
for _, edge := range q.Organization.Teams.Edges {
teamNames = append(teamNames, edge.Node.Name)
}
if resp.NextPage == 0 {
if !q.Organization.Teams.PageInfo.HasNextPage {
break
}
opts.Page = resp.NextPage
variables["teamCursor"] = githubv4.NewString(q.Organization.Teams.PageInfo.EndCursor)
}
return teamNames, nil
}
Expand Down

0 comments on commit 99338a1

Please sign in to comment.