From bd862a31ea7511cddf94206b33e85d325d373809 Mon Sep 17 00:00:00 2001 From: "cory.murphy" Date: Fri, 11 Oct 2024 07:49:11 -0400 Subject: [PATCH] refactor event metadata --- charts/argobot/Chart.yaml | 4 +- pkg/events/application_resolver.go | 26 +++--- pkg/events/apply_runner.go | 13 ++- pkg/events/comment_handler.go | 67 +++++++--------- pkg/events/comment_parser.go | 7 +- pkg/events/comment_parser_test.go | 9 ++- pkg/events/comment_response.go | 15 ++++ pkg/events/event.go | 9 --- pkg/events/event_handler.go | 25 ------ pkg/events/event_metadata.go | 122 ----------------------------- pkg/events/pull_request_handler.go | 16 ---- pkg/github/event_metadata.go | 120 ++++++++++++++++++++++++++++ pkg/github/pull_status_fetcher.go | 28 +++---- pkg/logging/simple_logging.go | 9 --- pkg/models/comment.go | 29 ------- pkg/models/pull_request.go | 7 -- version | 2 +- 17 files changed, 206 insertions(+), 302 deletions(-) create mode 100644 pkg/events/comment_response.go delete mode 100644 pkg/events/event.go delete mode 100644 pkg/events/event_handler.go delete mode 100644 pkg/events/event_metadata.go delete mode 100644 pkg/events/pull_request_handler.go create mode 100644 pkg/github/event_metadata.go delete mode 100644 pkg/models/comment.go delete mode 100644 pkg/models/pull_request.go diff --git a/charts/argobot/Chart.yaml b/charts/argobot/Chart.yaml index a94cb9e..2e7d4b6 100644 --- a/charts/argobot/Chart.yaml +++ b/charts/argobot/Chart.yaml @@ -2,5 +2,5 @@ apiVersion: v2 name: argobot description: Helm chart for the corymurphy/argobot app type: application -version: 0.12.0 -appVersion: 0.12.0 +version: 0.13.0 +appVersion: 0.13.0 diff --git a/pkg/events/application_resolver.go b/pkg/events/application_resolver.go index 7cb3e07..1d8835b 100644 --- a/pkg/events/application_resolver.go +++ b/pkg/events/application_resolver.go @@ -7,18 +7,18 @@ import ( "time" "github.com/corymurphy/argobot/pkg/argocd" + "github.com/corymurphy/argobot/pkg/github" "github.com/corymurphy/argobot/pkg/logging" - "github.com/corymurphy/argobot/pkg/models" - "github.com/google/go-github/v53/github" + gogithub "github.com/google/go-github/v53/github" ) type ApplicationResolver struct { - GitHubClient *github.Client + GitHubClient *gogithub.Client ArgoCdClient *argocd.ApplicationsClient Log logging.SimpleLogging } -func NewApplicationResolver(githubClient *github.Client, argocdClient *argocd.ApplicationsClient, log logging.SimpleLogging) *ApplicationResolver { +func NewApplicationResolver(githubClient *gogithub.Client, argocdClient *argocd.ApplicationsClient, log logging.SimpleLogging) *ApplicationResolver { return &ApplicationResolver{ GitHubClient: githubClient, ArgoCdClient: argocdClient, @@ -26,10 +26,10 @@ func NewApplicationResolver(githubClient *github.Client, argocdClient *argocd.Ap } } -func (a *ApplicationResolver) FindApplicationNames(ctx context.Context, command *CommentCommand, pull models.PullRequest) ([]string, error) { +func (a *ApplicationResolver) FindApplicationNames(ctx context.Context, command *CommentCommand, event github.Event) ([]string, error) { var changedApps []string - modified, err := a.GetModifiedFiles(ctx, pull) + modified, err := a.GetModifiedFiles(ctx, event) if err != nil { return changedApps, fmt.Errorf("unable to list github pull request modified files: %s", err) } @@ -43,8 +43,6 @@ func (a *ApplicationResolver) FindApplicationNames(ctx context.Context, command path := app.Spec.Source.Path name := app.Name - // name := app.Metadata.Name - // app.Name a.Log.Debug(fmt.Sprintf("name: %s | path: %s", name, path)) for _, file := range modified { @@ -58,14 +56,14 @@ func (a *ApplicationResolver) FindApplicationNames(ctx context.Context, command } // copied from atlantis -func (a *ApplicationResolver) GetModifiedFiles(ctx context.Context, pull models.PullRequest) ([]string, error) { - a.Log.Debug("Getting modified files for GitHub pull request %d", pull.Number) +func (a *ApplicationResolver) GetModifiedFiles(ctx context.Context, event github.Event) ([]string, error) { + a.Log.Debug("Getting modified files for GitHub pull request %d") var files []string nextPage := 0 listloop: for { - opts := github.ListOptions{ + opts := gogithub.ListOptions{ PerPage: 300, } if nextPage != 0 { @@ -81,12 +79,12 @@ listloop: time.Sleep(attemptDelay) attemptDelay = 2*attemptDelay + 1*time.Second - pageFiles, resp, err := a.GitHubClient.PullRequests.ListFiles(ctx, pull.Owner, pull.Name, pull.Number, &opts) + pageFiles, resp, err := a.GitHubClient.PullRequests.ListFiles(ctx, event.Repository.Owner, event.Repository.Name, event.PullRequest.Number, &opts) if resp != nil { - a.Log.Debug("[attempt %d] GET /repos/%v/%v/pulls/%d/files returned: %v", i+1, pull.Owner, pull.Name, pull.Number, resp.StatusCode) + a.Log.Debug("[attempt %d] GET /repos/%v/%v/pulls/%d/files returned: %v", i+1, event.Repository.Owner, event.Repository.Name, event.PullRequest.Number, resp.StatusCode) } if err != nil { - ghErr, ok := err.(*github.ErrorResponse) + ghErr, ok := err.(*gogithub.ErrorResponse) if ok && ghErr.Response.StatusCode == 404 { // (hopefully) transient 404, retry after backoff continue diff --git a/pkg/events/apply_runner.go b/pkg/events/apply_runner.go index 97da54b..6bdfccf 100644 --- a/pkg/events/apply_runner.go +++ b/pkg/events/apply_runner.go @@ -8,7 +8,6 @@ import ( "github.com/corymurphy/argobot/pkg/env" vsc "github.com/corymurphy/argobot/pkg/github" "github.com/corymurphy/argobot/pkg/logging" - "github.com/corymurphy/argobot/pkg/models" "github.com/google/go-github/v53/github" ) @@ -29,10 +28,10 @@ func NewApplyRunner(vcsClient *github.Client, config *env.Config, log logging.Si } // TODO: validate that the PR is in an approved/mergeable state -func (a *ApplyRunner) Run(ctx context.Context, cmd *CommentCommand, comment models.PullRequestComment) (models.CommentResponse, error) { - var resp models.CommentResponse +func (a *ApplyRunner) Run(ctx context.Context, cmd *CommentCommand, event vsc.Event) (CommentResponse, error) { + var resp CommentResponse - status, err := vsc.NewPullRequestStatusFetcher(ctx, a.Log, a.vcsClient).Fetch(comment.Pull) + status, err := vsc.NewPullRequestStatusFetcher(ctx, a.Log, a.vcsClient).Fetch(event) if err != nil { return resp, fmt.Errorf("unable to get status of pr %w", err) } @@ -41,13 +40,13 @@ func (a *ApplyRunner) Run(ctx context.Context, cmd *CommentCommand, comment mode "pull request was not in a mergeable state. approved %t, mergeable %t", status.ApprovalStatus.IsApproved, status.Mergeable) - return models.NewCommentResponse("pull request must be approved and in a mergeable state", comment), nil + return NewCommentResponse("pull request must be approved and in a mergeable state", event), nil } - apply, err := a.ApplyClient.Apply(cmd.Application, comment.Revision) + apply, err := a.ApplyClient.Apply(cmd.Application, event.Revision) if err != nil { return resp, fmt.Errorf("argoclient failed while applying %w", err) } a.Log.Debug(apply) - return models.NewCommentResponse(apply, comment), nil + return NewCommentResponse(apply, event), nil } diff --git a/pkg/events/comment_handler.go b/pkg/events/comment_handler.go index c744ada..f95eb21 100644 --- a/pkg/events/comment_handler.go +++ b/pkg/events/comment_handler.go @@ -8,8 +8,8 @@ import ( "github.com/corymurphy/argobot/pkg/argocd" "github.com/corymurphy/argobot/pkg/command" "github.com/corymurphy/argobot/pkg/env" + vsc "github.com/corymurphy/argobot/pkg/github" "github.com/corymurphy/argobot/pkg/logging" - "github.com/corymurphy/argobot/pkg/models" "github.com/corymurphy/argobot/pkg/utils" "github.com/google/go-github/v53/github" "github.com/palantir/go-githubapp/githubapp" @@ -20,10 +20,9 @@ const maxCommentLength = 32768 type PRCommentHandler struct { githubapp.ClientCreator - Config *env.Config - Log logging.SimpleLogging - ArgoClient argocd.ApplicationsClient - TestingMode bool + Config *env.Config + Log logging.SimpleLogging + ArgoClient argocd.ApplicationsClient } func (h *PRCommentHandler) Handles() []string { @@ -34,50 +33,38 @@ func (h *PRCommentHandler) Handle(ctx context.Context, eventType string, deliver // var event github.IssueCommentEvent // event.GetInstallation() // var pr github.PullRequestEvent - event, err := NewEventMetadata(eventType, payload) + event, err := vsc.NewEvent(eventType, payload) if err != nil { h.Log.Err(err, "unable to parse event metadata") return nil } - // if err := json.Unmarshal(payload, &event); err != nil { - // return errors.Wrap(err, "failed to parse issue comment event payload") - // } comment := NewCommentParser(h.Log).Parse(event) if (comment.Ignore || comment.ImmediateResponse) && !comment.HasResponseComment { return nil } - // repo := event.Re - // prNum := event.GetIssue().GetNumber() - // repoOwner := repo.GetOwner().GetLogin() - // repoName := repo.GetName() - - // githubapp.InstallationSource - installationID := githubapp.GetInstallationIDFromEvent(&event) - // ctx, _ = githubapp.PreparePRContext(ctx, installationID, repo, event.GetIssue().GetNumber()) - client, err := h.NewInstallationClient(installationID) if err != nil { return err } - pr, _, err := client.PullRequests.Get(ctx, event.Repository.Owner, event.Repository.Name, event.PullRequest.Number) - if err != nil { - return err - } + // pr, _, err := client.PullRequests.Get(ctx, event.Repository.Owner, event.Repository.Name, event.PullRequest.Number) + // if err != nil { + // return err + // } - request := models.NewPullRequestComment( - *pr.GetHead().SHA, - // TODO: replace this model with the event model - models.PullRequest{ - Number: event.PullRequest.Number, - Name: event.Repository.Name, - Owner: event.Repository.Owner, - }, - ) + // request := github.NewPullRequestComment( + // *pr.GetHead().SHA, + // // TODO: replace this model with the event model + // models.PullRequest{ + // Number: event.PullRequest.Number, + // Name: event.Repository.Name, + // Owner: event.Repository.Owner, + // }, + // ) if (comment.Ignore || comment.ImmediateResponse) && comment.HasResponseComment { prComment := github.IssueComment{ @@ -97,7 +84,7 @@ func (h *PRCommentHandler) Handle(ctx context.Context, eventType string, deliver if comment.Command.Application == "" { appResolver := NewApplicationResolver(client, &h.ArgoClient, h.Log) - apps, err := appResolver.FindApplicationNames(ctx, comment.Command, request.Pull) + apps, err := appResolver.FindApplicationNames(ctx, comment.Command, event) if err != nil { h.Log.Err(err, "unable to resolve app name") return nil @@ -110,7 +97,7 @@ func (h *PRCommentHandler) Handle(ctx context.Context, eventType string, deliver for _, app := range comment.Command.Applications { var err error = nil - plan, diff, err := h.Plan(ctx, app, request.Revision) + plan, diff, err := h.Plan(ctx, app, event.Revision) if err != nil { h.Log.Err(err, fmt.Sprintf("unable to plan: %s", plan)) return err @@ -123,7 +110,7 @@ func (h *PRCommentHandler) Handle(ctx context.Context, eventType string, deliver h.Log.Info(plan) } - err = h.CreateComment(client, ctx, request.Pull, msg, comment.Command.Name.String()) + err = h.CreateComment(client, ctx, event, msg, comment.Command.Name.String()) if err != nil { h.Log.Err(err, fmt.Sprintf("error while planning %s", app)) } @@ -135,14 +122,14 @@ func (h *PRCommentHandler) Handle(ctx context.Context, eventType string, deliver if comment.Command.Name == command.Apply { go func() { apply := NewApplyRunner(client, h.Config, h.Log, &h.ArgoClient) - response, err := apply.Run(ctx, comment.Command, request) + response, err := apply.Run(ctx, comment.Command, event) if err != nil { h.Log.Err(err, "unable to apply") return } msg := fmt.Sprintf("apply result for `%s`\n\n", comment.Command.Application) + "```\n" + response.Message + "\n```" - h.CreateComment(client, ctx, request.Pull, msg, comment.Command.Name.String()) + h.CreateComment(client, ctx, event, msg, comment.Command.Name.String()) }() return nil } @@ -182,8 +169,8 @@ func (h *PRCommentHandler) Plan(ctx context.Context, name string, revision strin } // TODO move this to another module -func (h *PRCommentHandler) CreateComment(client *github.Client, ctx context.Context, pull models.PullRequest, comment string, command string) error { - h.Log.Debug("Creating comment on GitHub pull request %d", pull.Number) +func (h *PRCommentHandler) CreateComment(client *github.Client, ctx context.Context, event vsc.Event, comment string, command string) error { + h.Log.Debug("Creating comment on GitHub pull request %d", event.PullRequest.Number) var sepStart string sepEnd := "\n```\n" + @@ -202,9 +189,9 @@ func (h *PRCommentHandler) CreateComment(client *github.Client, ctx context.Cont comments := utils.SplitComment(comment, maxCommentLength, sepEnd, sepStart, 100, truncationHeader) for i := range comments { - _, resp, err := client.Issues.CreateComment(ctx, pull.Owner, pull.Name, pull.Number, &github.IssueComment{Body: &comments[i]}) + _, resp, err := client.Issues.CreateComment(ctx, event.Repository.Owner, event.Repository.Name, event.PullRequest.Number, &github.IssueComment{Body: &comments[i]}) if resp != nil { - h.Log.Debug("POST /repos/%v/%v/issues/%d/comments returned: %v", pull.Owner, pull.Name, pull.Number, resp.StatusCode) + h.Log.Debug("POST /repos/%v/%v/issues/%d/comments returned: %v", event.Repository.Owner, event.Repository.Name, event.PullRequest.Number, resp.StatusCode) } if err != nil { return err diff --git a/pkg/events/comment_parser.go b/pkg/events/comment_parser.go index b4f1248..eebf0ac 100644 --- a/pkg/events/comment_parser.go +++ b/pkg/events/comment_parser.go @@ -7,6 +7,7 @@ import ( "unicode" "github.com/corymurphy/argobot/pkg/command" + vsc "github.com/corymurphy/argobot/pkg/github" "github.com/corymurphy/argobot/pkg/logging" "github.com/google/go-github/v53/github" "github.com/google/shlex" @@ -37,9 +38,9 @@ func NewCommentParser(logger logging.SimpleLogging) *CommentParser { } } -func (c *CommentParser) Parse(event EventMetadata) *CommentParseResult { +func (c *CommentParser) Parse(event vsc.Event) *CommentParseResult { - if event.Action == Opened { + if event.Action == vsc.Opened { c.Log.Info("responding to pull request open event with help message") return &CommentParseResult{ ImmediateResponse: true, @@ -52,7 +53,7 @@ func (c *CommentParser) Parse(event EventMetadata) *CommentParseResult { } } - if event.Action != Comment { + if event.Action != vsc.Comment { msg := "ignoring a non created event" c.Log.Info(msg) return &CommentParseResult{ diff --git a/pkg/events/comment_parser_test.go b/pkg/events/comment_parser_test.go index ba3611e..b5f6be2 100644 --- a/pkg/events/comment_parser_test.go +++ b/pkg/events/comment_parser_test.go @@ -4,6 +4,7 @@ import ( "testing" "github.com/corymurphy/argobot/pkg/command" + "github.com/corymurphy/argobot/pkg/github" "github.com/corymurphy/argobot/pkg/logging" ) @@ -24,7 +25,7 @@ func Test_Comment_IsHelp(t *testing.T) { } } ` - event, err := NewEventMetadata("issue_comment", []byte(serialized)) + event, err := github.NewEvent("issue_comment", []byte(serialized)) if err != nil { t.Error(err) } @@ -53,7 +54,7 @@ func Test_Comment_IsBot(t *testing.T) { } } ` - event, err := NewEventMetadata("issue_comment", []byte(serialized)) + event, err := github.NewEvent("issue_comment", []byte(serialized)) if err != nil { t.Error(err) } @@ -84,7 +85,7 @@ func Test_PlanHasApplicationName(t *testing.T) { } ` - event, err := NewEventMetadata("issue_comment", []byte(serialized)) + event, err := github.NewEvent("issue_comment", []byte(serialized)) if err != nil { t.Error(err) } @@ -119,7 +120,7 @@ func Test_ApplyHasApplicationName(t *testing.T) { } ` - event, err := NewEventMetadata("issue_comment", []byte(serialized)) + event, err := github.NewEvent("issue_comment", []byte(serialized)) if err != nil { t.Error(err) } diff --git a/pkg/events/comment_response.go b/pkg/events/comment_response.go new file mode 100644 index 0000000..4964b9a --- /dev/null +++ b/pkg/events/comment_response.go @@ -0,0 +1,15 @@ +package events + +import "github.com/corymurphy/argobot/pkg/github" + +type CommentResponse struct { + Message string + Event github.Event +} + +func NewCommentResponse(msg string, event github.Event) CommentResponse { + return CommentResponse{ + Message: msg, + Event: event, + } +} diff --git a/pkg/events/event.go b/pkg/events/event.go deleted file mode 100644 index 86b17bc..0000000 --- a/pkg/events/event.go +++ /dev/null @@ -1,9 +0,0 @@ -package events - -// type Event interface { -// Action() string -// } - -type Event struct { - Action *string `json:"action,omitempty"` -} diff --git a/pkg/events/event_handler.go b/pkg/events/event_handler.go deleted file mode 100644 index 78b2739..0000000 --- a/pkg/events/event_handler.go +++ /dev/null @@ -1,25 +0,0 @@ -package events - -import ( - "context" - "net/http" - - "github.com/corymurphy/argobot/pkg/logging" -) - -type EventHandler struct { - Log logging.SimpleLogging - Handlers map[string]http.Handler -} - -func (e *EventHandler) Handles() []string { - return []string{"issue_comment", "pull_request"} -} - -func (e *EventHandler) Handle(ctx context.Context, eventType string, deliveryID string, payload []byte) error { - // return e.Handlers[eventType] - - // handler := e.Handlers[eventType] - - return nil -} diff --git a/pkg/events/event_metadata.go b/pkg/events/event_metadata.go deleted file mode 100644 index e1b0c0f..0000000 --- a/pkg/events/event_metadata.go +++ /dev/null @@ -1,122 +0,0 @@ -package events - -import ( - "encoding/json" - "fmt" - - "github.com/google/go-github/v53/github" - "github.com/pkg/errors" -) - -type Action int - -const ( - Comment Action = iota - Opened Action = iota -) - -func (e Action) String() string { - switch e { - case Comment: - return "comment" - case Opened: - return "opened" - } - return "" -} - -type Repository struct { - Name string - Owner string -} - -type Actor struct { - Name string -} - -type PullRequest struct { - Number int -} - -type InstallationProvider interface { - GetInstallation() *github.Installation -} - -type EventMetadata struct { - Revision string - Message string - IsPullRequest bool - Action Action - Actor Actor - Repository Repository - PullRequest PullRequest - InstallationProvider InstallationProvider -} - -func (e *EventMetadata) GetInstallation() *github.Installation { - return e.InstallationProvider.GetInstallation() -} - -func (e *EventMetadata) HasMessage() bool { - return e.Message != "" -} - -func NewEventMetadata(eventType string, payload []byte) (EventMetadata, error) { - var metadata EventMetadata - var event Event - if err := json.Unmarshal(payload, &event); err != nil { - return metadata, errors.Wrap(err, "failed to parse event payload") - } - - if eventType == "issue_comment" && *event.Action == "created" { - var event github.IssueCommentEvent - if err := json.Unmarshal(payload, &event); err != nil { - return metadata, errors.Wrap(err, "failed to parse issue comment event payload") - } - - return EventMetadata{ - Actor: Actor{Name: event.GetComment().GetUser().GetLogin()}, - Action: Comment, - IsPullRequest: event.GetIssue().IsPullRequest(), - Repository: Repository{ - Name: event.GetRepo().GetName(), - Owner: event.GetRepo().GetOwner().GetLogin(), - }, - PullRequest: PullRequest{ - Number: event.GetIssue().GetNumber(), - }, - Message: *event.GetComment().Body, - InstallationProvider: &event, - }, nil - } - - if eventType == "pull_request" && (*event.Action == "opened" || *event.Action == "reopened" || *event.Action == "ready_for_review") { - var event github.PullRequestEvent - if err := json.Unmarshal(payload, &event); err != nil { - return metadata, errors.Wrap(err, "failed to parse issue comment event payload") - } - - return EventMetadata{ - Actor: Actor{Name: event.GetPullRequest().GetUser().GetLogin()}, - Action: Opened, - IsPullRequest: true, - Repository: Repository{ - Name: event.GetRepo().GetName(), - Owner: event.GetRepo().GetOwner().GetLogin(), - }, - PullRequest: PullRequest{ - Number: event.GetPullRequest().GetNumber(), - }, - Message: "", - InstallationProvider: &event, - }, nil - } - - return metadata, fmt.Errorf("unsupported event %s %s", eventType, *event.Action) -} - -type GithubEvent struct { - // Action is the action that was performed on the comment. - // Possible values are: "created", "edited", "deleted". - Action *string `json:"action,omitempty"` -} diff --git a/pkg/events/pull_request_handler.go b/pkg/events/pull_request_handler.go deleted file mode 100644 index 8f55782..0000000 --- a/pkg/events/pull_request_handler.go +++ /dev/null @@ -1,16 +0,0 @@ -package events - -import ( - "github.com/corymurphy/argobot/pkg/argocd" - "github.com/corymurphy/argobot/pkg/env" - "github.com/corymurphy/argobot/pkg/logging" - "github.com/palantir/go-githubapp/githubapp" -) - -type PullRequestHandler struct { - githubapp.ClientCreator - Config *env.Config - Log logging.SimpleLogging - ArgoClient argocd.ApplicationsClient - TestingMode bool -} diff --git a/pkg/github/event_metadata.go b/pkg/github/event_metadata.go new file mode 100644 index 0000000..9060034 --- /dev/null +++ b/pkg/github/event_metadata.go @@ -0,0 +1,120 @@ +package github + +import ( + "encoding/json" + "fmt" + + "github.com/google/go-github/v53/github" + "github.com/pkg/errors" +) + +type Action int + +const ( + Comment Action = iota + Opened Action = iota +) + +func (e Action) String() string { + switch e { + case Comment: + return "comment" + case Opened: + return "opened" + } + return "" +} + +type Repository struct { + Name string + Owner string +} + +type Actor struct { + Name string +} + +type PullRequest struct { + Number int +} + +type GithubEvent struct { + Action *string `json:"action,omitempty"` +} + +type InstallationProvider interface { + GetInstallation() *github.Installation +} + +type Event struct { + Revision string + Message string + IsPullRequest bool + Action Action + Actor Actor + Repository Repository + PullRequest PullRequest + InstallationProvider InstallationProvider +} + +func (e *Event) GetInstallation() *github.Installation { + return e.InstallationProvider.GetInstallation() +} + +func (e *Event) HasMessage() bool { + return e.Message != "" +} + +func NewEvent(eventType string, payload []byte) (Event, error) { + var event Event + var githubEvent GithubEvent + if err := json.Unmarshal(payload, &githubEvent); err != nil { + return event, errors.Wrap(err, "failed to parse event payload") + } + + if eventType == "issue_comment" && *githubEvent.Action == "created" { + var comment github.IssueCommentEvent + if err := json.Unmarshal(payload, &comment); err != nil { + return event, errors.Wrap(err, "failed to parse issue comment event payload") + } + + return Event{ + Actor: Actor{Name: comment.GetComment().GetUser().GetLogin()}, + Action: Comment, + IsPullRequest: comment.GetIssue().IsPullRequest(), + Repository: Repository{ + Name: comment.GetRepo().GetName(), + Owner: comment.GetRepo().GetOwner().GetLogin(), + }, + PullRequest: PullRequest{ + Number: comment.GetIssue().GetNumber(), + }, + Message: *comment.GetComment().Body, + InstallationProvider: &comment, + }, nil + } + + if eventType == "pull_request" && (*githubEvent.Action == "opened" || *githubEvent.Action == "reopened" || *githubEvent.Action == "ready_for_review") { + var pr github.PullRequestEvent + if err := json.Unmarshal(payload, &pr); err != nil { + return event, errors.Wrap(err, "failed to parse issue comment event payload") + } + + return Event{ + Actor: Actor{Name: pr.GetPullRequest().GetUser().GetLogin()}, + Action: Opened, + IsPullRequest: true, + Repository: Repository{ + Name: pr.GetRepo().GetName(), + Owner: pr.GetRepo().GetOwner().GetLogin(), + }, + PullRequest: PullRequest{ + Number: pr.GetPullRequest().GetNumber(), + }, + Message: "", + InstallationProvider: &pr, + }, nil + } + + return event, fmt.Errorf("unsupported event %s %s", eventType, *&githubEvent.Action) +} diff --git a/pkg/github/pull_status_fetcher.go b/pkg/github/pull_status_fetcher.go index ed8a7cf..60996be 100644 --- a/pkg/github/pull_status_fetcher.go +++ b/pkg/github/pull_status_fetcher.go @@ -10,7 +10,7 @@ import ( ) type VscPullRequestStatusFetcher interface { - Fetch(pull models.PullRequest) (models.PullRequestStatus, error) + Fetch(event Event) (models.PullRequestStatus, error) } type GithubPullRequestStatusFetcher struct { @@ -27,17 +27,17 @@ func NewPullRequestStatusFetcher(ctx context.Context, logger logging.SimpleLoggi } } -func (g *GithubPullRequestStatusFetcher) Fetch(pull models.PullRequest) (status models.PullRequestStatus, err error) { +func (g *GithubPullRequestStatusFetcher) Fetch(event Event) (status models.PullRequestStatus, err error) { - g.logger.Debug("getting approval status of pull request %d", pull.Number) - approvalStatus, err := g.PullIsApproved(pull) + g.logger.Debug("getting approval status of pull request %d", event.PullRequest.Number) + approvalStatus, err := g.PullIsApproved(event) if err != nil { - return status, errors.Wrapf(err, "fetching pull approval status for repo: %s, and pull number: %d", pull.Name, pull.Number) + return status, errors.Wrapf(err, "fetching pull approval status for repo: %s/%s, and pull number: %d", event.Repository.Owner, event.Repository.Name, event.PullRequest.Number) } - mergeable, err := g.PullIsMergeable(pull, "") + mergeable, err := g.PullIsMergeable(event, "") if err != nil { - return status, errors.Wrapf(err, "fetching mergeability status for repo: %s, and pull number: %d", pull.Name, pull.Number) + return status, errors.Wrapf(err, "fetching mergeability status for repo: $s/%s, and pull number: %d", event.Repository.Owner, event.Repository.Name, event.PullRequest.Number) } return models.PullRequestStatus{ @@ -46,8 +46,8 @@ func (g *GithubPullRequestStatusFetcher) Fetch(pull models.PullRequest) (status }, err } -func (g *GithubPullRequestStatusFetcher) PullIsApproved(pull models.PullRequest) (approvalStatus models.ApprovalStatus, err error) { - g.logger.Debug("Checking if GitHub pull request %d is approved", pull.Number) +func (g *GithubPullRequestStatusFetcher) PullIsApproved(event Event) (approvalStatus models.ApprovalStatus, err error) { + g.logger.Debug("Checking if GitHub pull request %d is approved", event.PullRequest.Number) nextPage := 0 for { opts := github.ListOptions{ @@ -56,9 +56,9 @@ func (g *GithubPullRequestStatusFetcher) PullIsApproved(pull models.PullRequest) if nextPage != 0 { opts.Page = nextPage } - pageReviews, resp, err := g.client.PullRequests.ListReviews(g.ctx, pull.Owner, pull.Name, pull.Number, &opts) + pageReviews, resp, err := g.client.PullRequests.ListReviews(g.ctx, event.Repository.Owner, event.Repository.Name, event.PullRequest.Number, &opts) if resp != nil { - g.logger.Debug("GET /repos/%v/%v/pulls/%d/reviews returned: %v", pull.Owner, pull.Name, pull.Number, resp.StatusCode) + g.logger.Debug("GET /repos/%v/%v/pulls/%d/reviews returned: %v", event.Repository.Owner, event.Repository.Name, event.PullRequest.Number, resp.StatusCode) } if err != nil { return approvalStatus, errors.Wrap(err, "getting reviews") @@ -82,9 +82,9 @@ func (g *GithubPullRequestStatusFetcher) PullIsApproved(pull models.PullRequest) // TODO: complete the bypass functionality from atlantis // TODO: check if approved by codeowner -func (g *GithubPullRequestStatusFetcher) PullIsMergeable(pull models.PullRequest, vcsstatusname string) (bool, error) { - g.logger.Debug("Checking if GitHub pull request %d is mergeable", pull.Number) - githubPR, _, err := g.client.PullRequests.Get(g.ctx, pull.Owner, pull.Name, pull.Number) +func (g *GithubPullRequestStatusFetcher) PullIsMergeable(event Event, vcsstatusname string) (bool, error) { + g.logger.Debug("Checking if GitHub pull request %d is mergeable", event.PullRequest.Number) + githubPR, _, err := g.client.PullRequests.Get(g.ctx, event.Repository.Owner, event.Repository.Name, event.PullRequest.Number) if err != nil { return false, errors.Wrap(err, "getting pull request") } diff --git a/pkg/logging/simple_logging.go b/pkg/logging/simple_logging.go index 582fb20..3050c17 100644 --- a/pkg/logging/simple_logging.go +++ b/pkg/logging/simple_logging.go @@ -18,7 +18,6 @@ type SimpleLogging interface { Debug(format string, a ...interface{}) Info(format string, a ...interface{}) Warn(format string, a ...interface{}) - // Err(format string, a ...interface{}) Err(err error, message string) } @@ -50,16 +49,8 @@ func (l *Logger) Warn(format string, a ...interface{}) { } } -// TODO: use errors.Wrap(error, string) func (l *Logger) Err(err error, message string) { if l.level >= Err { log.Printf("%v", errors.Wrap(err, message)) - // errors.Wrap(error, string) } } - -// func (l *Logger) Err(format string, a ...interface{}) { -// if l.level >= Err { -// log.Printf(format, a...) -// } -// } diff --git a/pkg/models/comment.go b/pkg/models/comment.go deleted file mode 100644 index 77affc8..0000000 --- a/pkg/models/comment.go +++ /dev/null @@ -1,29 +0,0 @@ -package models - -type PullRequestComment struct { - // Message string - Revision string - Pull PullRequest -} - -func NewPullRequestComment(revision string, pull PullRequest) PullRequestComment { - return PullRequestComment{ - // Message: msg, - Revision: revision, - Pull: pull, - } -} - -type CommentResponse struct { - Message string - Revision string - Pull PullRequest -} - -func NewCommentResponse(msg string, request PullRequestComment) CommentResponse { - return CommentResponse{ - Message: msg, - Revision: request.Revision, - Pull: request.Pull, - } -} diff --git a/pkg/models/pull_request.go b/pkg/models/pull_request.go deleted file mode 100644 index ff69659..0000000 --- a/pkg/models/pull_request.go +++ /dev/null @@ -1,7 +0,0 @@ -package models - -type PullRequest struct { - Number int - Owner string - Name string -} diff --git a/version b/version index ac454c6..54d1a4f 100644 --- a/version +++ b/version @@ -1 +1 @@ -0.12.0 +0.13.0