-
Notifications
You must be signed in to change notification settings - Fork 0
/
git.go
426 lines (403 loc) · 13.5 KB
/
git.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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
package main
import (
"context"
"encoding/json"
"fmt"
"github.com/google/go-github/v45/github"
"github.com/rs/zerolog/log"
"golang.org/x/oauth2"
"net/url"
"os"
"sort"
"strings"
"time"
)
type LabelAction struct {
IssueNumber int
Action string
}
type IssueAction struct {
Number int
State string
Action string
UserName string
LastUpdated string
Labels []string
}
type MemberAction struct {
UserName string
Action string
Team string
}
type TeamAction struct {
Action string
}
type GithubActions struct {
Organization string
Repository string
Member *MemberAction
Team *TeamAction
}
var supportedTeamActions = []string{"list"}
var supportedMemberActions = []string{"get", "add"}
var supportedMemberOptions = []string{"team"}
var ExcludeTeamName = []string{"legacy-team", "admin"}
//var availableStates = []string{"open", "closed", "assigned", "unassigned"}
func getGitClient() (*github.Client, context.Context, error) {
// Initilizing git client
ctx := context.Background()
ts := oauth2.StaticTokenSource(
&oauth2.Token{AccessToken: os.Getenv("GITHUB_OAUTH_TOKEN")},
)
tc := oauth2.NewClient(ctx, ts)
client := github.NewClient(tc)
if len(os.Getenv("GITHUB_ENTERPRISE_URL")) > 0 {
enterpriseURL, err := url.Parse(os.Getenv("GITHUB_ENTERPRISE_URL"))
if err != nil {
return nil, nil, fmt.Errorf("unable update new github client custom URL, Error: %s", err)
}
client.BaseURL = enterpriseURL
}
return client, ctx, nil
}
func validateUser(userName string, organization string) (bool, string, error) {
var err error
var reason string
client, ctx, err := getGitClient()
if err != nil {
return false, "Internal Error", fmt.Errorf("unable update New github client, Error: %s", err)
} else {
_, res, err := client.Users.Get(ctx, userName)
if err != nil {
reason = "Unknown User"
log.Info().Msg(fmt.Sprintf("Unable to find user, in the org `%s`", organization))
return false, reason, err
}
if res.StatusCode != 200 {
log.Info().Msg(fmt.Sprintf("Unable to find user, in the org `%s`", organization))
reason = "Unknown User"
return false, reason, err
} else {
log.Info().Msg(fmt.Sprintf("User found"))
return true, "", nil
}
}
}
func (g GithubActions) userGet() (bool, string, error) {
var err error
var reason string
client, ctx, err := getGitClient()
if err != nil {
return false, "Internal Error", fmt.Errorf("unable update New github client, Error: %s", err)
}
user, res, err := client.Users.Get(ctx, g.Member.UserName)
if err != nil {
reason = "Unknown User"
return false, reason, fmt.Errorf("unable to find user. Error:%s", err)
}
if res.StatusCode != 200 {
return false, "Unknown User", fmt.Errorf("unable to find user. Error: %s", err)
}
return true, fmt.Sprintf("Login:\t*<%s|%s>*\n \nName:\t*`%s`*\nEmail:\t*`%s`*\nID:\t*`%d`*\nPublic Repos:\t*`%d`*\n", *user.HTMLURL, *user.Login, *user.Name, *user.Email, *user.ID, *user.PublicRepos), nil
}
func (g GithubActions) validateTeam() (bool, string, error) {
client, ctx, err := getGitClient()
if err != nil {
log.Info().Msg(fmt.Sprintf("Unable update New github client, Error: %s", err))
return false, "Internal Error", err
} else {
_, res, err := client.Teams.GetTeamBySlug(ctx, g.Organization, g.Member.Team)
if err != nil {
log.Info().Msg(fmt.Sprintf("Unable to find the Team `%s`", g.Member.Team))
return false, "Unknown Team", err
}
if res.StatusCode != 200 {
log.Info().Msg(fmt.Sprintf("unable to find the team `%s`, you have to give a valid team name\n", g.Member.Team))
return false, "Unknown Team", err
} else {
log.Info().Msg("Team found")
return true, "", nil
}
}
}
func (g GithubActions) actOnMember() (bool, string, error) {
stat, err := g.validateInputs()
if !stat {
return false, "Unknown Options", fmt.Errorf("unknown inputs. Error:%s", err)
}
switch {
case g.Member.Action == "add":
_, msg, err := g.addMember()
if err != nil {
return false, msg, err
}
return true, msg, nil
case g.Member.Action == "get":
_, msg, err := g.userGet()
if err != nil {
return false, msg, err
}
return true, msg, nil
default:
return false, "", fmt.Errorf("unknown Action")
}
//return true, "", nil
}
func ListTeams(Org string) ([]string, string, error) {
var teamList []string
var message string
lstopt := &github.ListOptions{
Page: 1,
PerPage: 100,
}
client, ctx, err := getGitClient()
if err != nil {
return nil, "Internal Error", fmt.Errorf("unable update New github client, Error: %s", err)
}
for {
teams, resp, err := client.Teams.ListTeams(ctx, Org, lstopt)
if err != nil {
return nil, "Internal Error", fmt.Errorf("getting team failed, Error: %s", err)
}
if len(teams) > 0 {
for _, team := range teams {
if !contains(ExcludeTeamName, *team.Name) {
teamList = append(teamList, fmt.Sprintf("*<%s|%s>*\t*`%s`*\n", team.GetURL(), *team.Name, *team.Description))
}
}
} else {
message = fmt.Sprintf("No team found in Org: `\"%s\"`", Org)
return teamList, message, fmt.Errorf("no teams found, Error: %s", err)
}
if resp.NextPage == 0 {
break
}
lstopt.Page = resp.NextPage
}
return teamList, fmt.Sprintf("%d team/s found", len(teamList)), err
}
func (g GithubActions) actOnTeam() (bool, []string, string, error) {
var teamList []string
var message string
var err error
stat, message, err := g.validateRepoAndOrg()
if !stat {
return false, teamList, message, fmt.Errorf("invalid org/repo. Error: %s", err)
}
switch {
case g.Team.Action == "list":
stat, err = g.validateInputs()
if !stat {
return false, teamList, "Unknown Options", fmt.Errorf("unknown inputs, Error:%s", err)
}
teamList, message, err = ListTeams(g.Organization)
return true, teamList, message, nil
default:
return false, teamList, "", fmt.Errorf("unknown Action")
}
return true, teamList, "", nil
}
func (g GithubActions) addMember() (bool, string, error) {
var orgStatus string
var teamStatus string
orgStatus, err := g.OrganizationsEditOrgMembership()
if err != nil {
return false, "", fmt.Errorf("user `%s` failed to add to the organization `%s`. Error: %s", g.Member.UserName, g.Organization, err)
}
if orgStatus == "User Added" || orgStatus == "Already A Member" {
teamStatus, err = g.TeamsAddTeamMembershipBySlug()
if err != nil {
return false, "", fmt.Errorf("user `%s` failed to add to the team `%s`. Error: %s", g.Member.UserName, g.Member.Team, err)
}
if teamStatus == "User Added" {
return true, fmt.Sprintf("user `%s` added to team `%s` ", g.Member.UserName, g.Member.Team), nil
} else if teamStatus == "Already A Member" {
return true, fmt.Sprintf("user `%s` is already a member of team `%s`", g.Member.UserName, g.Member.Team), nil
} else {
return false, "", fmt.Errorf("user `%`s failed to add to the team `%s`. Erro: %s", g.Member.UserName, g.Member.Team, err)
}
} else {
return false, "", fmt.Errorf("user `%s` failed to add to the team `%s`. Error: %s", g.Member.UserName, g.Member.Team, err)
}
}
func (g GithubActions) OrganizationsEditOrgMembership() (string, error) {
var status string
stat, _ := g.checkIfUserAlreadyMemberOfOrg()
if !stat {
stat, reas, err := validateUser(g.Member.UserName, g.Organization)
if err != nil {
return reas, fmt.Errorf("unable to get the user details, Error: %s", err)
}
if stat {
log.Debug().Msg(fmt.Sprintf("User %s is a valid user", g.Member.UserName))
client, ctx, err := getGitClient()
if err != nil {
return "Internal Error", fmt.Errorf("unable update New github client, Error: %s", err)
}
_, resp, err := client.Organizations.EditOrgMembership(ctx, g.Member.UserName, g.Organization, nil)
if err != nil {
return "Failed to Add", fmt.Errorf("unable to add the user `%s`. Error: %s", g.Member.UserName, err)
}
if resp.StatusCode != 200 {
return "Failed to Add", fmt.Errorf("unable to add user `%s` to the org `%s`", g.Member.UserName, g.Organization)
} else {
status = "User Added"
log.Debug().Msg(fmt.Sprintf("User `%s` added to the Org `%s`", g.Member.UserName, g.Organization))
}
} else {
return "Unknown User", fmt.Errorf("unable to add user `%s` to the org `%s`", g.Member.UserName, g.Organization)
}
} else {
status = "Already A Member"
log.Info().Msg("User already a member of org")
}
return status, nil
}
func (g GithubActions) TeamsAddTeamMembershipBySlug() (string, error) {
var status string
stat, _ := g.checkIfUserAlreadyMemberOfTeam()
if !stat {
stat, reas, err := validateUser(g.Member.UserName, g.Organization)
if err != nil {
return reas, fmt.Errorf("unable to get the User %s details, Error: %s", g.Member.UserName, err)
}
stat, reas, err = g.validateTeam()
if err != nil {
return reas, fmt.Errorf("unable to get the Team, %s details, Error: %s", g.Member.Team, err)
}
if stat {
log.Debug().Msg(fmt.Sprintf("User %s is a valid user", g.Member.UserName))
client, ctx, err := getGitClient()
if err != nil {
return "Internal Error", fmt.Errorf("unable update New github client, Error: %s", err)
}
_, resp, err := client.Teams.AddTeamMembershipBySlug(ctx, g.Organization, g.Member.Team, g.Member.UserName, nil)
if err != nil {
return "Failed to Add", fmt.Errorf("unable to add the user %s. Error: %s", g.Member.UserName, err)
}
if resp.StatusCode != 200 {
fmt.Errorf("unable to add user %s to the Team %s", g.Member.UserName, g.Member.Team)
status = "Failed to Add"
} else {
status = "User Added"
log.Debug().Msg(fmt.Sprintf("User %s added to the OTeam %s", g.Member.UserName, g.Member.Team))
}
} else {
status = "Unknown Team"
return status, fmt.Errorf("unknown user %s", g.Member.Team)
}
} else {
status = "Already A Member"
log.Info().Msg("User already a member of Team")
}
return status, nil
}
func (g GithubActions) checkIfUserAlreadyMemberOfOrg() (bool, error) {
//Organization Membership
client, ctx, err := getGitClient()
if err != nil {
log.Info().Msg(fmt.Sprintf("Unable update New github client, Error: %s", err))
} else {
stat, _, err := client.Organizations.IsMember(ctx, g.Organization, g.Member.UserName)
if err != nil {
log.Info().Msg(fmt.Sprintf("Unable to get the user details. Error: %s", err))
}
if stat {
log.Debug().Msg(fmt.Sprintf("User %s is already a member of the Org %s", g.Member.UserName, g.Organization))
return true, nil
} else {
log.Debug().Msg(fmt.Sprintf("User %s is not a member of the org %s", g.Member.UserName, g.Organization))
}
}
return false, err
}
func (g GithubActions) checkIfUserAlreadyMemberOfTeam() (bool, error) {
client, ctx, err := getGitClient()
if err != nil {
log.Info().Msg(fmt.Sprintf("Unable update New github client, Error: %s", err))
} else {
mem, rsp, _ := client.Teams.GetTeamMembershipBySlug(ctx, g.Organization, g.Member.Team, g.Member.UserName)
/*if err != nil {
log.Debug().Msg(fmt.Sprintf("Unable to get the team details. Error: %s", err))
}*/
if rsp.Response.StatusCode != 200 {
log.Debug().Msg(fmt.Sprintf("User %s is not a member of the team %s", g.Member.UserName, g.Member.Team))
} else {
if *mem.State == "active" {
log.Debug().Msg(fmt.Sprintf("User %s is already a member of the team %s", g.Member.UserName, g.Member.Team))
return true, nil
} else if *mem.State == "pending" {
log.Debug().Msg(fmt.Sprintf("There is already an invite sent to %s", g.Member.UserName))
} else {
log.Debug().Msg("Unknown status")
}
}
}
return false, err
}
func (g GithubActions) validateRepoAndOrg() (bool, string, error) {
lstopt := &github.ListOptions{
Page: 1,
PerPage: 100,
}
opts := &github.RepositoryListByOrgOptions{ListOptions: *lstopt}
var message string
var err error
client, ctx, err := getGitClient()
if err != nil {
log.Info().Msg(fmt.Sprintf("Unable update New github client, Error: %s", err))
return false, "Internal Error", err
}
for {
repoList, resp, err := client.Repositories.ListByOrg(ctx, g.Organization, opts)
if err != nil {
message = fmt.Sprintf("Unable to get details of Organization:`%s` and/or Repository: `%s`", g.Organization, g.Repository)
log.Info().Msg(message)
return false, message, err
}
log.Debug().Msg(fmt.Sprintf("Page numer: %d", opts.ListOptions.Page))
if len(repoList) > 0 {
for _, repo := range repoList {
if *repo.Name == g.Repository && repo.Owner.GetLogin() == g.Organization {
message = fmt.Sprintf("Organization: %s and the repository is %s\n", repo.Owner.GetLogin(), *repo.Name)
log.Info().Msg(message)
return true, message, nil
}
message = fmt.Sprintf("Unknown Organization:`%s`and/or the repository is `%s`", repo.Owner.GetLogin(), *repo.Name)
}
}
log.Debug().Msg(fmt.Sprintf("Page numer: %d", resp.NextPage))
if resp.NextPage == 0 {
break
}
opts.ListOptions.Page = resp.NextPage
}
return false, message, err
}
func isDateValue(stringDate string) bool {
_, err := time.Parse("2006-01-02", stringDate)
return err == nil
}
func prettyPrint(i interface{}) string {
var userDetails string
var x map[string]interface{}
jsonStr, _ := json.Marshal(i)
json.Unmarshal([]byte(jsonStr), &x)
for key, opt := range x {
userDetails = userDetails + fmt.Sprintf("%v = %v \n", key, opt)
}
return SortString(userDetails)
}
func SortString(w string) string {
s := strings.Split(w, "\n")
sort.Strings(s)
return strings.Join(s, "\n")
}
func (g GithubActions) validateInputs() (bool, error) {
if g.Member != nil {
if len(g.Member.Team) == 0 && g.Member.Action == "add" {
return false, fmt.Errorf("`%s` expects team name as input", g.Member.Action)
}
}
return true, nil
}