Skip to content

Commit

Permalink
jenkins: try edit existing comment or else create a new comment (#228)
Browse files Browse the repository at this point in the history
* Try to first a comment to edit before creating

* Update lib/github-graphql-client.js

Co-Authored-By: refack <refack@gmail.com>

* Get GraphQL fixture in place to fix broken tests

* Add test verifying edited CI comments
  • Loading branch information
refack authored and phillipj committed Jun 10, 2019
1 parent 4b51d18 commit 1cbae04
Show file tree
Hide file tree
Showing 8 changed files with 341 additions and 30 deletions.
61 changes: 53 additions & 8 deletions lib/github-comment.js
Original file line number Diff line number Diff line change
@@ -1,16 +1,61 @@
'use strict'

const githubClient = require('./github-client')
const GQL = require('./github-graphql-client')

const getPRComments = `query getPRComments($owner: String!, $repo: String!, $number: Int!, $cursor: String){
repository(owner: $owner, name: $repo) {
pullRequest(number: $number) {
comments(first: 20, after:$cursor) {
nodes {
id
body
viewerDidAuthor
}
pageInfo {
endCursor
hasNextPage
}
}
labels(first: 15) {
nodes {
name
}
}
}
}
}`

function graphQlIdToRestId (nodeId) {
const decoded = Buffer.from(nodeId, 'base64').toString()
return decoded.match(/\d+$/)[0]
}

exports.getFirstBotComment = function getFirstBotComment ({ owner, repo, number }, cursor = null) {
return GQL(getPRComments, { owner, repo, number, cursor }).then(data => {
const { nodes, pageInfo } = data.repository.pullRequest.comments
const firstBotComment = nodes.find(e => e.viewerDidAuthor)
if (firstBotComment) {
return firstBotComment
}
if (pageInfo.hasNextPage) {
return exports.getFirstBotComment({ owner, repo, number }, pageInfo.endCursor)
}
return null
})
}

exports.createPrComment = function createPrComment ({ owner, repo, number, logger }, body) {
githubClient.issues.createComment({
owner,
repo,
number,
body
}, (err) => {
if (err) {
logger.error(err, 'Error while creating comment on GitHub')
exports.getFirstBotComment({ owner, repo, number, logger }).then((comment) => {
if (comment) {
const { id: nodeId, body: oldBody } = comment
const newBody = `${oldBody}\n${body}`
const id = graphQlIdToRestId(nodeId)
return githubClient.issues.editComment({ owner, repo, id, body: newBody })
}
return githubClient.issues.createComment({ owner, repo, number, body })
}).catch((err) => {
logger.error(err, 'Error while creating comment on GitHub')
// swallow error
})
}
10 changes: 10 additions & 0 deletions lib/github-graphql-client.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
'use strict'

const GitHubGQL = require('@octokit/graphql').defaults({
headers: {
'user-agent': 'Node.js GitHub Bot v1.0-beta',
authorization: 'token ' + (process.env.GITHUB_TOKEN || 'invalid-placeholder-token')
}
})

module.exports = GitHubGQL
Loading

0 comments on commit 1cbae04

Please sign in to comment.