-
Notifications
You must be signed in to change notification settings - Fork 46
Expand file tree
/
Copy pathgithub_repository.go
More file actions
2147 lines (1926 loc) · 68.4 KB
/
github_repository.go
File metadata and controls
2147 lines (1926 loc) · 68.4 KB
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
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright The Linux Foundation and each contributor to CommunityBridge.
// SPDX-License-Identifier: MIT
package github
import (
"context"
"encoding/json"
"errors"
"fmt"
"net/http"
"regexp"
"runtime"
"sort"
"strconv"
"strings"
"sync"
"sync/atomic"
"time"
log "github.com/linuxfoundation/easycla/cla-backend-go/logging"
"github.com/linuxfoundation/easycla/cla-backend-go/users"
"github.com/linuxfoundation/easycla/cla-backend-go/utils"
"github.com/sirupsen/logrus"
"github.com/google/go-github/v37/github"
"github.com/linuxfoundation/easycla/cla-backend-go/gen/v1/models"
"github.com/linuxfoundation/easycla/cla-backend-go/logging"
)
var (
// ErrGitHubRepositoryNotFound is returned when github repository is not found
ErrGitHubRepositoryNotFound = errors.New("github repository not found")
NoreplyIDPattern = regexp.MustCompile(`^(\d+)\+([a-zA-Z0-9-]+)@users\.noreply\.github\.com$`)
NoreplyUserPattern = regexp.MustCompile(`^([a-zA-Z0-9-]+)@users\.noreply\.github\.com$`)
GithubUsernameRegex = regexp.MustCompile(`^[A-Za-z0-9-]{3,39}$`)
)
// Note: we use | and ||| as placeholders for inline and fenced code, then swap to backticks at render time.
const MissingCoAuthorsMessage = `
One or more co-authors of this pull request were not found. You must specify co-authors in commit message trailer via:
|||
Co-authored-by: name <email>
|||
Supported |Co-authored-by:| formats include:
1) |Anything <id+login@users.noreply.github.com>| - it will locate your GitHub user by |id| part.
2) |Anything <login@users.noreply.github.com>| - it will locate your GitHub user by |login| part.
3) |Anything <public-email>| - it will locate your GitHub user by |public-email| part. Note that this email must be made public on Github.
4) |Anything <other-email>| - it will locate your GitHub user by |other-email| part but only if that email was used before for any other CLA as a main commit author.
5) |login <any-valid-email>| - it will locate your GitHub user by |login| part, note that |login| part must be at least 3 characters long.
Please update your commit message(s) by doing |git commit --amend| and then |git push [--force]| and then request re-running CLA check via commenting on this pull request:
|||
/easycla
|||
`
const (
unknown = "Unknown"
failureState = "failure"
successState = "success"
svgVersion = "?v=2"
NegativeCacheTTL = 3 * time.Minute // Used for negative caching of missing/not-signed users
ProjectCacheTTL = 3 * time.Hour // Used for per-project caching of signed users
)
// GraphQL related types
type gqlRequest struct {
Query string `json:"query"`
OperationName string `json:"operationName,omitempty"`
Variables map[string]interface{} `json:"variables,omitempty"`
}
type gqlError struct {
Message string `json:"message"`
Type string `json:"type,omitempty"` // sometimes "RATE_LIMITED"
Path []interface{} `json:"path,omitempty"`
Extensions map[string]any `json:"extensions,omitempty"`
}
type gqlResponse struct {
Data json.RawMessage `json:"data"`
Errors []gqlError `json:"errors,omitempty"`
}
type GraphQLError struct {
Errs []gqlError
}
func (e *GraphQLError) Error() string {
if len(e.Errs) == 0 {
return "graphql: unknown error"
}
msg := "graphql: "
for i, ge := range e.Errs {
msg += fmt.Sprintf("#%d: %s (type=%s path=%v)", i+1, ge.Message, ge.Type, ge.Path)
if i < len(e.Errs)-1 {
msg += "; "
}
}
return msg
}
// doGraphQL posts to /graphql using v3 client and unmarshals the "data" field into v.
// No retries; if GraphQL returns "errors", returns an error.
func doGraphQL(ctx context.Context, c *github.Client, query string, variables map[string]interface{}, v any) (*github.Response, error) {
reqBody := gqlRequest{Query: query, Variables: variables}
req, err := c.NewRequest("POST", "graphql", reqBody) // -> https://api.github.com/graphql
if err != nil {
return nil, err
}
req.Header.Set("Accept", "application/vnd.github+json")
req.Header.Set("Content-Type", "application/json")
req.Header.Set("X-GitHub-Api-Version", "2022-11-28")
var gr gqlResponse
resp, err := c.Do(ctx, req, &gr)
if err != nil {
return resp, err
}
if len(gr.Errors) > 0 {
return resp, &GraphQLError{Errs: gr.Errors}
}
if v != nil && len(gr.Data) > 0 {
if err := json.Unmarshal(gr.Data, v); err != nil {
return resp, fmt.Errorf("unmarshal graphql data: %w", err)
}
}
return resp, nil
}
type prCommitsPage struct {
Repository struct {
PullRequest struct {
Commits struct {
TotalCount int `json:"totalCount"`
PageInfo struct {
HasNextPage bool `json:"hasNextPage"`
EndCursor string `json:"endCursor"`
} `json:"pageInfo"`
Nodes []struct {
Commit struct {
OID string `json:"oid"`
Message string `json:"message"`
Author struct {
Name string `json:"name"` // commit metadata author
Email string `json:"email"` // commit metadata author
User struct {
DatabaseID int `json:"databaseId"`
Login string `json:"login"`
Name string `json:"name"` // profile
Email string `json:"email"` // profile (often empty)
} `json:"user"`
} `json:"author"`
} `json:"commit"`
} `json:"nodes"`
} `json:"commits"`
} `json:"pullRequest"`
} `json:"repository"`
}
type cacheEntry struct {
value *github.User
expiresAt time.Time
}
type Cache struct {
data map[[2]string]cacheEntry
mu sync.Mutex
ttl time.Duration
}
func NewCache(ttl time.Duration) *Cache {
return &Cache{
data: make(map[[2]string]cacheEntry),
ttl: ttl,
}
}
func (c *Cache) Get(key [2]string) (*github.User, bool) {
c.mu.Lock()
defer c.mu.Unlock()
entry, found := c.data[key]
if !found || time.Now().After(entry.expiresAt) {
if found {
delete(c.data, key)
}
return nil, false
}
return entry.value, true
}
func (c *Cache) Set(key [2]string, value *github.User) {
c.mu.Lock()
defer c.mu.Unlock()
c.data[key] = cacheEntry{
value: value,
expiresAt: time.Now().Add(c.ttl),
}
}
func (c *Cache) SetWithTTL(key [2]string, value *github.User, tl time.Duration) {
c.mu.Lock()
defer c.mu.Unlock()
c.data[key] = cacheEntry{
value: value,
expiresAt: time.Now().Add(tl),
}
}
func (c *Cache) Cleanup() {
c.mu.Lock()
defer c.mu.Unlock()
now := time.Now()
for k, v := range c.data {
if now.After(v.expiresAt) {
delete(c.data, k)
}
}
}
func (c *Cache) Clear() {
c.mu.Lock()
defer c.mu.Unlock()
c.data = make(map[[2]string]cacheEntry)
}
func (c *Cache) Delete(key [2]string) { c.mu.Lock(); delete(c.data, key); c.mu.Unlock() }
type userCacheEntry struct {
value *models.User
expiresAt time.Time
}
type UserCache struct {
data map[[3]string]userCacheEntry
mu sync.Mutex
ttl time.Duration
}
func NewUserCache(ttl time.Duration) *UserCache {
return &UserCache{
data: make(map[[3]string]userCacheEntry),
ttl: ttl,
}
}
func (c *UserCache) Get(key [3]string) (*models.User, bool) {
c.mu.Lock()
defer c.mu.Unlock()
entry, found := c.data[key]
if !found || time.Now().After(entry.expiresAt) {
if found {
delete(c.data, key)
}
return nil, false
}
return entry.value, true
}
func (c *UserCache) Set(key [3]string, value *models.User) {
c.mu.Lock()
defer c.mu.Unlock()
c.data[key] = userCacheEntry{
value: value,
expiresAt: time.Now().Add(c.ttl),
}
}
func (c *UserCache) SetWithTTL(key [3]string, value *models.User, tl time.Duration) {
c.mu.Lock()
defer c.mu.Unlock()
c.data[key] = userCacheEntry{
value: value,
expiresAt: time.Now().Add(tl),
}
}
func (c *UserCache) Cleanup() {
c.mu.Lock()
defer c.mu.Unlock()
now := time.Now()
for k, v := range c.data {
if now.After(v.expiresAt) {
delete(c.data, k)
}
}
}
func (c *UserCache) Clear() {
c.mu.Lock()
defer c.mu.Unlock()
c.data = make(map[[3]string]userCacheEntry)
}
func (c *UserCache) Delete(key [3]string) { c.mu.Lock(); delete(c.data, key); c.mu.Unlock() }
type projectUserCacheEntry struct {
value *models.User
signed bool
affiliated bool
expiresAt time.Time
}
type ProjectUserCache struct {
data map[[4]string]projectUserCacheEntry
mu sync.Mutex
ttl time.Duration
}
func NewProjectUserCache(ttl time.Duration) *ProjectUserCache {
return &ProjectUserCache{
data: make(map[[4]string]projectUserCacheEntry),
ttl: ttl,
}
}
func (c *ProjectUserCache) Get(key [4]string) (*models.User, bool, bool, bool) {
c.mu.Lock()
defer c.mu.Unlock()
entry, found := c.data[key]
if !found || time.Now().After(entry.expiresAt) {
if found {
delete(c.data, key)
}
return nil, false, false, false
}
return entry.value, entry.signed, entry.affiliated, true
}
func (c *ProjectUserCache) SetWithTTL(key [4]string, value *models.User, signed, affiliated bool, tl time.Duration) {
c.mu.Lock()
defer c.mu.Unlock()
c.data[key] = projectUserCacheEntry{
value: value,
signed: signed,
affiliated: affiliated,
expiresAt: time.Now().Add(tl),
}
}
func (c *ProjectUserCache) Set(key [4]string, value *models.User, signed, affiliated bool) {
c.mu.Lock()
defer c.mu.Unlock()
c.data[key] = projectUserCacheEntry{
value: value,
signed: signed,
affiliated: affiliated,
expiresAt: time.Now().Add(c.ttl),
}
}
func (c *ProjectUserCache) Cleanup() {
c.mu.Lock()
defer c.mu.Unlock()
now := time.Now()
for k, v := range c.data {
if now.After(v.expiresAt) {
delete(c.data, k)
}
}
}
func (c *ProjectUserCache) Clear() {
c.mu.Lock()
defer c.mu.Unlock()
c.data = make(map[[4]string]projectUserCacheEntry)
}
func (c *ProjectUserCache) Delete(key [4]string) { c.mu.Lock(); delete(c.data, key); c.mu.Unlock() }
var GithubUserCache = NewCache(12 * time.Hour)
var ModelUserCache = NewUserCache(12 * time.Hour)
var ModelProjectUserCache = NewProjectUserCache(3 * time.Hour)
func init() {
go func() {
for {
time.Sleep(time.Hour)
GithubUserCache.Cleanup()
ModelUserCache.Cleanup()
ModelProjectUserCache.Cleanup()
}
}()
}
// ClearCaches clears all in-memory caches maintained by the GitHub module.
func ClearCaches() {
f := logrus.Fields{
"functionName": "github.github_repository.ClearCaches",
}
GithubUserCache.Clear()
ModelUserCache.Clear()
ModelProjectUserCache.Clear()
log.WithFields(f).Info("cleared caches")
}
func GetGitHubRepository(ctx context.Context, installationID, githubRepositoryID int64) (*github.Repository, error) {
f := logrus.Fields{
"functionName": "github.github_repository.GetGitHubRepository",
"installationID": installationID,
"githubRepositoryID": githubRepositoryID,
}
client, clientErr := NewGithubAppClient(installationID)
if clientErr != nil {
log.WithFields(f).WithError(clientErr).Warnf("problem loading github client for installation ID: %d", installationID)
return nil, clientErr
}
log.WithFields(f).Debugf("getting github repository by id: %d", githubRepositoryID)
repository, httpResponse, repoErr := client.Repositories.GetByID(ctx, githubRepositoryID)
if repoErr != nil {
log.WithFields(f).WithError(repoErr).Warnf("unable to fetch repository by ID: %d", githubRepositoryID)
return nil, repoErr
}
if httpResponse.StatusCode != http.StatusOK {
log.WithFields(f).Warnf("unexpected status code: %d", httpResponse.StatusCode)
return nil, ErrGitHubRepositoryNotFound
}
//log.WithFields(f).Debugf("successfully retrieved github repository by id: %d - repository object: %+v", githubRepositoryID, repository)
return repository, nil
}
func GetPullRequest(ctx context.Context, pullRequestID int, owner, repo string, client *github.Client) (*github.PullRequest, error) {
f := logrus.Fields{
"functionName": "github.github_repository.GetPullRequest",
"pullRequestID": pullRequestID,
"owner": owner,
"repo": repo,
}
pullRequest, _, err := client.PullRequests.Get(ctx, owner, repo, pullRequestID)
if err != nil {
logging.WithFields(f).WithError(err).Warn("unable to get pull request")
return nil, err
}
return pullRequest, nil
}
// UserCommitSummary data model
type UserCommitSummary struct {
SHA string
CommitAuthor *github.User
Affiliated bool
Authorized bool
}
// GetCommitAuthorID commit author username ID (numeric value as a string) if available, otherwise returns empty string
func (u UserCommitSummary) GetCommitAuthorID() string {
if u.CommitAuthor != nil && u.CommitAuthor.ID != nil {
return strconv.Itoa(int(*u.CommitAuthor.ID))
}
return ""
}
// GetCommitAuthorUsername returns commit author username if available, otherwise returns empty string
func (u UserCommitSummary) GetCommitAuthorUsername() string {
if u.CommitAuthor != nil {
if u.CommitAuthor.Login != nil {
return *u.CommitAuthor.Login
}
if u.CommitAuthor.Name != nil {
return *u.CommitAuthor.Name
}
}
return ""
}
// GetCommitAuthorEmail returns commit author email if available, otherwise returns empty string
func (u UserCommitSummary) GetCommitAuthorEmail() string {
if u.CommitAuthor != nil && u.CommitAuthor.Email != nil {
return *u.CommitAuthor.Email
}
return ""
}
// IsValid returns true if the commit author information is available
func (u UserCommitSummary) IsValid() bool {
valid := false
if u.CommitAuthor != nil {
valid = u.CommitAuthor.ID != nil && (u.CommitAuthor.Login != nil || u.CommitAuthor.Name != nil)
}
return valid
}
// GetDisplayText returns the display text for the user commit summary
func (u UserCommitSummary) GetDisplayText(tagUser bool) string {
if !u.IsValid() {
return "Invalid author details.\n"
}
if u.Affiliated && u.Authorized {
return fmt.Sprintf("%s is authorized.\n ", u.getUserInfo(tagUser))
}
if u.Affiliated {
return fmt.Sprintf("%s is associated with a company, but not an approval list.\n", u.getUserInfo(tagUser))
} else {
return fmt.Sprintf("%s is not associated with a company.\n", u.getUserInfo(tagUser))
}
}
func (u UserCommitSummary) getUserInfo(tagUser bool) string {
f := logrus.Fields{
"functionName": "github.github_repository.getUserInfo",
"tagUser": tagUser,
}
userInfo := ""
tagValue := ""
var sb strings.Builder
sb.WriteString(userInfo)
log.WithFields(f).Debugf("author: %+v", u.CommitAuthor)
if tagUser {
tagValue = "@"
}
if u.CommitAuthor != nil {
if u.CommitAuthor.Login != nil && *u.CommitAuthor.Login != "" {
sb.WriteString(fmt.Sprintf("login: %s%s / ", tagValue, *u.CommitAuthor.Login))
}
if u.CommitAuthor.Name != nil {
sb.WriteString(fmt.Sprintf("%sname: %s / ", userInfo, utils.StringValue(u.CommitAuthor.Name)))
}
}
return strings.TrimSuffix(sb.String(), " / ")
}
// SearchGithubUserByEmail searches for a GitHub user by email using the GitHub search API.
// Returns the first found *github.User, or nil if not found or on error.
func SearchGithubUserByEmail(ctx context.Context, client *github.Client, email string) (*github.User, error) {
f := logrus.Fields{
"functionName": "github.github_repository.SearchGithubUserByEmail",
"email": email,
}
log.WithFields(f).Debugf("Searching for GitHub user by email: %s", email)
query := fmt.Sprintf("%s in:email", email)
opts := &github.SearchOptions{
ListOptions: github.ListOptions{PerPage: 1},
}
result, _, err := client.Search.Users(ctx, query, opts)
if err != nil {
log.WithFields(f).WithError(err).Errorf("Error searching for user by email: %s", email)
return nil, err
}
if result.GetTotal() == 0 || len(result.Users) == 0 {
log.WithFields(f).Debugf("No GitHub user found with email: %s", email)
return nil, nil
}
log.WithFields(f).Debugf("Found GitHub user by email: %s", *result.Users[0].Login)
return result.Users[0], nil
}
// GetGitHubUserByLogin fetches a GitHub user by their login (username).
// Returns (*github.User, nil) if found, (nil, nil) if not found, or (nil, error) on error.
func GetGithubUserByLogin(ctx context.Context, client *github.Client, login string) (*github.User, error) {
f := logrus.Fields{
"functionName": "github.github_repository.GetGitHubUserByLogin",
"login": login,
}
log.WithFields(f).Debugf("Getting GitHub user by login: %s", login)
user, _, err := client.Users.Get(ctx, login)
if err != nil {
if ghErr, ok := err.(*github.ErrorResponse); ok && ghErr.Response.StatusCode == 404 {
log.WithFields(f).Debugf("Could not find GitHub user with login: %s", login)
return nil, nil
}
log.WithFields(f).WithError(err).Errorf("Error getting GitHub user with login: %s", login)
return nil, err
}
if user == nil {
log.WithFields(f).Debugf("No user object returned for login: %s", login)
return nil, nil
}
log.WithFields(f).Debugf("Found GitHub user by login: %s", login)
return user, nil
}
// GetGitHubUserByID fetches a GitHub user by their GitHubID.
// Returns (*github.User, nil) if found, (nil, nil) if not found, or (nil, error) on error.
func GetGithubUserByID(ctx context.Context, client *github.Client, githubID int64) (*github.User, error) {
f := logrus.Fields{
"functionName": "github.github_repository.GetGitHubUserByID",
"githubID": githubID,
}
log.WithFields(f).Debugf("Getting GitHub user by GitHub ID: %d", githubID)
user, _, err := client.Users.GetByID(ctx, githubID)
if err != nil {
if ghErr, ok := err.(*github.ErrorResponse); ok && ghErr.Response.StatusCode == 404 {
log.WithFields(f).Debugf("Could not find GitHub user with GitHub ID: %d", githubID)
return nil, nil
}
log.WithFields(f).WithError(err).Errorf("Error getting GitHub user with GitHub ID: %d", githubID)
return nil, err
}
if user == nil {
log.WithFields(f).Debugf("No user object returned for GitHub ID: %d", githubID)
return nil, nil
}
log.WithFields(f).Debugf("Found GitHub user by GitHub ID: %d", githubID)
return user, nil
}
// GetCoAuthorsFromCommit returns a slice of [2]string, each representing [name, email] of a co-author.
func GetCoAuthorsFromCommit(
ctx context.Context,
commit *github.RepositoryCommit,
) [][2]string {
f := logrus.Fields{
"functionName": "github.github_repository.GetCoAuthorsFromCommit",
}
var coAuthors [][2]string
if commit != nil && commit.Commit != nil && commit.Commit.Message != nil {
commitMessage := commit.GetCommit().GetMessage()
// log.WithFields(f).Debugf("commit message: %s", commitMessage)
re := regexp.MustCompile(`(?i)co-authored-by:\s*(.+?)\s*<([^<>]+)>`)
matches := re.FindAllStringSubmatch(commitMessage, -1)
for _, match := range matches {
name := strings.TrimSpace(match[1])
email := strings.ToLower(strings.TrimSpace(match[2]))
if name != "" && email != "" {
coAuthors = append(coAuthors, [2]string{name, email})
log.WithFields(f).Debugf("found co-author: name: %s, email: %s", name, email)
}
}
}
return coAuthors
}
// ExpandWithCoAuthors appends UserCommitSummary objects for all co-authors to commitAuthors slice.
func ExpandWithCoAuthors(
ctx context.Context,
client *github.Client,
usersService users.Service,
commit *github.RepositoryCommit,
pr int,
installationID int64,
commitAuthors *[]*UserCommitSummary,
mu *sync.Mutex,
) bool {
f := logrus.Fields{
"functionName": "github.github_repository.ExpandWithCoAuthors",
"pr": pr,
}
coAuthors := GetCoAuthorsFromCommit(ctx, commit)
log.WithFields(f).Debugf("co-authors found: %s", coAuthors)
missing := false
for _, coAuthor := range coAuthors {
summary, found := GetCoAuthorCommits(ctx, client, usersService, coAuthor, commit, pr, installationID)
mu.Lock()
*commitAuthors = append(*commitAuthors, summary)
mu.Unlock()
if !missing && !found {
missing = true
}
}
return missing
}
// IsValidGitHubUsername checks if the provided username is a valid GitHub username.
func IsValidGitHubUsername(username string) bool {
if !GithubUsernameRegex.MatchString(username) {
return false
}
if strings.HasPrefix(username, "-") || strings.HasSuffix(username, "-") {
return false
}
if strings.Contains(username, "--") {
return false
}
return true
}
//nolint:gocyclo // complexity is acceptable for now
func GetCoAuthorCommits(
ctx context.Context,
client *github.Client,
usersService users.Service,
coAuthor [2]string,
commit *github.RepositoryCommit,
pr int,
installationID int64,
) (*UserCommitSummary, bool) {
f := logrus.Fields{
"functionName": "github.github_repository.GetCoAuthorCommits",
"pr": pr,
"installation-id": installationID,
"co-author-name": coAuthor[0],
"co-author-email": coAuthor[1],
}
var (
user *github.User
githubID int64
name, email, login string
err error
)
name = strings.TrimSpace(coAuthor[0])
email = strings.TrimSpace(coAuthor[1])
lName := strings.ToLower(name)
cacheKey := [2]string{lName, email}
if cachedUser, ok := GithubUserCache.Get(cacheKey); ok {
log.WithFields(f).Debugf("GitHub user found in cache for name/email: %s/%s: %+v", name, email, cachedUser)
found := false
var summary *UserCommitSummary
if cachedUser != nil {
summary = &UserCommitSummary{
SHA: utils.StringValue(commit.SHA),
CommitAuthor: cachedUser,
Affiliated: false,
Authorized: false,
}
found = cachedUser.ID != nil
} else {
summary = &UserCommitSummary{
SHA: utils.StringValue(commit.SHA),
CommitAuthor: &github.User{
Login: nil,
ID: nil,
Name: &name,
Email: &email,
},
Affiliated: false,
Authorized: false,
}
}
log.WithFields(f).Debugf("PR: %d, %+v (from cache)", pr, summary)
return summary, found
}
log.WithFields(f).Debugf("Getting co-author details: %+v", coAuthor)
// 1. Check for email in "id+username@users.noreply.github.com" format:
if matches := NoreplyIDPattern.FindStringSubmatch(email); matches != nil {
idStr, loginStr := matches[1], matches[2]
if githubID, err = strconv.ParseInt(idStr, 10, 64); err == nil {
log.WithFields(f).Debugf("Detected noreply GitHub email with ID: %s, login: %s", idStr, loginStr)
user, err = GetGithubUserByID(ctx, client, githubID)
if err != nil {
log.WithFields(f).Warnf("Error fetching user by ID %d: %v", githubID, err)
user = nil
}
}
}
// 2. Check for email in "username@users.noreply.github.com" format:
if user == nil {
if matches := NoreplyUserPattern.FindStringSubmatch(email); matches != nil {
loginStr := matches[1]
log.WithFields(f).Debugf("Detected noreply GitHub email with login: %s", loginStr)
user, err = GetGithubUserByLogin(ctx, client, loginStr)
if err != nil {
log.WithFields(f).Warnf("Error fetching user by login %s: %v", loginStr, err)
user = nil
}
}
}
// 3. Try to find user by email via GitHub APIs
if user == nil {
user, err = SearchGithubUserByEmail(ctx, client, email)
if err != nil {
log.WithFields(f).Debugf("Co-author GitHub user not found via github email %s: %v (error: %v)", email, coAuthor, err)
user = nil
}
}
// 3b. Try to find user by email in our database
if user == nil {
var githubID string
dbUsers, err2 := usersService.GetUsersByLFEmail(email)
if err2 == nil {
for _, dbUser := range dbUsers {
if dbUser.GithubID != "" {
githubID = dbUser.GithubID
// log.WithFields(f).Debugf("FOUND githubID.1 = %s", githubID)
break
}
}
} else {
log.WithFields(f).Debugf("Co-author GitHub user not found via lf email %s: %v (error: %v)", email, coAuthor, err2)
}
if githubID == "" {
dbUsers, err2 := usersService.GetUsersByEmail(email)
if err2 == nil {
for _, dbUser := range dbUsers {
if dbUser.GithubID != "" {
githubID = dbUser.GithubID
// log.WithFields(f).Debugf("FOUND githubID.2 = %s", githubID)
break
}
}
} else {
log.WithFields(f).Debugf("Co-author GitHub user not found via emails %s: %v (error: %v)", email, coAuthor, err2)
}
}
if githubID != "" {
githubIDInt, err2 := strconv.ParseInt(githubID, 10, 64)
if err2 != nil {
log.WithFields(f).Debugf("Co-author GitHub user not found via lf email %s, wrong GitHub ID: %s: %v (error: %v)", email, githubID, coAuthor, err2)
} else {
user, err = GetGithubUserByID(ctx, client, githubIDInt)
if err != nil {
log.WithFields(f).Debugf("Error fetching user by ID %d: %v", githubIDInt, err)
user = nil
}
// log.WithFields(f).Debugf("FOUND user = (%s, %d, %s, %s)", *user.Login, *user.ID, *user.Name, *user.Email)
}
}
}
// 4. Last resort - try to find by name=login
if user == nil && IsValidGitHubUsername(lName) {
// Note that Co-authored-by: name <email> is not actually a GitHub login but rather a name - but we are trying hard to find a GitHub profile
user, err = GetGithubUserByLogin(ctx, client, lName)
if err != nil {
log.WithFields(f).Debugf("Co-author GitHub user not found via name=login=%s: %v (error: %v)", name, coAuthor, err)
user = nil
}
}
log.WithFields(f).Debugf("Co-author: %v, user: %+v", coAuthor, user)
var summary *UserCommitSummary
found := false
if user != nil {
if user.Login != nil {
login = *user.Login
}
if user.ID != nil {
githubID = *user.ID
found = true
}
if user.Name == nil || (user.Name != nil && strings.TrimSpace(*user.Name) == "") {
user.Name = &name
}
if user.Email == nil || (user.Email != nil && strings.TrimSpace(*user.Email) == "") {
user.Email = &email
}
log.WithFields(f).Debugf("Co-author GitHub user details found: %v, user: %+v, login: %s, id: %d for email=%s, name=%s", coAuthor, user, login, githubID, email, name)
summary = &UserCommitSummary{
SHA: utils.StringValue(commit.SHA),
CommitAuthor: user,
Affiliated: false,
Authorized: false,
}
log.WithFields(f).Debugf("PR: %d, %+v", pr, summary)
} else {
summary = &UserCommitSummary{
SHA: utils.StringValue(commit.SHA),
CommitAuthor: &github.User{
Login: nil,
ID: nil,
Name: &name,
Email: &email,
},
Affiliated: false,
Authorized: false,
}
log.WithFields(f).Debugf("Co-author GitHub user details not found: %v", coAuthor)
}
if found {
GithubUserCache.Set(cacheKey, user)
} else {
// negative cache for 30 minutes (this is for GitHub user not found)
GithubUserCache.SetWithTTL(cacheKey, user, 30*time.Minute)
}
return summary, found
}
func UserKey(id, login, email string) [3]string {
return [3]string{id, strings.ToLower(login), strings.ToLower(strings.TrimSpace(email))}
}
func ProjectUserKey(projectID, id, login, email string) [4]string {
return [4]string{projectID, id, strings.ToLower(login), strings.ToLower(strings.TrimSpace(email))}
}
// strStripLower mirrors the Python str_strip_lower
func strStripLower(s string) string {
return strings.ToLower(strings.TrimSpace(s))
}
// DedupAndSortCommitSummaries mirrors Python dedup_and_sort
// Dedupe key: (author_id, login, email, sha)
// Sort key: login, name, email, sha (all case-insensitive)
func DedupAndSortCommitSummaries(items []*UserCommitSummary) []*UserCommitSummary {
seen := make(map[string]struct{}, len(items))
uniq := make([]*UserCommitSummary, 0, len(items))
for _, s := range items {
if s == nil || s.CommitAuthor == nil {
continue
}
var id int64
if s.CommitAuthor.ID != nil {
id = *s.CommitAuthor.ID
}
login := strStripLower(utils.StringValue(s.CommitAuthor.Login))
email := strStripLower(utils.StringValue(s.CommitAuthor.Email))
key := fmt.Sprintf("%d|%s|%s|%s", id, login, email, s.SHA)
if _, ok := seen[key]; ok {
continue
}
seen[key] = struct{}{}
uniq = append(uniq, s)
}
sort.SliceStable(uniq, func(i, j int) bool {
ai, aj := uniq[i], uniq[j]
li := strStripLower(utils.StringValue(ai.CommitAuthor.Login))
lj := strStripLower(utils.StringValue(aj.CommitAuthor.Login))
if li != lj {
return li < lj
}
ni := strStripLower(utils.StringValue(ai.CommitAuthor.Name))
nj := strStripLower(utils.StringValue(aj.CommitAuthor.Name))
if ni != nj {
return ni < nj
}
ei := strStripLower(utils.StringValue(ai.CommitAuthor.Email))
ej := strStripLower(utils.StringValue(aj.CommitAuthor.Email))
if ei != ej {
return ei < ej
}
return ai.SHA < aj.SHA
})
return uniq
}
// NormalizeComment mirrors Python normalize_comment
func NormalizeComment(s string) string {
if s == "" {
return ""
}
// Normalize newlines
s = strings.ReplaceAll(s, "\r\n", "\n")
s = strings.ReplaceAll(s, "\r", "\n")
// Trim trailing spaces per line
lines := strings.Split(s, "\n")
for i := range lines {
lines[i] = strings.TrimRight(lines[i], " \t")
}
// Drop trailing blank lines
for len(lines) > 0 && lines[len(lines)-1] == "" {
lines = lines[:len(lines)-1]
}
return strings.Join(lines, "\n")
}
// GetCommitAuthorSignedStatus checks if the commit author has signed the CLA for the given project
func GetCommitAuthorSignedStatus(
ctx context.Context,
usersService users.Service,
hasUserSigned func(context.Context, *models.User, string) (*bool, *bool, error),
projectID string,
userSummary *UserCommitSummary,
signed *[]*UserCommitSummary,
unsigned *[]*UserCommitSummary,
mu *sync.Mutex,
) {
// here userSummary is NOT nil
f := logrus.Fields{
"functionName": "github.github_repository.GetCommitAuthorSignedStatus",
"projectID": projectID,
}
commitAuthorID := userSummary.GetCommitAuthorID()
commitAuthorUsername := userSummary.GetCommitAuthorUsername()
commitAuthorEmail := userSummary.GetCommitAuthorEmail()
f["authorID"] = commitAuthorID
f["authorLogin"] = commitAuthorUsername
f["authorEmail"] = commitAuthorEmail
log.WithFields(f).Debugf("checking user - sha: %s, user ID: %s, username: %s, email: %s",
userSummary.SHA, commitAuthorID, commitAuthorUsername, commitAuthorEmail)
// LG: cache_authors - start
// Per-project cache - also caches per-project signatures status and affiliation
// (project_id, id, login, email) -> (user || None, authorized, affiliated)
projectCacheKey := ProjectUserKey(projectID, commitAuthorID, commitAuthorUsername, commitAuthorEmail)
cachedUser, authorized, affiliated, ok := ModelProjectUserCache.Get(projectCacheKey)
if cachedUser != nil {
log.WithFields(f).Debugf("per-project cache: %+v -> (%+v, %v, %v, %v)", projectCacheKey, *cachedUser, authorized, affiliated, ok)