From c7e7118247c2dd40d3f4c7a6a14e8439732ecebb Mon Sep 17 00:00:00 2001 From: Harold Wanyama Date: Mon, 11 Sep 2023 18:02:22 +0300 Subject: [PATCH] Revert "[#4001]refactor gitlab/github pr auto update" This reverts commit 29ad663979a2591a5a533384f43cb2e00be26ae2. Signed-off-by: Harold Wanyama --- cla-backend-go/cmd/server.go | 4 +- cla-backend-go/signatures/models.go | 10 - cla-backend-go/signatures/repository.go | 90 +----- cla-backend-go/signatures/service.go | 260 ++---------------- cla-backend-go/utils/gitlab.go | 121 -------- cla-backend-go/v2/gitlab-activity/service.go | 171 +++++++----- .../v2/gitlab-activity/service_test.go | 21 +- .../v2/gitlab_organizations/service.go | 12 +- 8 files changed, 130 insertions(+), 559 deletions(-) delete mode 100644 cla-backend-go/utils/gitlab.go diff --git a/cla-backend-go/cmd/server.go b/cla-backend-go/cmd/server.go index 150e607a5..c0a6c5a1c 100644 --- a/cla-backend-go/cmd/server.go +++ b/cla-backend-go/cmd/server.go @@ -304,14 +304,14 @@ func server(localMode bool) http.Handler { v2RepositoriesService := v2Repositories.NewService(gitV1Repository, gitV2Repository, v1ProjectClaGroupRepo, githubOrganizationsRepo, gitlabOrganizationRepo, eventsService) githubOrganizationsService := github_organizations.NewService(githubOrganizationsRepo, gitV1Repository, v1ProjectClaGroupRepo) gitlabOrganizationsService := gitlab_organizations.NewService(gitlabOrganizationRepo, v2RepositoriesService, v1ProjectClaGroupRepo, storeRepository, usersService, signaturesRepo, v1CompanyRepo) - gitlabActivityService := gitlab_activity.NewService(gitV1Repository, gitV2Repository, usersRepo, signaturesRepo, v1ProjectClaGroupRepo, v1CompanyRepo, signaturesRepo, gitlabOrganizationsService, storeRepository) - v1SignaturesService := signatures.NewService(signaturesRepo, v1CompanyService, usersService, eventsService, githubOrgValidation, v1RepositoriesService, githubOrganizationsService, gitlabOrganizationsService, v1ProjectService, gitlabApp, configFile.ClaV1ApiURL, configFile.CLALandingPage, configFile.CLALogoURL, gitlabActivityService) + v1SignaturesService := signatures.NewService(signaturesRepo, v1CompanyService, usersService, eventsService, githubOrgValidation, v1RepositoriesService, githubOrganizationsService, v1ProjectService, gitlabApp, configFile.ClaV1ApiURL, configFile.CLALandingPage, configFile.CLALogoURL) v2SignatureService := v2Signatures.NewService(awsSession, configFile.SignatureFilesBucket, v1ProjectService, v1CompanyService, v1SignaturesService, v1ProjectClaGroupRepo, signaturesRepo, usersService) v1ClaManagerService := cla_manager.NewService(claManagerReqRepo, v1ProjectClaGroupRepo, v1CompanyService, v1ProjectService, usersService, v1SignaturesService, eventsService, emailTemplateService, configFile.CorporateConsoleV1URL) v2ClaManagerService := v2ClaManager.NewService(emailTemplateService, v1CompanyService, v1ProjectService, v1ClaManagerService, usersService, v1RepositoriesService, v2CompanyService, eventsService, v1ProjectClaGroupRepo) v1ApprovalListService := approval_list.NewService(approvalListRepo, v1ProjectClaGroupRepo, v1ProjectService, usersRepo, v1CompanyRepo, v1CLAGroupRepo, signaturesRepo, emailTemplateService, configFile.CorporateConsoleV2URL, http.DefaultClient) authorizer := auth.NewAuthorizer(authValidator, userRepo) v2MetricsService := metrics.NewService(metricsRepo, v1ProjectClaGroupRepo) + gitlabActivityService := gitlab_activity.NewService(gitV1Repository, gitV2Repository, usersRepo, signaturesRepo, v1ProjectClaGroupRepo, v1CompanyRepo, signaturesRepo, gitlabOrganizationsService) gitlabSignService := gitlab_sign.NewService(v2RepositoriesService, usersService, storeRepository, gitlabApp, gitlabOrganizationsService) v2GithubOrganizationsService := v2GithubOrganizations.NewService(githubOrganizationsRepo, gitV1Repository, v1ProjectClaGroupRepo, githubOrganizationsService) autoEnableService := dynamo_events.NewAutoEnableService(v1RepositoriesService, gitV1Repository, githubOrganizationsRepo, v1ProjectClaGroupRepo, v1ProjectService) diff --git a/cla-backend-go/signatures/models.go b/cla-backend-go/signatures/models.go index 8dbf46922..006aedade 100644 --- a/cla-backend-go/signatures/models.go +++ b/cla-backend-go/signatures/models.go @@ -132,13 +132,3 @@ type ActivePullRequest struct { RepositoryID string `json:"repository_id"` PullRequestID string `json:"pull_request_id"` } - -// ActiveGitLabPullRequest data model -type ActiveGitLabPullRequest struct { - GitLabAuthorUserName string `json:"gitlab_author_username"` - GitLabAuthorEmail string `json:"gitlab_author_email"` - ClaGroupID string `json:"cla_group_id"` - RepositoryID string `json:"repository_id"` - MergeRequestID string `json:"merge_request_id"` - ProjectID string `json:"project_id"` -} diff --git a/cla-backend-go/signatures/repository.go b/cla-backend-go/signatures/repository.go index c9483dfbe..7473c5be5 100644 --- a/cla-backend-go/signatures/repository.go +++ b/cla-backend-go/signatures/repository.go @@ -96,7 +96,6 @@ type SignatureRepository interface { GetClaGroupCorporateContributors(ctx context.Context, claGroupID string, companyID *string, pageSize *int64, nextKey *string, searchTerm *string) (*models.CorporateContributorList, error) EclaAutoCreate(ctx context.Context, signatureID string, autoCreateECLA bool) error ActivateSignature(ctx context.Context, signatureID string) error - GetGitLabActiveMergeRequestMetadata(ctx context.Context, gitLabAuthorUsername, gitLabAuthorEmail string) (*ActiveGitLabPullRequest, error) } type iclaSignatureWithDetails struct { @@ -3036,7 +3035,7 @@ func (repo repository) UpdateApprovalList(ctx context.Context, claManager *model // Get ICLAs var wg sync.WaitGroup wg.Add(len(params.RemoveGitlabUsernameApprovalList)) - for _, glUsername := range params.RemoveGitlabUsernameApprovalList { + for _, ghUsername := range params.RemoveGitlabUsernameApprovalList { go func(gitLabUsername string) { defer wg.Done() var iclas []*models.IclaSignature @@ -3069,7 +3068,7 @@ func (repo repository) UpdateApprovalList(ctx context.Context, claManager *model if icla != nil { // Convert to IclSignature instance to leverage invalidateSignatures helper function approvalList.ICLAs = []*models.IclaSignature{{ - GitlabUsername: icla.UserGitlabUsername, + GitlabUsername: icla.UserGHUsername, LfUsername: icla.UserLFID, SignatureID: icla.SignatureID, }} @@ -3081,7 +3080,7 @@ func (repo repository) UpdateApprovalList(ctx context.Context, claManager *model // Send Email repo.sendEmail(ctx, getBestEmail(claUser), &approvalList, iclas, eclas) - }(glUsername) + }(ghUsername) } wg.Wait() } @@ -4302,86 +4301,3 @@ func decodeNextKey(str string) (map[string]*dynamodb.AttributeValue, error) { return m, nil } - -// GetGitLabActiveMergeRequestMetadata returns the pull request metadata for the given user ID -func (repo repository) GetGitLabActiveMergeRequestMetadata(ctx context.Context, gitLabAuthorUsername, gitLabAuthorEmail string) (*ActiveGitLabPullRequest, error) { - f := logrus.Fields{ - "functionName": "v1.signatures.repository.GetGitLabActiveMergeRequestMetadata", - utils.XREQUESTID: ctx.Value(utils.XREQUESTID), - "gitLabAuthorUsername": gitLabAuthorUsername, - "gitLabAuthorEmail": gitLabAuthorEmail, - } - - if gitLabAuthorUsername == "" && gitLabAuthorEmail == "" { - return nil, nil - } - - expr, err := expression.NewBuilder().WithProjection(buildSignatureMetadata()).Build() - if err != nil { - log.WithFields(f).WithError(err).Warn("error building expression for user ID query") - return nil, err - } - - // Try to lookup based on the following keys - could be indexed by either or both (depends if user shared their - // email and went through the GitHub authorization flow) - var keys []string - if gitLabAuthorUsername != "" { - keys = append(keys, fmt.Sprintf("active_mr:u:%s", gitLabAuthorUsername)) - } - if gitLabAuthorEmail != "" { - keys = append(keys, fmt.Sprintf("active_mr:e:%s", gitLabAuthorEmail)) - } - - var activeSignature ActiveGitLabPullRequest - for _, key := range keys { - itemInput := &dynamodb.GetItemInput{ - Key: map[string]*dynamodb.AttributeValue{ - "key": {S: aws.String(key)}, - }, - ExpressionAttributeNames: expr.Names(), - ProjectionExpression: expr.Projection(), - TableName: aws.String(fmt.Sprintf("cla-%s-store", repo.stage)), - } - - // Make the DynamoDb Query API call - // log.WithFields(f).Debugf("loading active signature using key: %s", key) - result, queryErr := repo.dynamoDBClient.GetItem(itemInput) - if queryErr != nil { - if queryErr.Error() == dynamodb.ErrCodeResourceNotFoundException { - continue - } - log.WithFields(f).WithError(queryErr).Warnf("error retrieving active signature metadata using key: %s", key) - return nil, queryErr - } - - if result == nil || result.Item == nil || result.Item["value"] == nil || result.Item["value"].S == nil { - log.WithFields(f).Debugf("query result is empty for key: %s", key) - continue - } - if result.Item["value"] == nil || result.Item["value"].S == nil { - log.WithFields(f).Debugf("query result value is empty for key: %s", key) - continue - } - - // Clean up the JSON string - strValue := utils.StringValue(result.Item["value"].S) - // log.WithFields(f).Debugf("decoding value: %s", strValue) - if strings.HasSuffix(strValue, "\"") { - // Trim the leading and trailing quotes from the JSON record - strValue = strValue[1 : len(strValue)-1] - } - // Unescape the JSON string - strValue = strings.Replace(strValue, "\\\"", "\"", -1) - // log.WithFields(f).Debugf("decoding value: %s", strValue) - - jsonUnMarshallErr := json.Unmarshal([]byte(strValue), &activeSignature) - if jsonUnMarshallErr != nil { - log.WithFields(f).WithError(jsonUnMarshallErr).Warn("unable to convert model for active signature ") - return nil, jsonUnMarshallErr - } - - return &activeSignature, nil - } - - return nil, nil -} diff --git a/cla-backend-go/signatures/service.go b/cla-backend-go/signatures/service.go index 5d7a6b709..9a37e4a33 100644 --- a/cla-backend-go/signatures/service.go +++ b/cla-backend-go/signatures/service.go @@ -8,7 +8,6 @@ import ( "errors" "fmt" "regexp" - "sort" "strconv" "strings" "sync" @@ -16,9 +15,6 @@ import ( "github.com/aws/aws-sdk-go/aws" gitlab_api "github.com/communitybridge/easycla/cla-backend-go/gitlab_api" service2 "github.com/communitybridge/easycla/cla-backend-go/project/service" - "github.com/communitybridge/easycla/cla-backend-go/v2/common" - "github.com/communitybridge/easycla/cla-backend-go/v2/gitlab_organizations" - "github.com/xanzy/go-gitlab" "github.com/communitybridge/easycla/cla-backend-go/github" "github.com/communitybridge/easycla/cla-backend-go/github_organizations" @@ -38,7 +34,6 @@ import ( log "github.com/communitybridge/easycla/cla-backend-go/logging" "github.com/communitybridge/easycla/cla-backend-go/gen/v1/models" - v2Models "github.com/communitybridge/easycla/cla-backend-go/gen/v2/models" githubpkg "github.com/google/go-github/v37/github" "golang.org/x/oauth2" ) @@ -75,30 +70,23 @@ type SignatureService interface { handleGitHubStatusUpdate(ctx context.Context, employeeUserModel *models.User) error } -// GitlabActivityService is a redefine the interface here to avoid circular dependency issues -type GitlabActivityService interface { - HasUserSigned(ctx context.Context, claGroupID string, gitlabUser *gitlab.User) (bool, error) -} - type service struct { - repo SignatureRepository - companyService company.IService - usersService users.Service - eventsService events.Service - githubOrgValidation bool - repositoryService repositories.Service - githubOrgService github_organizations.ServiceInterface - gitlabOrgService gitlab_organizations.ServiceInterface - claGroupService service2.Service - gitLabApp *gitlab_api.App - claBaseAPIURL string - claLandingPage string - claLogoURL string - gitlabActivityService GitlabActivityService + repo SignatureRepository + companyService company.IService + usersService users.Service + eventsService events.Service + githubOrgValidation bool + repositoryService repositories.Service + githubOrgService github_organizations.ServiceInterface + claGroupService service2.Service + gitLabApp *gitlab_api.App + claBaseAPIURL string + claLandingPage string + claLogoURL string } // NewService creates a new signature service -func NewService(repo SignatureRepository, companyService company.IService, usersService users.Service, eventsService events.Service, githubOrgValidation bool, repositoryService repositories.Service, githubOrgService github_organizations.ServiceInterface, gitlabOrgService gitlab_organizations.ServiceInterface, claGroupService service2.Service, gitLabApp *gitlab_api.App, CLABaseAPIURL, CLALandingPage, CLALogoURL string, gitlabActivityService GitlabActivityService) SignatureService { +func NewService(repo SignatureRepository, companyService company.IService, usersService users.Service, eventsService events.Service, githubOrgValidation bool, repositoryService repositories.Service, githubOrgService github_organizations.ServiceInterface, claGroupService service2.Service, gitLabApp *gitlab_api.App, CLABaseAPIURL, CLALandingPage, CLALogoURL string) SignatureService { return service{ repo, companyService, @@ -107,13 +95,11 @@ func NewService(repo SignatureRepository, companyService company.IService, users githubOrgValidation, repositoryService, githubOrgService, - gitlabOrgService, claGroupService, gitLabApp, CLABaseAPIURL, CLALandingPage, CLALogoURL, - gitlabActivityService, } } @@ -489,13 +475,6 @@ func (s service) UpdateApprovalList(ctx context.Context, authUser *auth.User, cl UserModel: userModel, ProjectSFID: projectSFID, } - // Get CCLA signature - For Approval List info - cclaSignature, err := s.repo.GetCorporateSignature(ctx, claGroupModel.ProjectID, companyModel.CompanyID, &approved, &signed) - if err != nil || cclaSignature == nil { - msg := fmt.Sprintf("unable to get corporate signature for CLA Group: %s and company: %s", claGroupModel.ProjectID, companyModel.CompanyID) - log.WithFields(f).Warn(msg) - return nil, errors.New(msg) - } updatedCorporateSignature, err := s.repo.UpdateApprovalList(ctx, userModel, claGroupModel, companyModel.CompanyID, params, eventArgs) if err != nil { @@ -503,34 +482,18 @@ func (s service) UpdateApprovalList(ctx context.Context, authUser *auth.User, cl return updatedCorporateSignature, err } - for _, email := range updatedCorporateSignature.EmailApprovalList { - if !contains(cclaSignature.EmailApprovalList, email) { - cclaSignature.EmailApprovalList = append(cclaSignature.EmailApprovalList, email) - } - } - for _, ghUserName := range updatedCorporateSignature.GithubUsernameApprovalList { - if !contains(cclaSignature.GithubUsernameApprovalList, ghUserName) { - cclaSignature.GithubUsernameApprovalList = append(cclaSignature.GithubUsernameApprovalList, ghUserName) - } - } - for _, glUserName := range updatedCorporateSignature.GitlabUsernameApprovalList { - if !contains(cclaSignature.GitlabUsernameApprovalList, glUserName) { - cclaSignature.GitlabUsernameApprovalList = append(cclaSignature.GitlabUsernameApprovalList, glUserName) - } - } - // If auto create ECLA is enabled for this Corporate Agreement, then create an ECLA for each employee that was added to the approval list // we get the complete user list as output from the processing of the approval list var userModelList []*models.User if corporateSigModel.AutoCreateECLA { log.WithFields(f).Debug("auto-create ECLA option is enabled - processing auto-enable request for all items on the approval list...") - userList, processErr := s.CreateOrUpdateEmployeeSignature(ctx, claGroupModel, companyModel, cclaSignature) + userList, processErr := s.CreateOrUpdateEmployeeSignature(ctx, claGroupModel, companyModel, updatedCorporateSignature) if processErr != nil { log.WithFields(f).WithError(processErr).Warnf("problem processing auto-enable request for company ID: %s, project ID: %s, cla group ID: %s", companyModel.CompanyID, claGroupModel.ProjectID, claGroupID) } userModelList = userList } else { - userList, processErr := s.createOrGetEmployeeModels(ctx, claGroupModel, companyModel, cclaSignature) + userList, processErr := s.createOrGetEmployeeModels(ctx, claGroupModel, companyModel, updatedCorporateSignature) if processErr != nil { log.WithFields(f).WithError(processErr).Warnf("problem processing user list for company ID: %s, project ID: %s, cla group ID: %s", companyModel.CompanyID, claGroupModel.ProjectID, claGroupID) } @@ -577,10 +540,6 @@ func (s service) UpdateApprovalList(ctx context.Context, authUser *auth.User, cl if handleStatusErr != nil { log.WithFields(f).WithError(handleStatusErr).Warnf("problem updating GitHub status for user: %+v", employeeUserModel) } - handleStatusErr = s.handleGitLabStatusUpdate(ctx, employeeUserModel) - if handleStatusErr != nil { - log.WithFields(f).WithError(handleStatusErr).Warnf("problem updating GitLabb status for user: %+v", employeeUserModel) - } }(utils.NewContextFromParent(ctx), employeeUserModel) } @@ -695,7 +654,7 @@ func (s service) createOrGetEmployeeModels(ctx context.Context, claGroupModel *m if simpleUserInfoModelEntry.GitLabUserName != "" { employeeUserModel, userLookupErr = s.usersService.GetUserByGitLabUsername(simpleUserInfoModelEntry.GitLabUserName) if userLookupErr != nil { - log.WithFields(f).WithError(userLookupErr).Warnf("problem looking up user by GitLab username: %s", simpleUserInfoModelEntry.GitLabUserName) + log.WithFields(f).WithError(userLookupErr).Warnf("problem looking up user by GitLab username: %s", simpleUserInfoModelEntry.GitHubUserName) } else if userLookupErr == nil && employeeUserModel != nil { updatedEmployeeUserModel, updateErr := s.updateUserCompanyID(ctx, employeeUserModel, companyModel) if updatedEmployeeUserModel != nil && updateErr == nil { @@ -731,7 +690,7 @@ func (s service) createOrGetEmployeeModels(ctx context.Context, claGroupModel *m } if gitLabUserModel.ID != 0 { - simpleUserInfoModelEntry.GitLabUserID = strconv.FormatInt(int64(gitLabUserModel.ID), 10) + simpleUserInfoModelEntry.GitHubUserID = strconv.FormatInt(int64(gitLabUserModel.ID), 10) } // User may not have a public email if gitLabUserModel.Email != "" { @@ -1435,188 +1394,3 @@ func (s service) handleGitHubStatusUpdate(ctx context.Context, employeeUserModel return nil } - -func (s service) handleGitLabStatusUpdate(ctx context.Context, employeeUserModel *models.User) error { - if employeeUserModel == nil { - return fmt.Errorf("employee user model is nil") - } - - f := logrus.Fields{ - "functionName": "v1.signatures.service.handleGitLabStatusUpdate", - utils.XREQUESTID: ctx.Value(utils.XREQUESTID), - "userID": employeeUserModel.UserID, - "GitLabUsername": employeeUserModel.GitlabUsername, - "GitLabID": employeeUserModel.GitlabID, - "userEmail": employeeUserModel.LfEmail.String(), - } - - log.WithFields(f).Debugf("processing GitLab status check request for user: %s", employeeUserModel.GitlabUsername) - activeMrMetadata, activeSigErr := s.repo.GetGitLabActiveMergeRequestMetadata(ctx, employeeUserModel.GitlabUsername, employeeUserModel.LfEmail.String()) - if activeSigErr != nil { - log.WithFields(f).WithError(activeSigErr).Warnf("unable to get active pull request metadata for user: %+v - unable to update GitLab status", employeeUserModel) - return activeSigErr - } - if activeMrMetadata == nil { - log.WithFields(f).Debugf("unable to get gitlab active merge requst metadata for user: %+v - unable to update gitlab status", employeeUserModel) - return nil - } - - // Fetch easycla repository - claRepository, repoErr := s.repositoryService.GetRepositoryByExternalID(ctx, activeMrMetadata.RepositoryID) - if repoErr != nil { - log.WithFields(f).WithError(repoErr).Warnf("unable to fetch repository by ID: %s - unable to update GitLab status", activeMrMetadata.RepositoryID) - return repoErr - } - - if !claRepository.Enabled { - log.WithFields(f).Debugf("repository: %s associated with PR: %s is NOT enabled - unable to update GitLab status", claRepository.RepositoryURL, activeMrMetadata.MergeRequestID) - return nil - } - - // fetch GitLab org details - gitlabOrg, gitlabOrgErr := s.gitlabOrgService.GetGitLabOrganizationByName(ctx, claRepository.RepositoryOrganizationName) - if gitlabOrgErr != nil { - log.WithFields(f).WithError(gitlabOrgErr).Warnf("unable to lookup GitLab organization by name: %s - unable to update GitLab status", claRepository.RepositoryOrganizationName) - return gitlabOrgErr - } - - repositoryID, idErr := strconv.Atoi(activeMrMetadata.RepositoryID) - if idErr != nil { - log.WithFields(f).WithError(idErr).Warnf("unable to convert repository ID: %s to integer - unable to update GitLab status", activeMrMetadata.RepositoryID) - return idErr - } - - mergeRequestID, idErr := strconv.Atoi(activeMrMetadata.MergeRequestID) - if idErr != nil { - log.WithFields(f).WithError(idErr).Warnf("unable to convert pull request ID: %s to integer - unable to update GitLab status", activeMrMetadata.RepositoryID) - return idErr - } - projectID, idErr := strconv.Atoi(activeMrMetadata.ProjectID) - if idErr != nil { - log.WithFields(f).WithError(idErr).Warnf("unable to convert pull request ID: %s to integer - unable to update GitLab status", activeMrMetadata.RepositoryID) - return idErr - } - - // Update change request - log.WithFields(f).Debugf("updating change request for repository: %d, merge request: %d", repositoryID, mergeRequestID) - updateErr := s.updateGitlabChangeRequest(ctx, gitlabOrg, int64(repositoryID), mergeRequestID, projectID, activeMrMetadata.ClaGroupID) - if updateErr != nil { - log.WithFields(f).WithError(updateErr).Warnf("unable to update merge request: %d", mergeRequestID) - return updateErr - } - - return nil -} - -// updateChangeRequest is a helper function that updates PR - typically after the auto ecla update -func (s service) updateGitlabChangeRequest(ctx context.Context, gitlabOrg *v2Models.GitlabOrganization, repositoryID int64, mergeRequestID int, projectID int, claGroupID string) error { - f := logrus.Fields{ - "functionName": "v1.signatures.service.updateGitlabChangeRequest", - "repositoryID": repositoryID, - "mergeRequestID": mergeRequestID, - "claGroupID": claGroupID, - } - - log.WithFields(f).Debugf("internal gitlab org : %s:%s is associated with repository id : %d", gitlabOrg.OrganizationID, gitlabOrg.OrganizationName, repositoryID) - - // fetch updated token info - log.WithFields(f).Debugf("refreshing gitlab org : %s:%s auth info", gitlabOrg.OrganizationID, gitlabOrg.OrganizationName) - oauthResponse, err := s.gitlabOrgService.RefreshGitLabOrganizationAuth(ctx, common.ToCommonModel(gitlabOrg)) - if err != nil { - return fmt.Errorf("refreshing gitlab org auth info failed : %v", err) - } - - gitlabClient, err := gitlab_api.NewGitlabOauthClient(*oauthResponse, s.gitLabApp) - if err != nil { - return fmt.Errorf("initializing gitlab client : %v", err) - } - - log.WithFields(f).Debugf("loading GitLab merge request info for merge request: %d", mergeRequestID) - lastSha, err := gitlab_api.GetLatestCommit(gitlabClient, projectID, mergeRequestID) - if err != nil { - return fmt.Errorf("fetching info for mr : %d and project : %d, failed : %v", mergeRequestID, projectID, err) - } - lastCommitSha := lastSha.ID - - f["lastCommitSha"] = lastCommitSha - log.WithFields(f).Debugf("last commit sha for merge request: %d is %s", mergeRequestID, lastCommitSha) - - _, err = gitlab_api.FetchMrInfo(gitlabClient, projectID, mergeRequestID) - if err != nil { - return fmt.Errorf("fetching info for mr : %d and project : %d, failed : %v", mergeRequestID, projectID, err) - } - - log.WithFields(f).Debugf("loading GitLab merge request participatants for merge request: %d", mergeRequestID) - participants, err := gitlab_api.FetchMrParticipants(gitlabClient, projectID, mergeRequestID) - if err != nil { - log.WithFields(f).WithError(err).Warnf("problem loading GitLab merge request participants for merge request: %d", mergeRequestID) - return fmt.Errorf("problem loading GitLab merge request participants for merge request: %d - error: %+v", mergeRequestID, err) - } - - if len(participants) == 0 { - return fmt.Errorf("no participants found in GitLab mr : %d, and gitlab project : %d", mergeRequestID, projectID) - } - - log.WithFields(f).Debugf("found %d participants for the MR ", len(participants)) - missingCLAMsg := "Missing CLA Authorization" - signedCLAMsg := "EasyCLA check passed. You are authorized to contribute." - - var missingUsers []*utils.GatedGitlabUser - var signedUsers []*gitlab.User - for _, gitlabUser := range participants { - log.WithFields(f).Debugf("checking if GitLab user: %s (%d) with email: %s has signed", gitlabUser.Username, gitlabUser.ID, gitlabUser.Email) - userSigned, signedCheckErr := s.gitlabActivityService.HasUserSigned(ctx, claGroupID, gitlabUser) - if signedCheckErr != nil { - log.WithFields(f).WithError(signedCheckErr).Warnf("problem checking if user : %s (%d) has signed - assuming not signed", gitlabUser.Username, gitlabUser.ID) - missingUsers = append(missingUsers, &utils.GatedGitlabUser{ - User: gitlabUser, - Err: err, - }) - continue - } - if userSigned { - log.WithFields(f).Infof("gitlabUser: %s (%d) has signed", gitlabUser.Username, gitlabUser.ID) - signedUsers = append(signedUsers, gitlabUser) - } else { - log.WithFields(f).Infof("gitlabUser: %s (%d) has NOT signed", gitlabUser.Username, gitlabUser.ID) - missingUsers = append(missingUsers, &utils.GatedGitlabUser{ - User: gitlabUser, - Err: err, - }) - } - } - - signURL := utils.GetFullSignURL(gitlabOrg.OrganizationID, strconv.Itoa(int(repositoryID)), strconv.Itoa(mergeRequestID)) - mrCommentContent := utils.PrepareMrCommentContent(missingUsers, signedUsers, signURL) - if len(missingUsers) > 0 { - log.WithFields(f).Errorf("merge request faild with 1 or more users not passing authorization - failed users : %+v", missingUsers) - if statusErr := gitlab_api.SetCommitStatus(gitlabClient, projectID, lastCommitSha, gitlab.Failed, missingCLAMsg, signURL); statusErr != nil { - log.WithFields(f).WithError(statusErr).Warnf("problem setting the commit status for merge request ID: %d, sha: %s", mergeRequestID, lastCommitSha) - return fmt.Errorf("setting commit status failed : %v", statusErr) - } - - if mrCommentErr := gitlab_api.SetMrComment(gitlabClient, projectID, mergeRequestID, mrCommentContent); mrCommentErr != nil { - log.WithFields(f).WithError(mrCommentErr).Warnf("problem setting the commit merge request comment for merge request ID: %d", mergeRequestID) - return fmt.Errorf("setting comment failed : %v", mrCommentErr) - } - - return nil - } - - commitStatusErr := gitlab_api.SetCommitStatus(gitlabClient, projectID, lastCommitSha, gitlab.Success, signedCLAMsg, "") - if commitStatusErr != nil { - log.WithFields(f).WithError(commitStatusErr).Warnf("problem setting the commit status for merge request ID: %d, sha: %s", mergeRequestID, lastCommitSha) - return fmt.Errorf("setting commit status failed : %v", commitStatusErr) - } - - if mrCommentErr := gitlab_api.SetMrComment(gitlabClient, projectID, mergeRequestID, mrCommentContent); mrCommentErr != nil { - log.WithFields(f).WithError(mrCommentErr).Warnf("problem setting the commit merge request comment for merge request ID: %d", mergeRequestID) - return fmt.Errorf("setting comment failed : %v", mrCommentErr) - } - return nil -} - -func contains(s []string, searchterm string) bool { - i := sort.SearchStrings(s, searchterm) - return i < len(s) && s[i] == searchterm -} diff --git a/cla-backend-go/utils/gitlab.go b/cla-backend-go/utils/gitlab.go deleted file mode 100644 index 4dede91df..000000000 --- a/cla-backend-go/utils/gitlab.go +++ /dev/null @@ -1,121 +0,0 @@ -// Copyright The Linux Foundation and each contributor to CommunityBridge. -// SPDX-License-Identifier: MIT - -package utils - -import ( - "errors" - "fmt" - - "github.com/communitybridge/easycla/cla-backend-go/config" - log "github.com/communitybridge/easycla/cla-backend-go/logging" - "github.com/sirupsen/logrus" - "github.com/xanzy/go-gitlab" -) - -type GatedGitlabUser struct { - *gitlab.User - Err error -} - -var missingCompanyAffiliation = errors.New("must confirm affiliation with their company") - -func PrepareMrCommentContent(missingUsers []*GatedGitlabUser, signedUsers []*gitlab.User, signURL string) string { - landingPage := config.GetConfig().CLALandingPage - landingPage += "/#/?version=2" - - var badgeHyperlink string - if len(missingUsers) > 0 { - badgeHyperlink = signURL - } else { - badgeHyperlink = landingPage - } - - coveredBadge := fmt.Sprintf(` - CLA Signed
`, badgeHyperlink) - failedBadge := fmt.Sprintf(` -CLA Not Signed
`, badgeHyperlink) - // missingUserIDBadge := fmt.Sprintf(` - // CLA Missing ID
`, badgeHyperlink) - confirmationNeededBadge := fmt.Sprintf(` -CLA Confirmation Needed
`, badgeHyperlink) - - var body string - - const startUl = "