diff --git a/server/controllers/api_controller.go b/server/controllers/api_controller.go index 784120e982..43e316bbdf 100644 --- a/server/controllers/api_controller.go +++ b/server/controllers/api_controller.go @@ -197,7 +197,7 @@ func (a *APIController) apiParseAndValidate(r *http.Request) (*APIRequest, *comm if err != nil { return nil, nil, http.StatusBadRequest, err } - cloneURL, err := a.VCSClient.GetCloneURL(VCSHostType, request.Repository) + cloneURL, err := a.VCSClient.GetCloneURL(a.Logger, VCSHostType, request.Repository) if err != nil { return nil, nil, http.StatusInternalServerError, err } diff --git a/server/controllers/events/events_controller.go b/server/controllers/events/events_controller.go index 121fb7e900..d8be6e7ed0 100644 --- a/server/controllers/events/events_controller.go +++ b/server/controllers/events/events_controller.go @@ -297,7 +297,7 @@ func (e *VCSEventsController) HandleGithubCommentEvent(event *github.IssueCommen } } - baseRepo, user, pullNum, err := e.Parser.ParseGithubIssueCommentEvent(event) + baseRepo, user, pullNum, err := e.Parser.ParseGithubIssueCommentEvent(logger, event) wrapped := errors.Wrapf(err, "Failed parsing event: %s", githubReqID) if err != nil { @@ -409,7 +409,7 @@ func (e *VCSEventsController) handleBitbucketServerPullRequestEvent(w http.Respo // request if the event is a pull request closed event. It's exported to make // testing easier. func (e *VCSEventsController) HandleGithubPullRequestEvent(logger logging.SimpleLogging, pullEvent *github.PullRequestEvent, githubReqID string) HTTPResponse { - pull, pullEventType, baseRepo, headRepo, user, err := e.Parser.ParseGithubPullEvent(pullEvent) + pull, pullEventType, baseRepo, headRepo, user, err := e.Parser.ParseGithubPullEvent(logger, pullEvent) if err != nil { wrapped := errors.Wrapf(err, "Error parsing pull data: %s %s", err, githubReqID) return HTTPResponse{ @@ -465,7 +465,7 @@ func (e *VCSEventsController) handlePullRequestEvent(logger logging.SimpleLoggin } case models.ClosedPullEvent: // If the pull request was closed, we delete locks. - if err := e.PullCleaner.CleanUpPull(baseRepo, pull); err != nil { + if err := e.PullCleaner.CleanUpPull(logger, baseRepo, pull); err != nil { return HTTPResponse{ body: err.Error(), err: HTTPError{ @@ -536,6 +536,11 @@ func (e *VCSEventsController) HandleGitlabCommentEvent(w http.ResponseWriter, ev } func (e *VCSEventsController) handleCommentEvent(logger logging.SimpleLogging, baseRepo models.Repo, maybeHeadRepo *models.Repo, maybePull *models.PullRequest, user models.User, pullNum int, comment string, commentID int64, vcsHost models.VCSHostType) HTTPResponse { + logger = logger.WithHistory( + "repo", baseRepo.FullName, + "pull", pullNum, + ) + parseResult := e.CommentParser.Parse(comment, vcsHost) if parseResult.Ignore { truncated := comment @@ -568,7 +573,7 @@ func (e *VCSEventsController) handleCommentEvent(logger logging.SimpleLogging, b // It's a comment we're gonna react to, so add a reaction. if e.EmojiReaction != "" { - err := e.VCSClient.ReactToComment(baseRepo, pullNum, commentID, e.EmojiReaction) + err := e.VCSClient.ReactToComment(logger, baseRepo, pullNum, commentID, e.EmojiReaction) if err != nil { logger.Warn("Failed to react to comment: %s", err) } @@ -579,7 +584,7 @@ func (e *VCSEventsController) handleCommentEvent(logger logging.SimpleLogging, b // We do this here rather than earlier because we need access to the pull // variable to comment back on the pull request. if parseResult.CommentResponse != "" { - if err := e.VCSClient.CreateComment(baseRepo, pullNum, parseResult.CommentResponse, ""); err != nil { + if err := e.VCSClient.CreateComment(logger, baseRepo, pullNum, parseResult.CommentResponse, ""); err != nil { logger.Err("unable to comment on pull request: %s", err) } return HTTPResponse{ @@ -762,7 +767,7 @@ func (e *VCSEventsController) commentNotAllowlisted(baseRepo models.Repo, pullNu } errMsg := "```\nError: This repo is not allowlisted for Atlantis.\n```" - if err := e.VCSClient.CreateComment(baseRepo, pullNum, errMsg, ""); err != nil { + if err := e.VCSClient.CreateComment(e.Logger, baseRepo, pullNum, errMsg, ""); err != nil { e.Logger.Err("unable to comment on pull request: %s", err) } } diff --git a/server/controllers/events/events_controller_e2e_test.go b/server/controllers/events/events_controller_e2e_test.go index aaf7f8d8ab..e2d0a7115c 100644 --- a/server/controllers/events/events_controller_e2e_test.go +++ b/server/controllers/events/events_controller_e2e_test.go @@ -643,8 +643,10 @@ func TestGitHubWorkflow(t *testing.T) { // Setup test dependencies. w := httptest.NewRecorder() - When(githubGetter.GetPullRequest(Any[models.Repo](), Any[int]())).ThenReturn(GitHubPullRequestParsed(headSHA), nil) - When(vcsClient.GetModifiedFiles(Any[models.Repo](), Any[models.PullRequest]())).ThenReturn(c.ModifiedFiles, nil) + When(githubGetter.GetPullRequest( + Any[logging.SimpleLogging](), Any[models.Repo](), Any[int]())).ThenReturn(GitHubPullRequestParsed(headSHA), nil) + When(vcsClient.GetModifiedFiles( + Any[logging.SimpleLogging](), Any[models.Repo](), Any[models.PullRequest]())).ThenReturn(c.ModifiedFiles, nil) // First, send the open pull request event which triggers autoplan. pullOpenedReq := GitHubPullRequestOpenedEvent(t, headSHA) @@ -707,7 +709,8 @@ func TestGitHubWorkflow(t *testing.T) { expNumReplies++ } - _, _, actReplies, _ := vcsClient.VerifyWasCalled(Times(expNumReplies)).CreateComment(Any[models.Repo](), Any[int](), Any[string](), Any[string]()).GetAllCapturedArguments() + _, _, _, actReplies, _ := vcsClient.VerifyWasCalled(Times(expNumReplies)).CreateComment( + Any[logging.SimpleLogging](), Any[models.Repo](), Any[int](), Any[string](), Any[string]()).GetAllCapturedArguments() Assert(t, len(c.ExpReplies) == len(actReplies), "missing expected replies, got %d but expected %d", len(actReplies), len(c.ExpReplies)) for i, expReply := range c.ExpReplies { assertCommentEquals(t, expReply, actReplies[i], c.RepoDir, c.ExpParallel) @@ -715,9 +718,9 @@ func TestGitHubWorkflow(t *testing.T) { if c.ExpAutomerge { // Verify that the merge API call was made. - vcsClient.VerifyWasCalledOnce().MergePull(Any[models.PullRequest](), Any[models.PullRequestOptions]()) + vcsClient.VerifyWasCalledOnce().MergePull(Any[logging.SimpleLogging](), Any[models.PullRequest](), Any[models.PullRequestOptions]()) } else { - vcsClient.VerifyWasCalled(Never()).MergePull(Any[models.PullRequest](), Any[models.PullRequestOptions]()) + vcsClient.VerifyWasCalled(Never()).MergePull(Any[logging.SimpleLogging](), Any[models.PullRequest](), Any[models.PullRequestOptions]()) } }) } @@ -819,8 +822,8 @@ func TestSimpleWorkflow_terraformLockFile(t *testing.T) { // Setup test dependencies. w := httptest.NewRecorder() - When(githubGetter.GetPullRequest(Any[models.Repo](), Any[int]())).ThenReturn(GitHubPullRequestParsed(headSHA), nil) - When(vcsClient.GetModifiedFiles(Any[models.Repo](), Any[models.PullRequest]())).ThenReturn(c.ModifiedFiles, nil) + When(githubGetter.GetPullRequest(Any[logging.SimpleLogging](), Any[models.Repo](), Any[int]())).ThenReturn(GitHubPullRequestParsed(headSHA), nil) + When(vcsClient.GetModifiedFiles(Any[logging.SimpleLogging](), Any[models.Repo](), Any[models.PullRequest]())).ThenReturn(c.ModifiedFiles, nil) // First, send the open pull request event which triggers autoplan. pullOpenedReq := GitHubPullRequestOpenedEvent(t, headSHA) @@ -880,7 +883,8 @@ func TestSimpleWorkflow_terraformLockFile(t *testing.T) { // and apply have 1 for each comment plus one for the locks deleted at the // end. - _, _, actReplies, _ := vcsClient.VerifyWasCalled(Times(2)).CreateComment(Any[models.Repo](), Any[int](), Any[string](), Any[string]()).GetAllCapturedArguments() + _, _, _, actReplies, _ := vcsClient.VerifyWasCalled(Times(2)).CreateComment( + Any[logging.SimpleLogging](), Any[models.Repo](), Any[int](), Any[string](), Any[string]()).GetAllCapturedArguments() Assert(t, len(c.ExpReplies) == len(actReplies), "missing expected replies, got %d but expected %d", len(actReplies), len(c.ExpReplies)) for i, expReply := range c.ExpReplies { assertCommentEquals(t, expReply, actReplies[i], c.RepoDir, false) @@ -1188,12 +1192,16 @@ func TestGitHubWorkflowWithPolicyCheck(t *testing.T) { // Setup test dependencies. w := httptest.NewRecorder() - When(vcsClient.PullIsMergeable(Any[models.Repo](), Any[models.PullRequest](), Eq("atlantis-test"))).ThenReturn(true, nil) - When(vcsClient.PullIsApproved(Any[models.Repo](), Any[models.PullRequest]())).ThenReturn(models.ApprovalStatus{ + When(vcsClient.PullIsMergeable( + Any[logging.SimpleLogging](), Any[models.Repo](), Any[models.PullRequest](), Eq("atlantis-test"))).ThenReturn(true, nil) + When(vcsClient.PullIsApproved( + Any[logging.SimpleLogging](), Any[models.Repo](), Any[models.PullRequest]())).ThenReturn(models.ApprovalStatus{ IsApproved: true, }, nil) - When(githubGetter.GetPullRequest(Any[models.Repo](), Any[int]())).ThenReturn(GitHubPullRequestParsed(headSHA), nil) - When(vcsClient.GetModifiedFiles(Any[models.Repo](), Any[models.PullRequest]())).ThenReturn(c.ModifiedFiles, nil) + When(githubGetter.GetPullRequest( + Any[logging.SimpleLogging](), Any[models.Repo](), Any[int]())).ThenReturn(GitHubPullRequestParsed(headSHA), nil) + When(vcsClient.GetModifiedFiles( + Any[logging.SimpleLogging](), Any[models.Repo](), Any[models.PullRequest]())).ThenReturn(c.ModifiedFiles, nil) // First, send the open pull request event which triggers autoplan. pullOpenedReq := GitHubPullRequestOpenedEvent(t, headSHA) @@ -1244,7 +1252,8 @@ func TestGitHubWorkflowWithPolicyCheck(t *testing.T) { if !c.ExpPolicyChecks { expNumReplies-- } - _, _, actReplies, _ := vcsClient.VerifyWasCalled(Times(expNumReplies)).CreateComment(Any[models.Repo](), Any[int](), Any[string](), Any[string]()).GetAllCapturedArguments() + _, _, _, actReplies, _ := vcsClient.VerifyWasCalled(Times(expNumReplies)).CreateComment( + Any[logging.SimpleLogging](), Any[models.Repo](), Any[int](), Any[string](), Any[string]()).GetAllCapturedArguments() Assert(t, len(c.ExpReplies) == len(actReplies), "missing expected replies, got %d but expected %d", len(actReplies), len(c.ExpReplies)) for i, expReply := range c.ExpReplies { @@ -1253,9 +1262,9 @@ func TestGitHubWorkflowWithPolicyCheck(t *testing.T) { if c.ExpAutomerge { // Verify that the merge API call was made. - vcsClient.VerifyWasCalledOnce().MergePull(Any[models.PullRequest](), Any[models.PullRequestOptions]()) + vcsClient.VerifyWasCalledOnce().MergePull(Any[logging.SimpleLogging](), Any[models.PullRequest](), Any[models.PullRequestOptions]()) } else { - vcsClient.VerifyWasCalled(Never()).MergePull(Any[models.PullRequest](), Any[models.PullRequestOptions]()) + vcsClient.VerifyWasCalled(Never()).MergePull(Any[logging.SimpleLogging](), Any[models.PullRequest](), Any[models.PullRequestOptions]()) } }) } diff --git a/server/controllers/events/events_controller_test.go b/server/controllers/events/events_controller_test.go index ad23ea7ddc..2d2e15bc7e 100644 --- a/server/controllers/events/events_controller_test.go +++ b/server/controllers/events/events_controller_test.go @@ -155,7 +155,7 @@ func TestPost_GithubInvalidComment(t *testing.T) { req.Header.Set(githubHeader, "issue_comment") event := `{"action": "created"}` When(v.Validate(req, secret)).ThenReturn([]byte(event), nil) - When(p.ParseGithubIssueCommentEvent(Any[*github.IssueCommentEvent]())).ThenReturn(models.Repo{}, models.User{}, 1, errors.New("err")) + When(p.ParseGithubIssueCommentEvent(Any[logging.SimpleLogging](), Any[*github.IssueCommentEvent]())).ThenReturn(models.Repo{}, models.User{}, 1, errors.New("err")) w := httptest.NewRecorder() e.Post(w, req) ResponseContains(t, w, http.StatusBadRequest, "Failed parsing event") @@ -180,12 +180,12 @@ func TestPost_GithubCommentInvalidCommand(t *testing.T) { req.Header.Set(githubHeader, "issue_comment") event := `{"action": "created"}` When(v.Validate(req, secret)).ThenReturn([]byte(event), nil) - When(p.ParseGithubIssueCommentEvent(Any[*github.IssueCommentEvent]())).ThenReturn(models.Repo{}, models.User{}, 1, nil) + When(p.ParseGithubIssueCommentEvent(Any[logging.SimpleLogging](), Any[*github.IssueCommentEvent]())).ThenReturn(models.Repo{}, models.User{}, 1, nil) When(cp.Parse("", models.Github)).ThenReturn(events.CommentParseResult{Ignore: true}) w := httptest.NewRecorder() e.Post(w, req) ResponseContains(t, w, http.StatusOK, "Ignoring non-command comment: \"\"") - vcsClient.VerifyWasCalled(Never()).ReactToComment(models.Repo{}, 1, 1, "eyes") + vcsClient.VerifyWasCalled(Never()).ReactToComment(Any[logging.SimpleLogging](), Eq(models.Repo{}), Eq(1), Eq(int64(1)), Eq("eyes")) } func TestPost_GitlabCommentNotAllowlisted(t *testing.T) { @@ -216,7 +216,8 @@ func TestPost_GitlabCommentNotAllowlisted(t *testing.T) { exp := "Repo not allowlisted" Assert(t, strings.Contains(string(body), exp), "exp %q to be contained in %q", exp, string(body)) expRepo, _ := models.NewRepo(models.Gitlab, "gitlabhq/gitlab-test", "https://example.com/gitlabhq/gitlab-test.git", "", "") - vcsClient.VerifyWasCalledOnce().CreateComment(expRepo, 1, "```\nError: This repo is not allowlisted for Atlantis.\n```", "") + vcsClient.VerifyWasCalledOnce().CreateComment( + Any[logging.SimpleLogging](), Eq(expRepo), Eq(1), Eq("```\nError: This repo is not allowlisted for Atlantis.\n```"), Eq("")) } func TestPost_GitlabCommentNotAllowlistedWithSilenceErrors(t *testing.T) { @@ -247,7 +248,7 @@ func TestPost_GitlabCommentNotAllowlistedWithSilenceErrors(t *testing.T) { body, _ := io.ReadAll(w.Result().Body) exp := "Repo not allowlisted" Assert(t, strings.Contains(string(body), exp), "exp %q to be contained in %q", exp, string(body)) - vcsClient.VerifyWasCalled(Never()).CreateComment(Any[models.Repo](), Any[int](), Any[string](), Any[string]()) + vcsClient.VerifyWasCalled(Never()).CreateComment(Any[logging.SimpleLogging](), Any[models.Repo](), Any[int](), Any[string](), Any[string]()) } @@ -280,7 +281,8 @@ func TestPost_GithubCommentNotAllowlisted(t *testing.T) { exp := "Repo not allowlisted" Assert(t, strings.Contains(string(body), exp), "exp %q to be contained in %q", exp, string(body)) expRepo, _ := models.NewRepo(models.Github, "baxterthehacker/public-repo", "https://github.com/baxterthehacker/public-repo.git", "", "") - vcsClient.VerifyWasCalledOnce().CreateComment(expRepo, 2, "```\nError: This repo is not allowlisted for Atlantis.\n```", "") + vcsClient.VerifyWasCalledOnce().CreateComment( + Any[logging.SimpleLogging](), Eq(expRepo), Eq(2), Eq("```\nError: This repo is not allowlisted for Atlantis.\n```"), Eq("")) } func TestPost_GithubCommentNotAllowlistedWithSilenceErrors(t *testing.T) { @@ -312,7 +314,7 @@ func TestPost_GithubCommentNotAllowlistedWithSilenceErrors(t *testing.T) { body, _ := io.ReadAll(w.Result().Body) exp := "Repo not allowlisted" Assert(t, strings.Contains(string(body), exp), "exp %q to be contained in %q", exp, string(body)) - vcsClient.VerifyWasCalled(Never()).CreateComment(Any[models.Repo](), Any[int](), Any[string](), Any[string]()) + vcsClient.VerifyWasCalled(Never()).CreateComment(Any[logging.SimpleLogging](), Any[models.Repo](), Any[int](), Any[string](), Any[string]()) } func TestPost_GitlabCommentResponse(t *testing.T) { @@ -324,7 +326,7 @@ func TestPost_GitlabCommentResponse(t *testing.T) { When(cp.Parse("", models.Gitlab)).ThenReturn(events.CommentParseResult{CommentResponse: "a comment"}) w := httptest.NewRecorder() e.Post(w, req) - vcsClient.VerifyWasCalledOnce().CreateComment(models.Repo{}, 0, "a comment", "") + vcsClient.VerifyWasCalledOnce().CreateComment(Any[logging.SimpleLogging](), Eq(models.Repo{}), Eq(0), Eq("a comment"), Eq("")) ResponseContains(t, w, http.StatusOK, "Commenting back on pull request") } @@ -337,12 +339,12 @@ func TestPost_GithubCommentResponse(t *testing.T) { When(v.Validate(req, secret)).ThenReturn([]byte(event), nil) baseRepo := models.Repo{} user := models.User{} - When(p.ParseGithubIssueCommentEvent(Any[*github.IssueCommentEvent]())).ThenReturn(baseRepo, user, 1, nil) + When(p.ParseGithubIssueCommentEvent(Any[logging.SimpleLogging](), Any[*github.IssueCommentEvent]())).ThenReturn(baseRepo, user, 1, nil) When(cp.Parse("", models.Github)).ThenReturn(events.CommentParseResult{CommentResponse: "a comment"}) w := httptest.NewRecorder() e.Post(w, req) - vcsClient.VerifyWasCalledOnce().CreateComment(baseRepo, 1, "a comment", "") + vcsClient.VerifyWasCalledOnce().CreateComment(Any[logging.SimpleLogging](), Eq(baseRepo), Eq(1), Eq("a comment"), Eq("")) ResponseContains(t, w, http.StatusOK, "Commenting back on pull request") } @@ -371,7 +373,7 @@ func TestPost_GithubCommentSuccess(t *testing.T) { baseRepo := models.Repo{} user := models.User{} cmd := events.CommentCommand{} - When(p.ParseGithubIssueCommentEvent(Any[*github.IssueCommentEvent]())).ThenReturn(baseRepo, user, 1, nil) + When(p.ParseGithubIssueCommentEvent(Any[logging.SimpleLogging](), Any[*github.IssueCommentEvent]())).ThenReturn(baseRepo, user, 1, nil) When(cp.Parse("", models.Github)).ThenReturn(events.CommentParseResult{Command: &cmd}) w := httptest.NewRecorder() e.Post(w, req) @@ -391,13 +393,13 @@ func TestPost_GithubCommentReaction(t *testing.T) { baseRepo := models.Repo{} user := models.User{} cmd := events.CommentCommand{Name: command.Plan} - When(p.ParseGithubIssueCommentEvent(Any[*github.IssueCommentEvent]())).ThenReturn(baseRepo, user, 1, nil) + When(p.ParseGithubIssueCommentEvent(Any[logging.SimpleLogging](), Any[*github.IssueCommentEvent]())).ThenReturn(baseRepo, user, 1, nil) When(cp.Parse(testComment, models.Github)).ThenReturn(events.CommentParseResult{Command: &cmd}) w := httptest.NewRecorder() e.Post(w, req) ResponseContains(t, w, http.StatusOK, "Processing...") - vcsClient.VerifyWasCalledOnce().ReactToComment(baseRepo, 1, 1, "eyes") + vcsClient.VerifyWasCalledOnce().ReactToComment(Any[logging.SimpleLogging](), Eq(baseRepo), Eq(1), Eq(int64(1)), Eq("eyes")) } func TestPost_GilabCommentReaction(t *testing.T) { @@ -411,7 +413,7 @@ func TestPost_GilabCommentReaction(t *testing.T) { w := httptest.NewRecorder() e.Post(w, req) ResponseContains(t, w, http.StatusOK, "Processing...") - vcsClient.VerifyWasCalledOnce().ReactToComment(models.Repo{}, 0, 0, "eyes") + vcsClient.VerifyWasCalledOnce().ReactToComment(Any[logging.SimpleLogging](), Eq(models.Repo{}), Eq(0), Eq(int64(0)), Eq("eyes")) } func TestPost_GithubPullRequestInvalid(t *testing.T) { @@ -422,7 +424,7 @@ func TestPost_GithubPullRequestInvalid(t *testing.T) { event := `{"action": "closed"}` When(v.Validate(req, secret)).ThenReturn([]byte(event), nil) - When(p.ParseGithubPullEvent(Any[*github.PullRequestEvent]())).ThenReturn(models.PullRequest{}, models.OpenedPullEvent, models.Repo{}, models.Repo{}, models.User{}, errors.New("err")) + When(p.ParseGithubPullEvent(Any[logging.SimpleLogging](), Any[*github.PullRequestEvent]())).ThenReturn(models.PullRequest{}, models.OpenedPullEvent, models.Repo{}, models.Repo{}, models.User{}, errors.New("err")) w := httptest.NewRecorder() e.Post(w, req) ResponseContains(t, w, http.StatusBadRequest, "Error parsing pull data: err") @@ -742,8 +744,8 @@ func TestPost_GithubPullRequestClosedErrCleaningPull(t *testing.T) { When(v.Validate(req, secret)).ThenReturn([]byte(event), nil) repo := models.Repo{} pull := models.PullRequest{State: models.ClosedPullState} - When(p.ParseGithubPullEvent(Any[*github.PullRequestEvent]())).ThenReturn(pull, models.OpenedPullEvent, repo, repo, models.User{}, nil) - When(c.CleanUpPull(repo, pull)).ThenReturn(errors.New("cleanup err")) + When(p.ParseGithubPullEvent(Any[logging.SimpleLogging](), Any[*github.PullRequestEvent]())).ThenReturn(pull, models.OpenedPullEvent, repo, repo, models.User{}, nil) + When(c.CleanUpPull(Any[logging.SimpleLogging](), repo, pull)).ThenReturn(errors.New("cleanup err")) w := httptest.NewRecorder() e.Post(w, req) ResponseContains(t, w, http.StatusInternalServerError, "Error cleaning pull request: cleanup err") @@ -761,7 +763,7 @@ func TestPost_GitlabMergeRequestClosedErrCleaningPull(t *testing.T) { repo := models.Repo{} pullRequest := models.PullRequest{State: models.ClosedPullState} When(p.ParseGitlabMergeRequestEvent(event)).ThenReturn(pullRequest, models.OpenedPullEvent, repo, repo, models.User{}, nil) - When(c.CleanUpPull(repo, pullRequest)).ThenReturn(errors.New("err")) + When(c.CleanUpPull(Any[logging.SimpleLogging](), repo, pullRequest)).ThenReturn(errors.New("err")) w := httptest.NewRecorder() e.Post(w, req) ResponseContains(t, w, http.StatusInternalServerError, "Error cleaning pull request: err") @@ -778,8 +780,8 @@ func TestPost_GithubClosedPullRequestSuccess(t *testing.T) { When(v.Validate(req, secret)).ThenReturn([]byte(event), nil) repo := models.Repo{} pull := models.PullRequest{State: models.ClosedPullState} - When(p.ParseGithubPullEvent(Any[*github.PullRequestEvent]())).ThenReturn(pull, models.OpenedPullEvent, repo, repo, models.User{}, nil) - When(c.CleanUpPull(repo, pull)).ThenReturn(nil) + When(p.ParseGithubPullEvent(Any[logging.SimpleLogging](), Any[*github.PullRequestEvent]())).ThenReturn(pull, models.OpenedPullEvent, repo, repo, models.User{}, nil) + When(c.CleanUpPull(Any[logging.SimpleLogging](), repo, pull)).ThenReturn(nil) w := httptest.NewRecorder() e.Post(w, req) ResponseContains(t, w, http.StatusOK, "Pull request cleaned successfully") @@ -867,7 +869,9 @@ func TestPost_BBServerPullClosed(t *testing.T) { Type: models.BitbucketServer, }, } - pullCleaner.VerifyWasCalledOnce().CleanUpPull(expRepo, models.PullRequest{ + pullCleaner.VerifyWasCalledOnce().CleanUpPull( + logger, + expRepo, models.PullRequest{ Num: 10, HeadCommit: "2d9fb6b9a46eafb1dcef7b008d1a429d45ca742c", URL: "https://bbserver.com/projects/PROJ/repos/repository/pull-requests/10", @@ -931,7 +935,7 @@ func TestPost_PullOpenedOrUpdated(t *testing.T) { When(v.Validate(req, secret)).ThenReturn([]byte(event), nil) repo = models.Repo{} pullRequest = models.PullRequest{State: models.ClosedPullState} - When(p.ParseGithubPullEvent(Any[*github.PullRequestEvent]())).ThenReturn(pullRequest, models.OpenedPullEvent, repo, repo, models.User{}, nil) + When(p.ParseGithubPullEvent(Any[logging.SimpleLogging](), Any[*github.PullRequestEvent]())).ThenReturn(pullRequest, models.OpenedPullEvent, repo, repo, models.User{}, nil) } w := httptest.NewRecorder() diff --git a/server/controllers/github_app_controller.go b/server/controllers/github_app_controller.go index 670f13351c..5ac08d00fa 100644 --- a/server/controllers/github_app_controller.go +++ b/server/controllers/github_app_controller.go @@ -62,7 +62,7 @@ func (g *GithubAppController) ExchangeCode(w http.ResponseWriter, r *http.Reques return } - app, err := client.ExchangeCode(code) + app, err := client.ExchangeCode(g.Logger, code) if err != nil { g.respond(w, logging.Error, http.StatusInternalServerError, "Failed to exchange code for github app: %s", err) return diff --git a/server/controllers/locks_controller.go b/server/controllers/locks_controller.go index 85a4420430..bab7fad27a 100644 --- a/server/controllers/locks_controller.go +++ b/server/controllers/locks_controller.go @@ -133,7 +133,7 @@ func (l *LocksController) DeleteLock(w http.ResponseWriter, r *http.Request) { // Once the lock has been deleted, comment back on the pull request. comment := fmt.Sprintf("**Warning**: The plan for dir: `%s` workspace: `%s` was **discarded** via the Atlantis UI.\n\n"+ "To `apply` this plan you must run `plan` again.", lock.Project.Path, lock.Workspace) - if err = l.VCSClient.CreateComment(lock.Pull.BaseRepo, lock.Pull.Num, comment, ""); err != nil { + if err = l.VCSClient.CreateComment(l.Logger, lock.Pull.BaseRepo, lock.Pull.Num, comment, ""); err != nil { l.Logger.Warn("failed commenting on pull request: %s", err) } } else { diff --git a/server/controllers/locks_controller_test.go b/server/controllers/locks_controller_test.go index 88e538d15d..0f80e7c1f7 100644 --- a/server/controllers/locks_controller_test.go +++ b/server/controllers/locks_controller_test.go @@ -266,7 +266,7 @@ func TestDeleteLock_OldFormat(t *testing.T) { w := httptest.NewRecorder() lc.DeleteLock(w, req) ResponseContains(t, w, http.StatusOK, "Deleted lock id \"id\"") - cp.VerifyWasCalled(Never()).CreateComment(Any[models.Repo](), Any[int](), Any[string](), Any[string]()) + cp.VerifyWasCalled(Never()).CreateComment(Any[logging.SimpleLogging](), Any[models.Repo](), Any[int](), Any[string](), Any[string]()) } func TestDeleteLock_UpdateProjectStatus(t *testing.T) { @@ -350,7 +350,7 @@ func TestDeleteLock_CommentFailed(t *testing.T) { tmp := t.TempDir() backend, err := db.New(tmp) Ok(t, err) - When(cp.CreateComment(Any[models.Repo](), Any[int](), Any[string](), Any[string]())).ThenReturn(errors.New("err")) + When(cp.CreateComment(Any[logging.SimpleLogging](), Any[models.Repo](), Any[int](), Any[string](), Any[string]())).ThenReturn(errors.New("err")) lc := controllers.LocksController{ DeleteLockCommand: dlc, Logger: logging.NewNoopLogger(t), @@ -401,7 +401,7 @@ func TestDeleteLock_CommentSuccess(t *testing.T) { w := httptest.NewRecorder() lc.DeleteLock(w, req) ResponseContains(t, w, http.StatusOK, "Deleted lock id \"id\"") - cp.VerifyWasCalled(Once()).CreateComment(pull.BaseRepo, pull.Num, - "**Warning**: The plan for dir: `path` workspace: `workspace` was **discarded** via the Atlantis UI.\n\n"+ - "To `apply` this plan you must run `plan` again.", "") + cp.VerifyWasCalled(Once()).CreateComment(Any[logging.SimpleLogging](), Eq(pull.BaseRepo), Eq(pull.Num), + Eq("**Warning**: The plan for dir: `path` workspace: `workspace` was **discarded** via the Atlantis UI.\n\n"+ + "To `apply` this plan you must run `plan` again."), Eq("")) } diff --git a/server/core/runtime/pull_approved_checker.go b/server/core/runtime/pull_approved_checker.go index d3d9c39080..f4884c2e98 100644 --- a/server/core/runtime/pull_approved_checker.go +++ b/server/core/runtime/pull_approved_checker.go @@ -2,10 +2,11 @@ package runtime import ( "github.com/runatlantis/atlantis/server/events/models" + "github.com/runatlantis/atlantis/server/logging" ) //go:generate pegomock generate --package mocks -o mocks/mock_pull_approved_checker.go PullApprovedChecker type PullApprovedChecker interface { - PullIsApproved(baseRepo models.Repo, pull models.PullRequest) (models.ApprovalStatus, error) + PullIsApproved(logger logging.SimpleLogging, baseRepo models.Repo, pull models.PullRequest) (models.ApprovalStatus, error) } diff --git a/server/events/apply_command_runner.go b/server/events/apply_command_runner.go index fdaf36d337..2a40c454d9 100644 --- a/server/events/apply_command_runner.go +++ b/server/events/apply_command_runner.go @@ -77,7 +77,7 @@ func (a *ApplyCommandRunner) Run(ctx *command.Context, cmd *CommentCommand) { if locked { ctx.Log.Info("ignoring apply command since apply disabled globally") - if err := a.vcsClient.CreateComment(baseRepo, pull.Num, applyDisabledComment, command.Apply.String()); err != nil { + if err := a.vcsClient.CreateComment(ctx.Log, baseRepo, pull.Num, applyDisabledComment, command.Apply.String()); err != nil { ctx.Log.Err("unable to comment on pull request: %s", err) } @@ -86,14 +86,14 @@ func (a *ApplyCommandRunner) Run(ctx *command.Context, cmd *CommentCommand) { if a.DisableApplyAll && !cmd.IsForSpecificProject() { ctx.Log.Info("ignoring apply command without flags since apply all is disabled") - if err := a.vcsClient.CreateComment(baseRepo, pull.Num, applyAllDisabledComment, command.Apply.String()); err != nil { + if err := a.vcsClient.CreateComment(ctx.Log, baseRepo, pull.Num, applyAllDisabledComment, command.Apply.String()); err != nil { ctx.Log.Err("unable to comment on pull request: %s", err) } return } - if err = a.commitStatusUpdater.UpdateCombined(baseRepo, pull, models.PendingCommitStatus, cmd.CommandName()); err != nil { + if err = a.commitStatusUpdater.UpdateCombined(ctx.Log, baseRepo, pull, models.PendingCommitStatus, cmd.CommandName()); err != nil { ctx.Log.Warn("unable to update commit status: %s", err) } @@ -102,7 +102,7 @@ func (a *ApplyCommandRunner) Run(ctx *command.Context, cmd *CommentCommand) { // required the Atlantis status checks to pass, then we've now changed // the mergeability status of the pull request. // This sets the approved, mergeable, and sqlocked status in the context. - ctx.PullRequestStatus, err = a.pullReqStatusFetcher.FetchPullStatus(pull) + ctx.PullRequestStatus, err = a.pullReqStatusFetcher.FetchPullStatus(ctx.Log, pull) if err != nil { // On error we continue the request with mergeable assumed false. // We want to continue because not all apply's will need this status, @@ -115,7 +115,7 @@ func (a *ApplyCommandRunner) Run(ctx *command.Context, cmd *CommentCommand) { projectCmds, err = a.prjCmdBuilder.BuildApplyCommands(ctx, cmd) if err != nil { - if statusErr := a.commitStatusUpdater.UpdateCombined(ctx.Pull.BaseRepo, ctx.Pull, models.FailedCommitStatus, cmd.CommandName()); statusErr != nil { + if statusErr := a.commitStatusUpdater.UpdateCombined(ctx.Log, ctx.Pull.BaseRepo, ctx.Pull, models.FailedCommitStatus, cmd.CommandName()); statusErr != nil { ctx.Log.Warn("unable to update commit status: %s", statusErr) } a.pullUpdater.updatePull(ctx, cmd, command.Result{Error: err}) @@ -136,7 +136,7 @@ func (a *ApplyCommandRunner) Run(ctx *command.Context, cmd *CommentCommand) { if pullStatus == nil { // default to 0/0 ctx.Log.Debug("setting VCS status to 0/0 success as no previous state was found") - if err := a.commitStatusUpdater.UpdateCombinedCount(baseRepo, pull, models.SuccessCommitStatus, command.Apply, 0, 0); err != nil { + if err := a.commitStatusUpdater.UpdateCombinedCount(ctx.Log, baseRepo, pull, models.SuccessCommitStatus, command.Apply, 0, 0); err != nil { ctx.Log.Warn("unable to update commit status: %s", err) } return @@ -149,7 +149,7 @@ func (a *ApplyCommandRunner) Run(ctx *command.Context, cmd *CommentCommand) { // the Atlantis status to be passing for all pull requests. // Does not apply to skipped runs for specific projects ctx.Log.Debug("setting VCS status to success with no projects found") - if err := a.commitStatusUpdater.UpdateCombinedCount(baseRepo, pull, models.SuccessCommitStatus, command.Apply, 0, 0); err != nil { + if err := a.commitStatusUpdater.UpdateCombinedCount(ctx.Log, baseRepo, pull, models.SuccessCommitStatus, command.Apply, 0, 0); err != nil { ctx.Log.Warn("unable to update commit status: %s", err) } } @@ -211,6 +211,7 @@ func (a *ApplyCommandRunner) updateCommitStatus(ctx *command.Context, pullStatus } if err := a.commitStatusUpdater.UpdateCombinedCount( + ctx.Log, ctx.Pull.BaseRepo, ctx.Pull, status, diff --git a/server/events/apply_command_runner_test.go b/server/events/apply_command_runner_test.go index 9ce45cc261..fb3b0c5dfe 100644 --- a/server/events/apply_command_runner_test.go +++ b/server/events/apply_command_runner_test.go @@ -57,8 +57,8 @@ func TestApplyCommandRunner_IsLocked(t *testing.T) { State: github.String("open"), } modelPull := models.PullRequest{BaseRepo: testdata.GithubRepo, State: models.OpenPullState, Num: testdata.Pull.Num} - When(githubGetter.GetPullRequest(testdata.GithubRepo, testdata.Pull.Num)).ThenReturn(pull, nil) - When(eventParsing.ParseGithubPull(pull)).ThenReturn(modelPull, modelPull.BaseRepo, testdata.GithubRepo, nil) + When(githubGetter.GetPullRequest(logger, testdata.GithubRepo, testdata.Pull.Num)).ThenReturn(pull, nil) + When(eventParsing.ParseGithubPull(logger, pull)).ThenReturn(modelPull, modelPull.BaseRepo, testdata.GithubRepo, nil) ctx := &command.Context{ User: testdata.User, @@ -72,7 +72,8 @@ func TestApplyCommandRunner_IsLocked(t *testing.T) { When(applyLockChecker.CheckApplyLock()).ThenReturn(locking.ApplyCommandLock{Locked: c.ApplyLocked}, c.ApplyLockError) applyCommandRunner.Run(ctx, &events.CommentCommand{Name: command.Apply}) - vcsClient.VerifyWasCalledOnce().CreateComment(testdata.GithubRepo, modelPull.Num, c.ExpComment, "apply") + vcsClient.VerifyWasCalledOnce().CreateComment( + Any[logging.SimpleLogging](), Eq(testdata.GithubRepo), Eq(modelPull.Num), Eq(c.ExpComment), Eq("apply")) }) } } @@ -191,9 +192,11 @@ func TestApplyCommandRunner_IsSilenced(t *testing.T) { timesComment = 0 } - vcsClient.VerifyWasCalled(Times(timesComment)).CreateComment(Any[models.Repo](), Any[int](), Any[string](), Any[string]()) + vcsClient.VerifyWasCalled(Times(timesComment)).CreateComment( + Any[logging.SimpleLogging](), Any[models.Repo](), Any[int](), Any[string](), Any[string]()) if c.ExpVCSStatusSet { commitUpdater.VerifyWasCalledOnce().UpdateCombinedCount( + Any[logging.SimpleLogging](), Any[models.Repo](), Any[models.PullRequest](), Eq[models.CommitStatus](models.SuccessCommitStatus), @@ -203,6 +206,7 @@ func TestApplyCommandRunner_IsSilenced(t *testing.T) { ) } else { commitUpdater.VerifyWasCalled(Never()).UpdateCombinedCount( + Any[logging.SimpleLogging](), Any[models.Repo](), Any[models.PullRequest](), Any[models.CommitStatus](), @@ -486,8 +490,8 @@ func TestApplyCommandRunner_ExecutionOrder(t *testing.T) { Trigger: command.CommentTrigger, } - When(githubGetter.GetPullRequest(testdata.GithubRepo, testdata.Pull.Num)).ThenReturn(pull, nil) - When(eventParsing.ParseGithubPull(pull)).ThenReturn(modelPull, modelPull.BaseRepo, testdata.GithubRepo, nil) + When(githubGetter.GetPullRequest(logger, testdata.GithubRepo, testdata.Pull.Num)).ThenReturn(pull, nil) + When(eventParsing.ParseGithubPull(logger, pull)).ThenReturn(modelPull, modelPull.BaseRepo, testdata.GithubRepo, nil) When(projectCommandBuilder.BuildApplyCommands(ctx, cmd)).ThenReturn(c.ProjectContexts, nil) for i := range c.ProjectContexts { @@ -502,7 +506,7 @@ func TestApplyCommandRunner_ExecutionOrder(t *testing.T) { } vcsClient.VerifyWasCalledOnce().CreateComment( - testdata.GithubRepo, modelPull.Num, c.ExpComment, "apply", + Any[logging.SimpleLogging](), Eq(testdata.GithubRepo), Eq(modelPull.Num), Eq(c.ExpComment), Eq("apply"), ) }) } diff --git a/server/events/approve_policies_command_runner.go b/server/events/approve_policies_command_runner.go index 6deefd242f..c1a4fef9cc 100644 --- a/server/events/approve_policies_command_runner.go +++ b/server/events/approve_policies_command_runner.go @@ -45,13 +45,13 @@ func (a *ApprovePoliciesCommandRunner) Run(ctx *command.Context, cmd *CommentCom baseRepo := ctx.Pull.BaseRepo pull := ctx.Pull - if err := a.commitStatusUpdater.UpdateCombined(baseRepo, pull, models.PendingCommitStatus, command.PolicyCheck); err != nil { + if err := a.commitStatusUpdater.UpdateCombined(ctx.Log, baseRepo, pull, models.PendingCommitStatus, command.PolicyCheck); err != nil { ctx.Log.Warn("unable to update commit status: %s", err) } projectCmds, err := a.prjCmdBuilder.BuildApprovePoliciesCommands(ctx, cmd) if err != nil { - if statusErr := a.commitStatusUpdater.UpdateCombined(ctx.Pull.BaseRepo, ctx.Pull, models.FailedCommitStatus, command.PolicyCheck); statusErr != nil { + if statusErr := a.commitStatusUpdater.UpdateCombined(ctx.Log, ctx.Pull.BaseRepo, ctx.Pull, models.FailedCommitStatus, command.PolicyCheck); statusErr != nil { ctx.Log.Warn("unable to update commit status: %s", statusErr) } a.pullUpdater.updatePull(ctx, cmd, command.Result{Error: err}) @@ -65,7 +65,7 @@ func (a *ApprovePoliciesCommandRunner) Run(ctx *command.Context, cmd *CommentCom // with 0/0 projects approve_policies successfully because some users require // the Atlantis status to be passing for all pull requests. ctx.Log.Debug("setting VCS status to success with no projects found") - if err := a.commitStatusUpdater.UpdateCombinedCount(ctx.Pull.BaseRepo, ctx.Pull, models.SuccessCommitStatus, command.PolicyCheck, 0, 0); err != nil { + if err := a.commitStatusUpdater.UpdateCombinedCount(ctx.Log, ctx.Pull.BaseRepo, ctx.Pull, models.SuccessCommitStatus, command.PolicyCheck, 0, 0); err != nil { ctx.Log.Warn("unable to update commit status: %s", err) } } @@ -101,7 +101,7 @@ func (a *ApprovePoliciesCommandRunner) updateCommitStatus(ctx *command.Context, status = models.FailedCommitStatus } - if err := a.commitStatusUpdater.UpdateCombinedCount(ctx.Pull.BaseRepo, ctx.Pull, status, command.PolicyCheck, numSuccess, len(pullStatus.Projects)); err != nil { + if err := a.commitStatusUpdater.UpdateCombinedCount(ctx.Log, ctx.Pull.BaseRepo, ctx.Pull, status, command.PolicyCheck, numSuccess, len(pullStatus.Projects)); err != nil { ctx.Log.Warn("unable to update commit status: %s", err) } } diff --git a/server/events/automerger.go b/server/events/automerger.go index b3c05e75e8..fa74beac0f 100644 --- a/server/events/automerger.go +++ b/server/events/automerger.go @@ -23,7 +23,7 @@ func (c *AutoMerger) automerge(ctx *command.Context, pullStatus models.PullStatu } // Comment that we're automerging the pull request. - if err := c.VCSClient.CreateComment(ctx.Pull.BaseRepo, ctx.Pull.Num, automergeComment, command.Apply.String()); err != nil { + if err := c.VCSClient.CreateComment(ctx.Log, ctx.Pull.BaseRepo, ctx.Pull.Num, automergeComment, command.Apply.String()); err != nil { ctx.Log.Err("failed to comment about automerge: %s", err) // Commenting isn't required so continue. } @@ -32,13 +32,13 @@ func (c *AutoMerger) automerge(ctx *command.Context, pullStatus models.PullStatu ctx.Log.Info("automerging pull request") var pullOptions models.PullRequestOptions pullOptions.DeleteSourceBranchOnMerge = deleteSourceBranchOnMerge - err := c.VCSClient.MergePull(ctx.Pull, pullOptions) + err := c.VCSClient.MergePull(ctx.Log, ctx.Pull, pullOptions) if err != nil { ctx.Log.Err("automerging failed: %s", err) failureComment := fmt.Sprintf("Automerging failed:\n```\n%s\n```", err) - if commentErr := c.VCSClient.CreateComment(ctx.Pull.BaseRepo, ctx.Pull.Num, failureComment, command.Apply.String()); commentErr != nil { + if commentErr := c.VCSClient.CreateComment(ctx.Log, ctx.Pull.BaseRepo, ctx.Pull.Num, failureComment, command.Apply.String()); commentErr != nil { ctx.Log.Err("failed to comment about automerge failing: %s", err) } } diff --git a/server/events/command_runner.go b/server/events/command_runner.go index 4bf9c0e653..409e4a64d8 100644 --- a/server/events/command_runner.go +++ b/server/events/command_runner.go @@ -36,7 +36,7 @@ const ( ShutdownComment = "Atlantis server is shutting down, please try again later." ) -//go:generate pegomock generate --package mocks -o mocks/mock_command_runner.go CommandRunner +//go:generate pegomock generate github.com/runatlantis/atlantis/server/events --package mocks -o mocks/mock_command_runner.go CommandRunner // CommandRunner is the first step after a command request has been parsed. type CommandRunner interface { @@ -47,28 +47,28 @@ type CommandRunner interface { RunAutoplanCommand(baseRepo models.Repo, headRepo models.Repo, pull models.PullRequest, user models.User) } -//go:generate pegomock generate --package mocks -o mocks/mock_github_pull_getter.go GithubPullGetter +//go:generate pegomock generate github.com/runatlantis/atlantis/server/events --package mocks -o mocks/mock_github_pull_getter.go GithubPullGetter // GithubPullGetter makes API calls to get pull requests. type GithubPullGetter interface { // GetPullRequest gets the pull request with id pullNum for the repo. - GetPullRequest(repo models.Repo, pullNum int) (*github.PullRequest, error) + GetPullRequest(logger logging.SimpleLogging, repo models.Repo, pullNum int) (*github.PullRequest, error) } -//go:generate pegomock generate --package mocks -o mocks/mock_azuredevops_pull_getter.go AzureDevopsPullGetter +//go:generate pegomock generate github.com/runatlantis/atlantis/server/events --package mocks -o mocks/mock_azuredevops_pull_getter.go AzureDevopsPullGetter // AzureDevopsPullGetter makes API calls to get pull requests. type AzureDevopsPullGetter interface { // GetPullRequest gets the pull request with id pullNum for the repo. - GetPullRequest(repo models.Repo, pullNum int) (*azuredevops.GitPullRequest, error) + GetPullRequest(logger logging.SimpleLogging, repo models.Repo, pullNum int) (*azuredevops.GitPullRequest, error) } -//go:generate pegomock generate --package mocks -o mocks/mock_gitlab_merge_request_getter.go GitlabMergeRequestGetter +//go:generate pegomock generate github.com/runatlantis/atlantis/server/events --package mocks -o mocks/mock_gitlab_merge_request_getter.go GitlabMergeRequestGetter // GitlabMergeRequestGetter makes API calls to get merge requests. type GitlabMergeRequestGetter interface { // GetMergeRequest gets the pull request with the id pullNum for the repo. - GetMergeRequest(repoFullName string, pullNum int) (*gitlab.MergeRequest, error) + GetMergeRequest(logger logging.SimpleLogging, repoFullName string, pullNum int) (*gitlab.MergeRequest, error) } // CommentCommandRunner runs individual command workflows. @@ -134,7 +134,7 @@ type DefaultCommandRunner struct { // RunAutoplanCommand runs plan and policy_checks when a pull request is opened or updated. func (c *DefaultCommandRunner) RunAutoplanCommand(baseRepo models.Repo, headRepo models.Repo, pull models.PullRequest, user models.User) { if opStarted := c.Drainer.StartOp(); !opStarted { - if commentErr := c.VCSClient.CreateComment(baseRepo, pull.Num, ShutdownComment, command.Plan.String()); commentErr != nil { + if commentErr := c.VCSClient.CreateComment(c.Logger, baseRepo, pull.Num, ShutdownComment, command.Plan.String()); commentErr != nil { c.Logger.Log(logging.Error, "unable to comment that Atlantis is shutting down: %s", commentErr) } return @@ -179,7 +179,7 @@ func (c *DefaultCommandRunner) RunAutoplanCommand(baseRepo models.Repo, headRepo return } if len(c.DisableAutoplanLabel) > 0 { - labels, err := c.VCSClient.GetPullLabels(baseRepo, pull) + labels, err := c.VCSClient.GetPullLabels(ctx.Log, baseRepo, pull) if err != nil { ctx.Log.Err("Unable to get pull labels. Proceeding with %s command.", err, command.Plan) } else if utils.SlicesContains(labels, c.DisableAutoplanLabel) { @@ -201,11 +201,11 @@ func (c *DefaultCommandRunner) RunAutoplanCommand(baseRepo models.Repo, headRepo // Update the plan or apply commit status to pending whilst the pre workflow hook is running so that the PR can't be merged. switch cmd.Name { case command.Plan: - if err := c.CommitStatusUpdater.UpdateCombined(ctx.Pull.BaseRepo, ctx.Pull, models.FailedCommitStatus, command.Plan); err != nil { + if err := c.CommitStatusUpdater.UpdateCombined(ctx.Log, ctx.Pull.BaseRepo, ctx.Pull, models.FailedCommitStatus, command.Plan); err != nil { ctx.Log.Warn("unable to update plan commit status: %s", err) } case command.Apply: - if err := c.CommitStatusUpdater.UpdateCombined(ctx.Pull.BaseRepo, ctx.Pull, models.FailedCommitStatus, command.Apply); err != nil { + if err := c.CommitStatusUpdater.UpdateCombined(ctx.Log, ctx.Pull.BaseRepo, ctx.Pull, models.FailedCommitStatus, command.Apply); err != nil { ctx.Log.Warn("unable to update apply commit status: %s", err) } } @@ -231,7 +231,7 @@ func (c *DefaultCommandRunner) RunAutoplanCommand(baseRepo models.Repo, headRepo // is not allowed to execute the command. func (c *DefaultCommandRunner) commentUserDoesNotHavePermissions(baseRepo models.Repo, pullNum int, user models.User, cmd *CommentCommand) { errMsg := fmt.Sprintf("```\nError: User @%s does not have permissions to execute '%s' command.\n```", user.Username, cmd.Name.String()) - if err := c.VCSClient.CreateComment(baseRepo, pullNum, errMsg, ""); err != nil { + if err := c.VCSClient.CreateComment(c.Logger, baseRepo, pullNum, errMsg, ""); err != nil { c.Logger.Err("unable to comment on pull request: %s", err) } } @@ -269,7 +269,7 @@ func (c *DefaultCommandRunner) checkVarFilesInPlanCommandAllowlisted(cmd *Commen // wasteful) call to get the necessary data. func (c *DefaultCommandRunner) RunCommentCommand(baseRepo models.Repo, maybeHeadRepo *models.Repo, maybePull *models.PullRequest, user models.User, pullNum int, cmd *CommentCommand) { if opStarted := c.Drainer.StartOp(); !opStarted { - if commentErr := c.VCSClient.CreateComment(baseRepo, pullNum, ShutdownComment, ""); commentErr != nil { + if commentErr := c.VCSClient.CreateComment(c.Logger, baseRepo, pullNum, ShutdownComment, ""); commentErr != nil { c.Logger.Log(logging.Error, "unable to comment that Atlantis is shutting down: %s", commentErr) } return @@ -301,7 +301,7 @@ func (c *DefaultCommandRunner) RunCommentCommand(baseRepo models.Repo, maybeHead // Check if the provided var files in a 'plan' command are allowlisted if err := c.checkVarFilesInPlanCommandAllowlisted(cmd); err != nil { errMsg := fmt.Sprintf("```\n%s\n```", err.Error()) - if commentErr := c.VCSClient.CreateComment(baseRepo, pullNum, errMsg, ""); commentErr != nil { + if commentErr := c.VCSClient.CreateComment(c.Logger, baseRepo, pullNum, errMsg, ""); commentErr != nil { c.Logger.Err("unable to comment on pull request: %s", commentErr) } return @@ -345,11 +345,11 @@ func (c *DefaultCommandRunner) RunCommentCommand(baseRepo models.Repo, maybeHead // Update the plan or apply commit status to pending whilst the pre workflow hook is running so that the PR can't be merged. switch cmd.Name { case command.Plan: - if err := c.CommitStatusUpdater.UpdateCombined(ctx.Pull.BaseRepo, ctx.Pull, models.FailedCommitStatus, command.Plan); err != nil { + if err := c.CommitStatusUpdater.UpdateCombined(ctx.Log, ctx.Pull.BaseRepo, ctx.Pull, models.FailedCommitStatus, command.Plan); err != nil { ctx.Log.Warn("unable to update plan commit status: %s", err) } case command.Apply: - if err := c.CommitStatusUpdater.UpdateCombined(ctx.Pull.BaseRepo, ctx.Pull, models.FailedCommitStatus, command.Apply); err != nil { + if err := c.CommitStatusUpdater.UpdateCombined(ctx.Log, ctx.Pull.BaseRepo, ctx.Pull, models.FailedCommitStatus, command.Apply); err != nil { ctx.Log.Warn("unable to update apply commit status: %s", err) } } @@ -371,26 +371,26 @@ func (c *DefaultCommandRunner) RunCommentCommand(baseRepo models.Repo, maybeHead } } -func (c *DefaultCommandRunner) getGithubData(baseRepo models.Repo, pullNum int) (models.PullRequest, models.Repo, error) { +func (c *DefaultCommandRunner) getGithubData(logger logging.SimpleLogging, baseRepo models.Repo, pullNum int) (models.PullRequest, models.Repo, error) { if c.GithubPullGetter == nil { return models.PullRequest{}, models.Repo{}, errors.New("Atlantis not configured to support GitHub") } - ghPull, err := c.GithubPullGetter.GetPullRequest(baseRepo, pullNum) + ghPull, err := c.GithubPullGetter.GetPullRequest(logger, baseRepo, pullNum) if err != nil { return models.PullRequest{}, models.Repo{}, errors.Wrap(err, "making pull request API call to GitHub") } - pull, _, headRepo, err := c.EventParser.ParseGithubPull(ghPull) + pull, _, headRepo, err := c.EventParser.ParseGithubPull(logger, ghPull) if err != nil { return pull, headRepo, errors.Wrap(err, "extracting required fields from comment data") } return pull, headRepo, nil } -func (c *DefaultCommandRunner) getGitlabData(baseRepo models.Repo, pullNum int) (models.PullRequest, error) { +func (c *DefaultCommandRunner) getGitlabData(logger logging.SimpleLogging, baseRepo models.Repo, pullNum int) (models.PullRequest, error) { if c.GitlabMergeRequestGetter == nil { return models.PullRequest{}, errors.New("Atlantis not configured to support GitLab") } - mr, err := c.GitlabMergeRequestGetter.GetMergeRequest(baseRepo.FullName, pullNum) + mr, err := c.GitlabMergeRequestGetter.GetMergeRequest(logger, baseRepo.FullName, pullNum) if err != nil { return models.PullRequest{}, errors.Wrap(err, "making merge request API call to GitLab") } @@ -398,11 +398,11 @@ func (c *DefaultCommandRunner) getGitlabData(baseRepo models.Repo, pullNum int) return pull, nil } -func (c *DefaultCommandRunner) getAzureDevopsData(baseRepo models.Repo, pullNum int) (models.PullRequest, models.Repo, error) { +func (c *DefaultCommandRunner) getAzureDevopsData(logger logging.SimpleLogging, baseRepo models.Repo, pullNum int) (models.PullRequest, models.Repo, error) { if c.AzureDevopsPullGetter == nil { return models.PullRequest{}, models.Repo{}, errors.New("atlantis not configured to support Azure DevOps") } - adPull, err := c.AzureDevopsPullGetter.GetPullRequest(baseRepo, pullNum) + adPull, err := c.AzureDevopsPullGetter.GetPullRequest(logger, baseRepo, pullNum) if err != nil { return models.PullRequest{}, models.Repo{}, errors.Wrap(err, "making pull request API call to Azure DevOps") } @@ -435,9 +435,9 @@ func (c *DefaultCommandRunner) ensureValidRepoMetadata( switch baseRepo.VCSHost.Type { case models.Github: - pull, headRepo, err = c.getGithubData(baseRepo, pullNum) + pull, headRepo, err = c.getGithubData(log, baseRepo, pullNum) case models.Gitlab: - pull, err = c.getGitlabData(baseRepo, pullNum) + pull, err = c.getGitlabData(log, baseRepo, pullNum) case models.BitbucketCloud, models.BitbucketServer: if maybePull == nil { err = errors.New("pull request should not be nil–this is a bug") @@ -445,14 +445,14 @@ func (c *DefaultCommandRunner) ensureValidRepoMetadata( } pull = *maybePull case models.AzureDevops: - pull, headRepo, err = c.getAzureDevopsData(baseRepo, pullNum) + pull, headRepo, err = c.getAzureDevopsData(log, baseRepo, pullNum) default: err = errors.New("Unknown VCS type–this is a bug") } if err != nil { log.Err(err.Error()) - if commentErr := c.VCSClient.CreateComment(baseRepo, pullNum, fmt.Sprintf("`Error: %s`", err), ""); commentErr != nil { + if commentErr := c.VCSClient.CreateComment(c.Logger, baseRepo, pullNum, fmt.Sprintf("`Error: %s`", err), ""); commentErr != nil { log.Err("unable to comment: %s", commentErr) } } @@ -466,7 +466,7 @@ func (c *DefaultCommandRunner) validateCtxAndComment(ctx *command.Context, comma return false } ctx.Log.Info("command was run on a fork pull request which is disallowed") - if err := c.VCSClient.CreateComment(ctx.Pull.BaseRepo, ctx.Pull.Num, fmt.Sprintf("Atlantis commands can't be run on fork pull requests. To enable, set --%s or, to disable this message, set --%s", c.AllowForkPRsFlag, c.SilenceForkPRErrorsFlag), ""); err != nil { + if err := c.VCSClient.CreateComment(ctx.Log, ctx.Pull.BaseRepo, ctx.Pull.Num, fmt.Sprintf("Atlantis commands can't be run on fork pull requests. To enable, set --%s or, to disable this message, set --%s", c.AllowForkPRsFlag, c.SilenceForkPRErrorsFlag), ""); err != nil { ctx.Log.Err("unable to comment: %s", err) } return false @@ -474,7 +474,7 @@ func (c *DefaultCommandRunner) validateCtxAndComment(ctx *command.Context, comma if ctx.Pull.State != models.OpenPullState && commandName != command.Unlock { ctx.Log.Info("command was run on closed pull request") - if err := c.VCSClient.CreateComment(ctx.Pull.BaseRepo, ctx.Pull.Num, "Atlantis commands can't be run on closed pull requests", ""); err != nil { + if err := c.VCSClient.CreateComment(ctx.Log, ctx.Pull.BaseRepo, ctx.Pull.Num, "Atlantis commands can't be run on closed pull requests", ""); err != nil { ctx.Log.Err("unable to comment: %s", err) } return false @@ -495,6 +495,7 @@ func (c *DefaultCommandRunner) logPanics(baseRepo models.Repo, pullNum int, logg stack := recovery.Stack(3) logger.Err("PANIC: %s\n%s", err, stack) if commentErr := c.VCSClient.CreateComment( + logger, baseRepo, pullNum, fmt.Sprintf("**Error: goroutine panic. This is a bug.**\n```\n%s\n%s```", err, stack), diff --git a/server/events/command_runner_internal_test.go b/server/events/command_runner_internal_test.go index 1241fecc55..02a54c3870 100644 --- a/server/events/command_runner_internal_test.go +++ b/server/events/command_runner_internal_test.go @@ -5,6 +5,7 @@ import ( "github.com/runatlantis/atlantis/server/events/command" "github.com/runatlantis/atlantis/server/events/models" + "github.com/runatlantis/atlantis/server/logging" . "github.com/runatlantis/atlantis/testing" ) @@ -273,7 +274,7 @@ type MockCSU struct { Called bool } -func (m *MockCSU) UpdateCombinedCount(repo models.Repo, pull models.PullRequest, status models.CommitStatus, command command.Name, numSuccess int, numTotal int) error { +func (m *MockCSU) UpdateCombinedCount(_ logging.SimpleLogging, repo models.Repo, pull models.PullRequest, status models.CommitStatus, command command.Name, numSuccess int, numTotal int) error { m.Called = true m.CalledRepo = repo m.CalledPull = pull @@ -284,7 +285,7 @@ func (m *MockCSU) UpdateCombinedCount(repo models.Repo, pull models.PullRequest, return nil } -func (m *MockCSU) UpdateCombined(_ models.Repo, _ models.PullRequest, _ models.CommitStatus, _ command.Name) error { +func (m *MockCSU) UpdateCombined(_ logging.SimpleLogging, _ models.Repo, _ models.PullRequest, _ models.CommitStatus, _ command.Name) error { return nil } @@ -292,10 +293,10 @@ func (m *MockCSU) UpdateProject(_ command.ProjectContext, _ command.Name, _ mode return nil } -func (m *MockCSU) UpdatePreWorkflowHook(_ models.PullRequest, _ models.CommitStatus, _ string, _ string, _ string) error { +func (m *MockCSU) UpdatePreWorkflowHook(_ logging.SimpleLogging, _ models.PullRequest, _ models.CommitStatus, _ string, _ string, _ string) error { return nil } -func (m *MockCSU) UpdatePostWorkflowHook(_ models.PullRequest, _ models.CommitStatus, _ string, _ string, _ string) error { +func (m *MockCSU) UpdatePostWorkflowHook(_ logging.SimpleLogging, _ models.PullRequest, _ models.CommitStatus, _ string, _ string, _ string) error { return nil } diff --git a/server/events/command_runner_test.go b/server/events/command_runner_test.go index d9c8451570..bbc265fb8a 100644 --- a/server/events/command_runner_test.go +++ b/server/events/command_runner_test.go @@ -261,37 +261,42 @@ func setup(t *testing.T, options ...func(testConfig *TestConfig)) *vcsmocks.Mock func TestRunCommentCommand_LogPanics(t *testing.T) { t.Log("if there is a panic it is commented back on the pull request") vcsClient := setup(t) - When(githubGetter.GetPullRequest(testdata.GithubRepo, testdata.Pull.Num)).ThenPanic("panic test - if you're seeing this in a test failure this isn't the failing test") + When(githubGetter.GetPullRequest(Any[logging.SimpleLogging](), Eq(testdata.GithubRepo), Eq(testdata.Pull.Num))).ThenPanic( + "panic test - if you're seeing this in a test failure this isn't the failing test") ch.RunCommentCommand(testdata.GithubRepo, &testdata.GithubRepo, nil, testdata.User, 1, &events.CommentCommand{Name: command.Plan}) - _, _, comment, _ := vcsClient.VerifyWasCalledOnce().CreateComment(Any[models.Repo](), Any[int](), Any[string](), Any[string]()).GetCapturedArguments() + _, _, _, comment, _ := vcsClient.VerifyWasCalledOnce().CreateComment( + Any[logging.SimpleLogging](), Any[models.Repo](), Any[int](), Any[string](), Any[string]()).GetCapturedArguments() Assert(t, strings.Contains(comment, "Error: goroutine panic"), fmt.Sprintf("comment should be about a goroutine panic but was %q", comment)) } func TestRunCommentCommand_GithubPullErr(t *testing.T) { t.Log("if getting the github pull request fails an error should be logged") vcsClient := setup(t) - When(githubGetter.GetPullRequest(testdata.GithubRepo, testdata.Pull.Num)).ThenReturn(nil, errors.New("err")) + When(githubGetter.GetPullRequest(Any[logging.SimpleLogging](), Eq(testdata.GithubRepo), Eq(testdata.Pull.Num))).ThenReturn(nil, errors.New("err")) ch.RunCommentCommand(testdata.GithubRepo, &testdata.GithubRepo, nil, testdata.User, testdata.Pull.Num, &events.CommentCommand{Name: command.Plan}) - vcsClient.VerifyWasCalledOnce().CreateComment(testdata.GithubRepo, testdata.Pull.Num, "`Error: making pull request API call to GitHub: err`", "") + vcsClient.VerifyWasCalledOnce().CreateComment( + Any[logging.SimpleLogging](), Eq(testdata.GithubRepo), Eq(testdata.Pull.Num), Eq("`Error: making pull request API call to GitHub: err`"), Eq("")) } func TestRunCommentCommand_GitlabMergeRequestErr(t *testing.T) { t.Log("if getting the gitlab merge request fails an error should be logged") vcsClient := setup(t) - When(gitlabGetter.GetMergeRequest(testdata.GitlabRepo.FullName, testdata.Pull.Num)).ThenReturn(nil, errors.New("err")) + When(gitlabGetter.GetMergeRequest(Any[logging.SimpleLogging](), Eq(testdata.GitlabRepo.FullName), Eq(testdata.Pull.Num))).ThenReturn(nil, errors.New("err")) ch.RunCommentCommand(testdata.GitlabRepo, &testdata.GitlabRepo, nil, testdata.User, testdata.Pull.Num, &events.CommentCommand{Name: command.Plan}) - vcsClient.VerifyWasCalledOnce().CreateComment(testdata.GitlabRepo, testdata.Pull.Num, "`Error: making merge request API call to GitLab: err`", "") + vcsClient.VerifyWasCalledOnce().CreateComment( + Any[logging.SimpleLogging](), Eq(testdata.GitlabRepo), Eq(testdata.Pull.Num), Eq("`Error: making merge request API call to GitLab: err`"), Eq("")) } func TestRunCommentCommand_GithubPullParseErr(t *testing.T) { t.Log("if parsing the returned github pull request fails an error should be logged") vcsClient := setup(t) var pull github.PullRequest - When(githubGetter.GetPullRequest(testdata.GithubRepo, testdata.Pull.Num)).ThenReturn(&pull, nil) - When(eventParsing.ParseGithubPull(&pull)).ThenReturn(testdata.Pull, testdata.GithubRepo, testdata.GitlabRepo, errors.New("err")) + When(githubGetter.GetPullRequest(Any[logging.SimpleLogging](), Eq(testdata.GithubRepo), Eq(testdata.Pull.Num))).ThenReturn(&pull, nil) + When(eventParsing.ParseGithubPull(Any[logging.SimpleLogging](), Eq(&pull))).ThenReturn(testdata.Pull, testdata.GithubRepo, testdata.GitlabRepo, errors.New("err")) ch.RunCommentCommand(testdata.GithubRepo, &testdata.GithubRepo, nil, testdata.User, testdata.Pull.Num, &events.CommentCommand{Name: command.Plan}) - vcsClient.VerifyWasCalledOnce().CreateComment(testdata.GithubRepo, testdata.Pull.Num, "`Error: extracting required fields from comment data: err`", "") + vcsClient.VerifyWasCalledOnce().CreateComment( + Any[logging.SimpleLogging](), Eq(testdata.GithubRepo), Eq(testdata.Pull.Num), Eq("`Error: extracting required fields from comment data: err`"), Eq("")) } func TestRunCommentCommand_TeamAllowListChecker(t *testing.T) { @@ -304,12 +309,13 @@ func TestRunCommentCommand_TeamAllowListChecker(t *testing.T) { BaseRepo: testdata.GithubRepo, State: models.OpenPullState, } - When(githubGetter.GetPullRequest(testdata.GithubRepo, testdata.Pull.Num)).ThenReturn(&pull, nil) - When(eventParsing.ParseGithubPull(&pull)).ThenReturn(modelPull, modelPull.BaseRepo, testdata.GithubRepo, nil) + When(githubGetter.GetPullRequest(Any[logging.SimpleLogging](), Eq(testdata.GithubRepo), Eq(testdata.Pull.Num))).ThenReturn(&pull, nil) + When(eventParsing.ParseGithubPull(Any[logging.SimpleLogging](), Eq(&pull))).ThenReturn(modelPull, modelPull.BaseRepo, testdata.GithubRepo, nil) ch.RunCommentCommand(testdata.GithubRepo, nil, nil, testdata.User, testdata.Pull.Num, &events.CommentCommand{Name: command.Plan}) vcsClient.VerifyWasCalled(Never()).GetTeamNamesForUser(testdata.GithubRepo, testdata.User) - vcsClient.VerifyWasCalledOnce().CreateComment(testdata.GithubRepo, modelPull.Num, "Ran Plan for 0 projects:", "plan") + vcsClient.VerifyWasCalledOnce().CreateComment( + Any[logging.SimpleLogging](), Eq(testdata.GithubRepo), Eq(modelPull.Num), Eq("Ran Plan for 0 projects:"), Eq("plan")) }) t.Run("no rules", func(t *testing.T) { @@ -321,12 +327,13 @@ func TestRunCommentCommand_TeamAllowListChecker(t *testing.T) { BaseRepo: testdata.GithubRepo, State: models.OpenPullState, } - When(githubGetter.GetPullRequest(testdata.GithubRepo, testdata.Pull.Num)).ThenReturn(&pull, nil) - When(eventParsing.ParseGithubPull(&pull)).ThenReturn(modelPull, modelPull.BaseRepo, testdata.GithubRepo, nil) + When(githubGetter.GetPullRequest(Any[logging.SimpleLogging](), Eq(testdata.GithubRepo), Eq(testdata.Pull.Num))).ThenReturn(&pull, nil) + When(eventParsing.ParseGithubPull(Any[logging.SimpleLogging](), Eq(&pull))).ThenReturn(modelPull, modelPull.BaseRepo, testdata.GithubRepo, nil) ch.RunCommentCommand(testdata.GithubRepo, nil, nil, testdata.User, testdata.Pull.Num, &events.CommentCommand{Name: command.Plan}) vcsClient.VerifyWasCalled(Never()).GetTeamNamesForUser(testdata.GithubRepo, testdata.User) - vcsClient.VerifyWasCalledOnce().CreateComment(testdata.GithubRepo, modelPull.Num, "Ran Plan for 0 projects:", "plan") + vcsClient.VerifyWasCalledOnce().CreateComment( + Any[logging.SimpleLogging](), Eq(testdata.GithubRepo), Eq(modelPull.Num), Eq("Ran Plan for 0 projects:"), Eq("plan")) }) } @@ -342,16 +349,17 @@ func TestRunCommentCommand_ForkPRDisabled(t *testing.T) { BaseRepo: testdata.GithubRepo, State: models.OpenPullState, } - When(githubGetter.GetPullRequest(testdata.GithubRepo, testdata.Pull.Num)).ThenReturn(&pull, nil) + When(githubGetter.GetPullRequest(Any[logging.SimpleLogging](), Eq(testdata.GithubRepo), Eq(testdata.Pull.Num))).ThenReturn(&pull, nil) headRepo := testdata.GithubRepo headRepo.FullName = "forkrepo/atlantis" headRepo.Owner = "forkrepo" - When(eventParsing.ParseGithubPull(&pull)).ThenReturn(modelPull, modelPull.BaseRepo, headRepo, nil) + When(eventParsing.ParseGithubPull(Any[logging.SimpleLogging](), Eq(&pull))).ThenReturn(modelPull, modelPull.BaseRepo, headRepo, nil) ch.RunCommentCommand(testdata.GithubRepo, nil, nil, testdata.User, testdata.Pull.Num, &events.CommentCommand{Name: command.Plan}) commentMessage := fmt.Sprintf("Atlantis commands can't be run on fork pull requests. To enable, set --%s or, to disable this message, set --%s", ch.AllowForkPRsFlag, ch.SilenceForkPRErrorsFlag) - vcsClient.VerifyWasCalledOnce().CreateComment(testdata.GithubRepo, modelPull.Num, commentMessage, "") + vcsClient.VerifyWasCalledOnce().CreateComment( + Any[logging.SimpleLogging](), Eq(testdata.GithubRepo), Eq(modelPull.Num), Eq(commentMessage), Eq("")) } func TestRunCommentCommand_ForkPRDisabled_SilenceEnabled(t *testing.T) { @@ -361,15 +369,16 @@ func TestRunCommentCommand_ForkPRDisabled_SilenceEnabled(t *testing.T) { ch.SilenceForkPRErrors = true var pull github.PullRequest modelPull := models.PullRequest{BaseRepo: testdata.GithubRepo, State: models.OpenPullState} - When(githubGetter.GetPullRequest(testdata.GithubRepo, testdata.Pull.Num)).ThenReturn(&pull, nil) + When(githubGetter.GetPullRequest(Any[logging.SimpleLogging](), Eq(testdata.GithubRepo), Eq(testdata.Pull.Num))).ThenReturn(&pull, nil) headRepo := testdata.GithubRepo headRepo.FullName = "forkrepo/atlantis" headRepo.Owner = "forkrepo" - When(eventParsing.ParseGithubPull(&pull)).ThenReturn(modelPull, modelPull.BaseRepo, headRepo, nil) + When(eventParsing.ParseGithubPull(Any[logging.SimpleLogging](), Eq(&pull))).ThenReturn(modelPull, modelPull.BaseRepo, headRepo, nil) ch.RunCommentCommand(testdata.GithubRepo, nil, nil, testdata.User, testdata.Pull.Num, &events.CommentCommand{Name: command.Plan}) - vcsClient.VerifyWasCalled(Never()).CreateComment(Any[models.Repo](), Any[int](), Any[string](), Any[string]()) + vcsClient.VerifyWasCalled(Never()).CreateComment( + Any[logging.SimpleLogging](), Any[models.Repo](), Any[int](), Any[string](), Any[string]()) } func TestRunCommentCommandPlan_NoProjects_SilenceEnabled(t *testing.T) { @@ -378,12 +387,14 @@ func TestRunCommentCommandPlan_NoProjects_SilenceEnabled(t *testing.T) { planCommandRunner.SilenceNoProjects = true var pull github.PullRequest modelPull := models.PullRequest{BaseRepo: testdata.GithubRepo, State: models.OpenPullState} - When(githubGetter.GetPullRequest(testdata.GithubRepo, testdata.Pull.Num)).ThenReturn(&pull, nil) - When(eventParsing.ParseGithubPull(&pull)).ThenReturn(modelPull, modelPull.BaseRepo, testdata.GithubRepo, nil) + When(githubGetter.GetPullRequest(Any[logging.SimpleLogging](), Eq(testdata.GithubRepo), Eq(testdata.Pull.Num))).ThenReturn(&pull, nil) + When(eventParsing.ParseGithubPull(Any[logging.SimpleLogging](), Eq(&pull))).ThenReturn(modelPull, modelPull.BaseRepo, testdata.GithubRepo, nil) ch.RunCommentCommand(testdata.GithubRepo, nil, nil, testdata.User, testdata.Pull.Num, &events.CommentCommand{Name: command.Plan}) - vcsClient.VerifyWasCalled(Never()).CreateComment(Any[models.Repo](), Any[int](), Any[string](), Any[string]()) + vcsClient.VerifyWasCalled(Never()).CreateComment( + Any[logging.SimpleLogging](), Any[models.Repo](), Any[int](), Any[string](), Any[string]()) commitUpdater.VerifyWasCalledOnce().UpdateCombinedCount( + Any[logging.SimpleLogging](), Any[models.Repo](), Any[models.PullRequest](), Eq[models.CommitStatus](models.SuccessCommitStatus), @@ -400,12 +411,14 @@ func TestRunCommentCommandPlan_NoProjectsTarget_SilenceEnabled(t *testing.T) { planCommandRunner.SilenceNoProjects = true var pull github.PullRequest modelPull := models.PullRequest{BaseRepo: testdata.GithubRepo, State: models.OpenPullState} - When(githubGetter.GetPullRequest(testdata.GithubRepo, testdata.Pull.Num)).ThenReturn(&pull, nil) - When(eventParsing.ParseGithubPull(&pull)).ThenReturn(modelPull, modelPull.BaseRepo, testdata.GithubRepo, nil) + When(githubGetter.GetPullRequest(Any[logging.SimpleLogging](), Eq(testdata.GithubRepo), Eq(testdata.Pull.Num))).ThenReturn(&pull, nil) + When(eventParsing.ParseGithubPull(Any[logging.SimpleLogging](), Eq(&pull))).ThenReturn(modelPull, modelPull.BaseRepo, testdata.GithubRepo, nil) ch.RunCommentCommand(testdata.GithubRepo, nil, nil, testdata.User, testdata.Pull.Num, &events.CommentCommand{Name: command.Plan, ProjectName: "meow"}) - vcsClient.VerifyWasCalled(Never()).CreateComment(Any[models.Repo](), Any[int](), Any[string](), Any[string]()) + vcsClient.VerifyWasCalled(Never()).CreateComment( + Any[logging.SimpleLogging](), Any[models.Repo](), Any[int](), Any[string](), Any[string]()) commitUpdater.VerifyWasCalledOnce().UpdateCombinedCount( + Any[logging.SimpleLogging](), Any[models.Repo](), Any[models.PullRequest](), Eq[models.CommitStatus](models.SuccessCommitStatus), @@ -421,12 +434,14 @@ func TestRunCommentCommandApply_NoProjects_SilenceEnabled(t *testing.T) { applyCommandRunner.SilenceNoProjects = true var pull github.PullRequest modelPull := models.PullRequest{BaseRepo: testdata.GithubRepo, State: models.OpenPullState} - When(githubGetter.GetPullRequest(testdata.GithubRepo, testdata.Pull.Num)).ThenReturn(&pull, nil) - When(eventParsing.ParseGithubPull(&pull)).ThenReturn(modelPull, modelPull.BaseRepo, testdata.GithubRepo, nil) + When(githubGetter.GetPullRequest(Any[logging.SimpleLogging](), Eq(testdata.GithubRepo), Eq(testdata.Pull.Num))).ThenReturn(&pull, nil) + When(eventParsing.ParseGithubPull(Any[logging.SimpleLogging](), Eq(&pull))).ThenReturn(modelPull, modelPull.BaseRepo, testdata.GithubRepo, nil) ch.RunCommentCommand(testdata.GithubRepo, nil, nil, testdata.User, testdata.Pull.Num, &events.CommentCommand{Name: command.Apply}) - vcsClient.VerifyWasCalled(Never()).CreateComment(Any[models.Repo](), Any[int](), Any[string](), Any[string]()) + vcsClient.VerifyWasCalled(Never()).CreateComment( + Any[logging.SimpleLogging](), Any[models.Repo](), Any[int](), Any[string](), Any[string]()) commitUpdater.VerifyWasCalledOnce().UpdateCombinedCount( + Any[logging.SimpleLogging](), Any[models.Repo](), Any[models.PullRequest](), Eq[models.CommitStatus](models.SuccessCommitStatus), @@ -442,12 +457,14 @@ func TestRunCommentCommandApprovePolicy_NoProjects_SilenceEnabled(t *testing.T) approvePoliciesCommandRunner.SilenceNoProjects = true var pull github.PullRequest modelPull := models.PullRequest{BaseRepo: testdata.GithubRepo, State: models.OpenPullState} - When(githubGetter.GetPullRequest(testdata.GithubRepo, testdata.Pull.Num)).ThenReturn(&pull, nil) - When(eventParsing.ParseGithubPull(&pull)).ThenReturn(modelPull, modelPull.BaseRepo, testdata.GithubRepo, nil) + When(githubGetter.GetPullRequest(Any[logging.SimpleLogging](), Eq(testdata.GithubRepo), Eq(testdata.Pull.Num))).ThenReturn(&pull, nil) + When(eventParsing.ParseGithubPull(Any[logging.SimpleLogging](), Eq(&pull))).ThenReturn(modelPull, modelPull.BaseRepo, testdata.GithubRepo, nil) ch.RunCommentCommand(testdata.GithubRepo, nil, nil, testdata.User, testdata.Pull.Num, &events.CommentCommand{Name: command.ApprovePolicies}) - vcsClient.VerifyWasCalled(Never()).CreateComment(Any[models.Repo](), Any[int](), Any[string](), Any[string]()) + vcsClient.VerifyWasCalled(Never()).CreateComment( + Any[logging.SimpleLogging](), Any[models.Repo](), Any[int](), Any[string](), Any[string]()) commitUpdater.VerifyWasCalledOnce().UpdateCombinedCount( + Any[logging.SimpleLogging](), Any[models.Repo](), Any[models.PullRequest](), Eq[models.CommitStatus](models.SuccessCommitStatus), @@ -463,11 +480,11 @@ func TestRunCommentCommandUnlock_NoProjects_SilenceEnabled(t *testing.T) { unlockCommandRunner.SilenceNoProjects = true var pull github.PullRequest modelPull := models.PullRequest{BaseRepo: testdata.GithubRepo, State: models.OpenPullState} - When(githubGetter.GetPullRequest(testdata.GithubRepo, testdata.Pull.Num)).ThenReturn(&pull, nil) - When(eventParsing.ParseGithubPull(&pull)).ThenReturn(modelPull, modelPull.BaseRepo, testdata.GithubRepo, nil) + When(githubGetter.GetPullRequest(Any[logging.SimpleLogging](), Eq(testdata.GithubRepo), Eq(testdata.Pull.Num))).ThenReturn(&pull, nil) + When(eventParsing.ParseGithubPull(Any[logging.SimpleLogging](), Eq(&pull))).ThenReturn(modelPull, modelPull.BaseRepo, testdata.GithubRepo, nil) ch.RunCommentCommand(testdata.GithubRepo, nil, nil, testdata.User, testdata.Pull.Num, &events.CommentCommand{Name: command.Unlock}) - vcsClient.VerifyWasCalled(Never()).CreateComment(Any[models.Repo](), Any[int](), Any[string](), Any[string]()) + vcsClient.VerifyWasCalled(Never()).CreateComment(Any[logging.SimpleLogging](), Any[models.Repo](), Any[int](), Any[string](), Any[string]()) } func TestRunCommentCommandImport_NoProjects_SilenceEnabled(t *testing.T) { @@ -476,11 +493,11 @@ func TestRunCommentCommandImport_NoProjects_SilenceEnabled(t *testing.T) { importCommandRunner.SilenceNoProjects = true var pull github.PullRequest modelPull := models.PullRequest{BaseRepo: testdata.GithubRepo, State: models.OpenPullState} - When(githubGetter.GetPullRequest(testdata.GithubRepo, testdata.Pull.Num)).ThenReturn(&pull, nil) - When(eventParsing.ParseGithubPull(&pull)).ThenReturn(modelPull, modelPull.BaseRepo, testdata.GithubRepo, nil) + When(githubGetter.GetPullRequest(Any[logging.SimpleLogging](), Eq(testdata.GithubRepo), Eq(testdata.Pull.Num))).ThenReturn(&pull, nil) + When(eventParsing.ParseGithubPull(Any[logging.SimpleLogging](), Eq(&pull))).ThenReturn(modelPull, modelPull.BaseRepo, testdata.GithubRepo, nil) ch.RunCommentCommand(testdata.GithubRepo, nil, nil, testdata.User, testdata.Pull.Num, &events.CommentCommand{Name: command.Import}) - vcsClient.VerifyWasCalled(Never()).CreateComment(Any[models.Repo](), Any[int](), Any[string](), Any[string]()) + vcsClient.VerifyWasCalled(Never()).CreateComment(Any[logging.SimpleLogging](), Any[models.Repo](), Any[int](), Any[string](), Any[string]()) } func TestRunCommentCommand_DisableApplyAllDisabled(t *testing.T) { @@ -492,11 +509,13 @@ func TestRunCommentCommand_DisableApplyAllDisabled(t *testing.T) { State: github.String("open"), } modelPull := models.PullRequest{BaseRepo: testdata.GithubRepo, State: models.OpenPullState, Num: testdata.Pull.Num} - When(githubGetter.GetPullRequest(testdata.GithubRepo, testdata.Pull.Num)).ThenReturn(pull, nil) - When(eventParsing.ParseGithubPull(pull)).ThenReturn(modelPull, modelPull.BaseRepo, testdata.GithubRepo, nil) + When(githubGetter.GetPullRequest(Any[logging.SimpleLogging](), Eq(testdata.GithubRepo), Eq(testdata.Pull.Num))).ThenReturn(pull, nil) + When(eventParsing.ParseGithubPull(Any[logging.SimpleLogging](), Eq(pull))).ThenReturn(modelPull, modelPull.BaseRepo, testdata.GithubRepo, nil) ch.RunCommentCommand(testdata.GithubRepo, nil, nil, testdata.User, modelPull.Num, &events.CommentCommand{Name: command.Apply}) - vcsClient.VerifyWasCalledOnce().CreateComment(testdata.GithubRepo, modelPull.Num, "**Error:** Running `atlantis apply` without flags is disabled. You must specify which project to apply via the `-d `, `-w ` or `-p ` flags.", "apply") + vcsClient.VerifyWasCalledOnce().CreateComment( + Any[logging.SimpleLogging](), Eq(testdata.GithubRepo), Eq(modelPull.Num), + Eq("**Error:** Running `atlantis apply` without flags is disabled. You must specify which project to apply via the `-d `, `-w ` or `-p ` flags."), Eq("apply")) } func TestRunCommentCommand_DisableAutoplan(t *testing.T) { @@ -538,11 +557,12 @@ func TestRunCommentCommand_DisableAutoplanLabel(t *testing.T) { CommandName: command.Plan, }, }, nil) - When(ch.VCSClient.GetPullLabels(testdata.GithubRepo, modelPull)).ThenReturn([]string{"disable-auto-plan", "need-help"}, nil) + When(ch.VCSClient.GetPullLabels( + Any[logging.SimpleLogging](), Eq(testdata.GithubRepo), Eq(modelPull))).ThenReturn([]string{"disable-auto-plan", "need-help"}, nil) ch.RunAutoplanCommand(testdata.GithubRepo, testdata.GithubRepo, modelPull, testdata.User) projectCommandBuilder.VerifyWasCalled(Never()).BuildAutoplanCommands(Any[*command.Context]()) - vcsClient.VerifyWasCalledOnce().GetPullLabels(testdata.GithubRepo, modelPull) + vcsClient.VerifyWasCalledOnce().GetPullLabels(Any[logging.SimpleLogging](), Eq(testdata.GithubRepo), Eq(modelPull)) } func TestRunCommentCommand_DisableAutoplanLabel_PullNotLabeled(t *testing.T) { @@ -562,11 +582,11 @@ func TestRunCommentCommand_DisableAutoplanLabel_PullNotLabeled(t *testing.T) { CommandName: command.Plan, }, }, nil) - When(ch.VCSClient.GetPullLabels(testdata.GithubRepo, modelPull)).ThenReturn(nil, nil) + When(ch.VCSClient.GetPullLabels(Any[logging.SimpleLogging](), Eq(testdata.GithubRepo), Eq(modelPull))).ThenReturn(nil, nil) ch.RunAutoplanCommand(testdata.GithubRepo, testdata.GithubRepo, modelPull, testdata.User) projectCommandBuilder.VerifyWasCalled(Once()).BuildAutoplanCommands(Any[*command.Context]()) - vcsClient.VerifyWasCalledOnce().GetPullLabels(testdata.GithubRepo, modelPull) + vcsClient.VerifyWasCalledOnce().GetPullLabels(Any[logging.SimpleLogging](), Eq(testdata.GithubRepo), Eq(modelPull)) } func TestRunCommentCommand_ClosedPull(t *testing.T) { @@ -577,11 +597,12 @@ func TestRunCommentCommand_ClosedPull(t *testing.T) { State: github.String("closed"), } modelPull := models.PullRequest{BaseRepo: testdata.GithubRepo, State: models.ClosedPullState, Num: testdata.Pull.Num} - When(githubGetter.GetPullRequest(testdata.GithubRepo, testdata.Pull.Num)).ThenReturn(pull, nil) - When(eventParsing.ParseGithubPull(pull)).ThenReturn(modelPull, modelPull.BaseRepo, testdata.GithubRepo, nil) + When(githubGetter.GetPullRequest(Any[logging.SimpleLogging](), Eq(testdata.GithubRepo), Eq(testdata.Pull.Num))).ThenReturn(pull, nil) + When(eventParsing.ParseGithubPull(Any[logging.SimpleLogging](), Eq(pull))).ThenReturn(modelPull, modelPull.BaseRepo, testdata.GithubRepo, nil) ch.RunCommentCommand(testdata.GithubRepo, &testdata.GithubRepo, nil, testdata.User, testdata.Pull.Num, &events.CommentCommand{Name: command.Plan}) - vcsClient.VerifyWasCalledOnce().CreateComment(testdata.GithubRepo, modelPull.Num, "Atlantis commands can't be run on closed pull requests", "") + vcsClient.VerifyWasCalledOnce().CreateComment( + Any[logging.SimpleLogging](), Eq(testdata.GithubRepo), Eq(modelPull.Num), Eq("Atlantis commands can't be run on closed pull requests"), Eq("")) } func TestRunCommentCommand_MatchedBranch(t *testing.T) { @@ -594,11 +615,12 @@ func TestRunCommentCommand_MatchedBranch(t *testing.T) { }) var pull github.PullRequest modelPull := models.PullRequest{BaseRepo: testdata.GithubRepo, BaseBranch: "main"} - When(githubGetter.GetPullRequest(testdata.GithubRepo, testdata.Pull.Num)).ThenReturn(&pull, nil) - When(eventParsing.ParseGithubPull(&pull)).ThenReturn(modelPull, modelPull.BaseRepo, testdata.GithubRepo, nil) + When(githubGetter.GetPullRequest(Any[logging.SimpleLogging](), Eq(testdata.GithubRepo), Eq(testdata.Pull.Num))).ThenReturn(&pull, nil) + When(eventParsing.ParseGithubPull(Any[logging.SimpleLogging](), Eq(&pull))).ThenReturn(modelPull, modelPull.BaseRepo, testdata.GithubRepo, nil) ch.RunCommentCommand(testdata.GithubRepo, nil, nil, testdata.User, testdata.Pull.Num, &events.CommentCommand{Name: command.Plan}) - vcsClient.VerifyWasCalledOnce().CreateComment(testdata.GithubRepo, modelPull.Num, "Ran Plan for 0 projects:", "plan") + vcsClient.VerifyWasCalledOnce().CreateComment( + Any[logging.SimpleLogging](), Eq(testdata.GithubRepo), Eq(modelPull.Num), Eq("Ran Plan for 0 projects:"), Eq("plan")) } func TestRunCommentCommand_UnmatchedBranch(t *testing.T) { @@ -611,11 +633,11 @@ func TestRunCommentCommand_UnmatchedBranch(t *testing.T) { }) var pull github.PullRequest modelPull := models.PullRequest{BaseRepo: testdata.GithubRepo, BaseBranch: "foo"} - When(githubGetter.GetPullRequest(testdata.GithubRepo, testdata.Pull.Num)).ThenReturn(&pull, nil) - When(eventParsing.ParseGithubPull(&pull)).ThenReturn(modelPull, modelPull.BaseRepo, testdata.GithubRepo, nil) + When(githubGetter.GetPullRequest(Any[logging.SimpleLogging](), Eq(testdata.GithubRepo), Eq(testdata.Pull.Num))).ThenReturn(&pull, nil) + When(eventParsing.ParseGithubPull(Any[logging.SimpleLogging](), Eq(&pull))).ThenReturn(modelPull, modelPull.BaseRepo, testdata.GithubRepo, nil) ch.RunCommentCommand(testdata.GithubRepo, nil, nil, testdata.User, testdata.Pull.Num, &events.CommentCommand{Name: command.Plan}) - vcsClient.VerifyWasCalled(Never()).CreateComment(Any[models.Repo](), Any[int](), Any[string](), Any[string]()) + vcsClient.VerifyWasCalled(Never()).CreateComment(Any[logging.SimpleLogging](), Any[models.Repo](), Any[int](), Any[string](), Any[string]()) } func TestRunUnlockCommand_VCSComment(t *testing.T) { @@ -644,13 +666,15 @@ func TestRunUnlockCommand_VCSComment(t *testing.T) { State: tc.prState, } modelPull := models.PullRequest{BaseRepo: testdata.GithubRepo, State: models.OpenPullState, Num: testdata.Pull.Num} - When(githubGetter.GetPullRequest(testdata.GithubRepo, testdata.Pull.Num)).ThenReturn(pull, nil) - When(eventParsing.ParseGithubPull(pull)).ThenReturn(modelPull, modelPull.BaseRepo, testdata.GithubRepo, nil) + When(githubGetter.GetPullRequest(Any[logging.SimpleLogging](), Eq(testdata.GithubRepo), Eq(testdata.Pull.Num))).ThenReturn(pull, nil) + When(eventParsing.ParseGithubPull(Any[logging.SimpleLogging](), Eq(pull))).ThenReturn(modelPull, modelPull.BaseRepo, testdata.GithubRepo, nil) ch.RunCommentCommand(testdata.GithubRepo, &testdata.GithubRepo, nil, testdata.User, testdata.Pull.Num, &events.CommentCommand{Name: command.Unlock}) deleteLockCommand.VerifyWasCalledOnce().DeleteLocksByPull(testdata.GithubRepo.FullName, testdata.Pull.Num) - vcsClient.VerifyWasCalledOnce().CreateComment(testdata.GithubRepo, testdata.Pull.Num, "All Atlantis locks for this PR have been unlocked and plans discarded", "unlock") + vcsClient.VerifyWasCalledOnce().CreateComment( + Any[logging.SimpleLogging](), Eq(testdata.GithubRepo), Eq(testdata.Pull.Num), + Eq("All Atlantis locks for this PR have been unlocked and plans discarded"), Eq("unlock")) }) } } @@ -664,13 +688,14 @@ func TestRunUnlockCommandFail_VCSComment(t *testing.T) { State: github.String("open"), } modelPull := models.PullRequest{BaseRepo: testdata.GithubRepo, State: models.OpenPullState, Num: testdata.Pull.Num} - When(githubGetter.GetPullRequest(testdata.GithubRepo, testdata.Pull.Num)).ThenReturn(pull, nil) - When(eventParsing.ParseGithubPull(pull)).ThenReturn(modelPull, modelPull.BaseRepo, testdata.GithubRepo, nil) + When(githubGetter.GetPullRequest(Any[logging.SimpleLogging](), Eq(testdata.GithubRepo), Eq(testdata.Pull.Num))).ThenReturn(pull, nil) + When(eventParsing.ParseGithubPull(Any[logging.SimpleLogging](), Eq(pull))).ThenReturn(modelPull, modelPull.BaseRepo, testdata.GithubRepo, nil) When(deleteLockCommand.DeleteLocksByPull(testdata.GithubRepo.FullName, testdata.Pull.Num)).ThenReturn(0, errors.New("err")) ch.RunCommentCommand(testdata.GithubRepo, &testdata.GithubRepo, nil, testdata.User, testdata.Pull.Num, &events.CommentCommand{Name: command.Unlock}) - vcsClient.VerifyWasCalledOnce().CreateComment(testdata.GithubRepo, testdata.Pull.Num, "Failed to delete PR locks", "unlock") + vcsClient.VerifyWasCalledOnce().CreateComment( + Any[logging.SimpleLogging](), Eq(testdata.GithubRepo), Eq(testdata.Pull.Num), Eq("Failed to delete PR locks"), Eq("unlock")) } func TestRunUnlockCommandFail_DisableUnlockLabel(t *testing.T) { @@ -683,14 +708,15 @@ func TestRunUnlockCommandFail_DisableUnlockLabel(t *testing.T) { State: github.String("open"), } modelPull := models.PullRequest{BaseRepo: testdata.GithubRepo, State: models.OpenPullState, Num: testdata.Pull.Num} - When(githubGetter.GetPullRequest(testdata.GithubRepo, testdata.Pull.Num)).ThenReturn(pull, nil) - When(eventParsing.ParseGithubPull(pull)).ThenReturn(modelPull, modelPull.BaseRepo, testdata.GithubRepo, nil) + When(githubGetter.GetPullRequest(Any[logging.SimpleLogging](), Eq(testdata.GithubRepo), Eq(testdata.Pull.Num))).ThenReturn(pull, nil) + When(eventParsing.ParseGithubPull(Any[logging.SimpleLogging](), Eq(pull))).ThenReturn(modelPull, modelPull.BaseRepo, testdata.GithubRepo, nil) When(deleteLockCommand.DeleteLocksByPull(testdata.GithubRepo.FullName, testdata.Pull.Num)).ThenReturn(0, errors.New("err")) - When(ch.VCSClient.GetPullLabels(testdata.GithubRepo, modelPull)).ThenReturn([]string{doNotUnlock, "need-help"}, nil) + When(ch.VCSClient.GetPullLabels(Any[logging.SimpleLogging](), Eq(testdata.GithubRepo), Eq(modelPull))).ThenReturn([]string{doNotUnlock, "need-help"}, nil) ch.RunCommentCommand(testdata.GithubRepo, &testdata.GithubRepo, nil, testdata.User, testdata.Pull.Num, &events.CommentCommand{Name: command.Unlock}) - vcsClient.VerifyWasCalledOnce().CreateComment(testdata.GithubRepo, testdata.Pull.Num, "Not allowed to unlock PR with "+doNotUnlock+" label", "unlock") + vcsClient.VerifyWasCalledOnce().CreateComment( + Any[logging.SimpleLogging](), Eq(testdata.GithubRepo), Eq(testdata.Pull.Num), Eq("Not allowed to unlock PR with "+doNotUnlock+" label"), Eq("unlock")) } func TestRunUnlockCommandFail_GetLabelsFail(t *testing.T) { @@ -701,14 +727,15 @@ func TestRunUnlockCommandFail_GetLabelsFail(t *testing.T) { State: github.String("open"), } modelPull := models.PullRequest{BaseRepo: testdata.GithubRepo, State: models.OpenPullState, Num: testdata.Pull.Num} - When(githubGetter.GetPullRequest(testdata.GithubRepo, testdata.Pull.Num)).ThenReturn(pull, nil) - When(eventParsing.ParseGithubPull(pull)).ThenReturn(modelPull, modelPull.BaseRepo, testdata.GithubRepo, nil) + When(githubGetter.GetPullRequest(Any[logging.SimpleLogging](), Eq(testdata.GithubRepo), Eq(testdata.Pull.Num))).ThenReturn(pull, nil) + When(eventParsing.ParseGithubPull(Any[logging.SimpleLogging](), Eq(pull))).ThenReturn(modelPull, modelPull.BaseRepo, testdata.GithubRepo, nil) When(deleteLockCommand.DeleteLocksByPull(testdata.GithubRepo.FullName, testdata.Pull.Num)).ThenReturn(0, errors.New("err")) - When(ch.VCSClient.GetPullLabels(testdata.GithubRepo, modelPull)).ThenReturn(nil, errors.New("err")) + When(ch.VCSClient.GetPullLabels(Any[logging.SimpleLogging](), Eq(testdata.GithubRepo), Eq(modelPull))).ThenReturn(nil, errors.New("err")) ch.RunCommentCommand(testdata.GithubRepo, &testdata.GithubRepo, nil, testdata.User, testdata.Pull.Num, &events.CommentCommand{Name: command.Unlock}) - vcsClient.VerifyWasCalledOnce().CreateComment(testdata.GithubRepo, testdata.Pull.Num, "Failed to retrieve PR labels... Not unlocking", "unlock") + vcsClient.VerifyWasCalledOnce().CreateComment( + Any[logging.SimpleLogging](), Eq(testdata.GithubRepo), Eq(testdata.Pull.Num), Eq("Failed to retrieve PR labels... Not unlocking"), Eq("unlock")) } func TestRunUnlockCommandDoesntRetrieveLabelsIfDisableUnlockLabelNotSet(t *testing.T) { @@ -721,15 +748,15 @@ func TestRunUnlockCommandDoesntRetrieveLabelsIfDisableUnlockLabelNotSet(t *testi State: github.String("open"), } modelPull := models.PullRequest{BaseRepo: testdata.GithubRepo, State: models.OpenPullState, Num: testdata.Pull.Num} - When(githubGetter.GetPullRequest(testdata.GithubRepo, testdata.Pull.Num)).ThenReturn(pull, nil) - When(eventParsing.ParseGithubPull(pull)).ThenReturn(modelPull, modelPull.BaseRepo, testdata.GithubRepo, nil) + When(githubGetter.GetPullRequest(Any[logging.SimpleLogging](), Eq(testdata.GithubRepo), Eq(testdata.Pull.Num))).ThenReturn(pull, nil) + When(eventParsing.ParseGithubPull(Any[logging.SimpleLogging](), Eq(pull))).ThenReturn(modelPull, modelPull.BaseRepo, testdata.GithubRepo, nil) When(deleteLockCommand.DeleteLocksByPull(testdata.GithubRepo.FullName, testdata.Pull.Num)).ThenReturn(0, errors.New("err")) - When(ch.VCSClient.GetPullLabels(testdata.GithubRepo, modelPull)).ThenReturn([]string{doNotUnlock, "need-help"}, nil) + When(ch.VCSClient.GetPullLabels(Any[logging.SimpleLogging](), Eq(testdata.GithubRepo), Eq(modelPull))).ThenReturn([]string{doNotUnlock, "need-help"}, nil) unlockCommandRunner.DisableUnlockLabel = "" ch.RunCommentCommand(testdata.GithubRepo, &testdata.GithubRepo, nil, testdata.User, testdata.Pull.Num, &events.CommentCommand{Name: command.Unlock}) - vcsClient.VerifyWasCalled(Never()).GetPullLabels(testdata.GithubRepo, modelPull) + vcsClient.VerifyWasCalled(Never()).GetPullLabels(Any[logging.SimpleLogging](), Eq(testdata.GithubRepo), Eq(modelPull)) } func TestRunAutoplanCommand_DeletePlans(t *testing.T) { @@ -817,8 +844,8 @@ func TestRunCommentCommand_FailedPreWorkflowHook_FailOnPreWorkflowHookError_Fals When(workingDir.GetPullDir(Any[models.Repo](), Any[models.PullRequest]())).ThenReturn(tmp, nil) pull := &github.PullRequest{State: github.String("open")} modelPull := models.PullRequest{BaseRepo: testdata.GithubRepo, State: models.OpenPullState, Num: testdata.Pull.Num} - When(githubGetter.GetPullRequest(testdata.GithubRepo, testdata.Pull.Num)).ThenReturn(pull, nil) - When(eventParsing.ParseGithubPull(pull)).ThenReturn(modelPull, modelPull.BaseRepo, testdata.GithubRepo, nil) + When(githubGetter.GetPullRequest(Any[logging.SimpleLogging](), Eq(testdata.GithubRepo), Eq(testdata.Pull.Num))).ThenReturn(pull, nil) + When(eventParsing.ParseGithubPull(Any[logging.SimpleLogging](), Eq(pull))).ThenReturn(modelPull, modelPull.BaseRepo, testdata.GithubRepo, nil) When(preWorkflowHooksCommandRunner.RunPreHooks(Any[*command.Context](), Any[*events.CommentCommand]())).ThenReturn(errors.New("err")) testdata.Pull.BaseRepo = testdata.GithubRepo ch.FailOnPreWorkflowHookError = false @@ -859,8 +886,8 @@ func TestRunGenericPlanCommand_DeletePlans(t *testing.T) { When(workingDir.GetPullDir(Any[models.Repo](), Any[models.PullRequest]())).ThenReturn(tmp, nil) pull := &github.PullRequest{State: github.String("open")} modelPull := models.PullRequest{BaseRepo: testdata.GithubRepo, State: models.OpenPullState, Num: testdata.Pull.Num} - When(githubGetter.GetPullRequest(testdata.GithubRepo, testdata.Pull.Num)).ThenReturn(pull, nil) - When(eventParsing.ParseGithubPull(pull)).ThenReturn(modelPull, modelPull.BaseRepo, testdata.GithubRepo, nil) + When(githubGetter.GetPullRequest(Any[logging.SimpleLogging](), Eq(testdata.GithubRepo), Eq(testdata.Pull.Num))).ThenReturn(pull, nil) + When(eventParsing.ParseGithubPull(Any[logging.SimpleLogging](), Eq(pull))).ThenReturn(modelPull, modelPull.BaseRepo, testdata.GithubRepo, nil) testdata.Pull.BaseRepo = testdata.GithubRepo ch.RunCommentCommand(testdata.GithubRepo, nil, nil, testdata.User, testdata.Pull.Num, &events.CommentCommand{Name: command.Plan}) pendingPlanFinder.VerifyWasCalledOnce().DeletePlans(tmp) @@ -953,8 +980,8 @@ func TestRunGenericPlanCommand_DiscardApprovals(t *testing.T) { When(workingDir.GetPullDir(Any[models.Repo](), Any[models.PullRequest]())).ThenReturn(tmp, nil) pull := &github.PullRequest{State: github.String("open")} modelPull := models.PullRequest{BaseRepo: testdata.GithubRepo, State: models.OpenPullState, Num: testdata.Pull.Num} - When(githubGetter.GetPullRequest(testdata.GithubRepo, testdata.Pull.Num)).ThenReturn(pull, nil) - When(eventParsing.ParseGithubPull(pull)).ThenReturn(modelPull, modelPull.BaseRepo, testdata.GithubRepo, nil) + When(githubGetter.GetPullRequest(Any[logging.SimpleLogging](), Eq(testdata.GithubRepo), Eq(testdata.Pull.Num))).ThenReturn(pull, nil) + When(eventParsing.ParseGithubPull(Any[logging.SimpleLogging](), Eq(pull))).ThenReturn(modelPull, modelPull.BaseRepo, testdata.GithubRepo, nil) testdata.Pull.BaseRepo = testdata.GithubRepo ch.RunCommentCommand(testdata.GithubRepo, nil, nil, testdata.User, testdata.Pull.Num, &events.CommentCommand{Name: command.Plan}) pendingPlanFinder.VerifyWasCalledOnce().DeletePlans(tmp) @@ -983,8 +1010,8 @@ func TestFailedApprovalCreatesFailedStatusUpdate(t *testing.T) { State: models.OpenPullState, Num: testdata.Pull.Num, } - When(githubGetter.GetPullRequest(testdata.GithubRepo, testdata.Pull.Num)).ThenReturn(pull, nil) - When(eventParsing.ParseGithubPull(pull)).ThenReturn(modelPull, modelPull.BaseRepo, testdata.GithubRepo, nil) + When(githubGetter.GetPullRequest(Any[logging.SimpleLogging](), Eq(testdata.GithubRepo), Eq(testdata.Pull.Num))).ThenReturn(pull, nil) + When(eventParsing.ParseGithubPull(Any[logging.SimpleLogging](), Eq(pull))).ThenReturn(modelPull, modelPull.BaseRepo, testdata.GithubRepo, nil) When(projectCommandBuilder.BuildApprovePoliciesCommands(Any[*command.Context](), Any[*events.CommentCommand]())).ThenReturn([]command.ProjectContext{ { @@ -999,6 +1026,7 @@ func TestFailedApprovalCreatesFailedStatusUpdate(t *testing.T) { ch.RunCommentCommand(testdata.GithubRepo, &testdata.GithubRepo, &testdata.Pull, testdata.User, testdata.Pull.Num, &events.CommentCommand{Name: command.ApprovePolicies}) commitUpdater.VerifyWasCalledOnce().UpdateCombinedCount( + Any[logging.SimpleLogging](), Any[models.Repo](), Any[models.PullRequest](), Eq[models.CommitStatus](models.SuccessCommitStatus), @@ -1028,8 +1056,8 @@ func TestApprovedPoliciesUpdateFailedPolicyStatus(t *testing.T) { State: models.OpenPullState, Num: testdata.Pull.Num, } - When(githubGetter.GetPullRequest(testdata.GithubRepo, testdata.Pull.Num)).ThenReturn(pull, nil) - When(eventParsing.ParseGithubPull(pull)).ThenReturn(modelPull, modelPull.BaseRepo, testdata.GithubRepo, nil) + When(githubGetter.GetPullRequest(Any[logging.SimpleLogging](), Eq(testdata.GithubRepo), Eq(testdata.Pull.Num))).ThenReturn(pull, nil) + When(eventParsing.ParseGithubPull(Any[logging.SimpleLogging](), Eq(pull))).ThenReturn(modelPull, modelPull.BaseRepo, testdata.GithubRepo, nil) When(projectCommandBuilder.BuildApprovePoliciesCommands(Any[*command.Context](), Any[*events.CommentCommand]())).ThenReturn([]command.ProjectContext{ { @@ -1054,6 +1082,7 @@ func TestApprovedPoliciesUpdateFailedPolicyStatus(t *testing.T) { ch.RunCommentCommand(testdata.GithubRepo, &testdata.GithubRepo, &testdata.Pull, testdata.User, testdata.Pull.Num, &events.CommentCommand{Name: command.ApprovePolicies}) commitUpdater.VerifyWasCalledOnce().UpdateCombinedCount( + Any[logging.SimpleLogging](), Any[models.Repo](), Any[models.PullRequest](), Eq[models.CommitStatus](models.SuccessCommitStatus), @@ -1083,8 +1112,8 @@ func TestApplyMergeablityWhenPolicyCheckFails(t *testing.T) { State: models.OpenPullState, Num: testdata.Pull.Num, } - When(githubGetter.GetPullRequest(testdata.GithubRepo, testdata.Pull.Num)).ThenReturn(pull, nil) - When(eventParsing.ParseGithubPull(pull)).ThenReturn(modelPull, modelPull.BaseRepo, testdata.GithubRepo, nil) + When(githubGetter.GetPullRequest(Any[logging.SimpleLogging](), Eq(testdata.GithubRepo), Eq(testdata.Pull.Num))).ThenReturn(pull, nil) + When(eventParsing.ParseGithubPull(Any[logging.SimpleLogging](), Eq(pull))).ThenReturn(modelPull, modelPull.BaseRepo, testdata.GithubRepo, nil) _, _ = boltDB.UpdatePullWithResults(modelPull, []command.ProjectResult{ { @@ -1096,7 +1125,7 @@ func TestApplyMergeablityWhenPolicyCheckFails(t *testing.T) { }, }) - When(ch.VCSClient.PullIsMergeable(testdata.GithubRepo, modelPull, "atlantis-test")).ThenReturn(true, nil) + When(ch.VCSClient.PullIsMergeable(Any[logging.SimpleLogging](), Eq(testdata.GithubRepo), Eq(modelPull), Eq("atlantis-test"))).ThenReturn(true, nil) When(projectCommandBuilder.BuildApplyCommands(Any[*command.Context](), Any[*events.CommentCommand]())).Then(func(args []Param) ReturnValues { return ReturnValues{ @@ -1125,8 +1154,8 @@ func TestApplyWithAutoMerge_VSCMerge(t *testing.T) { State: github.String("open"), } modelPull := models.PullRequest{BaseRepo: testdata.GithubRepo, State: models.OpenPullState} - When(githubGetter.GetPullRequest(testdata.GithubRepo, testdata.Pull.Num)).ThenReturn(pull, nil) - When(eventParsing.ParseGithubPull(pull)).ThenReturn(modelPull, modelPull.BaseRepo, testdata.GithubRepo, nil) + When(githubGetter.GetPullRequest(Any[logging.SimpleLogging](), Eq(testdata.GithubRepo), Eq(testdata.Pull.Num))).ThenReturn(pull, nil) + When(eventParsing.ParseGithubPull(Any[logging.SimpleLogging](), Eq(pull))).ThenReturn(modelPull, modelPull.BaseRepo, testdata.GithubRepo, nil) autoMerger.GlobalAutomerge = true defer func() { autoMerger.GlobalAutomerge = false }() @@ -1135,7 +1164,7 @@ func TestApplyWithAutoMerge_VSCMerge(t *testing.T) { } ch.RunCommentCommand(testdata.GithubRepo, &testdata.GithubRepo, nil, testdata.User, testdata.Pull.Num, &events.CommentCommand{Name: command.Apply}) - vcsClient.VerifyWasCalledOnce().MergePull(modelPull, pullOptions) + vcsClient.VerifyWasCalledOnce().MergePull(Any[logging.SimpleLogging](), Eq(modelPull), Eq(pullOptions)) } func TestRunApply_DiscardedProjects(t *testing.T) { @@ -1167,13 +1196,13 @@ func TestRunApply_DiscardedProjects(t *testing.T) { ghPull := &github.PullRequest{ State: github.String("open"), } - When(githubGetter.GetPullRequest(testdata.GithubRepo, testdata.Pull.Num)).ThenReturn(ghPull, nil) - When(eventParsing.ParseGithubPull(ghPull)).ThenReturn(pull, pull.BaseRepo, testdata.GithubRepo, nil) + When(githubGetter.GetPullRequest(Any[logging.SimpleLogging](), Eq(testdata.GithubRepo), Eq(testdata.Pull.Num))).ThenReturn(ghPull, nil) + When(eventParsing.ParseGithubPull(Any[logging.SimpleLogging](), Eq(ghPull))).ThenReturn(pull, pull.BaseRepo, testdata.GithubRepo, nil) When(workingDir.GetPullDir(Any[models.Repo](), Any[models.PullRequest]())). ThenReturn(tmp, nil) ch.RunCommentCommand(testdata.GithubRepo, &testdata.GithubRepo, &pull, testdata.User, testdata.Pull.Num, &events.CommentCommand{Name: command.Apply}) - vcsClient.VerifyWasCalled(Never()).MergePull(Any[models.PullRequest](), Any[models.PullRequestOptions]()) + vcsClient.VerifyWasCalled(Never()).MergePull(Any[logging.SimpleLogging](), Any[models.PullRequest](), Any[models.PullRequestOptions]()) } func TestRunCommentCommand_DrainOngoing(t *testing.T) { @@ -1181,15 +1210,17 @@ func TestRunCommentCommand_DrainOngoing(t *testing.T) { vcsClient := setup(t) drainer.ShutdownBlocking() ch.RunCommentCommand(testdata.GithubRepo, &testdata.GithubRepo, nil, testdata.User, testdata.Pull.Num, nil) - vcsClient.VerifyWasCalledOnce().CreateComment(testdata.GithubRepo, testdata.Pull.Num, "Atlantis server is shutting down, please try again later.", "") + vcsClient.VerifyWasCalledOnce().CreateComment( + Any[logging.SimpleLogging](), Eq(testdata.GithubRepo), Eq(testdata.Pull.Num), Eq("Atlantis server is shutting down, please try again later."), Eq("")) } func TestRunCommentCommand_DrainNotOngoing(t *testing.T) { t.Log("if drain is not ongoing then remove ongoing operation must be called even if panic occurred") setup(t) - When(githubGetter.GetPullRequest(testdata.GithubRepo, testdata.Pull.Num)).ThenPanic("panic test - if you're seeing this in a test failure this isn't the failing test") + When(githubGetter.GetPullRequest(Any[logging.SimpleLogging](), Eq(testdata.GithubRepo), Eq(testdata.Pull.Num))).ThenPanic( + "panic test - if you're seeing this in a test failure this isn't the failing test") ch.RunCommentCommand(testdata.GithubRepo, &testdata.GithubRepo, nil, testdata.User, testdata.Pull.Num, &events.CommentCommand{Name: command.Plan}) - githubGetter.VerifyWasCalledOnce().GetPullRequest(testdata.GithubRepo, testdata.Pull.Num) + githubGetter.VerifyWasCalledOnce().GetPullRequest(Any[logging.SimpleLogging](), Eq(testdata.GithubRepo), Eq(testdata.Pull.Num)) Equals(t, 0, drainer.GetStatus().InProgressOps) } @@ -1198,7 +1229,8 @@ func TestRunAutoplanCommand_DrainOngoing(t *testing.T) { vcsClient := setup(t) drainer.ShutdownBlocking() ch.RunAutoplanCommand(testdata.GithubRepo, testdata.GithubRepo, testdata.Pull, testdata.User) - vcsClient.VerifyWasCalledOnce().CreateComment(testdata.GithubRepo, testdata.Pull.Num, "Atlantis server is shutting down, please try again later.", "plan") + vcsClient.VerifyWasCalledOnce().CreateComment( + Any[logging.SimpleLogging](), Eq(testdata.GithubRepo), Eq(testdata.Pull.Num), Eq("Atlantis server is shutting down, please try again later."), Eq("plan")) } func TestRunAutoplanCommand_DrainNotOngoing(t *testing.T) { diff --git a/server/events/commit_status_updater.go b/server/events/commit_status_updater.go index 07c97b184b..a05b7ef808 100644 --- a/server/events/commit_status_updater.go +++ b/server/events/commit_status_updater.go @@ -20,24 +20,25 @@ import ( "github.com/runatlantis/atlantis/server/events/command" "github.com/runatlantis/atlantis/server/events/models" "github.com/runatlantis/atlantis/server/events/vcs" + "github.com/runatlantis/atlantis/server/logging" "golang.org/x/text/cases" "golang.org/x/text/language" ) -//go:generate pegomock generate --package mocks -o mocks/mock_commit_status_updater.go CommitStatusUpdater +//go:generate pegomock generate github.com/runatlantis/atlantis/server/events --package mocks -o mocks/mock_commit_status_updater.go CommitStatusUpdater // CommitStatusUpdater updates the status of a commit with the VCS host. We set // the status to signify whether the plan/apply succeeds. type CommitStatusUpdater interface { // UpdateCombined updates the combined status of the head commit of pull. // A combined status represents all the projects modified in the pull. - UpdateCombined(repo models.Repo, pull models.PullRequest, status models.CommitStatus, cmdName command.Name) error + UpdateCombined(logger logging.SimpleLogging, repo models.Repo, pull models.PullRequest, status models.CommitStatus, cmdName command.Name) error // UpdateCombinedCount updates the combined status to reflect the // numSuccess out of numTotal. - UpdateCombinedCount(repo models.Repo, pull models.PullRequest, status models.CommitStatus, cmdName command.Name, numSuccess int, numTotal int) error + UpdateCombinedCount(logger logging.SimpleLogging, repo models.Repo, pull models.PullRequest, status models.CommitStatus, cmdName command.Name, numSuccess int, numTotal int) error - UpdatePreWorkflowHook(pull models.PullRequest, status models.CommitStatus, hookDescription string, runtimeDescription string, url string) error - UpdatePostWorkflowHook(pull models.PullRequest, status models.CommitStatus, hookDescription string, runtimeDescription string, url string) error + UpdatePreWorkflowHook(logger logging.SimpleLogging, pull models.PullRequest, status models.CommitStatus, hookDescription string, runtimeDescription string, url string) error + UpdatePostWorkflowHook(logger logging.SimpleLogging, pull models.PullRequest, status models.CommitStatus, hookDescription string, runtimeDescription string, url string) error } // DefaultCommitStatusUpdater implements CommitStatusUpdater. @@ -51,7 +52,7 @@ type DefaultCommitStatusUpdater struct { // cause runtime.StatusUpdater is extracted for resolving circular dependency var _ runtime.StatusUpdater = (*DefaultCommitStatusUpdater)(nil) -func (d *DefaultCommitStatusUpdater) UpdateCombined(repo models.Repo, pull models.PullRequest, status models.CommitStatus, cmdName command.Name) error { +func (d *DefaultCommitStatusUpdater) UpdateCombined(logger logging.SimpleLogging, repo models.Repo, pull models.PullRequest, status models.CommitStatus, cmdName command.Name) error { src := fmt.Sprintf("%s/%s", d.StatusName, cmdName.String()) var descripWords string switch status { @@ -62,10 +63,10 @@ func (d *DefaultCommitStatusUpdater) UpdateCombined(repo models.Repo, pull model case models.SuccessCommitStatus: descripWords = genProjectStatusDescription(cmdName.String(), "succeeded.") } - return d.Client.UpdateStatus(repo, pull, status, src, descripWords, "") + return d.Client.UpdateStatus(logger, repo, pull, status, src, descripWords, "") } -func (d *DefaultCommitStatusUpdater) UpdateCombinedCount(repo models.Repo, pull models.PullRequest, status models.CommitStatus, cmdName command.Name, numSuccess int, numTotal int) error { +func (d *DefaultCommitStatusUpdater) UpdateCombinedCount(logger logging.SimpleLogging, repo models.Repo, pull models.PullRequest, status models.CommitStatus, cmdName command.Name, numSuccess int, numTotal int) error { src := fmt.Sprintf("%s/%s", d.StatusName, cmdName.String()) cmdVerb := "unknown" @@ -78,7 +79,7 @@ func (d *DefaultCommitStatusUpdater) UpdateCombinedCount(repo models.Repo, pull cmdVerb = "applied" } - return d.Client.UpdateStatus(repo, pull, status, src, fmt.Sprintf("%d/%d projects %s successfully.", numSuccess, numTotal, cmdVerb), "") + return d.Client.UpdateStatus(logger, repo, pull, status, src, fmt.Sprintf("%d/%d projects %s successfully.", numSuccess, numTotal, cmdVerb), "") } func (d *DefaultCommitStatusUpdater) UpdateProject(ctx command.ProjectContext, cmdName command.Name, status models.CommitStatus, url string, result *command.ProjectResult) error { @@ -100,22 +101,22 @@ func (d *DefaultCommitStatusUpdater) UpdateProject(ctx command.ProjectContext, c descripWords = genProjectStatusDescription(cmdName.String(), "succeeded.") } } - return d.Client.UpdateStatus(ctx.BaseRepo, ctx.Pull, status, src, descripWords, url) + return d.Client.UpdateStatus(ctx.Log, ctx.BaseRepo, ctx.Pull, status, src, descripWords, url) } func genProjectStatusDescription(cmdName, description string) string { return fmt.Sprintf("%s %s", cases.Title(language.English).String(cmdName), description) } -func (d *DefaultCommitStatusUpdater) UpdatePreWorkflowHook(pull models.PullRequest, status models.CommitStatus, hookDescription string, runtimeDescription string, url string) error { - return d.updateWorkflowHook(pull, status, hookDescription, runtimeDescription, "pre_workflow_hook", url) +func (d *DefaultCommitStatusUpdater) UpdatePreWorkflowHook(log logging.SimpleLogging, pull models.PullRequest, status models.CommitStatus, hookDescription string, runtimeDescription string, url string) error { + return d.updateWorkflowHook(log, pull, status, hookDescription, runtimeDescription, "pre_workflow_hook", url) } -func (d *DefaultCommitStatusUpdater) UpdatePostWorkflowHook(pull models.PullRequest, status models.CommitStatus, hookDescription string, runtimeDescription string, url string) error { - return d.updateWorkflowHook(pull, status, hookDescription, runtimeDescription, "post_workflow_hook", url) +func (d *DefaultCommitStatusUpdater) UpdatePostWorkflowHook(log logging.SimpleLogging, pull models.PullRequest, status models.CommitStatus, hookDescription string, runtimeDescription string, url string) error { + return d.updateWorkflowHook(log, pull, status, hookDescription, runtimeDescription, "post_workflow_hook", url) } -func (d *DefaultCommitStatusUpdater) updateWorkflowHook(pull models.PullRequest, status models.CommitStatus, hookDescription string, runtimeDescription string, workflowType string, url string) error { +func (d *DefaultCommitStatusUpdater) updateWorkflowHook(log logging.SimpleLogging, pull models.PullRequest, status models.CommitStatus, hookDescription string, runtimeDescription string, workflowType string, url string) error { src := fmt.Sprintf("%s/%s: %s", d.StatusName, workflowType, hookDescription) var descripWords string @@ -132,5 +133,5 @@ func (d *DefaultCommitStatusUpdater) updateWorkflowHook(pull models.PullRequest, } } - return d.Client.UpdateStatus(pull.BaseRepo, pull, status, src, descripWords, url) + return d.Client.UpdateStatus(log, pull.BaseRepo, pull, status, src, descripWords, url) } diff --git a/server/events/commit_status_updater_test.go b/server/events/commit_status_updater_test.go index a84f1ced17..1fe059f203 100644 --- a/server/events/commit_status_updater_test.go +++ b/server/events/commit_status_updater_test.go @@ -22,10 +22,12 @@ import ( "github.com/runatlantis/atlantis/server/events/command" "github.com/runatlantis/atlantis/server/events/models" "github.com/runatlantis/atlantis/server/events/vcs/mocks" + "github.com/runatlantis/atlantis/server/logging" . "github.com/runatlantis/atlantis/testing" ) func TestUpdateCombined(t *testing.T) { + logger := logging.NewNoopLogger(t) cases := []struct { status models.CommitStatus command command.Name @@ -68,16 +70,17 @@ func TestUpdateCombined(t *testing.T) { RegisterMockTestingT(t) client := mocks.NewMockClient() s := events.DefaultCommitStatusUpdater{Client: client, StatusName: "atlantis"} - err := s.UpdateCombined(models.Repo{}, models.PullRequest{}, c.status, c.command) + err := s.UpdateCombined(logger, models.Repo{}, models.PullRequest{}, c.status, c.command) Ok(t, err) expSrc := fmt.Sprintf("atlantis/%s", c.command) - client.VerifyWasCalledOnce().UpdateStatus(models.Repo{}, models.PullRequest{}, c.status, expSrc, c.expDescrip, "") + client.VerifyWasCalledOnce().UpdateStatus(logger, models.Repo{}, models.PullRequest{}, c.status, expSrc, c.expDescrip, "") }) } } func TestUpdateCombinedCount(t *testing.T) { + logger := logging.NewNoopLogger(t) cases := []struct { status models.CommitStatus command command.Name @@ -134,11 +137,11 @@ func TestUpdateCombinedCount(t *testing.T) { RegisterMockTestingT(t) client := mocks.NewMockClient() s := events.DefaultCommitStatusUpdater{Client: client, StatusName: "atlantis-test"} - err := s.UpdateCombinedCount(models.Repo{}, models.PullRequest{}, c.status, c.command, c.numSuccess, c.numTotal) + err := s.UpdateCombinedCount(logger, models.Repo{}, models.PullRequest{}, c.status, c.command, c.numSuccess, c.numTotal) Ok(t, err) expSrc := fmt.Sprintf("%s/%s", s.StatusName, c.command) - client.VerifyWasCalledOnce().UpdateStatus(models.Repo{}, models.PullRequest{}, c.status, expSrc, c.expDescrip, "") + client.VerifyWasCalledOnce().UpdateStatus(logger, models.Repo{}, models.PullRequest{}, c.status, expSrc, c.expDescrip, "") }) } } @@ -177,7 +180,9 @@ func TestDefaultCommitStatusUpdater_UpdateProjectSrc(t *testing.T) { Workspace: c.workspace, }, command.Plan, models.PendingCommitStatus, "url", nil) Ok(t, err) - client.VerifyWasCalledOnce().UpdateStatus(models.Repo{}, models.PullRequest{}, models.PendingCommitStatus, c.expSrc, "Plan in progress...", "url") + client.VerifyWasCalledOnce().UpdateStatus( + Any[logging.SimpleLogging](), Eq(models.Repo{}), Eq(models.PullRequest{}), Eq(models.PendingCommitStatus), Eq(c.expSrc), + Eq("Plan in progress..."), Eq("url")) }) } } @@ -240,7 +245,8 @@ func TestDefaultCommitStatusUpdater_UpdateProject(t *testing.T) { Workspace: "default", }, c.cmd, c.status, "url", c.result) Ok(t, err) - client.VerifyWasCalledOnce().UpdateStatus(models.Repo{}, models.PullRequest{}, c.status, fmt.Sprintf("atlantis/%s: ./default", c.cmd.String()), c.expDescrip, "url") + client.VerifyWasCalledOnce().UpdateStatus(Any[logging.SimpleLogging](), Eq(models.Repo{}), Eq(models.PullRequest{}), Eq(c.status), + Eq(fmt.Sprintf("atlantis/%s: ./default", c.cmd.String())), Eq(c.expDescrip), Eq("url")) }) } } @@ -255,6 +261,6 @@ func TestDefaultCommitStatusUpdater_UpdateProjectCustomStatusName(t *testing.T) Workspace: "default", }, command.Apply, models.SuccessCommitStatus, "url", nil) Ok(t, err) - client.VerifyWasCalledOnce().UpdateStatus(models.Repo{}, models.PullRequest{}, - models.SuccessCommitStatus, "custom/apply: ./default", "Apply succeeded.", "url") + client.VerifyWasCalledOnce().UpdateStatus(Any[logging.SimpleLogging](), Eq(models.Repo{}), Eq(models.PullRequest{}), + Eq(models.SuccessCommitStatus), Eq("custom/apply: ./default"), Eq("Apply succeeded."), Eq("url")) } diff --git a/server/events/event_parser.go b/server/events/event_parser.go index 6aa043f794..77089f8f51 100644 --- a/server/events/event_parser.go +++ b/server/events/event_parser.go @@ -29,6 +29,7 @@ import ( "github.com/runatlantis/atlantis/server/events/models" "github.com/runatlantis/atlantis/server/events/vcs/bitbucketcloud" "github.com/runatlantis/atlantis/server/events/vcs/bitbucketserver" + "github.com/runatlantis/atlantis/server/logging" "github.com/xanzy/go-gitlab" ) @@ -200,7 +201,7 @@ func NewCommentCommand(repoRelDir string, flags []string, name command.Name, sub } } -//go:generate pegomock generate --package mocks -o mocks/mock_event_parsing.go EventParsing +//go:generate pegomock generate github.com/runatlantis/atlantis/server/events --package mocks -o mocks/mock_event_parsing.go EventParsing // EventParsing parses webhook events from different VCS hosts into their // respective Atlantis models. @@ -210,7 +211,7 @@ type EventParsing interface { // baseRepo is the repo that the pull request will be merged into. // user is the pull request author. // pullNum is the number of the pull request that triggered the webhook. - ParseGithubIssueCommentEvent(comment *github.IssueCommentEvent) ( + ParseGithubIssueCommentEvent(logger logging.SimpleLogging, comment *github.IssueCommentEvent) ( baseRepo models.Repo, user models.User, pullNum int, err error) // ParseGithubPull parses the response from the GitHub API endpoint (not @@ -218,7 +219,7 @@ type EventParsing interface { // pull is the parsed pull request. // baseRepo is the repo the pull request will be merged into. // headRepo is the repo the pull request branch is from. - ParseGithubPull(ghPull *github.PullRequest) ( + ParseGithubPull(logger logging.SimpleLogging, ghPull *github.PullRequest) ( pull models.PullRequest, baseRepo models.Repo, headRepo models.Repo, err error) // ParseGithubPullEvent parses GitHub pull request events. @@ -227,7 +228,7 @@ type EventParsing interface { // baseRepo is the repo the pull request will be merged into. // headRepo is the repo the pull request branch is from. // user is the pull request author. - ParseGithubPullEvent(pullEvent *github.PullRequestEvent) ( + ParseGithubPullEvent(logger logging.SimpleLogging, pullEvent *github.PullRequestEvent) ( pull models.PullRequest, pullEventType models.PullRequestEventType, baseRepo models.Repo, headRepo models.Repo, user models.User, err error) @@ -471,7 +472,7 @@ func (e *EventParser) ParseBitbucketCloudPullEvent(body []byte) (pull models.Pul // ParseGithubIssueCommentEvent parses GitHub pull request comment events. // See EventParsing for return value docs. -func (e *EventParser) ParseGithubIssueCommentEvent(comment *github.IssueCommentEvent) (baseRepo models.Repo, user models.User, pullNum int, err error) { +func (e *EventParser) ParseGithubIssueCommentEvent(logger logging.SimpleLogging, comment *github.IssueCommentEvent) (baseRepo models.Repo, user models.User, pullNum int, err error) { baseRepo, err = e.ParseGithubRepo(comment.Repo) if err != nil { return @@ -494,12 +495,12 @@ func (e *EventParser) ParseGithubIssueCommentEvent(comment *github.IssueCommentE // ParseGithubPullEvent parses GitHub pull request events. // See EventParsing for return value docs. -func (e *EventParser) ParseGithubPullEvent(pullEvent *github.PullRequestEvent) (pull models.PullRequest, pullEventType models.PullRequestEventType, baseRepo models.Repo, headRepo models.Repo, user models.User, err error) { +func (e *EventParser) ParseGithubPullEvent(logger logging.SimpleLogging, pullEvent *github.PullRequestEvent) (pull models.PullRequest, pullEventType models.PullRequestEventType, baseRepo models.Repo, headRepo models.Repo, user models.User, err error) { if pullEvent.PullRequest == nil { err = errors.New("pull_request is null") return } - pull, baseRepo, headRepo, err = e.ParseGithubPull(pullEvent.PullRequest) + pull, baseRepo, headRepo, err = e.ParseGithubPull(logger, pullEvent.PullRequest) if err != nil { return } @@ -543,7 +544,7 @@ func (e *EventParser) ParseGithubPullEvent(pullEvent *github.PullRequestEvent) ( // ParseGithubPull parses the response from the GitHub API endpoint (not // from a webhook) that returns a pull request. // See EventParsing for return value docs. -func (e *EventParser) ParseGithubPull(pull *github.PullRequest) (pullModel models.PullRequest, baseRepo models.Repo, headRepo models.Repo, err error) { +func (e *EventParser) ParseGithubPull(logger logging.SimpleLogging, pull *github.PullRequest) (pullModel models.PullRequest, baseRepo models.Repo, headRepo models.Repo, err error) { commit := pull.Head.GetSHA() if commit == "" { err = errors.New("head.sha is null") diff --git a/server/events/event_parser_test.go b/server/events/event_parser_test.go index bd71a2a335..961c659151 100644 --- a/server/events/event_parser_test.go +++ b/server/events/event_parser_test.go @@ -28,6 +28,7 @@ import ( "github.com/runatlantis/atlantis/server/events/command" "github.com/runatlantis/atlantis/server/events/models" . "github.com/runatlantis/atlantis/server/events/vcs/testdata" + "github.com/runatlantis/atlantis/server/logging" . "github.com/runatlantis/atlantis/testing" gitlab "github.com/xanzy/go-gitlab" ) @@ -62,6 +63,7 @@ func TestParseGithubRepo(t *testing.T) { } func TestParseGithubIssueCommentEvent(t *testing.T) { + logger := logging.NewNoopLogger(t) comment := github.IssueCommentEvent{ Repo: &Repo, Issue: &github.Issue{ @@ -76,26 +78,26 @@ func TestParseGithubIssueCommentEvent(t *testing.T) { testComment := deepcopy.Copy(comment).(github.IssueCommentEvent) testComment.Comment = nil - _, _, _, err := parser.ParseGithubIssueCommentEvent(&testComment) + _, _, _, err := parser.ParseGithubIssueCommentEvent(logger, &testComment) ErrEquals(t, "comment.user.login is null", err) testComment = deepcopy.Copy(comment).(github.IssueCommentEvent) testComment.Comment.User = nil - _, _, _, err = parser.ParseGithubIssueCommentEvent(&testComment) + _, _, _, err = parser.ParseGithubIssueCommentEvent(logger, &testComment) ErrEquals(t, "comment.user.login is null", err) testComment = deepcopy.Copy(comment).(github.IssueCommentEvent) testComment.Comment.User.Login = nil - _, _, _, err = parser.ParseGithubIssueCommentEvent(&testComment) + _, _, _, err = parser.ParseGithubIssueCommentEvent(logger, &testComment) ErrEquals(t, "comment.user.login is null", err) testComment = deepcopy.Copy(comment).(github.IssueCommentEvent) testComment.Issue = nil - _, _, _, err = parser.ParseGithubIssueCommentEvent(&testComment) + _, _, _, err = parser.ParseGithubIssueCommentEvent(logger, &testComment) ErrEquals(t, "issue.number is null", err) // this should be successful - repo, user, pullNum, err := parser.ParseGithubIssueCommentEvent(&comment) + repo, user, pullNum, err := parser.ParseGithubIssueCommentEvent(logger, &comment) Ok(t, err) Equals(t, models.Repo{ Owner: *comment.Repo.Owner.Login, @@ -115,25 +117,26 @@ func TestParseGithubIssueCommentEvent(t *testing.T) { } func TestParseGithubPullEvent(t *testing.T) { - _, _, _, _, _, err := parser.ParseGithubPullEvent(&github.PullRequestEvent{}) + logger := logging.NewNoopLogger(t) + _, _, _, _, _, err := parser.ParseGithubPullEvent(logger, &github.PullRequestEvent{}) ErrEquals(t, "pull_request is null", err) testEvent := deepcopy.Copy(PullEvent).(github.PullRequestEvent) testEvent.PullRequest.HTMLURL = nil - _, _, _, _, _, err = parser.ParseGithubPullEvent(&testEvent) + _, _, _, _, _, err = parser.ParseGithubPullEvent(logger, &testEvent) ErrEquals(t, "html_url is null", err) testEvent = deepcopy.Copy(PullEvent).(github.PullRequestEvent) testEvent.Sender = nil - _, _, _, _, _, err = parser.ParseGithubPullEvent(&testEvent) + _, _, _, _, _, err = parser.ParseGithubPullEvent(logger, &testEvent) ErrEquals(t, "sender is null", err) testEvent = deepcopy.Copy(PullEvent).(github.PullRequestEvent) testEvent.Sender.Login = nil - _, _, _, _, _, err = parser.ParseGithubPullEvent(&testEvent) + _, _, _, _, _, err = parser.ParseGithubPullEvent(logger, &testEvent) ErrEquals(t, "sender.login is null", err) - actPull, evType, actBaseRepo, actHeadRepo, actUser, err := parser.ParseGithubPullEvent(&PullEvent) + actPull, evType, actBaseRepo, actHeadRepo, actUser, err := parser.ParseGithubPullEvent(logger, &PullEvent) Ok(t, err) expBaseRepo := models.Repo{ Owner: "owner", @@ -163,30 +166,32 @@ func TestParseGithubPullEvent(t *testing.T) { } func TestParseGithubPullEventFromDraft(t *testing.T) { + logger := logging.NewNoopLogger(t) // verify that close event treated as 'close' events by default closeEvent := deepcopy.Copy(PullEvent).(github.PullRequestEvent) closeEvent.Action = github.String("closed") closeEvent.PullRequest.Draft = github.Bool(true) - _, evType, _, _, _, err := parser.ParseGithubPullEvent(&closeEvent) + _, evType, _, _, _, err := parser.ParseGithubPullEvent(logger, &closeEvent) Ok(t, err) Equals(t, models.ClosedPullEvent, evType) // verify that draft PRs are treated as 'other' events by default testEvent := deepcopy.Copy(PullEvent).(github.PullRequestEvent) testEvent.PullRequest.Draft = github.Bool(true) - _, evType, _, _, _, err = parser.ParseGithubPullEvent(&testEvent) + _, evType, _, _, _, err = parser.ParseGithubPullEvent(logger, &testEvent) Ok(t, err) Equals(t, models.OtherPullEvent, evType) // verify that drafts are planned if requested parser.AllowDraftPRs = true defer func() { parser.AllowDraftPRs = false }() - _, evType, _, _, _, err = parser.ParseGithubPullEvent(&testEvent) + _, evType, _, _, _, err = parser.ParseGithubPullEvent(logger, &testEvent) Ok(t, err) Equals(t, models.OpenedPullEvent, evType) } func TestParseGithubPullEvent_EventType(t *testing.T) { + logger := logging.NewNoopLogger(t) cases := []struct { action string exp models.PullRequestEventType @@ -255,19 +260,19 @@ func TestParseGithubPullEvent_EventType(t *testing.T) { event := deepcopy.Copy(PullEvent).(github.PullRequestEvent) action := c.action event.Action = &action - _, actType, _, _, _, err := parser.ParseGithubPullEvent(&event) + _, actType, _, _, _, err := parser.ParseGithubPullEvent(logger, &event) Ok(t, err) Equals(t, c.exp, actType) // Test draft parsing when draft PRs disabled draftPR := true event.PullRequest.Draft = &draftPR - _, draftEvType, _, _, _, err := parser.ParseGithubPullEvent(&event) + _, draftEvType, _, _, _, err := parser.ParseGithubPullEvent(logger, &event) Ok(t, err) Equals(t, c.draftExp, draftEvType) // Test draft parsing when draft PRs are enabled. draftParser := parser draftParser.AllowDraftPRs = true - _, draftEvType, _, _, _, err = draftParser.ParseGithubPullEvent(&event) + _, draftEvType, _, _, _, err = draftParser.ParseGithubPullEvent(logger, &event) Ok(t, err) Equals(t, c.exp, draftEvType) }) @@ -275,37 +280,38 @@ func TestParseGithubPullEvent_EventType(t *testing.T) { } func TestParseGithubPull(t *testing.T) { + logger := logging.NewNoopLogger(t) testPull := deepcopy.Copy(Pull).(github.PullRequest) testPull.Head.SHA = nil - _, _, _, err := parser.ParseGithubPull(&testPull) + _, _, _, err := parser.ParseGithubPull(logger, &testPull) ErrEquals(t, "head.sha is null", err) testPull = deepcopy.Copy(Pull).(github.PullRequest) testPull.HTMLURL = nil - _, _, _, err = parser.ParseGithubPull(&testPull) + _, _, _, err = parser.ParseGithubPull(logger, &testPull) ErrEquals(t, "html_url is null", err) testPull = deepcopy.Copy(Pull).(github.PullRequest) testPull.Head.Ref = nil - _, _, _, err = parser.ParseGithubPull(&testPull) + _, _, _, err = parser.ParseGithubPull(logger, &testPull) ErrEquals(t, "head.ref is null", err) testPull = deepcopy.Copy(Pull).(github.PullRequest) testPull.Base.Ref = nil - _, _, _, err = parser.ParseGithubPull(&testPull) + _, _, _, err = parser.ParseGithubPull(logger, &testPull) ErrEquals(t, "base.ref is null", err) testPull = deepcopy.Copy(Pull).(github.PullRequest) testPull.User.Login = nil - _, _, _, err = parser.ParseGithubPull(&testPull) + _, _, _, err = parser.ParseGithubPull(logger, &testPull) ErrEquals(t, "user.login is null", err) testPull = deepcopy.Copy(Pull).(github.PullRequest) testPull.Number = nil - _, _, _, err = parser.ParseGithubPull(&testPull) + _, _, _, err = parser.ParseGithubPull(logger, &testPull) ErrEquals(t, "number is null", err) - pullRes, actBaseRepo, actHeadRepo, err := parser.ParseGithubPull(&Pull) + pullRes, actBaseRepo, actHeadRepo, err := parser.ParseGithubPull(logger, &Pull) Ok(t, err) expBaseRepo := models.Repo{ Owner: "owner", diff --git a/server/events/import_command_runner.go b/server/events/import_command_runner.go index 51fbe34981..7f850ca409 100644 --- a/server/events/import_command_runner.go +++ b/server/events/import_command_runner.go @@ -36,7 +36,7 @@ func (v *ImportCommandRunner) Run(ctx *command.Context, cmd *CommentCommand) { // required the Atlantis status checks to pass, then we've now changed // the mergeability status of the pull request. // This sets the approved, mergeable, and sqlocked status in the context. - ctx.PullRequestStatus, err = v.pullReqStatusFetcher.FetchPullStatus(ctx.Pull) + ctx.PullRequestStatus, err = v.pullReqStatusFetcher.FetchPullStatus(ctx.Log, ctx.Pull) if err != nil { // On error we continue the request with mergeable assumed false. // We want to continue because not all import will need this status, diff --git a/server/events/import_command_runner_test.go b/server/events/import_command_runner_test.go index 140fb86685..694f7d79e8 100644 --- a/server/events/import_command_runner_test.go +++ b/server/events/import_command_runner_test.go @@ -64,7 +64,7 @@ func TestImportCommandRunner_Run(t *testing.T) { modelPull := models.PullRequest{BaseRepo: testdata.GithubRepo, State: models.OpenPullState, Num: testdata.Pull.Num} ctx := &command.Context{ User: testdata.User, - Log: logging.NewNoopLogger(t), + Log: logger, Scope: scopeNull, Pull: modelPull, HeadRepo: testdata.GithubRepo, @@ -72,16 +72,18 @@ func TestImportCommandRunner_Run(t *testing.T) { } cmd := &events.CommentCommand{Name: command.Import} - When(pullReqStatusFetcher.FetchPullStatus(modelPull)).ThenReturn(tt.pullReqStatus, nil) + When(pullReqStatusFetcher.FetchPullStatus(logger, modelPull)).ThenReturn(tt.pullReqStatus, nil) When(projectCommandBuilder.BuildImportCommands(ctx, cmd)).ThenReturn(tt.projectCmds, nil) importCommandRunner.Run(ctx, cmd) Assert(t, ctx.PullRequestStatus.Mergeable == true, "PullRequestStatus must be set for import_requirements") if tt.expNoComment { - vcsClient.VerifyWasCalled(Never()).CreateComment(Any[models.Repo](), Any[int](), Any[string](), Any[string]()) + vcsClient.VerifyWasCalled(Never()).CreateComment( + Any[logging.SimpleLogging](), Any[models.Repo](), Any[int](), Any[string](), Any[string]()) } else { - vcsClient.VerifyWasCalledOnce().CreateComment(testdata.GithubRepo, modelPull.Num, tt.expComment, "import") + vcsClient.VerifyWasCalledOnce().CreateComment( + Any[logging.SimpleLogging](), Eq(testdata.GithubRepo), Eq(modelPull.Num), Eq(tt.expComment), Eq("import")) } }) } diff --git a/server/events/instrumented_pull_closed_executor.go b/server/events/instrumented_pull_closed_executor.go index 0751a0d21b..5b1bba01e6 100644 --- a/server/events/instrumented_pull_closed_executor.go +++ b/server/events/instrumented_pull_closed_executor.go @@ -1,8 +1,6 @@ package events import ( - "strconv" - "github.com/runatlantis/atlantis/server/events/models" "github.com/runatlantis/atlantis/server/logging" "github.com/runatlantis/atlantis/server/metrics" @@ -31,24 +29,20 @@ func NewInstrumentedPullClosedExecutor( } } -func (e *InstrumentedPullClosedExecutor) CleanUpPull(repo models.Repo, pull models.PullRequest) error { - log := e.log.With( - "repository", repo.FullName, - "pull-num", strconv.Itoa(pull.Num), - ) +func (e *InstrumentedPullClosedExecutor) CleanUpPull(logger logging.SimpleLogging, repo models.Repo, pull models.PullRequest) error { executionSuccess := e.scope.Counter(metrics.ExecutionSuccessMetric) executionError := e.scope.Counter(metrics.ExecutionErrorMetric) executionTime := e.scope.Timer(metrics.ExecutionTimeMetric).Start() defer executionTime.Stop() - log.Info("Initiating cleanup of pull data.") + logger.Info("Initiating cleanup of pull data.") - err := e.cleaner.CleanUpPull(repo, pull) + err := e.cleaner.CleanUpPull(logger, repo, pull) if err != nil { executionError.Inc(1) - log.Err("error during cleanup of pull data", err) + logger.Err("error during cleanup of pull data", err) return err } diff --git a/server/events/mocks/mock_azuredevops_pull_getter.go b/server/events/mocks/mock_azuredevops_pull_getter.go index ce3a618b88..95c57e0e89 100644 --- a/server/events/mocks/mock_azuredevops_pull_getter.go +++ b/server/events/mocks/mock_azuredevops_pull_getter.go @@ -7,6 +7,7 @@ import ( azuredevops "github.com/mcdafydd/go-azuredevops/azuredevops" pegomock "github.com/petergtz/pegomock/v4" models "github.com/runatlantis/atlantis/server/events/models" + logging "github.com/runatlantis/atlantis/server/logging" "reflect" "time" ) @@ -26,11 +27,11 @@ func NewMockAzureDevopsPullGetter(options ...pegomock.Option) *MockAzureDevopsPu func (mock *MockAzureDevopsPullGetter) SetFailHandler(fh pegomock.FailHandler) { mock.fail = fh } func (mock *MockAzureDevopsPullGetter) FailHandler() pegomock.FailHandler { return mock.fail } -func (mock *MockAzureDevopsPullGetter) GetPullRequest(repo models.Repo, pullNum int) (*azuredevops.GitPullRequest, error) { +func (mock *MockAzureDevopsPullGetter) GetPullRequest(logger logging.SimpleLogging, repo models.Repo, pullNum int) (*azuredevops.GitPullRequest, error) { if mock == nil { panic("mock must not be nil. Use myMock := NewMockAzureDevopsPullGetter().") } - params := []pegomock.Param{repo, pullNum} + params := []pegomock.Param{logger, repo, pullNum} result := pegomock.GetGenericMockFrom(mock).Invoke("GetPullRequest", params, []reflect.Type{reflect.TypeOf((**azuredevops.GitPullRequest)(nil)).Elem(), reflect.TypeOf((*error)(nil)).Elem()}) var ret0 *azuredevops.GitPullRequest var ret1 error @@ -82,8 +83,8 @@ type VerifierMockAzureDevopsPullGetter struct { timeout time.Duration } -func (verifier *VerifierMockAzureDevopsPullGetter) GetPullRequest(repo models.Repo, pullNum int) *MockAzureDevopsPullGetter_GetPullRequest_OngoingVerification { - params := []pegomock.Param{repo, pullNum} +func (verifier *VerifierMockAzureDevopsPullGetter) GetPullRequest(logger logging.SimpleLogging, repo models.Repo, pullNum int) *MockAzureDevopsPullGetter_GetPullRequest_OngoingVerification { + params := []pegomock.Param{logger, repo, pullNum} methodInvocations := pegomock.GetGenericMockFrom(verifier.mock).Verify(verifier.inOrderContext, verifier.invocationCountMatcher, "GetPullRequest", params, verifier.timeout) return &MockAzureDevopsPullGetter_GetPullRequest_OngoingVerification{mock: verifier.mock, methodInvocations: methodInvocations} } @@ -93,21 +94,25 @@ type MockAzureDevopsPullGetter_GetPullRequest_OngoingVerification struct { methodInvocations []pegomock.MethodInvocation } -func (c *MockAzureDevopsPullGetter_GetPullRequest_OngoingVerification) GetCapturedArguments() (models.Repo, int) { - repo, pullNum := c.GetAllCapturedArguments() - return repo[len(repo)-1], pullNum[len(pullNum)-1] +func (c *MockAzureDevopsPullGetter_GetPullRequest_OngoingVerification) GetCapturedArguments() (logging.SimpleLogging, models.Repo, int) { + logger, repo, pullNum := c.GetAllCapturedArguments() + return logger[len(logger)-1], repo[len(repo)-1], pullNum[len(pullNum)-1] } -func (c *MockAzureDevopsPullGetter_GetPullRequest_OngoingVerification) GetAllCapturedArguments() (_param0 []models.Repo, _param1 []int) { +func (c *MockAzureDevopsPullGetter_GetPullRequest_OngoingVerification) GetAllCapturedArguments() (_param0 []logging.SimpleLogging, _param1 []models.Repo, _param2 []int) { params := pegomock.GetGenericMockFrom(c.mock).GetInvocationParams(c.methodInvocations) if len(params) > 0 { - _param0 = make([]models.Repo, len(c.methodInvocations)) + _param0 = make([]logging.SimpleLogging, len(c.methodInvocations)) for u, param := range params[0] { - _param0[u] = param.(models.Repo) + _param0[u] = param.(logging.SimpleLogging) } - _param1 = make([]int, len(c.methodInvocations)) + _param1 = make([]models.Repo, len(c.methodInvocations)) for u, param := range params[1] { - _param1[u] = param.(int) + _param1[u] = param.(models.Repo) + } + _param2 = make([]int, len(c.methodInvocations)) + for u, param := range params[2] { + _param2[u] = param.(int) } } return diff --git a/server/events/mocks/mock_command_requirement_handler.go b/server/events/mocks/mock_command_requirement_handler.go index d302bf4525..d5a36f20eb 100644 --- a/server/events/mocks/mock_command_requirement_handler.go +++ b/server/events/mocks/mock_command_requirement_handler.go @@ -44,12 +44,12 @@ func (mock *MockCommandRequirementHandler) ValidateApplyProject(repoDir string, return ret0, ret1 } -func (mock *MockCommandRequirementHandler) ValidateProjectDependencies(_param0 command.ProjectContext) (string, error) { +func (mock *MockCommandRequirementHandler) ValidateImportProject(repoDir string, ctx command.ProjectContext) (string, error) { if mock == nil { panic("mock must not be nil. Use myMock := NewMockCommandRequirementHandler().") } - params := []pegomock.Param{_param0} - result := pegomock.GetGenericMockFrom(mock).Invoke("ValidateProjectDependencies", params, []reflect.Type{reflect.TypeOf((*string)(nil)).Elem(), reflect.TypeOf((*error)(nil)).Elem()}) + params := []pegomock.Param{repoDir, ctx} + result := pegomock.GetGenericMockFrom(mock).Invoke("ValidateImportProject", params, []reflect.Type{reflect.TypeOf((*string)(nil)).Elem(), reflect.TypeOf((*error)(nil)).Elem()}) var ret0 string var ret1 error if len(result) != 0 { @@ -63,12 +63,12 @@ func (mock *MockCommandRequirementHandler) ValidateProjectDependencies(_param0 c return ret0, ret1 } -func (mock *MockCommandRequirementHandler) ValidateImportProject(repoDir string, ctx command.ProjectContext) (string, error) { +func (mock *MockCommandRequirementHandler) ValidatePlanProject(repoDir string, ctx command.ProjectContext) (string, error) { if mock == nil { panic("mock must not be nil. Use myMock := NewMockCommandRequirementHandler().") } params := []pegomock.Param{repoDir, ctx} - result := pegomock.GetGenericMockFrom(mock).Invoke("ValidateImportProject", params, []reflect.Type{reflect.TypeOf((*string)(nil)).Elem(), reflect.TypeOf((*error)(nil)).Elem()}) + result := pegomock.GetGenericMockFrom(mock).Invoke("ValidatePlanProject", params, []reflect.Type{reflect.TypeOf((*string)(nil)).Elem(), reflect.TypeOf((*error)(nil)).Elem()}) var ret0 string var ret1 error if len(result) != 0 { @@ -82,12 +82,12 @@ func (mock *MockCommandRequirementHandler) ValidateImportProject(repoDir string, return ret0, ret1 } -func (mock *MockCommandRequirementHandler) ValidatePlanProject(repoDir string, ctx command.ProjectContext) (string, error) { +func (mock *MockCommandRequirementHandler) ValidateProjectDependencies(ctx command.ProjectContext) (string, error) { if mock == nil { panic("mock must not be nil. Use myMock := NewMockCommandRequirementHandler().") } - params := []pegomock.Param{repoDir, ctx} - result := pegomock.GetGenericMockFrom(mock).Invoke("ValidatePlanProject", params, []reflect.Type{reflect.TypeOf((*string)(nil)).Elem(), reflect.TypeOf((*error)(nil)).Elem()}) + params := []pegomock.Param{ctx} + result := pegomock.GetGenericMockFrom(mock).Invoke("ValidateProjectDependencies", params, []reflect.Type{reflect.TypeOf((*string)(nil)).Elem(), reflect.TypeOf((*error)(nil)).Elem()}) var ret0 string var ret1 error if len(result) != 0 { @@ -230,3 +230,30 @@ func (c *MockCommandRequirementHandler_ValidatePlanProject_OngoingVerification) } return } + +func (verifier *VerifierMockCommandRequirementHandler) ValidateProjectDependencies(ctx command.ProjectContext) *MockCommandRequirementHandler_ValidateProjectDependencies_OngoingVerification { + params := []pegomock.Param{ctx} + methodInvocations := pegomock.GetGenericMockFrom(verifier.mock).Verify(verifier.inOrderContext, verifier.invocationCountMatcher, "ValidateProjectDependencies", params, verifier.timeout) + return &MockCommandRequirementHandler_ValidateProjectDependencies_OngoingVerification{mock: verifier.mock, methodInvocations: methodInvocations} +} + +type MockCommandRequirementHandler_ValidateProjectDependencies_OngoingVerification struct { + mock *MockCommandRequirementHandler + methodInvocations []pegomock.MethodInvocation +} + +func (c *MockCommandRequirementHandler_ValidateProjectDependencies_OngoingVerification) GetCapturedArguments() command.ProjectContext { + ctx := c.GetAllCapturedArguments() + return ctx[len(ctx)-1] +} + +func (c *MockCommandRequirementHandler_ValidateProjectDependencies_OngoingVerification) GetAllCapturedArguments() (_param0 []command.ProjectContext) { + params := pegomock.GetGenericMockFrom(c.mock).GetInvocationParams(c.methodInvocations) + if len(params) > 0 { + _param0 = make([]command.ProjectContext, len(c.methodInvocations)) + for u, param := range params[0] { + _param0[u] = param.(command.ProjectContext) + } + } + return +} diff --git a/server/events/mocks/mock_commit_status_updater.go b/server/events/mocks/mock_commit_status_updater.go index 9525b9846f..b0e5fcea97 100644 --- a/server/events/mocks/mock_commit_status_updater.go +++ b/server/events/mocks/mock_commit_status_updater.go @@ -7,6 +7,7 @@ import ( pegomock "github.com/petergtz/pegomock/v4" command "github.com/runatlantis/atlantis/server/events/command" models "github.com/runatlantis/atlantis/server/events/models" + logging "github.com/runatlantis/atlantis/server/logging" "reflect" "time" ) @@ -26,11 +27,11 @@ func NewMockCommitStatusUpdater(options ...pegomock.Option) *MockCommitStatusUpd func (mock *MockCommitStatusUpdater) SetFailHandler(fh pegomock.FailHandler) { mock.fail = fh } func (mock *MockCommitStatusUpdater) FailHandler() pegomock.FailHandler { return mock.fail } -func (mock *MockCommitStatusUpdater) UpdateCombined(repo models.Repo, pull models.PullRequest, status models.CommitStatus, cmdName command.Name) error { +func (mock *MockCommitStatusUpdater) UpdateCombined(logger logging.SimpleLogging, repo models.Repo, pull models.PullRequest, status models.CommitStatus, cmdName command.Name) error { if mock == nil { panic("mock must not be nil. Use myMock := NewMockCommitStatusUpdater().") } - params := []pegomock.Param{repo, pull, status, cmdName} + params := []pegomock.Param{logger, repo, pull, status, cmdName} result := pegomock.GetGenericMockFrom(mock).Invoke("UpdateCombined", params, []reflect.Type{reflect.TypeOf((*error)(nil)).Elem()}) var ret0 error if len(result) != 0 { @@ -41,11 +42,11 @@ func (mock *MockCommitStatusUpdater) UpdateCombined(repo models.Repo, pull model return ret0 } -func (mock *MockCommitStatusUpdater) UpdateCombinedCount(repo models.Repo, pull models.PullRequest, status models.CommitStatus, cmdName command.Name, numSuccess int, numTotal int) error { +func (mock *MockCommitStatusUpdater) UpdateCombinedCount(logger logging.SimpleLogging, repo models.Repo, pull models.PullRequest, status models.CommitStatus, cmdName command.Name, numSuccess int, numTotal int) error { if mock == nil { panic("mock must not be nil. Use myMock := NewMockCommitStatusUpdater().") } - params := []pegomock.Param{repo, pull, status, cmdName, numSuccess, numTotal} + params := []pegomock.Param{logger, repo, pull, status, cmdName, numSuccess, numTotal} result := pegomock.GetGenericMockFrom(mock).Invoke("UpdateCombinedCount", params, []reflect.Type{reflect.TypeOf((*error)(nil)).Elem()}) var ret0 error if len(result) != 0 { @@ -56,11 +57,11 @@ func (mock *MockCommitStatusUpdater) UpdateCombinedCount(repo models.Repo, pull return ret0 } -func (mock *MockCommitStatusUpdater) UpdatePostWorkflowHook(pull models.PullRequest, status models.CommitStatus, hookDescription string, runtimeDescription string, url string) error { +func (mock *MockCommitStatusUpdater) UpdatePostWorkflowHook(logger logging.SimpleLogging, pull models.PullRequest, status models.CommitStatus, hookDescription string, runtimeDescription string, url string) error { if mock == nil { panic("mock must not be nil. Use myMock := NewMockCommitStatusUpdater().") } - params := []pegomock.Param{pull, status, hookDescription, runtimeDescription, url} + params := []pegomock.Param{logger, pull, status, hookDescription, runtimeDescription, url} result := pegomock.GetGenericMockFrom(mock).Invoke("UpdatePostWorkflowHook", params, []reflect.Type{reflect.TypeOf((*error)(nil)).Elem()}) var ret0 error if len(result) != 0 { @@ -71,11 +72,11 @@ func (mock *MockCommitStatusUpdater) UpdatePostWorkflowHook(pull models.PullRequ return ret0 } -func (mock *MockCommitStatusUpdater) UpdatePreWorkflowHook(pull models.PullRequest, status models.CommitStatus, hookDescription string, runtimeDescription string, url string) error { +func (mock *MockCommitStatusUpdater) UpdatePreWorkflowHook(logger logging.SimpleLogging, pull models.PullRequest, status models.CommitStatus, hookDescription string, runtimeDescription string, url string) error { if mock == nil { panic("mock must not be nil. Use myMock := NewMockCommitStatusUpdater().") } - params := []pegomock.Param{pull, status, hookDescription, runtimeDescription, url} + params := []pegomock.Param{logger, pull, status, hookDescription, runtimeDescription, url} result := pegomock.GetGenericMockFrom(mock).Invoke("UpdatePreWorkflowHook", params, []reflect.Type{reflect.TypeOf((*error)(nil)).Elem()}) var ret0 error if len(result) != 0 { @@ -123,8 +124,8 @@ type VerifierMockCommitStatusUpdater struct { timeout time.Duration } -func (verifier *VerifierMockCommitStatusUpdater) UpdateCombined(repo models.Repo, pull models.PullRequest, status models.CommitStatus, cmdName command.Name) *MockCommitStatusUpdater_UpdateCombined_OngoingVerification { - params := []pegomock.Param{repo, pull, status, cmdName} +func (verifier *VerifierMockCommitStatusUpdater) UpdateCombined(logger logging.SimpleLogging, repo models.Repo, pull models.PullRequest, status models.CommitStatus, cmdName command.Name) *MockCommitStatusUpdater_UpdateCombined_OngoingVerification { + params := []pegomock.Param{logger, repo, pull, status, cmdName} methodInvocations := pegomock.GetGenericMockFrom(verifier.mock).Verify(verifier.inOrderContext, verifier.invocationCountMatcher, "UpdateCombined", params, verifier.timeout) return &MockCommitStatusUpdater_UpdateCombined_OngoingVerification{mock: verifier.mock, methodInvocations: methodInvocations} } @@ -134,36 +135,40 @@ type MockCommitStatusUpdater_UpdateCombined_OngoingVerification struct { methodInvocations []pegomock.MethodInvocation } -func (c *MockCommitStatusUpdater_UpdateCombined_OngoingVerification) GetCapturedArguments() (models.Repo, models.PullRequest, models.CommitStatus, command.Name) { - repo, pull, status, cmdName := c.GetAllCapturedArguments() - return repo[len(repo)-1], pull[len(pull)-1], status[len(status)-1], cmdName[len(cmdName)-1] +func (c *MockCommitStatusUpdater_UpdateCombined_OngoingVerification) GetCapturedArguments() (logging.SimpleLogging, models.Repo, models.PullRequest, models.CommitStatus, command.Name) { + logger, repo, pull, status, cmdName := c.GetAllCapturedArguments() + return logger[len(logger)-1], repo[len(repo)-1], pull[len(pull)-1], status[len(status)-1], cmdName[len(cmdName)-1] } -func (c *MockCommitStatusUpdater_UpdateCombined_OngoingVerification) GetAllCapturedArguments() (_param0 []models.Repo, _param1 []models.PullRequest, _param2 []models.CommitStatus, _param3 []command.Name) { +func (c *MockCommitStatusUpdater_UpdateCombined_OngoingVerification) GetAllCapturedArguments() (_param0 []logging.SimpleLogging, _param1 []models.Repo, _param2 []models.PullRequest, _param3 []models.CommitStatus, _param4 []command.Name) { params := pegomock.GetGenericMockFrom(c.mock).GetInvocationParams(c.methodInvocations) if len(params) > 0 { - _param0 = make([]models.Repo, len(c.methodInvocations)) + _param0 = make([]logging.SimpleLogging, len(c.methodInvocations)) for u, param := range params[0] { - _param0[u] = param.(models.Repo) + _param0[u] = param.(logging.SimpleLogging) } - _param1 = make([]models.PullRequest, len(c.methodInvocations)) + _param1 = make([]models.Repo, len(c.methodInvocations)) for u, param := range params[1] { - _param1[u] = param.(models.PullRequest) + _param1[u] = param.(models.Repo) } - _param2 = make([]models.CommitStatus, len(c.methodInvocations)) + _param2 = make([]models.PullRequest, len(c.methodInvocations)) for u, param := range params[2] { - _param2[u] = param.(models.CommitStatus) + _param2[u] = param.(models.PullRequest) } - _param3 = make([]command.Name, len(c.methodInvocations)) + _param3 = make([]models.CommitStatus, len(c.methodInvocations)) for u, param := range params[3] { - _param3[u] = param.(command.Name) + _param3[u] = param.(models.CommitStatus) + } + _param4 = make([]command.Name, len(c.methodInvocations)) + for u, param := range params[4] { + _param4[u] = param.(command.Name) } } return } -func (verifier *VerifierMockCommitStatusUpdater) UpdateCombinedCount(repo models.Repo, pull models.PullRequest, status models.CommitStatus, cmdName command.Name, numSuccess int, numTotal int) *MockCommitStatusUpdater_UpdateCombinedCount_OngoingVerification { - params := []pegomock.Param{repo, pull, status, cmdName, numSuccess, numTotal} +func (verifier *VerifierMockCommitStatusUpdater) UpdateCombinedCount(logger logging.SimpleLogging, repo models.Repo, pull models.PullRequest, status models.CommitStatus, cmdName command.Name, numSuccess int, numTotal int) *MockCommitStatusUpdater_UpdateCombinedCount_OngoingVerification { + params := []pegomock.Param{logger, repo, pull, status, cmdName, numSuccess, numTotal} methodInvocations := pegomock.GetGenericMockFrom(verifier.mock).Verify(verifier.inOrderContext, verifier.invocationCountMatcher, "UpdateCombinedCount", params, verifier.timeout) return &MockCommitStatusUpdater_UpdateCombinedCount_OngoingVerification{mock: verifier.mock, methodInvocations: methodInvocations} } @@ -173,44 +178,48 @@ type MockCommitStatusUpdater_UpdateCombinedCount_OngoingVerification struct { methodInvocations []pegomock.MethodInvocation } -func (c *MockCommitStatusUpdater_UpdateCombinedCount_OngoingVerification) GetCapturedArguments() (models.Repo, models.PullRequest, models.CommitStatus, command.Name, int, int) { - repo, pull, status, cmdName, numSuccess, numTotal := c.GetAllCapturedArguments() - return repo[len(repo)-1], pull[len(pull)-1], status[len(status)-1], cmdName[len(cmdName)-1], numSuccess[len(numSuccess)-1], numTotal[len(numTotal)-1] +func (c *MockCommitStatusUpdater_UpdateCombinedCount_OngoingVerification) GetCapturedArguments() (logging.SimpleLogging, models.Repo, models.PullRequest, models.CommitStatus, command.Name, int, int) { + logger, repo, pull, status, cmdName, numSuccess, numTotal := c.GetAllCapturedArguments() + return logger[len(logger)-1], repo[len(repo)-1], pull[len(pull)-1], status[len(status)-1], cmdName[len(cmdName)-1], numSuccess[len(numSuccess)-1], numTotal[len(numTotal)-1] } -func (c *MockCommitStatusUpdater_UpdateCombinedCount_OngoingVerification) GetAllCapturedArguments() (_param0 []models.Repo, _param1 []models.PullRequest, _param2 []models.CommitStatus, _param3 []command.Name, _param4 []int, _param5 []int) { +func (c *MockCommitStatusUpdater_UpdateCombinedCount_OngoingVerification) GetAllCapturedArguments() (_param0 []logging.SimpleLogging, _param1 []models.Repo, _param2 []models.PullRequest, _param3 []models.CommitStatus, _param4 []command.Name, _param5 []int, _param6 []int) { params := pegomock.GetGenericMockFrom(c.mock).GetInvocationParams(c.methodInvocations) if len(params) > 0 { - _param0 = make([]models.Repo, len(c.methodInvocations)) + _param0 = make([]logging.SimpleLogging, len(c.methodInvocations)) for u, param := range params[0] { - _param0[u] = param.(models.Repo) + _param0[u] = param.(logging.SimpleLogging) } - _param1 = make([]models.PullRequest, len(c.methodInvocations)) + _param1 = make([]models.Repo, len(c.methodInvocations)) for u, param := range params[1] { - _param1[u] = param.(models.PullRequest) + _param1[u] = param.(models.Repo) } - _param2 = make([]models.CommitStatus, len(c.methodInvocations)) + _param2 = make([]models.PullRequest, len(c.methodInvocations)) for u, param := range params[2] { - _param2[u] = param.(models.CommitStatus) + _param2[u] = param.(models.PullRequest) } - _param3 = make([]command.Name, len(c.methodInvocations)) + _param3 = make([]models.CommitStatus, len(c.methodInvocations)) for u, param := range params[3] { - _param3[u] = param.(command.Name) + _param3[u] = param.(models.CommitStatus) } - _param4 = make([]int, len(c.methodInvocations)) + _param4 = make([]command.Name, len(c.methodInvocations)) for u, param := range params[4] { - _param4[u] = param.(int) + _param4[u] = param.(command.Name) } _param5 = make([]int, len(c.methodInvocations)) for u, param := range params[5] { _param5[u] = param.(int) } + _param6 = make([]int, len(c.methodInvocations)) + for u, param := range params[6] { + _param6[u] = param.(int) + } } return } -func (verifier *VerifierMockCommitStatusUpdater) UpdatePostWorkflowHook(pull models.PullRequest, status models.CommitStatus, hookDescription string, runtimeDescription string, url string) *MockCommitStatusUpdater_UpdatePostWorkflowHook_OngoingVerification { - params := []pegomock.Param{pull, status, hookDescription, runtimeDescription, url} +func (verifier *VerifierMockCommitStatusUpdater) UpdatePostWorkflowHook(logger logging.SimpleLogging, pull models.PullRequest, status models.CommitStatus, hookDescription string, runtimeDescription string, url string) *MockCommitStatusUpdater_UpdatePostWorkflowHook_OngoingVerification { + params := []pegomock.Param{logger, pull, status, hookDescription, runtimeDescription, url} methodInvocations := pegomock.GetGenericMockFrom(verifier.mock).Verify(verifier.inOrderContext, verifier.invocationCountMatcher, "UpdatePostWorkflowHook", params, verifier.timeout) return &MockCommitStatusUpdater_UpdatePostWorkflowHook_OngoingVerification{mock: verifier.mock, methodInvocations: methodInvocations} } @@ -220,25 +229,25 @@ type MockCommitStatusUpdater_UpdatePostWorkflowHook_OngoingVerification struct { methodInvocations []pegomock.MethodInvocation } -func (c *MockCommitStatusUpdater_UpdatePostWorkflowHook_OngoingVerification) GetCapturedArguments() (models.PullRequest, models.CommitStatus, string, string, string) { - pull, status, hookDescription, runtimeDescription, url := c.GetAllCapturedArguments() - return pull[len(pull)-1], status[len(status)-1], hookDescription[len(hookDescription)-1], runtimeDescription[len(runtimeDescription)-1], url[len(url)-1] +func (c *MockCommitStatusUpdater_UpdatePostWorkflowHook_OngoingVerification) GetCapturedArguments() (logging.SimpleLogging, models.PullRequest, models.CommitStatus, string, string, string) { + logger, pull, status, hookDescription, runtimeDescription, url := c.GetAllCapturedArguments() + return logger[len(logger)-1], pull[len(pull)-1], status[len(status)-1], hookDescription[len(hookDescription)-1], runtimeDescription[len(runtimeDescription)-1], url[len(url)-1] } -func (c *MockCommitStatusUpdater_UpdatePostWorkflowHook_OngoingVerification) GetAllCapturedArguments() (_param0 []models.PullRequest, _param1 []models.CommitStatus, _param2 []string, _param3 []string, _param4 []string) { +func (c *MockCommitStatusUpdater_UpdatePostWorkflowHook_OngoingVerification) GetAllCapturedArguments() (_param0 []logging.SimpleLogging, _param1 []models.PullRequest, _param2 []models.CommitStatus, _param3 []string, _param4 []string, _param5 []string) { params := pegomock.GetGenericMockFrom(c.mock).GetInvocationParams(c.methodInvocations) if len(params) > 0 { - _param0 = make([]models.PullRequest, len(c.methodInvocations)) + _param0 = make([]logging.SimpleLogging, len(c.methodInvocations)) for u, param := range params[0] { - _param0[u] = param.(models.PullRequest) + _param0[u] = param.(logging.SimpleLogging) } - _param1 = make([]models.CommitStatus, len(c.methodInvocations)) + _param1 = make([]models.PullRequest, len(c.methodInvocations)) for u, param := range params[1] { - _param1[u] = param.(models.CommitStatus) + _param1[u] = param.(models.PullRequest) } - _param2 = make([]string, len(c.methodInvocations)) + _param2 = make([]models.CommitStatus, len(c.methodInvocations)) for u, param := range params[2] { - _param2[u] = param.(string) + _param2[u] = param.(models.CommitStatus) } _param3 = make([]string, len(c.methodInvocations)) for u, param := range params[3] { @@ -248,12 +257,16 @@ func (c *MockCommitStatusUpdater_UpdatePostWorkflowHook_OngoingVerification) Get for u, param := range params[4] { _param4[u] = param.(string) } + _param5 = make([]string, len(c.methodInvocations)) + for u, param := range params[5] { + _param5[u] = param.(string) + } } return } -func (verifier *VerifierMockCommitStatusUpdater) UpdatePreWorkflowHook(pull models.PullRequest, status models.CommitStatus, hookDescription string, runtimeDescription string, url string) *MockCommitStatusUpdater_UpdatePreWorkflowHook_OngoingVerification { - params := []pegomock.Param{pull, status, hookDescription, runtimeDescription, url} +func (verifier *VerifierMockCommitStatusUpdater) UpdatePreWorkflowHook(logger logging.SimpleLogging, pull models.PullRequest, status models.CommitStatus, hookDescription string, runtimeDescription string, url string) *MockCommitStatusUpdater_UpdatePreWorkflowHook_OngoingVerification { + params := []pegomock.Param{logger, pull, status, hookDescription, runtimeDescription, url} methodInvocations := pegomock.GetGenericMockFrom(verifier.mock).Verify(verifier.inOrderContext, verifier.invocationCountMatcher, "UpdatePreWorkflowHook", params, verifier.timeout) return &MockCommitStatusUpdater_UpdatePreWorkflowHook_OngoingVerification{mock: verifier.mock, methodInvocations: methodInvocations} } @@ -263,25 +276,25 @@ type MockCommitStatusUpdater_UpdatePreWorkflowHook_OngoingVerification struct { methodInvocations []pegomock.MethodInvocation } -func (c *MockCommitStatusUpdater_UpdatePreWorkflowHook_OngoingVerification) GetCapturedArguments() (models.PullRequest, models.CommitStatus, string, string, string) { - pull, status, hookDescription, runtimeDescription, url := c.GetAllCapturedArguments() - return pull[len(pull)-1], status[len(status)-1], hookDescription[len(hookDescription)-1], runtimeDescription[len(runtimeDescription)-1], url[len(url)-1] +func (c *MockCommitStatusUpdater_UpdatePreWorkflowHook_OngoingVerification) GetCapturedArguments() (logging.SimpleLogging, models.PullRequest, models.CommitStatus, string, string, string) { + logger, pull, status, hookDescription, runtimeDescription, url := c.GetAllCapturedArguments() + return logger[len(logger)-1], pull[len(pull)-1], status[len(status)-1], hookDescription[len(hookDescription)-1], runtimeDescription[len(runtimeDescription)-1], url[len(url)-1] } -func (c *MockCommitStatusUpdater_UpdatePreWorkflowHook_OngoingVerification) GetAllCapturedArguments() (_param0 []models.PullRequest, _param1 []models.CommitStatus, _param2 []string, _param3 []string, _param4 []string) { +func (c *MockCommitStatusUpdater_UpdatePreWorkflowHook_OngoingVerification) GetAllCapturedArguments() (_param0 []logging.SimpleLogging, _param1 []models.PullRequest, _param2 []models.CommitStatus, _param3 []string, _param4 []string, _param5 []string) { params := pegomock.GetGenericMockFrom(c.mock).GetInvocationParams(c.methodInvocations) if len(params) > 0 { - _param0 = make([]models.PullRequest, len(c.methodInvocations)) + _param0 = make([]logging.SimpleLogging, len(c.methodInvocations)) for u, param := range params[0] { - _param0[u] = param.(models.PullRequest) + _param0[u] = param.(logging.SimpleLogging) } - _param1 = make([]models.CommitStatus, len(c.methodInvocations)) + _param1 = make([]models.PullRequest, len(c.methodInvocations)) for u, param := range params[1] { - _param1[u] = param.(models.CommitStatus) + _param1[u] = param.(models.PullRequest) } - _param2 = make([]string, len(c.methodInvocations)) + _param2 = make([]models.CommitStatus, len(c.methodInvocations)) for u, param := range params[2] { - _param2[u] = param.(string) + _param2[u] = param.(models.CommitStatus) } _param3 = make([]string, len(c.methodInvocations)) for u, param := range params[3] { @@ -291,6 +304,10 @@ func (c *MockCommitStatusUpdater_UpdatePreWorkflowHook_OngoingVerification) GetA for u, param := range params[4] { _param4[u] = param.(string) } + _param5 = make([]string, len(c.methodInvocations)) + for u, param := range params[5] { + _param5[u] = param.(string) + } } return } diff --git a/server/events/mocks/mock_event_parsing.go b/server/events/mocks/mock_event_parsing.go index de0a543c38..42dc0a1346 100644 --- a/server/events/mocks/mock_event_parsing.go +++ b/server/events/mocks/mock_event_parsing.go @@ -8,6 +8,7 @@ import ( azuredevops "github.com/mcdafydd/go-azuredevops/azuredevops" pegomock "github.com/petergtz/pegomock/v4" models "github.com/runatlantis/atlantis/server/events/models" + logging "github.com/runatlantis/atlantis/server/logging" go_gitlab "github.com/xanzy/go-gitlab" "reflect" "time" @@ -290,11 +291,11 @@ func (mock *MockEventParsing) ParseBitbucketServerPullEvent(body []byte) (models return ret0, ret1, ret2, ret3, ret4 } -func (mock *MockEventParsing) ParseGithubIssueCommentEvent(comment *github.IssueCommentEvent) (models.Repo, models.User, int, error) { +func (mock *MockEventParsing) ParseGithubIssueCommentEvent(logger logging.SimpleLogging, comment *github.IssueCommentEvent) (models.Repo, models.User, int, error) { if mock == nil { panic("mock must not be nil. Use myMock := NewMockEventParsing().") } - params := []pegomock.Param{comment} + params := []pegomock.Param{logger, comment} result := pegomock.GetGenericMockFrom(mock).Invoke("ParseGithubIssueCommentEvent", params, []reflect.Type{reflect.TypeOf((*models.Repo)(nil)).Elem(), reflect.TypeOf((*models.User)(nil)).Elem(), reflect.TypeOf((*int)(nil)).Elem(), reflect.TypeOf((*error)(nil)).Elem()}) var ret0 models.Repo var ret1 models.User @@ -317,11 +318,11 @@ func (mock *MockEventParsing) ParseGithubIssueCommentEvent(comment *github.Issue return ret0, ret1, ret2, ret3 } -func (mock *MockEventParsing) ParseGithubPull(ghPull *github.PullRequest) (models.PullRequest, models.Repo, models.Repo, error) { +func (mock *MockEventParsing) ParseGithubPull(logger logging.SimpleLogging, ghPull *github.PullRequest) (models.PullRequest, models.Repo, models.Repo, error) { if mock == nil { panic("mock must not be nil. Use myMock := NewMockEventParsing().") } - params := []pegomock.Param{ghPull} + params := []pegomock.Param{logger, ghPull} result := pegomock.GetGenericMockFrom(mock).Invoke("ParseGithubPull", params, []reflect.Type{reflect.TypeOf((*models.PullRequest)(nil)).Elem(), reflect.TypeOf((*models.Repo)(nil)).Elem(), reflect.TypeOf((*models.Repo)(nil)).Elem(), reflect.TypeOf((*error)(nil)).Elem()}) var ret0 models.PullRequest var ret1 models.Repo @@ -344,11 +345,11 @@ func (mock *MockEventParsing) ParseGithubPull(ghPull *github.PullRequest) (model return ret0, ret1, ret2, ret3 } -func (mock *MockEventParsing) ParseGithubPullEvent(pullEvent *github.PullRequestEvent) (models.PullRequest, models.PullRequestEventType, models.Repo, models.Repo, models.User, error) { +func (mock *MockEventParsing) ParseGithubPullEvent(logger logging.SimpleLogging, pullEvent *github.PullRequestEvent) (models.PullRequest, models.PullRequestEventType, models.Repo, models.Repo, models.User, error) { if mock == nil { panic("mock must not be nil. Use myMock := NewMockEventParsing().") } - params := []pegomock.Param{pullEvent} + params := []pegomock.Param{logger, pullEvent} result := pegomock.GetGenericMockFrom(mock).Invoke("ParseGithubPullEvent", params, []reflect.Type{reflect.TypeOf((*models.PullRequest)(nil)).Elem(), reflect.TypeOf((*models.PullRequestEventType)(nil)).Elem(), reflect.TypeOf((*models.Repo)(nil)).Elem(), reflect.TypeOf((*models.Repo)(nil)).Elem(), reflect.TypeOf((*models.User)(nil)).Elem(), reflect.TypeOf((*error)(nil)).Elem()}) var ret0 models.PullRequest var ret1 models.PullRequestEventType @@ -817,8 +818,8 @@ func (c *MockEventParsing_ParseBitbucketServerPullEvent_OngoingVerification) Get return } -func (verifier *VerifierMockEventParsing) ParseGithubIssueCommentEvent(comment *github.IssueCommentEvent) *MockEventParsing_ParseGithubIssueCommentEvent_OngoingVerification { - params := []pegomock.Param{comment} +func (verifier *VerifierMockEventParsing) ParseGithubIssueCommentEvent(logger logging.SimpleLogging, comment *github.IssueCommentEvent) *MockEventParsing_ParseGithubIssueCommentEvent_OngoingVerification { + params := []pegomock.Param{logger, comment} methodInvocations := pegomock.GetGenericMockFrom(verifier.mock).Verify(verifier.inOrderContext, verifier.invocationCountMatcher, "ParseGithubIssueCommentEvent", params, verifier.timeout) return &MockEventParsing_ParseGithubIssueCommentEvent_OngoingVerification{mock: verifier.mock, methodInvocations: methodInvocations} } @@ -828,24 +829,28 @@ type MockEventParsing_ParseGithubIssueCommentEvent_OngoingVerification struct { methodInvocations []pegomock.MethodInvocation } -func (c *MockEventParsing_ParseGithubIssueCommentEvent_OngoingVerification) GetCapturedArguments() *github.IssueCommentEvent { - comment := c.GetAllCapturedArguments() - return comment[len(comment)-1] +func (c *MockEventParsing_ParseGithubIssueCommentEvent_OngoingVerification) GetCapturedArguments() (logging.SimpleLogging, *github.IssueCommentEvent) { + logger, comment := c.GetAllCapturedArguments() + return logger[len(logger)-1], comment[len(comment)-1] } -func (c *MockEventParsing_ParseGithubIssueCommentEvent_OngoingVerification) GetAllCapturedArguments() (_param0 []*github.IssueCommentEvent) { +func (c *MockEventParsing_ParseGithubIssueCommentEvent_OngoingVerification) GetAllCapturedArguments() (_param0 []logging.SimpleLogging, _param1 []*github.IssueCommentEvent) { params := pegomock.GetGenericMockFrom(c.mock).GetInvocationParams(c.methodInvocations) if len(params) > 0 { - _param0 = make([]*github.IssueCommentEvent, len(c.methodInvocations)) + _param0 = make([]logging.SimpleLogging, len(c.methodInvocations)) for u, param := range params[0] { - _param0[u] = param.(*github.IssueCommentEvent) + _param0[u] = param.(logging.SimpleLogging) + } + _param1 = make([]*github.IssueCommentEvent, len(c.methodInvocations)) + for u, param := range params[1] { + _param1[u] = param.(*github.IssueCommentEvent) } } return } -func (verifier *VerifierMockEventParsing) ParseGithubPull(ghPull *github.PullRequest) *MockEventParsing_ParseGithubPull_OngoingVerification { - params := []pegomock.Param{ghPull} +func (verifier *VerifierMockEventParsing) ParseGithubPull(logger logging.SimpleLogging, ghPull *github.PullRequest) *MockEventParsing_ParseGithubPull_OngoingVerification { + params := []pegomock.Param{logger, ghPull} methodInvocations := pegomock.GetGenericMockFrom(verifier.mock).Verify(verifier.inOrderContext, verifier.invocationCountMatcher, "ParseGithubPull", params, verifier.timeout) return &MockEventParsing_ParseGithubPull_OngoingVerification{mock: verifier.mock, methodInvocations: methodInvocations} } @@ -855,24 +860,28 @@ type MockEventParsing_ParseGithubPull_OngoingVerification struct { methodInvocations []pegomock.MethodInvocation } -func (c *MockEventParsing_ParseGithubPull_OngoingVerification) GetCapturedArguments() *github.PullRequest { - ghPull := c.GetAllCapturedArguments() - return ghPull[len(ghPull)-1] +func (c *MockEventParsing_ParseGithubPull_OngoingVerification) GetCapturedArguments() (logging.SimpleLogging, *github.PullRequest) { + logger, ghPull := c.GetAllCapturedArguments() + return logger[len(logger)-1], ghPull[len(ghPull)-1] } -func (c *MockEventParsing_ParseGithubPull_OngoingVerification) GetAllCapturedArguments() (_param0 []*github.PullRequest) { +func (c *MockEventParsing_ParseGithubPull_OngoingVerification) GetAllCapturedArguments() (_param0 []logging.SimpleLogging, _param1 []*github.PullRequest) { params := pegomock.GetGenericMockFrom(c.mock).GetInvocationParams(c.methodInvocations) if len(params) > 0 { - _param0 = make([]*github.PullRequest, len(c.methodInvocations)) + _param0 = make([]logging.SimpleLogging, len(c.methodInvocations)) for u, param := range params[0] { - _param0[u] = param.(*github.PullRequest) + _param0[u] = param.(logging.SimpleLogging) + } + _param1 = make([]*github.PullRequest, len(c.methodInvocations)) + for u, param := range params[1] { + _param1[u] = param.(*github.PullRequest) } } return } -func (verifier *VerifierMockEventParsing) ParseGithubPullEvent(pullEvent *github.PullRequestEvent) *MockEventParsing_ParseGithubPullEvent_OngoingVerification { - params := []pegomock.Param{pullEvent} +func (verifier *VerifierMockEventParsing) ParseGithubPullEvent(logger logging.SimpleLogging, pullEvent *github.PullRequestEvent) *MockEventParsing_ParseGithubPullEvent_OngoingVerification { + params := []pegomock.Param{logger, pullEvent} methodInvocations := pegomock.GetGenericMockFrom(verifier.mock).Verify(verifier.inOrderContext, verifier.invocationCountMatcher, "ParseGithubPullEvent", params, verifier.timeout) return &MockEventParsing_ParseGithubPullEvent_OngoingVerification{mock: verifier.mock, methodInvocations: methodInvocations} } @@ -882,17 +891,21 @@ type MockEventParsing_ParseGithubPullEvent_OngoingVerification struct { methodInvocations []pegomock.MethodInvocation } -func (c *MockEventParsing_ParseGithubPullEvent_OngoingVerification) GetCapturedArguments() *github.PullRequestEvent { - pullEvent := c.GetAllCapturedArguments() - return pullEvent[len(pullEvent)-1] +func (c *MockEventParsing_ParseGithubPullEvent_OngoingVerification) GetCapturedArguments() (logging.SimpleLogging, *github.PullRequestEvent) { + logger, pullEvent := c.GetAllCapturedArguments() + return logger[len(logger)-1], pullEvent[len(pullEvent)-1] } -func (c *MockEventParsing_ParseGithubPullEvent_OngoingVerification) GetAllCapturedArguments() (_param0 []*github.PullRequestEvent) { +func (c *MockEventParsing_ParseGithubPullEvent_OngoingVerification) GetAllCapturedArguments() (_param0 []logging.SimpleLogging, _param1 []*github.PullRequestEvent) { params := pegomock.GetGenericMockFrom(c.mock).GetInvocationParams(c.methodInvocations) if len(params) > 0 { - _param0 = make([]*github.PullRequestEvent, len(c.methodInvocations)) + _param0 = make([]logging.SimpleLogging, len(c.methodInvocations)) for u, param := range params[0] { - _param0[u] = param.(*github.PullRequestEvent) + _param0[u] = param.(logging.SimpleLogging) + } + _param1 = make([]*github.PullRequestEvent, len(c.methodInvocations)) + for u, param := range params[1] { + _param1[u] = param.(*github.PullRequestEvent) } } return diff --git a/server/events/mocks/mock_github_pull_getter.go b/server/events/mocks/mock_github_pull_getter.go index cd38c859cd..3d1fb8419c 100644 --- a/server/events/mocks/mock_github_pull_getter.go +++ b/server/events/mocks/mock_github_pull_getter.go @@ -7,6 +7,7 @@ import ( github "github.com/google/go-github/v58/github" pegomock "github.com/petergtz/pegomock/v4" models "github.com/runatlantis/atlantis/server/events/models" + logging "github.com/runatlantis/atlantis/server/logging" "reflect" "time" ) @@ -26,11 +27,11 @@ func NewMockGithubPullGetter(options ...pegomock.Option) *MockGithubPullGetter { func (mock *MockGithubPullGetter) SetFailHandler(fh pegomock.FailHandler) { mock.fail = fh } func (mock *MockGithubPullGetter) FailHandler() pegomock.FailHandler { return mock.fail } -func (mock *MockGithubPullGetter) GetPullRequest(repo models.Repo, pullNum int) (*github.PullRequest, error) { +func (mock *MockGithubPullGetter) GetPullRequest(logger logging.SimpleLogging, repo models.Repo, pullNum int) (*github.PullRequest, error) { if mock == nil { panic("mock must not be nil. Use myMock := NewMockGithubPullGetter().") } - params := []pegomock.Param{repo, pullNum} + params := []pegomock.Param{logger, repo, pullNum} result := pegomock.GetGenericMockFrom(mock).Invoke("GetPullRequest", params, []reflect.Type{reflect.TypeOf((**github.PullRequest)(nil)).Elem(), reflect.TypeOf((*error)(nil)).Elem()}) var ret0 *github.PullRequest var ret1 error @@ -82,8 +83,8 @@ type VerifierMockGithubPullGetter struct { timeout time.Duration } -func (verifier *VerifierMockGithubPullGetter) GetPullRequest(repo models.Repo, pullNum int) *MockGithubPullGetter_GetPullRequest_OngoingVerification { - params := []pegomock.Param{repo, pullNum} +func (verifier *VerifierMockGithubPullGetter) GetPullRequest(logger logging.SimpleLogging, repo models.Repo, pullNum int) *MockGithubPullGetter_GetPullRequest_OngoingVerification { + params := []pegomock.Param{logger, repo, pullNum} methodInvocations := pegomock.GetGenericMockFrom(verifier.mock).Verify(verifier.inOrderContext, verifier.invocationCountMatcher, "GetPullRequest", params, verifier.timeout) return &MockGithubPullGetter_GetPullRequest_OngoingVerification{mock: verifier.mock, methodInvocations: methodInvocations} } @@ -93,21 +94,25 @@ type MockGithubPullGetter_GetPullRequest_OngoingVerification struct { methodInvocations []pegomock.MethodInvocation } -func (c *MockGithubPullGetter_GetPullRequest_OngoingVerification) GetCapturedArguments() (models.Repo, int) { - repo, pullNum := c.GetAllCapturedArguments() - return repo[len(repo)-1], pullNum[len(pullNum)-1] +func (c *MockGithubPullGetter_GetPullRequest_OngoingVerification) GetCapturedArguments() (logging.SimpleLogging, models.Repo, int) { + logger, repo, pullNum := c.GetAllCapturedArguments() + return logger[len(logger)-1], repo[len(repo)-1], pullNum[len(pullNum)-1] } -func (c *MockGithubPullGetter_GetPullRequest_OngoingVerification) GetAllCapturedArguments() (_param0 []models.Repo, _param1 []int) { +func (c *MockGithubPullGetter_GetPullRequest_OngoingVerification) GetAllCapturedArguments() (_param0 []logging.SimpleLogging, _param1 []models.Repo, _param2 []int) { params := pegomock.GetGenericMockFrom(c.mock).GetInvocationParams(c.methodInvocations) if len(params) > 0 { - _param0 = make([]models.Repo, len(c.methodInvocations)) + _param0 = make([]logging.SimpleLogging, len(c.methodInvocations)) for u, param := range params[0] { - _param0[u] = param.(models.Repo) + _param0[u] = param.(logging.SimpleLogging) } - _param1 = make([]int, len(c.methodInvocations)) + _param1 = make([]models.Repo, len(c.methodInvocations)) for u, param := range params[1] { - _param1[u] = param.(int) + _param1[u] = param.(models.Repo) + } + _param2 = make([]int, len(c.methodInvocations)) + for u, param := range params[2] { + _param2[u] = param.(int) } } return diff --git a/server/events/mocks/mock_gitlab_merge_request_getter.go b/server/events/mocks/mock_gitlab_merge_request_getter.go index 76cc8565b7..cdb481741d 100644 --- a/server/events/mocks/mock_gitlab_merge_request_getter.go +++ b/server/events/mocks/mock_gitlab_merge_request_getter.go @@ -5,6 +5,7 @@ package mocks import ( pegomock "github.com/petergtz/pegomock/v4" + logging "github.com/runatlantis/atlantis/server/logging" go_gitlab "github.com/xanzy/go-gitlab" "reflect" "time" @@ -25,11 +26,11 @@ func NewMockGitlabMergeRequestGetter(options ...pegomock.Option) *MockGitlabMerg func (mock *MockGitlabMergeRequestGetter) SetFailHandler(fh pegomock.FailHandler) { mock.fail = fh } func (mock *MockGitlabMergeRequestGetter) FailHandler() pegomock.FailHandler { return mock.fail } -func (mock *MockGitlabMergeRequestGetter) GetMergeRequest(repoFullName string, pullNum int) (*go_gitlab.MergeRequest, error) { +func (mock *MockGitlabMergeRequestGetter) GetMergeRequest(logger logging.SimpleLogging, repoFullName string, pullNum int) (*go_gitlab.MergeRequest, error) { if mock == nil { panic("mock must not be nil. Use myMock := NewMockGitlabMergeRequestGetter().") } - params := []pegomock.Param{repoFullName, pullNum} + params := []pegomock.Param{logger, repoFullName, pullNum} result := pegomock.GetGenericMockFrom(mock).Invoke("GetMergeRequest", params, []reflect.Type{reflect.TypeOf((**go_gitlab.MergeRequest)(nil)).Elem(), reflect.TypeOf((*error)(nil)).Elem()}) var ret0 *go_gitlab.MergeRequest var ret1 error @@ -81,8 +82,8 @@ type VerifierMockGitlabMergeRequestGetter struct { timeout time.Duration } -func (verifier *VerifierMockGitlabMergeRequestGetter) GetMergeRequest(repoFullName string, pullNum int) *MockGitlabMergeRequestGetter_GetMergeRequest_OngoingVerification { - params := []pegomock.Param{repoFullName, pullNum} +func (verifier *VerifierMockGitlabMergeRequestGetter) GetMergeRequest(logger logging.SimpleLogging, repoFullName string, pullNum int) *MockGitlabMergeRequestGetter_GetMergeRequest_OngoingVerification { + params := []pegomock.Param{logger, repoFullName, pullNum} methodInvocations := pegomock.GetGenericMockFrom(verifier.mock).Verify(verifier.inOrderContext, verifier.invocationCountMatcher, "GetMergeRequest", params, verifier.timeout) return &MockGitlabMergeRequestGetter_GetMergeRequest_OngoingVerification{mock: verifier.mock, methodInvocations: methodInvocations} } @@ -92,21 +93,25 @@ type MockGitlabMergeRequestGetter_GetMergeRequest_OngoingVerification struct { methodInvocations []pegomock.MethodInvocation } -func (c *MockGitlabMergeRequestGetter_GetMergeRequest_OngoingVerification) GetCapturedArguments() (string, int) { - repoFullName, pullNum := c.GetAllCapturedArguments() - return repoFullName[len(repoFullName)-1], pullNum[len(pullNum)-1] +func (c *MockGitlabMergeRequestGetter_GetMergeRequest_OngoingVerification) GetCapturedArguments() (logging.SimpleLogging, string, int) { + logger, repoFullName, pullNum := c.GetAllCapturedArguments() + return logger[len(logger)-1], repoFullName[len(repoFullName)-1], pullNum[len(pullNum)-1] } -func (c *MockGitlabMergeRequestGetter_GetMergeRequest_OngoingVerification) GetAllCapturedArguments() (_param0 []string, _param1 []int) { +func (c *MockGitlabMergeRequestGetter_GetMergeRequest_OngoingVerification) GetAllCapturedArguments() (_param0 []logging.SimpleLogging, _param1 []string, _param2 []int) { params := pegomock.GetGenericMockFrom(c.mock).GetInvocationParams(c.methodInvocations) if len(params) > 0 { - _param0 = make([]string, len(c.methodInvocations)) + _param0 = make([]logging.SimpleLogging, len(c.methodInvocations)) for u, param := range params[0] { - _param0[u] = param.(string) + _param0[u] = param.(logging.SimpleLogging) } - _param1 = make([]int, len(c.methodInvocations)) + _param1 = make([]string, len(c.methodInvocations)) for u, param := range params[1] { - _param1[u] = param.(int) + _param1[u] = param.(string) + } + _param2 = make([]int, len(c.methodInvocations)) + for u, param := range params[2] { + _param2[u] = param.(int) } } return diff --git a/server/events/mocks/mock_pull_cleaner.go b/server/events/mocks/mock_pull_cleaner.go index 588f9b3d31..53fd1877fe 100644 --- a/server/events/mocks/mock_pull_cleaner.go +++ b/server/events/mocks/mock_pull_cleaner.go @@ -6,6 +6,7 @@ package mocks import ( pegomock "github.com/petergtz/pegomock/v4" models "github.com/runatlantis/atlantis/server/events/models" + logging "github.com/runatlantis/atlantis/server/logging" "reflect" "time" ) @@ -25,11 +26,11 @@ func NewMockPullCleaner(options ...pegomock.Option) *MockPullCleaner { func (mock *MockPullCleaner) SetFailHandler(fh pegomock.FailHandler) { mock.fail = fh } func (mock *MockPullCleaner) FailHandler() pegomock.FailHandler { return mock.fail } -func (mock *MockPullCleaner) CleanUpPull(repo models.Repo, pull models.PullRequest) error { +func (mock *MockPullCleaner) CleanUpPull(logger logging.SimpleLogging, repo models.Repo, pull models.PullRequest) error { if mock == nil { panic("mock must not be nil. Use myMock := NewMockPullCleaner().") } - params := []pegomock.Param{repo, pull} + params := []pegomock.Param{logger, repo, pull} result := pegomock.GetGenericMockFrom(mock).Invoke("CleanUpPull", params, []reflect.Type{reflect.TypeOf((*error)(nil)).Elem()}) var ret0 error if len(result) != 0 { @@ -77,8 +78,8 @@ type VerifierMockPullCleaner struct { timeout time.Duration } -func (verifier *VerifierMockPullCleaner) CleanUpPull(repo models.Repo, pull models.PullRequest) *MockPullCleaner_CleanUpPull_OngoingVerification { - params := []pegomock.Param{repo, pull} +func (verifier *VerifierMockPullCleaner) CleanUpPull(logger logging.SimpleLogging, repo models.Repo, pull models.PullRequest) *MockPullCleaner_CleanUpPull_OngoingVerification { + params := []pegomock.Param{logger, repo, pull} methodInvocations := pegomock.GetGenericMockFrom(verifier.mock).Verify(verifier.inOrderContext, verifier.invocationCountMatcher, "CleanUpPull", params, verifier.timeout) return &MockPullCleaner_CleanUpPull_OngoingVerification{mock: verifier.mock, methodInvocations: methodInvocations} } @@ -88,21 +89,25 @@ type MockPullCleaner_CleanUpPull_OngoingVerification struct { methodInvocations []pegomock.MethodInvocation } -func (c *MockPullCleaner_CleanUpPull_OngoingVerification) GetCapturedArguments() (models.Repo, models.PullRequest) { - repo, pull := c.GetAllCapturedArguments() - return repo[len(repo)-1], pull[len(pull)-1] +func (c *MockPullCleaner_CleanUpPull_OngoingVerification) GetCapturedArguments() (logging.SimpleLogging, models.Repo, models.PullRequest) { + logger, repo, pull := c.GetAllCapturedArguments() + return logger[len(logger)-1], repo[len(repo)-1], pull[len(pull)-1] } -func (c *MockPullCleaner_CleanUpPull_OngoingVerification) GetAllCapturedArguments() (_param0 []models.Repo, _param1 []models.PullRequest) { +func (c *MockPullCleaner_CleanUpPull_OngoingVerification) GetAllCapturedArguments() (_param0 []logging.SimpleLogging, _param1 []models.Repo, _param2 []models.PullRequest) { params := pegomock.GetGenericMockFrom(c.mock).GetInvocationParams(c.methodInvocations) if len(params) > 0 { - _param0 = make([]models.Repo, len(c.methodInvocations)) + _param0 = make([]logging.SimpleLogging, len(c.methodInvocations)) for u, param := range params[0] { - _param0[u] = param.(models.Repo) + _param0[u] = param.(logging.SimpleLogging) } - _param1 = make([]models.PullRequest, len(c.methodInvocations)) + _param1 = make([]models.Repo, len(c.methodInvocations)) for u, param := range params[1] { - _param1[u] = param.(models.PullRequest) + _param1[u] = param.(models.Repo) + } + _param2 = make([]models.PullRequest, len(c.methodInvocations)) + for u, param := range params[2] { + _param2[u] = param.(models.PullRequest) } } return diff --git a/server/events/plan_command_runner.go b/server/events/plan_command_runner.go index 044a594233..b8657f5a85 100644 --- a/server/events/plan_command_runner.go +++ b/server/events/plan_command_runner.go @@ -84,7 +84,7 @@ func (p *PlanCommandRunner) runAutoplan(ctx *command.Context) { projectCmds, err := p.prjCmdBuilder.BuildAutoplanCommands(ctx) if err != nil { - if statusErr := p.commitStatusUpdater.UpdateCombined(baseRepo, pull, models.FailedCommitStatus, command.Plan); statusErr != nil { + if statusErr := p.commitStatusUpdater.UpdateCombined(ctx.Log, baseRepo, pull, models.FailedCommitStatus, command.Plan); statusErr != nil { ctx.Log.Warn("unable to update commit status: %s", statusErr) } p.pullUpdater.updatePull(ctx, AutoplanCommand{}, command.Result{Error: err}) @@ -100,13 +100,13 @@ func (p *PlanCommandRunner) runAutoplan(ctx *command.Context) { // with 0/0 projects planned/policy_checked/applied successfully because some users require // the Atlantis status to be passing for all pull requests. ctx.Log.Debug("setting VCS status to success with no projects found") - if err := p.commitStatusUpdater.UpdateCombinedCount(baseRepo, pull, models.SuccessCommitStatus, command.Plan, 0, 0); err != nil { + if err := p.commitStatusUpdater.UpdateCombinedCount(ctx.Log, baseRepo, pull, models.SuccessCommitStatus, command.Plan, 0, 0); err != nil { ctx.Log.Warn("unable to update commit status: %s", err) } - if err := p.commitStatusUpdater.UpdateCombinedCount(baseRepo, pull, models.SuccessCommitStatus, command.PolicyCheck, 0, 0); err != nil { + if err := p.commitStatusUpdater.UpdateCombinedCount(ctx.Log, baseRepo, pull, models.SuccessCommitStatus, command.PolicyCheck, 0, 0); err != nil { ctx.Log.Warn("unable to update commit status: %s", err) } - if err := p.commitStatusUpdater.UpdateCombinedCount(baseRepo, pull, models.SuccessCommitStatus, command.Apply, 0, 0); err != nil { + if err := p.commitStatusUpdater.UpdateCombinedCount(ctx.Log, baseRepo, pull, models.SuccessCommitStatus, command.Apply, 0, 0); err != nil { ctx.Log.Warn("unable to update commit status: %s", err) } } @@ -114,7 +114,7 @@ func (p *PlanCommandRunner) runAutoplan(ctx *command.Context) { } // At this point we are sure Atlantis has work to do, so set commit status to pending - if err := p.commitStatusUpdater.UpdateCombined(ctx.Pull.BaseRepo, ctx.Pull, models.PendingCommitStatus, command.Plan); err != nil { + if err := p.commitStatusUpdater.UpdateCombined(ctx.Log, ctx.Pull.BaseRepo, ctx.Pull, models.PendingCommitStatus, command.Plan); err != nil { ctx.Log.Warn("unable to update plan commit status: %s", err) } @@ -172,7 +172,7 @@ func (p *PlanCommandRunner) run(ctx *command.Context, cmd *CommentCommand) { baseRepo := ctx.Pull.BaseRepo pull := ctx.Pull - ctx.PullRequestStatus, err = p.pullReqStatusFetcher.FetchPullStatus(pull) + ctx.PullRequestStatus, err = p.pullReqStatusFetcher.FetchPullStatus(ctx.Log, pull) if err != nil { // On error we continue the request with mergeable assumed false. // We want to continue because not all apply's will need this status, @@ -187,13 +187,13 @@ func (p *PlanCommandRunner) run(ctx *command.Context, cmd *CommentCommand) { } } - if err = p.commitStatusUpdater.UpdateCombined(baseRepo, pull, models.PendingCommitStatus, command.Plan); err != nil { + if err = p.commitStatusUpdater.UpdateCombined(ctx.Log, baseRepo, pull, models.PendingCommitStatus, command.Plan); err != nil { ctx.Log.Warn("unable to update commit status: %s", err) } projectCmds, err := p.prjCmdBuilder.BuildPlanCommands(ctx, cmd) if err != nil { - if statusErr := p.commitStatusUpdater.UpdateCombined(ctx.Pull.BaseRepo, ctx.Pull, models.FailedCommitStatus, command.Plan); statusErr != nil { + if statusErr := p.commitStatusUpdater.UpdateCombined(ctx.Log, ctx.Pull.BaseRepo, ctx.Pull, models.FailedCommitStatus, command.Plan); statusErr != nil { ctx.Log.Warn("unable to update commit status: %s", statusErr) } p.pullUpdater.updatePull(ctx, cmd, command.Result{Error: err}) @@ -213,7 +213,7 @@ func (p *PlanCommandRunner) run(ctx *command.Context, cmd *CommentCommand) { if pullStatus == nil { // default to 0/0 ctx.Log.Debug("setting VCS status to 0/0 success as no previous state was found") - if err := p.commitStatusUpdater.UpdateCombinedCount(baseRepo, pull, models.SuccessCommitStatus, command.Plan, 0, 0); err != nil { + if err := p.commitStatusUpdater.UpdateCombinedCount(ctx.Log, baseRepo, pull, models.SuccessCommitStatus, command.Plan, 0, 0); err != nil { ctx.Log.Warn("unable to update commit status: %s", err) } return @@ -226,13 +226,13 @@ func (p *PlanCommandRunner) run(ctx *command.Context, cmd *CommentCommand) { // the Atlantis status to be passing for all pull requests. // Does not apply to skipped runs for specific projects ctx.Log.Debug("setting VCS status to success with no projects found") - if err := p.commitStatusUpdater.UpdateCombinedCount(baseRepo, pull, models.SuccessCommitStatus, command.Plan, 0, 0); err != nil { + if err := p.commitStatusUpdater.UpdateCombinedCount(ctx.Log, baseRepo, pull, models.SuccessCommitStatus, command.Plan, 0, 0); err != nil { ctx.Log.Warn("unable to update commit status: %s", err) } - if err := p.commitStatusUpdater.UpdateCombinedCount(baseRepo, pull, models.SuccessCommitStatus, command.PolicyCheck, 0, 0); err != nil { + if err := p.commitStatusUpdater.UpdateCombinedCount(ctx.Log, baseRepo, pull, models.SuccessCommitStatus, command.PolicyCheck, 0, 0); err != nil { ctx.Log.Warn("unable to update commit status: %s", err) } - if err := p.commitStatusUpdater.UpdateCombinedCount(baseRepo, pull, models.SuccessCommitStatus, command.Apply, 0, 0); err != nil { + if err := p.commitStatusUpdater.UpdateCombinedCount(ctx.Log, baseRepo, pull, models.SuccessCommitStatus, command.Apply, 0, 0); err != nil { ctx.Log.Warn("unable to update commit status: %s", err) } } @@ -293,7 +293,7 @@ func (p *PlanCommandRunner) run(ctx *command.Context, cmd *CommentCommand) { // with 0/0 projects planned/policy_checked/applied successfully because some users require // the Atlantis status to be passing for all pull requests. ctx.Log.Debug("setting VCS status to success with no projects found") - if err := p.commitStatusUpdater.UpdateCombinedCount(baseRepo, pull, models.SuccessCommitStatus, command.PolicyCheck, 0, 0); err != nil { + if err := p.commitStatusUpdater.UpdateCombinedCount(ctx.Log, baseRepo, pull, models.SuccessCommitStatus, command.PolicyCheck, 0, 0); err != nil { ctx.Log.Warn("unable to update commit status: %s", err) } } @@ -335,6 +335,7 @@ func (p *PlanCommandRunner) updateCommitStatus(ctx *command.Context, pullStatus } if err := p.commitStatusUpdater.UpdateCombinedCount( + ctx.Log, ctx.Pull.BaseRepo, ctx.Pull, status, diff --git a/server/events/plan_command_runner_test.go b/server/events/plan_command_runner_test.go index 6ccac2f2e8..4f57aff39f 100644 --- a/server/events/plan_command_runner_test.go +++ b/server/events/plan_command_runner_test.go @@ -128,9 +128,11 @@ func TestPlanCommandRunner_IsSilenced(t *testing.T) { timesComment = 0 } - vcsClient.VerifyWasCalled(Times(timesComment)).CreateComment(Any[models.Repo](), Any[int](), Any[string](), Any[string]()) + vcsClient.VerifyWasCalled(Times(timesComment)).CreateComment( + Any[logging.SimpleLogging](), Any[models.Repo](), Any[int](), Any[string](), Any[string]()) if c.ExpVCSStatusSet { commitUpdater.VerifyWasCalledOnce().UpdateCombinedCount( + Any[logging.SimpleLogging](), Any[models.Repo](), Any[models.PullRequest](), Eq[models.CommitStatus](models.SuccessCommitStatus), @@ -140,6 +142,7 @@ func TestPlanCommandRunner_IsSilenced(t *testing.T) { ) } else { commitUpdater.VerifyWasCalled(Never()).UpdateCombinedCount( + Any[logging.SimpleLogging](), Any[models.Repo](), Any[models.PullRequest](), Any[models.CommitStatus](), @@ -484,8 +487,8 @@ func TestPlanCommandRunner_ExecutionOrder(t *testing.T) { Trigger: command.CommentTrigger, } - When(githubGetter.GetPullRequest(testdata.GithubRepo, testdata.Pull.Num)).ThenReturn(pull, nil) - When(eventParsing.ParseGithubPull(pull)).ThenReturn(modelPull, modelPull.BaseRepo, testdata.GithubRepo, nil) + When(githubGetter.GetPullRequest(Any[logging.SimpleLogging](), Eq(testdata.GithubRepo), Eq(testdata.Pull.Num))).ThenReturn(pull, nil) + When(eventParsing.ParseGithubPull(Any[logging.SimpleLogging](), Eq(pull))).ThenReturn(modelPull, modelPull.BaseRepo, testdata.GithubRepo, nil) When(projectCommandBuilder.BuildPlanCommands(ctx, cmd)).ThenReturn(c.ProjectContexts, nil) // When(projectCommandBuilder.BuildPlanCommands(ctx, cmd)).Then(func(args []Param) ReturnValues { @@ -502,7 +505,7 @@ func TestPlanCommandRunner_ExecutionOrder(t *testing.T) { } vcsClient.VerifyWasCalledOnce().CreateComment( - Any[models.Repo](), Eq(modelPull.Num), Any[string](), Eq("plan"), + Any[logging.SimpleLogging](), Any[models.Repo](), Eq(modelPull.Num), Any[string](), Eq("plan"), ) }) } @@ -739,7 +742,7 @@ func TestPlanCommandRunner_AtlantisApplyStatus(t *testing.T) { planCommandRunner.Run(ctx, cmd) - vcsClient.VerifyWasCalledOnce().CreateComment(Any[models.Repo](), AnyInt(), AnyString(), AnyString()) + vcsClient.VerifyWasCalledOnce().CreateComment(Any[logging.SimpleLogging](), Any[models.Repo](), AnyInt(), AnyString(), AnyString()) ExpCommitStatus := models.SuccessCommitStatus if c.ExpVCSApplyStatusSucc != c.ExpVCSApplyStatusTotal { @@ -747,6 +750,7 @@ func TestPlanCommandRunner_AtlantisApplyStatus(t *testing.T) { } if c.DoNotUpdateApply { commitUpdater.VerifyWasCalled(Never()).UpdateCombinedCount( + Any[logging.SimpleLogging](), Any[models.Repo](), Any[models.PullRequest](), Any[models.CommitStatus](), @@ -756,6 +760,7 @@ func TestPlanCommandRunner_AtlantisApplyStatus(t *testing.T) { ) } else { commitUpdater.VerifyWasCalledOnce().UpdateCombinedCount( + Any[logging.SimpleLogging](), Any[models.Repo](), Any[models.PullRequest](), Eq[models.CommitStatus](ExpCommitStatus), diff --git a/server/events/policy_check_command_runner.go b/server/events/policy_check_command_runner.go index c0283aae3e..2f76237f4d 100644 --- a/server/events/policy_check_command_runner.go +++ b/server/events/policy_check_command_runner.go @@ -45,7 +45,7 @@ func (p *PolicyCheckCommandRunner) Run(ctx *command.Context, cmds []command.Proj // with 0/0 projects policy_checked successfully because some users require // the Atlantis status to be passing for all pull requests. ctx.Log.Debug("setting VCS status to success with no projects found") - if err := p.commitStatusUpdater.UpdateCombinedCount(ctx.Pull.BaseRepo, ctx.Pull, models.SuccessCommitStatus, command.PolicyCheck, 0, 0); err != nil { + if err := p.commitStatusUpdater.UpdateCombinedCount(ctx.Log, ctx.Pull.BaseRepo, ctx.Pull, models.SuccessCommitStatus, command.PolicyCheck, 0, 0); err != nil { ctx.Log.Warn("unable to update commit status: %s", err) } } @@ -53,7 +53,7 @@ func (p *PolicyCheckCommandRunner) Run(ctx *command.Context, cmds []command.Proj } // So set policy_check commit status to pending - if err := p.commitStatusUpdater.UpdateCombined(ctx.Pull.BaseRepo, ctx.Pull, models.PendingCommitStatus, command.PolicyCheck); err != nil { + if err := p.commitStatusUpdater.UpdateCombined(ctx.Log, ctx.Pull.BaseRepo, ctx.Pull, models.PendingCommitStatus, command.PolicyCheck); err != nil { ctx.Log.Warn("unable to update commit status: %s", err) } @@ -90,7 +90,7 @@ func (p *PolicyCheckCommandRunner) updateCommitStatus(ctx *command.Context, pull status = models.FailedCommitStatus } - if err := p.commitStatusUpdater.UpdateCombinedCount(ctx.Pull.BaseRepo, ctx.Pull, status, command.PolicyCheck, numSuccess, len(pullStatus.Projects)); err != nil { + if err := p.commitStatusUpdater.UpdateCombinedCount(ctx.Log, ctx.Pull.BaseRepo, ctx.Pull, status, command.PolicyCheck, numSuccess, len(pullStatus.Projects)); err != nil { ctx.Log.Warn("unable to update commit status: %s", err) } } diff --git a/server/events/post_workflow_hooks_command_runner.go b/server/events/post_workflow_hooks_command_runner.go index 4a7a587292..5e36794572 100644 --- a/server/events/post_workflow_hooks_command_runner.go +++ b/server/events/post_workflow_hooks_command_runner.go @@ -136,20 +136,20 @@ func (w *DefaultPostWorkflowHooksCommandRunner) runHooks( return err } - if err := w.CommitStatusUpdater.UpdatePostWorkflowHook(ctx.Pull, models.PendingCommitStatus, ctx.HookDescription, "", url); err != nil { + if err := w.CommitStatusUpdater.UpdatePostWorkflowHook(ctx.Log, ctx.Pull, models.PendingCommitStatus, ctx.HookDescription, "", url); err != nil { ctx.Log.Warn("unable to update post workflow hook status: %s", err) } _, runtimeDesc, err := w.PostWorkflowHookRunner.Run(ctx, hook.RunCommand, shell, shellArgs, repoDir) if err != nil { - if err := w.CommitStatusUpdater.UpdatePostWorkflowHook(ctx.Pull, models.FailedCommitStatus, ctx.HookDescription, runtimeDesc, url); err != nil { + if err := w.CommitStatusUpdater.UpdatePostWorkflowHook(ctx.Log, ctx.Pull, models.FailedCommitStatus, ctx.HookDescription, runtimeDesc, url); err != nil { ctx.Log.Warn("unable to update post workflow hook status: %s", err) } return err } - if err := w.CommitStatusUpdater.UpdatePostWorkflowHook(ctx.Pull, models.SuccessCommitStatus, ctx.HookDescription, runtimeDesc, url); err != nil { + if err := w.CommitStatusUpdater.UpdatePostWorkflowHook(ctx.Log, ctx.Pull, models.SuccessCommitStatus, ctx.HookDescription, runtimeDesc, url); err != nil { ctx.Log.Warn("unable to update post workflow hook status: %s", err) } } diff --git a/server/events/pre_workflow_hooks_command_runner.go b/server/events/pre_workflow_hooks_command_runner.go index e73f0c5037..17b9864757 100644 --- a/server/events/pre_workflow_hooks_command_runner.go +++ b/server/events/pre_workflow_hooks_command_runner.go @@ -78,11 +78,11 @@ func (w *DefaultPreWorkflowHooksCommandRunner) RunPreHooks(ctx *command.Context, // Update the plan or apply commit status to pending whilst the pre workflow hook is running switch cmd.Name { case command.Plan: - if err := w.CommitStatusUpdater.UpdateCombined(ctx.Pull.BaseRepo, ctx.Pull, models.PendingCommitStatus, command.Plan); err != nil { + if err := w.CommitStatusUpdater.UpdateCombined(ctx.Log, ctx.Pull.BaseRepo, ctx.Pull, models.PendingCommitStatus, command.Plan); err != nil { ctx.Log.Warn("unable to update plan commit status: %s", err) } case command.Apply: - if err := w.CommitStatusUpdater.UpdateCombined(ctx.Pull.BaseRepo, ctx.Pull, models.PendingCommitStatus, command.Apply); err != nil { + if err := w.CommitStatusUpdater.UpdateCombined(ctx.Log, ctx.Pull.BaseRepo, ctx.Pull, models.PendingCommitStatus, command.Apply); err != nil { ctx.Log.Warn("unable to update apply commit status: %s", err) } } @@ -145,7 +145,7 @@ func (w *DefaultPreWorkflowHooksCommandRunner) runHooks( return err } - if err := w.CommitStatusUpdater.UpdatePreWorkflowHook(ctx.Pull, models.PendingCommitStatus, ctx.HookDescription, "", url); err != nil { + if err := w.CommitStatusUpdater.UpdatePreWorkflowHook(ctx.Log, ctx.Pull, models.PendingCommitStatus, ctx.HookDescription, "", url); err != nil { ctx.Log.Warn("unable to update pre workflow hook status: %s", err) return err } @@ -153,13 +153,13 @@ func (w *DefaultPreWorkflowHooksCommandRunner) runHooks( _, runtimeDesc, err := w.PreWorkflowHookRunner.Run(ctx, hook.RunCommand, shell, shellArgs, repoDir) if err != nil { - if err := w.CommitStatusUpdater.UpdatePreWorkflowHook(ctx.Pull, models.FailedCommitStatus, ctx.HookDescription, runtimeDesc, url); err != nil { + if err := w.CommitStatusUpdater.UpdatePreWorkflowHook(ctx.Log, ctx.Pull, models.FailedCommitStatus, ctx.HookDescription, runtimeDesc, url); err != nil { ctx.Log.Warn("unable to update pre workflow hook status: %s", err) } return err } - if err := w.CommitStatusUpdater.UpdatePreWorkflowHook(ctx.Pull, models.SuccessCommitStatus, ctx.HookDescription, runtimeDesc, url); err != nil { + if err := w.CommitStatusUpdater.UpdatePreWorkflowHook(ctx.Log, ctx.Pull, models.SuccessCommitStatus, ctx.HookDescription, runtimeDesc, url); err != nil { ctx.Log.Warn("unable to update pre workflow hook status: %s", err) return err } diff --git a/server/events/project_command_builder.go b/server/events/project_command_builder.go index 6868635324..98f1ef9997 100644 --- a/server/events/project_command_builder.go +++ b/server/events/project_command_builder.go @@ -327,7 +327,7 @@ func (p *DefaultProjectCommandBuilder) BuildStateRmCommands(ctx *command.Context // modified in this ctx. func (p *DefaultProjectCommandBuilder) buildAllCommandsByCfg(ctx *command.Context, cmdName command.Name, subCmdName string, commentFlags []string, verbose bool) ([]command.ProjectContext, error) { // We'll need the list of modified files. - modifiedFiles, err := p.VCSClient.GetModifiedFiles(ctx.Pull.BaseRepo, ctx.Pull) + modifiedFiles, err := p.VCSClient.GetModifiedFiles(ctx.Log, ctx.Pull.BaseRepo, ctx.Pull) if err != nil { return nil, err } @@ -352,7 +352,7 @@ func (p *DefaultProjectCommandBuilder) buildAllCommandsByCfg(ctx *command.Contex if p.SkipCloneNoChanges && p.VCSClient.SupportsSingleFileDownload(ctx.Pull.BaseRepo) { repoCfgFile := p.GlobalCfg.RepoConfigFile(ctx.Pull.BaseRepo.ID()) - hasRepoCfg, repoCfgData, err := p.VCSClient.GetFileContent(ctx.Pull, repoCfgFile) + hasRepoCfg, repoCfgData, err := p.VCSClient.GetFileContent(ctx.Log, ctx.Pull, repoCfgFile) if err != nil { return nil, errors.Wrapf(err, "downloading %s", repoCfgFile) } @@ -588,7 +588,7 @@ func (p *DefaultProjectCommandBuilder) buildProjectPlanCommand(ctx *command.Cont if p.RestrictFileList { ctx.Log.Debug("'restrict-file-list' option is set, checking modified files") - modifiedFiles, err := p.VCSClient.GetModifiedFiles(ctx.Pull.BaseRepo, ctx.Pull) + modifiedFiles, err := p.VCSClient.GetModifiedFiles(ctx.Log, ctx.Pull.BaseRepo, ctx.Pull) if err != nil { return nil, err } diff --git a/server/events/project_command_builder_internal_test.go b/server/events/project_command_builder_internal_test.go index 98ded0aa9c..fc7c022073 100644 --- a/server/events/project_command_builder_internal_test.go +++ b/server/events/project_command_builder_internal_test.go @@ -632,7 +632,8 @@ projects: workingDir := NewMockWorkingDir() When(workingDir.Clone(Any[models.Repo](), Any[models.PullRequest](), Any[string]())).ThenReturn(tmp, false, nil) vcsClient := vcsmocks.NewMockClient() - When(vcsClient.GetModifiedFiles(Any[models.Repo](), Any[models.PullRequest]())).ThenReturn([]string{"modules/module/main.tf"}, nil) + When(vcsClient.GetModifiedFiles( + Any[logging.SimpleLogging](), Any[models.Repo](), Any[models.PullRequest]())).ThenReturn([]string{"modules/module/main.tf"}, nil) // Write and parse the global config file. globalCfgPath := filepath.Join(tmp, "global.yaml") @@ -846,7 +847,8 @@ projects: workingDir := NewMockWorkingDir() When(workingDir.Clone(Any[models.Repo](), Any[models.PullRequest](), Any[string]())).ThenReturn(tmp, false, nil) vcsClient := vcsmocks.NewMockClient() - When(vcsClient.GetModifiedFiles(Any[models.Repo](), Any[models.PullRequest]())).ThenReturn([]string{"modules/module/main.tf"}, nil) + When(vcsClient.GetModifiedFiles( + Any[logging.SimpleLogging](), Any[models.Repo](), Any[models.PullRequest]())).ThenReturn([]string{"modules/module/main.tf"}, nil) // Write and parse the global config file. globalCfgPath := filepath.Join(tmp, "global.yaml") @@ -1091,7 +1093,8 @@ workflows: workingDir := NewMockWorkingDir() When(workingDir.Clone(Any[models.Repo](), Any[models.PullRequest](), Any[string]())).ThenReturn(tmp, false, nil) vcsClient := vcsmocks.NewMockClient() - When(vcsClient.GetModifiedFiles(Any[models.Repo](), Any[models.PullRequest]())).ThenReturn([]string{"modules/module/main.tf"}, nil) + When(vcsClient.GetModifiedFiles( + Any[logging.SimpleLogging](), Any[models.Repo](), Any[models.PullRequest]())).ThenReturn([]string{"modules/module/main.tf"}, nil) // Write and parse the global config file. globalCfgPath := filepath.Join(tmp, "global.yaml") @@ -1245,7 +1248,8 @@ projects: workingDir := NewMockWorkingDir() When(workingDir.Clone(Any[models.Repo](), Any[models.PullRequest](), Any[string]())).ThenReturn(tmp, false, nil) vcsClient := vcsmocks.NewMockClient() - When(vcsClient.GetModifiedFiles(Any[models.Repo](), Any[models.PullRequest]())).ThenReturn([]string{"modules/module/main.tf"}, nil) + When(vcsClient.GetModifiedFiles( + Any[logging.SimpleLogging](), Any[models.Repo](), Any[models.PullRequest]())).ThenReturn([]string{"modules/module/main.tf"}, nil) // Write and parse the global config file. globalCfgPath := filepath.Join(tmp, "global.yaml") @@ -1384,7 +1388,8 @@ projects: workingDir := NewMockWorkingDir() When(workingDir.Clone(Any[models.Repo](), Any[models.PullRequest](), Any[string]())).ThenReturn(tmp, false, nil) vcsClient := vcsmocks.NewMockClient() - When(vcsClient.GetModifiedFiles(Any[models.Repo](), Any[models.PullRequest]())).ThenReturn(c.modifiedFiles, nil) + When(vcsClient.GetModifiedFiles( + Any[logging.SimpleLogging](), Any[models.Repo](), Any[models.PullRequest]())).ThenReturn(c.modifiedFiles, nil) // Write and parse the global config file. globalCfgPath := filepath.Join(tmp, "global.yaml") diff --git a/server/events/project_command_builder_test.go b/server/events/project_command_builder_test.go index 1937f990f0..3bcc0294be 100644 --- a/server/events/project_command_builder_test.go +++ b/server/events/project_command_builder_test.go @@ -163,7 +163,8 @@ projects: workingDir := mocks.NewMockWorkingDir() When(workingDir.Clone(Any[models.Repo](), Any[models.PullRequest](), Any[string]())).ThenReturn(tmpDir, false, nil) vcsClient := vcsmocks.NewMockClient() - When(vcsClient.GetModifiedFiles(Any[models.Repo](), Any[models.PullRequest]())).ThenReturn([]string{"main.tf"}, nil) + When(vcsClient.GetModifiedFiles( + Any[logging.SimpleLogging](), Any[models.Repo](), Any[models.PullRequest]())).ThenReturn([]string{"main.tf"}, nil) if c.AtlantisYAML != "" { err := os.WriteFile(filepath.Join(tmpDir, valid.DefaultAtlantisFile), []byte(c.AtlantisYAML), 0600) Ok(t, err) @@ -513,7 +514,8 @@ projects: When(workingDir.Clone(Any[models.Repo](), Any[models.PullRequest](), Any[string]())).ThenReturn(tmpDir, false, nil) When(workingDir.GetWorkingDir(Any[models.Repo](), Any[models.PullRequest](), Any[string]())).ThenReturn(tmpDir, nil) vcsClient := vcsmocks.NewMockClient() - When(vcsClient.GetModifiedFiles(Any[models.Repo](), Any[models.PullRequest]())).ThenReturn([]string{"main.tf"}, nil) + When(vcsClient.GetModifiedFiles( + Any[logging.SimpleLogging](), Any[models.Repo](), Any[models.PullRequest]())).ThenReturn([]string{"main.tf"}, nil) if c.AtlantisYAML != "" { err := os.WriteFile(filepath.Join(tmpDir, valid.DefaultAtlantisFile), []byte(c.AtlantisYAML), 0600) Ok(t, err) @@ -701,7 +703,8 @@ projects: When(workingDir.Clone(Any[models.Repo](), Any[models.PullRequest](), Any[string]())).ThenReturn(tmpDir, false, nil) When(workingDir.GetWorkingDir(Any[models.Repo](), Any[models.PullRequest](), Any[string]())).ThenReturn(tmpDir, nil) vcsClient := vcsmocks.NewMockClient() - When(vcsClient.GetModifiedFiles(Any[models.Repo](), Any[models.PullRequest]())).ThenReturn(c.ModifiedFiles, nil) + When(vcsClient.GetModifiedFiles( + Any[logging.SimpleLogging](), Any[models.Repo](), Any[models.PullRequest]())).ThenReturn(c.ModifiedFiles, nil) if c.AtlantisYAML != "" { err := os.WriteFile(filepath.Join(tmpDir, valid.DefaultAtlantisFile), []byte(c.AtlantisYAML), 0600) Ok(t, err) @@ -1030,7 +1033,8 @@ projects: When(workingDir.Clone(Any[models.Repo](), Any[models.PullRequest](), Any[string]())).ThenReturn(tmpDir, false, nil) When(workingDir.GetWorkingDir(Any[models.Repo](), Any[models.PullRequest](), Any[string]())).ThenReturn(tmpDir, nil) vcsClient := vcsmocks.NewMockClient() - When(vcsClient.GetModifiedFiles(Any[models.Repo](), Any[models.PullRequest]())).ThenReturn(c.ModifiedFiles, nil) + When(vcsClient.GetModifiedFiles( + Any[logging.SimpleLogging](), Any[models.Repo](), Any[models.PullRequest]())).ThenReturn(c.ModifiedFiles, nil) if c.AtlantisYAML != "" { err := os.WriteFile(filepath.Join(tmpDir, valid.DefaultAtlantisFile), []byte(c.AtlantisYAML), 0600) Ok(t, err) @@ -1315,7 +1319,8 @@ func TestDefaultProjectCommandBuilder_EscapeArgs(t *testing.T) { When(workingDir.Clone(Any[models.Repo](), Any[models.PullRequest](), Any[string]())).ThenReturn(tmpDir, false, nil) When(workingDir.GetWorkingDir(Any[models.Repo](), Any[models.PullRequest](), Any[string]())).ThenReturn(tmpDir, nil) vcsClient := vcsmocks.NewMockClient() - When(vcsClient.GetModifiedFiles(Any[models.Repo](), Any[models.PullRequest]())).ThenReturn([]string{"main.tf"}, nil) + When(vcsClient.GetModifiedFiles( + Any[logging.SimpleLogging](), Any[models.Repo](), Any[models.PullRequest]())).ThenReturn([]string{"main.tf"}, nil) globalCfgArgs := valid.GlobalCfgArgs{ AllowAllRepoSettings: true, @@ -1465,7 +1470,8 @@ projects: tmpDir := DirStructure(t, testCase.DirStructure) vcsClient := vcsmocks.NewMockClient() - When(vcsClient.GetModifiedFiles(Any[models.Repo](), Any[models.PullRequest]())).ThenReturn(testCase.ModifiedFiles, nil) + When(vcsClient.GetModifiedFiles( + Any[logging.SimpleLogging](), Any[models.Repo](), Any[models.PullRequest]())).ThenReturn(testCase.ModifiedFiles, nil) workingDir := mocks.NewMockWorkingDir() When(workingDir.Clone( @@ -1589,9 +1595,11 @@ projects: for _, c := range cases { RegisterMockTestingT(t) vcsClient := vcsmocks.NewMockClient() - When(vcsClient.GetModifiedFiles(Any[models.Repo](), Any[models.PullRequest]())).ThenReturn(c.ModifiedFiles, nil) + When(vcsClient.GetModifiedFiles( + Any[logging.SimpleLogging](), Any[models.Repo](), Any[models.PullRequest]())).ThenReturn(c.ModifiedFiles, nil) When(vcsClient.SupportsSingleFileDownload(Any[models.Repo]())).ThenReturn(true) - When(vcsClient.GetFileContent(Any[models.PullRequest](), Any[string]())).ThenReturn(true, []byte(c.AtlantisYAML), nil) + When(vcsClient.GetFileContent( + Any[logging.SimpleLogging](), Any[models.PullRequest](), Any[string]())).ThenReturn(true, []byte(c.AtlantisYAML), nil) workingDir := mocks.NewMockWorkingDir() logger := logging.NewNoopLogger(t) @@ -1660,7 +1668,8 @@ func TestDefaultProjectCommandBuilder_WithPolicyCheckEnabled_BuildAutoplanComman workingDir := mocks.NewMockWorkingDir() When(workingDir.Clone(Any[models.Repo](), Any[models.PullRequest](), Any[string]())).ThenReturn(tmpDir, false, nil) vcsClient := vcsmocks.NewMockClient() - When(vcsClient.GetModifiedFiles(Any[models.Repo](), Any[models.PullRequest]())).ThenReturn([]string{"main.tf"}, nil) + When(vcsClient.GetModifiedFiles( + Any[logging.SimpleLogging](), Any[models.Repo](), Any[models.PullRequest]())).ThenReturn([]string{"main.tf"}, nil) globalCfgArgs := valid.GlobalCfgArgs{ AllowAllRepoSettings: false, @@ -1881,7 +1890,8 @@ func TestDefaultProjectCommandBuilder_BuildPlanCommands_Single_With_RestrictFile When(workingDir.GetWorkingDir(Any[models.Repo](), Any[models.PullRequest](), Any[string]())).ThenReturn(tmpDir, nil) When(workingDir.GetGitUntrackedFiles(Any[models.Repo](), Any[models.PullRequest](), Any[string]())).ThenReturn(c.UntrackedFiles, nil) vcsClient := vcsmocks.NewMockClient() - When(vcsClient.GetModifiedFiles(Any[models.Repo](), Any[models.PullRequest]())).ThenReturn(c.ModifiedFiles, nil) + When(vcsClient.GetModifiedFiles( + Any[logging.SimpleLogging](), Any[models.Repo](), Any[models.PullRequest]())).ThenReturn(c.ModifiedFiles, nil) if c.AtlantisYAML != "" { err := os.WriteFile(filepath.Join(tmpDir, valid.DefaultAtlantisFile), []byte(c.AtlantisYAML), 0600) Ok(t, err) @@ -1991,7 +2001,8 @@ func TestDefaultProjectCommandBuilder_BuildPlanCommands_with_IncludeGitUntracked When(workingDir.GetWorkingDir(Any[models.Repo](), Any[models.PullRequest](), Any[string]())).ThenReturn(tmpDir, nil) When(workingDir.GetGitUntrackedFiles(Any[models.Repo](), Any[models.PullRequest](), Any[string]())).ThenReturn(c.UntrackedFiles, nil) vcsClient := vcsmocks.NewMockClient() - When(vcsClient.GetModifiedFiles(Any[models.Repo](), Any[models.PullRequest]())).ThenReturn(c.ModifiedFiles, nil) + When(vcsClient.GetModifiedFiles( + Any[logging.SimpleLogging](), Any[models.Repo](), Any[models.PullRequest]())).ThenReturn(c.ModifiedFiles, nil) if c.AtlantisYAML != "" { err := os.WriteFile(filepath.Join(tmpDir, valid.DefaultAtlantisFile), []byte(c.AtlantisYAML), 0600) Ok(t, err) diff --git a/server/events/pull_closed_executor.go b/server/events/pull_closed_executor.go index de3e4e8009..64b929633b 100644 --- a/server/events/pull_closed_executor.go +++ b/server/events/pull_closed_executor.go @@ -30,19 +30,19 @@ import ( "github.com/runatlantis/atlantis/server/jobs" ) -//go:generate pegomock generate --package mocks -o mocks/mock_resource_cleaner.go ResourceCleaner +//go:generate pegomock generate github.com/runatlantis/atlantis/server/events --package mocks -o mocks/mock_resource_cleaner.go ResourceCleaner type ResourceCleaner interface { CleanUp(pullInfo jobs.PullInfo) } -//go:generate pegomock generate --package mocks -o mocks/mock_pull_cleaner.go PullCleaner +//go:generate pegomock generate github.com/runatlantis/atlantis/server/events --package mocks -o mocks/mock_pull_cleaner.go PullCleaner // PullCleaner cleans up pull requests after they're closed/merged. type PullCleaner interface { // CleanUpPull deletes the workspaces used by the pull request on disk // and deletes any locks associated with this pull request for all workspaces. - CleanUpPull(repo models.Repo, pull models.PullRequest) error + CleanUpPull(logger logging.SimpleLogging, repo models.Repo, pull models.PullRequest) error } // PullClosedExecutor executes the tasks required to clean up a closed pull @@ -78,7 +78,7 @@ func (t *PullClosedEventTemplate) Execute(wr io.Writer, data interface{}) error } // CleanUpPull cleans up after a closed pull request. -func (p *PullClosedExecutor) CleanUpPull(repo models.Repo, pull models.PullRequest) error { +func (p *PullClosedExecutor) CleanUpPull(logger logging.SimpleLogging, repo models.Repo, pull models.PullRequest) error { pullStatus, err := p.Backend.GetPullStatus(pull) if err != nil { // Log and continue to clean up other resources. @@ -124,7 +124,7 @@ func (p *PullClosedExecutor) CleanUpPull(repo models.Repo, pull models.PullReque if err = pullClosedTemplate.Execute(&buf, templateData); err != nil { return errors.Wrap(err, "rendering template for comment") } - return p.VCSClient.CreateComment(repo, pull.Num, buf.String(), "") + return p.VCSClient.CreateComment(logger, repo, pull.Num, buf.String(), "") } // buildTemplateData formats the lock data into a slice that can easily be diff --git a/server/events/pull_closed_executor_test.go b/server/events/pull_closed_executor_test.go index 2992f4f820..1236060d39 100644 --- a/server/events/pull_closed_executor_test.go +++ b/server/events/pull_closed_executor_test.go @@ -39,6 +39,7 @@ import ( func TestCleanUpPullWorkspaceErr(t *testing.T) { t.Log("when workspace.Delete returns an error, we return it") RegisterMockTestingT(t) + logger := logging.NewNoopLogger(t) w := mocks.NewMockWorkingDir() tmp := t.TempDir() db, err := db.New(tmp) @@ -50,13 +51,14 @@ func TestCleanUpPullWorkspaceErr(t *testing.T) { } err = errors.New("err") When(w.Delete(testdata.GithubRepo, testdata.Pull)).ThenReturn(err) - actualErr := pce.CleanUpPull(testdata.GithubRepo, testdata.Pull) + actualErr := pce.CleanUpPull(logger, testdata.GithubRepo, testdata.Pull) Equals(t, "cleaning workspace: err", actualErr.Error()) } func TestCleanUpPullUnlockErr(t *testing.T) { t.Log("when locker.UnlockByPull returns an error, we return it") RegisterMockTestingT(t) + logger := logging.NewNoopLogger(t) w := mocks.NewMockWorkingDir() l := lockmocks.NewMockLocker() tmp := t.TempDir() @@ -70,11 +72,12 @@ func TestCleanUpPullUnlockErr(t *testing.T) { } err = errors.New("err") When(l.UnlockByPull(testdata.GithubRepo.FullName, testdata.Pull.Num)).ThenReturn(nil, err) - actualErr := pce.CleanUpPull(testdata.GithubRepo, testdata.Pull) + actualErr := pce.CleanUpPull(logger, testdata.GithubRepo, testdata.Pull) Equals(t, "cleaning up locks: err", actualErr.Error()) } func TestCleanUpPullNoLocks(t *testing.T) { + logger := logging.NewNoopLogger(t) t.Log("when there are no locks to clean up, we don't comment") RegisterMockTestingT(t) w := mocks.NewMockWorkingDir() @@ -90,12 +93,13 @@ func TestCleanUpPullNoLocks(t *testing.T) { Backend: db, } When(l.UnlockByPull(testdata.GithubRepo.FullName, testdata.Pull.Num)).ThenReturn(nil, nil) - err = pce.CleanUpPull(testdata.GithubRepo, testdata.Pull) + err = pce.CleanUpPull(logger, testdata.GithubRepo, testdata.Pull) Ok(t, err) - cp.VerifyWasCalled(Never()).CreateComment(Any[models.Repo](), Any[int](), Any[string](), Any[string]()) + cp.VerifyWasCalled(Never()).CreateComment(Any[logging.SimpleLogging](), Any[models.Repo](), Any[int](), Any[string](), Any[string]()) } func TestCleanUpPullComments(t *testing.T) { + logger := logging.NewNoopLogger(t) t.Log("should comment correctly") RegisterMockTestingT(t) cases := []struct { @@ -187,9 +191,10 @@ func TestCleanUpPullComments(t *testing.T) { } t.Log("testing: " + c.Description) When(l.UnlockByPull(testdata.GithubRepo.FullName, testdata.Pull.Num)).ThenReturn(c.Locks, nil) - err = pce.CleanUpPull(testdata.GithubRepo, testdata.Pull) + err = pce.CleanUpPull(logger, testdata.GithubRepo, testdata.Pull) Ok(t, err) - _, _, comment, _ := cp.VerifyWasCalledOnce().CreateComment(Any[models.Repo](), Any[int](), Any[string](), Any[string]()).GetCapturedArguments() + _, _, _, comment, _ := cp.VerifyWasCalledOnce().CreateComment( + Any[logging.SimpleLogging](), Any[models.Repo](), Any[int](), Any[string](), Any[string]()).GetCapturedArguments() expected := "Locks and plans deleted for the projects and workspaces modified in this pull request:\n\n" + c.Exp Equals(t, expected, comment) @@ -278,11 +283,12 @@ func TestCleanUpLogStreaming(t *testing.T) { When(locker.UnlockByPull(testdata.GithubRepo.FullName, testdata.Pull.Num)).ThenReturn(locks, nil) // Clean up. - err = pullClosedExecutor.CleanUpPull(testdata.GithubRepo, testdata.Pull) + err = pullClosedExecutor.CleanUpPull(logger, testdata.GithubRepo, testdata.Pull) Ok(t, err) close(prjCmdOutput) - _, _, comment, _ := client.VerifyWasCalledOnce().CreateComment(Any[models.Repo](), Any[int](), Any[string](), Any[string]()).GetCapturedArguments() + _, _, _, comment, _ := client.VerifyWasCalledOnce().CreateComment( + Any[logging.SimpleLogging](), Any[models.Repo](), Any[int](), Any[string](), Any[string]()).GetCapturedArguments() expectedComment := "Locks and plans deleted for the projects and workspaces modified in this pull request:\n\n" + "- dir: `.` workspace: `default`" Equals(t, expectedComment, comment) diff --git a/server/events/pull_updater.go b/server/events/pull_updater.go index d8fcfe34f9..d640e5a374 100644 --- a/server/events/pull_updater.go +++ b/server/events/pull_updater.go @@ -24,13 +24,13 @@ func (c *PullUpdater) updatePull(ctx *command.Context, cmd PullCommand, res comm // comment trail may be useful in auditing or backtracing problems. if c.HidePrevPlanComments { ctx.Log.Debug("Hiding previous plan comments for command: '%v', directory: '%v'", cmd.CommandName().TitleString(), cmd.Dir()) - if err := c.VCSClient.HidePrevCommandComments(ctx.Pull.BaseRepo, ctx.Pull.Num, cmd.CommandName().TitleString(), cmd.Dir()); err != nil { + if err := c.VCSClient.HidePrevCommandComments(ctx.Log, ctx.Pull.BaseRepo, ctx.Pull.Num, cmd.CommandName().TitleString(), cmd.Dir()); err != nil { ctx.Log.Err("unable to hide old comments: %s", err) } } comment := c.MarkdownRenderer.Render(res, cmd.CommandName(), cmd.SubCommandName(), ctx.Log.GetHistory(), cmd.IsVerbose(), ctx.Pull.BaseRepo.VCSHost.Type) - if err := c.VCSClient.CreateComment(ctx.Pull.BaseRepo, ctx.Pull.Num, comment, cmd.CommandName().String()); err != nil { + if err := c.VCSClient.CreateComment(ctx.Log, ctx.Pull.BaseRepo, ctx.Pull.Num, comment, cmd.CommandName().String()); err != nil { ctx.Log.Err("unable to comment: %s", err) } } diff --git a/server/events/unlock_command_runner.go b/server/events/unlock_command_runner.go index dd2b4c45ef..470fe26118 100644 --- a/server/events/unlock_command_runner.go +++ b/server/events/unlock_command_runner.go @@ -42,7 +42,7 @@ func (u *UnlockCommandRunner) Run(ctx *command.Context, _ *CommentCommand) { var err error if disableUnlockLabel != "" { var labels []string - labels, err = u.vcsClient.GetPullLabels(baseRepo, ctx.Pull) + labels, err = u.vcsClient.GetPullLabels(ctx.Log, baseRepo, ctx.Pull) if err != nil { vcsMessage = "Failed to retrieve PR labels... Not unlocking" ctx.Log.Err("Failed to retrieve PR labels for pull %s", err.Error()) @@ -71,7 +71,7 @@ func (u *UnlockCommandRunner) Run(ctx *command.Context, _ *CommentCommand) { } } - if commentErr := u.vcsClient.CreateComment(baseRepo, pullNum, vcsMessage, command.Unlock.String()); commentErr != nil { + if commentErr := u.vcsClient.CreateComment(ctx.Log, baseRepo, pullNum, vcsMessage, command.Unlock.String()); commentErr != nil { ctx.Log.Err("unable to comment: %s", commentErr) } } diff --git a/server/events/vcs/azuredevops_client.go b/server/events/vcs/azuredevops_client.go index c89d490005..03bc1963c0 100644 --- a/server/events/vcs/azuredevops_client.go +++ b/server/events/vcs/azuredevops_client.go @@ -13,6 +13,7 @@ import ( "github.com/pkg/errors" "github.com/runatlantis/atlantis/server/events/models" "github.com/runatlantis/atlantis/server/events/vcs/common" + "github.com/runatlantis/atlantis/server/logging" ) // AzureDevopsClient represents an Azure DevOps VCS client @@ -55,7 +56,7 @@ func NewAzureDevopsClient(hostname string, userName string, token string) (*Azur // GetModifiedFiles returns the names of files that were modified in the merge request // relative to the repo root, e.g. parent/child/file.txt. -func (g *AzureDevopsClient) GetModifiedFiles(repo models.Repo, pull models.PullRequest) ([]string, error) { +func (g *AzureDevopsClient) GetModifiedFiles(logger logging.SimpleLogging, repo models.Repo, pull models.PullRequest) ([]string, error) { var files []string owner, project, repoName := SplitAzureDevopsRepoFullName(repo.FullName) @@ -95,7 +96,7 @@ func (g *AzureDevopsClient) GetModifiedFiles(repo models.Repo, pull models.PullR // // If comment length is greater than the max comment length we split into // multiple comments. -func (g *AzureDevopsClient) CreateComment(repo models.Repo, pullNum int, comment string, command string) error { //nolint: revive +func (g *AzureDevopsClient) CreateComment(logger logging.SimpleLogging, repo models.Repo, pullNum int, comment string, command string) error { //nolint: revive sepEnd := "\n```\n" + "\n
\n\n**Warning**: Output length greater than max comment size. Continued in next comment." sepStart := "Continued from previous comment.\n
Show Output\n\n" + @@ -130,17 +131,17 @@ func (g *AzureDevopsClient) CreateComment(repo models.Repo, pullNum int, comment return nil } -func (g *AzureDevopsClient) ReactToComment(repo models.Repo, pullNum int, commentID int64, reaction string) error { //nolint: revive +func (g *AzureDevopsClient) ReactToComment(logger logging.SimpleLogging, repo models.Repo, pullNum int, commentID int64, reaction string) error { //nolint: revive return nil } -func (g *AzureDevopsClient) HidePrevCommandComments(repo models.Repo, pullNum int, command string, dir string) error { //nolint: revive +func (g *AzureDevopsClient) HidePrevCommandComments(logger logging.SimpleLogging, repo models.Repo, pullNum int, command string, dir string) error { //nolint: revive return nil } // PullIsApproved returns true if the merge request was approved by another reviewer. // https://docs.microsoft.com/en-us/azure/devops/repos/git/branch-policies?view=azure-devops#require-a-minimum-number-of-reviewers -func (g *AzureDevopsClient) PullIsApproved(repo models.Repo, pull models.PullRequest) (approvalStatus models.ApprovalStatus, err error) { +func (g *AzureDevopsClient) PullIsApproved(logger logging.SimpleLogging, repo models.Repo, pull models.PullRequest) (approvalStatus models.ApprovalStatus, err error) { owner, project, repoName := SplitAzureDevopsRepoFullName(repo.FullName) opts := azuredevops.PullRequestGetOptions{ @@ -176,7 +177,7 @@ func (g *AzureDevopsClient) DiscardReviews(repo models.Repo, pull models.PullReq } // PullIsMergeable returns true if the merge request can be merged. -func (g *AzureDevopsClient) PullIsMergeable(repo models.Repo, pull models.PullRequest, vcsstatusname string) (bool, error) { //nolint: revive +func (g *AzureDevopsClient) PullIsMergeable(logger logging.SimpleLogging, repo models.Repo, pull models.PullRequest, vcsstatusname string) (bool, error) { //nolint: revive owner, project, repoName := SplitAzureDevopsRepoFullName(repo.FullName) opts := azuredevops.PullRequestGetOptions{IncludeWorkItemRefs: true} @@ -227,7 +228,7 @@ func (g *AzureDevopsClient) PullIsMergeable(repo models.Repo, pull models.PullRe } // GetPullRequest returns the pull request. -func (g *AzureDevopsClient) GetPullRequest(repo models.Repo, num int) (*azuredevops.GitPullRequest, error) { +func (g *AzureDevopsClient) GetPullRequest(logger logging.SimpleLogging, repo models.Repo, num int) (*azuredevops.GitPullRequest, error) { opts := azuredevops.PullRequestGetOptions{ IncludeWorkItemRefs: true, } @@ -237,7 +238,7 @@ func (g *AzureDevopsClient) GetPullRequest(repo models.Repo, num int) (*azuredev } // UpdateStatus updates the build status of a commit. -func (g *AzureDevopsClient) UpdateStatus(repo models.Repo, pull models.PullRequest, state models.CommitStatus, src string, description string, url string) error { +func (g *AzureDevopsClient) UpdateStatus(logger logging.SimpleLogging, repo models.Repo, pull models.PullRequest, state models.CommitStatus, src string, description string, url string) error { adState := azuredevops.GitError.String() switch state { case models.PendingCommitStatus: @@ -303,7 +304,7 @@ func (g *AzureDevopsClient) UpdateStatus(repo models.Repo, pull models.PullReque // If the user has set a branch policy that disallows no fast-forward, the merge will fail // until we handle branch policies // https://docs.microsoft.com/en-us/azure/devops/repos/git/branch-policies?view=azure-devops -func (g *AzureDevopsClient) MergePull(pull models.PullRequest, pullOptions models.PullRequestOptions) error { +func (g *AzureDevopsClient) MergePull(logger logging.SimpleLogging, pull models.PullRequest, pullOptions models.PullRequestOptions) error { owner, project, repoName := SplitAzureDevopsRepoFullName(pull.BaseRepo.FullName) descriptor := "Atlantis Terraform Pull Request Automation" @@ -398,7 +399,7 @@ func (g *AzureDevopsClient) SupportsSingleFileDownload(repo models.Repo) bool { return false } -func (g *AzureDevopsClient) GetFileContent(pull models.PullRequest, fileName string) (bool, []byte, error) { //nolint: revive +func (g *AzureDevopsClient) GetFileContent(_ logging.SimpleLogging, pull models.PullRequest, fileName string) (bool, []byte, error) { //nolint: revive return false, []byte{}, fmt.Errorf("not implemented") } @@ -421,10 +422,10 @@ func GitStatusContextFromSrc(src string) *azuredevops.GitStatusContext { } } -func (g *AzureDevopsClient) GetCloneURL(VCSHostType models.VCSHostType, repo string) (string, error) { //nolint: revive +func (g *AzureDevopsClient) GetCloneURL(_ logging.SimpleLogging, VCSHostType models.VCSHostType, repo string) (string, error) { //nolint: revive return "", fmt.Errorf("not yet implemented") } -func (g *AzureDevopsClient) GetPullLabels(_ models.Repo, _ models.PullRequest) ([]string, error) { +func (g *AzureDevopsClient) GetPullLabels(_ logging.SimpleLogging, _ models.Repo, _ models.PullRequest) ([]string, error) { return nil, fmt.Errorf("not yet implemented") } diff --git a/server/events/vcs/azuredevops_client_test.go b/server/events/vcs/azuredevops_client_test.go index 1c6e142298..1e428023b8 100644 --- a/server/events/vcs/azuredevops_client_test.go +++ b/server/events/vcs/azuredevops_client_test.go @@ -15,10 +15,12 @@ import ( "github.com/runatlantis/atlantis/server/events/models" "github.com/runatlantis/atlantis/server/events/vcs" "github.com/runatlantis/atlantis/server/events/vcs/testdata" + "github.com/runatlantis/atlantis/server/logging" . "github.com/runatlantis/atlantis/testing" ) func TestAzureDevopsClient_MergePull(t *testing.T) { + logger := logging.NewNoopLogger(t) cases := []struct { description string response string @@ -121,16 +123,18 @@ func TestAzureDevopsClient_MergePull(t *testing.T) { } fmt.Printf("Successfully merged pull request: %+v\n", merge) - err = client.MergePull(models.PullRequest{ - Num: 22, - BaseRepo: models.Repo{ - FullName: "owner/project/repo", - Owner: "owner", - Name: "repo", - }, - }, models.PullRequestOptions{ - DeleteSourceBranchOnMerge: false, - }) + err = client.MergePull( + logger, + models.PullRequest{ + Num: 22, + BaseRepo: models.Repo{ + FullName: "owner/project/repo", + Owner: "owner", + Name: "repo", + }, + }, models.PullRequestOptions{ + DeleteSourceBranchOnMerge: false, + }) if c.expErr == "" { Ok(t, err) } else { @@ -142,6 +146,7 @@ func TestAzureDevopsClient_MergePull(t *testing.T) { } func TestAzureDevopsClient_UpdateStatus(t *testing.T) { + logger := logging.NewNoopLogger(t) cases := []struct { status models.CommitStatus expState string @@ -223,11 +228,14 @@ func TestAzureDevopsClient_UpdateStatus(t *testing.T) { Owner: "owner", Name: "repo", } - err = client.UpdateStatus(repo, models.PullRequest{ - Num: 22, - BaseRepo: repo, - HeadCommit: "sha", - }, c.status, "src", "description", "https://google.com") + err = client.UpdateStatus( + logger, + repo, + models.PullRequest{ + Num: 22, + BaseRepo: repo, + HeadCommit: "sha", + }, c.status, "src", "description", "https://google.com") Ok(t, err) Assert(t, gotRequest, "expected to get the request") }) @@ -237,6 +245,7 @@ func TestAzureDevopsClient_UpdateStatus(t *testing.T) { // GetModifiedFiles should make multiple requests if more than one page // and concat results. func TestAzureDevopsClient_GetModifiedFiles(t *testing.T) { + logger := logging.NewNoopLogger(t) itemRespTemplate := `{ "changes": [ { @@ -281,24 +290,27 @@ func TestAzureDevopsClient_GetModifiedFiles(t *testing.T) { Ok(t, err) defer disableSSLVerification()() - files, err := client.GetModifiedFiles(models.Repo{ - FullName: "owner/project/repo", - Owner: "owner", - Name: "repo", - CloneURL: "", - SanitizedCloneURL: "", - VCSHost: models.VCSHost{ - Type: models.AzureDevops, - Hostname: "dev.azure.com", - }, - }, models.PullRequest{ - Num: 1, - }) + files, err := client.GetModifiedFiles( + logger, + models.Repo{ + FullName: "owner/project/repo", + Owner: "owner", + Name: "repo", + CloneURL: "", + SanitizedCloneURL: "", + VCSHost: models.VCSHost{ + Type: models.AzureDevops, + Hostname: "dev.azure.com", + }, + }, models.PullRequest{ + Num: 1, + }) Ok(t, err) Equals(t, []string{"file1.txt", "file2.txt"}, files) } func TestAzureDevopsClient_PullIsMergeable(t *testing.T) { + logger := logging.NewNoopLogger(t) type Policy struct { genre string name string @@ -402,19 +414,21 @@ func TestAzureDevopsClient_PullIsMergeable(t *testing.T) { defer disableSSLVerification()() - actMergeable, err := client.PullIsMergeable(models.Repo{ - FullName: "owner/project/repo", - Owner: "owner", - Name: "repo", - CloneURL: "", - SanitizedCloneURL: "", - VCSHost: models.VCSHost{ - Type: models.AzureDevops, - Hostname: "dev.azure.com", - }, - }, models.PullRequest{ - Num: 1, - }, "atlantis-test") + actMergeable, err := client.PullIsMergeable( + logger, + models.Repo{ + FullName: "owner/project/repo", + Owner: "owner", + Name: "repo", + CloneURL: "", + SanitizedCloneURL: "", + VCSHost: models.VCSHost{ + Type: models.AzureDevops, + Hostname: "dev.azure.com", + }, + }, models.PullRequest{ + Num: 1, + }, "atlantis-test") Ok(t, err) Equals(t, c.expMergeable, actMergeable) }) @@ -422,6 +436,7 @@ func TestAzureDevopsClient_PullIsMergeable(t *testing.T) { } func TestAzureDevopsClient_PullIsApproved(t *testing.T) { + logger := logging.NewNoopLogger(t) cases := []struct { testName string reviewerUniqueName string @@ -496,19 +511,21 @@ func TestAzureDevopsClient_PullIsApproved(t *testing.T) { defer disableSSLVerification()() - approvalStatus, err := client.PullIsApproved(models.Repo{ - FullName: "owner/project/repo", - Owner: "owner", - Name: "repo", - CloneURL: "", - SanitizedCloneURL: "", - VCSHost: models.VCSHost{ - Type: models.AzureDevops, - Hostname: "dev.azure.com", - }, - }, models.PullRequest{ - Num: 1, - }) + approvalStatus, err := client.PullIsApproved( + logger, + models.Repo{ + FullName: "owner/project/repo", + Owner: "owner", + Name: "repo", + CloneURL: "", + SanitizedCloneURL: "", + VCSHost: models.VCSHost{ + Type: models.AzureDevops, + Hostname: "dev.azure.com", + }, + }, models.PullRequest{ + Num: 1, + }) Ok(t, err) Equals(t, c.expApproved, approvalStatus.IsApproved) }) @@ -516,6 +533,7 @@ func TestAzureDevopsClient_PullIsApproved(t *testing.T) { } func TestAzureDevopsClient_GetPullRequest(t *testing.T) { + logger := logging.NewNoopLogger(t) // Use a real Azure DevOps json response and edit the mergeable_state field. jsBytes, err := os.ReadFile("testdata/azuredevops-pr.json") Ok(t, err) @@ -540,17 +558,19 @@ func TestAzureDevopsClient_GetPullRequest(t *testing.T) { Ok(t, err) defer disableSSLVerification()() - _, err = client.GetPullRequest(models.Repo{ - FullName: "owner/project/repo", - Owner: "owner", - Name: "repo", - CloneURL: "", - SanitizedCloneURL: "", - VCSHost: models.VCSHost{ - Type: models.AzureDevops, - Hostname: "dev.azure.com", - }, - }, 1) + _, err = client.GetPullRequest( + logger, + models.Repo{ + FullName: "owner/project/repo", + Owner: "owner", + Name: "repo", + CloneURL: "", + SanitizedCloneURL: "", + VCSHost: models.VCSHost{ + Type: models.AzureDevops, + Hostname: "dev.azure.com", + }, + }, 1) Ok(t, err) }) } diff --git a/server/events/vcs/bitbucketcloud/client.go b/server/events/vcs/bitbucketcloud/client.go index a9b38b4d09..a0dcfd7161 100644 --- a/server/events/vcs/bitbucketcloud/client.go +++ b/server/events/vcs/bitbucketcloud/client.go @@ -11,6 +11,7 @@ import ( validator "github.com/go-playground/validator/v10" "github.com/pkg/errors" "github.com/runatlantis/atlantis/server/events/models" + "github.com/runatlantis/atlantis/server/logging" ) type Client struct { @@ -40,7 +41,7 @@ func NewClient(httpClient *http.Client, username string, password string, atlant // GetModifiedFiles returns the names of files that were modified in the merge request // relative to the repo root, e.g. parent/child/file.txt. -func (b *Client) GetModifiedFiles(repo models.Repo, pull models.PullRequest) ([]string, error) { +func (b *Client) GetModifiedFiles(logger logging.SimpleLogging, repo models.Repo, pull models.PullRequest) ([]string, error) { var files []string nextPageURL := fmt.Sprintf("%s/2.0/repositories/%s/pullrequests/%d/diffstat", b.BaseURL, repo.FullName, pull.Num) @@ -85,7 +86,7 @@ func (b *Client) GetModifiedFiles(repo models.Repo, pull models.PullRequest) ([] } // CreateComment creates a comment on the merge request. -func (b *Client) CreateComment(repo models.Repo, pullNum int, comment string, _ string) error { +func (b *Client) CreateComment(logger logging.SimpleLogging, repo models.Repo, pullNum int, comment string, _ string) error { // NOTE: I tried to find the maximum size of a comment for bitbucket.org but // I got up to 200k chars without issue so for now I'm not going to bother // to detect this. @@ -101,17 +102,17 @@ func (b *Client) CreateComment(repo models.Repo, pullNum int, comment string, _ } // UpdateComment updates the body of a comment on the merge request. -func (b *Client) ReactToComment(_ models.Repo, _ int, _ int64, _ string) error { +func (b *Client) ReactToComment(_ logging.SimpleLogging, _ models.Repo, _ int, _ int64, _ string) error { // TODO: Bitbucket support for reactions return nil } -func (b *Client) HidePrevCommandComments(_ models.Repo, _ int, _ string, _ string) error { +func (b *Client) HidePrevCommandComments(_ logging.SimpleLogging, _ models.Repo, _ int, _ string, _ string) error { return nil } // PullIsApproved returns true if the merge request was approved. -func (b *Client) PullIsApproved(repo models.Repo, pull models.PullRequest) (approvalStatus models.ApprovalStatus, err error) { +func (b *Client) PullIsApproved(logger logging.SimpleLogging, repo models.Repo, pull models.PullRequest) (approvalStatus models.ApprovalStatus, err error) { path := fmt.Sprintf("%s/2.0/repositories/%s/pullrequests/%d", b.BaseURL, repo.FullName, pull.Num) resp, err := b.makeRequest("GET", path, nil) if err != nil { @@ -138,7 +139,7 @@ func (b *Client) PullIsApproved(repo models.Repo, pull models.PullRequest) (appr } // PullIsMergeable returns true if the merge request has no conflicts and can be merged. -func (b *Client) PullIsMergeable(repo models.Repo, pull models.PullRequest, _ string) (bool, error) { +func (b *Client) PullIsMergeable(logger logging.SimpleLogging, repo models.Repo, pull models.PullRequest, _ string) (bool, error) { nextPageURL := fmt.Sprintf("%s/2.0/repositories/%s/pullrequests/%d/diffstat", b.BaseURL, repo.FullName, pull.Num) // We'll only loop 1000 times as a safety measure. maxLoops := 1000 @@ -169,7 +170,7 @@ func (b *Client) PullIsMergeable(repo models.Repo, pull models.PullRequest, _ st } // UpdateStatus updates the status of a commit. -func (b *Client) UpdateStatus(repo models.Repo, pull models.PullRequest, status models.CommitStatus, src string, description string, url string) error { +func (b *Client) UpdateStatus(logger logging.SimpleLogging, repo models.Repo, pull models.PullRequest, status models.CommitStatus, src string, description string, url string) error { bbState := "FAILED" switch status { case models.PendingCommitStatus: @@ -207,7 +208,7 @@ func (b *Client) UpdateStatus(repo models.Repo, pull models.PullRequest, status } // MergePull merges the pull request. -func (b *Client) MergePull(pull models.PullRequest, _ models.PullRequestOptions) error { +func (b *Client) MergePull(logger logging.SimpleLogging, pull models.PullRequest, _ models.PullRequestOptions) error { path := fmt.Sprintf("%s/2.0/repositories/%s/pullrequests/%d/merge", b.BaseURL, pull.BaseRepo.FullName, pull.Num) _, err := b.makeRequest("POST", path, nil) return err @@ -274,14 +275,14 @@ func (b *Client) SupportsSingleFileDownload(models.Repo) bool { // GetFileContent a repository file content from VCS (which support fetch a single file from repository) // The first return value indicates whether the repo contains a file or not // if BaseRepo had a file, its content will placed on the second return value -func (b *Client) GetFileContent(_ models.PullRequest, _ string) (bool, []byte, error) { +func (b *Client) GetFileContent(_ logging.SimpleLogging, _ models.PullRequest, _ string) (bool, []byte, error) { return false, []byte{}, fmt.Errorf("not implemented") } -func (b *Client) GetCloneURL(_ models.VCSHostType, _ string) (string, error) { +func (b *Client) GetCloneURL(_ logging.SimpleLogging, _ models.VCSHostType, _ string) (string, error) { return "", fmt.Errorf("not yet implemented") } -func (b *Client) GetPullLabels(_ models.Repo, _ models.PullRequest) ([]string, error) { +func (b *Client) GetPullLabels(_ logging.SimpleLogging, _ models.Repo, _ models.PullRequest) ([]string, error) { return nil, fmt.Errorf("not yet implemented") } diff --git a/server/events/vcs/bitbucketcloud/client_test.go b/server/events/vcs/bitbucketcloud/client_test.go index a193dc4743..e7def22b66 100644 --- a/server/events/vcs/bitbucketcloud/client_test.go +++ b/server/events/vcs/bitbucketcloud/client_test.go @@ -10,11 +10,13 @@ import ( "github.com/runatlantis/atlantis/server/events/models" "github.com/runatlantis/atlantis/server/events/vcs/bitbucketcloud" + "github.com/runatlantis/atlantis/server/logging" . "github.com/runatlantis/atlantis/testing" ) // Should follow pagination properly. func TestClient_GetModifiedFilesPagination(t *testing.T) { + logger := logging.NewNoopLogger(t) respTemplate := ` { "pagelen": 1, @@ -73,25 +75,28 @@ func TestClient_GetModifiedFilesPagination(t *testing.T) { client := bitbucketcloud.NewClient(http.DefaultClient, "user", "pass", "runatlantis.io") client.BaseURL = testServer.URL - files, err := client.GetModifiedFiles(models.Repo{ - FullName: "owner/repo", - Owner: "owner", - Name: "repo", - CloneURL: "", - SanitizedCloneURL: "", - VCSHost: models.VCSHost{ - Type: models.BitbucketCloud, - Hostname: "bitbucket.org", - }, - }, models.PullRequest{ - Num: 1, - }) + files, err := client.GetModifiedFiles( + logger, + models.Repo{ + FullName: "owner/repo", + Owner: "owner", + Name: "repo", + CloneURL: "", + SanitizedCloneURL: "", + VCSHost: models.VCSHost{ + Type: models.BitbucketCloud, + Hostname: "bitbucket.org", + }, + }, models.PullRequest{ + Num: 1, + }) Ok(t, err) Equals(t, []string{"file1.txt", "file2.txt", "file3.txt"}, files) } // If the "old" key in the list of files is nil we shouldn't error. func TestClient_GetModifiedFilesOldNil(t *testing.T) { + logger := logging.NewNoopLogger(t) resp := ` { "pagelen": 500, @@ -134,24 +139,27 @@ func TestClient_GetModifiedFilesOldNil(t *testing.T) { client := bitbucketcloud.NewClient(http.DefaultClient, "user", "pass", "runatlantis.io") client.BaseURL = testServer.URL - files, err := client.GetModifiedFiles(models.Repo{ - FullName: "owner/repo", - Owner: "owner", - Name: "repo", - CloneURL: "", - SanitizedCloneURL: "", - VCSHost: models.VCSHost{ - Type: models.BitbucketCloud, - Hostname: "bitbucket.org", - }, - }, models.PullRequest{ - Num: 1, - }) + files, err := client.GetModifiedFiles( + logger, + models.Repo{ + FullName: "owner/repo", + Owner: "owner", + Name: "repo", + CloneURL: "", + SanitizedCloneURL: "", + VCSHost: models.VCSHost{ + Type: models.BitbucketCloud, + Hostname: "bitbucket.org", + }, + }, models.PullRequest{ + Num: 1, + }) Ok(t, err) Equals(t, []string{"parent/child/file1.txt"}, files) } func TestClient_PullIsApproved(t *testing.T) { + logger := logging.NewNoopLogger(t) cases := []struct { description string testdata string @@ -202,12 +210,14 @@ func TestClient_PullIsApproved(t *testing.T) { repo, err := models.NewRepo(models.BitbucketServer, "owner/repo", "https://bitbucket.org/owner/repo.git", "user", "token") Ok(t, err) - approvalStatus, err := client.PullIsApproved(repo, models.PullRequest{ - Num: 1, - HeadBranch: "branch", - Author: "author", - BaseRepo: repo, - }) + approvalStatus, err := client.PullIsApproved( + logger, + repo, models.PullRequest{ + Num: 1, + HeadBranch: "branch", + Author: "author", + BaseRepo: repo, + }) Ok(t, err) Equals(t, c.exp, approvalStatus.IsApproved) }) @@ -215,6 +225,7 @@ func TestClient_PullIsApproved(t *testing.T) { } func TestClient_PullIsMergeable(t *testing.T) { + logger := logging.NewNoopLogger(t) cases := map[string]struct { DiffStat string ExpMergeable bool @@ -325,19 +336,21 @@ func TestClient_PullIsMergeable(t *testing.T) { client := bitbucketcloud.NewClient(http.DefaultClient, "user", "pass", "runatlantis.io") client.BaseURL = testServer.URL - actMergeable, err := client.PullIsMergeable(models.Repo{ - FullName: "owner/repo", - Owner: "owner", - Name: "repo", - CloneURL: "", - SanitizedCloneURL: "", - VCSHost: models.VCSHost{ - Type: models.BitbucketCloud, - Hostname: "bitbucket.org", - }, - }, models.PullRequest{ - Num: 1, - }, "atlantis-test") + actMergeable, err := client.PullIsMergeable( + logger, + models.Repo{ + FullName: "owner/repo", + Owner: "owner", + Name: "repo", + CloneURL: "", + SanitizedCloneURL: "", + VCSHost: models.VCSHost{ + Type: models.BitbucketCloud, + Hostname: "bitbucket.org", + }, + }, models.PullRequest{ + Num: 1, + }, "atlantis-test") Ok(t, err) Equals(t, c.ExpMergeable, actMergeable) }) diff --git a/server/events/vcs/bitbucketserver/client.go b/server/events/vcs/bitbucketserver/client.go index b6c75f3197..0c741faaa6 100644 --- a/server/events/vcs/bitbucketserver/client.go +++ b/server/events/vcs/bitbucketserver/client.go @@ -11,6 +11,7 @@ import ( "strings" "github.com/runatlantis/atlantis/server/events/vcs/common" + "github.com/runatlantis/atlantis/server/logging" validator "github.com/go-playground/validator/v10" "github.com/pkg/errors" @@ -64,7 +65,7 @@ func NewClient(httpClient *http.Client, username string, password string, baseUR // GetModifiedFiles returns the names of files that were modified in the merge request // relative to the repo root, e.g. parent/child/file.txt. -func (b *Client) GetModifiedFiles(repo models.Repo, pull models.PullRequest) ([]string, error) { +func (b *Client) GetModifiedFiles(logger logging.SimpleLogging, repo models.Repo, pull models.PullRequest) ([]string, error) { var files []string projectKey, err := b.GetProjectKey(repo.Name, repo.SanitizedCloneURL) @@ -133,7 +134,7 @@ func (b *Client) GetProjectKey(repoName string, cloneURL string) (string, error) // CreateComment creates a comment on the merge request. It will write multiple // comments if a single comment is too long. -func (b *Client) CreateComment(repo models.Repo, pullNum int, comment string, _ string) error { +func (b *Client) CreateComment(logger logging.SimpleLogging, repo models.Repo, pullNum int, comment string, _ string) error { sepEnd := "\n```\n**Warning**: Output length greater than max comment size. Continued in next comment." sepStart := "Continued from previous comment.\n```diff\n" comments := common.SplitComment(comment, maxCommentLength, sepEnd, sepStart) @@ -145,11 +146,11 @@ func (b *Client) CreateComment(repo models.Repo, pullNum int, comment string, _ return nil } -func (b *Client) ReactToComment(_ models.Repo, _ int, _ int64, _ string) error { +func (b *Client) ReactToComment(_ logging.SimpleLogging, _ models.Repo, _ int, _ int64, _ string) error { return nil } -func (b *Client) HidePrevCommandComments(_ models.Repo, _ int, _ string, _ string) error { +func (b *Client) HidePrevCommandComments(_ logging.SimpleLogging, _ models.Repo, _ int, _ string, _ string) error { return nil } @@ -169,7 +170,7 @@ func (b *Client) postComment(repo models.Repo, pullNum int, comment string) erro } // PullIsApproved returns true if the merge request was approved. -func (b *Client) PullIsApproved(repo models.Repo, pull models.PullRequest) (approvalStatus models.ApprovalStatus, err error) { +func (b *Client) PullIsApproved(logger logging.SimpleLogging, repo models.Repo, pull models.PullRequest) (approvalStatus models.ApprovalStatus, err error) { projectKey, err := b.GetProjectKey(repo.Name, repo.SanitizedCloneURL) if err != nil { return approvalStatus, err @@ -202,7 +203,7 @@ func (b *Client) DiscardReviews(_ models.Repo, _ models.PullRequest) error { } // PullIsMergeable returns true if the merge request has no conflicts and can be merged. -func (b *Client) PullIsMergeable(repo models.Repo, pull models.PullRequest, _ string) (bool, error) { +func (b *Client) PullIsMergeable(logger logging.SimpleLogging, repo models.Repo, pull models.PullRequest, _ string) (bool, error) { projectKey, err := b.GetProjectKey(repo.Name, repo.SanitizedCloneURL) if err != nil { return false, err @@ -226,7 +227,7 @@ func (b *Client) PullIsMergeable(repo models.Repo, pull models.PullRequest, _ st } // UpdateStatus updates the status of a commit. -func (b *Client) UpdateStatus(_ models.Repo, pull models.PullRequest, status models.CommitStatus, src string, description string, url string) error { +func (b *Client) UpdateStatus(logger logging.SimpleLogging, _ models.Repo, pull models.PullRequest, status models.CommitStatus, src string, description string, url string) error { bbState := "FAILED" switch status { case models.PendingCommitStatus: @@ -259,7 +260,7 @@ func (b *Client) UpdateStatus(_ models.Repo, pull models.PullRequest, status mod } // MergePull merges the pull request. -func (b *Client) MergePull(pull models.PullRequest, pullOptions models.PullRequestOptions) error { +func (b *Client) MergePull(logger logging.SimpleLogging, pull models.PullRequest, pullOptions models.PullRequestOptions) error { projectKey, err := b.GetProjectKey(pull.BaseRepo.Name, pull.BaseRepo.SanitizedCloneURL) if err != nil { return err @@ -358,14 +359,14 @@ func (b *Client) SupportsSingleFileDownload(_ models.Repo) bool { // GetFileContent a repository file content from VCS (which support fetch a single file from repository) // The first return value indicates whether the repo contains a file or not // if BaseRepo had a file, its content will placed on the second return value -func (b *Client) GetFileContent(_ models.PullRequest, _ string) (bool, []byte, error) { +func (b *Client) GetFileContent(_ logging.SimpleLogging, _ models.PullRequest, _ string) (bool, []byte, error) { return false, []byte{}, fmt.Errorf("not implemented") } -func (b *Client) GetCloneURL(_ models.VCSHostType, _ string) (string, error) { +func (b *Client) GetCloneURL(_ logging.SimpleLogging, _ models.VCSHostType, _ string) (string, error) { return "", fmt.Errorf("not yet implemented") } -func (b *Client) GetPullLabels(_ models.Repo, _ models.PullRequest) ([]string, error) { +func (b *Client) GetPullLabels(_ logging.SimpleLogging, _ models.Repo, _ models.PullRequest) ([]string, error) { return nil, fmt.Errorf("not yet implemented") } diff --git a/server/events/vcs/bitbucketserver/client_test.go b/server/events/vcs/bitbucketserver/client_test.go index 73aa8b0962..4827b76ed1 100644 --- a/server/events/vcs/bitbucketserver/client_test.go +++ b/server/events/vcs/bitbucketserver/client_test.go @@ -13,6 +13,7 @@ import ( "github.com/runatlantis/atlantis/server/events/models" "github.com/runatlantis/atlantis/server/events/vcs/bitbucketserver" + "github.com/runatlantis/atlantis/server/logging" . "github.com/runatlantis/atlantis/testing" ) @@ -72,6 +73,7 @@ func TestClient_BasePath(t *testing.T) { // Should follow pagination properly. func TestClient_GetModifiedFilesPagination(t *testing.T) { + logger := logging.NewNoopLogger(t) respTemplate := ` { "values": [ @@ -120,18 +122,20 @@ func TestClient_GetModifiedFilesPagination(t *testing.T) { client, err := bitbucketserver.NewClient(http.DefaultClient, "user", "pass", serverURL, "runatlantis.io") Ok(t, err) - files, err := client.GetModifiedFiles(models.Repo{ - FullName: "owner/repo", - Owner: "owner", - Name: "repo", - SanitizedCloneURL: fmt.Sprintf("%s/scm/ow/repo.git", serverURL), - VCSHost: models.VCSHost{ - Type: models.BitbucketCloud, - Hostname: "bitbucket.org", - }, - }, models.PullRequest{ - Num: 1, - }) + files, err := client.GetModifiedFiles( + logger, + models.Repo{ + FullName: "owner/repo", + Owner: "owner", + Name: "repo", + SanitizedCloneURL: fmt.Sprintf("%s/scm/ow/repo.git", serverURL), + VCSHost: models.VCSHost{ + Type: models.BitbucketCloud, + Hostname: "bitbucket.org", + }, + }, models.PullRequest{ + Num: 1, + }) Ok(t, err) Equals(t, []string{"file1.txt", "file2.txt", "file3.txt"}, files) } @@ -139,6 +143,7 @@ func TestClient_GetModifiedFilesPagination(t *testing.T) { // Test that we use the correct version parameter in our call to merge the pull // request. func TestClient_MergePull(t *testing.T) { + logger := logging.NewNoopLogger(t) pullRequest, err := os.ReadFile(filepath.Join("testdata", "pull-request.json")) Ok(t, err) testServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { @@ -161,33 +166,36 @@ func TestClient_MergePull(t *testing.T) { client, err := bitbucketserver.NewClient(http.DefaultClient, "user", "pass", testServer.URL, "runatlantis.io") Ok(t, err) - err = client.MergePull(models.PullRequest{ - Num: 1, - HeadCommit: "", - URL: "", - HeadBranch: "", - BaseBranch: "", - Author: "", - State: 0, - BaseRepo: models.Repo{ - FullName: "owner/repo", - Owner: "owner", - Name: "repo", - SanitizedCloneURL: fmt.Sprintf("%s/scm/ow/repo.git", testServer.URL), - VCSHost: models.VCSHost{ - Type: models.BitbucketCloud, - Hostname: "bitbucket.org", + err = client.MergePull( + logger, + models.PullRequest{ + Num: 1, + HeadCommit: "", + URL: "", + HeadBranch: "", + BaseBranch: "", + Author: "", + State: 0, + BaseRepo: models.Repo{ + FullName: "owner/repo", + Owner: "owner", + Name: "repo", + SanitizedCloneURL: fmt.Sprintf("%s/scm/ow/repo.git", testServer.URL), + VCSHost: models.VCSHost{ + Type: models.BitbucketCloud, + Hostname: "bitbucket.org", + }, }, - }, - }, models.PullRequestOptions{ - DeleteSourceBranchOnMerge: false, - }) + }, models.PullRequestOptions{ + DeleteSourceBranchOnMerge: false, + }) Ok(t, err) } // Test that we delete the source branch in our call to merge the pull // request. func TestClient_MergePullDeleteSourceBranch(t *testing.T) { + logger := logging.NewNoopLogger(t) pullRequest, err := os.ReadFile(filepath.Join("testdata", "pull-request.json")) Ok(t, err) testServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { @@ -220,27 +228,31 @@ func TestClient_MergePullDeleteSourceBranch(t *testing.T) { client, err := bitbucketserver.NewClient(http.DefaultClient, "user", "pass", testServer.URL, "runatlantis.io") Ok(t, err) - err = client.MergePull(models.PullRequest{ - Num: 1, - HeadCommit: "", - URL: "", - HeadBranch: "foo", - BaseBranch: "", - Author: "", - State: 0, - BaseRepo: models.Repo{ - FullName: "owner/repo", - Owner: "owner", - Name: "repo", - SanitizedCloneURL: fmt.Sprintf("%s/scm/ow/repo.git", testServer.URL), - VCSHost: models.VCSHost{ - Type: models.BitbucketServer, - Hostname: "bitbucket.org", + err = client.MergePull( + logger, + models.PullRequest{ + Num: 1, + HeadCommit: "", + URL: "", + HeadBranch: "foo", + BaseBranch: "", + Author: "", + State: 0, + BaseRepo: models.Repo{ + FullName: "owner/repo", + Owner: "owner", + Name: "repo", + SanitizedCloneURL: fmt.Sprintf("%s/scm/ow/repo.git", testServer.URL), + VCSHost: models.VCSHost{ + Type: models.BitbucketServer, + Hostname: "bitbucket.org", + }, }, }, - }, models.PullRequestOptions{ - DeleteSourceBranchOnMerge: true, - }) + models.PullRequestOptions{ + DeleteSourceBranchOnMerge: true, + }, + ) Ok(t, err) } diff --git a/server/events/vcs/client.go b/server/events/vcs/client.go index 9bcf972f6a..b6ad7cb9cd 100644 --- a/server/events/vcs/client.go +++ b/server/events/vcs/client.go @@ -15,6 +15,7 @@ package vcs import ( "github.com/runatlantis/atlantis/server/events/models" + "github.com/runatlantis/atlantis/server/logging" ) //go:generate pegomock generate --package mocks -o mocks/mock_client.go github.com/runatlantis/atlantis/server/events/vcs Client @@ -23,13 +24,13 @@ import ( type Client interface { // GetModifiedFiles returns the names of files that were modified in the merge request // relative to the repo root, e.g. parent/child/file.txt. - GetModifiedFiles(repo models.Repo, pull models.PullRequest) ([]string, error) - CreateComment(repo models.Repo, pullNum int, comment string, command string) error + GetModifiedFiles(logger logging.SimpleLogging, repo models.Repo, pull models.PullRequest) ([]string, error) + CreateComment(logger logging.SimpleLogging, repo models.Repo, pullNum int, comment string, command string) error - ReactToComment(repo models.Repo, pullNum int, commentID int64, reaction string) error - HidePrevCommandComments(repo models.Repo, pullNum int, command string, dir string) error - PullIsApproved(repo models.Repo, pull models.PullRequest) (models.ApprovalStatus, error) - PullIsMergeable(repo models.Repo, pull models.PullRequest, vcsstatusname string) (bool, error) + ReactToComment(logger logging.SimpleLogging, repo models.Repo, pullNum int, commentID int64, reaction string) error + HidePrevCommandComments(logger logging.SimpleLogging, repo models.Repo, pullNum int, command string, dir string) error + PullIsApproved(logger logging.SimpleLogging, repo models.Repo, pull models.PullRequest) (models.ApprovalStatus, error) + PullIsMergeable(logger logging.SimpleLogging, repo models.Repo, pull models.PullRequest, vcsstatusname string) (bool, error) // UpdateStatus updates the commit status to state for pull. src is the // source of this status. This should be relatively static across runs, // ex. atlantis/plan or atlantis/apply. @@ -37,19 +38,19 @@ type Client interface { // change across runs. // url is an optional link that users should click on for more information // about this status. - UpdateStatus(repo models.Repo, pull models.PullRequest, state models.CommitStatus, src string, description string, url string) error + UpdateStatus(logger logging.SimpleLogging, repo models.Repo, pull models.PullRequest, state models.CommitStatus, src string, description string, url string) error DiscardReviews(repo models.Repo, pull models.PullRequest) error - MergePull(pull models.PullRequest, pullOptions models.PullRequestOptions) error + MergePull(logger logging.SimpleLogging, pull models.PullRequest, pullOptions models.PullRequestOptions) error MarkdownPullLink(pull models.PullRequest) (string, error) GetTeamNamesForUser(repo models.Repo, user models.User) ([]string, error) // GetFileContent a repository file content from VCS (which support fetch a single file from repository) // The first return value indicates whether the repo contains a file or not // if BaseRepo had a file, its content will placed on the second return value - GetFileContent(pull models.PullRequest, fileName string) (bool, []byte, error) + GetFileContent(logger logging.SimpleLogging, pull models.PullRequest, fileName string) (bool, []byte, error) SupportsSingleFileDownload(repo models.Repo) bool - GetCloneURL(VCSHostType models.VCSHostType, repo string) (string, error) + GetCloneURL(logger logging.SimpleLogging, VCSHostType models.VCSHostType, repo string) (string, error) // GetPullLabels returns the labels of a pull request - GetPullLabels(repo models.Repo, pull models.PullRequest) ([]string, error) + GetPullLabels(logger logging.SimpleLogging, repo models.Repo, pull models.PullRequest) ([]string, error) } diff --git a/server/events/vcs/gh_app_creds_rotator_test.go b/server/events/vcs/gh_app_creds_rotator_test.go index e0d2e28bf4..fd0536f206 100644 --- a/server/events/vcs/gh_app_creds_rotator_test.go +++ b/server/events/vcs/gh_app_creds_rotator_test.go @@ -14,6 +14,7 @@ import ( ) func Test_githubAppTokenRotator_GenerateJob(t *testing.T) { + logger := logging.NewNoopLogger(t) defer disableSSLVerification()() testServer, err := testdata.GithubAppTestServer(t) Ok(t, err) @@ -21,7 +22,7 @@ func Test_githubAppTokenRotator_GenerateJob(t *testing.T) { anonCreds := &vcs.GithubAnonymousCredentials{} anonClient, err := vcs.NewGithubClient(testServer, anonCreds, vcs.GithubConfig{}, logging.NewNoopLogger(t)) Ok(t, err) - tempSecrets, err := anonClient.ExchangeCode("good-code") + tempSecrets, err := anonClient.ExchangeCode(logger, "good-code") Ok(t, err) type fields struct { githubCredentials vcs.GithubCredentials diff --git a/server/events/vcs/github_client.go b/server/events/vcs/github_client.go index 12c5500cfa..f098398095 100644 --- a/server/events/vcs/github_client.go +++ b/server/events/vcs/github_client.go @@ -45,7 +45,6 @@ type GithubClient struct { client *github.Client v4Client *githubv4.Client ctx context.Context - logger logging.SimpleLogging config GithubConfig } @@ -77,7 +76,8 @@ type GithubPRReviewSummary struct { } // NewGithubClient returns a valid GitHub client. -func NewGithubClient(hostname string, credentials GithubCredentials, config GithubConfig, logger logging.SimpleLogging) (*GithubClient, error) { +func NewGithubClient(hostname string, credentials GithubCredentials, config GithubConfig, logger logging.SimpleLogging) (*GithubClient, error) { //nolint:staticcheck + logger.Debug("Creating new GitHub client for host: %s", hostname) transport, err := credentials.Client() if err != nil { return nil, errors.Wrap(err, "error initializing github authentication transport") @@ -111,14 +111,14 @@ func NewGithubClient(hostname string, credentials GithubCredentials, config Gith client: client, v4Client: v4Client, ctx: context.Background(), - logger: logger, config: config, }, nil } // GetModifiedFiles returns the names of files that were modified in the pull request // relative to the repo root, e.g. parent/child/file.txt. -func (g *GithubClient) GetModifiedFiles(repo models.Repo, pull models.PullRequest) ([]string, error) { +func (g *GithubClient) GetModifiedFiles(logger logging.SimpleLogging, repo models.Repo, pull models.PullRequest) ([]string, error) { + logger.Debug("Getting modified files for GitHub pull request %d", pull.Num) var files []string nextPage := 0 @@ -142,7 +142,7 @@ listloop: pageFiles, resp, err := g.client.PullRequests.ListFiles(g.ctx, repo.Owner, repo.Name, pull.Num, &opts) if resp != nil { - g.logger.Debug("[attempt %d] GET /repos/%v/%v/pulls/%d/files returned: %v", i+1, repo.Owner, repo.Name, pull.Num, resp.StatusCode) + logger.Debug("[attempt %d] GET /repos/%v/%v/pulls/%d/files returned: %v", i+1, repo.Owner, repo.Name, pull.Num, resp.StatusCode) } if err != nil { ghErr, ok := err.(*github.ErrorResponse) @@ -175,7 +175,8 @@ listloop: // CreateComment creates a comment on the pull request. // If comment length is greater than the max comment length we split into // multiple comments. -func (g *GithubClient) CreateComment(repo models.Repo, pullNum int, comment string, command string) error { +func (g *GithubClient) CreateComment(logger logging.SimpleLogging, repo models.Repo, pullNum int, comment string, command string) error { + logger.Debug("Creating comment on GitHub pull request %d", pullNum) var sepStart string sepEnd := "\n```\n
" + @@ -193,7 +194,7 @@ func (g *GithubClient) CreateComment(repo models.Repo, pullNum int, comment stri for i := range comments { _, resp, err := g.client.Issues.CreateComment(g.ctx, repo.Owner, repo.Name, pullNum, &github.IssueComment{Body: &comments[i]}) if resp != nil { - g.logger.Debug("POST /repos/%v/%v/issues/%d/comments returned: %v", repo.Owner, repo.Name, pullNum, resp.StatusCode) + logger.Debug("POST /repos/%v/%v/issues/%d/comments returned: %v", repo.Owner, repo.Name, pullNum, resp.StatusCode) } if err != nil { return err @@ -203,15 +204,17 @@ func (g *GithubClient) CreateComment(repo models.Repo, pullNum int, comment stri } // ReactToComment adds a reaction to a comment. -func (g *GithubClient) ReactToComment(repo models.Repo, _ int, commentID int64, reaction string) error { +func (g *GithubClient) ReactToComment(logger logging.SimpleLogging, repo models.Repo, _ int, commentID int64, reaction string) error { + logger.Debug("Adding reaction to GitHub pull request comment %d", commentID) _, resp, err := g.client.Reactions.CreateIssueCommentReaction(g.ctx, repo.Owner, repo.Name, commentID, reaction) if resp != nil { - g.logger.Debug("POST /repos/%v/%v/issues/comments/%d/reactions returned: %v", repo.Owner, repo.Name, commentID, resp.StatusCode) + logger.Debug("POST /repos/%v/%v/issues/comments/%d/reactions returned: %v", repo.Owner, repo.Name, commentID, resp.StatusCode) } return err } -func (g *GithubClient) HidePrevCommandComments(repo models.Repo, pullNum int, command string, dir string) error { +func (g *GithubClient) HidePrevCommandComments(logger logging.SimpleLogging, repo models.Repo, pullNum int, command string, dir string) error { + logger.Debug("Hiding previous command comments on GitHub pull request %d", pullNum) var allComments []*github.IssueComment nextPage := 0 for { @@ -221,7 +224,7 @@ func (g *GithubClient) HidePrevCommandComments(repo models.Repo, pullNum int, co ListOptions: github.ListOptions{Page: nextPage}, }) if resp != nil { - g.logger.Debug("GET /repos/%v/%v/issues/%d/comments returned: %v", repo.Owner, repo.Name, pullNum, resp.StatusCode) + logger.Debug("GET /repos/%v/%v/issues/%d/comments returned: %v", repo.Owner, repo.Name, pullNum, resp.StatusCode) } if err != nil { return errors.Wrap(err, "listing comments") @@ -271,7 +274,7 @@ func (g *GithubClient) HidePrevCommandComments(repo models.Repo, pullNum int, co Classifier: githubv4.ReportedContentClassifiersOutdated, SubjectID: comment.GetNodeID(), } - g.logger.Debug("Hiding comment %s", comment.GetNodeID()) + logger.Debug("Hiding comment %s", comment.GetNodeID()) if err := g.v4Client.Mutate(g.ctx, &m, input, nil); err != nil { return errors.Wrapf(err, "minimize comment %s", comment.GetNodeID()) } @@ -333,7 +336,8 @@ func (g *GithubClient) getPRReviews(repo models.Repo, pull models.PullRequest) ( } // PullIsApproved returns true if the pull request was approved. -func (g *GithubClient) PullIsApproved(repo models.Repo, pull models.PullRequest) (approvalStatus models.ApprovalStatus, err error) { +func (g *GithubClient) PullIsApproved(logger logging.SimpleLogging, repo models.Repo, pull models.PullRequest) (approvalStatus models.ApprovalStatus, err error) { + logger.Debug("Checking if GitHub pull request %d is approved", pull.Num) nextPage := 0 for { opts := github.ListOptions{ @@ -344,7 +348,7 @@ func (g *GithubClient) PullIsApproved(repo models.Repo, pull models.PullRequest) } pageReviews, resp, err := g.client.PullRequests.ListReviews(g.ctx, repo.Owner, repo.Name, pull.Num, &opts) if resp != nil { - g.logger.Debug("GET /repos/%v/%v/pulls/%d/reviews returned: %v", repo.Owner, repo.Name, pull.Num, resp.StatusCode) + logger.Debug("GET /repos/%v/%v/pulls/%d/reviews returned: %v", repo.Owner, repo.Name, pull.Num, resp.StatusCode) } if err != nil { return approvalStatus, errors.Wrap(err, "getting reviews") @@ -412,11 +416,12 @@ func isRequiredCheck(check string, required []string) bool { } // GetCombinedStatusMinusApply checks Statuses for PR, excluding atlantis apply. Returns true if all other statuses are not in failure. -func (g *GithubClient) GetCombinedStatusMinusApply(repo models.Repo, pull *github.PullRequest, vcstatusname string) (bool, error) { +func (g *GithubClient) GetCombinedStatusMinusApply(logger logging.SimpleLogging, repo models.Repo, pull *github.PullRequest, vcstatusname string) (bool, error) { + logger.Debug("Checking if GitHub pull request %d has successful status checks", pull.GetNumber()) //check combined status api status, resp, err := g.client.Repositories.GetCombinedStatus(g.ctx, *pull.Head.Repo.Owner.Login, repo.Name, *pull.Head.Ref, nil) if resp != nil { - g.logger.Debug("GET /repos/%v/%v/commits/%s/status returned: %v", *pull.Head.Repo.Owner.Login, repo.Name, *pull.Head.Ref, resp.StatusCode) + logger.Debug("GET /repos/%v/%v/commits/%s/status returned: %v", *pull.Head.Repo.Owner.Login, repo.Name, *pull.Head.Ref, resp.StatusCode) } if err != nil { return false, errors.Wrap(err, "getting combined status") @@ -435,7 +440,7 @@ func (g *GithubClient) GetCombinedStatusMinusApply(repo models.Repo, pull *githu //get required status checks required, resp, err := g.client.Repositories.GetBranchProtection(context.Background(), repo.Owner, repo.Name, *pull.Base.Ref) if resp != nil { - g.logger.Debug("GET /repos/%v/%v/branches/%s/protection returned: %v", repo.Owner, repo.Name, *pull.Base.Ref, resp.StatusCode) + logger.Debug("GET /repos/%v/%v/branches/%s/protection returned: %v", repo.Owner, repo.Name, *pull.Base.Ref, resp.StatusCode) } if err != nil { return false, errors.Wrap(err, "getting required status checks") @@ -448,7 +453,7 @@ func (g *GithubClient) GetCombinedStatusMinusApply(repo models.Repo, pull *githu //check check suite/check run api checksuites, resp, err := g.client.Checks.ListCheckSuitesForRef(context.Background(), *pull.Head.Repo.Owner.Login, repo.Name, *pull.Head.Ref, nil) if resp != nil { - g.logger.Debug("GET /repos/%v/%v/commits/%s/check-suites returned: %v", *pull.Head.Repo.Owner.Login, repo.Name, *pull.Head.Ref, resp.StatusCode) + logger.Debug("GET /repos/%v/%v/commits/%s/check-suites returned: %v", *pull.Head.Repo.Owner.Login, repo.Name, *pull.Head.Ref, resp.StatusCode) } if err != nil { return false, errors.Wrap(err, "getting check suites for ref") @@ -460,7 +465,7 @@ func (g *GithubClient) GetCombinedStatusMinusApply(repo models.Repo, pull *githu //iterate over the runs inside the suite suite, resp, err := g.client.Checks.ListCheckRunsCheckSuite(context.Background(), *pull.Head.Repo.Owner.Login, repo.Name, *c.ID, nil) if resp != nil { - g.logger.Debug("GET /repos/%v/%v/check-suites/%d/check-runs returned: %v", *pull.Head.Repo.Owner.Login, repo.Name, *c.ID, resp.StatusCode) + logger.Debug("GET /repos/%v/%v/check-suites/%d/check-runs returned: %v", *pull.Head.Repo.Owner.Login, repo.Name, *c.ID, resp.StatusCode) } if err != nil { return false, errors.Wrap(err, "getting check runs for check suite") @@ -512,8 +517,9 @@ func (g *GithubClient) GetPullReviewDecision(repo models.Repo, pull models.PullR } // PullIsMergeable returns true if the pull request is mergeable. -func (g *GithubClient) PullIsMergeable(repo models.Repo, pull models.PullRequest, vcsstatusname string) (bool, error) { - githubPR, err := g.GetPullRequest(repo, pull.Num) +func (g *GithubClient) PullIsMergeable(logger logging.SimpleLogging, repo models.Repo, pull models.PullRequest, vcsstatusname string) (bool, error) { + logger.Debug("Checking if GitHub pull request %d is mergeable", pull.Num) + githubPR, err := g.GetPullRequest(logger, repo, pull.Num) if err != nil { return false, errors.Wrap(err, "getting pull request") } @@ -531,10 +537,10 @@ func (g *GithubClient) PullIsMergeable(repo models.Repo, pull models.PullRequest if state != "clean" && state != "unstable" && state != "has_hooks" { //mergeable bypass apply code hidden by feature flag if g.config.AllowMergeableBypassApply { - g.logger.Debug("AllowMergeableBypassApply feature flag is enabled - attempting to bypass apply from mergeable requirements") + logger.Debug("AllowMergeableBypassApply feature flag is enabled - attempting to bypass apply from mergeable requirements") if state == "blocked" { //check status excluding atlantis apply - status, err := g.GetCombinedStatusMinusApply(repo, githubPR, vcsstatusname) + status, err := g.GetCombinedStatusMinusApply(logger, repo, githubPR, vcsstatusname) if err != nil { return false, errors.Wrap(err, "getting pull request status") } @@ -558,7 +564,8 @@ func (g *GithubClient) PullIsMergeable(repo models.Repo, pull models.PullRequest } // GetPullRequest returns the pull request. -func (g *GithubClient) GetPullRequest(repo models.Repo, num int) (*github.PullRequest, error) { +func (g *GithubClient) GetPullRequest(logger logging.SimpleLogging, repo models.Repo, num int) (*github.PullRequest, error) { + logger.Debug("Getting GitHub pull request %d", num) var err error var pull *github.PullRequest @@ -574,7 +581,7 @@ func (g *GithubClient) GetPullRequest(repo models.Repo, num int) (*github.PullRe pull, resp, err := g.client.PullRequests.Get(g.ctx, repo.Owner, repo.Name, num) if resp != nil { - g.logger.Debug("GET /repos/%v/%v/pulls/%d returned: %v", repo.Owner, repo.Name, num, resp.StatusCode) + logger.Debug("GET /repos/%v/%v/pulls/%d returned: %v", repo.Owner, repo.Name, num, resp.StatusCode) } if err == nil { return pull, nil @@ -589,7 +596,7 @@ func (g *GithubClient) GetPullRequest(repo models.Repo, num int) (*github.PullRe // UpdateStatus updates the status badge on the pull request. // See https://github.com/blog/1227-commit-status-api. -func (g *GithubClient) UpdateStatus(repo models.Repo, pull models.PullRequest, state models.CommitStatus, src string, description string, url string) error { +func (g *GithubClient) UpdateStatus(logger logging.SimpleLogging, repo models.Repo, pull models.PullRequest, state models.CommitStatus, src string, description string, url string) error { ghState := "error" switch state { case models.PendingCommitStatus: @@ -599,6 +606,7 @@ func (g *GithubClient) UpdateStatus(repo models.Repo, pull models.PullRequest, s case models.FailedCommitStatus: ghState = "failure" } + logger.Debug("Updating status on GitHub pull request %d for '%s' to '%s'", pull.Num, description, ghState) status := &github.RepoStatus{ State: github.String(ghState), @@ -608,18 +616,19 @@ func (g *GithubClient) UpdateStatus(repo models.Repo, pull models.PullRequest, s } _, resp, err := g.client.Repositories.CreateStatus(g.ctx, repo.Owner, repo.Name, pull.HeadCommit, status) if resp != nil { - g.logger.Debug("POST /repos/%v/%v/statuses/%s returned: %v", repo.Owner, repo.Name, pull.HeadCommit, resp.StatusCode) + logger.Debug("POST /repos/%v/%v/statuses/%s returned: %v", repo.Owner, repo.Name, pull.HeadCommit, resp.StatusCode) } return err } // MergePull merges the pull request. -func (g *GithubClient) MergePull(pull models.PullRequest, _ models.PullRequestOptions) error { +func (g *GithubClient) MergePull(logger logging.SimpleLogging, pull models.PullRequest, _ models.PullRequestOptions) error { + logger.Debug("Merging GitHub pull request %d", pull.Num) // Users can set their repo to disallow certain types of merging. // We detect which types aren't allowed and use the type that is. repo, resp, err := g.client.Repositories.Get(g.ctx, pull.BaseRepo.Owner, pull.BaseRepo.Name) if resp != nil { - g.logger.Debug("GET /repos/%v/%v returned: %v", pull.BaseRepo.Owner, pull.BaseRepo.Name, resp.StatusCode) + logger.Debug("GET /repos/%v/%v returned: %v", pull.BaseRepo.Owner, pull.BaseRepo.Name, resp.StatusCode) } if err != nil { return errors.Wrap(err, "fetching repo info") @@ -642,7 +651,7 @@ func (g *GithubClient) MergePull(pull models.PullRequest, _ models.PullRequestOp options := &github.PullRequestOptions{ MergeMethod: method, } - g.logger.Debug("PUT /repos/%v/%v/pulls/%d/merge", repo.Owner, repo.Name, pull.Num) + logger.Debug("PUT /repos/%v/%v/pulls/%d/merge", repo.Owner, repo.Name, pull.Num) mergeResult, resp, err := g.client.PullRequests.Merge( g.ctx, pull.BaseRepo.Owner, @@ -653,7 +662,7 @@ func (g *GithubClient) MergePull(pull models.PullRequest, _ models.PullRequestOp "", options) if resp != nil { - g.logger.Debug("POST /repos/%v/%v/pulls/%d/merge returned: %v", repo.Owner, repo.Name, pull.Num, resp.StatusCode) + logger.Debug("POST /repos/%v/%v/pulls/%d/merge returned: %v", repo.Owner, repo.Name, pull.Num, resp.StatusCode) } if err != nil { return errors.Wrap(err, "merging pull request") @@ -713,11 +722,12 @@ func (g *GithubClient) GetTeamNamesForUser(repo models.Repo, user models.User) ( } // ExchangeCode returns a newly created app's info -func (g *GithubClient) ExchangeCode(code string) (*GithubAppTemporarySecrets, error) { +func (g *GithubClient) ExchangeCode(logger logging.SimpleLogging, code string) (*GithubAppTemporarySecrets, error) { + logger.Debug("Exchanging code for app secrets") ctx := context.Background() cfg, resp, err := g.client.Apps.CompleteAppManifest(ctx, code) if resp != nil { - g.logger.Debug("POST /app-manifests/%s/conversions returned: %v", code, resp.StatusCode) + logger.Debug("POST /app-manifests/%s/conversions returned: %v", code, resp.StatusCode) } data := &GithubAppTemporarySecrets{ ID: cfg.GetID(), @@ -733,11 +743,12 @@ func (g *GithubClient) ExchangeCode(code string) (*GithubAppTemporarySecrets, er // GetFileContent a repository file content from VCS (which support fetch a single file from repository) // The first return value indicates whether the repo contains a file or not // if BaseRepo had a file, its content will placed on the second return value -func (g *GithubClient) GetFileContent(pull models.PullRequest, fileName string) (bool, []byte, error) { +func (g *GithubClient) GetFileContent(logger logging.SimpleLogging, pull models.PullRequest, fileName string) (bool, []byte, error) { + logger.Debug("Getting file content for %s in GitHub pull request %d", fileName, pull.Num) opt := github.RepositoryContentGetOptions{Ref: pull.HeadBranch} fileContent, _, resp, err := g.client.Repositories.GetContents(g.ctx, pull.BaseRepo.Owner, pull.BaseRepo.Name, fileName, &opt) if resp != nil { - g.logger.Debug("GET /repos/%v/%v/contents/%s returned: %v", pull.BaseRepo.Owner, pull.BaseRepo.Name, fileName, resp.StatusCode) + logger.Debug("GET /repos/%v/%v/contents/%s returned: %v", pull.BaseRepo.Owner, pull.BaseRepo.Name, fileName, resp.StatusCode) } if resp.StatusCode == http.StatusNotFound { @@ -759,11 +770,12 @@ func (g *GithubClient) SupportsSingleFileDownload(_ models.Repo) bool { return true } -func (g *GithubClient) GetCloneURL(_ models.VCSHostType, repo string) (string, error) { +func (g *GithubClient) GetCloneURL(logger logging.SimpleLogging, _ models.VCSHostType, repo string) (string, error) { + logger.Debug("Getting clone URL for %s", repo) parts := strings.Split(repo, "/") repository, resp, err := g.client.Repositories.Get(g.ctx, parts[0], parts[1]) if resp != nil { - g.logger.Debug("GET /repos/%v/%v returned: %v", parts[0], parts[1], resp.StatusCode) + logger.Debug("GET /repos/%v/%v returned: %v", parts[0], parts[1], resp.StatusCode) } if err != nil { return "", err @@ -771,10 +783,11 @@ func (g *GithubClient) GetCloneURL(_ models.VCSHostType, repo string) (string, e return repository.GetCloneURL(), nil } -func (g *GithubClient) GetPullLabels(repo models.Repo, pull models.PullRequest) ([]string, error) { +func (g *GithubClient) GetPullLabels(logger logging.SimpleLogging, repo models.Repo, pull models.PullRequest) ([]string, error) { + logger.Debug("Getting labels for GitHub pull request %d", pull.Num) pullDetails, resp, err := g.client.PullRequests.Get(g.ctx, repo.Owner, repo.Name, pull.Num) if resp != nil { - g.logger.Debug("GET /repos/%v/%v/pulls/%d returned: %v", repo.Owner, repo.Name, pull.Num, resp.StatusCode) + logger.Debug("GET /repos/%v/%v/pulls/%d returned: %v", repo.Owner, repo.Name, pull.Num, resp.StatusCode) } if err != nil { return nil, err diff --git a/server/events/vcs/github_client_test.go b/server/events/vcs/github_client_test.go index acb7d07b10..e4cad22359 100644 --- a/server/events/vcs/github_client_test.go +++ b/server/events/vcs/github_client_test.go @@ -67,19 +67,21 @@ func TestGithubClient_GetModifiedFiles(t *testing.T) { Ok(t, err) defer disableSSLVerification()() - files, err := client.GetModifiedFiles(models.Repo{ - FullName: "owner/repo", - Owner: "owner", - Name: "repo", - CloneURL: "", - SanitizedCloneURL: "", - VCSHost: models.VCSHost{ - Type: models.Github, - Hostname: "github.com", - }, - }, models.PullRequest{ - Num: 1, - }) + files, err := client.GetModifiedFiles( + logger, + models.Repo{ + FullName: "owner/repo", + Owner: "owner", + Name: "repo", + CloneURL: "", + SanitizedCloneURL: "", + VCSHost: models.VCSHost{ + Type: models.Github, + Hostname: "github.com", + }, + }, models.PullRequest{ + Num: 1, + }) Ok(t, err) Equals(t, []string{"file1.txt", "file2.txt"}, files) } @@ -87,6 +89,7 @@ func TestGithubClient_GetModifiedFiles(t *testing.T) { // GetModifiedFiles should include the source and destination of a moved // file. func TestGithubClient_GetModifiedFilesMovedFile(t *testing.T) { + logger := logging.NewNoopLogger(t) resp := `[ { "sha": "bbcd538c8e72b8c175046e27cc8f907076331401", @@ -122,24 +125,27 @@ func TestGithubClient_GetModifiedFilesMovedFile(t *testing.T) { Ok(t, err) defer disableSSLVerification()() - files, err := client.GetModifiedFiles(models.Repo{ - FullName: "owner/repo", - Owner: "owner", - Name: "repo", - CloneURL: "", - SanitizedCloneURL: "", - VCSHost: models.VCSHost{ - Type: models.Github, - Hostname: "github.com", - }, - }, models.PullRequest{ - Num: 1, - }) + files, err := client.GetModifiedFiles( + logger, + models.Repo{ + FullName: "owner/repo", + Owner: "owner", + Name: "repo", + CloneURL: "", + SanitizedCloneURL: "", + VCSHost: models.VCSHost{ + Type: models.Github, + Hostname: "github.com", + }, + }, models.PullRequest{ + Num: 1, + }) Ok(t, err) Equals(t, []string{"new/filename.txt", "previous/filename.txt"}, files) } func TestGithubClient_PaginatesComments(t *testing.T) { + logger := logging.NewNoopLogger(t) calls := 0 issueResps := []string{ `[ @@ -217,6 +223,7 @@ func TestGithubClient_PaginatesComments(t *testing.T) { defer disableSSLVerification()() err = client.HidePrevCommandComments( + logger, models.Repo{ FullName: "owner/repo", Owner: "owner", @@ -241,6 +248,7 @@ func TestGithubClient_PaginatesComments(t *testing.T) { } func TestGithubClient_HideOldComments(t *testing.T) { + logger := logging.NewNoopLogger(t) atlantisUser := "AtlantisUser" pullRequestNum := 123 issueResp := strings.ReplaceAll(`[ @@ -332,6 +340,7 @@ func TestGithubClient_HideOldComments(t *testing.T) { defer disableSSLVerification()() err = client.HidePrevCommandComments( + logger, models.Repo{ FullName: "owner/repo", Owner: "owner", @@ -358,6 +367,7 @@ func TestGithubClient_HideOldComments(t *testing.T) { } func TestGithubClient_UpdateStatus(t *testing.T) { + logger := logging.NewNoopLogger(t) cases := []struct { status models.CommitStatus expState string @@ -401,25 +411,28 @@ func TestGithubClient_UpdateStatus(t *testing.T) { Ok(t, err) defer disableSSLVerification()() - err = client.UpdateStatus(models.Repo{ - FullName: "owner/repo", - Owner: "owner", - Name: "repo", - CloneURL: "", - SanitizedCloneURL: "", - VCSHost: models.VCSHost{ - Type: models.Github, - Hostname: "github.com", - }, - }, models.PullRequest{ - Num: 1, - }, c.status, "src", "description", "https://google.com") + err = client.UpdateStatus( + logger, + models.Repo{ + FullName: "owner/repo", + Owner: "owner", + Name: "repo", + CloneURL: "", + SanitizedCloneURL: "", + VCSHost: models.VCSHost{ + Type: models.Github, + Hostname: "github.com", + }, + }, models.PullRequest{ + Num: 1, + }, c.status, "src", "description", "https://google.com") Ok(t, err) }) } } func TestGithubClient_PullIsApproved(t *testing.T) { + logger := logging.NewNoopLogger(t) respTemplate := `[ { "id": %d, @@ -487,24 +500,27 @@ func TestGithubClient_PullIsApproved(t *testing.T) { Ok(t, err) defer disableSSLVerification()() - approvalStatus, err := client.PullIsApproved(models.Repo{ - FullName: "owner/repo", - Owner: "owner", - Name: "repo", - CloneURL: "", - SanitizedCloneURL: "", - VCSHost: models.VCSHost{ - Type: models.Github, - Hostname: "github.com", - }, - }, models.PullRequest{ - Num: 1, - }) + approvalStatus, err := client.PullIsApproved( + logger, + models.Repo{ + FullName: "owner/repo", + Owner: "owner", + Name: "repo", + CloneURL: "", + SanitizedCloneURL: "", + VCSHost: models.VCSHost{ + Type: models.Github, + Hostname: "github.com", + }, + }, models.PullRequest{ + Num: 1, + }) Ok(t, err) Equals(t, false, approvalStatus.IsApproved) } func TestGithubClient_PullIsMergeable(t *testing.T) { + logger := logging.NewNoopLogger(t) vcsStatusName := "atlantis-test" cases := []struct { state string @@ -602,19 +618,21 @@ func TestGithubClient_PullIsMergeable(t *testing.T) { Ok(t, err) defer disableSSLVerification()() - actMergeable, err := client.PullIsMergeable(models.Repo{ - FullName: "owner/repo", - Owner: "owner", - Name: "repo", - CloneURL: "", - SanitizedCloneURL: "", - VCSHost: models.VCSHost{ - Type: models.Github, - Hostname: "github.com", - }, - }, models.PullRequest{ - Num: 1, - }, vcsStatusName) + actMergeable, err := client.PullIsMergeable( + logger, + models.Repo{ + FullName: "owner/repo", + Owner: "owner", + Name: "repo", + CloneURL: "", + SanitizedCloneURL: "", + VCSHost: models.VCSHost{ + Type: models.Github, + Hostname: "github.com", + }, + }, models.PullRequest{ + Num: 1, + }, vcsStatusName) Ok(t, err) Equals(t, c.expMergeable, actMergeable) }) @@ -622,6 +640,7 @@ func TestGithubClient_PullIsMergeable(t *testing.T) { } func TestGithubClient_PullIsMergeableWithAllowMergeableBypassApply(t *testing.T) { + logger := logging.NewNoopLogger(t) vcsStatusName := "atlantis" cases := []struct { state string @@ -753,19 +772,21 @@ func TestGithubClient_PullIsMergeableWithAllowMergeableBypassApply(t *testing.T) Ok(t, err) defer disableSSLVerification()() - actMergeable, err := client.PullIsMergeable(models.Repo{ - FullName: "octocat/repo", - Owner: "octocat", - Name: "repo", - CloneURL: "", - SanitizedCloneURL: "", - VCSHost: models.VCSHost{ - Type: models.Github, - Hostname: "github.com", - }, - }, models.PullRequest{ - Num: 1, - }, vcsStatusName) + actMergeable, err := client.PullIsMergeable( + logger, + models.Repo{ + FullName: "octocat/repo", + Owner: "octocat", + Name: "repo", + CloneURL: "", + SanitizedCloneURL: "", + VCSHost: models.VCSHost{ + Type: models.Github, + Hostname: "github.com", + }, + }, models.PullRequest{ + Num: 1, + }, vcsStatusName) Ok(t, err) Equals(t, c.expMergeable, actMergeable) }) @@ -773,6 +794,7 @@ func TestGithubClient_PullIsMergeableWithAllowMergeableBypassApply(t *testing.T) } func TestGithubClient_PullIsMergeableWithAllowMergeableBypassApplyButWithNoBranchProtectionChecks(t *testing.T) { + logger := logging.NewNoopLogger(t) vcsStatusName := "atlantis" cases := []struct { state string @@ -861,19 +883,21 @@ func TestGithubClient_PullIsMergeableWithAllowMergeableBypassApplyButWithNoBranc Ok(t, err) defer disableSSLVerification()() - actMergeable, err := client.PullIsMergeable(models.Repo{ - FullName: "octocat/Hello-World", - Owner: "octocat", - Name: "Hello-World", - CloneURL: "", - SanitizedCloneURL: "", - VCSHost: models.VCSHost{ - Type: models.Github, - Hostname: "github.com", - }, - }, models.PullRequest{ - Num: 1, - }, vcsStatusName) + actMergeable, err := client.PullIsMergeable( + logger, + models.Repo{ + FullName: "octocat/Hello-World", + Owner: "octocat", + Name: "Hello-World", + CloneURL: "", + SanitizedCloneURL: "", + VCSHost: models.VCSHost{ + Type: models.Github, + Hostname: "github.com", + }, + }, models.PullRequest{ + Num: 1, + }, vcsStatusName) Ok(t, err) Equals(t, c.expMergeable, actMergeable) }) @@ -881,6 +905,7 @@ func TestGithubClient_PullIsMergeableWithAllowMergeableBypassApplyButWithNoBranc } func TestGithubClient_MergePullHandlesError(t *testing.T) { + logger := logging.NewNoopLogger(t) cases := []struct { code int message string @@ -944,6 +969,7 @@ func TestGithubClient_MergePullHandlesError(t *testing.T) { defer disableSSLVerification()() err = client.MergePull( + logger, models.PullRequest{ BaseRepo: models.Repo{ FullName: "owner/repo", @@ -973,6 +999,7 @@ func TestGithubClient_MergePullHandlesError(t *testing.T) { // Test that if the pull request only allows a certain merge method that we // use that method func TestGithubClient_MergePullCorrectMethod(t *testing.T) { + logger := logging.NewNoopLogger(t) cases := map[string]struct { allowMerge bool allowRebase bool @@ -1067,6 +1094,7 @@ func TestGithubClient_MergePullCorrectMethod(t *testing.T) { defer disableSSLVerification()() err = client.MergePull( + logger, models.PullRequest{ BaseRepo: models.Repo{ FullName: "runatlantis/atlantis", @@ -1110,6 +1138,7 @@ func disableSSLVerification() func() { } func TestGithubClient_SplitComments(t *testing.T) { + logger := logging.NewNoopLogger(t) type githubComment struct { Body string `json:"body"` } @@ -1162,9 +1191,9 @@ func TestGithubClient_SplitComments(t *testing.T) { } // create an extra long string comment := strings.Repeat("a", 65537) - err = client.CreateComment(repo, pull.Num, comment, command.Plan.String()) + err = client.CreateComment(logger, repo, pull.Num, comment, command.Plan.String()) Ok(t, err) - err = client.CreateComment(repo, pull.Num, comment, "") + err = client.CreateComment(logger, repo, pull.Num, comment, "") Ok(t, err) body := strings.Split(githubComments[1].Body, "\n") @@ -1179,6 +1208,7 @@ func TestGithubClient_SplitComments(t *testing.T) { // Test that we retry the get pull request call if it 404s. func TestGithubClient_Retry404(t *testing.T) { + logger := logging.NewNoopLogger(t) var numCalls = 0 testServer := httptest.NewTLSServer( @@ -1217,13 +1247,14 @@ func TestGithubClient_Retry404(t *testing.T) { Hostname: "github.com", }, } - _, err = client.GetPullRequest(repo, 1) + _, err = client.GetPullRequest(logger, repo, 1) Ok(t, err) Equals(t, 3, numCalls) } // Test that we retry the get pull request files call if it 404s. func TestGithubClient_Retry404Files(t *testing.T) { + logger := logging.NewNoopLogger(t) var numCalls = 0 testServer := httptest.NewTLSServer( @@ -1263,7 +1294,7 @@ func TestGithubClient_Retry404Files(t *testing.T) { }, } pr := models.PullRequest{Num: 1} - _, err = client.GetModifiedFiles(repo, pr) + _, err = client.GetModifiedFiles(logger, repo, pr) Ok(t, err) Equals(t, 3, numCalls) } @@ -1572,12 +1603,14 @@ func TestGithubClient_GetPullLabels(t *testing.T) { Ok(t, err) defer disableSSLVerification()() - labels, err := client.GetPullLabels(models.Repo{ - Owner: "runatlantis", - Name: "atlantis", - }, models.PullRequest{ - Num: 1, - }) + labels, err := client.GetPullLabels( + logger, + models.Repo{ + Owner: "runatlantis", + Name: "atlantis", + }, models.PullRequest{ + Num: 1, + }) Ok(t, err) Equals(t, []string{"docs", "go", "needs tests", "work-in-progress"}, labels) } @@ -1607,12 +1640,15 @@ func TestGithubClient_GetPullLabels_EmptyResponse(t *testing.T) { Ok(t, err) defer disableSSLVerification()() - labels, err := client.GetPullLabels(models.Repo{ - Owner: "runatlantis", - Name: "atlantis", - }, models.PullRequest{ - Num: 1, - }) + labels, err := client.GetPullLabels( + logger, + models.Repo{ + Owner: "runatlantis", + Name: "atlantis", + }, + models.PullRequest{ + Num: 1, + }) Ok(t, err) Equals(t, 0, len(labels)) } diff --git a/server/events/vcs/github_credentials_test.go b/server/events/vcs/github_credentials_test.go index f6975056c9..f6604adfa0 100644 --- a/server/events/vcs/github_credentials_test.go +++ b/server/events/vcs/github_credentials_test.go @@ -10,6 +10,7 @@ import ( ) func TestGithubClient_GetUser_AppSlug(t *testing.T) { + logger := logging.NewNoopLogger(t) defer disableSSLVerification()() testServer, err := testdata.GithubAppTestServer(t) Ok(t, err) @@ -17,7 +18,7 @@ func TestGithubClient_GetUser_AppSlug(t *testing.T) { anonCreds := &vcs.GithubAnonymousCredentials{} anonClient, err := vcs.NewGithubClient(testServer, anonCreds, vcs.GithubConfig{}, logging.NewNoopLogger(t)) Ok(t, err) - tempSecrets, err := anonClient.ExchangeCode("good-code") + tempSecrets, err := anonClient.ExchangeCode(logger, "good-code") Ok(t, err) appCreds := &vcs.GithubAppCredentials{ @@ -34,6 +35,7 @@ func TestGithubClient_GetUser_AppSlug(t *testing.T) { } func TestGithubClient_AppAuthentication(t *testing.T) { + logger := logging.NewNoopLogger(t) defer disableSSLVerification()() testServer, err := testdata.GithubAppTestServer(t) Ok(t, err) @@ -41,7 +43,7 @@ func TestGithubClient_AppAuthentication(t *testing.T) { anonCreds := &vcs.GithubAnonymousCredentials{} anonClient, err := vcs.NewGithubClient(testServer, anonCreds, vcs.GithubConfig{}, logging.NewNoopLogger(t)) Ok(t, err) - tempSecrets, err := anonClient.ExchangeCode("good-code") + tempSecrets, err := anonClient.ExchangeCode(logger, "good-code") Ok(t, err) appCreds := &vcs.GithubAppCredentials{ diff --git a/server/events/vcs/gitlab_client.go b/server/events/vcs/gitlab_client.go index d9e2b4d33c..c4cb837a4e 100644 --- a/server/events/vcs/gitlab_client.go +++ b/server/events/vcs/gitlab_client.go @@ -46,8 +46,6 @@ type GitlabClient struct { PollingInterval time.Duration // PollingInterval is the total duration for which to poll, where applicable. PollingTimeout time.Duration - // logger - logger logging.SimpleLogging } // commonMarkSupported is a version constraint that is true when this version of @@ -60,10 +58,10 @@ var gitlabClientUnderTest = false // NewGitlabClient returns a valid GitLab client. func NewGitlabClient(hostname string, token string, logger logging.SimpleLogging) (*GitlabClient, error) { + logger.Debug("Creating new GitLab client for %s", hostname) client := &GitlabClient{ PollingInterval: time.Second, PollingTimeout: time.Second * 30, - logger: logger, } // Create the client differently depending on the base URL. @@ -107,7 +105,7 @@ func NewGitlabClient(hostname string, token string, logger logging.SimpleLogging // Determine which version of GitLab is running. if !gitlabClientUnderTest { var err error - client.Version, err = client.GetVersion() + client.Version, err = client.GetVersion(logger) if err != nil { return nil, err } @@ -119,7 +117,8 @@ func NewGitlabClient(hostname string, token string, logger logging.SimpleLogging // GetModifiedFiles returns the names of files that were modified in the merge request // relative to the repo root, e.g. parent/child/file.txt. -func (g *GitlabClient) GetModifiedFiles(repo models.Repo, pull models.PullRequest) ([]string, error) { +func (g *GitlabClient) GetModifiedFiles(logger logging.SimpleLogging, repo models.Repo, pull models.PullRequest) ([]string, error) { + logger.Debug("Getting modified files for GitLab merge request %d", pull.Num) const maxPerPage = 100 var files []string nextPage := 1 @@ -140,7 +139,7 @@ func (g *GitlabClient) GetModifiedFiles(repo models.Repo, pull models.PullReques for { resp, err = g.Client.Do(req, mr) if resp != nil { - g.logger.Debug("GET %s returned: %d", apiURL, resp.StatusCode) + logger.Debug("GET %s returned: %d", apiURL, resp.StatusCode) } if err != nil { return nil, err @@ -173,7 +172,8 @@ func (g *GitlabClient) GetModifiedFiles(repo models.Repo, pull models.PullReques } // CreateComment creates a comment on the merge request. -func (g *GitlabClient) CreateComment(repo models.Repo, pullNum int, comment string, _ string) error { +func (g *GitlabClient) CreateComment(logger logging.SimpleLogging, repo models.Repo, pullNum int, comment string, _ string) error { + logger.Debug("Creating comment on GitLab merge request %d", pullNum) sepEnd := "\n```\n" + "\n
\n\n**Warning**: Output length greater than max comment size. Continued in next comment." sepStart := "Continued from previous comment.\n
Show Output\n\n" + @@ -182,7 +182,7 @@ func (g *GitlabClient) CreateComment(repo models.Repo, pullNum int, comment stri for _, c := range comments { _, resp, err := g.Client.Notes.CreateMergeRequestNote(repo.FullName, pullNum, &gitlab.CreateMergeRequestNoteOptions{Body: gitlab.Ptr(c)}) if resp != nil { - g.logger.Debug("POST /projects/%s/merge_requests/%d/notes returned: %d", repo.FullName, pullNum, resp.StatusCode) + logger.Debug("POST /projects/%s/merge_requests/%d/notes returned: %d", repo.FullName, pullNum, resp.StatusCode) } if err != nil { return err @@ -192,20 +192,22 @@ func (g *GitlabClient) CreateComment(repo models.Repo, pullNum int, comment stri } // ReactToComment adds a reaction to a comment. -func (g *GitlabClient) ReactToComment(repo models.Repo, pullNum int, commentID int64, reaction string) error { +func (g *GitlabClient) ReactToComment(logger logging.SimpleLogging, repo models.Repo, pullNum int, commentID int64, reaction string) error { + logger.Debug("Adding reaction '%s' to comment %d on GitLab merge request %d", reaction, commentID, pullNum) _, resp, err := g.Client.AwardEmoji.CreateMergeRequestAwardEmojiOnNote(repo.FullName, pullNum, int(commentID), &gitlab.CreateAwardEmojiOptions{Name: reaction}) if resp != nil { - g.logger.Debug("POST /projects/%s/merge_requests/%d/notes/%d/award_emoji returned: %d", repo.FullName, pullNum, commentID, resp.StatusCode) + logger.Debug("POST /projects/%s/merge_requests/%d/notes/%d/award_emoji returned: %d", repo.FullName, pullNum, commentID, resp.StatusCode) } return err } -func (g *GitlabClient) HidePrevCommandComments(repo models.Repo, pullNum int, command string, dir string) error { +func (g *GitlabClient) HidePrevCommandComments(logger logging.SimpleLogging, repo models.Repo, pullNum int, command string, dir string) error { + logger.Debug("Hiding previous command comments on GitLab merge request %d", pullNum) var allComments []*gitlab.Note nextPage := 0 for { - g.logger.Debug("/projects/%v/merge_requests/%d/notes", repo.FullName, pullNum) + logger.Debug("/projects/%v/merge_requests/%d/notes", repo.FullName, pullNum) comments, resp, err := g.Client.Notes.ListMergeRequestNotes(repo.FullName, pullNum, &gitlab.ListMergeRequestNotesOptions{ Sort: gitlab.Ptr("asc"), @@ -213,7 +215,7 @@ func (g *GitlabClient) HidePrevCommandComments(repo models.Repo, pullNum int, co ListOptions: gitlab.ListOptions{Page: nextPage}, }) if resp != nil { - g.logger.Debug("GET /projects/%s/merge_requests/%d/notes returned: %d", repo.FullName, pullNum, resp.StatusCode) + logger.Debug("GET /projects/%s/merge_requests/%d/notes returned: %d", repo.FullName, pullNum, resp.StatusCode) } if err != nil { return errors.Wrap(err, "listing comments") @@ -255,12 +257,12 @@ func (g *GitlabClient) HidePrevCommandComments(repo models.Repo, pullNum int, co continue } - g.logger.Debug("Updating merge request note: Repo: '%s', MR: '%d', comment ID: '%d'", repo.FullName, pullNum, comment.ID) + logger.Debug("Updating merge request note: Repo: '%s', MR: '%d', comment ID: '%d'", repo.FullName, pullNum, comment.ID) supersededComment := summaryHeader + lineFeed + comment.Body + lineFeed + summaryFooter + lineFeed _, resp, err := g.Client.Notes.UpdateMergeRequestNote(repo.FullName, pullNum, comment.ID, &gitlab.UpdateMergeRequestNoteOptions{Body: &supersededComment}) if resp != nil { - g.logger.Debug("PUT /projects/%s/merge_requests/%d/notes/%d returned: %d", repo.FullName, pullNum, comment.ID, resp.StatusCode) + logger.Debug("PUT /projects/%s/merge_requests/%d/notes/%d returned: %d", repo.FullName, pullNum, comment.ID, resp.StatusCode) } if err != nil { return errors.Wrapf(err, "updating comment %d", comment.ID) @@ -271,10 +273,11 @@ func (g *GitlabClient) HidePrevCommandComments(repo models.Repo, pullNum int, co } // PullIsApproved returns true if the merge request was approved. -func (g *GitlabClient) PullIsApproved(repo models.Repo, pull models.PullRequest) (approvalStatus models.ApprovalStatus, err error) { +func (g *GitlabClient) PullIsApproved(logger logging.SimpleLogging, repo models.Repo, pull models.PullRequest) (approvalStatus models.ApprovalStatus, err error) { + logger.Debug("Checking if GitLab merge request %d is approved", pull.Num) approvals, resp, err := g.Client.MergeRequests.GetMergeRequestApprovals(repo.FullName, pull.Num) if resp != nil { - g.logger.Debug("GET /projects/%s/merge_requests/%d/approvals returned: %d", repo.FullName, pull.Num, resp.StatusCode) + logger.Debug("GET /projects/%s/merge_requests/%d/approvals returned: %d", repo.FullName, pull.Num, resp.StatusCode) } if err != nil { return approvalStatus, err @@ -298,10 +301,11 @@ func (g *GitlabClient) PullIsApproved(repo models.Repo, pull models.PullRequest) // See: // - https://gitlab.com/gitlab-org/gitlab-ee/issues/3169 // - https://gitlab.com/gitlab-org/gitlab-ce/issues/42344 -func (g *GitlabClient) PullIsMergeable(repo models.Repo, pull models.PullRequest, vcsstatusname string) (bool, error) { +func (g *GitlabClient) PullIsMergeable(logger logging.SimpleLogging, repo models.Repo, pull models.PullRequest, vcsstatusname string) (bool, error) { + logger.Debug("Checking if GitLab merge request %d is mergeable", pull.Num) mr, resp, err := g.Client.MergeRequests.GetMergeRequest(repo.FullName, pull.Num, nil) if resp != nil { - g.logger.Debug("GET /projects/%s/merge_requests/%d returned: %d", repo.FullName, pull.Num, resp.StatusCode) + logger.Debug("GET /projects/%s/merge_requests/%d returned: %d", repo.FullName, pull.Num, resp.StatusCode) } if err != nil { return false, err @@ -319,7 +323,7 @@ func (g *GitlabClient) PullIsMergeable(repo models.Repo, pull models.PullRequest // Get project configuration project, resp, err := g.Client.Projects.GetProject(mr.ProjectID, nil) if resp != nil { - g.logger.Debug("GET /projects/%d returned: %d", mr.ProjectID, resp.StatusCode) + logger.Debug("GET /projects/%d returned: %d", mr.ProjectID, resp.StatusCode) } if err != nil { return false, err @@ -328,7 +332,7 @@ func (g *GitlabClient) PullIsMergeable(repo models.Repo, pull models.PullRequest // Get Commit Statuses statuses, _, err := g.Client.Commits.GetCommitStatuses(mr.ProjectID, commit, nil) if resp != nil { - g.logger.Debug("GET /projects/%d/commits/%s/statuses returned: %d", mr.ProjectID, commit, resp.StatusCode) + logger.Debug("GET /projects/%d/commits/%s/statuses returned: %d", mr.ProjectID, commit, resp.StatusCode) } if err != nil { return false, err @@ -346,7 +350,7 @@ func (g *GitlabClient) PullIsMergeable(repo models.Repo, pull models.PullRequest allowSkippedPipeline := project.AllowMergeOnSkippedPipeline && isPipelineSkipped - supportsDetailedMergeStatus, err := g.SupportsDetailedMergeStatus() + supportsDetailedMergeStatus, err := g.SupportsDetailedMergeStatus(logger) if err != nil { return false, err } @@ -366,8 +370,9 @@ func (g *GitlabClient) PullIsMergeable(repo models.Repo, pull models.PullRequest return false, nil } -func (g *GitlabClient) SupportsDetailedMergeStatus() (bool, error) { - v, err := g.GetVersion() +func (g *GitlabClient) SupportsDetailedMergeStatus(logger logging.SimpleLogging) (bool, error) { + logger.Debug("Checking if GitLab supports detailed merge status") + v, err := g.GetVersion(logger) if err != nil { return false, err } @@ -380,7 +385,8 @@ func (g *GitlabClient) SupportsDetailedMergeStatus() (bool, error) { } // UpdateStatus updates the build status of a commit. -func (g *GitlabClient) UpdateStatus(repo models.Repo, pull models.PullRequest, state models.CommitStatus, src string, description string, url string) error { +func (g *GitlabClient) UpdateStatus(logger logging.SimpleLogging, repo models.Repo, pull models.PullRequest, state models.CommitStatus, src string, description string, url string) error { + logger.Debug("Updating GitLab commit status for '%s' to '%s'", src, state) gitlabState := gitlab.Pending switch state { case models.PendingCommitStatus: @@ -403,22 +409,22 @@ func (g *GitlabClient) UpdateStatus(repo models.Repo, pull models.PullRequest, s var err error for i := 0; i <= retries; i++ { - mr, err = g.GetMergeRequest(pull.BaseRepo.FullName, pull.Num) + mr, err = g.GetMergeRequest(logger, pull.BaseRepo.FullName, pull.Num) if err != nil { return err } if mr.HeadPipeline != nil { - g.logger.Debug("Head pipeline found for merge request %d, source '%s'. refTarget '%s'", + logger.Debug("Head pipeline found for merge request %d, source '%s'. refTarget '%s'", pull.Num, mr.HeadPipeline.Source, mr.HeadPipeline.Ref) refTarget = mr.HeadPipeline.Ref break } if i != retries { - g.logger.Debug("Head pipeline not found for merge request %d. Retrying in %s", + logger.Debug("Head pipeline not found for merge request %d. Retrying in %s", pull.Num, delay) time.Sleep(delay) } else { - g.logger.Debug("Head pipeline not found for merge request %d.", + logger.Debug("Head pipeline not found for merge request %d.", pull.Num) } } @@ -431,20 +437,22 @@ func (g *GitlabClient) UpdateStatus(repo models.Repo, pull models.PullRequest, s Ref: gitlab.Ptr(refTarget), }) if resp != nil { - g.logger.Debug("POST /projects/%s/statuses/%s returned: %d", repo.FullName, pull.HeadCommit, resp.StatusCode) + logger.Debug("POST /projects/%s/statuses/%s returned: %d", repo.FullName, pull.HeadCommit, resp.StatusCode) } return err } -func (g *GitlabClient) GetMergeRequest(repoFullName string, pullNum int) (*gitlab.MergeRequest, error) { +func (g *GitlabClient) GetMergeRequest(logger logging.SimpleLogging, repoFullName string, pullNum int) (*gitlab.MergeRequest, error) { + logger.Debug("Getting GitLab merge request %d", pullNum) mr, resp, err := g.Client.MergeRequests.GetMergeRequest(repoFullName, pullNum, nil) if resp != nil { - g.logger.Debug("GET /projects/%s/merge_requests/%d returned: %d", repoFullName, pullNum, resp.StatusCode) + logger.Debug("GET /projects/%s/merge_requests/%d returned: %d", repoFullName, pullNum, resp.StatusCode) } return mr, err } -func (g *GitlabClient) WaitForSuccessPipeline(ctx context.Context, pull models.PullRequest) { +func (g *GitlabClient) WaitForSuccessPipeline(logger logging.SimpleLogging, ctx context.Context, pull models.PullRequest) { + logger.Debug("Waiting for GitLab success pipeline for merge request %d", pull.Num) ctx, cancel := context.WithTimeout(ctx, 10*time.Second) defer cancel() @@ -456,7 +464,7 @@ func (g *GitlabClient) WaitForSuccessPipeline(ctx context.Context, pull models.P return //ctx.Err() default: - mr, _ := g.GetMergeRequest(pull.BaseRepo.FullName, pull.Num) + mr, _ := g.GetMergeRequest(logger, pull.BaseRepo.FullName, pull.Num) // check if pipeline has a success state to merge if mr.HeadPipeline.Status == "success" { return @@ -467,17 +475,18 @@ func (g *GitlabClient) WaitForSuccessPipeline(ctx context.Context, pull models.P } // MergePull merges the merge request. -func (g *GitlabClient) MergePull(pull models.PullRequest, pullOptions models.PullRequestOptions) error { +func (g *GitlabClient) MergePull(logger logging.SimpleLogging, pull models.PullRequest, pullOptions models.PullRequestOptions) error { + logger.Debug("Merging GitLab merge request %d", pull.Num) commitMsg := common.AutomergeCommitMsg(pull.Num) - mr, err := g.GetMergeRequest(pull.BaseRepo.FullName, pull.Num) + mr, err := g.GetMergeRequest(logger, pull.BaseRepo.FullName, pull.Num) if err != nil { return errors.Wrap( err, "unable to merge merge request, it was not possible to retrieve the merge request") } project, resp, err := g.Client.Projects.GetProject(mr.ProjectID, nil) if resp != nil { - g.logger.Debug("GET /projects/%d returned: %d", mr.ProjectID, resp.StatusCode) + logger.Debug("GET /projects/%d returned: %d", mr.ProjectID, resp.StatusCode) } if err != nil { return errors.Wrap( @@ -485,7 +494,7 @@ func (g *GitlabClient) MergePull(pull models.PullRequest, pullOptions models.Pul } if project != nil && project.OnlyAllowMergeIfPipelineSucceeds { - g.WaitForSuccessPipeline(context.Background(), pull) + g.WaitForSuccessPipeline(logger, context.Background(), pull) } _, resp, err = g.Client.MergeRequests.AcceptMergeRequest( @@ -496,7 +505,7 @@ func (g *GitlabClient) MergePull(pull models.PullRequest, pullOptions models.Pul ShouldRemoveSourceBranch: &pullOptions.DeleteSourceBranchOnMerge, }) if resp != nil { - g.logger.Debug("PUT /projects/%s/merge_requests/%d/merge returned: %d", pull.BaseRepo.FullName, pull.Num, resp.StatusCode) + logger.Debug("PUT /projects/%s/merge_requests/%d/merge returned: %d", pull.BaseRepo.FullName, pull.Num, resp.StatusCode) } return errors.Wrap(err, "unable to merge merge request, it may not be in a mergeable state") } @@ -512,10 +521,11 @@ func (g *GitlabClient) DiscardReviews(_ models.Repo, _ models.PullRequest) error } // GetVersion returns the version of the Gitlab server this client is using. -func (g *GitlabClient) GetVersion() (*version.Version, error) { +func (g *GitlabClient) GetVersion(logger logging.SimpleLogging) (*version.Version, error) { + logger.Debug("Getting GitLab version") versionResp, resp, err := g.Client.Version.GetVersion() if resp != nil { - g.logger.Debug("GET /version returned: %d", resp.StatusCode) + logger.Debug("GET /version returned: %d", resp.StatusCode) } if err != nil { return nil, err @@ -560,12 +570,13 @@ func (g *GitlabClient) GetTeamNamesForUser(_ models.Repo, _ models.User) ([]stri // GetFileContent a repository file content from VCS (which support fetch a single file from repository) // The first return value indicates whether the repo contains a file or not // if BaseRepo had a file, its content will placed on the second return value -func (g *GitlabClient) GetFileContent(pull models.PullRequest, fileName string) (bool, []byte, error) { +func (g *GitlabClient) GetFileContent(logger logging.SimpleLogging, pull models.PullRequest, fileName string) (bool, []byte, error) { + logger.Debug("Getting GitLab file content for file '%s'", fileName) opt := gitlab.GetRawFileOptions{Ref: gitlab.Ptr(pull.HeadBranch)} bytes, resp, err := g.Client.RepositoryFiles.GetRawFile(pull.BaseRepo.FullName, fileName, &opt) if resp != nil { - g.logger.Debug("GET /projects/%s/repository/files/%s/raw returned: %d", pull.BaseRepo.FullName, fileName, resp.StatusCode) + logger.Debug("GET /projects/%s/repository/files/%s/raw returned: %d", pull.BaseRepo.FullName, fileName, resp.StatusCode) } if resp != nil && resp.StatusCode == http.StatusNotFound { return false, []byte{}, nil @@ -582,10 +593,11 @@ func (g *GitlabClient) SupportsSingleFileDownload(_ models.Repo) bool { return true } -func (g *GitlabClient) GetCloneURL(_ models.VCSHostType, repo string) (string, error) { +func (g *GitlabClient) GetCloneURL(logger logging.SimpleLogging, _ models.VCSHostType, repo string) (string, error) { + logger.Debug("Getting GitLab clone URL for repo '%s'", repo) project, resp, err := g.Client.Projects.GetProject(repo, nil) if resp != nil { - g.logger.Debug("GET /projects/%s returned: %d", repo, resp.StatusCode) + logger.Debug("GET /projects/%s returned: %d", repo, resp.StatusCode) } if err != nil { return "", err @@ -593,10 +605,11 @@ func (g *GitlabClient) GetCloneURL(_ models.VCSHostType, repo string) (string, e return project.HTTPURLToRepo, nil } -func (g *GitlabClient) GetPullLabels(repo models.Repo, pull models.PullRequest) ([]string, error) { +func (g *GitlabClient) GetPullLabels(logger logging.SimpleLogging, repo models.Repo, pull models.PullRequest) ([]string, error) { + logger.Debug("Getting GitLab labels for merge request %d", pull.Num) mr, resp, err := g.Client.MergeRequests.GetMergeRequest(repo.FullName, pull.Num, nil) if resp != nil { - g.logger.Debug("GET /projects/%s/merge_requests/%d returned: %d", repo.FullName, pull.Num, resp.StatusCode) + logger.Debug("GET /projects/%s/merge_requests/%d returned: %d", repo.FullName, pull.Num, resp.StatusCode) } if err != nil { diff --git a/server/events/vcs/gitlab_client_test.go b/server/events/vcs/gitlab_client_test.go index 99cf6b426e..5c463e85cf 100644 --- a/server/events/vcs/gitlab_client_test.go +++ b/server/events/vcs/gitlab_client_test.go @@ -114,6 +114,7 @@ func TestGitlabClient_SupportsCommonMark(t *testing.T) { } func TestGitlabClient_GetModifiedFiles(t *testing.T) { + logger := logging.NewNoopLogger(t) cases := []struct { attempts int }{ @@ -155,10 +156,10 @@ func TestGitlabClient_GetModifiedFiles(t *testing.T) { Version: nil, PollingInterval: time.Second * 0, PollingTimeout: time.Second * 10, - logger: logging.NewNoopLogger(t), } filenames, err := client.GetModifiedFiles( + logger, models.Repo{ FullName: "lkysow/atlantis-example", Owner: "lkysow", @@ -180,6 +181,7 @@ func TestGitlabClient_GetModifiedFiles(t *testing.T) { } func TestGitlabClient_MergePull(t *testing.T) { + logger := logging.NewNoopLogger(t) mergeSuccess, err := os.ReadFile("testdata/github-pull-request.json") Ok(t, err) @@ -244,19 +246,20 @@ func TestGitlabClient_MergePull(t *testing.T) { client := &GitlabClient{ Client: internalClient, Version: nil, - logger: logging.NewNoopLogger(t), } - err = client.MergePull(models.PullRequest{ - Num: 1, - BaseRepo: models.Repo{ - FullName: "runatlantis/atlantis", - Owner: "runatlantis", - Name: "atlantis", - }, - }, models.PullRequestOptions{ - DeleteSourceBranchOnMerge: false, - }) + err = client.MergePull( + logger, + models.PullRequest{ + Num: 1, + BaseRepo: models.Repo{ + FullName: "runatlantis/atlantis", + Owner: "runatlantis", + Name: "atlantis", + }, + }, models.PullRequestOptions{ + DeleteSourceBranchOnMerge: false, + }) if c.expErr == "" { Ok(t, err) } else { @@ -268,6 +271,7 @@ func TestGitlabClient_MergePull(t *testing.T) { } func TestGitlabClient_UpdateStatus(t *testing.T) { + logger := logging.NewNoopLogger(t) pipelineSuccess, err := os.ReadFile("testdata/gitlab-pipeline-success.json") Ok(t, err) @@ -320,7 +324,6 @@ func TestGitlabClient_UpdateStatus(t *testing.T) { client := &GitlabClient{ Client: internalClient, Version: nil, - logger: logging.NewNoopLogger(t), } repo := models.Repo{ @@ -328,12 +331,15 @@ func TestGitlabClient_UpdateStatus(t *testing.T) { Owner: "runatlantis", Name: "atlantis", } - err = client.UpdateStatus(repo, models.PullRequest{ - Num: 1, - BaseRepo: repo, - HeadCommit: "sha", - HeadBranch: "test", - }, c.status, "src", "description", "https://google.com") + err = client.UpdateStatus( + logger, + repo, + models.PullRequest{ + Num: 1, + BaseRepo: repo, + HeadCommit: "sha", + HeadBranch: "test", + }, c.status, "src", "description", "https://google.com") Ok(t, err) Assert(t, gotRequest, "expected to get the request") }) @@ -341,6 +347,7 @@ func TestGitlabClient_UpdateStatus(t *testing.T) { } func TestGitlabClient_PullIsMergeable(t *testing.T) { + logger := logging.NewNoopLogger(t) gitlabClientUnderTest = true gitlabVersionOver15_6 := "15.8.3-ee" gitlabVersion15_6 := "15.6.0-ee" @@ -511,7 +518,6 @@ func TestGitlabClient_PullIsMergeable(t *testing.T) { client := &GitlabClient{ Client: internalClient, Version: nil, - logger: logging.NewNoopLogger(t), } repo := models.Repo{ @@ -524,11 +530,14 @@ func TestGitlabClient_PullIsMergeable(t *testing.T) { }, } - mergeable, err := client.PullIsMergeable(repo, models.PullRequest{ - Num: c.mrID, - BaseRepo: repo, - HeadCommit: "67cb91d3f6198189f433c045154a885784ba6977", - }, vcsStatusName) + mergeable, err := client.PullIsMergeable( + logger, + repo, + models.PullRequest{ + Num: c.mrID, + BaseRepo: repo, + HeadCommit: "67cb91d3f6198189f433c045154a885784ba6977", + }, vcsStatusName) Ok(t, err) Equals(t, c.expState, mergeable) @@ -538,9 +547,10 @@ func TestGitlabClient_PullIsMergeable(t *testing.T) { } func TestGitlabClient_MarkdownPullLink(t *testing.T) { + logger := logging.NewNoopLogger(t) gitlabClientUnderTest = true defer func() { gitlabClientUnderTest = false }() - client, err := NewGitlabClient("gitlab.com", "token", nil) + client, err := NewGitlabClient("gitlab.com", "token", logger) Ok(t, err) pull := models.PullRequest{Num: 1} s, _ := client.MarkdownPullLink(pull) @@ -549,6 +559,7 @@ func TestGitlabClient_MarkdownPullLink(t *testing.T) { } func TestGitlabClient_HideOldComments(t *testing.T) { + logger := logging.NewNoopLogger(t) type notePutCallDetails struct { noteID string comment []string @@ -673,10 +684,9 @@ func TestGitlabClient_HideOldComments(t *testing.T) { client := &GitlabClient{ Client: internalClient, Version: nil, - logger: logging.NewNoopLogger(t), } - err = client.HidePrevCommandComments(repo, pullNum, command.Plan.TitleString(), c.dir) + err = client.HidePrevCommandComments(logger, repo, pullNum, command.Plan.TitleString(), c.dir) Ok(t, err) // Check the correct number of plan comments have been processed @@ -693,6 +703,7 @@ func TestGitlabClient_HideOldComments(t *testing.T) { } func TestGithubClient_GetPullLabels(t *testing.T) { + logger := logging.NewNoopLogger(t) mergeSuccessWithLabel, err := os.ReadFile("testdata/gitlab-merge-success-with-label.json") Ok(t, err) @@ -713,19 +724,23 @@ func TestGithubClient_GetPullLabels(t *testing.T) { client := &GitlabClient{ Client: internalClient, Version: nil, - logger: logging.NewNoopLogger(t), } - labels, err := client.GetPullLabels(models.Repo{ - FullName: "runatlantis/atlantis", - }, models.PullRequest{ - Num: 1, - }) + labels, err := client.GetPullLabels( + logger, + models.Repo{ + FullName: "runatlantis/atlantis", + }, + models.PullRequest{ + Num: 1, + }, + ) Ok(t, err) Equals(t, []string{"work in progress"}, labels) } func TestGithubClient_GetPullLabels_EmptyResponse(t *testing.T) { + logger := logging.NewNoopLogger(t) pipelineSuccess, err := os.ReadFile("testdata/gitlab-pipeline-success.json") Ok(t, err) @@ -746,14 +761,15 @@ func TestGithubClient_GetPullLabels_EmptyResponse(t *testing.T) { client := &GitlabClient{ Client: internalClient, Version: nil, - logger: logging.NewNoopLogger(t), } - labels, err := client.GetPullLabels(models.Repo{ - FullName: "runatlantis/atlantis", - }, models.PullRequest{ - Num: 1, - }) + labels, err := client.GetPullLabels( + logger, + models.Repo{ + FullName: "runatlantis/atlantis", + }, models.PullRequest{ + Num: 1, + }) Ok(t, err) Equals(t, 0, len(labels)) } diff --git a/server/events/vcs/instrumented_client.go b/server/events/vcs/instrumented_client.go index 83dc0b2873..4f2cb9554e 100644 --- a/server/events/vcs/instrumented_client.go +++ b/server/events/vcs/instrumented_client.go @@ -1,7 +1,6 @@ package vcs import ( - "fmt" "strconv" "github.com/google/go-github/v58/github" @@ -32,7 +31,7 @@ func NewInstrumentedGithubClient(client *GithubClient, statsScope tally.Scope, l //go:generate pegomock generate --package mocks -o mocks/mock_github_pull_request_getter.go GithubPullRequestGetter type GithubPullRequestGetter interface { - GetPullRequest(repo models.Repo, pullNum int) (*github.PullRequest, error) + GetPullRequest(logger logging.SimpleLogging, repo models.Repo, pullNum int) (*github.PullRequest, error) } // IGithubClient exists to bridge the gap between GithubPullRequestGetter and Client interface to allow @@ -51,13 +50,9 @@ type InstrumentedGithubClient struct { Logger logging.SimpleLogging } -func (c *InstrumentedGithubClient) GetPullRequest(repo models.Repo, pullNum int) (*github.PullRequest, error) { +func (c *InstrumentedGithubClient) GetPullRequest(logger logging.SimpleLogging, repo models.Repo, pullNum int) (*github.PullRequest, error) { scope := c.StatsScope.SubScope("get_pull_request") scope = SetGitScopeTags(scope, repo.FullName, pullNum) - logger := c.Logger.WithHistory([]interface{}{ - "repository", fmt.Sprintf("%s/%s", repo.Owner, repo.Name), - "pull-num", strconv.Itoa(pullNum), - }...) executionTime := scope.Timer(metrics.ExecutionTimeMetric).Start() defer executionTime.Stop() @@ -65,7 +60,7 @@ func (c *InstrumentedGithubClient) GetPullRequest(repo models.Repo, pullNum int) executionSuccess := scope.Counter(metrics.ExecutionSuccessMetric) executionError := scope.Counter(metrics.ExecutionErrorMetric) - pull, err := c.PullRequestGetter.GetPullRequest(repo, pullNum) + pull, err := c.PullRequestGetter.GetPullRequest(logger, repo, pullNum) if err != nil { executionError.Inc(1) @@ -84,10 +79,9 @@ type InstrumentedClient struct { Logger logging.SimpleLogging } -func (c *InstrumentedClient) GetModifiedFiles(repo models.Repo, pull models.PullRequest) ([]string, error) { +func (c *InstrumentedClient) GetModifiedFiles(logger logging.SimpleLogging, repo models.Repo, pull models.PullRequest) ([]string, error) { scope := c.StatsScope.SubScope("get_modified_files") scope = SetGitScopeTags(scope, repo.FullName, pull.Num) - logger := c.Logger.WithHistory(fmtLogSrc(repo, pull.Num)...) executionTime := scope.Timer(metrics.ExecutionTimeMetric).Start() defer executionTime.Stop() @@ -95,7 +89,7 @@ func (c *InstrumentedClient) GetModifiedFiles(repo models.Repo, pull models.Pull executionSuccess := scope.Counter(metrics.ExecutionSuccessMetric) executionError := scope.Counter(metrics.ExecutionErrorMetric) - files, err := c.Client.GetModifiedFiles(repo, pull) + files, err := c.Client.GetModifiedFiles(logger, repo, pull) if err != nil { executionError.Inc(1) @@ -107,10 +101,9 @@ func (c *InstrumentedClient) GetModifiedFiles(repo models.Repo, pull models.Pull return files, err } -func (c *InstrumentedClient) CreateComment(repo models.Repo, pullNum int, comment string, command string) error { +func (c *InstrumentedClient) CreateComment(logger logging.SimpleLogging, repo models.Repo, pullNum int, comment string, command string) error { scope := c.StatsScope.SubScope("create_comment") scope = SetGitScopeTags(scope, repo.FullName, pullNum) - logger := c.Logger.WithHistory(fmtLogSrc(repo, pullNum)...) executionTime := scope.Timer(metrics.ExecutionTimeMetric).Start() defer executionTime.Stop() @@ -118,7 +111,7 @@ func (c *InstrumentedClient) CreateComment(repo models.Repo, pullNum int, commen executionSuccess := scope.Counter(metrics.ExecutionSuccessMetric) executionError := scope.Counter(metrics.ExecutionErrorMetric) - if err := c.Client.CreateComment(repo, pullNum, comment, command); err != nil { + if err := c.Client.CreateComment(logger, repo, pullNum, comment, command); err != nil { executionError.Inc(1) logger.Err("Unable to create comment for command %s, error: %s", command, err.Error()) return err @@ -128,7 +121,7 @@ func (c *InstrumentedClient) CreateComment(repo models.Repo, pullNum int, commen return nil } -func (c *InstrumentedClient) ReactToComment(repo models.Repo, pullNum int, commentID int64, reaction string) error { +func (c *InstrumentedClient) ReactToComment(logger logging.SimpleLogging, repo models.Repo, pullNum int, commentID int64, reaction string) error { scope := c.StatsScope.SubScope("react_to_comment") executionTime := scope.Timer(metrics.ExecutionTimeMetric).Start() @@ -137,9 +130,9 @@ func (c *InstrumentedClient) ReactToComment(repo models.Repo, pullNum int, comme executionSuccess := scope.Counter(metrics.ExecutionSuccessMetric) executionError := scope.Counter(metrics.ExecutionErrorMetric) - if err := c.Client.ReactToComment(repo, pullNum, commentID, reaction); err != nil { + if err := c.Client.ReactToComment(logger, repo, pullNum, commentID, reaction); err != nil { executionError.Inc(1) - c.Logger.Err("Unable to react to comment, error: %s", err.Error()) + logger.Err("Unable to react to comment, error: %s", err.Error()) return err } @@ -147,10 +140,9 @@ func (c *InstrumentedClient) ReactToComment(repo models.Repo, pullNum int, comme return nil } -func (c *InstrumentedClient) HidePrevCommandComments(repo models.Repo, pullNum int, command string, dir string) error { +func (c *InstrumentedClient) HidePrevCommandComments(logger logging.SimpleLogging, repo models.Repo, pullNum int, command string, dir string) error { scope := c.StatsScope.SubScope("hide_prev_plan_comments") scope = SetGitScopeTags(scope, repo.FullName, pullNum) - logger := c.Logger.WithHistory(fmtLogSrc(repo, pullNum)...) executionTime := scope.Timer(metrics.ExecutionTimeMetric).Start() defer executionTime.Stop() @@ -158,7 +150,7 @@ func (c *InstrumentedClient) HidePrevCommandComments(repo models.Repo, pullNum i executionSuccess := scope.Counter(metrics.ExecutionSuccessMetric) executionError := scope.Counter(metrics.ExecutionErrorMetric) - if err := c.Client.HidePrevCommandComments(repo, pullNum, command, dir); err != nil { + if err := c.Client.HidePrevCommandComments(logger, repo, pullNum, command, dir); err != nil { executionError.Inc(1) logger.Err("Unable to hide previous %s comments, error: %s", command, err.Error()) return err @@ -169,10 +161,9 @@ func (c *InstrumentedClient) HidePrevCommandComments(repo models.Repo, pullNum i } -func (c *InstrumentedClient) PullIsApproved(repo models.Repo, pull models.PullRequest) (models.ApprovalStatus, error) { +func (c *InstrumentedClient) PullIsApproved(logger logging.SimpleLogging, repo models.Repo, pull models.PullRequest) (models.ApprovalStatus, error) { scope := c.StatsScope.SubScope("pull_is_approved") scope = SetGitScopeTags(scope, repo.FullName, pull.Num) - logger := c.Logger.WithHistory(fmtLogSrc(repo, pull.Num)...) executionTime := scope.Timer(metrics.ExecutionTimeMetric).Start() defer executionTime.Stop() @@ -180,7 +171,7 @@ func (c *InstrumentedClient) PullIsApproved(repo models.Repo, pull models.PullRe executionSuccess := scope.Counter(metrics.ExecutionSuccessMetric) executionError := scope.Counter(metrics.ExecutionErrorMetric) - approved, err := c.Client.PullIsApproved(repo, pull) + approved, err := c.Client.PullIsApproved(logger, repo, pull) if err != nil { executionError.Inc(1) @@ -192,10 +183,9 @@ func (c *InstrumentedClient) PullIsApproved(repo models.Repo, pull models.PullRe return approved, err } -func (c *InstrumentedClient) PullIsMergeable(repo models.Repo, pull models.PullRequest, vcsstatusname string) (bool, error) { +func (c *InstrumentedClient) PullIsMergeable(logger logging.SimpleLogging, repo models.Repo, pull models.PullRequest, vcsstatusname string) (bool, error) { scope := c.StatsScope.SubScope("pull_is_mergeable") scope = SetGitScopeTags(scope, repo.FullName, pull.Num) - logger := c.Logger.WithHistory(fmtLogSrc(repo, pull.Num)...) executionTime := scope.Timer(metrics.ExecutionTimeMetric).Start() defer executionTime.Stop() @@ -203,7 +193,7 @@ func (c *InstrumentedClient) PullIsMergeable(repo models.Repo, pull models.PullR executionSuccess := scope.Counter(metrics.ExecutionSuccessMetric) executionError := scope.Counter(metrics.ExecutionErrorMetric) - mergeable, err := c.Client.PullIsMergeable(repo, pull, vcsstatusname) + mergeable, err := c.Client.PullIsMergeable(logger, repo, pull, vcsstatusname) if err != nil { executionError.Inc(1) @@ -215,17 +205,9 @@ func (c *InstrumentedClient) PullIsMergeable(repo models.Repo, pull models.PullR return mergeable, err } -func (c *InstrumentedClient) UpdateStatus(repo models.Repo, pull models.PullRequest, state models.CommitStatus, src string, description string, url string) error { +func (c *InstrumentedClient) UpdateStatus(logger logging.SimpleLogging, repo models.Repo, pull models.PullRequest, state models.CommitStatus, src string, description string, url string) error { scope := c.StatsScope.SubScope("update_status") scope = SetGitScopeTags(scope, repo.FullName, pull.Num) - logger := c.Logger.WithHistory([]interface{}{ - "repository", fmt.Sprintf("%s/%s", repo.Owner, repo.Name), - "pull-num", strconv.Itoa(pull.Num), - "src", src, - "description", description, - "state", state, - "url", url, - }...) executionTime := scope.Timer(metrics.ExecutionTimeMetric).Start() defer executionTime.Stop() @@ -234,7 +216,7 @@ func (c *InstrumentedClient) UpdateStatus(repo models.Repo, pull models.PullRequ executionError := scope.Counter(metrics.ExecutionErrorMetric) logger.Info("updating vcs status") - if err := c.Client.UpdateStatus(repo, pull, state, src, description, url); err != nil { + if err := c.Client.UpdateStatus(logger, repo, pull, state, src, description, url); err != nil { executionError.Inc(1) logger.Err("Unable to update status at url: %s, error: %s", url, err.Error()) return err @@ -244,10 +226,9 @@ func (c *InstrumentedClient) UpdateStatus(repo models.Repo, pull models.PullRequ return nil } -func (c *InstrumentedClient) MergePull(pull models.PullRequest, pullOptions models.PullRequestOptions) error { +func (c *InstrumentedClient) MergePull(logger logging.SimpleLogging, pull models.PullRequest, pullOptions models.PullRequestOptions) error { scope := c.StatsScope.SubScope("merge_pull") scope = SetGitScopeTags(scope, pull.BaseRepo.FullName, pull.Num) - logger := c.Logger.WithHistory("pull-num", pull.Num) executionTime := scope.Timer(metrics.ExecutionTimeMetric).Start() defer executionTime.Stop() @@ -255,7 +236,7 @@ func (c *InstrumentedClient) MergePull(pull models.PullRequest, pullOptions mode executionSuccess := scope.Counter(metrics.ExecutionSuccessMetric) executionError := scope.Counter(metrics.ExecutionErrorMetric) - if err := c.Client.MergePull(pull, pullOptions); err != nil { + if err := c.Client.MergePull(logger, pull, pullOptions); err != nil { executionError.Inc(1) logger.Err("Unable to merge pull, error: %s", err.Error()) return err @@ -265,14 +246,6 @@ func (c *InstrumentedClient) MergePull(pull models.PullRequest, pullOptions mode return nil } -// taken from other parts of the code, would be great to have this in a shared spot -func fmtLogSrc(repo models.Repo, pullNum int) []interface{} { - return []interface{}{ - "repository", repo.FullName, - "pull-num", strconv.Itoa(pullNum), - } -} - func SetGitScopeTags(scope tally.Scope, repoFullName string, pullNum int) tally.Scope { return scope.Tagged(map[string]string{ "base_repo": repoFullName, diff --git a/server/events/vcs/mocks/mock_client.go b/server/events/vcs/mocks/mock_client.go index 5b0bb3051a..ffa37fe8cb 100644 --- a/server/events/vcs/mocks/mock_client.go +++ b/server/events/vcs/mocks/mock_client.go @@ -6,6 +6,7 @@ package mocks import ( pegomock "github.com/petergtz/pegomock/v4" models "github.com/runatlantis/atlantis/server/events/models" + logging "github.com/runatlantis/atlantis/server/logging" "reflect" "time" ) @@ -25,11 +26,11 @@ func NewMockClient(options ...pegomock.Option) *MockClient { func (mock *MockClient) SetFailHandler(fh pegomock.FailHandler) { mock.fail = fh } func (mock *MockClient) FailHandler() pegomock.FailHandler { return mock.fail } -func (mock *MockClient) CreateComment(repo models.Repo, pullNum int, comment string, command string) error { +func (mock *MockClient) CreateComment(logger logging.SimpleLogging, repo models.Repo, pullNum int, comment string, command string) error { if mock == nil { panic("mock must not be nil. Use myMock := NewMockClient().") } - params := []pegomock.Param{repo, pullNum, comment, command} + params := []pegomock.Param{logger, repo, pullNum, comment, command} result := pegomock.GetGenericMockFrom(mock).Invoke("CreateComment", params, []reflect.Type{reflect.TypeOf((*error)(nil)).Elem()}) var ret0 error if len(result) != 0 { @@ -55,11 +56,11 @@ func (mock *MockClient) DiscardReviews(repo models.Repo, pull models.PullRequest return ret0 } -func (mock *MockClient) GetCloneURL(VCSHostType models.VCSHostType, repo string) (string, error) { +func (mock *MockClient) GetCloneURL(logger logging.SimpleLogging, VCSHostType models.VCSHostType, repo string) (string, error) { if mock == nil { panic("mock must not be nil. Use myMock := NewMockClient().") } - params := []pegomock.Param{VCSHostType, repo} + params := []pegomock.Param{logger, VCSHostType, repo} result := pegomock.GetGenericMockFrom(mock).Invoke("GetCloneURL", params, []reflect.Type{reflect.TypeOf((*string)(nil)).Elem(), reflect.TypeOf((*error)(nil)).Elem()}) var ret0 string var ret1 error @@ -74,11 +75,11 @@ func (mock *MockClient) GetCloneURL(VCSHostType models.VCSHostType, repo string) return ret0, ret1 } -func (mock *MockClient) GetFileContent(pull models.PullRequest, fileName string) (bool, []byte, error) { +func (mock *MockClient) GetFileContent(logger logging.SimpleLogging, pull models.PullRequest, fileName string) (bool, []byte, error) { if mock == nil { panic("mock must not be nil. Use myMock := NewMockClient().") } - params := []pegomock.Param{pull, fileName} + params := []pegomock.Param{logger, pull, fileName} result := pegomock.GetGenericMockFrom(mock).Invoke("GetFileContent", params, []reflect.Type{reflect.TypeOf((*bool)(nil)).Elem(), reflect.TypeOf((*[]byte)(nil)).Elem(), reflect.TypeOf((*error)(nil)).Elem()}) var ret0 bool var ret1 []byte @@ -97,11 +98,11 @@ func (mock *MockClient) GetFileContent(pull models.PullRequest, fileName string) return ret0, ret1, ret2 } -func (mock *MockClient) GetModifiedFiles(repo models.Repo, pull models.PullRequest) ([]string, error) { +func (mock *MockClient) GetModifiedFiles(logger logging.SimpleLogging, repo models.Repo, pull models.PullRequest) ([]string, error) { if mock == nil { panic("mock must not be nil. Use myMock := NewMockClient().") } - params := []pegomock.Param{repo, pull} + params := []pegomock.Param{logger, repo, pull} result := pegomock.GetGenericMockFrom(mock).Invoke("GetModifiedFiles", params, []reflect.Type{reflect.TypeOf((*[]string)(nil)).Elem(), reflect.TypeOf((*error)(nil)).Elem()}) var ret0 []string var ret1 error @@ -116,11 +117,11 @@ func (mock *MockClient) GetModifiedFiles(repo models.Repo, pull models.PullReque return ret0, ret1 } -func (mock *MockClient) GetPullLabels(repo models.Repo, pull models.PullRequest) ([]string, error) { +func (mock *MockClient) GetPullLabels(logger logging.SimpleLogging, repo models.Repo, pull models.PullRequest) ([]string, error) { if mock == nil { panic("mock must not be nil. Use myMock := NewMockClient().") } - params := []pegomock.Param{repo, pull} + params := []pegomock.Param{logger, repo, pull} result := pegomock.GetGenericMockFrom(mock).Invoke("GetPullLabels", params, []reflect.Type{reflect.TypeOf((*[]string)(nil)).Elem(), reflect.TypeOf((*error)(nil)).Elem()}) var ret0 []string var ret1 error @@ -154,11 +155,11 @@ func (mock *MockClient) GetTeamNamesForUser(repo models.Repo, user models.User) return ret0, ret1 } -func (mock *MockClient) HidePrevCommandComments(repo models.Repo, pullNum int, command string, dir string) error { +func (mock *MockClient) HidePrevCommandComments(logger logging.SimpleLogging, repo models.Repo, pullNum int, command string, dir string) error { if mock == nil { panic("mock must not be nil. Use myMock := NewMockClient().") } - params := []pegomock.Param{repo, pullNum, command, dir} + params := []pegomock.Param{logger, repo, pullNum, command, dir} result := pegomock.GetGenericMockFrom(mock).Invoke("HidePrevCommandComments", params, []reflect.Type{reflect.TypeOf((*error)(nil)).Elem()}) var ret0 error if len(result) != 0 { @@ -188,11 +189,11 @@ func (mock *MockClient) MarkdownPullLink(pull models.PullRequest) (string, error return ret0, ret1 } -func (mock *MockClient) MergePull(pull models.PullRequest, pullOptions models.PullRequestOptions) error { +func (mock *MockClient) MergePull(logger logging.SimpleLogging, pull models.PullRequest, pullOptions models.PullRequestOptions) error { if mock == nil { panic("mock must not be nil. Use myMock := NewMockClient().") } - params := []pegomock.Param{pull, pullOptions} + params := []pegomock.Param{logger, pull, pullOptions} result := pegomock.GetGenericMockFrom(mock).Invoke("MergePull", params, []reflect.Type{reflect.TypeOf((*error)(nil)).Elem()}) var ret0 error if len(result) != 0 { @@ -203,11 +204,11 @@ func (mock *MockClient) MergePull(pull models.PullRequest, pullOptions models.Pu return ret0 } -func (mock *MockClient) PullIsApproved(repo models.Repo, pull models.PullRequest) (models.ApprovalStatus, error) { +func (mock *MockClient) PullIsApproved(logger logging.SimpleLogging, repo models.Repo, pull models.PullRequest) (models.ApprovalStatus, error) { if mock == nil { panic("mock must not be nil. Use myMock := NewMockClient().") } - params := []pegomock.Param{repo, pull} + params := []pegomock.Param{logger, repo, pull} result := pegomock.GetGenericMockFrom(mock).Invoke("PullIsApproved", params, []reflect.Type{reflect.TypeOf((*models.ApprovalStatus)(nil)).Elem(), reflect.TypeOf((*error)(nil)).Elem()}) var ret0 models.ApprovalStatus var ret1 error @@ -222,11 +223,11 @@ func (mock *MockClient) PullIsApproved(repo models.Repo, pull models.PullRequest return ret0, ret1 } -func (mock *MockClient) PullIsMergeable(repo models.Repo, pull models.PullRequest, vcsstatusname string) (bool, error) { +func (mock *MockClient) PullIsMergeable(logger logging.SimpleLogging, repo models.Repo, pull models.PullRequest, vcsstatusname string) (bool, error) { if mock == nil { panic("mock must not be nil. Use myMock := NewMockClient().") } - params := []pegomock.Param{repo, pull, vcsstatusname} + params := []pegomock.Param{logger, repo, pull, vcsstatusname} result := pegomock.GetGenericMockFrom(mock).Invoke("PullIsMergeable", params, []reflect.Type{reflect.TypeOf((*bool)(nil)).Elem(), reflect.TypeOf((*error)(nil)).Elem()}) var ret0 bool var ret1 error @@ -241,11 +242,11 @@ func (mock *MockClient) PullIsMergeable(repo models.Repo, pull models.PullReques return ret0, ret1 } -func (mock *MockClient) ReactToComment(repo models.Repo, pullNum int, commentID int64, reaction string) error { +func (mock *MockClient) ReactToComment(logger logging.SimpleLogging, repo models.Repo, pullNum int, commentID int64, reaction string) error { if mock == nil { panic("mock must not be nil. Use myMock := NewMockClient().") } - params := []pegomock.Param{repo, pullNum, commentID, reaction} + params := []pegomock.Param{logger, repo, pullNum, commentID, reaction} result := pegomock.GetGenericMockFrom(mock).Invoke("ReactToComment", params, []reflect.Type{reflect.TypeOf((*error)(nil)).Elem()}) var ret0 error if len(result) != 0 { @@ -271,11 +272,11 @@ func (mock *MockClient) SupportsSingleFileDownload(repo models.Repo) bool { return ret0 } -func (mock *MockClient) UpdateStatus(repo models.Repo, pull models.PullRequest, state models.CommitStatus, src string, description string, url string) error { +func (mock *MockClient) UpdateStatus(logger logging.SimpleLogging, repo models.Repo, pull models.PullRequest, state models.CommitStatus, src string, description string, url string) error { if mock == nil { panic("mock must not be nil. Use myMock := NewMockClient().") } - params := []pegomock.Param{repo, pull, state, src, description, url} + params := []pegomock.Param{logger, repo, pull, state, src, description, url} result := pegomock.GetGenericMockFrom(mock).Invoke("UpdateStatus", params, []reflect.Type{reflect.TypeOf((*error)(nil)).Elem()}) var ret0 error if len(result) != 0 { @@ -323,8 +324,8 @@ type VerifierMockClient struct { timeout time.Duration } -func (verifier *VerifierMockClient) CreateComment(repo models.Repo, pullNum int, comment string, command string) *MockClient_CreateComment_OngoingVerification { - params := []pegomock.Param{repo, pullNum, comment, command} +func (verifier *VerifierMockClient) CreateComment(logger logging.SimpleLogging, repo models.Repo, pullNum int, comment string, command string) *MockClient_CreateComment_OngoingVerification { + params := []pegomock.Param{logger, repo, pullNum, comment, command} methodInvocations := pegomock.GetGenericMockFrom(verifier.mock).Verify(verifier.inOrderContext, verifier.invocationCountMatcher, "CreateComment", params, verifier.timeout) return &MockClient_CreateComment_OngoingVerification{mock: verifier.mock, methodInvocations: methodInvocations} } @@ -334,30 +335,34 @@ type MockClient_CreateComment_OngoingVerification struct { methodInvocations []pegomock.MethodInvocation } -func (c *MockClient_CreateComment_OngoingVerification) GetCapturedArguments() (models.Repo, int, string, string) { - repo, pullNum, comment, command := c.GetAllCapturedArguments() - return repo[len(repo)-1], pullNum[len(pullNum)-1], comment[len(comment)-1], command[len(command)-1] +func (c *MockClient_CreateComment_OngoingVerification) GetCapturedArguments() (logging.SimpleLogging, models.Repo, int, string, string) { + logger, repo, pullNum, comment, command := c.GetAllCapturedArguments() + return logger[len(logger)-1], repo[len(repo)-1], pullNum[len(pullNum)-1], comment[len(comment)-1], command[len(command)-1] } -func (c *MockClient_CreateComment_OngoingVerification) GetAllCapturedArguments() (_param0 []models.Repo, _param1 []int, _param2 []string, _param3 []string) { +func (c *MockClient_CreateComment_OngoingVerification) GetAllCapturedArguments() (_param0 []logging.SimpleLogging, _param1 []models.Repo, _param2 []int, _param3 []string, _param4 []string) { params := pegomock.GetGenericMockFrom(c.mock).GetInvocationParams(c.methodInvocations) if len(params) > 0 { - _param0 = make([]models.Repo, len(c.methodInvocations)) + _param0 = make([]logging.SimpleLogging, len(c.methodInvocations)) for u, param := range params[0] { - _param0[u] = param.(models.Repo) + _param0[u] = param.(logging.SimpleLogging) } - _param1 = make([]int, len(c.methodInvocations)) + _param1 = make([]models.Repo, len(c.methodInvocations)) for u, param := range params[1] { - _param1[u] = param.(int) + _param1[u] = param.(models.Repo) } - _param2 = make([]string, len(c.methodInvocations)) + _param2 = make([]int, len(c.methodInvocations)) for u, param := range params[2] { - _param2[u] = param.(string) + _param2[u] = param.(int) } _param3 = make([]string, len(c.methodInvocations)) for u, param := range params[3] { _param3[u] = param.(string) } + _param4 = make([]string, len(c.methodInvocations)) + for u, param := range params[4] { + _param4[u] = param.(string) + } } return } @@ -393,8 +398,8 @@ func (c *MockClient_DiscardReviews_OngoingVerification) GetAllCapturedArguments( return } -func (verifier *VerifierMockClient) GetCloneURL(VCSHostType models.VCSHostType, repo string) *MockClient_GetCloneURL_OngoingVerification { - params := []pegomock.Param{VCSHostType, repo} +func (verifier *VerifierMockClient) GetCloneURL(logger logging.SimpleLogging, VCSHostType models.VCSHostType, repo string) *MockClient_GetCloneURL_OngoingVerification { + params := []pegomock.Param{logger, VCSHostType, repo} methodInvocations := pegomock.GetGenericMockFrom(verifier.mock).Verify(verifier.inOrderContext, verifier.invocationCountMatcher, "GetCloneURL", params, verifier.timeout) return &MockClient_GetCloneURL_OngoingVerification{mock: verifier.mock, methodInvocations: methodInvocations} } @@ -404,28 +409,32 @@ type MockClient_GetCloneURL_OngoingVerification struct { methodInvocations []pegomock.MethodInvocation } -func (c *MockClient_GetCloneURL_OngoingVerification) GetCapturedArguments() (models.VCSHostType, string) { - VCSHostType, repo := c.GetAllCapturedArguments() - return VCSHostType[len(VCSHostType)-1], repo[len(repo)-1] +func (c *MockClient_GetCloneURL_OngoingVerification) GetCapturedArguments() (logging.SimpleLogging, models.VCSHostType, string) { + logger, VCSHostType, repo := c.GetAllCapturedArguments() + return logger[len(logger)-1], VCSHostType[len(VCSHostType)-1], repo[len(repo)-1] } -func (c *MockClient_GetCloneURL_OngoingVerification) GetAllCapturedArguments() (_param0 []models.VCSHostType, _param1 []string) { +func (c *MockClient_GetCloneURL_OngoingVerification) GetAllCapturedArguments() (_param0 []logging.SimpleLogging, _param1 []models.VCSHostType, _param2 []string) { params := pegomock.GetGenericMockFrom(c.mock).GetInvocationParams(c.methodInvocations) if len(params) > 0 { - _param0 = make([]models.VCSHostType, len(c.methodInvocations)) + _param0 = make([]logging.SimpleLogging, len(c.methodInvocations)) for u, param := range params[0] { - _param0[u] = param.(models.VCSHostType) + _param0[u] = param.(logging.SimpleLogging) } - _param1 = make([]string, len(c.methodInvocations)) + _param1 = make([]models.VCSHostType, len(c.methodInvocations)) for u, param := range params[1] { - _param1[u] = param.(string) + _param1[u] = param.(models.VCSHostType) + } + _param2 = make([]string, len(c.methodInvocations)) + for u, param := range params[2] { + _param2[u] = param.(string) } } return } -func (verifier *VerifierMockClient) GetFileContent(pull models.PullRequest, fileName string) *MockClient_GetFileContent_OngoingVerification { - params := []pegomock.Param{pull, fileName} +func (verifier *VerifierMockClient) GetFileContent(logger logging.SimpleLogging, pull models.PullRequest, fileName string) *MockClient_GetFileContent_OngoingVerification { + params := []pegomock.Param{logger, pull, fileName} methodInvocations := pegomock.GetGenericMockFrom(verifier.mock).Verify(verifier.inOrderContext, verifier.invocationCountMatcher, "GetFileContent", params, verifier.timeout) return &MockClient_GetFileContent_OngoingVerification{mock: verifier.mock, methodInvocations: methodInvocations} } @@ -435,28 +444,32 @@ type MockClient_GetFileContent_OngoingVerification struct { methodInvocations []pegomock.MethodInvocation } -func (c *MockClient_GetFileContent_OngoingVerification) GetCapturedArguments() (models.PullRequest, string) { - pull, fileName := c.GetAllCapturedArguments() - return pull[len(pull)-1], fileName[len(fileName)-1] +func (c *MockClient_GetFileContent_OngoingVerification) GetCapturedArguments() (logging.SimpleLogging, models.PullRequest, string) { + logger, pull, fileName := c.GetAllCapturedArguments() + return logger[len(logger)-1], pull[len(pull)-1], fileName[len(fileName)-1] } -func (c *MockClient_GetFileContent_OngoingVerification) GetAllCapturedArguments() (_param0 []models.PullRequest, _param1 []string) { +func (c *MockClient_GetFileContent_OngoingVerification) GetAllCapturedArguments() (_param0 []logging.SimpleLogging, _param1 []models.PullRequest, _param2 []string) { params := pegomock.GetGenericMockFrom(c.mock).GetInvocationParams(c.methodInvocations) if len(params) > 0 { - _param0 = make([]models.PullRequest, len(c.methodInvocations)) + _param0 = make([]logging.SimpleLogging, len(c.methodInvocations)) for u, param := range params[0] { - _param0[u] = param.(models.PullRequest) + _param0[u] = param.(logging.SimpleLogging) } - _param1 = make([]string, len(c.methodInvocations)) + _param1 = make([]models.PullRequest, len(c.methodInvocations)) for u, param := range params[1] { - _param1[u] = param.(string) + _param1[u] = param.(models.PullRequest) + } + _param2 = make([]string, len(c.methodInvocations)) + for u, param := range params[2] { + _param2[u] = param.(string) } } return } -func (verifier *VerifierMockClient) GetModifiedFiles(repo models.Repo, pull models.PullRequest) *MockClient_GetModifiedFiles_OngoingVerification { - params := []pegomock.Param{repo, pull} +func (verifier *VerifierMockClient) GetModifiedFiles(logger logging.SimpleLogging, repo models.Repo, pull models.PullRequest) *MockClient_GetModifiedFiles_OngoingVerification { + params := []pegomock.Param{logger, repo, pull} methodInvocations := pegomock.GetGenericMockFrom(verifier.mock).Verify(verifier.inOrderContext, verifier.invocationCountMatcher, "GetModifiedFiles", params, verifier.timeout) return &MockClient_GetModifiedFiles_OngoingVerification{mock: verifier.mock, methodInvocations: methodInvocations} } @@ -466,28 +479,32 @@ type MockClient_GetModifiedFiles_OngoingVerification struct { methodInvocations []pegomock.MethodInvocation } -func (c *MockClient_GetModifiedFiles_OngoingVerification) GetCapturedArguments() (models.Repo, models.PullRequest) { - repo, pull := c.GetAllCapturedArguments() - return repo[len(repo)-1], pull[len(pull)-1] +func (c *MockClient_GetModifiedFiles_OngoingVerification) GetCapturedArguments() (logging.SimpleLogging, models.Repo, models.PullRequest) { + logger, repo, pull := c.GetAllCapturedArguments() + return logger[len(logger)-1], repo[len(repo)-1], pull[len(pull)-1] } -func (c *MockClient_GetModifiedFiles_OngoingVerification) GetAllCapturedArguments() (_param0 []models.Repo, _param1 []models.PullRequest) { +func (c *MockClient_GetModifiedFiles_OngoingVerification) GetAllCapturedArguments() (_param0 []logging.SimpleLogging, _param1 []models.Repo, _param2 []models.PullRequest) { params := pegomock.GetGenericMockFrom(c.mock).GetInvocationParams(c.methodInvocations) if len(params) > 0 { - _param0 = make([]models.Repo, len(c.methodInvocations)) + _param0 = make([]logging.SimpleLogging, len(c.methodInvocations)) for u, param := range params[0] { - _param0[u] = param.(models.Repo) + _param0[u] = param.(logging.SimpleLogging) } - _param1 = make([]models.PullRequest, len(c.methodInvocations)) + _param1 = make([]models.Repo, len(c.methodInvocations)) for u, param := range params[1] { - _param1[u] = param.(models.PullRequest) + _param1[u] = param.(models.Repo) + } + _param2 = make([]models.PullRequest, len(c.methodInvocations)) + for u, param := range params[2] { + _param2[u] = param.(models.PullRequest) } } return } -func (verifier *VerifierMockClient) GetPullLabels(repo models.Repo, pull models.PullRequest) *MockClient_GetPullLabels_OngoingVerification { - params := []pegomock.Param{repo, pull} +func (verifier *VerifierMockClient) GetPullLabels(logger logging.SimpleLogging, repo models.Repo, pull models.PullRequest) *MockClient_GetPullLabels_OngoingVerification { + params := []pegomock.Param{logger, repo, pull} methodInvocations := pegomock.GetGenericMockFrom(verifier.mock).Verify(verifier.inOrderContext, verifier.invocationCountMatcher, "GetPullLabels", params, verifier.timeout) return &MockClient_GetPullLabels_OngoingVerification{mock: verifier.mock, methodInvocations: methodInvocations} } @@ -497,21 +514,25 @@ type MockClient_GetPullLabels_OngoingVerification struct { methodInvocations []pegomock.MethodInvocation } -func (c *MockClient_GetPullLabels_OngoingVerification) GetCapturedArguments() (models.Repo, models.PullRequest) { - repo, pull := c.GetAllCapturedArguments() - return repo[len(repo)-1], pull[len(pull)-1] +func (c *MockClient_GetPullLabels_OngoingVerification) GetCapturedArguments() (logging.SimpleLogging, models.Repo, models.PullRequest) { + logger, repo, pull := c.GetAllCapturedArguments() + return logger[len(logger)-1], repo[len(repo)-1], pull[len(pull)-1] } -func (c *MockClient_GetPullLabels_OngoingVerification) GetAllCapturedArguments() (_param0 []models.Repo, _param1 []models.PullRequest) { +func (c *MockClient_GetPullLabels_OngoingVerification) GetAllCapturedArguments() (_param0 []logging.SimpleLogging, _param1 []models.Repo, _param2 []models.PullRequest) { params := pegomock.GetGenericMockFrom(c.mock).GetInvocationParams(c.methodInvocations) if len(params) > 0 { - _param0 = make([]models.Repo, len(c.methodInvocations)) + _param0 = make([]logging.SimpleLogging, len(c.methodInvocations)) for u, param := range params[0] { - _param0[u] = param.(models.Repo) + _param0[u] = param.(logging.SimpleLogging) } - _param1 = make([]models.PullRequest, len(c.methodInvocations)) + _param1 = make([]models.Repo, len(c.methodInvocations)) for u, param := range params[1] { - _param1[u] = param.(models.PullRequest) + _param1[u] = param.(models.Repo) + } + _param2 = make([]models.PullRequest, len(c.methodInvocations)) + for u, param := range params[2] { + _param2[u] = param.(models.PullRequest) } } return @@ -548,8 +569,8 @@ func (c *MockClient_GetTeamNamesForUser_OngoingVerification) GetAllCapturedArgum return } -func (verifier *VerifierMockClient) HidePrevCommandComments(repo models.Repo, pullNum int, command string, dir string) *MockClient_HidePrevCommandComments_OngoingVerification { - params := []pegomock.Param{repo, pullNum, command, dir} +func (verifier *VerifierMockClient) HidePrevCommandComments(logger logging.SimpleLogging, repo models.Repo, pullNum int, command string, dir string) *MockClient_HidePrevCommandComments_OngoingVerification { + params := []pegomock.Param{logger, repo, pullNum, command, dir} methodInvocations := pegomock.GetGenericMockFrom(verifier.mock).Verify(verifier.inOrderContext, verifier.invocationCountMatcher, "HidePrevCommandComments", params, verifier.timeout) return &MockClient_HidePrevCommandComments_OngoingVerification{mock: verifier.mock, methodInvocations: methodInvocations} } @@ -559,30 +580,34 @@ type MockClient_HidePrevCommandComments_OngoingVerification struct { methodInvocations []pegomock.MethodInvocation } -func (c *MockClient_HidePrevCommandComments_OngoingVerification) GetCapturedArguments() (models.Repo, int, string, string) { - repo, pullNum, command, dir := c.GetAllCapturedArguments() - return repo[len(repo)-1], pullNum[len(pullNum)-1], command[len(command)-1], dir[len(dir)-1] +func (c *MockClient_HidePrevCommandComments_OngoingVerification) GetCapturedArguments() (logging.SimpleLogging, models.Repo, int, string, string) { + logger, repo, pullNum, command, dir := c.GetAllCapturedArguments() + return logger[len(logger)-1], repo[len(repo)-1], pullNum[len(pullNum)-1], command[len(command)-1], dir[len(dir)-1] } -func (c *MockClient_HidePrevCommandComments_OngoingVerification) GetAllCapturedArguments() (_param0 []models.Repo, _param1 []int, _param2 []string, _param3 []string) { +func (c *MockClient_HidePrevCommandComments_OngoingVerification) GetAllCapturedArguments() (_param0 []logging.SimpleLogging, _param1 []models.Repo, _param2 []int, _param3 []string, _param4 []string) { params := pegomock.GetGenericMockFrom(c.mock).GetInvocationParams(c.methodInvocations) if len(params) > 0 { - _param0 = make([]models.Repo, len(c.methodInvocations)) + _param0 = make([]logging.SimpleLogging, len(c.methodInvocations)) for u, param := range params[0] { - _param0[u] = param.(models.Repo) + _param0[u] = param.(logging.SimpleLogging) } - _param1 = make([]int, len(c.methodInvocations)) + _param1 = make([]models.Repo, len(c.methodInvocations)) for u, param := range params[1] { - _param1[u] = param.(int) + _param1[u] = param.(models.Repo) } - _param2 = make([]string, len(c.methodInvocations)) + _param2 = make([]int, len(c.methodInvocations)) for u, param := range params[2] { - _param2[u] = param.(string) + _param2[u] = param.(int) } _param3 = make([]string, len(c.methodInvocations)) for u, param := range params[3] { _param3[u] = param.(string) } + _param4 = make([]string, len(c.methodInvocations)) + for u, param := range params[4] { + _param4[u] = param.(string) + } } return } @@ -614,8 +639,8 @@ func (c *MockClient_MarkdownPullLink_OngoingVerification) GetAllCapturedArgument return } -func (verifier *VerifierMockClient) MergePull(pull models.PullRequest, pullOptions models.PullRequestOptions) *MockClient_MergePull_OngoingVerification { - params := []pegomock.Param{pull, pullOptions} +func (verifier *VerifierMockClient) MergePull(logger logging.SimpleLogging, pull models.PullRequest, pullOptions models.PullRequestOptions) *MockClient_MergePull_OngoingVerification { + params := []pegomock.Param{logger, pull, pullOptions} methodInvocations := pegomock.GetGenericMockFrom(verifier.mock).Verify(verifier.inOrderContext, verifier.invocationCountMatcher, "MergePull", params, verifier.timeout) return &MockClient_MergePull_OngoingVerification{mock: verifier.mock, methodInvocations: methodInvocations} } @@ -625,28 +650,32 @@ type MockClient_MergePull_OngoingVerification struct { methodInvocations []pegomock.MethodInvocation } -func (c *MockClient_MergePull_OngoingVerification) GetCapturedArguments() (models.PullRequest, models.PullRequestOptions) { - pull, pullOptions := c.GetAllCapturedArguments() - return pull[len(pull)-1], pullOptions[len(pullOptions)-1] +func (c *MockClient_MergePull_OngoingVerification) GetCapturedArguments() (logging.SimpleLogging, models.PullRequest, models.PullRequestOptions) { + logger, pull, pullOptions := c.GetAllCapturedArguments() + return logger[len(logger)-1], pull[len(pull)-1], pullOptions[len(pullOptions)-1] } -func (c *MockClient_MergePull_OngoingVerification) GetAllCapturedArguments() (_param0 []models.PullRequest, _param1 []models.PullRequestOptions) { +func (c *MockClient_MergePull_OngoingVerification) GetAllCapturedArguments() (_param0 []logging.SimpleLogging, _param1 []models.PullRequest, _param2 []models.PullRequestOptions) { params := pegomock.GetGenericMockFrom(c.mock).GetInvocationParams(c.methodInvocations) if len(params) > 0 { - _param0 = make([]models.PullRequest, len(c.methodInvocations)) + _param0 = make([]logging.SimpleLogging, len(c.methodInvocations)) for u, param := range params[0] { - _param0[u] = param.(models.PullRequest) + _param0[u] = param.(logging.SimpleLogging) } - _param1 = make([]models.PullRequestOptions, len(c.methodInvocations)) + _param1 = make([]models.PullRequest, len(c.methodInvocations)) for u, param := range params[1] { - _param1[u] = param.(models.PullRequestOptions) + _param1[u] = param.(models.PullRequest) + } + _param2 = make([]models.PullRequestOptions, len(c.methodInvocations)) + for u, param := range params[2] { + _param2[u] = param.(models.PullRequestOptions) } } return } -func (verifier *VerifierMockClient) PullIsApproved(repo models.Repo, pull models.PullRequest) *MockClient_PullIsApproved_OngoingVerification { - params := []pegomock.Param{repo, pull} +func (verifier *VerifierMockClient) PullIsApproved(logger logging.SimpleLogging, repo models.Repo, pull models.PullRequest) *MockClient_PullIsApproved_OngoingVerification { + params := []pegomock.Param{logger, repo, pull} methodInvocations := pegomock.GetGenericMockFrom(verifier.mock).Verify(verifier.inOrderContext, verifier.invocationCountMatcher, "PullIsApproved", params, verifier.timeout) return &MockClient_PullIsApproved_OngoingVerification{mock: verifier.mock, methodInvocations: methodInvocations} } @@ -656,28 +685,32 @@ type MockClient_PullIsApproved_OngoingVerification struct { methodInvocations []pegomock.MethodInvocation } -func (c *MockClient_PullIsApproved_OngoingVerification) GetCapturedArguments() (models.Repo, models.PullRequest) { - repo, pull := c.GetAllCapturedArguments() - return repo[len(repo)-1], pull[len(pull)-1] +func (c *MockClient_PullIsApproved_OngoingVerification) GetCapturedArguments() (logging.SimpleLogging, models.Repo, models.PullRequest) { + logger, repo, pull := c.GetAllCapturedArguments() + return logger[len(logger)-1], repo[len(repo)-1], pull[len(pull)-1] } -func (c *MockClient_PullIsApproved_OngoingVerification) GetAllCapturedArguments() (_param0 []models.Repo, _param1 []models.PullRequest) { +func (c *MockClient_PullIsApproved_OngoingVerification) GetAllCapturedArguments() (_param0 []logging.SimpleLogging, _param1 []models.Repo, _param2 []models.PullRequest) { params := pegomock.GetGenericMockFrom(c.mock).GetInvocationParams(c.methodInvocations) if len(params) > 0 { - _param0 = make([]models.Repo, len(c.methodInvocations)) + _param0 = make([]logging.SimpleLogging, len(c.methodInvocations)) for u, param := range params[0] { - _param0[u] = param.(models.Repo) + _param0[u] = param.(logging.SimpleLogging) } - _param1 = make([]models.PullRequest, len(c.methodInvocations)) + _param1 = make([]models.Repo, len(c.methodInvocations)) for u, param := range params[1] { - _param1[u] = param.(models.PullRequest) + _param1[u] = param.(models.Repo) + } + _param2 = make([]models.PullRequest, len(c.methodInvocations)) + for u, param := range params[2] { + _param2[u] = param.(models.PullRequest) } } return } -func (verifier *VerifierMockClient) PullIsMergeable(repo models.Repo, pull models.PullRequest, vcsstatusname string) *MockClient_PullIsMergeable_OngoingVerification { - params := []pegomock.Param{repo, pull, vcsstatusname} +func (verifier *VerifierMockClient) PullIsMergeable(logger logging.SimpleLogging, repo models.Repo, pull models.PullRequest, vcsstatusname string) *MockClient_PullIsMergeable_OngoingVerification { + params := []pegomock.Param{logger, repo, pull, vcsstatusname} methodInvocations := pegomock.GetGenericMockFrom(verifier.mock).Verify(verifier.inOrderContext, verifier.invocationCountMatcher, "PullIsMergeable", params, verifier.timeout) return &MockClient_PullIsMergeable_OngoingVerification{mock: verifier.mock, methodInvocations: methodInvocations} } @@ -687,32 +720,36 @@ type MockClient_PullIsMergeable_OngoingVerification struct { methodInvocations []pegomock.MethodInvocation } -func (c *MockClient_PullIsMergeable_OngoingVerification) GetCapturedArguments() (models.Repo, models.PullRequest, string) { - repo, pull, vcsstatusname := c.GetAllCapturedArguments() - return repo[len(repo)-1], pull[len(pull)-1], vcsstatusname[len(vcsstatusname)-1] +func (c *MockClient_PullIsMergeable_OngoingVerification) GetCapturedArguments() (logging.SimpleLogging, models.Repo, models.PullRequest, string) { + logger, repo, pull, vcsstatusname := c.GetAllCapturedArguments() + return logger[len(logger)-1], repo[len(repo)-1], pull[len(pull)-1], vcsstatusname[len(vcsstatusname)-1] } -func (c *MockClient_PullIsMergeable_OngoingVerification) GetAllCapturedArguments() (_param0 []models.Repo, _param1 []models.PullRequest, _param2 []string) { +func (c *MockClient_PullIsMergeable_OngoingVerification) GetAllCapturedArguments() (_param0 []logging.SimpleLogging, _param1 []models.Repo, _param2 []models.PullRequest, _param3 []string) { params := pegomock.GetGenericMockFrom(c.mock).GetInvocationParams(c.methodInvocations) if len(params) > 0 { - _param0 = make([]models.Repo, len(c.methodInvocations)) + _param0 = make([]logging.SimpleLogging, len(c.methodInvocations)) for u, param := range params[0] { - _param0[u] = param.(models.Repo) + _param0[u] = param.(logging.SimpleLogging) } - _param1 = make([]models.PullRequest, len(c.methodInvocations)) + _param1 = make([]models.Repo, len(c.methodInvocations)) for u, param := range params[1] { - _param1[u] = param.(models.PullRequest) + _param1[u] = param.(models.Repo) } - _param2 = make([]string, len(c.methodInvocations)) + _param2 = make([]models.PullRequest, len(c.methodInvocations)) for u, param := range params[2] { - _param2[u] = param.(string) + _param2[u] = param.(models.PullRequest) + } + _param3 = make([]string, len(c.methodInvocations)) + for u, param := range params[3] { + _param3[u] = param.(string) } } return } -func (verifier *VerifierMockClient) ReactToComment(repo models.Repo, pullNum int, commentID int64, reaction string) *MockClient_ReactToComment_OngoingVerification { - params := []pegomock.Param{repo, pullNum, commentID, reaction} +func (verifier *VerifierMockClient) ReactToComment(logger logging.SimpleLogging, repo models.Repo, pullNum int, commentID int64, reaction string) *MockClient_ReactToComment_OngoingVerification { + params := []pegomock.Param{logger, repo, pullNum, commentID, reaction} methodInvocations := pegomock.GetGenericMockFrom(verifier.mock).Verify(verifier.inOrderContext, verifier.invocationCountMatcher, "ReactToComment", params, verifier.timeout) return &MockClient_ReactToComment_OngoingVerification{mock: verifier.mock, methodInvocations: methodInvocations} } @@ -722,29 +759,33 @@ type MockClient_ReactToComment_OngoingVerification struct { methodInvocations []pegomock.MethodInvocation } -func (c *MockClient_ReactToComment_OngoingVerification) GetCapturedArguments() (models.Repo, int, int64, string) { - repo, pullNum, commentID, reaction := c.GetAllCapturedArguments() - return repo[len(repo)-1], pullNum[len(pullNum)-1], commentID[len(commentID)-1], reaction[len(reaction)-1] +func (c *MockClient_ReactToComment_OngoingVerification) GetCapturedArguments() (logging.SimpleLogging, models.Repo, int, int64, string) { + logger, repo, pullNum, commentID, reaction := c.GetAllCapturedArguments() + return logger[len(logger)-1], repo[len(repo)-1], pullNum[len(pullNum)-1], commentID[len(commentID)-1], reaction[len(reaction)-1] } -func (c *MockClient_ReactToComment_OngoingVerification) GetAllCapturedArguments() (_param0 []models.Repo, _param1 []int, _param2 []int64, _param3 []string) { +func (c *MockClient_ReactToComment_OngoingVerification) GetAllCapturedArguments() (_param0 []logging.SimpleLogging, _param1 []models.Repo, _param2 []int, _param3 []int64, _param4 []string) { params := pegomock.GetGenericMockFrom(c.mock).GetInvocationParams(c.methodInvocations) if len(params) > 0 { - _param0 = make([]models.Repo, len(c.methodInvocations)) + _param0 = make([]logging.SimpleLogging, len(c.methodInvocations)) for u, param := range params[0] { - _param0[u] = param.(models.Repo) + _param0[u] = param.(logging.SimpleLogging) } - _param1 = make([]int, len(c.methodInvocations)) + _param1 = make([]models.Repo, len(c.methodInvocations)) for u, param := range params[1] { - _param1[u] = param.(int) + _param1[u] = param.(models.Repo) } - _param2 = make([]int64, len(c.methodInvocations)) + _param2 = make([]int, len(c.methodInvocations)) for u, param := range params[2] { - _param2[u] = param.(int64) + _param2[u] = param.(int) } - _param3 = make([]string, len(c.methodInvocations)) + _param3 = make([]int64, len(c.methodInvocations)) for u, param := range params[3] { - _param3[u] = param.(string) + _param3[u] = param.(int64) + } + _param4 = make([]string, len(c.methodInvocations)) + for u, param := range params[4] { + _param4[u] = param.(string) } } return @@ -777,8 +818,8 @@ func (c *MockClient_SupportsSingleFileDownload_OngoingVerification) GetAllCaptur return } -func (verifier *VerifierMockClient) UpdateStatus(repo models.Repo, pull models.PullRequest, state models.CommitStatus, src string, description string, url string) *MockClient_UpdateStatus_OngoingVerification { - params := []pegomock.Param{repo, pull, state, src, description, url} +func (verifier *VerifierMockClient) UpdateStatus(logger logging.SimpleLogging, repo models.Repo, pull models.PullRequest, state models.CommitStatus, src string, description string, url string) *MockClient_UpdateStatus_OngoingVerification { + params := []pegomock.Param{logger, repo, pull, state, src, description, url} methodInvocations := pegomock.GetGenericMockFrom(verifier.mock).Verify(verifier.inOrderContext, verifier.invocationCountMatcher, "UpdateStatus", params, verifier.timeout) return &MockClient_UpdateStatus_OngoingVerification{mock: verifier.mock, methodInvocations: methodInvocations} } @@ -788,29 +829,29 @@ type MockClient_UpdateStatus_OngoingVerification struct { methodInvocations []pegomock.MethodInvocation } -func (c *MockClient_UpdateStatus_OngoingVerification) GetCapturedArguments() (models.Repo, models.PullRequest, models.CommitStatus, string, string, string) { - repo, pull, state, src, description, url := c.GetAllCapturedArguments() - return repo[len(repo)-1], pull[len(pull)-1], state[len(state)-1], src[len(src)-1], description[len(description)-1], url[len(url)-1] +func (c *MockClient_UpdateStatus_OngoingVerification) GetCapturedArguments() (logging.SimpleLogging, models.Repo, models.PullRequest, models.CommitStatus, string, string, string) { + logger, repo, pull, state, src, description, url := c.GetAllCapturedArguments() + return logger[len(logger)-1], repo[len(repo)-1], pull[len(pull)-1], state[len(state)-1], src[len(src)-1], description[len(description)-1], url[len(url)-1] } -func (c *MockClient_UpdateStatus_OngoingVerification) GetAllCapturedArguments() (_param0 []models.Repo, _param1 []models.PullRequest, _param2 []models.CommitStatus, _param3 []string, _param4 []string, _param5 []string) { +func (c *MockClient_UpdateStatus_OngoingVerification) GetAllCapturedArguments() (_param0 []logging.SimpleLogging, _param1 []models.Repo, _param2 []models.PullRequest, _param3 []models.CommitStatus, _param4 []string, _param5 []string, _param6 []string) { params := pegomock.GetGenericMockFrom(c.mock).GetInvocationParams(c.methodInvocations) if len(params) > 0 { - _param0 = make([]models.Repo, len(c.methodInvocations)) + _param0 = make([]logging.SimpleLogging, len(c.methodInvocations)) for u, param := range params[0] { - _param0[u] = param.(models.Repo) + _param0[u] = param.(logging.SimpleLogging) } - _param1 = make([]models.PullRequest, len(c.methodInvocations)) + _param1 = make([]models.Repo, len(c.methodInvocations)) for u, param := range params[1] { - _param1[u] = param.(models.PullRequest) + _param1[u] = param.(models.Repo) } - _param2 = make([]models.CommitStatus, len(c.methodInvocations)) + _param2 = make([]models.PullRequest, len(c.methodInvocations)) for u, param := range params[2] { - _param2[u] = param.(models.CommitStatus) + _param2[u] = param.(models.PullRequest) } - _param3 = make([]string, len(c.methodInvocations)) + _param3 = make([]models.CommitStatus, len(c.methodInvocations)) for u, param := range params[3] { - _param3[u] = param.(string) + _param3[u] = param.(models.CommitStatus) } _param4 = make([]string, len(c.methodInvocations)) for u, param := range params[4] { @@ -820,6 +861,10 @@ func (c *MockClient_UpdateStatus_OngoingVerification) GetAllCapturedArguments() for u, param := range params[5] { _param5[u] = param.(string) } + _param6 = make([]string, len(c.methodInvocations)) + for u, param := range params[6] { + _param6[u] = param.(string) + } } return } diff --git a/server/events/vcs/mocks/mock_pull_req_status_fetcher.go b/server/events/vcs/mocks/mock_pull_req_status_fetcher.go index 3e13d29990..d9e6494d9a 100644 --- a/server/events/vcs/mocks/mock_pull_req_status_fetcher.go +++ b/server/events/vcs/mocks/mock_pull_req_status_fetcher.go @@ -6,6 +6,7 @@ package mocks import ( pegomock "github.com/petergtz/pegomock/v4" models "github.com/runatlantis/atlantis/server/events/models" + logging "github.com/runatlantis/atlantis/server/logging" "reflect" "time" ) @@ -25,11 +26,11 @@ func NewMockPullReqStatusFetcher(options ...pegomock.Option) *MockPullReqStatusF func (mock *MockPullReqStatusFetcher) SetFailHandler(fh pegomock.FailHandler) { mock.fail = fh } func (mock *MockPullReqStatusFetcher) FailHandler() pegomock.FailHandler { return mock.fail } -func (mock *MockPullReqStatusFetcher) FetchPullStatus(pull models.PullRequest) (models.PullReqStatus, error) { +func (mock *MockPullReqStatusFetcher) FetchPullStatus(logger logging.SimpleLogging, pull models.PullRequest) (models.PullReqStatus, error) { if mock == nil { panic("mock must not be nil. Use myMock := NewMockPullReqStatusFetcher().") } - params := []pegomock.Param{pull} + params := []pegomock.Param{logger, pull} result := pegomock.GetGenericMockFrom(mock).Invoke("FetchPullStatus", params, []reflect.Type{reflect.TypeOf((*models.PullReqStatus)(nil)).Elem(), reflect.TypeOf((*error)(nil)).Elem()}) var ret0 models.PullReqStatus var ret1 error @@ -81,8 +82,8 @@ type VerifierMockPullReqStatusFetcher struct { timeout time.Duration } -func (verifier *VerifierMockPullReqStatusFetcher) FetchPullStatus(pull models.PullRequest) *MockPullReqStatusFetcher_FetchPullStatus_OngoingVerification { - params := []pegomock.Param{pull} +func (verifier *VerifierMockPullReqStatusFetcher) FetchPullStatus(logger logging.SimpleLogging, pull models.PullRequest) *MockPullReqStatusFetcher_FetchPullStatus_OngoingVerification { + params := []pegomock.Param{logger, pull} methodInvocations := pegomock.GetGenericMockFrom(verifier.mock).Verify(verifier.inOrderContext, verifier.invocationCountMatcher, "FetchPullStatus", params, verifier.timeout) return &MockPullReqStatusFetcher_FetchPullStatus_OngoingVerification{mock: verifier.mock, methodInvocations: methodInvocations} } @@ -92,17 +93,21 @@ type MockPullReqStatusFetcher_FetchPullStatus_OngoingVerification struct { methodInvocations []pegomock.MethodInvocation } -func (c *MockPullReqStatusFetcher_FetchPullStatus_OngoingVerification) GetCapturedArguments() models.PullRequest { - pull := c.GetAllCapturedArguments() - return pull[len(pull)-1] +func (c *MockPullReqStatusFetcher_FetchPullStatus_OngoingVerification) GetCapturedArguments() (logging.SimpleLogging, models.PullRequest) { + logger, pull := c.GetAllCapturedArguments() + return logger[len(logger)-1], pull[len(pull)-1] } -func (c *MockPullReqStatusFetcher_FetchPullStatus_OngoingVerification) GetAllCapturedArguments() (_param0 []models.PullRequest) { +func (c *MockPullReqStatusFetcher_FetchPullStatus_OngoingVerification) GetAllCapturedArguments() (_param0 []logging.SimpleLogging, _param1 []models.PullRequest) { params := pegomock.GetGenericMockFrom(c.mock).GetInvocationParams(c.methodInvocations) if len(params) > 0 { - _param0 = make([]models.PullRequest, len(c.methodInvocations)) + _param0 = make([]logging.SimpleLogging, len(c.methodInvocations)) for u, param := range params[0] { - _param0[u] = param.(models.PullRequest) + _param0[u] = param.(logging.SimpleLogging) + } + _param1 = make([]models.PullRequest, len(c.methodInvocations)) + for u, param := range params[1] { + _param1[u] = param.(models.PullRequest) } } return diff --git a/server/events/vcs/not_configured_vcs_client.go b/server/events/vcs/not_configured_vcs_client.go index b7eed9e900..6fd7a731cb 100644 --- a/server/events/vcs/not_configured_vcs_client.go +++ b/server/events/vcs/not_configured_vcs_client.go @@ -17,6 +17,7 @@ import ( "fmt" "github.com/runatlantis/atlantis/server/events/models" + "github.com/runatlantis/atlantis/server/logging" ) // NotConfiguredVCSClient is used as a placeholder when Atlantis isn't configured @@ -26,31 +27,31 @@ type NotConfiguredVCSClient struct { Host models.VCSHostType } -func (a *NotConfiguredVCSClient) GetModifiedFiles(_ models.Repo, _ models.PullRequest) ([]string, error) { +func (a *NotConfiguredVCSClient) GetModifiedFiles(_ logging.SimpleLogging, _ models.Repo, _ models.PullRequest) ([]string, error) { return nil, a.err() } -func (a *NotConfiguredVCSClient) CreateComment(_ models.Repo, _ int, _ string, _ string) error { +func (a *NotConfiguredVCSClient) CreateComment(_ logging.SimpleLogging, _ models.Repo, _ int, _ string, _ string) error { return a.err() } -func (a *NotConfiguredVCSClient) HidePrevCommandComments(_ models.Repo, _ int, _ string, _ string) error { +func (a *NotConfiguredVCSClient) HidePrevCommandComments(_ logging.SimpleLogging, _ models.Repo, _ int, _ string, _ string) error { return nil } -func (a *NotConfiguredVCSClient) ReactToComment(repo models.Repo, pullNum int, commentID int64, reaction string) error { // nolint: revive +func (a *NotConfiguredVCSClient) ReactToComment(logger logging.SimpleLogging, repo models.Repo, pullNum int, commentID int64, reaction string) error { // nolint: revive return nil } -func (a *NotConfiguredVCSClient) PullIsApproved(_ models.Repo, _ models.PullRequest) (models.ApprovalStatus, error) { +func (a *NotConfiguredVCSClient) PullIsApproved(_ logging.SimpleLogging, _ models.Repo, _ models.PullRequest) (models.ApprovalStatus, error) { return models.ApprovalStatus{}, a.err() } func (a *NotConfiguredVCSClient) DiscardReviews(_ models.Repo, _ models.PullRequest) error { return nil } -func (a *NotConfiguredVCSClient) PullIsMergeable(_ models.Repo, _ models.PullRequest, _ string) (bool, error) { +func (a *NotConfiguredVCSClient) PullIsMergeable(_ logging.SimpleLogging, _ models.Repo, _ models.PullRequest, _ string) (bool, error) { return false, a.err() } -func (a *NotConfiguredVCSClient) UpdateStatus(_ models.Repo, _ models.PullRequest, _ models.CommitStatus, _ string, _ string, _ string) error { +func (a *NotConfiguredVCSClient) UpdateStatus(_ logging.SimpleLogging, _ models.Repo, _ models.PullRequest, _ models.CommitStatus, _ string, _ string, _ string) error { return a.err() } -func (a *NotConfiguredVCSClient) MergePull(_ models.PullRequest, _ models.PullRequestOptions) error { +func (a *NotConfiguredVCSClient) MergePull(_ logging.SimpleLogging, _ models.PullRequest, _ models.PullRequestOptions) error { return a.err() } func (a *NotConfiguredVCSClient) MarkdownPullLink(_ models.PullRequest) (string, error) { @@ -67,13 +68,13 @@ func (a *NotConfiguredVCSClient) SupportsSingleFileDownload(_ models.Repo) bool return false } -func (a *NotConfiguredVCSClient) GetFileContent(_ models.PullRequest, _ string) (bool, []byte, error) { +func (a *NotConfiguredVCSClient) GetFileContent(_ logging.SimpleLogging, _ models.PullRequest, _ string) (bool, []byte, error) { return true, []byte{}, a.err() } -func (a *NotConfiguredVCSClient) GetCloneURL(_ models.VCSHostType, _ string) (string, error) { +func (a *NotConfiguredVCSClient) GetCloneURL(_ logging.SimpleLogging, _ models.VCSHostType, _ string) (string, error) { return "", a.err() } -func (a *NotConfiguredVCSClient) GetPullLabels(_ models.Repo, _ models.PullRequest) ([]string, error) { +func (a *NotConfiguredVCSClient) GetPullLabels(_ logging.SimpleLogging, _ models.Repo, _ models.PullRequest) ([]string, error) { return nil, a.err() } diff --git a/server/events/vcs/proxy.go b/server/events/vcs/proxy.go index 768b0b6255..d3d60b03fb 100644 --- a/server/events/vcs/proxy.go +++ b/server/events/vcs/proxy.go @@ -15,6 +15,7 @@ package vcs import ( "github.com/runatlantis/atlantis/server/events/models" + "github.com/runatlantis/atlantis/server/logging" ) // ClientProxy proxies calls to the correct VCS client depending on which @@ -52,40 +53,40 @@ func NewClientProxy(githubClient Client, gitlabClient Client, bitbucketCloudClie } } -func (d *ClientProxy) GetModifiedFiles(repo models.Repo, pull models.PullRequest) ([]string, error) { - return d.clients[repo.VCSHost.Type].GetModifiedFiles(repo, pull) +func (d *ClientProxy) GetModifiedFiles(logger logging.SimpleLogging, repo models.Repo, pull models.PullRequest) ([]string, error) { + return d.clients[repo.VCSHost.Type].GetModifiedFiles(logger, repo, pull) } -func (d *ClientProxy) CreateComment(repo models.Repo, pullNum int, comment string, command string) error { - return d.clients[repo.VCSHost.Type].CreateComment(repo, pullNum, comment, command) +func (d *ClientProxy) CreateComment(logger logging.SimpleLogging, repo models.Repo, pullNum int, comment string, command string) error { + return d.clients[repo.VCSHost.Type].CreateComment(logger, repo, pullNum, comment, command) } -func (d *ClientProxy) HidePrevCommandComments(repo models.Repo, pullNum int, command string, dir string) error { - return d.clients[repo.VCSHost.Type].HidePrevCommandComments(repo, pullNum, command, dir) +func (d *ClientProxy) HidePrevCommandComments(logger logging.SimpleLogging, repo models.Repo, pullNum int, command string, dir string) error { + return d.clients[repo.VCSHost.Type].HidePrevCommandComments(logger, repo, pullNum, command, dir) } -func (d *ClientProxy) ReactToComment(repo models.Repo, pullNum int, commentID int64, reaction string) error { - return d.clients[repo.VCSHost.Type].ReactToComment(repo, pullNum, commentID, reaction) +func (d *ClientProxy) ReactToComment(logger logging.SimpleLogging, repo models.Repo, pullNum int, commentID int64, reaction string) error { + return d.clients[repo.VCSHost.Type].ReactToComment(logger, repo, pullNum, commentID, reaction) } -func (d *ClientProxy) PullIsApproved(repo models.Repo, pull models.PullRequest) (models.ApprovalStatus, error) { - return d.clients[repo.VCSHost.Type].PullIsApproved(repo, pull) +func (d *ClientProxy) PullIsApproved(logger logging.SimpleLogging, repo models.Repo, pull models.PullRequest) (models.ApprovalStatus, error) { + return d.clients[repo.VCSHost.Type].PullIsApproved(logger, repo, pull) } func (d *ClientProxy) DiscardReviews(repo models.Repo, pull models.PullRequest) error { return d.clients[repo.VCSHost.Type].DiscardReviews(repo, pull) } -func (d *ClientProxy) PullIsMergeable(repo models.Repo, pull models.PullRequest, vcsstatusname string) (bool, error) { - return d.clients[repo.VCSHost.Type].PullIsMergeable(repo, pull, vcsstatusname) +func (d *ClientProxy) PullIsMergeable(logger logging.SimpleLogging, repo models.Repo, pull models.PullRequest, vcsstatusname string) (bool, error) { + return d.clients[repo.VCSHost.Type].PullIsMergeable(logger, repo, pull, vcsstatusname) } -func (d *ClientProxy) UpdateStatus(repo models.Repo, pull models.PullRequest, state models.CommitStatus, src string, description string, url string) error { - return d.clients[repo.VCSHost.Type].UpdateStatus(repo, pull, state, src, description, url) +func (d *ClientProxy) UpdateStatus(logger logging.SimpleLogging, repo models.Repo, pull models.PullRequest, state models.CommitStatus, src string, description string, url string) error { + return d.clients[repo.VCSHost.Type].UpdateStatus(logger, repo, pull, state, src, description, url) } -func (d *ClientProxy) MergePull(pull models.PullRequest, pullOptions models.PullRequestOptions) error { - return d.clients[pull.BaseRepo.VCSHost.Type].MergePull(pull, pullOptions) +func (d *ClientProxy) MergePull(logger logging.SimpleLogging, pull models.PullRequest, pullOptions models.PullRequestOptions) error { + return d.clients[pull.BaseRepo.VCSHost.Type].MergePull(logger, pull, pullOptions) } func (d *ClientProxy) MarkdownPullLink(pull models.PullRequest) (string, error) { @@ -96,18 +97,18 @@ func (d *ClientProxy) GetTeamNamesForUser(repo models.Repo, user models.User) ([ return d.clients[repo.VCSHost.Type].GetTeamNamesForUser(repo, user) } -func (d *ClientProxy) GetFileContent(pull models.PullRequest, fileName string) (bool, []byte, error) { - return d.clients[pull.BaseRepo.VCSHost.Type].GetFileContent(pull, fileName) +func (d *ClientProxy) GetFileContent(logger logging.SimpleLogging, pull models.PullRequest, fileName string) (bool, []byte, error) { + return d.clients[pull.BaseRepo.VCSHost.Type].GetFileContent(logger, pull, fileName) } func (d *ClientProxy) SupportsSingleFileDownload(repo models.Repo) bool { return d.clients[repo.VCSHost.Type].SupportsSingleFileDownload(repo) } -func (d *ClientProxy) GetCloneURL(VCSHostType models.VCSHostType, repo string) (string, error) { - return d.clients[VCSHostType].GetCloneURL(VCSHostType, repo) +func (d *ClientProxy) GetCloneURL(logger logging.SimpleLogging, VCSHostType models.VCSHostType, repo string) (string, error) { + return d.clients[VCSHostType].GetCloneURL(logger, VCSHostType, repo) } -func (d *ClientProxy) GetPullLabels(repo models.Repo, pull models.PullRequest) ([]string, error) { - return d.clients[repo.VCSHost.Type].GetPullLabels(repo, pull) +func (d *ClientProxy) GetPullLabels(logger logging.SimpleLogging, repo models.Repo, pull models.PullRequest) ([]string, error) { + return d.clients[repo.VCSHost.Type].GetPullLabels(logger, repo, pull) } diff --git a/server/events/vcs/pull_status_fetcher.go b/server/events/vcs/pull_status_fetcher.go index 43aef1183c..b5b8a46383 100644 --- a/server/events/vcs/pull_status_fetcher.go +++ b/server/events/vcs/pull_status_fetcher.go @@ -3,12 +3,13 @@ package vcs import ( "github.com/pkg/errors" "github.com/runatlantis/atlantis/server/events/models" + "github.com/runatlantis/atlantis/server/logging" ) -//go:generate pegomock generate --package mocks -o mocks/mock_pull_req_status_fetcher.go PullReqStatusFetcher +//go:generate pegomock generate github.com/runatlantis/atlantis/server/events/vcs --package mocks -o mocks/mock_pull_req_status_fetcher.go PullReqStatusFetcher type PullReqStatusFetcher interface { - FetchPullStatus(pull models.PullRequest) (models.PullReqStatus, error) + FetchPullStatus(logger logging.SimpleLogging, pull models.PullRequest) (models.PullReqStatus, error) } type pullReqStatusFetcher struct { @@ -23,13 +24,13 @@ func NewPullReqStatusFetcher(client Client, vcsStatusName string) PullReqStatusF } } -func (f *pullReqStatusFetcher) FetchPullStatus(pull models.PullRequest) (pullStatus models.PullReqStatus, err error) { - approvalStatus, err := f.client.PullIsApproved(pull.BaseRepo, pull) +func (f *pullReqStatusFetcher) FetchPullStatus(logger logging.SimpleLogging, pull models.PullRequest) (pullStatus models.PullReqStatus, err error) { + approvalStatus, err := f.client.PullIsApproved(logger, pull.BaseRepo, pull) if err != nil { return pullStatus, errors.Wrapf(err, "fetching pull approval status for repo: %s, and pull number: %d", pull.BaseRepo.FullName, pull.Num) } - mergeable, err := f.client.PullIsMergeable(pull.BaseRepo, pull, f.vcsStatusName) + mergeable, err := f.client.PullIsMergeable(logger, pull.BaseRepo, pull, f.vcsStatusName) if err != nil { return pullStatus, errors.Wrapf(err, "fetching mergeability status for repo: %s, and pull number: %d", pull.BaseRepo.FullName, pull.Num) }