diff --git a/README.md b/README.md index 2b840d6..4bbc089 100644 --- a/README.md +++ b/README.md @@ -438,6 +438,62 @@ stoke pr merge -o heavy-duty -r stoke -n 2 --delete-branch Calls `POST /api/v1/repos/{owner}/{repo}/pulls/{number}/merge`. +### `stoke pr show` + +Show details of a pull request. + +```text +Options: + -o, --owner repository owner (required) + -r, --repo repository name (required) + -n, --number pull request number (required) +``` + +```bash +stoke pr show -o heavy-duty -r stoke -n 3 +``` + +Calls `GET /api/v1/repos/{owner}/{repo}/pulls/{number}`. + +### `stoke pr comment` + +Add a comment to a pull request. + +```text +Options: + -o, --owner repository owner (required) + -r, --repo repository name (required) + -n, --number pull request number (required) + -b, --body comment body (markdown) + --body-file read the comment body from a file +``` + +```bash +stoke pr comment -o heavy-duty -r stoke -n 3 -b "Looks good." +``` + +Calls `POST /api/v1/repos/{owner}/{repo}/issues/{number}/comments`. + +### `stoke pr review` + +Submit a review on a pull request. + +```text +Options: + -o, --owner repository owner (required) + -r, --repo repository name (required) + -n, --number pull request number (required) + --event review event: approve, request-changes|request_changes, comment (required) + -b, --body review body (markdown) + --body-file read the review body from a file +``` + +```bash +stoke pr review -o heavy-duty -r stoke -n 3 --event approve -b "Ship it." +``` + +Calls `POST /api/v1/repos/{owner}/{repo}/pulls/{number}/reviews`. + ### `stoke branch list` List branches in a repository. diff --git a/src/api.js b/src/api.js index 75137e5..ea45bc2 100644 --- a/src/api.js +++ b/src/api.js @@ -167,6 +167,21 @@ class ForgejoClient { return this.post(`/repos/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}/pulls`, payload); } + async getPullRequest(owner, repo, index) { + return this.get(`/repos/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}/pulls/${index}`); + } + + async createPullRequestComment(owner, repo, index, body) { + return this.post(`/repos/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}/issues/${index}/comments`, { body }); + } + + async createPullRequestReview(owner, repo, index, event, body) { + return this.post(`/repos/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}/pulls/${index}/reviews`, { + event, + body: body || '', + }); + } + async mergePullRequest(owner, repo, index, payload) { return this.post(`/repos/${encodeURIComponent(owner)}/${encodeURIComponent(repo)}/pulls/${index}/merge`, payload); } diff --git a/src/cli.js b/src/cli.js index 5522461..954f0ae 100755 --- a/src/cli.js +++ b/src/cli.js @@ -679,6 +679,98 @@ pr } }); +pr + .command('show') + .description('Show details of a pull request') + .requiredOption('-o, --owner ', 'repository owner') + .requiredOption('-r, --repo ', 'repository name') + .requiredOption('-n, --number ', 'pull request number', parseId) + .action(async (options) => { + try { + const config = loadConfig(); + const client = ForgejoClient.fromConfig(config); + const prData = await client.getPullRequest(options.owner, options.repo, options.number); + console.log(`!${prData.number} [${prData.state}] ${prData.title}`); + console.log(`URL: ${prData.html_url}`); + console.log(`Author: ${prData.user.login}`); + console.log(`Branch: ${prData.head.ref} -> ${prData.base.ref}`); + console.log(`Mergeable: ${prData.mergeable}`); + console.log(`Created: ${prData.created_at}`); + if (prData.body) { + console.log('\n' + prData.body); + } + } catch (err) { + console.error(`Failed to show pull request: ${err.message}`); + if (err.status) console.error(`HTTP status: ${err.status}`); + process.exit(1); + } + }); + +pr + .command('comment') + .description('Add a comment to a pull request') + .requiredOption('-o, --owner ', 'repository owner') + .requiredOption('-r, --repo ', 'repository name') + .requiredOption('-n, --number ', 'pull request number', parseId) + .option('-b, --body ', 'comment body (markdown)') + .option('--body-file ', 'read the comment body from a file') + .action(async (options) => { + try { + const config = loadConfig(); + const client = ForgejoClient.fromConfig(config); + const rawBody = readBodyOption(options) || ''; + if (rawBody.trim().length === 0) { + console.error('Comment body is required. Use -b/--body or --body-file.'); + process.exit(1); + } + const result = await client.createPullRequestComment(options.owner, options.repo, options.number, rawBody); + console.log(`Comment added to !${options.number}.`); + console.log(`URL: ${result.html_url}`); + } catch (err) { + console.error(`Failed to comment on pull request: ${err.message}`); + if (err.status) console.error(`HTTP status: ${err.status}`); + process.exit(1); + } + }); + +pr + .command('review') + .description('Submit a review on a pull request') + .requiredOption('-o, --owner ', 'repository owner') + .requiredOption('-r, --repo ', 'repository name') + .requiredOption('-n, --number ', 'pull request number', parseId) + .requiredOption('--event ', 'review event: approve, request-changes|request_changes, comment') + .option('-b, --body ', 'review body (markdown)') + .option('--body-file ', 'read the review body from a file') + .action(async (options) => { + try { + const config = loadConfig(); + const client = ForgejoClient.fromConfig(config); + const eventMap = { + approve: 'APPROVED', + 'request-changes': 'REQUEST_CHANGES', + request_changes: 'REQUEST_CHANGES', + comment: 'COMMENT', + }; + const event = eventMap[options.event.toLowerCase()]; + if (!event) { + console.error(`Invalid review event: ${options.event}. Must be approve, request-changes (or request_changes), or comment.`); + process.exit(1); + } + const rawBody = readBodyOption(options) || ''; + if (event !== 'APPROVED' && rawBody.trim().length === 0) { + console.error(`Review event ${options.event} requires a non-empty body. Use -b/--body or --body-file.`); + process.exit(1); + } + await client.createPullRequestReview(options.owner, options.repo, options.number, event, rawBody); + console.log(`Review submitted on !${options.number}: ${event}.`); + } catch (err) { + console.error(`Failed to submit review: ${err.message}`); + if (err.status) console.error(`HTTP status: ${err.status}`); + process.exit(1); + } + }); + const branchCmd = program .command('branch') .description('Manage branches'); diff --git a/test/api.test.js b/test/api.test.js index 52eb911..4fede09 100644 --- a/test/api.test.js +++ b/test/api.test.js @@ -141,3 +141,41 @@ test('createIssue and createPullRequest hit the expected endpoints', async () => assert.equal(calls[0].opts.method, 'POST'); assert.equal(JSON.parse(calls[1].opts.body).head, 'h'); }); + +test('getPullRequest fetches a single pull request', async () => { + const calls = mockFetch(() => jsonResponse({ number: 7, title: 'Fix' })); + const client = new ForgejoClient('https://forge.test', 'tok'); + const pr = await client.getPullRequest('owner', 'repo', 7); + assert.equal(pr.number, 7); + assert.equal(calls[0].url, 'https://forge.test/api/v1/repos/owner/repo/pulls/7'); + assert.equal(calls[0].opts.method, 'GET'); +}); + +test('createPullRequestComment posts to the issue comments endpoint', async () => { + const calls = mockFetch(() => jsonResponse({ id: 99, html_url: 'https://forge.test/comment/99' })); + const client = new ForgejoClient('https://forge.test', 'tok'); + await client.createPullRequestComment('owner', 'repo', 7, 'Looks good.'); + assert.equal(calls[0].url, 'https://forge.test/api/v1/repos/owner/repo/issues/7/comments'); + assert.equal(calls[0].opts.method, 'POST'); + assert.equal(JSON.parse(calls[0].opts.body).body, 'Looks good.'); +}); + +test('createPullRequestReview posts the review event and body', async () => { + const calls = mockFetch(() => jsonResponse({ id: 88 })); + const client = new ForgejoClient('https://forge.test', 'tok'); + await client.createPullRequestReview('owner', 'repo', 7, 'APPROVED', 'Ship it.'); + assert.equal(calls[0].url, 'https://forge.test/api/v1/repos/owner/repo/pulls/7/reviews'); + assert.equal(calls[0].opts.method, 'POST'); + const body = JSON.parse(calls[0].opts.body); + assert.equal(body.event, 'APPROVED'); + assert.equal(body.body, 'Ship it.'); +}); + +test('createPullRequestReview preserves leading and trailing whitespace in the body', async () => { + const calls = mockFetch(() => jsonResponse({ id: 89 })); + const client = new ForgejoClient('https://forge.test', 'tok'); + const rawBody = ' code block prefix\n'; + await client.createPullRequestReview('owner', 'repo', 8, 'REQUEST_CHANGES', rawBody); + const body = JSON.parse(calls[0].opts.body); + assert.equal(body.body, rawBody); +}); diff --git a/test/cli.test.js b/test/cli.test.js index b3b4a48..3de1b83 100644 --- a/test/cli.test.js +++ b/test/cli.test.js @@ -1,7 +1,8 @@ const { test } = require('node:test'); const assert = require('node:assert/strict'); -const { execFileSync, spawnSync } = require('node:child_process'); +const { execFileSync, spawn, spawnSync } = require('node:child_process'); const fs = require('node:fs'); +const http = require('node:http'); const os = require('node:os'); const path = require('node:path'); @@ -75,3 +76,139 @@ test('issue create --body-file reports unreadable files cleanly', () => { fs.unlinkSync(cfg); } }); + +test('pr show validates --number before any network call', () => { + const cfg = path.join(os.tmpdir(), `stoke-cfg-${process.pid}.json`); + fs.writeFileSync(cfg, JSON.stringify({ url: 'https://forge.test', token: 'tok' })); + try { + const res = run(['pr', 'show', '-o', 'o', '-r', 'r', '-n', 'zero'], { STOKE_CONFIG_FILE: cfg }); + assert.equal(res.status, 1); + assert.match(res.stderr, /Id must be a positive integer/); + } finally { + fs.unlinkSync(cfg); + } +}); + +test('pr comment rejects a missing body before any network call', () => { + const cfg = path.join(os.tmpdir(), `stoke-cfg-${process.pid}.json`); + fs.writeFileSync(cfg, JSON.stringify({ url: 'https://forge.test', token: 'tok' })); + try { + const res = run(['pr', 'comment', '-o', 'o', '-r', 'r', '-n', '1'], { STOKE_CONFIG_FILE: cfg }); + assert.equal(res.status, 1); + assert.match(res.stderr, /Comment body is required/); + } finally { + fs.unlinkSync(cfg); + } +}); + +test('pr review rejects an invalid event before any network call', () => { + const cfg = path.join(os.tmpdir(), `stoke-cfg-${process.pid}.json`); + fs.writeFileSync(cfg, JSON.stringify({ url: 'https://forge.test', token: 'tok' })); + try { + const res = run(['pr', 'review', '-o', 'o', '-r', 'r', '-n', '1', '--event', 'nope'], { STOKE_CONFIG_FILE: cfg }); + assert.equal(res.status, 1); + assert.match(res.stderr, /Invalid review event/); + } finally { + fs.unlinkSync(cfg); + } +}); + +test('pr review request-changes rejects a missing body before any network call', () => { + const cfg = path.join(os.tmpdir(), `stoke-cfg-${process.pid}.json`); + fs.writeFileSync(cfg, JSON.stringify({ url: 'https://forge.test', token: 'tok' })); + try { + const res = run(['pr', 'review', '-o', 'o', '-r', 'r', '-n', '1', '--event', 'request-changes'], { STOKE_CONFIG_FILE: cfg }); + assert.equal(res.status, 1); + assert.match(res.stderr, /requires a non-empty body/); + } finally { + fs.unlinkSync(cfg); + } +}); + +test('pr review comment rejects a whitespace-only body before any network call', () => { + const cfg = path.join(os.tmpdir(), `stoke-cfg-${process.pid}.json`); + fs.writeFileSync(cfg, JSON.stringify({ url: 'https://forge.test', token: 'tok' })); + try { + const res = run(['pr', 'review', '-o', 'o', '-r', 'r', '-n', '1', '--event', 'comment', '-b', ' '], { STOKE_CONFIG_FILE: cfg }); + assert.equal(res.status, 1); + assert.match(res.stderr, /requires a non-empty body/); + } finally { + fs.unlinkSync(cfg); + } +}); + +test('pr review approve allows an empty body before any network call', () => { + const cfg = path.join(os.tmpdir(), `stoke-cfg-${process.pid}.json`); + fs.writeFileSync(cfg, JSON.stringify({ url: 'https://forge.test', token: 'tok' })); + try { + const res = run(['pr', 'review', '-o', 'o', '-r', 'r', '-n', '1', '--event', 'approve'], { STOKE_CONFIG_FILE: cfg }); + // It fails at the network call, not at validation. + assert.equal(res.status, 1); + assert.doesNotMatch(res.stderr, /requires a non-empty body/); + } finally { + fs.unlinkSync(cfg); + } +}); + +function spawnAsync(args, env = {}) { + return new Promise((resolve, reject) => { + const child = spawn(process.execPath, [CLI, ...args], { + env: { ...process.env, ...env }, + }); + let stdout = ''; + let stderr = ''; + child.stdout.setEncoding('utf8'); + child.stderr.setEncoding('utf8'); + child.stdout.on('data', (chunk) => { stdout += chunk; }); + child.stderr.on('data', (chunk) => { stderr += chunk; }); + child.on('error', reject); + child.on('close', (status) => resolve({ status, stdout, stderr })); + }); +} + +test('pr review preserves exact body-file whitespace through the CLI boundary', async () => { + const cfg = path.join(os.tmpdir(), `stoke-cfg-${process.pid}.json`); + const bodyFile = path.join(os.tmpdir(), `stoke-body-${process.pid}.md`); + const rawBody = ' leading spaces\nline\ntrailing newline\n'; + + fs.writeFileSync(bodyFile, rawBody, 'utf8'); + + const captured = await new Promise((resolve, reject) => { + const server = http.createServer((req, res) => { + let data = ''; + req.setEncoding('utf8'); + req.on('data', (chunk) => { data += chunk; }); + req.on('end', () => { + res.writeHead(200, { 'Content-Type': 'application/json' }); + res.end(JSON.stringify({ id: 99 })); + server.close(() => resolve({ url: req.url, body: data })); + }); + }); + + server.listen(0, '127.0.0.1', async () => { + const { port } = server.address(); + fs.writeFileSync(cfg, JSON.stringify({ url: `http://127.0.0.1:${port}`, token: 'tok' })); + try { + const res = await spawnAsync( + ['pr', 'review', '-o', 'o', '-r', 'r', '-n', '7', '--event', 'request-changes', '--body-file', bodyFile], + { STOKE_CONFIG_FILE: cfg }, + ); + if (res.status !== 0) { + server.close(() => reject(new Error(`CLI failed: ${res.stderr}`))); + } + } catch (err) { + server.close(() => reject(err)); + } + }); + }); + + try { + assert.equal(captured.url, '/api/v1/repos/o/r/pulls/7/reviews'); + const json = JSON.parse(captured.body); + assert.equal(json.event, 'REQUEST_CHANGES'); + assert.equal(json.body, rawBody); + } finally { + fs.unlinkSync(cfg); + fs.unlinkSync(bodyFile); + } +});