-
Notifications
You must be signed in to change notification settings - Fork 5
/
pr.go
196 lines (160 loc) · 4.78 KB
/
pr.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
package pr
import (
"bytes"
"regexp"
"strings"
"text/template"
"github.com/AlecAivazis/survey/v2"
"github.com/caarlos0/log"
"github.com/pkg/errors"
"github.com/samber/lo"
"github.com/ilaif/gh-prx/pkg/config"
"github.com/ilaif/gh-prx/pkg/models"
"github.com/ilaif/gh-prx/pkg/utils"
)
var (
TypeToLabel = map[string]string{
"fix": "bug",
"feat": "enhancement",
"feature": "enhancement",
"docs": "documentation",
"task": "chore",
}
mdCheckboxMatcher = regexp.MustCompile(`^\s*[\-\*]\s*\[(x|\s)\]`)
commitMsgSeparatorMatcher = regexp.MustCompile(`[\*\-]`)
mapHasNoEntryForKeyMatcher = regexp.MustCompile(`map has no entry for key "(.*)"`)
)
type AISummarizer func() (string, error)
func TemplatePR(
b models.Branch,
prCfg config.PullRequestConfig,
confirm bool,
tokenSeparators []string,
commits []string,
aiSummarizer func() (string, error),
) (*models.PullRequest, error) {
log.Debug("Templating PR")
funcMaps, err := utils.GenerateTemplateFunctions(tokenSeparators)
if err != nil {
return nil, errors.Wrap(err, "Failed to generate template functions")
}
pr := &models.PullRequest{}
var res bytes.Buffer
titleTpl, err := template.New("pr-title-tpl").Funcs(funcMaps).Parse(prCfg.Title)
if err != nil {
return nil, errors.Wrap(err, "Failed to parse pr title template")
}
for {
res = bytes.Buffer{}
err := titleTpl.Option("missingkey=error").Execute(&res, b.Fields)
if err == nil {
break
}
matches := mapHasNoEntryForKeyMatcher.FindStringSubmatch(err.Error())
if len(matches) == 0 {
return nil, errors.Wrap(err, "Failed to template pr title")
}
log.Warn("Missing key in branch fields, prompting user to enter it manually")
answer := ""
if err := survey.AskOne(&survey.Input{
Message: "Enter value for " + matches[1],
}, &answer, survey.WithValidator(survey.Required)); err != nil {
return nil, errors.Wrap(err, "Failed to ask for missing field value")
}
b.Fields[matches[1]] = answer
}
pr.Title = res.String()
bodyData := lo.Assign(b.Fields, make(map[string]any))
prBody := prCfg.Body
if strings.Contains(prBody, ".Commits") {
commits, err := processCommits(prCfg.IgnoreCommitsPatterns, commits)
if err != nil {
return nil, err
}
bodyData["Commits"] = commits
}
aiSummary, err := aiSummarizer()
if err != nil {
return nil, err
}
if strings.Contains(prBody, ".AISummary") {
bodyData["AISummary"] = aiSummary
} else if aiSummary != "" {
prBody = aiSummary
}
res = bytes.Buffer{}
bodyTpl, err := template.New("pr-body-tpl").Funcs(funcMaps).Parse(prBody)
if err != nil {
return nil, errors.Wrap(err, "Failed to parse pr body template")
}
if err := bodyTpl.Option("missingkey=zero").Execute(&res, bodyData); err != nil {
return nil, errors.Wrap(err, "Failed to template pr body")
}
pr.Body = res.String()
if *prCfg.AnswerChecklist {
body, err := answerPRChecklist(pr.Body, confirm)
if err != nil {
return nil, err
}
pr.Body = body
}
if typeAny, ok := b.Fields["Type"]; ok {
if typeStr, ok := typeAny.(string); ok {
typeStr = strings.ToLower(typeStr)
label, ok := TypeToLabel[typeStr]
if !ok {
label = typeStr
}
pr.Labels = append(pr.Labels, label)
}
}
return pr, nil
}
func processCommits(ignoreCommitsPatterns []string, commits []string) ([]string, error) {
ignoreCommitsMatcher, err := regexp.Compile(strings.Join(ignoreCommitsPatterns, "|"))
if err != nil {
return nil, errors.Wrap(err, "Failed to compile ignore commits matcher")
}
splitCommits := []string{}
for _, commit := range commits {
splitCommits = append(splitCommits, commitMsgSeparatorMatcher.Split(commit, -1)...)
}
splitCommits = lo.Filter(splitCommits, func(commit string, _ int) bool {
return !ignoreCommitsMatcher.MatchString(commit) && commit != ""
})
return lo.Reverse(splitCommits), nil
}
func answerPRChecklist(body string, confirm bool) (string, error) {
if confirm {
log.Info("Answering yes to all checklist items (if exists in PR description)")
}
bodyLines := strings.Split(body, "\n")
newBodyLines := []string{}
for _, line := range bodyLines {
addLine := true
if mdCheckboxMatcher.MatchString(line) {
q := mdCheckboxMatcher.ReplaceAllString(line, "")
answer := "no"
if !confirm {
if err := survey.AskOne(&survey.Select{
Message: q,
Options: []string{"yes", "no", "skip"},
}, &answer, survey.WithValidator(survey.Required)); err != nil {
return "", errors.Wrap(err, "Failed to ask for action item status")
}
}
switch answer {
case "yes":
line = mdCheckboxMatcher.ReplaceAllString(line, "- [x]")
case "no":
line = mdCheckboxMatcher.ReplaceAllString(line, "- [ ]")
case "skip":
addLine = false
}
}
if addLine {
newBodyLines = append(newBodyLines, line)
}
}
return strings.Join(newBodyLines, "\n"), nil
}