Skip to content

Commit 65ec31f

Browse files
authored
Merge pull request vince-riv#31 from vince-riv/chore/long-comments
feat: properly handle long diff comments
2 parents a8b0d68 + 48ca292 commit 65ec31f

File tree

6 files changed

+532
-119
lines changed

6 files changed

+532
-119
lines changed

Diff for: cmd/main.go

+13-2
Original file line numberDiff line numberDiff line change
@@ -70,6 +70,7 @@ func processEvent(eventInfo webhook.EventInfo) {
7070
unknownCount := 0 // how many apps we can't determine if there's changes (usually when we can new manifests but not current ones)
7171
firstError := "" // string of the first error we receive - used in commit status message
7272
markdown := "" // markdown for pull request comment
73+
cMarkdown := github.CommentMarkdown{}
7374
for _, a := range appResList {
7475
appName := a.ArgoApp.ObjectMeta.Name
7576
appSyncStatus := a.ArgoApp.Status.Sync.Status
@@ -80,16 +81,19 @@ func processEvent(eventInfo webhook.EventInfo) {
8081
errorCount++
8182
markdown += github.AppMarkdownStart(appName, "Error: "+a.WarnStr, appSyncStatus, appHealthStatus, appHealthMsg)
8283
markdown += github.AppMarkdownEnd()
84+
_ = cMarkdown.AppMarkdown(appName, "Error: "+a.WarnStr, appSyncStatus, appHealthStatus, appHealthMsg)
8385
if firstError == "" {
8486
firstError = a.WarnStr
8587
}
8688
} else {
8789
if len(a.ChangedResources) > 0 {
8890
changeCount++
8991
markdown += github.AppMarkdownStart(appName, "", appSyncStatus, appHealthStatus, appHealthMsg)
92+
appMarkdown := cMarkdown.AppMarkdown(appName, "", appSyncStatus, appHealthStatus, appHealthMsg)
9093
for _, ar := range a.ChangedResources {
9194
diffStr := gendiff.UnifiedDiff("live.yaml", fmt.Sprintf("%s.yaml", shortSha(eventInfo.Sha)), ar.YamlCur, ar.YamlNew)
9295
markdown += github.ResourceDiffMarkdown(ar.ApiVersion, ar.Kind, ar.Name, ar.Namespace, diffStr)
96+
appMarkdown.AddResourceDiff(ar.ApiVersion, ar.Kind, ar.Name, ar.Namespace, diffStr)
9397
}
9498
markdown += github.AppMarkdownEnd()
9599
}
@@ -127,7 +131,14 @@ func processEvent(eventInfo webhook.EventInfo) {
127131
markdownStart += " compared to live state\n"
128132
markdownStart += "\n" + tStr + "\n"
129133
// markdownStart += fmt.Sprintf(" as compared to live state in [%s](https://github.com/%s/%s/tree/%s) as of _%s_", eventInfo.BaseRef, eventInfo.RepoOwner, eventInfo.RepoName, eventInfo.BaseRef, tStr)
130-
_, _ = github.Comment(ctx, eventInfo.RepoOwner, eventInfo.RepoName, eventInfo.PrNum, markdownStart+"\n\n"+markdown)
134+
//_, _ = github.Comment(ctx, eventInfo.RepoOwner, eventInfo.RepoName, eventInfo.PrNum, markdownStart+"\n\n"+markdown)
135+
cMarkdown.Preamble = markdownStart
136+
//println(".............")
137+
//fmt.Print(markdown)
138+
//println("+++++++++++++")
139+
//fmt.Print(cMarkdown.String()[0])
140+
//println(".............")
141+
_, _ = github.Comment(ctx, eventInfo.RepoOwner, eventInfo.RepoName, eventInfo.PrNum, cMarkdown.String())
131142
return
132143
}
133144
}
@@ -211,7 +222,7 @@ func devHandler(w http.ResponseWriter, r *http.Request) {
211222
RepoOwner: "vince-riv",
212223
RepoName: "argo-diff-config",
213224
RepoDefaultRef: "main",
214-
Sha: "06cddc3a36c3b7758349104a429488901923c6c4",
225+
Sha: "ad5613a98f8db09f26981ce709ea039d3012e240",
215226
PrNum: 2,
216227
ChangeRef: "annotation",
217228
BaseRef: "main",

Diff for: internal/github/comment.go

+59-62
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,6 @@ import (
44
"context"
55
"fmt"
66
"os"
7-
"strconv"
87
"strings"
98
"sync"
109

@@ -13,10 +12,9 @@ import (
1312
)
1413

1514
var (
16-
commentClient *github.Client
17-
commentUser *github.User
18-
mux *sync.RWMutex
19-
commentLineMaxChar int
15+
commentClient *github.Client
16+
commentUser *github.User
17+
mux *sync.RWMutex
2018
)
2119

2220
const commentIdentifier = "<!-- comment produced by argo-diff -->"
@@ -29,17 +27,6 @@ func init() {
2927
commentClient = github.NewClient(nil).WithAuthToken(githubPAT)
3028
}
3129
mux = &sync.RWMutex{}
32-
33-
commentLineMaxChar = 175
34-
lineMaxCharStr := os.Getenv("COMMENT_LINE_MAX_CHARS")
35-
if lineMaxCharStr != "" {
36-
v, err := strconv.Atoi(lineMaxCharStr)
37-
if err == nil {
38-
commentLineMaxChar = v
39-
} else {
40-
log.Warn().Err(err).Msg("Failed to decode COMMENT_LINE_MAX_CHARS")
41-
}
42-
}
4330
}
4431

4532
// Populates commentUser singleton with the Github user associated with our github client
@@ -90,15 +77,16 @@ func getCommentUser(ctx context.Context) error {
9077
// }
9178
//}
9279

93-
// Returns a pointer to a pull request comment previously generated by argo-diff.
94-
// Returns nil if there is no matching comment
95-
func getExistingComment(ctx context.Context, owner, repo string, prNum int) (*github.IssueComment, error) {
80+
// Returns a list of pointers to pull request comments previously generated by argo-diff.
81+
// Returns an empty list if there is no matching comment
82+
func getExistingComments(ctx context.Context, owner, repo string, prNum int) ([]*github.IssueComment, error) {
9683
sortOpt := "created"
9784
sortDirection := "asc"
9885
issueListCommentsOpts := github.IssueListCommentsOptions{
9986
Sort: &sortOpt,
10087
Direction: &sortDirection,
10188
}
89+
var res []*github.IssueComment
10290
//var existingComment *github.IssueComment
10391
if commentClient == nil {
10492
log.Error().Msg("Cannot call github API - I don't have a client set")
@@ -121,63 +109,72 @@ func getExistingComment(ctx context.Context, owner, repo string, prNum int) (*gi
121109
log.Debug().Msgf("Checking %d comments in %s/%s#%d", len(comments), owner, repo, prNum)
122110
for _, c := range comments {
123111
if *c.User.Login == *commentUser.Login && strings.Contains(*c.Body, commentIdentifier) {
124-
return c, nil
112+
res = append(res, c)
125113
}
126114
}
127115
if resp.NextPage > 0 {
128116
issueListCommentsOpts.Page = resp.NextPage
129117
checkComments = true
130118
}
131119
}
132-
return nil, nil
120+
return res, nil
133121
}
134122

135123
// Creates or updates comment on the specified pull request
136-
func Comment(ctx context.Context, owner, repo string, prNum int, commentBody string) (int64, error) {
137-
existingComment, err := getExistingComment(ctx, owner, repo, prNum)
124+
func Comment(ctx context.Context, owner, repo string, prNum int, commentBodies []string) ([]*github.IssueComment, error) {
125+
var res []*github.IssueComment
126+
existingComments, err := getExistingComments(ctx, owner, repo, prNum)
138127
if err != nil {
139-
return -1, err
140-
}
141-
commentBody += "\n\n"
142-
commentBody += commentIdentifier
143-
commentBody += "\n"
144-
newComment := github.IssueComment{Body: truncateLines(commentBody, commentLineMaxChar)}
145-
var issueComment *github.IssueComment
146-
var resp *github.Response
147-
if existingComment != nil {
148-
issueComment, resp, err = commentClient.Issues.EditComment(ctx, owner, repo, *existingComment.ID, &newComment)
149-
} else {
150-
issueComment, resp, err = commentClient.Issues.CreateComment(ctx, owner, repo, prNum, &newComment)
151-
}
152-
if resp != nil {
153-
log.Info().Msgf("%s received from %s", resp.Status, resp.Request.URL.String())
154-
}
155-
if err != nil {
156-
if existingComment != nil {
157-
log.Error().Err(err).Msgf("Failed to update comment %d for %s/%s#%d", *existingComment.ID, owner, repo, prNum)
128+
return res, err
129+
}
130+
nextExistingCommentIdx := 0
131+
for i, commentBody := range commentBodies {
132+
commentBody += "\n\n"
133+
commentBody += commentIdentifier
134+
commentBody += "\n"
135+
newComment := github.IssueComment{Body: &commentBody}
136+
var existingComment *github.IssueComment
137+
var issueComment *github.IssueComment
138+
var resp *github.Response
139+
if i < len(existingComments) {
140+
nextExistingCommentIdx = i + 1
141+
existingComment = existingComments[i]
142+
issueComment, resp, err = commentClient.Issues.EditComment(ctx, owner, repo, *existingComment.ID, &newComment)
158143
} else {
159-
log.Error().Err(err).Msgf("Failed to create comment for %s/%s#%d", owner, repo, prNum)
144+
issueComment, resp, err = commentClient.Issues.CreateComment(ctx, owner, repo, prNum, &newComment)
160145
}
161-
return -1, err
162-
}
163-
if issueComment == nil {
164-
log.Error().Msg("issueComment is nil? How did I get here?")
165-
return -1, fmt.Errorf("unknown error - issueComment is nil")
166-
}
167-
log.Info().Msgf("Created or Updated comment ID %d in %s/%s#%d: %s", *issueComment.ID, owner, repo, prNum, *issueComment.IssueURL)
168-
return *issueComment.ID, nil
169-
}
170-
171-
func truncateLines(s string, maxLen int) *string {
172-
var result string
173-
lines := strings.Split(s, "\n")
174-
for _, line := range lines {
175-
if len(line) > maxLen {
176-
result += line[:maxLen] + "...[TRUNCATED]"
146+
if resp != nil {
147+
log.Info().Msgf("%s received from %s", resp.Status, resp.Request.URL.String())
148+
}
149+
if err != nil {
150+
if existingComment != nil {
151+
log.Error().Err(err).Msgf("Failed to update comment %d for %s/%s#%d", *existingComment.ID, owner, repo, prNum)
152+
} else {
153+
log.Error().Err(err).Msgf("Failed to create comment for %s/%s#%d", owner, repo, prNum)
154+
}
155+
return res, err
156+
}
157+
if issueComment == nil {
158+
log.Error().Msg("issueComment is nil? How did I get here?")
159+
return res, fmt.Errorf("unknown error - issueComment is nil")
160+
}
161+
log.Info().Msgf("Created or Updated comment ID %d in %s/%s#%d: %s", *issueComment.ID, owner, repo, prNum, *issueComment.IssueURL)
162+
res = append(res, issueComment)
163+
}
164+
for nextExistingCommentIdx < len(existingComments) {
165+
existingComment := existingComments[nextExistingCommentIdx]
166+
truncateCommentBody := "[Refreshed diff content is in above comments]\n\n" + commentIdentifier + "\n"
167+
newComment := github.IssueComment{Body: &truncateCommentBody}
168+
issueComment, resp, err := commentClient.Issues.EditComment(ctx, owner, repo, *existingComment.ID, &newComment)
169+
if resp != nil {
170+
log.Info().Msgf("%s received from %s", resp.Status, resp.Request.URL.String())
171+
}
172+
if err != nil {
173+
log.Error().Err(err).Msgf("Failed to update comment %d for %s/%s#%d", *existingComment.ID, owner, repo, prNum)
177174
} else {
178-
result += line
175+
res = append(res, issueComment)
179176
}
180-
result += "\n"
177+
nextExistingCommentIdx++
181178
}
182-
return &result
179+
return res, nil
183180
}

0 commit comments

Comments
 (0)