Skip to content

Commit

Permalink
refactor event metadata
Browse files Browse the repository at this point in the history
  • Loading branch information
corymurphy committed Oct 11, 2024
1 parent 439859d commit bd862a3
Show file tree
Hide file tree
Showing 17 changed files with 206 additions and 302 deletions.
4 changes: 2 additions & 2 deletions charts/argobot/Chart.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -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
26 changes: 12 additions & 14 deletions pkg/events/application_resolver.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,29 +7,29 @@ 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,
Log: log,
}
}

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)
}
Expand All @@ -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 {
Expand All @@ -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 {
Expand All @@ -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
Expand Down
13 changes: 6 additions & 7 deletions pkg/events/apply_runner.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
)

Expand All @@ -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)
}
Expand All @@ -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
}
67 changes: 27 additions & 40 deletions pkg/events/comment_handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand All @@ -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 {
Expand All @@ -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{
Expand All @@ -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
Expand All @@ -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
Expand All @@ -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))
}
Expand All @@ -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
}
Expand Down Expand Up @@ -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</details>" +
Expand All @@ -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
Expand Down
7 changes: 4 additions & 3 deletions pkg/events/comment_parser.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down Expand Up @@ -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,
Expand All @@ -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{
Expand Down
9 changes: 5 additions & 4 deletions pkg/events/comment_parser_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"testing"

"github.com/corymurphy/argobot/pkg/command"
"github.com/corymurphy/argobot/pkg/github"
"github.com/corymurphy/argobot/pkg/logging"
)

Expand All @@ -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)
}
Expand Down Expand Up @@ -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)
}
Expand Down Expand Up @@ -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)
}
Expand Down Expand Up @@ -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)
}
Expand Down
15 changes: 15 additions & 0 deletions pkg/events/comment_response.go
Original file line number Diff line number Diff line change
@@ -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,
}
}
9 changes: 0 additions & 9 deletions pkg/events/event.go

This file was deleted.

Loading

0 comments on commit bd862a3

Please sign in to comment.