Skip to content
Merged
6 changes: 6 additions & 0 deletions docs/guide/gutenberg-issues.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
5 changes: 5 additions & 0 deletions scripts/screenshots/fixtures.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -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' }));
Expand Down
14 changes: 14 additions & 0 deletions scripts/screenshots/shots.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -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',
Expand Down
11 changes: 8 additions & 3 deletions src/github-prs.js
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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;
Expand All @@ -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 };
2 changes: 1 addition & 1 deletion src/main.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 () => {
Expand Down
36 changes: 30 additions & 6 deletions src/patch-sources.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -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]);
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
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). `(?<![0-9])` is not needed on
// the left: the keyword is what precedes the digits.
function closingReference(repoPath, id, flags) {
const repo = String(repoPath).replace(/[.\\/]/g, '\\$&');
// GitHub's closing keywords, each in its three forms, then an optional
// colon, then the reference in any of its three shapes. `(?<![0-9])` is
// not needed on the left: the keyword is what precedes the digits.
const reference = `(?:(?:${repo})?#${id}|https?://github\\.com/${repo}/issues/${id})(?![0-9])`;
const closing = new RegExp(`\\b(?:close|closes|closed|fix|fixes|fixed|resolve|resolves|resolved)\\s*:?\\s*${reference}`, 'i');
return closing.test(body);
const reference = `(?:(?:${repo})?#(${id})|https?://github\\.com/${repo}/issues/(${id}))(?![0-9])`;
return new RegExp(`\\b(?:close|closes|closed|fix|fixes|fixed|resolve|resolves|resolved)\\s*:?\\s*${reference}`, flags);
}

/**
Expand Down Expand Up @@ -252,6 +275,7 @@ module.exports = {
PR_REPO_PATH,
bodyCitesTicket,
bodyCitesIssue,
issuesClosedBy,
citesWorkItemFor,
parseLinkedPrs,
orderByCommitDate,
Expand Down
57 changes: 50 additions & 7 deletions src/renderer/github-issue.cjs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,8 @@
* imports it and `node --test` requires it directly.
*/

const { __, sprintf } = require('@wordpress/i18n');
const { __, _n, sprintf } = require('@wordpress/i18n');
const { listOf } = require('./applied-layer.cjs');

const GITHUB_HOST = 'github.com';

Expand Down Expand Up @@ -134,24 +135,66 @@ function issueToCheck(workItem, input) {
* links: not being able to reach GitHub is no reason to stop someone linking
* the issue they meant, and main logs why it could not tell.
*
* When the pull request's description closes issues, the sentence names them
* and `issues` lists them, so the field can offer to link each one (#748).
* Most pull requests name none, and the sentence says so, rather than sending
* the contributor to look for an issue the description does not name.
*
* @param {number} id
* @param {?Object} answer What `github:is-pull-request` returned, if anything.
* @return {string|null}
* @return {{message: string, issues: number[]}|null}
*/
function pullRequestRefusal(id, answer) {
if (!answer || answer.ok !== true || answer.pullRequest !== true) return null;
return sprintf(
// translators: %d: a pull request number, such as 71234.
__('#%d 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.'),
id
);
// The same bound the field holds a typed number to: a description can say
// anything, and a button must not offer what the link would refuse.
const issues = Array.isArray(answer.fixes) ? answer.fixes.filter((n) => 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 = {
GITHUB_HOST,
MAX_ISSUE_ID,
issueUrl,
issueToCheck,
issuesOnOffer,
parseIssueRef,
pullRequestRefusal
};
27 changes: 20 additions & 7 deletions src/renderer/hooks/use-site-ticket.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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('');
Expand All @@ -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,
Expand Down Expand Up @@ -299,6 +310,8 @@ export function useSiteTicket({ sitePath, workItem, tracTicket, setTracTicket, s
setTicketInput,
ticketError,
setTicketError,
offeredIssues,
linkOfferedIssue,
ticketSaving,
ticketBranches,
deletingBranch,
Expand Down
16 changes: 15 additions & 1 deletion src/renderer/index.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -1569,6 +1569,20 @@ function SiteRow({ sitePath, initialized, createdAt, label, projectType = null,
{ticketError ? (
<Notice.Root intent="error" role="alert" spokenMessage={SILENT}>
<Notice.Description>{ticketError}</Notice.Description>
{/* The issues a refused pull request fixes, one click from being
linked instead of looked up on GitHub (#748). */}
{offeredIssues.length ? (
<Notice.Actions>
{offeredIssues.map((issue) => (
<ReasonedUiButton key={issue} variant="outline" tone="neutral" size="compact" reason={ticketActionsReason} onClick={() => linkOfferedIssue(issue)}>
{
// translators: %d: a GitHub issue number, such as 70001.
sprintf(__('Link #%d'), issue)
}
</ReasonedUiButton>
))}
</Notice.Actions>
) : null}
</Notice.Root>
) : null}
{switchProgressLine}
Expand Down
Loading
Loading