Skip to content

Commit 1cbae04

Browse files
refackphillipj
authored andcommitted
jenkins: try edit existing comment or else create a new comment (#228)
* Try to first a comment to edit before creating * Update lib/github-graphql-client.js Co-Authored-By: refack <[email protected]> * Get GraphQL fixture in place to fix broken tests * Add test verifying edited CI comments
1 parent 4b51d18 commit 1cbae04

8 files changed

+341
-30
lines changed

lib/github-comment.js

+53-8
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,61 @@
11
'use strict'
22

33
const githubClient = require('./github-client')
4+
const GQL = require('./github-graphql-client')
5+
6+
const getPRComments = `query getPRComments($owner: String!, $repo: String!, $number: Int!, $cursor: String){
7+
repository(owner: $owner, name: $repo) {
8+
pullRequest(number: $number) {
9+
comments(first: 20, after:$cursor) {
10+
nodes {
11+
id
12+
body
13+
viewerDidAuthor
14+
}
15+
pageInfo {
16+
endCursor
17+
hasNextPage
18+
}
19+
}
20+
labels(first: 15) {
21+
nodes {
22+
name
23+
}
24+
}
25+
}
26+
}
27+
}`
28+
29+
function graphQlIdToRestId (nodeId) {
30+
const decoded = Buffer.from(nodeId, 'base64').toString()
31+
return decoded.match(/\d+$/)[0]
32+
}
33+
34+
exports.getFirstBotComment = function getFirstBotComment ({ owner, repo, number }, cursor = null) {
35+
return GQL(getPRComments, { owner, repo, number, cursor }).then(data => {
36+
const { nodes, pageInfo } = data.repository.pullRequest.comments
37+
const firstBotComment = nodes.find(e => e.viewerDidAuthor)
38+
if (firstBotComment) {
39+
return firstBotComment
40+
}
41+
if (pageInfo.hasNextPage) {
42+
return exports.getFirstBotComment({ owner, repo, number }, pageInfo.endCursor)
43+
}
44+
return null
45+
})
46+
}
447

548
exports.createPrComment = function createPrComment ({ owner, repo, number, logger }, body) {
6-
githubClient.issues.createComment({
7-
owner,
8-
repo,
9-
number,
10-
body
11-
}, (err) => {
12-
if (err) {
13-
logger.error(err, 'Error while creating comment on GitHub')
49+
exports.getFirstBotComment({ owner, repo, number, logger }).then((comment) => {
50+
if (comment) {
51+
const { id: nodeId, body: oldBody } = comment
52+
const newBody = `${oldBody}\n${body}`
53+
const id = graphQlIdToRestId(nodeId)
54+
return githubClient.issues.editComment({ owner, repo, id, body: newBody })
1455
}
56+
return githubClient.issues.createComment({ owner, repo, number, body })
57+
}).catch((err) => {
58+
logger.error(err, 'Error while creating comment on GitHub')
59+
// swallow error
1560
})
1661
}

lib/github-graphql-client.js

+10
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
'use strict'
2+
3+
const GitHubGQL = require('@octokit/graphql').defaults({
4+
headers: {
5+
'user-agent': 'Node.js GitHub Bot v1.0-beta',
6+
authorization: 'token ' + (process.env.GITHUB_TOKEN || 'invalid-placeholder-token')
7+
}
8+
})
9+
10+
module.exports = GitHubGQL

0 commit comments

Comments
 (0)