nitter/nitters/gitea/pr_nitter.go

92 lines
2.1 KiB
Go
Raw Normal View History

2023-03-08 08:05:13 +00:00
package gitea
2023-03-08 13:40:04 +00:00
import (
2023-03-08 15:13:49 +00:00
"bytes"
"embed"
"text/template"
2023-03-08 08:05:13 +00:00
2023-03-08 13:40:04 +00:00
"code.gitea.io/sdk/gitea"
"github.com/golangci/golangci-lint/pkg/report"
"github.com/golangci/golangci-lint/pkg/result"
2023-03-08 08:05:13 +00:00
2023-03-08 13:40:04 +00:00
"code.icb4dc0.de/prskr/nitter/nitters"
)
2023-03-08 15:13:49 +00:00
var (
_ nitters.Nitter = (*prNitter)(nil)
2023-03-08 13:40:04 +00:00
2023-03-08 15:13:49 +00:00
//go:embed templates/*
templatesFS embed.FS
2023-03-08 15:13:49 +00:00
templates *template.Template
)
func init() {
if tmpl, err := template.New("issue_templates").ParseFS(templatesFS, "templates/*.tmpl.md"); err != nil {
2023-03-08 15:13:49 +00:00
panic(err)
} else {
templates = tmpl
}
}
func NewPRNitter(cli PullReviewCreator, cfg *GiteaPRConfig) *prNitter {
2023-03-08 13:40:04 +00:00
return &prNitter{
2023-03-08 15:13:49 +00:00
PullReviewCreator: cli,
cfg: cfg,
2023-03-08 13:40:04 +00:00
}
}
//go:generate mockery --name PullReviewCreator --filename pull_review_creator.mock.go
2023-03-08 15:13:49 +00:00
type PullReviewCreator interface {
CreatePullReview(owner, repo string, index int64, opt gitea.CreatePullReviewOptions) (*gitea.PullReview, *gitea.Response, error)
}
2023-03-08 13:40:04 +00:00
type prNitter struct {
2023-03-08 15:13:49 +00:00
PullReviewCreator
2023-03-08 13:40:04 +00:00
cfg *GiteaPRConfig
}
func (p prNitter) Report(report *report.Data, issues []result.Issue) error {
2023-03-08 15:13:49 +00:00
templateBuf := bytes.Buffer{}
summaryData := map[string]any{
"Report": report,
"Issues": issues,
}
if err := templates.ExecuteTemplate(&templateBuf, "issue_summary.tmpl.md", summaryData); err != nil {
return err
2023-03-08 13:40:04 +00:00
}
pullReviewOptions := gitea.CreatePullReviewOptions{
State: gitea.ReviewStateComment,
2023-03-08 15:13:49 +00:00
Body: templateBuf.String(),
2023-03-08 13:40:04 +00:00
Comments: make([]gitea.CreatePullReviewComment, 0, len(issues)),
}
2023-03-08 15:13:49 +00:00
templateBuf.Reset()
2023-03-08 13:40:04 +00:00
for i := range issues {
2023-03-08 15:13:49 +00:00
templateData := map[string]any{
"Issue": issues[i],
}
if err := templates.ExecuteTemplate(&templateBuf, "issue_comment.tmpl.md", templateData); err != nil {
return err
}
2023-03-08 13:40:04 +00:00
pullReviewOptions.Comments = append(pullReviewOptions.Comments, gitea.CreatePullReviewComment{
2023-03-08 15:13:49 +00:00
Path: issues[i].Pos.Filename,
Body: templateBuf.String(),
NewLineNum: int64(issues[i].Pos.Line),
2023-03-08 13:40:04 +00:00
})
2023-03-08 15:13:49 +00:00
templateBuf.Reset()
2023-03-08 13:40:04 +00:00
}
_, _, err := p.CreatePullReview(p.cfg.Namespace, p.cfg.Repo, p.cfg.PRIndex, pullReviewOptions)
if err != nil {
return err
}
return nil
2023-03-08 08:05:13 +00:00
}