forked from trstringer/manual-approval
-
Notifications
You must be signed in to change notification settings - Fork 0
/
approvers.go
73 lines (60 loc) · 1.94 KB
/
approvers.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
package main
import (
"context"
"fmt"
"os"
"strconv"
"strings"
"github.com/google/go-github/v43/github"
)
func retrieveApprovers(client *github.Client, repoOwner string) ([]string, error) {
approvers := []string{}
requiredApproversRaw := os.Getenv(envVarApprovers)
requiredApprovers := strings.Split(requiredApproversRaw, ",")
for _, approverUser := range requiredApprovers {
expandedUsers := expandGroupFromUser(client, repoOwner, approverUser)
if expandedUsers != nil {
approvers = append(approvers, expandedUsers...)
} else {
approvers = append(approvers, approverUser)
}
}
approvers = deduplicateUsers(approvers)
minimumApprovalsRaw := os.Getenv(envVarMinimumApprovals)
minimumApprovals := len(approvers)
var err error
if minimumApprovalsRaw != "" {
minimumApprovals, err = strconv.Atoi(minimumApprovalsRaw)
if err != nil {
return nil, fmt.Errorf("error parsing minimum number of approvals: %w", err)
}
}
if minimumApprovals > len(approvers) {
return nil, fmt.Errorf("error: minimum required approvals (%d) is greater than the total number of approvers (%d)", minimumApprovals, len(approvers))
}
return approvers, nil
}
func expandGroupFromUser(client *github.Client, org, userOrTeam string) []string {
fmt.Printf("Attempting to expand user %s/%s as a group (may not succeed)\n", org, userOrTeam)
users, _, err := client.Teams.ListTeamMembersBySlug(context.Background(), org, userOrTeam, &github.TeamListTeamMembersOptions{})
if err != nil {
fmt.Printf("%v\n", err)
return nil
}
userNames := make([]string, 0, len(users))
for _, user := range users {
userNames = append(userNames, user.GetLogin())
}
return userNames
}
func deduplicateUsers(users []string) []string {
uniqValuesByKey := make(map[string]bool)
uniqUsers := []string{}
for _, user := range users {
if _, ok := uniqValuesByKey[user]; !ok {
uniqValuesByKey[user] = true
uniqUsers = append(uniqUsers, user)
}
}
return uniqUsers
}