Skip to content

Commit

Permalink
Add sticky comment feature and ID based reference. (#61)
Browse files Browse the repository at this point in the history
* sticky comment feature
* remove unused param
  • Loading branch information
mshick committed Nov 7, 2022
1 parent f9a5a1c commit 3aa992a
Show file tree
Hide file tree
Showing 8 changed files with 212 additions and 180 deletions.
4 changes: 2 additions & 2 deletions .github/workflows/integration.yml
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ jobs:
- uses: ./
with:
message: |
**Hello**
**Hello ${{ github.run_number }}**
🌏
!
!
repo-token: ${{ secrets.GITHUB_TOKEN }}
35 changes: 18 additions & 17 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,14 @@
## Features

- Fast, runs in the GitHub Actions node.js runtime; no Docker pull needed.
- Modify issues for PRs merged to master.
- Fast, runs in the GitHub Actions node.js runtime.
- Modify issues for PRs merged to main.
- By default will post "sticky" comments. If on a subsequent run the message text changes the original comment will be updated.
- Multiple sticky comments allowed by setting unique `message-id`s.
- Multiple posts of the same comment optionally allowable.
- Supports emoji 😂😂😂!
- Supports a proxy for fork-based PRs. [See below](#proxy-for-fork-based-prs).
- Supports creating a message from a file path
- Supports creating a message from a file path.

## Usage

Expand All @@ -32,17 +34,17 @@ jobs:
🌏
!
repo-token: ${{ secrets.GITHUB_TOKEN }}
repo-token-user-login: 'github-actions[bot]' # The user.login for temporary GitHub tokens
allow-repeats: false # This is the default
message-id: 'add-pr-comment' # This is the default
```
You can even use it on PR Issues that are related to PRs that were merged into master, for example:
You can even use it on PR Issues that are related to PRs that were merged into main, for example:
```yaml
on:
push:
branches:
- master
- main

jobs:
test:
Expand All @@ -55,21 +57,20 @@ jobs:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
message: |
**Hello MASTER**
allow-repeats: true
**Hello MAIN**
```
## Configuration options
| Variable or Argument | Location | Description | Required | Default |
| --------------------- | -------- | --------------------------------------------------------------------------------------------------------------------------- | -------- | ------- |
| message | with | The message you'd like displayed, supports Markdown and all valid Unicode characters | maybe | |
| message-path | with | A path to a message you'd like displayed. Will be read and displayed just like a normal message | maybe | |
| repo-token | with | A valid GitHub token, either the temporary token GitHub provides or a personal access token | maybe | |
| repo-token-user-login | with | Define this to save on comment processing time when checking for repeats. GitHub's default token uses `github-actions[bot]` | no | |
| allow-repeats | with | A boolean flag to allow identical messages to be posted each time this action is run | no | false |
| proxy-url | with | A string for your proxy service URL if you'd like this to work with fork-based PRs | no | |
| GITHUB_TOKEN | env | A valid GitHub token, can alternatively be defined in the env | maybe | |
| Variable or Argument | Location | Description | Required | Default |
| -------------------- | -------- | ---------------------------------------------------------------------------------------------------- | -------- | ------- |
| message | with | The message you'd like displayed, supports Markdown and all valid Unicode characters. | maybe | |
| message-path | with | Path to a message you'd like displayed. Will be read and displayed just like a normal message. | maybe | |
| repo-token | with | Valid GitHub token, either the temporary token GitHub provides or a personal access token. | maybe | |
| message-id | with | Message id to use when searching existing comments. If found, updates the existing (sticky comment). | no | |
| allow-repeats | with | Boolean flag to allow identical messages to be posted each time this action is run. | no | false |
| proxy-url | with | String for your proxy service URL if you'd like this to work with fork-based PRs. | no | |
| GITHUB_TOKEN | env | Valid GitHub token, can alternatively be defined in the env. | maybe | |
## Proxy for Fork-based PRs
Expand Down
50 changes: 25 additions & 25 deletions __tests__/add-pr-comment.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,44 +3,36 @@ import * as github from '@actions/github'
import { WebhookPayload } from '@actions/github/lib/interfaces'
import { rest } from 'msw'
import { setupServer } from 'msw/node'
import * as fs from 'node:fs'
import * as path from 'node:path'
import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'
import run from '../src/main'
import apiResponse from './sample-pulls-api-response.json'

const repoFullName = 'foo/bar'
const repoToken = '12345'
const userLogin = 'github-actions[bot]'
const commitSha = 'abc123'
const simpleMessage = 'hello world'
const multilineMessage = fs
.readFileSync(path.resolve(__dirname, './message-windows.txt'))
.toString()
const multilineMessageWindows = fs
.readFileSync(path.resolve(__dirname, './message-windows.txt'))
.toString()

type Inputs = {
message: string | undefined
'message-path': string | undefined
'repo-token': string
'repo-token-user-login': string
'message-id': string
'allow-repeats': string
}

const inputs: Inputs = {
message: '',
'message-path': undefined,
'repo-token': '',
'repo-token-user-login': '',
'message-id': 'add-pr-comment',
'allow-repeats': 'false',
}

let issueNumber = 1
let getCommitPullsResponse
let getIssueCommentsResponse
const postIssueCommentsResponse = {
let postIssueCommentsResponse = {
id: 42,
}

Expand All @@ -53,6 +45,12 @@ export const handlers = [
return res(ctx.status(200), ctx.json(postIssueCommentsResponse))
},
),
rest.patch(
`https://api.github.com/repos/${repoFullName}/issues/comments/:commentId`,
(req, res, ctx) => {
return res(ctx.status(200), ctx.json(postIssueCommentsResponse))
},
),
rest.get(
`https://api.github.com/repos/${repoFullName}/issues/:issueNumber/comments`,
(req, res, ctx) => {
Expand Down Expand Up @@ -182,47 +180,49 @@ describe('add-pr-comment action', () => {
expect(core.setOutput).toHaveBeenCalledWith('comment-created', 'false')
})

it('identifies repeat messages and does not create a comment [user login provided]', async () => {
it('creates a message when the message id does not exist', async () => {
inputs.message = simpleMessage
inputs['message-path'] = undefined
inputs['repo-token'] = repoToken
inputs['repo-token-user-login'] = userLogin
inputs['allow-repeats'] = 'false'
inputs['message-id'] = 'custom-id'

const replyBody = [
{
body: simpleMessage,
user: {
login: userLogin,
},
body: `<!-- some-other-id -->\n\n${simpleMessage}`,
},
]

getIssueCommentsResponse = replyBody

await run()

expect(core.setOutput).toHaveBeenCalledWith('comment-created', 'false')
expect(core.setOutput).toHaveBeenCalledWith('comment-created', 'true')
})

it('matches multiline messages with windows line feeds against api responses with unix linefeeds [no user login provided]', async () => {
inputs.message = multilineMessageWindows
it('identifies an existing message by id and updates it', async () => {
inputs.message = simpleMessage
inputs['message-path'] = undefined
inputs['repo-token'] = repoToken
inputs['allow-repeats'] = 'false'

const commentId = 123

const replyBody = [
{
body: multilineMessage,
user: {
login: userLogin,
},
id: commentId,
body: `<!-- ${inputs['message-id']} -->\n\n${simpleMessage}`,
},
]

getIssueCommentsResponse = replyBody
postIssueCommentsResponse = {
id: commentId,
}

await run()
expect(core.setOutput).toHaveBeenCalledWith('comment-created', 'false')

expect(core.setOutput).toHaveBeenCalledWith('comment-updated', 'true')
expect(core.setOutput).toHaveBeenCalledWith('comment-id', commentId)
})
})
13 changes: 8 additions & 5 deletions action.yml
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,14 @@ inputs:
required: false
message-path:
description: "A path to a file to print as a message instead of a string."
required: false
required: false
message-id:
description: "An optional id to use for this message."
required: false
default: "add-pr-comment"
repo-token:
description: "A GitHub token for API access."
required: false
repo-token-user-login:
description: "A user login associated with your token, for temporary repo tokens this is `github-actions[bot]`."
required: false
allow-repeats:
description: "Allow messages to be repeated."
required: false
Expand All @@ -23,8 +24,10 @@ inputs:
outputs:
comment-created:
description: "Whether a comment was created."
comment-updated:
description: "Whether a comment was updated."
comment-id:
description: "If a comment was created, the id of it."
description: "If a comment was created or updated, it's id."
branding:
icon: message-circle
color: purple
Expand Down
90 changes: 50 additions & 40 deletions dist/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -39,37 +39,35 @@ const http_client_1 = __nccwpck_require__(6255);
const promises_1 = __importDefault(__nccwpck_require__(3977));
const getIssueNumberFromCommitPullsList = (commitPullsList) => (commitPullsList.length ? commitPullsList[0].number : null);
const createCommentProxy = async (params) => {
const { repoToken, owner, repo, issueNumber, body, proxyUrl } = params;
const { repoToken, owner, repo, issueNumber, body, commentId, proxyUrl } = params;
const http = new http_client_1.HttpClient('http-client-add-pr-comment');
const response = await http.postJson(`${proxyUrl}/repos/${owner}/${repo}/issues/${issueNumber}/comments`, { body }, {
const response = await http.postJson(`${proxyUrl}/repos/${owner}/${repo}/issues/${issueNumber}/comments`, { comment_id: commentId, body }, {
['temporary-github-token']: repoToken,
});
return response.result;
};
const isMessagePresent = (message, comments, login) => {
const cleanRe = new RegExp('\\R|\\s', 'g');
const messageClean = message.replace(cleanRe, '');
return comments.some(({ user, body }) => {
// If a username is provided we can save on a bit of processing
if (login && (user === null || user === void 0 ? void 0 : user.login) !== login) {
return false;
}
return (body === null || body === void 0 ? void 0 : body.replace(cleanRe, '')) === messageClean;
const getExistingCommentId = (comments, messageId) => {
const found = comments.find(({ body }) => {
var _a;
return ((_a = body === null || body === void 0 ? void 0 : body.search(messageId)) !== null && _a !== void 0 ? _a : -1) > -1;
});
return found === null || found === void 0 ? void 0 : found.id;
};
const getInputs = () => {
const messageId = core.getInput('message-id');
return {
allowRepeats: Boolean(core.getInput('allow-repeats') === 'true'),
message: core.getInput('message'),
messageId: messageId === '' ? 'add-pr-comment' : messageId,
messagePath: core.getInput('message-path'),
proxyUrl: core.getInput('proxy-url').replace(/\/$/, ''),
repoToken: core.getInput('repo-token') || process.env['GITHUB_TOKEN'],
repoTokenUserLogin: core.getInput('repo-token-user-login'),
};
};
const run = async () => {
try {
const { allowRepeats, message, messagePath, repoToken, repoTokenUserLogin, proxyUrl } = getInputs();
const { allowRepeats, message, messageId, messagePath, repoToken, proxyUrl } = getInputs();
const messageIdComment = `<!-- ${messageId} -->`;
if (!repoToken) {
throw new Error('no github token provided, set one with the repo-token input or GITHUB_TOKEN env variable');
}
Expand Down Expand Up @@ -118,47 +116,59 @@ const run = async () => {
core.setOutput('comment-created', 'false');
return;
}
let shouldCreateComment = true;
let existingCommentId;
if (!allowRepeats) {
core.debug('repeat comments are disallowed, checking for existing');
const { data: comments } = await octokit.rest.issues.listComments({
owner,
repo,
issue_number: issueNumber,
});
if (isMessagePresent(message, comments, repoTokenUserLogin)) {
core.info('the issue already contains an identical message');
shouldCreateComment = false;
existingCommentId = getExistingCommentId(comments, messageIdComment);
if (existingCommentId) {
core.debug(`existing comment found with id: ${existingCommentId}`);
}
}
let createdCommentData;
if (shouldCreateComment) {
if (proxyUrl) {
createdCommentData = await createCommentProxy({
owner,
repo,
issueNumber,
body: message,
repoToken,
proxyUrl,
});
}
else {
const createdComment = await octokit.rest.issues.createComment({
owner,
repo,
issue_number: issueNumber,
body: message,
});
createdCommentData = createdComment.data;
}
let comment;
const body = `${messageIdComment}\n\n${messageText}`;
if (proxyUrl) {
comment = await createCommentProxy({
commentId: existingCommentId,
owner,
repo,
issueNumber,
body,
repoToken,
proxyUrl,
});
core.setOutput(existingCommentId ? 'comment-updated' : 'comment-created', 'true');
}
if (createdCommentData) {
else if (existingCommentId) {
const updatedComment = await octokit.rest.issues.updateComment({
comment_id: existingCommentId,
owner,
repo,
body,
});
comment = updatedComment.data;
core.setOutput('comment-updated', 'true');
}
else {
const createdComment = await octokit.rest.issues.createComment({
issue_number: issueNumber,
owner,
repo,
body,
});
comment = createdComment.data;
core.setOutput('comment-created', 'true');
core.setOutput('comment-id', createdCommentData.id);
}
if (comment) {
core.setOutput('comment-id', comment.id);
}
else {
core.setOutput('comment-created', 'false');
core.setOutput('comment-updated', 'false');
}
}
catch (err) {
Expand Down
2 changes: 1 addition & 1 deletion dist/index.js.map

Large diffs are not rendered by default.

Loading

0 comments on commit 3aa992a

Please sign in to comment.