Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions .changeset/issue-comment-edit.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
---
'gcb-core': minor
---

Add `issue:comment-edit` (`issues: write`) and `pr:comment-edit` (`pull_requests: write`), which
PATCH one issue/PR conversation comment through a fixed gh api endpoint. The body travels in an
`--input` JSON file, never in argv. `pr:comment` also gains the person route, matching
`issue:comment`.
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -801,11 +801,13 @@ actions. Grant them on the App, then approve any changed permissions on each ins
| `pr checks` | `pull_requests: read`, `checks: read`, `statuses: read` |
| `pr status` | `pull_requests: read`, `checks: read`, `statuses: read` |
| `pr comment` | `pull_requests: write` |
| `pr comment-edit` | `pull_requests: write` |
| `pr review` | `pull_requests: write` |
| `pr review --id` (`pr:review-by-id`) | `pull_requests: read` |
| `issue create` | `issues: write` |
| `issue edit` | `issues: write` |
| `issue comment` | `issues: write` |
| `issue comment-edit` | `issues: write` |
| `issue close` | `issues: write` |
| `issue reopen` | `issues: write` |
| `issue lock` | `issues: write` |
Expand Down
51 changes: 50 additions & 1 deletion packages/core/src/actions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,8 +44,10 @@ export interface FlagSpec {

/** A fixed `gh api` request, with only typed values substituted. */
export interface ApiSpec {
readonly method: 'GET';
readonly method: 'GET' | 'PATCH';
readonly endpoint: string;
/** When true, the action sends `{ body }` as JSON through gh api --input. */
readonly jsonBody?: true;
}

/** One allowed `gh` action. */
Expand Down Expand Up @@ -81,6 +83,16 @@ export interface GhAction {
/** Values supplied by the caller, keyed by positional or flag name. */
export type ActionValues = Readonly<Record<string, string | number | boolean | readonly string[] | undefined>>;

/**
* Encode the body payload for a gh api action that posts `{ body }` as JSON.
*
* @param body - the comment text.
* @returns the JSON payload for gh api --input.
*/
export function apiBodyJson(body: string): string {
return JSON.stringify({ body });
}

/** A failure the caller can act on, and that contains no provider output. */
export class ActionError extends Error {
constructor(message: string) {
Expand Down Expand Up @@ -187,6 +199,7 @@ const PR_COMMENT: GhAction = {
flags: [{ name: 'body', type: 'string', required: true, nonEmpty: true }],
permissions: { pull_requests: 'write' },
timeoutSeconds: 120,
appUser: true,
};

// GitHub GraphQL: closePullRequest
Expand Down Expand Up @@ -393,6 +406,30 @@ const ISSUE_REOPEN: GhAction = {
target: 'issue',
};

// GitHub: PATCH /repos/{owner}/{repo}/issues/comments/{comment_id}
const ISSUE_COMMENT_EDIT: GhAction = {
name: 'issue:comment-edit',
command: ['issue', 'comment-edit'],
positionals: [{ name: 'commentId', type: 'number', required: true }],
flags: [{ name: 'body', type: 'string', required: true, nonEmpty: true }],
permissions: { issues: 'write' },
timeoutSeconds: 120,
appUser: true,
api: {
method: 'PATCH',
endpoint: 'repos/{owner}/{repo}/issues/comments/{commentId}',
jsonBody: true,
},
};

// GitHub: PATCH /repos/{owner}/{repo}/issues/comments/{comment_id}; a PR conversation comment is an issue comment
const PR_COMMENT_EDIT: GhAction = {
...ISSUE_COMMENT_EDIT,
name: 'pr:comment-edit',
command: ['pr', 'comment-edit'],
permissions: { pull_requests: 'write' },
};

// GitHub: GET /repos/{owner}/{repo}/issues/{issue_number}
const ISSUE_VIEW: GhAction = {
name: 'issue:view',
Expand Down Expand Up @@ -652,11 +689,13 @@ export const GH_ACTIONS: Readonly<Record<string, GhAction>> = Object.freeze({
'pr:checks': PR_CHECKS,
'pr:status': PR_STATUS,
'pr:comment': PR_COMMENT,
'pr:comment-edit': PR_COMMENT_EDIT,
'pr:review': PR_REVIEW,
'pr:review-by-id': PR_REVIEW_BY_ID,
'issue:create': ISSUE_CREATE,
'issue:edit': ISSUE_EDIT,
'issue:comment': ISSUE_COMMENT,
'issue:comment-edit': ISSUE_COMMENT_EDIT,
'issue:close': ISSUE_CLOSE,
'issue:reopen': ISSUE_REOPEN,
'issue:lock': ISSUE_LOCK,
Expand Down Expand Up @@ -803,6 +842,16 @@ export function buildGhArgv(
continue;
}

if (flag.name === 'body' && action.api?.jsonBody === true) {
const text = asString(value, flag.name);
if (flag.nonEmpty === true && text.trim() === '') {
throw new ActionError(`${name} needs a non-empty --${flag.name}`);
}
if (bodyFile !== undefined) argv.push('--input', bodyFile);
present.add(flag.name);
provided.add(flag.name);
continue;
}
if (flag.name === 'body' && bodyFile !== undefined) {
const text = asString(value, flag.name);
if (flag.nonEmpty === true && text.trim() === '') {
Expand Down
10 changes: 8 additions & 2 deletions packages/host/src/commands/host.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ import {
requestProblems,
writeHostBroker,
writeResult,
apiBodyJson,
HOST,
REPOSITORY,
ANSWER_TIMEOUT_MS,
Expand Down Expand Up @@ -524,10 +525,11 @@ async function personRun(
async function withBodyFile(
body: string,
work: (bodyFile: string) => Promise<HostResult>,
name = 'body.md',
): Promise<HostResult> {
const scratch = mkdtempSync(join(tmpdir(), 'gcb-body-'));
try {
const bodyFile = join(scratch, 'body.md');
const bodyFile = join(scratch, name);
writeFileSync(bodyFile, body, 'utf8');
return await work(bodyFile);
} finally {
Expand Down Expand Up @@ -643,7 +645,11 @@ async function openOne(
});
return result;
};
return body === undefined ? invoke() : withBodyFile(body, invoke);
if (body === undefined) return invoke();
if (action.api?.jsonBody === true) {
return withBodyFile(apiBodyJson(body), invoke, 'body.json');
}
return withBodyFile(body, invoke);
};

let hostBlock: ReturnType<typeof blockFor>;
Expand Down
8 changes: 5 additions & 3 deletions packages/host/src/gh.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import { tmpdir } from 'node:os';
import { StringDecoder } from 'node:string_decoder';
import path from 'node:path';

import { buildGhArgv, getGhAction, type ActionValues } from 'gcb-core';
import { apiBodyJson, buildGhArgv, getGhAction, type ActionValues } from 'gcb-core';
import { applyProxyChoice, PROXY_ENV_KEYS } from './http.ts';

/** The default stdout/stderr ceiling, in bytes per stream. */
Expand Down Expand Up @@ -231,8 +231,10 @@ export async function runGhAction(options: GhRunOptions): Promise<GhRunResult> {
// argv, so this is about the free-form body rather than everything the person wrote.
let bodyFile: string | undefined;
if (typeof options.values['body'] === 'string') {
bodyFile = path.join(home, 'body.md');
writeFileSync(bodyFile, options.values['body'], { mode: 0o600 });
const apiBody = action.api?.jsonBody === true;
bodyFile = path.join(home, apiBody ? 'body.json' : 'body.md');
const content = apiBody ? apiBodyJson(options.values['body']) : options.values['body'];
writeFileSync(bodyFile, content, { mode: 0o600 });
}
const argv = buildGhArgv(action.name, options.values, options.repo, bodyFile);
return await new Promise<GhRunResult>((resolve) => {
Expand Down
14 changes: 14 additions & 0 deletions test/unit/actions.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,11 +27,13 @@ describe('gh action catalog', () => {
'pr:checks',
'pr:status',
'pr:comment',
'pr:comment-edit',
'pr:review',
'pr:review-by-id',
'issue:create',
'issue:edit',
'issue:comment',
'issue:comment-edit',
'issue:close',
'issue:reopen',
'issue:lock',
Expand Down Expand Up @@ -90,6 +92,13 @@ describe('gh action catalog', () => {
});
assert.deepEqual(getGhAction('issue:view').permissions, { issues: 'read' });
assert.deepEqual(getGhAction('issue:list').permissions, { issues: 'read' });
assert.deepEqual(getGhAction('issue:comment-edit').permissions, { issues: 'write' });
assert.equal(getGhAction('issue:comment-edit').command.join(' '), 'issue comment-edit');
assert.deepEqual(getGhAction('pr:comment-edit').permissions, { pull_requests: 'write' });
assert.equal(getGhAction('pr:comment').appUser, true);
assert.equal(getGhAction('pr:comment-edit').appUser, true);
assert.equal(getGhAction('pr:comment-edit').command.join(' '), 'pr comment-edit');
assert.equal(getGhAction('issue:comment-edit').appUser, true);
assert.deepEqual(getGhAction('release:list').permissions, { contents: 'read' });
assert.deepEqual(getGhAction('release:view').permissions, { contents: 'read' });
assert.deepEqual(getGhAction('workflow:list').permissions, { actions: 'read' });
Expand Down Expand Up @@ -206,6 +215,11 @@ describe('buildGhArgv', () => {
buildGhArgv('workflow:view', { workflow: 'ci.yml', ref: 'main', yaml: true }, 'acme/widget'),
['workflow', 'view', '--ref', 'main', '--yaml', '--repo', 'acme/widget', '--', 'ci.yml'],
);
assert.deepEqual(
buildGhArgv('issue:comment-edit', { commentId: 123, body: 'secret' }, 'acme/widget', '/tmp/body.json'),
['api', '--method', 'PATCH', 'repos/acme/widget/issues/comments/123', '--input', '/tmp/body.json'],
);

assert.deepEqual(buildGhArgv('workflow:list', { all: true, limit: 10 }, 'acme/widget'), [
'workflow',
'list',
Expand Down
16 changes: 16 additions & 0 deletions test/unit/gh.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -186,6 +186,22 @@ describe('runGhAction', { skip: onWindows }, () => {
assert.equal(result.stdout, 'ok\n');
});

it('passes an issue-comment edit body through an input file', async () => {
const gh = shim('printf "ARGS=%s\n" "$*"; while [ "$#" -gt 0 ]; do if [ "$1" = "--input" ]; then cat "$2"; fi; shift; done');
const result = await runGhAction({
action: 'issue:comment-edit',
values: { commentId: 123, body: 'secret edit' },
repo: 'acme/widget',
token: 'app-token',
ghPath: gh,
env: { PATH: process.env.PATH },
});
assert.equal(result.code, 0);
assert.match(result.stdout, /api --method PATCH repos\/acme\/widget\/issues\/comments\/123 --input/u);
assert.match(result.stdout, /"body":"secret edit"/u);
assert.doesNotMatch(result.stdout, /ARGS=.*secret edit/u);
});

it('SIGKILLs after the grace period when the process ignores SIGTERM', async () => {
const timeoutMs = 2_000;
const gh = shim('trap "" TERM; while :; do sleep 1; done');
Expand Down
30 changes: 30 additions & 0 deletions test/unit/host.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -434,6 +434,36 @@ describe('the host action route', () => {
}
});

it('passes a comment edit body as JSON through --input', async () => {
const root = mkdtempSync(join(tmpdir(), 'host-broker-comment-edit-'));
const repo = join(root, 'checkout');
mkdirSync(join(repo, '.git'), { recursive: true });
writeFileSync(join(repo, '.git', 'HEAD'), 'ref: refs/heads/main\n', 'utf8');
const config = forkConfig(root, 'acme/widget');
const dir = channelDir(join(repo, '.git'));
const captured = join(root, 'captured.json');
const command = join(root, 'not-gh');
writeFileSync(
command,
'#!/bin/sh\nwhile [ "$#" -gt 0 ]; do if [ "$1" = "--input" ]; then cat "$2" > ' + captured + '; fi; shift; done\necho ok\n',
'utf8',
);
chmodSync(command, 0o755);
try {
const id = writeRequest(dir, {
kind: 'action',
action: 'pr:comment-edit',
repo: 'acme/widget',
values: { commentId: 123, body: 'secret edit' },
});
assert.equal(await runHostBroker(['--repo', repo, '--command', command, '--config', config, '--once']), 0);
assert.equal(readResult(dir, id)?.stdout, 'ok\n');
assert.equal(readFileSync(captured, 'utf8'), '{"body":"secret edit"}');
} finally {
rmSync(root, { recursive: true, force: true });
}
});

it('runs a catalogued action and returns its output', async () => {
const root = mkdtempSync(join(tmpdir(), 'host-broker-action-'));
const repo = join(root, 'checkout');
Expand Down
Loading