diff --git a/docs/guide/gutenberg-issues.md b/docs/guide/gutenberg-issues.md index b4eff4f3..ca146cf3 100644 --- a/docs/guide/gutenberg-issues.md +++ b/docs/guide/gutenberg-issues.md @@ -17,6 +17,12 @@ The issue is stored with the site, so it survives restarts. You can change or re Two things are refused by name rather than linked: a pull request URL, because the obvious mistake is pasting the pull request instead of the issue it fixes, and an issue from another repository, because a site cannot cite a number from a project it is not a checkout of. +A pull request's bare number is refused too. GitHub numbers issues and pull requests from one sequence, so the app asks GitHub which one a number is before linking it. When the pull request's description names the issues it fixes (`Fixes #47401`, the same forms the [linked pull requests](#linked-pull-requests) list reads), the refusal names them and shows a **Link #47401** button for each, which links that issue instead. A button is checked the same way the field is, so one that names another pull request is refused as well. When the description does not name an issue on `WordPress/gutenberg`, the refusal says so, and you can find the issue on GitHub. To try the pull request rather than work on its issue, use the **Check out a pull request** card. + +![The GitHub issue card refusing pull request #86733 and offering a Link #47401 button for the issue it fixes](/screenshots/gutenberg-pull-request-refused.png) + +If GitHub cannot be reached, the number is linked as typed. + If you do not have an issue yet, click **Not sure yet? Browse good first issues on GitHub** to open the `Good First Issue` list in your browser. Linking an issue gives it its own branch inside the site, named `issue/71234`, so the work you do for it is kept apart from every other issue on that site. Everything in [Working on several tickets](./ticket-branches) applies, with *issue* for *ticket*: switching, parking, the **Your issues on this site** card, the update to the current trunk, and the four choices for edits made before linking. diff --git a/docs/public/screenshots/gutenberg-pull-request-refused.png b/docs/public/screenshots/gutenberg-pull-request-refused.png new file mode 100644 index 00000000..0abc473c Binary files /dev/null and b/docs/public/screenshots/gutenberg-pull-request-refused.png differ diff --git a/scripts/screenshots/fixtures.cjs b/scripts/screenshots/fixtures.cjs index 40d03ea7..73920ddc 100644 --- a/scripts/screenshots/fixtures.cjs +++ b/scripts/screenshots/fixtures.cjs @@ -205,6 +205,11 @@ async function standInForTheOutside(app) { replace('github:account', () => ({ ok: true, login: null, configured: true, testMode: null })); replace('github:sign-in', () => ({ ok: true, userCode: 'WDJB-MJHT', verificationUri: 'https://github.com/login/device' })); replace('github:sign-in-cancel', () => ({ ok: true })); + // Whether a number typed into the issue field is a pull request (#736): + // 86733 is one, and its description fixes #47401 (#748), as on GitHub. + replace('github:is-pull-request', (_e, _sitePath, id) => (Number(id) === 86733 + ? { ok: true, pullRequest: true, fixes: [47401] } + : { ok: true, pullRequest: false, fixes: [] })); // An install is "started" and never ends, like the script. replace('npm:install', async () => ({ installId: 'docs-fixture' })); replace('npm:run-script', async () => ({ runId: 'docs-fixture' })); diff --git a/scripts/screenshots/shots.cjs b/scripts/screenshots/shots.cjs index cfc6465f..c1041277 100644 --- a/scripts/screenshots/shots.cjs +++ b/scripts/screenshots/shots.cjs @@ -224,6 +224,20 @@ const shots = [ await ui.card(page, 'GitHub issue').waitFor(); } }, + { + // A pull request's number typed where the issue goes (#736), and the + // issue its description fixes offered in its place (#748). + slug: 'gutenberg-pull-request-refused', + tier: 'fixture', + variant: 'gutenberg', + target: (page) => ui.card(page, 'GitHub issue'), + prepare: async (page) => { + await selectSite(page, 'my-gutenberg-fix'); + await ui.issueField(page).fill('86733'); + await ui.linkIssueButton(page).click(); + await page.getByRole('button', { name: 'Link #47401', exact: true }).waitFor(); + } + }, { slug: 'gutenberg-pull-request-panel', tier: 'fixture', diff --git a/src/github-prs.js b/src/github-prs.js index a7c202c9..857dda71 100644 --- a/src/github-prs.js +++ b/src/github-prs.js @@ -23,7 +23,7 @@ * anything (#281). See resolveCommitDates for how few it settles for. */ -const { PR_REPO_PATH, parseLinkedPrs, orderByCommitDate, classifyHttpFailure, citesWorkItemFor } = require('./patch-sources.cjs'); +const { PR_REPO_PATH, parseLinkedPrs, orderByCommitDate, classifyHttpFailure, citesWorkItemFor, issuesClosedBy } = require('./patch-sources.cjs'); const { httpGet } = require('./github-http.cjs'); // The repository every request goes to when the caller names none: a Core @@ -316,11 +316,15 @@ async function fetchLinkedPrs(ticketId, deps = {}) { * quota or a missing number must not stop someone linking the issue they * meant, and a check that quietly stopped working must still leave a trace. * + * A pull request's answer carries its description, so the issues it closes + * come with it at no extra cost (#748): `fixes` lists them, empty when it + * names none or the number is an issue. + * * @param {number} number Already parsed by the site's work-item provider. * @param {Object} [deps] * @param {Function} [deps.httpGet] * @param {string} [deps.repo] `owner/repo` - * @return {Promise<{known: true, pullRequest: boolean}|{known: false, reason: string}>} + * @return {Promise<{known: true, pullRequest: boolean, fixes: number[]}|{known: false, reason: string}>} */ async function isPullRequest(number, deps = {}) { const get = deps.httpGet || httpGet; @@ -334,7 +338,8 @@ async function isPullRequest(number, deps = {}) { if (res.status !== 200) return { known: false, reason: `${classifyHttpFailure(res.status, res.headers)} (GitHub returned ${res.status})` }; let json; try { json = JSON.parse(res.body); } catch { return { known: false, reason: 'unreadable response from GitHub' }; } - return { known: true, pullRequest: Boolean(json && json.pull_request) }; + const pullRequest = Boolean(json && json.pull_request); + return { known: true, pullRequest, fixes: pullRequest ? issuesClosedBy(json.body, repo) : [] }; } module.exports = { MAX_COMMIT_LOOKUPS, fetchLinkedPrs, isPullRequest, httpGet }; diff --git a/src/main.js b/src/main.js index d88c2c98..33d7eb1c 100644 --- a/src/main.js +++ b/src/main.js @@ -3493,7 +3493,7 @@ ipcMain.handle('github:is-pull-request', async (_e, sitePath, id) => withRegiste logEvent('github', `could not tell whether #${parsed.id} on ${owner}/${repo} is a pull request, so linking it: ${answer.reason}`); return { ok: true, pullRequest: false }; } - return { ok: true, pullRequest: answer.pullRequest }; + return { ok: true, pullRequest: answer.pullRequest, fixes: answer.fixes || [] }; })); ipcMain.handle('sites:set-ticket', async (event, sitePath, ref, options) => withRegisteredSite(sitePath, async () => { diff --git a/src/patch-sources.cjs b/src/patch-sources.cjs index 5d4aa473..176d97f6 100644 --- a/src/patch-sources.cjs +++ b/src/patch-sources.cjs @@ -109,13 +109,36 @@ function bodyCitesIssue(body, issueId, repoPath = PR_REPO_PATH) { if (typeof body !== 'string') return false; const id = String(issueId).replace(/[^0-9]/g, ''); if (!id) return false; + return closingReference(repoPath, id, 'i').test(body); +} + +/** + * Every issue on this repository a PR body closes, in the order it names them + * (#748): the same closing-keyword forms `bodyCitesIssue` accepts, built from + * the same pattern so the two cannot come to disagree. + * + * @param {string} body + * @param {string} [repoPath] + * @return {number[]} + */ +function issuesClosedBy(body, repoPath = PR_REPO_PATH) { + if (typeof body !== 'string') return []; + const found = []; + for (const match of body.matchAll(closingReference(repoPath, '[0-9]+', 'gi'))) { + const id = Number(match[1] || match[2]); + if (!found.includes(id)) found.push(id); + } + return found; +} + +// GitHub's closing keywords, each in its three forms, then an optional colon, +// then the reference in any of its three shapes, with the number captured in +// group 1 (`#N`, `owner/repo#N`) or 2 (the URL). `(? Number.isSafeInteger(n) && n >= 1 && n <= MAX_ISSUE_ID) : []; + if (!issues.length) { + return { + message: sprintf( + // translators: %d: a pull request number, such as 71234. + __('#%d is a pull request, not an issue, and its description does not say which issue here it fixes. To test it, use Check out a pull request.'), + id + ), + issues + }; + } + return { + message: sprintf( + // translators: 1: a pull request number, such as 71234. 2: the issues it fixes, such as "#70001" or "#70001 and #70002". + _n( + '#%1$d is a pull request. It fixes %2$s. Link that issue instead, or use Check out a pull request to test it.', + '#%1$d is a pull request. It fixes %2$s. Link one of those issues instead, or use Check out a pull request to test it.', + issues.length + ), + id, + listOf(issues.map((n) => `#${n}`)) + ), + issues + }; +} + +/** + * The issues to offer as links under the issue field (#748): those of the + * pull-request refusal, while its sentence is still the error shown. Any later + * error, a cleared field or a link under way replaces that sentence, and the + * offer goes with it. + * + * @param {?{message: string, issues: number[]}} offer What pullRequestRefusal last returned. + * @param {string} errorShown The issue field's error now. + * @return {number[]} + */ +function issuesOnOffer(offer, errorShown) { + if (!offer || !errorShown || offer.message !== errorShown) return []; + return offer.issues; } module.exports = { @@ -152,6 +194,7 @@ module.exports = { MAX_ISSUE_ID, issueUrl, issueToCheck, + issuesOnOffer, parseIssueRef, pullRequestRefusal }; diff --git a/src/renderer/hooks/use-site-ticket.jsx b/src/renderer/hooks/use-site-ticket.jsx index 024303a4..d949d6f5 100644 --- a/src/renderer/hooks/use-site-ticket.jsx +++ b/src/renderer/hooks/use-site-ticket.jsx @@ -2,7 +2,7 @@ import { useCallback, useEffect, useRef, useState } from 'react'; import { __ } from '@wordpress/i18n'; import { discardOutcome } from '../changes-note.cjs'; import { rebaseRefusal } from '../ticket-trunk-notice.cjs'; -import { issueToCheck, pullRequestRefusal } from '../github-issue.cjs'; +import { issueToCheck, issuesOnOffer, pullRequestRefusal } from '../github-issue.cjs'; // The ticket or issue a site is working on (#109, #108, #554): linking one, // leaving it, switching between the ones that already have work here, moving @@ -36,6 +36,10 @@ import { issueToCheck, pullRequestRefusal } from '../github-issue.cjs'; export function useSiteTicket({ sitePath, workItem, tracTicket, setTracTicket, setTicketBehindTrunk, metaPatchRef, loadStatus, onClearSwitchNotices, reprobeAfterBranchChange, applyDiscardToNote }) { const [ticketInput, setTicketInput] = useState(''); const [ticketError, setTicketError] = useState(''); + // The pull-request refusal that named the issues it fixes (#748). Whether + // its buttons still show is issuesOnOffer's call, against the error on + // screen, so nothing that clears or replaces the error has to clear this. + const [pullRequestOffer, setPullRequestOffer] = useState(null); const [ticketSaving, setTicketSaving] = useState(false); // The site's ticket branches (#108): what branches:list reported, so the // panel can offer the tickets that already have work here. @@ -144,9 +148,11 @@ export function useSiteTicket({ sitePath, workItem, tracTicket, setTracTicket, s // A bare number on a GitHub site may be a pull request: both share one // sequence, and linking one leaves the site on a branch no pull request // cites, with nothing to say why (#736). The decision and its sentence live - // in github-issue.cjs; this holds the state and the call. - const linkTicket = useCallback(async () => { - const id = issueToCheck(workItem, ticketInput); + // in github-issue.cjs; this holds the state and the call. The field and the + // issues a refusal offers both come through here, because a pull request's + // "Fixes #N" can name another pull request (#748). + const linkChecked = useCallback(async (ref) => { + const id = issueToCheck(workItem, ref); if (id !== null) { setTicketSaving(true); setTicketError(''); @@ -161,13 +167,18 @@ export function useSiteTicket({ sitePath, workItem, tracTicket, setTracTicket, s } const refusal = pullRequestRefusal(id, answer); if (refusal) { - setTicketError(refusal); + setTicketError(refusal.message); + setPullRequestOffer(refusal); return; } } - return saveTicket(ticketInput); - }, [saveTicket, ticketInput, workItem, sitePath]); + return saveTicket(ref); + }, [saveTicket, workItem, sitePath]); + // Called from a button's onClick too, so the event it passes is ignored. + const linkTicket = useCallback(() => linkChecked(ticketInput), [linkChecked, ticketInput]); + const linkOfferedIssue = useCallback((issue) => linkChecked(String(issue)), [linkChecked]); const unlinkTicket = useCallback(() => saveTicket(''), [saveTicket]); + const offeredIssues = issuesOnOffer(pullRequestOffer, ticketError); // The notice's own button (#385): the ticket's work replayed onto the // current trunk in main. Same busy flag and progress line as a switch, @@ -299,6 +310,8 @@ export function useSiteTicket({ sitePath, workItem, tracTicket, setTracTicket, s setTicketInput, ticketError, setTicketError, + offeredIssues, + linkOfferedIssue, ticketSaving, ticketBranches, deletingBranch, diff --git a/src/renderer/index.jsx b/src/renderer/index.jsx index bd4d795b..23a98073 100644 --- a/src/renderer/index.jsx +++ b/src/renderer/index.jsx @@ -1137,7 +1137,7 @@ function SiteRow({ sitePath, initialized, createdAt, label, projectType = null, // switching, moving onto trunk and deleting, with the question a switch // asks about trunk's loose edits. The three refs are how it and the apply // chain, called further down, reach each other. - const { ticketInput, setTicketInput, ticketError, setTicketError, ticketSaving, ticketBranches, deletingBranch, blockedByTrunkWork, setBlockedByTrunkWork, patchSavedNotice, patchSavedTo, setPatchSavedTo, saveTicket, linkTicket, unlinkTicket, rebaseTicket, discardTrunkWorkAndSwitch, saveTrunkWorkThenStartClean, deleteTicketWork, retryPrSwitchRef, ticketSwitchLifecycleRef, autoReadTicketRef } = useSiteTicket({ sitePath, workItem, tracTicket, setTracTicket, setTicketBehindTrunk, metaPatchRef, loadStatus, onClearSwitchNotices, reprobeAfterBranchChange, applyDiscardToNote }); + const { ticketInput, setTicketInput, ticketError, setTicketError, offeredIssues, linkOfferedIssue, ticketSaving, ticketBranches, deletingBranch, blockedByTrunkWork, setBlockedByTrunkWork, patchSavedNotice, patchSavedTo, setPatchSavedTo, saveTicket, linkTicket, unlinkTicket, rebaseTicket, discardTrunkWorkAndSwitch, saveTrunkWorkThenStartClean, deleteTicketWork, retryPrSwitchRef, ticketSwitchLifecycleRef, autoReadTicketRef } = useSiteTicket({ sitePath, workItem, tracTicket, setTracTicket, setTicketBehindTrunk, metaPatchRef, loadStatus, onClearSwitchNotices, reprobeAfterBranchChange, applyDiscardToNote }); // A ticket arrived from a link and this is the site in front of the // contributor (#464). The answer goes through `saveTicket` like any other @@ -1569,6 +1569,20 @@ function SiteRow({ sitePath, initialized, createdAt, label, projectType = null, {ticketError ? ( {ticketError} + {/* The issues a refused pull request fixes, one click from being + linked instead of looked up on GitHub (#748). */} + {offeredIssues.length ? ( + + {offeredIssues.map((issue) => ( + linkOfferedIssue(issue)}> + { + // translators: %d: a GitHub issue number, such as 70001. + sprintf(__('Link #%d'), issue) + } + + ))} + + ) : null} ) : null} {switchProgressLine} diff --git a/tests/e2e/journeys/gutenberg-site.spec.js b/tests/e2e/journeys/gutenberg-site.spec.js index ea62f258..12a04aff 100644 --- a/tests/e2e/journeys/gutenberg-site.spec.js +++ b/tests/e2e/journeys/gutenberg-site.spec.js @@ -30,11 +30,15 @@ test( 'a Gutenberg site is tagged, works on a GitHub issue under issue/, and tur global.__tracScrapes = ( global.__tracScrapes || 0 ) + 1; return { ok: true, status: 'ok', items: [], ticket: { summary: 'A CORE TICKET WITH THE SAME NUMBER', keywords: [] } }; } ); - // GitHub stands in too, for whether a number is a pull request: only - // the fixture's own pull request is one. On the real repository 71234 - // is a pull request as well. + // GitHub stands in too, for whether a number is a pull request: the + // fixture's own pull request is one, and so are 4497, whose + // description closes 4498 and issue 70001, and 4498, which closes + // nothing. On the real repository 71234 is a pull request as well. ipcMain.removeHandler( 'github:is-pull-request' ); - ipcMain.handle( 'github:is-pull-request', ( _e, _sitePath, id ) => ( { ok: true, pullRequest: id === pr } ) ); + ipcMain.handle( 'github:is-pull-request', ( _e, _sitePath, id ) => { + if ( id === 4497 ) return { ok: true, pullRequest: true, fixes: [ 4498, 70001 ] }; + return { ok: true, pullRequest: id === pr || id === 4498, fixes: [] }; + } ); }, PR ); // INVARIANT — the row and the header say which kind of site this is. @@ -62,9 +66,36 @@ test( 'a Gutenberg site is tagged, works on a GitHub issue under issue/, and tur // goes instead (#736). await field.fill( String( PR ) ); await ui.linkIssueButton( page ).click(); - await expect( page.getByRole( 'alert' ).filter( { hasText: `#${ PR } is a pull request, not an issue. To test it, use Check out a pull request.` } ) ).toBeVisible(); + await expect( page.getByRole( 'alert' ).filter( { hasText: `#${ PR } is a pull request, not an issue, and its description does not say which issue here it fixes. To test it, use Check out a pull request.` } ) ).toBeVisible(); + expect( branches( site.dir ) ).toEqual( [ 'trunk' ] ); + + // INVARIANT — a pull request that names the issues it fixes says which, + // and offers to link each in its place (#748). Nothing is written until + // an offer is taken. + const offerFrom4497 = async () => { + await field.fill( '4497' ); + await ui.linkIssueButton( page ).click(); + await expect( page.getByRole( 'alert' ).filter( { hasText: '#4497 is a pull request. It fixes #4498 and #70001. Link one of those issues instead' } ) ).toBeVisible(); + }; + await offerFrom4497(); expect( branches( site.dir ) ).toEqual( [ 'trunk' ] ); + // INVARIANT — an offer is checked like the field: one that names another + // pull request is refused, and its button goes with the sentence it + // belonged to. + await page.getByRole( 'button', { name: 'Link #4498', exact: true } ).click(); + await expect( page.getByRole( 'alert' ).filter( { hasText: '#4498 is a pull request, not an issue, and its description does not say which issue here it fixes.' } ) ).toBeVisible(); + await expect( page.getByRole( 'button', { name: 'Link #70001', exact: true } ) ).toHaveCount( 0 ); + expect( branches( site.dir ) ).toEqual( [ 'trunk' ] ); + + // INVARIANT — taking an offer that is an issue links it. + await offerFrom4497(); + await page.getByRole( 'button', { name: 'Link #70001', exact: true } ).click(); + await expect( ui.workItemNumber( page, 70001 ) ).toBeVisible( { timeout: 30_000 } ); + expect( branches( site.dir ) ).toContain( 'issue/70001' ); + await ui.unlinkButton( page ).click(); + await expect( ui.issueField( page ) ).toBeVisible( { timeout: 30_000 } ); + // INVARIANT — linking an issue by URL names it on the card and gives it a // branch under issue/, the noun its upstream uses; the Trac-only pieces // stay off the linked card too. diff --git a/tests/unit/github-issue.test.cjs b/tests/unit/github-issue.test.cjs index b36ab015..d6bdd9da 100644 --- a/tests/unit/github-issue.test.cjs +++ b/tests/unit/github-issue.test.cjs @@ -6,7 +6,7 @@ const test = require('node:test'); const assert = require('node:assert'); -const { parseIssueRef, issueUrl, issueToCheck, pullRequestRefusal } = require('../../src/renderer/github-issue.cjs'); +const { MAX_ISSUE_ID, parseIssueRef, issueUrl, issueToCheck, issuesOnOffer, pullRequestRefusal } = require('../../src/renderer/github-issue.cjs'); const { workItemProvider } = require('../../src/work-item.cjs'); const { addFilter, removeFilter } = require('@wordpress/hooks'); const { pseudoLocalize } = require('../../src/renderer/pseudo-locale.cjs'); @@ -136,11 +136,32 @@ test('issueToCheck asks about what a GitHub-issue site would link, and nothing e }); test('pullRequestRefusal refuses only on a clear pull-request answer, and says where a pull request goes', () => { - assert.strictEqual( - pullRequestRefusal(71234, { ok: true, pullRequest: true }), - '#71234 is a pull request, not an issue. To test it, use Check out a pull request. To work on it, link the issue it fixes.' - ); + const told = { message: '#71234 is a pull request, not an issue, and its description does not say which issue here it fixes. To test it, use Check out a pull request.', issues: [] }; + assert.deepStrictEqual(pullRequestRefusal(71234, { ok: true, pullRequest: true }), told); + assert.deepStrictEqual(pullRequestRefusal(71234, { ok: true, pullRequest: true, fixes: [] }), told); for (const answer of [{ ok: true, pullRequest: false }, { ok: false, error: 'Site is not registered' }, null, undefined]) { assert.strictEqual(pullRequestRefusal(71234, answer), null); } }); + +test('pullRequestRefusal names the issues a pull request fixes and offers each (#748)', () => { + assert.deepStrictEqual(pullRequestRefusal(71234, { ok: true, pullRequest: true, fixes: [70001] }), { + message: '#71234 is a pull request. It fixes #70001. Link that issue instead, or use Check out a pull request to test it.', + issues: [70001] + }); + assert.deepStrictEqual(pullRequestRefusal(71234, { ok: true, pullRequest: true, fixes: [70001, 70002, 70003] }), { + message: '#71234 is a pull request. It fixes #70001, #70002 and #70003. Link one of those issues instead, or use Check out a pull request to test it.', + issues: [70001, 70002, 70003] + }); + // Only numbers the field itself would link cross into a button. + assert.deepStrictEqual(pullRequestRefusal(71234, { ok: true, pullRequest: true, fixes: ['70001', 0, null, 1.5, MAX_ISSUE_ID + 1, 1e21] }).issues, []); + assert.deepStrictEqual(pullRequestRefusal(71234, { ok: true, pullRequest: true, fixes: [1, MAX_ISSUE_ID] }).issues, [1, MAX_ISSUE_ID]); +}); + +test('issuesOnOffer keeps the offer only while its own sentence is the error shown (#748)', () => { + const offer = pullRequestRefusal(71234, { ok: true, pullRequest: true, fixes: [70001] }); + assert.deepStrictEqual(issuesOnOffer(offer, offer.message), [70001]); + assert.deepStrictEqual(issuesOnOffer(offer, ''), [], 'cleared by typing or by a link under way'); + assert.deepStrictEqual(issuesOnOffer(offer, '#70001 is a pull request, not an issue, and its description does not say which issue here it fixes. To test it, use Check out a pull request.'), [], 'replaced by a later refusal'); + assert.deepStrictEqual(issuesOnOffer(null, offer.message), []); +}); diff --git a/tests/unit/github-prs.test.cjs b/tests/unit/github-prs.test.cjs index 461c604d..69a80f47 100644 --- a/tests/unit/github-prs.test.cjs +++ b/tests/unit/github-prs.test.cjs @@ -397,14 +397,24 @@ test('fetchLinkedPrs without a repository is a Core site\'s, unchanged (#251)', test('isPullRequest asks the repository for the number and reads pull_request off the answer', async () => { const urls = []; const get = (body) => async (url) => { urls.push(url); return { status: 200, headers: {}, body: JSON.stringify(body) }; }; - assert.deepStrictEqual(await isPullRequest(71234, { repo: 'WordPress/gutenberg', httpGet: get({ number: 71234, pull_request: { url: 'x' } }) }), { known: true, pullRequest: true }); - assert.deepStrictEqual(await isPullRequest(4496, { repo: 'WordPress/gutenberg', httpGet: get({ number: 4496 }) }), { known: true, pullRequest: false }); + assert.deepStrictEqual(await isPullRequest(71234, { repo: 'WordPress/gutenberg', httpGet: get({ number: 71234, pull_request: { url: 'x' } }) }), { known: true, pullRequest: true, fixes: [] }); + assert.deepStrictEqual(await isPullRequest(4496, { repo: 'WordPress/gutenberg', httpGet: get({ number: 4496 }) }), { known: true, pullRequest: false, fixes: [] }); assert.deepStrictEqual(urls, [ 'https://api.github.com/repos/WordPress/gutenberg/issues/71234', 'https://api.github.com/repos/WordPress/gutenberg/issues/4496' ]); }); +test('isPullRequest reads the issues a pull request closes off the same answer, and none off an issue (#748)', async () => { + let calls = 0; + const get = (body) => async () => { calls++; return { status: 200, headers: {}, body: JSON.stringify(body) }; }; + const pr = { number: 71234, pull_request: { url: 'x' }, body: 'Fixes #70001\r\nCloses WordPress/wordpress-develop#9 and resolves #70002' }; + assert.deepStrictEqual(await isPullRequest(71234, { repo: 'WordPress/gutenberg', httpGet: get(pr) }), { known: true, pullRequest: true, fixes: [70001, 70002] }); + assert.deepStrictEqual(await isPullRequest(71234, { repo: 'WordPress/gutenberg', httpGet: get({ ...pr, body: null }) }), { known: true, pullRequest: true, fixes: [] }); + assert.deepStrictEqual(await isPullRequest(4496, { repo: 'WordPress/gutenberg', httpGet: get({ number: 4496, body: 'Fixes #70001' }) }), { known: true, pullRequest: false, fixes: [] }); + assert.strictEqual(calls, 3, 'one request each'); +}); + test('isPullRequest says it could not tell, and why, for anything short of a clear answer', async () => { const cases = [ [async () => ({ status: 404, headers: {}, body: '{"message":"Not Found"}' }), /GitHub returned 404/], diff --git a/tests/unit/ipc-wiring.test.cjs b/tests/unit/ipc-wiring.test.cjs index c4a2cb96..a791b01a 100644 --- a/tests/unit/ipc-wiring.test.cjs +++ b/tests/unit/ipc-wiring.test.cjs @@ -4563,14 +4563,14 @@ test('git:list-ticket-patches on a Gutenberg site names its repository and provi // of the site's own repository on a Gutenberg site, and not asked at all on a // Core site, whose Trac tickets share no numbers with GitHub. test('github:is-pull-request asks github-prs about the site\'s own repository, and only on a GitHub-issue site', async () => { - const isPullRequest = spy(async () => ({ known: true, pullRequest: true })); + const isPullRequest = spy(async () => ({ known: true, pullRequest: true, fixes: [70001] })); const settings = fakeSettingsStore({ sites: ['/sites/wp', '/sites/gb'], siteMeta: { '/sites/wp': {}, '/sites/gb': { projectType: 'gutenberg' } } }); const main = loadMain({ stubs: { ...silentLogging(), ...settings.stubs, './github-prs': { isPullRequest } } }); - assert.deepEqual(await main.invoke('github:is-pull-request', '/sites/gb', 71234), { ok: true, pullRequest: true }); + assert.deepEqual(await main.invoke('github:is-pull-request', '/sites/gb', 71234), { ok: true, pullRequest: true, fixes: [70001] }); assert.deepEqual(await main.invoke('github:is-pull-request', '/sites/wp', 71234), { ok: true, pullRequest: false }); assert.deepEqual(isPullRequest.calls, [[71234, { repo: 'WordPress/gutenberg' }]]); assert.equal((await main.invoke('github:is-pull-request', '/sites/other', 1)).ok, false, 'an unregistered site is refused'); diff --git a/tests/unit/patch-sources.test.cjs b/tests/unit/patch-sources.test.cjs index 5517dbd2..f3c5efd8 100644 --- a/tests/unit/patch-sources.test.cjs +++ b/tests/unit/patch-sources.test.cjs @@ -2,7 +2,7 @@ const test = require('node:test'); const assert = require('node:assert'); -const { bodyCitesTicket, bodyCitesIssue, citesWorkItemFor, parseLinkedPrs, orderByCommitDate, classifyHttpFailure } = require('../../src/patch-sources.cjs'); +const { bodyCitesTicket, bodyCitesIssue, issuesClosedBy, citesWorkItemFor, parseLinkedPrs, orderByCommitDate, classifyHttpFailure } = require('../../src/patch-sources.cjs'); // Shaped like a real search/issues item, trimmed to the fields the parser reads. function item(number, overrides = {}) { @@ -208,6 +208,24 @@ test('bodyCitesIssue: a bare #N, a longer number, another repository or a prefix assert.strictEqual(bodyCitesIssue('Fixes #71234', '', GB), false); }); +test('issuesClosedBy: every issue a body closes, in order, by the forms bodyCitesIssue accepts (#748)', () => { + const body = [ + 'Fixes #70001.', + 'Also closes: WordPress/gutenberg#70002 and resolves https://github.com/WordPress/gutenberg/issues/70003', + 'fixes #70001 again' + ].join('\n'); + assert.deepStrictEqual(issuesClosedBy(body, GB), [70001, 70002, 70003]); + for (const n of issuesClosedBy(body, GB)) assert.strictEqual(bodyCitesIssue(body, n, GB), true, `the two agree on #${n}`); +}); + +test('issuesClosedBy: a mention, another repository or no body names nothing (#748)', () => { + assert.deepStrictEqual(issuesClosedBy('Related to #70001. See https://github.com/WordPress/gutenberg/issues/70002', GB), []); + assert.deepStrictEqual(issuesClosedBy('Fixes WordPress/wordpress-develop#70001', GB), []); + assert.deepStrictEqual(issuesClosedBy('prefix #70001', GB), []); + assert.deepStrictEqual(issuesClosedBy(null, GB), []); + assert.deepStrictEqual(issuesClosedBy('', GB), []); +}); + test('citesWorkItemFor: Trac by default, the issue form for a GitHub site (#251)', () => { assert.strictEqual(citesWorkItemFor(), bodyCitesTicket); assert.strictEqual(citesWorkItemFor('trac'), bodyCitesTicket);