0
0
mirror of https://github.com/thegeeklab/wp-github-comment.git synced 2024-11-28 08:30:36 +00:00
wp-github-comment/plugin/comment.go

85 lines
1.6 KiB
Go
Raw Normal View History

2020-09-19 22:00:34 +00:00
package plugin
import (
"context"
"fmt"
"strings"
"github.com/google/go-github/v61/github"
2020-09-19 22:00:34 +00:00
)
type commentClient struct {
Message string
Update bool
Key string
Repo string
Owner string
IssueNum int
*github.Client
}
func (cc *commentClient) issueComment(ctx context.Context) error {
var (
err error
comment *github.IssueComment
resp *github.Response
)
2020-09-19 22:00:34 +00:00
issueComment := &github.IssueComment{
2020-09-19 22:00:34 +00:00
Body: &cc.Message,
}
if cc.Update {
// Append plugin comment ID to comment message so we can search for it later
message := fmt.Sprintf("%s\n<!-- id: %s -->\n", cc.Message, cc.Key)
issueComment.Body = &message
2020-09-19 22:00:34 +00:00
comment, err = cc.comment(ctx)
2020-09-19 22:00:34 +00:00
if err == nil && comment != nil {
_, resp, err = cc.Client.Issues.EditComment(ctx, cc.Owner, cc.Repo, *comment.ID, issueComment)
2020-09-19 22:00:34 +00:00
}
}
if err == nil && resp == nil {
_, _, err = cc.Client.Issues.CreateComment(ctx, cc.Owner, cc.Repo, cc.IssueNum, issueComment)
2020-09-19 22:00:34 +00:00
}
if err != nil {
return err
2020-09-19 22:00:34 +00:00
}
return nil
}
func (cc *commentClient) comment(ctx context.Context) (*github.IssueComment, error) {
2020-09-19 22:00:34 +00:00
var allComments []*github.IssueComment
opts := &github.IssueListCommentsOptions{}
for {
comments, resp, err := cc.Client.Issues.ListComments(ctx, cc.Owner, cc.Repo, cc.IssueNum, opts)
2020-09-19 22:00:34 +00:00
if err != nil {
return nil, err
}
allComments = append(allComments, comments...)
2020-09-19 22:00:34 +00:00
if resp.NextPage == 0 {
break
}
2020-09-19 22:00:34 +00:00
opts.Page = resp.NextPage
}
for _, comment := range allComments {
if strings.Contains(*comment.Body, fmt.Sprintf("<!-- id: %s -->", cc.Key)) {
return comment, nil
}
}
//nolint:nilnil
2020-09-19 22:00:34 +00:00
return nil, nil
}