adds support for message-path (#58)

This commit is contained in:
Michael Shick 2022-11-05 09:52:35 -04:00 committed by GitHub
parent 841d232c5a
commit cd100c8b09
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
8 changed files with 110 additions and 19 deletions

View file

@ -52,7 +52,7 @@ jobs:
run: | run: |
npm run build npm run build
- uses: mshick/add-pr-comment@v2 - uses: ./
with: with:
message: | message: |
**Hello** **Hello**

View file

@ -9,6 +9,7 @@
- Multiple posts of the same comment optionally allowable. - Multiple posts of the same comment optionally allowable.
- Supports emoji 😂😂😂! - Supports emoji 😂😂😂!
- Supports a proxy for fork-based PRs. [See below](#proxy-for-fork-based-prs). - Supports a proxy for fork-based PRs. [See below](#proxy-for-fork-based-prs).
- Supports creating a message from a file path
## Usage ## Usage
@ -56,7 +57,8 @@ jobs:
| Variable or Argument | Location | Description | Required | Default | | Variable or Argument | Location | Description | Required | Default |
| --------------------- | -------- | --------------------------------------------------------------------------------------------------------------------------- | -------- | ------- | | --------------------- | -------- | --------------------------------------------------------------------------------------------------------------------------- | -------- | ------- |
| message | with | The message you'd like displayed, supports Markdown and all valid Unicode characters | yes | | | 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 | 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 | | | 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 | | allow-repeats | with | A boolean flag to allow identical messages to be posted each time this action is run | no | false |

View file

@ -21,8 +21,17 @@ const multilineMessageWindows = fs
.readFileSync(path.resolve(__dirname, './message-windows.txt')) .readFileSync(path.resolve(__dirname, './message-windows.txt'))
.toString() .toString()
const inputs = { type Inputs = {
message: string | undefined
'message-path': string | undefined
'repo-token': string
'repo-token-user-login': string
'allow-repeats': string
}
const inputs: Inputs = {
message: '', message: '',
'message-path': undefined,
'repo-token': '', 'repo-token': '',
'repo-token-user-login': '', 'repo-token-user-login': '',
'allow-repeats': 'false', 'allow-repeats': 'false',
@ -90,20 +99,17 @@ describe('add-pr-comment action', () => {
server.resetHandlers() server.resetHandlers()
}) })
vi.mocked(core.getInput).mockImplementation((name: string) => { vi.mocked(core.getInput).mockImplementation((name: string, options?: core.InputOptions) => {
switch (name) { const value = inputs[name] ?? ''
case 'message':
return inputs.message if (options?.required && value === undefined) {
case 'repo-token': throw new Error(`${name} is required`)
return inputs['repo-token']
case 'allow-repeats':
return inputs['allow-repeats']
default:
return ''
} }
return value
}) })
it('creates a comment', async () => { it('creates a comment with message text', async () => {
inputs.message = simpleMessage inputs.message = simpleMessage
inputs['repo-token'] = repoToken inputs['repo-token'] = repoToken
inputs['allow-repeats'] = 'true' inputs['allow-repeats'] = 'true'
@ -113,10 +119,31 @@ describe('add-pr-comment action', () => {
expect(core.setOutput).toHaveBeenCalledWith('comment-id', postIssueCommentsResponse.id) expect(core.setOutput).toHaveBeenCalledWith('comment-id', postIssueCommentsResponse.id)
}) })
it('creates a comment with a message-path', async () => {
inputs.message = undefined
inputs['message-path'] = path.resolve(__dirname, './message.txt')
inputs['repo-token'] = repoToken
inputs['allow-repeats'] = 'true'
await expect(run()).resolves.not.toThrow()
expect(core.setOutput).toHaveBeenCalledWith('comment-created', 'true')
expect(core.setOutput).toHaveBeenCalledWith('comment-id', postIssueCommentsResponse.id)
})
it('fails when both message and message-path are defined', async () => {
inputs.message = 'foobar'
inputs['message-path'] = path.resolve(__dirname, './message.txt')
inputs['repo-token'] = repoToken
await expect(run()).resolves.not.toThrow()
expect(core.setFailed).toHaveBeenCalledWith('must specify only one, message or message-path')
})
it('creates a comment in an existing PR', async () => { it('creates a comment in an existing PR', async () => {
process.env['GITHUB_TOKEN'] = repoToken process.env['GITHUB_TOKEN'] = repoToken
inputs.message = simpleMessage inputs.message = simpleMessage
inputs['message-path'] = undefined
inputs['repo-token'] = repoToken inputs['repo-token'] = repoToken
inputs['allow-repeats'] = 'true' inputs['allow-repeats'] = 'true'
@ -139,6 +166,7 @@ describe('add-pr-comment action', () => {
process.env['GITHUB_TOKEN'] = repoToken process.env['GITHUB_TOKEN'] = repoToken
inputs.message = simpleMessage inputs.message = simpleMessage
inputs['message-path'] = undefined
inputs['allow-repeats'] = 'true' inputs['allow-repeats'] = 'true'
github.context.payload = { github.context.payload = {
@ -156,6 +184,7 @@ describe('add-pr-comment action', () => {
it('identifies repeat messages and does not create a comment [user login provided]', async () => { it('identifies repeat messages and does not create a comment [user login provided]', async () => {
inputs.message = simpleMessage inputs.message = simpleMessage
inputs['message-path'] = undefined
inputs['repo-token'] = repoToken inputs['repo-token'] = repoToken
inputs['repo-token-user-login'] = userLogin inputs['repo-token-user-login'] = userLogin
inputs['allow-repeats'] = 'false' inputs['allow-repeats'] = 'false'
@ -178,6 +207,7 @@ describe('add-pr-comment action', () => {
it('matches multiline messages with windows line feeds against api responses with unix linefeeds [no user login provided]', async () => { it('matches multiline messages with windows line feeds against api responses with unix linefeeds [no user login provided]', async () => {
inputs.message = multilineMessageWindows inputs.message = multilineMessageWindows
inputs['message-path'] = undefined
inputs['repo-token'] = repoToken inputs['repo-token'] = repoToken
inputs['allow-repeats'] = 'false' inputs['allow-repeats'] = 'false'

View file

@ -3,7 +3,10 @@ description: "Add a comment to a pull request"
inputs: inputs:
message: message:
description: "The message to print." description: "The message to print."
required: true required: false
message-path:
description: "A path to a file to print as a message instead of a string."
required: false
repo-token: repo-token:
description: "A GitHub token for API access." description: "A GitHub token for API access."
required: false required: false

25
dist/index.js vendored
View file

@ -1107,10 +1107,14 @@ var __importStar = (this && this.__importStar) || function (mod) {
__setModuleDefault(result, mod); __setModuleDefault(result, mod);
return result; return result;
}; };
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true }); Object.defineProperty(exports, "__esModule", { value: true });
const core = __importStar(__webpack_require__(470)); const core = __importStar(__webpack_require__(470));
const github = __importStar(__webpack_require__(469)); const github = __importStar(__webpack_require__(469));
const http_client_1 = __webpack_require__(425); const http_client_1 = __webpack_require__(425);
const promises_1 = __importDefault(__webpack_require__(269));
const listCommitPulls = async (params) => { const listCommitPulls = async (params) => {
const { repoToken, owner, repo, commitSha } = params; const { repoToken, owner, repo, commitSha } = params;
const http = new http_client_1.HttpClient('http-client-add-pr-comment'); const http = new http_client_1.HttpClient('http-client-add-pr-comment');
@ -1145,6 +1149,7 @@ const getInputs = () => {
return { return {
allowRepeats: Boolean(core.getInput('allow-repeats') === 'true'), allowRepeats: Boolean(core.getInput('allow-repeats') === 'true'),
message: core.getInput('message'), message: core.getInput('message'),
messagePath: core.getInput('message-path'),
proxyUrl: core.getInput('proxy-url').replace(/\/$/, ''), proxyUrl: core.getInput('proxy-url').replace(/\/$/, ''),
repoToken: core.getInput('repo-token') || process.env['GITHUB_TOKEN'], repoToken: core.getInput('repo-token') || process.env['GITHUB_TOKEN'],
repoTokenUserLogin: core.getInput('repo-token-user-login'), repoTokenUserLogin: core.getInput('repo-token-user-login'),
@ -1152,10 +1157,20 @@ const getInputs = () => {
}; };
const run = async () => { const run = async () => {
try { try {
const { allowRepeats, message, repoToken, repoTokenUserLogin, proxyUrl } = getInputs(); const { allowRepeats, message, messagePath, repoToken, repoTokenUserLogin, proxyUrl } = getInputs();
if (!repoToken) { if (!repoToken) {
throw new Error('no github token provided, set one with the repo-token input or GITHUB_TOKEN env variable'); throw new Error('no github token provided, set one with the repo-token input or GITHUB_TOKEN env variable');
} }
if (message && messagePath) {
throw new Error('must specify only one, message or message-path');
}
let messageText = message;
if (messagePath) {
messageText = await promises_1.default.readFile(messagePath, { encoding: 'utf8' });
}
if (!messageText) {
throw new Error('could not get message text, check your message-path');
}
const { payload: { pull_request: pullRequest, issue, repository }, sha: commitSha, } = github.context; const { payload: { pull_request: pullRequest, issue, repository }, sha: commitSha, } = github.context;
if (!repository) { if (!repository) {
core.info('unable to determine repository from request type'); core.info('unable to determine repository from request type');
@ -1429,6 +1444,14 @@ class Context {
exports.Context = Context; exports.Context = Context;
//# sourceMappingURL=context.js.map //# sourceMappingURL=context.js.map
/***/ }),
/***/ 269:
/***/ (function(module) {
module.exports = eval("require")("node:fs/promises");
/***/ }), /***/ }),
/***/ 280: /***/ 280:

2
dist/index.js.map vendored

File diff suppressed because one or more lines are too long

View file

@ -22,10 +22,14 @@ var __importStar = (this && this.__importStar) || function (mod) {
__setModuleDefault(result, mod); __setModuleDefault(result, mod);
return result; return result;
}; };
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true }); Object.defineProperty(exports, "__esModule", { value: true });
const core = __importStar(require("@actions/core")); const core = __importStar(require("@actions/core"));
const github = __importStar(require("@actions/github")); const github = __importStar(require("@actions/github"));
const http_client_1 = require("@actions/http-client"); const http_client_1 = require("@actions/http-client");
const promises_1 = __importDefault(require("node:fs/promises"));
const listCommitPulls = async (params) => { const listCommitPulls = async (params) => {
const { repoToken, owner, repo, commitSha } = params; const { repoToken, owner, repo, commitSha } = params;
const http = new http_client_1.HttpClient('http-client-add-pr-comment'); const http = new http_client_1.HttpClient('http-client-add-pr-comment');
@ -60,6 +64,7 @@ const getInputs = () => {
return { return {
allowRepeats: Boolean(core.getInput('allow-repeats') === 'true'), allowRepeats: Boolean(core.getInput('allow-repeats') === 'true'),
message: core.getInput('message'), message: core.getInput('message'),
messagePath: core.getInput('message-path'),
proxyUrl: core.getInput('proxy-url').replace(/\/$/, ''), proxyUrl: core.getInput('proxy-url').replace(/\/$/, ''),
repoToken: core.getInput('repo-token') || process.env['GITHUB_TOKEN'], repoToken: core.getInput('repo-token') || process.env['GITHUB_TOKEN'],
repoTokenUserLogin: core.getInput('repo-token-user-login'), repoTokenUserLogin: core.getInput('repo-token-user-login'),
@ -67,10 +72,20 @@ const getInputs = () => {
}; };
const run = async () => { const run = async () => {
try { try {
const { allowRepeats, message, repoToken, repoTokenUserLogin, proxyUrl } = getInputs(); const { allowRepeats, message, messagePath, repoToken, repoTokenUserLogin, proxyUrl } = getInputs();
if (!repoToken) { if (!repoToken) {
throw new Error('no github token provided, set one with the repo-token input or GITHUB_TOKEN env variable'); throw new Error('no github token provided, set one with the repo-token input or GITHUB_TOKEN env variable');
} }
if (message && messagePath) {
throw new Error('must specify only one, message or message-path');
}
let messageText = message;
if (messagePath) {
messageText = await promises_1.default.readFile(messagePath, { encoding: 'utf8' });
}
if (!messageText) {
throw new Error('could not get message text, check your message-path');
}
const { payload: { pull_request: pullRequest, issue, repository }, sha: commitSha, } = github.context; const { payload: { pull_request: pullRequest, issue, repository }, sha: commitSha, } = github.context;
if (!repository) { if (!repository) {
core.info('unable to determine repository from request type'); core.info('unable to determine repository from request type');

View file

@ -2,6 +2,7 @@ import * as core from '@actions/core'
import * as github from '@actions/github' import * as github from '@actions/github'
import { HttpClient } from '@actions/http-client' import { HttpClient } from '@actions/http-client'
import { Endpoints, RequestHeaders } from '@octokit/types' import { Endpoints, RequestHeaders } from '@octokit/types'
import fs from 'node:fs/promises'
type ListCommitPullsResponseData = type ListCommitPullsResponseData =
Endpoints['GET /repos/{owner}/{repo}/commits/{commit_sha}/pulls']['response']['data'] Endpoints['GET /repos/{owner}/{repo}/commits/{commit_sha}/pulls']['response']['data']
@ -88,6 +89,7 @@ const isMessagePresent = (
interface AddPrCommentInputs { interface AddPrCommentInputs {
allowRepeats: boolean allowRepeats: boolean
message: string message: string
messagePath: string
proxyUrl?: string proxyUrl?: string
repoToken?: string repoToken?: string
repoTokenUserLogin?: string repoTokenUserLogin?: string
@ -97,6 +99,7 @@ const getInputs = (): AddPrCommentInputs => {
return { return {
allowRepeats: Boolean(core.getInput('allow-repeats') === 'true'), allowRepeats: Boolean(core.getInput('allow-repeats') === 'true'),
message: core.getInput('message'), message: core.getInput('message'),
messagePath: core.getInput('message-path'),
proxyUrl: core.getInput('proxy-url').replace(/\/$/, ''), proxyUrl: core.getInput('proxy-url').replace(/\/$/, ''),
repoToken: core.getInput('repo-token') || process.env['GITHUB_TOKEN'], repoToken: core.getInput('repo-token') || process.env['GITHUB_TOKEN'],
repoTokenUserLogin: core.getInput('repo-token-user-login'), repoTokenUserLogin: core.getInput('repo-token-user-login'),
@ -105,7 +108,8 @@ const getInputs = (): AddPrCommentInputs => {
const run = async (): Promise<void> => { const run = async (): Promise<void> => {
try { try {
const { allowRepeats, message, repoToken, repoTokenUserLogin, proxyUrl } = getInputs() const { allowRepeats, message, messagePath, repoToken, repoTokenUserLogin, proxyUrl } =
getInputs()
if (!repoToken) { if (!repoToken) {
throw new Error( throw new Error(
@ -113,6 +117,20 @@ const run = async (): Promise<void> => {
) )
} }
if (message && messagePath) {
throw new Error('must specify only one, message or message-path')
}
let messageText = message
if (messagePath) {
messageText = await fs.readFile(messagePath, { encoding: 'utf8' })
}
if (!messageText) {
throw new Error('could not get message text, check your message-path')
}
const { const {
payload: { pull_request: pullRequest, issue, repository }, payload: { pull_request: pullRequest, issue, repository },
sha: commitSha, sha: commitSha,