Skip to content

Commit

Permalink
Merge pull request #36 from vince-riv/feat/pr-head-check
Browse files Browse the repository at this point in the history
feat: compare event sha to HEAD
  • Loading branch information
vrivellino authored Jan 23, 2024
2 parents 5e583a6 + d809dfc commit 804b156
Show file tree
Hide file tree
Showing 4 changed files with 454 additions and 6 deletions.
2 changes: 1 addition & 1 deletion cmd/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -138,7 +138,7 @@ func processEvent(eventInfo webhook.EventInfo) {
//println("+++++++++++++")
//fmt.Print(cMarkdown.String()[0])
//println(".............")
_, _ = github.Comment(ctx, eventInfo.RepoOwner, eventInfo.RepoName, eventInfo.PrNum, cMarkdown.String())
_, _ = github.Comment(ctx, eventInfo.RepoOwner, eventInfo.RepoName, eventInfo.PrNum, eventInfo.Sha, cMarkdown.String())
return
}
}
Expand Down
37 changes: 36 additions & 1 deletion internal/github/comment.go
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,37 @@ func getCommentUser(ctx context.Context) error {
return nil
}

// Gets the specified pull request
func GetPullRequest(ctx context.Context, owner, repo string, prNum int) (*github.PullRequest, error) {
pr, resp, err := commentClient.PullRequests.Get(ctx, owner, repo, prNum)
if resp != nil {
log.Info().Msgf("%s received when calling client.Users.Get() via go-github", resp.Status)
}
if err != nil {
log.Error().Err(err).Msgf("Unable to fetch pull request %s/%s#%d", owner, repo, prNum)
return nil, err
}
return pr, nil
}

// Returns true if sha is HEAD of the pull request
func isPrHead(ctx context.Context, sha, owner, repo string, prNum int) bool {
pr, err := GetPullRequest(ctx, owner, repo, prNum)
if err != nil {
log.Warn().Msgf("GetPullRequest() err'd - assuming %s is HEAD of %s/%s#%d", sha, owner, repo, prNum)
return true
}
if pr.Head == nil {
log.Warn().Msgf("%s/%s#%d has no HEAD - assuming %s is not HEAD", owner, repo, prNum, sha)
return false
}
if pr.Head.SHA == nil {
log.Warn().Msgf("SHA for PullRequestBranch of %s/%s#%d is nil - assuming %s is not HEAD", owner, repo, prNum, sha)
return false
}
return sha == *pr.Head.SHA
}

//func saveResponse(v any, filename string) {
// jsonData, err := json.Marshal(v)
// if err != nil {
Expand Down Expand Up @@ -121,8 +152,12 @@ func getExistingComments(ctx context.Context, owner, repo string, prNum int) ([]
}

// Creates or updates comment on the specified pull request
func Comment(ctx context.Context, owner, repo string, prNum int, commentBodies []string) ([]*github.IssueComment, error) {
func Comment(ctx context.Context, owner, repo string, prNum int, sha string, commentBodies []string) ([]*github.IssueComment, error) {
var res []*github.IssueComment
if !isPrHead(ctx, sha, owner, repo, prNum) {
log.Info().Msgf("%s is not HEAD for %s/%s#%d - skipping comment", sha, owner, repo, prNum)
return res, nil
}
existingComments, err := getExistingComments(ctx, owner, repo, prNum)
if err != nil {
return res, err
Expand Down
55 changes: 51 additions & 4 deletions internal/github/comment_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,9 @@ const payloadPr2CreateComment = "payload-pr-2-create-comment.json"

// const payloadPr3UpdateComment = "payload-pr-3-update-comment.json"
const payloadPatchComment = "payload-pr-patch-comment.json"
const payloadPullRequest = "payload-pr-get.json"

const prHeadSha = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"

func readFileToByteArray(fileName string) ([]byte, string, error) {
workingDir, err := os.Getwd()
Expand Down Expand Up @@ -65,6 +68,7 @@ func jsonFieldExtract(srcField string, src []byte, destField string, dest []byte
}

func newHttpTestServer(t *testing.T) *httptest.Server {
// TODO - unclutter this mess
newServer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
statusCode := http.StatusNotFound
payload := []byte(`404 Page Not Found`)
Expand Down Expand Up @@ -98,6 +102,30 @@ func newHttpTestServer(t *testing.T) *httptest.Server {
} else {
statusCode = http.StatusMethodNotAllowed
}
} else if strings.HasPrefix(r.URL.Path, "/repos/vince-riv/argo-diff/pulls/") {
if r.Method == "GET" {
urlPathParts := strings.Split(r.URL.Path, "/")
if urlPathParts[5] == "" {
statusCode = http.StatusInternalServerError
t.Errorf("Bad URL Path: %s", r.URL.Path)
} else {
statusCode = http.StatusOK
payload, filePath, err = readFileToByteArray(payloadPullRequest)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
t.Errorf("readFileToByteArray() failed: %s", err)
return
}
payload = bytes.Replace(payload, []byte("%%_PR_NUM_%%"), []byte(urlPathParts[5]), -1)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
t.Errorf("jsonFieldExtract() failed: %s", err)
return
}
}
} else {
statusCode = http.StatusMethodNotAllowed
}
} else {
switch r.URL.Path {
case "/user":
Expand Down Expand Up @@ -159,7 +187,7 @@ func TestCommentNoExistingComments(t *testing.T) {
t.Error("Expected no existing comment")
}

comments, err := Comment(context.Background(), "vince-riv", "argo-diff", 1, []string{"argo-diff test comment"})
comments, err := Comment(context.Background(), "vince-riv", "argo-diff", 1, prHeadSha, []string{"argo-diff test comment"})
if err != nil {
t.Errorf("Comment() failed: %s", err)
}
Expand All @@ -184,7 +212,7 @@ func TestCommentExistingDifferentUser(t *testing.T) {
t.Error("Expected no existing comment")
}

comments, err := Comment(context.Background(), "vince-riv", "argo-diff", 2, []string{"argo-diff test comment"})
comments, err := Comment(context.Background(), "vince-riv", "argo-diff", 2, prHeadSha, []string{"argo-diff test comment"})
if err != nil {
t.Errorf("Comment() failed: %s", err)
}
Expand All @@ -211,7 +239,7 @@ func TestCommentExisting(t *testing.T) {
t.Error("Comment ID doesn't match")
}

comments, err := Comment(context.Background(), "vince-riv", "argo-diff", 3, []string{"argo-diff test comment"})
comments, err := Comment(context.Background(), "vince-riv", "argo-diff", 3, prHeadSha, []string{"argo-diff test comment"})
if err != nil {
t.Errorf("Comment() failed: %s", err)
}
Expand All @@ -238,7 +266,7 @@ func TestCommentExistingMulti(t *testing.T) {
t.Error("Unexpected issue commit IDs")
}

comments, err := Comment(context.Background(), "vince-riv", "argo-diff", 4, []string{"argo-diff test comment update"})
comments, err := Comment(context.Background(), "vince-riv", "argo-diff", 4, prHeadSha, []string{"argo-diff test comment update"})
if err != nil {
t.Errorf("Comment() failed: %s", err)
}
Expand All @@ -255,3 +283,22 @@ func TestCommentExistingMulti(t *testing.T) {
t.Errorf("1st Comment body doesn't match '[Outdated argo-diff content]': %s", *comments[1].Body)
}
}

func TestCommentNotHead(t *testing.T) {
server := newHttpTestServer(t)
defer server.Close()
httpBaseUrl, _ := url.Parse(server.URL + "/")
commentClient = github.NewClient(nil).WithAuthToken("test1234")
commentClient.BaseURL = httpBaseUrl
commentClient.UploadURL = httpBaseUrl

prHeadShaOld := "1111111111111111111111111111111111111111"

comments, err := Comment(context.Background(), "vince-riv", "argo-diff", 1, prHeadShaOld, []string{"argo-diff test comment"})
if err != nil {
t.Errorf("Comment() failed: %s", err)
}
if len(comments) > 0 {
t.Error("Not expecting to comment")
}
}
Loading

0 comments on commit 804b156

Please sign in to comment.