Skip to content

Commit 9614aa9

Browse files
rtibblesclaude
andcommitted
Link an issue the pull request description names when GitHub did not
- Off the default branch, link every issue after a closing keyword, as GitHub would on it - Otherwise link the one mentioned issue assigned to the author, and name it in the reply - Name several assigned mentions and ask which one, without linking - Tell an unlinked author the issue comes first Closes #112 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_013PjXpbp1QSbkpzvnRwm7yv
1 parent d6a4168 commit 9614aa9

8 files changed

Lines changed: 418 additions & 18 deletions

File tree

‎.github/workflows/contributor-pr-reply.yml‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,7 @@ jobs:
3838
with:
3939
app-id: ${{ secrets.LE_BOT_APP_ID }}
4040
private-key: ${{ secrets.LE_BOT_PRIVATE_KEY }}
41-
permission-issues: read
41+
permission-issues: write
4242
permission-pull-requests: write
4343
- name: Checkout .github repository
4444
uses: actions/checkout@v7

‎docs/community-automations.md‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -71,13 +71,21 @@ What happens depends on who the linked issue is assigned to:
7171

7272
An issue counts as linked only when the description closes it, for example `Fixes #123`. Assignments on any other issue are ignored. If the author is assigned to any linked issue, the pull request is not closed. Close contributors are never closed or labelled `unlinked`.
7373

74+
When nothing is linked, the automation reads the description for open issues in the same repository, as `#123`, `owner/repo#123`, or an issue URL, outside code and HTML comments, and links some itself:
75+
76+
- on a base other than the default branch, where GitHub ignores closing keywords: every issue after a closing keyword, whoever it is assigned to
77+
- otherwise, the one mentioned issue assigned to the author; the reply names it
78+
- several mentioned issues assigned to the author link none; the reply names them and asks which one
79+
7480
It runs on `opened`, and again on `edited` when the description changes. An edit sends no reply: it closes, labels, or removes `unlinked` by the rules above, and starts review only on a pull request that carried `unlinked`.
7581

7682
The weekly `unassign-inactive-issues` run closes every open pull request labelled `unlinked` for longer than `PR_UNLINKED_MAX_DAYS` days, except a close contributor's. It re-reads the links first, because a link added from the Development sidebar fires no `edited` event: a pull request now linked to its author's issue loses the label and starts review instead.
7783

7884
In `scripts/constants.js` set:
7985
- `BOT_MESSAGE_PULL_REQUEST`: Message text
8086
- `BOT_MESSAGE_LINK_ISSUE`: Text added when no issue is linked
87+
- `BOT_MESSAGE_LINKED_ISSUE`: Text added when the automation linked the author's issue
88+
- `BOT_MESSAGE_LINK_WHICH_ISSUE`: Text added when several mentioned issues are assigned to the author
8189
- `BOT_MESSAGE_PULL_REQUEST_CLOSED`: Closing message when the issue is assigned to someone else
8290
- `BOT_MESSAGE_PULL_REQUEST_UNASSIGNED`: Closing message when the issue is assigned to no one
8391
- `BOT_MESSAGE_PULL_REQUEST_UNLINKED_CLOSED`: Closing message from the sweep when still no issue is linked

‎scripts/constants.js‎

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -166,7 +166,15 @@ const BOT_MESSAGE_PULL_REQUEST = author =>
166166
const LABEL_UNLINKED = 'unlinked';
167167
const PR_UNLINKED_MAX_DAYS = 7;
168168

169-
const BOT_MESSAGE_LINK_ISSUE = `**📎 We couldn't find an issue linked to this pull request.** Please edit the description and link the issue assigned to you under **References**, for example \`Fixes #123\` or \`Closes #123\`. A plain \`#123\` mention doesn't link the PR to the issue. **Pull requests with no linked issue are closed after ${PR_UNLINKED_MAX_DAYS} days.**`;
169+
const BOT_MESSAGE_UNLINKED_DEADLINE = `**Pull requests with no linked issue are closed after ${PR_UNLINKED_MAX_DAYS} days.**`;
170+
171+
const BOT_MESSAGE_LINK_ISSUE = `**📎 We couldn't find an issue linked to this pull request.** Please edit the description and link the issue assigned to you under **References**, for example \`Fixes #123\` or \`Closes #123\`. A plain \`#123\` mention doesn't link the PR to the issue. ${BOT_MESSAGE_UNLINKED_DEADLINE}\n\n**Open an issue and get assigned to it before you open a pull request.** Visit [Contributing guidelines](https://learningequality.org/contributing-to-our-open-code-base) to learn about the contributing process.`;
172+
173+
const BOT_MESSAGE_LINKED_ISSUE = number =>
174+
`**📎 We linked this pull request to #${number}, the issue assigned to you.** Next time, link it yourself with \`Closes #${number}\` under **References**.`;
175+
176+
const BOT_MESSAGE_LINK_WHICH_ISSUE = numbers =>
177+
`**📎 This pull request mentions more than one issue assigned to you: ${numbers.map(number => `#${number}`).join(', ')}.** Please edit the description and add \`Closes #123\` under **References** to say which one this pull request closes. ${BOT_MESSAGE_UNLINKED_DEADLINE}`;
170178

171179
const BOT_MESSAGE_PULL_REQUEST_UNASSIGNED = (author, issueUrl) =>
172180
`👋 Hi @${author}, thanks for your interest! \n\n **We're closing this pull request because ${issueUrl} isn't assigned to you.** We check and assign issues before work on them starts. Comment on the issue to ask to be assigned, and open a new pull request once you are. Visit [Contributing guidelines](https://learningequality.org/contributing-to-our-open-code-base) to learn about the contributing process.${GSOC_NOTE}`;
@@ -254,6 +262,8 @@ module.exports = {
254262
BOT_MESSAGE_KEYWORD_GOOD_FIRST_ISSUE,
255263
BOT_MESSAGE_PULL_REQUEST,
256264
BOT_MESSAGE_LINK_ISSUE,
265+
BOT_MESSAGE_LINKED_ISSUE,
266+
BOT_MESSAGE_LINK_WHICH_ISSUE,
257267
BOT_MESSAGE_PULL_REQUEST_CLOSED,
258268
BOT_MESSAGE_PULL_REQUEST_UNASSIGNED,
259269
BOT_MESSAGE_PULL_REQUEST_UNLINKED_CLOSED,

‎scripts/contributor-pr-reply.js‎

Lines changed: 23 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,29 @@
1-
const { BOT_MESSAGE_PULL_REQUEST, BOT_MESSAGE_LINK_ISSUE } = require('./constants');
1+
const {
2+
BOT_MESSAGE_PULL_REQUEST,
3+
BOT_MESSAGE_LINK_ISSUE,
4+
BOT_MESSAGE_LINKED_ISSUE,
5+
BOT_MESSAGE_LINK_WHICH_ISSUE,
6+
} = require('./constants');
27
const { sendBotMessage, getLinkedIssues, escapeIssueTitleForSlackMessage } = require('./utils');
3-
const { linkStatus, planLink, applyLink } = require('./pull-request-link');
8+
const { linkReferences, linkStatus, planLink, applyLink } = require('./pull-request-link');
49

510
function slackLine(context, text) {
611
const { repo } = context.repo;
712
const { html_url: url, title } = context.payload.pull_request;
813
return `*[${repo}] ${text}: <${url}|${escapeIssueTitleForSlackMessage(title)}>*`;
914
}
1015

11-
async function sendReply({ github, context, core }, unlinked) {
16+
function linkNote(link, { named, ambiguous }) {
17+
if (named) return BOT_MESSAGE_LINKED_ISSUE(named.number);
18+
if (link.status !== 'unlinked') return null;
19+
if (ambiguous.length) return BOT_MESSAGE_LINK_WHICH_ISSUE(ambiguous.map(issue => issue.number));
20+
return BOT_MESSAGE_LINK_ISSUE;
21+
}
22+
23+
async function sendReply({ github, context, core }, note) {
1224
const { number, user } = context.payload.pull_request;
13-
const body = unlinked
14-
? `${BOT_MESSAGE_PULL_REQUEST(user.login)}\n\n${BOT_MESSAGE_LINK_ISSUE}`
15-
: BOT_MESSAGE_PULL_REQUEST(user.login);
25+
const reply = BOT_MESSAGE_PULL_REQUEST(user.login);
26+
const body = note ? `${reply}\n\n${note}` : reply;
1627
const botMessageUrl = await sendBotMessage(number, body, { github, context, core });
1728
core.setOutput(
1829
'slack_notification',
@@ -63,15 +74,18 @@ module.exports = async ({ github, context, core }) => {
6374
const lookup = await getLinkedIssues(number, { github, context, core });
6475
if (lookup === null) {
6576
if (opening) {
66-
await sendReply({ github, context, core }, false);
77+
await sendReply({ github, context, core }, null);
6778
}
6879
return;
6980
}
7081

71-
const link = linkStatus(lookup, author);
82+
const found = lookup.length
83+
? { linked: lookup, named: null, ambiguous: [] }
84+
: await linkReferences(owner, repo, pullRequest, { github, core });
85+
const link = linkStatus(found.linked, author);
7286
const first = await plan(link);
7387
if (opening && first.action !== 'close') {
74-
await sendReply({ github, context, core }, link.status === 'unlinked');
88+
await sendReply({ github, context, core }, linkNote(link, found));
7589
}
7690
await act({ github, context, core }, first, link);
7791

‎scripts/contributor-pr-reply.test.js‎

Lines changed: 176 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -15,24 +15,29 @@ const CLOSE_CONTRIBUTOR = CLOSE_CONTRIBUTORS[0];
1515
function fakeContext(
1616
author = AUTHOR,
1717
title = 'Fix it',
18-
{ action = 'opened', state = 'open', labels = [] } = {},
18+
{ action = 'opened', state = 'open', labels = [], body = '', base = 'develop' } = {},
1919
) {
2020
return {
2121
repo: { owner: 'learningequality', repo: 'kolibri' },
2222
payload: {
2323
action,
2424
pull_request: {
2525
number: 42,
26+
node_id: 'PR_42',
2627
html_url: 'https://github.com/learningequality/kolibri/pull/42',
2728
title,
29+
body,
2830
state,
2931
labels: labels.map(name => ({ name })),
3032
user: { login: author },
33+
base: { ref: base, repo: { default_branch: 'develop' } },
3134
},
3235
},
3336
};
3437
}
3538

39+
const describing = (body, options = {}) => fakeContext(AUTHOR, 'Fix it', { body, ...options });
40+
3641
const edited = (author = AUTHOR, options = {}) =>
3742
fakeContext(author, 'Fix it', { action: 'edited', ...options });
3843

@@ -57,18 +62,66 @@ function fakeCore() {
5762
};
5863
}
5964

60-
function fakeGithub(linkedIssues = [], { graphqlError, relinked } = {}) {
61-
const calls = { comments: [], updates: [], reviewers: [], labels: [], removed: [], order: [] };
65+
function referencedNode(number, { assignees = [], state = 'OPEN', type = 'Issue' } = {}) {
66+
if (type !== 'Issue') {
67+
return { __typename: type };
68+
}
69+
return {
70+
__typename: type,
71+
id: `I_${number}`,
72+
number,
73+
url: `https://github.com/learningequality/kolibri/issues/${number}`,
74+
state,
75+
assignees: { nodes: assignees.map(login => ({ login })) },
76+
};
77+
}
78+
79+
function lookUpReferences(query, referenced) {
80+
const repository = {};
81+
for (const [, alias, number] of query.matchAll(/(\w+): issueOrPullRequest\(number: (\d+)\)/g)) {
82+
const issue = referenced[number];
83+
repository[alias] = issue ? referencedNode(Number(number), issue) : null;
84+
}
85+
if (Object.values(repository).includes(null)) {
86+
throw Object.assign(new Error('Could not resolve to an issue'), { data: { repository } });
87+
}
88+
return { repository };
89+
}
90+
91+
function fakeGithub(
92+
linkedIssues = [],
93+
{ graphqlError, relinked, referenced = {}, linkError } = {},
94+
) {
95+
const calls = {
96+
comments: [],
97+
updates: [],
98+
reviewers: [],
99+
labels: [],
100+
removed: [],
101+
links: [],
102+
order: [],
103+
};
62104
const current = new Set();
63105
let lookups = 0;
64106
return {
65107
calls,
66108
current,
67109
paginate: async (fn, params) => fn(params),
68-
graphql: async () => {
110+
graphql: async (query, variables) => {
69111
if (graphqlError) {
70112
throw new Error(graphqlError);
71113
}
114+
if (query.includes('addCloseIssueReferences')) {
115+
if (linkError) {
116+
throw new Error(linkError);
117+
}
118+
calls.links.push(variables);
119+
calls.order.push('link');
120+
return {};
121+
}
122+
if (query.includes('issueOrPullRequest')) {
123+
return lookUpReferences(query, referenced);
124+
}
72125
lookups += 1;
73126
const issues = lookups > 1 && relinked ? relinked : linkedIssues;
74127
return {
@@ -374,3 +427,122 @@ test('a failed lookup does not ask the author to link an issue', async () => {
374427

375428
assert.doesNotMatch(github.calls.comments[0].body, /link the issue/);
376429
});
430+
431+
test('a mentioned issue assigned to the author is linked and named', async () => {
432+
const github = fakeGithub([], { referenced: { 7: { assignees: [AUTHOR] } } });
433+
await run(
434+
github,
435+
describing('Fix for [the bug](https://github.com/learningequality/kolibri/issues/7)'),
436+
);
437+
438+
assert.deepEqual(github.calls.links, [{ issueId: 'I_7', pullRequestIds: ['PR_42'] }]);
439+
assert.match(github.calls.comments[0].body, /We linked this pull request to #7/);
440+
assert.match(github.calls.comments[0].body, /`Closes #7`/);
441+
assert.doesNotMatch(github.calls.comments[0].body, /couldn't find an issue/);
442+
assert.deepEqual(github.calls.reviewers, [RTIBBLESBOT_USERNAME]);
443+
assert.deepEqual(github.calls.labels, [LABEL_COMMUNITY_REVIEW]);
444+
});
445+
446+
test('a mentioned issue the author cannot claim is not linked', async () => {
447+
const cases = [
448+
{ assignees: ['someone-else'] },
449+
{ assignees: [] },
450+
{ assignees: [AUTHOR], state: 'CLOSED' },
451+
{ type: 'PullRequest' },
452+
];
453+
for (const issue of cases) {
454+
const github = fakeGithub([], { referenced: { 7: issue } });
455+
await run(github, describing('See #7'));
456+
457+
assert.deepEqual(github.calls.links, []);
458+
assert.deepEqual(github.calls.updates, []);
459+
assert.deepEqual(github.calls.labels, [LABEL_UNLINKED]);
460+
assert.match(github.calls.comments[0].body, /couldn't find an issue/);
461+
}
462+
});
463+
464+
test('two mentioned issues assigned to the author are named and neither is linked', async () => {
465+
const github = fakeGithub([], {
466+
referenced: { 7: { assignees: [AUTHOR] }, 8: { assignees: [AUTHOR] } },
467+
});
468+
await run(github, describing('See #7 and #8'));
469+
470+
assert.deepEqual(github.calls.links, []);
471+
assert.deepEqual(github.calls.labels, [LABEL_UNLINKED]);
472+
assert.match(github.calls.comments[0].body, /#7, #8/);
473+
assert.match(github.calls.comments[0].body, /which one this pull request closes/);
474+
});
475+
476+
test('a missing issue number does not hide the other mentions', async () => {
477+
const github = fakeGithub([], { referenced: { 7: { assignees: [AUTHOR] } } });
478+
const core = await run(github, describing('See #7 and #9999'));
479+
480+
assert.equal(github.calls.links.length, 1);
481+
assert.deepEqual(core.failures, []);
482+
});
483+
484+
test('an unlinked pull request is told the issue comes first', async () => {
485+
const github = fakeGithub([]);
486+
await run(github, describing('A drive-by fix'));
487+
488+
assert.match(github.calls.comments[0].body, /Open an issue and get assigned to it/);
489+
});
490+
491+
test('a closing keyword on another base links the issue the way the default branch would', async () => {
492+
const github = fakeGithub([], { referenced: { 7: { assignees: ['someone-else'] } } });
493+
await run(github, describing('Fixes #7', { base: 'release-v0.20.x' }));
494+
495+
assert.deepEqual(github.calls.links, [{ issueId: 'I_7', pullRequestIds: ['PR_42'] }]);
496+
assert.deepEqual(github.calls.updates, [{ pull_number: 42, state: 'closed' }]);
497+
assert.match(github.calls.comments[0].body, /issues\/7 is assigned to someone else/);
498+
});
499+
500+
test('a closing keyword on another base starts review without naming the link', async () => {
501+
const github = fakeGithub([], { referenced: { 7: { assignees: [AUTHOR] } } });
502+
await run(github, describing('Fixes #7', { base: 'release-v0.20.x' }));
503+
504+
assert.equal(github.calls.links.length, 1);
505+
assert.deepEqual(github.calls.reviewers, [RTIBBLESBOT_USERNAME]);
506+
assert.doesNotMatch(github.calls.comments[0].body, /We linked/);
507+
});
508+
509+
test('a closing keyword on the default branch is left to GitHub', async () => {
510+
const github = fakeGithub([], { referenced: { 7: { assignees: ['someone-else'] } } });
511+
await run(github, describing('Fixes #7'));
512+
513+
assert.deepEqual(github.calls.links, []);
514+
assert.deepEqual(github.calls.updates, []);
515+
});
516+
517+
test('a pull request that already links an issue reads no mentions', async () => {
518+
const github = fakeGithub([{ number: 7, assignees: [AUTHOR] }], {
519+
referenced: { 8: { assignees: [AUTHOR] } },
520+
});
521+
await run(github, describing('Fixes #7, see #8'));
522+
523+
assert.deepEqual(github.calls.links, []);
524+
});
525+
526+
test('a refused link falls back to asking', async () => {
527+
const github = fakeGithub([], {
528+
referenced: { 7: { assignees: [AUTHOR] } },
529+
linkError: 'Resource not accessible',
530+
});
531+
const core = await run(github, describing('See #7'));
532+
533+
assert.match(github.calls.comments[0].body, /couldn't find an issue/);
534+
assert.doesNotMatch(github.calls.comments[0].body, /We linked/);
535+
assert.deepEqual(github.calls.labels, [LABEL_UNLINKED]);
536+
assert.match(core.warnings.join('\n'), /Resource not accessible/);
537+
assert.deepEqual(core.failures, []);
538+
});
539+
540+
test('an edit mentioning the issue assigned to the author links it and starts review', async () => {
541+
const github = fakeGithub([], { referenced: { 7: { assignees: [AUTHOR] } } });
542+
await run(github, edited(AUTHOR, { labels: [LABEL_UNLINKED], body: 'See #7' }));
543+
544+
assert.equal(github.calls.links.length, 1);
545+
assert.deepEqual(github.calls.comments, []);
546+
assert.deepEqual(github.calls.removed, [LABEL_UNLINKED]);
547+
assert.deepEqual(github.calls.reviewers, [RTIBBLESBOT_USERNAME]);
548+
});

‎scripts/pull-request-link.js‎

Lines changed: 35 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,40 @@ const {
55
LABEL_UNLINKED,
66
RTIBBLESBOT_USERNAME,
77
} = require('./constants');
8-
const { addLabel, removeLabel, isCloseContributor } = require('./utils');
8+
const {
9+
addLabel,
10+
removeLabel,
11+
isCloseContributor,
12+
findIssueReferences,
13+
getReferencedIssues,
14+
addClosingIssueReference,
15+
} = require('./utils');
16+
17+
function chooseReferences(issues, author, defaultBase) {
18+
const closing = defaultBase ? [] : issues.filter(issue => issue.keyword);
19+
if (closing.length) return { link: closing, named: false, ambiguous: [] };
20+
const assigned = issues.filter(issue => issue.assignees.includes(author));
21+
if (assigned.length === 1) return { link: assigned, named: true, ambiguous: [] };
22+
return { link: [], named: false, ambiguous: assigned.length > 1 ? assigned : [] };
23+
}
24+
25+
async function linkReferences(owner, repo, pullRequest, { github, core }) {
26+
const references = findIssueReferences(pullRequest.body, owner, repo);
27+
if (!references.length) return { linked: [], named: null, ambiguous: [] };
28+
const issues = await getReferencedIssues(owner, repo, references, { github, core });
29+
const defaultBase = pullRequest.base.ref === pullRequest.base.repo.default_branch;
30+
const { link, named, ambiguous } = chooseReferences(issues, pullRequest.user.login, defaultBase);
31+
const linked = [];
32+
for (const issue of link) {
33+
try {
34+
await addClosingIssueReference(issue.id, pullRequest.node_id, github);
35+
linked.push(issue);
36+
} catch (error) {
37+
core.warning(`Failed to link #${issue.number} to #${pullRequest.number}: ${error.message}`);
38+
}
39+
}
40+
return { linked, named: named && linked.length ? linked[0] : null, ambiguous };
41+
}
942

1043
function linkStatus(linkedIssues, author) {
1144
if (!linkedIssues.length) return { status: 'unlinked' };
@@ -86,4 +119,4 @@ async function applyLink(owner, repo, number, plan, { github, core }) {
86119
return null;
87120
}
88121

89-
module.exports = { linkStatus, planLink, applyLink };
122+
module.exports = { linkReferences, linkStatus, planLink, applyLink };

0 commit comments

Comments
 (0)