Skip to content
This repository was archived by the owner on Jul 1, 2024. It is now read-only.

Commit 8e68864

Browse files
committed
Put explanations next to suggestions
1 parent 3c0650d commit 8e68864

File tree

4 files changed

+44
-50
lines changed

4 files changed

+44
-50
lines changed

src/comments.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -125,5 +125,5 @@ I'll bump it to the DT maintainer queue. Thank you for your patience, @${author}
125125

126126
// Introduction to the review when config files diverge from the
127127
// expected form
128-
export const suggestions = (user: string) =>
128+
export const explanations = (user: string) =>
129129
`@${user} I noticed these differences from the expected form. If you can revise your changes to avoid them, so much the better! Otherwise please reply with explanations why they're needed and a maintainer will take a look. Thanks!`;

src/compute-pr-actions.ts

Lines changed: 13 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import * as Comments from "./comments";
22
import * as urls from "./urls";
33
import { PrInfo, BotResult, FileInfo } from "./pr-info";
4-
import { ReviewInfo, Suggestion } from "./pr-info";
4+
import { ReviewInfo, Explanation } from "./pr-info";
55
import { noNullish, flatten, unique, sameUser, min, sha256, abbrOid } from "./util/util";
66
import * as dayjs from "dayjs";
77
import * as advancedFormat from "dayjs/plugin/advancedFormat";
@@ -52,7 +52,7 @@ export interface Actions {
5252
targetColumn?: ColumnName;
5353
labels: LabelName[];
5454
responseComments: Comments.Comment[];
55-
suggestions: ({ path: string } & Suggestion)[];
55+
explanations: ({ path: string } & Explanation)[];
5656
shouldClose: boolean;
5757
shouldMerge: boolean;
5858
shouldUpdateLabels: boolean;
@@ -65,7 +65,7 @@ function createDefaultActions(): Actions {
6565
targetColumn: "Other",
6666
labels: [],
6767
responseComments: [],
68-
suggestions: [],
68+
explanations: [],
6969
shouldClose: false,
7070
shouldMerge: false,
7171
shouldUpdateLabels: true,
@@ -78,7 +78,7 @@ function createEmptyActions(): Actions {
7878
return {
7979
labels: [],
8080
responseComments: [],
81-
suggestions: [],
81+
explanations: [],
8282
shouldClose: false,
8383
shouldMerge: false,
8484
shouldUpdateLabels: false,
@@ -294,9 +294,9 @@ export function process(prInfo: BotResult,
294294
// Update intro comment
295295
post({ tag: "welcome", status: createWelcomeComment(info, post) });
296296

297-
// Propagate suggestions into actions
298-
context.suggestions = noNullish(flatten(info.pkgInfo.map(pkg => pkg.files.map(({ path, suggestion }) =>
299-
suggestion && { path, ...suggestion }))));
297+
// Propagate explanations into actions
298+
context.explanations = noNullish(flatten(info.pkgInfo.map(pkg => pkg.files.map(({ path, suspect }) =>
299+
suspect && { path, ...suspect }))));
300300

301301
// Ping reviewers when needed
302302
const headCommitAbbrOid = abbrOid(info.headCommitOid);
@@ -433,9 +433,6 @@ function createWelcomeComment(info: ExtendedPrInfo, post: (c: Comments.Comment)
433433

434434
const announceList = (what: string, xs: readonly string[]) => `${xs.length} ${what}${xs.length !== 1 ? "s" : ""}`;
435435
const usersToString = (users: string[]) => users.map(u => (info.isAuthor(u) ? "✎" : "") + "@" + u).join(", ");
436-
const reviewLink = (f: FileInfo) =>
437-
`[\`${f.path.replace(/^types\/(.*\/)/, "$1")}\`](${
438-
urls.review(info.pr_number)}/${info.headCommitOid}#diff-${sha256(f.path)})`;
439436

440437
display(``,
441438
`## ${announceList("package", info.packages)} in this PR`,
@@ -465,15 +462,6 @@ function createWelcomeComment(info: ExtendedPrInfo, post: (c: Comments.Comment)
465462
displayOwners("added", p.addedOwners);
466463
displayOwners("removed", p.deletedOwners);
467464
if (!info.authorIsOwner && p.owners.length >= 4 && p.addedOwners.some(info.isAuthor)) addedSelfToManyOwners++;
468-
469-
let showSuspects = false;
470-
for (const file of p.files) {
471-
if (!file.suspect) continue;
472-
if (!showSuspects) display(` - Config files to check:`);
473-
display(` - ${reviewLink(file)}: ${file.suspect}`);
474-
showSuspects = true;
475-
}
476-
477465
}
478466
if (addedSelfToManyOwners > 0) {
479467
display(``,
@@ -512,6 +500,9 @@ function createWelcomeComment(info: ExtendedPrInfo, post: (c: Comments.Comment)
512500
display(` * ${emoji(info.ciResult === "pass")} Continuous integration tests have ${expectedResults}`);
513501

514502
const approved = emoji(info.approved);
503+
const reviewLink = (f: FileInfo) =>
504+
`[\`${f.path.replace(/^types\/(.*\/)/, "$1")}\`](${
505+
urls.review(info.pr_number)}/${info.headCommitOid}#diff-${sha256(f.path)})`;
515506

516507
if (info.hasNewPackages) {
517508
display(` * ${approved} Only ${requiredApprover} can approve changes when there are new packages added`);
@@ -532,7 +523,9 @@ function createWelcomeComment(info: ExtendedPrInfo, post: (c: Comments.Comment)
532523
} else if (info.noOtherOwners) {
533524
display(` * ${approved} ${RequiredApprover} can merge changes when there are no other reviewers`);
534525
} else if (info.checkConfig) {
535-
display(` * ${approved} ${RequiredApprover} needs to approve changes which affect module config files`);
526+
const configFiles = flatten(info.pkgInfo.map(pkg => pkg.files.filter(({ kind }) => kind === "package-meta")));
527+
const links = configFiles.map(reviewLink);
528+
display(` * ${approved} ${RequiredApprover} needs to approve changes which affect module config files (${links.join(", ")})`);
536529
} else {
537530
display(` * ${approved} Only ${requiredApprover} can approve changes [without tests](${testsLink})`);
538531
}

src/execute-pr-actions.ts

Lines changed: 13 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ export async function executePrActions(actions: Actions, pr: PR_repository_pullR
1818
...await getMutationsForProjectChanges(actions, pr),
1919
...getMutationsForComments(actions, pr.id, botComments),
2020
...getMutationsForCommentRemovals(actions, botComments),
21-
...getMutationsForSuggestions(actions, pr),
21+
...getMutationsForExplanations(actions, pr),
2222
...getMutationsForChangingPRState(actions, pr),
2323
]);
2424
if (!dry) {
@@ -102,23 +102,28 @@ function getMutationsForCommentRemovals(actions: Actions, botComments: ParsedCom
102102
});
103103
}
104104

105-
function getMutationsForSuggestions(actions: Actions, pr: PR_repository_pullRequest) {
106-
// Suggestions will be empty if we already reviewed this head
107-
if (actions.suggestions.length === 0) return [];
105+
function getMutationsForExplanations(actions: Actions, pr: PR_repository_pullRequest) {
106+
// Explanations will be empty if we already reviewed this head
107+
if (actions.explanations.length === 0) return [];
108108
if (!pr.author) throw new Error("Internal Error: expected to be checked");
109109
return [
110-
...actions.suggestions.map(({ path, startLine, endLine, text }) =>
111-
createMutation<schema.AddPullRequestReviewThreadInput>("addPullRequestReviewThread", {
110+
...actions.explanations.map(({ path, startLine, endLine, body }) => endLine
111+
? createMutation<schema.AddPullRequestReviewThreadInput>("addPullRequestReviewThread", {
112112
pullRequestId: pr.id,
113113
path,
114114
startLine: startLine === endLine ? undefined : startLine,
115115
line: endLine,
116-
body: "```suggestion\n" + text + "```",
116+
body,
117+
})
118+
: createMutation<schema.AddPullRequestReviewCommentInput>("addPullRequestReviewComment", {
119+
pullRequestId: pr.id,
120+
path,
121+
body,
117122
})
118123
),
119124
createMutation<schema.SubmitPullRequestReviewInput>("submitPullRequestReview", {
120125
pullRequestId: pr.id,
121-
body: comments.suggestions(pr.author.login),
126+
body: comments.explanations(pr.author.login),
122127
event: "COMMENT",
123128
}),
124129
];

src/pr-info.ts

Lines changed: 17 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -55,14 +55,13 @@ type FileKind = "test" | "definition" | "markdown" | "package-meta" | "package-m
5555
export type FileInfo = {
5656
path: string,
5757
kind: FileKind,
58-
suspect?: string, // reason for a file being "package-meta" rather than "package-meta-ok"
59-
suggestion?: Suggestion, // The differences from the expected form, as GitHub suggestions
58+
suspect?: Explanation // reason for a file being "package-meta" rather than "package-meta-ok"
6059
};
6160

62-
export interface Suggestion {
63-
readonly startLine: number;
64-
readonly endLine: number;
65-
readonly text: string;
61+
export interface Explanation {
62+
readonly startLine?: number;
63+
readonly endLine?: number;
64+
readonly body: string;
6665
}
6766

6867
export type ReviewInfo = {
@@ -185,7 +184,7 @@ export async function queryPRInfo(prNumber: number) {
185184
interface Refs {
186185
readonly head: string;
187186
readonly master: "master";
188-
readonly latestSuggestions: string;
187+
readonly latestExplanations: string;
189188
}
190189

191190
// The GQL response => Useful data for us
@@ -217,8 +216,8 @@ export async function deriveStateForPR(
217216
const refs = {
218217
head: prInfo.headRefOid,
219218
master: "master",
220-
// Exclude existing suggestions from subsequent reviews
221-
latestSuggestions: max(noNullish(prInfo.reviews?.nodes).filter(review => !authorNotBot(review)), (a, b) =>
219+
// Exclude existing explanations from subsequent reviews
220+
latestExplanations: max(noNullish(prInfo.reviews?.nodes).filter(review => !authorNotBot(review)), (a, b) =>
222221
Date.parse(a.submittedAt) - Date.parse(b.submittedAt))?.commit?.oid,
223222
} as const;
224223
const pkgInfoEtc = await getPackageInfosEtc(
@@ -352,19 +351,19 @@ async function categorizeFile(path: string, getContents: GetContents): Promise<[
352351
case "md": return [pkg, { path, kind: "markdown" }];
353352
default: {
354353
const suspect = await configSuspicious(path, getContents);
355-
return [pkg, { path, kind: suspect ? "package-meta" : "package-meta-ok", ...suspect }];
354+
return [pkg, { path, kind: suspect ? "package-meta" : "package-meta-ok", suspect }];
356355
}
357356
}
358357
}
359358

360359
interface ConfigSuspicious {
361-
(path: string, getContents: GetContents): Promise<{ suspect: string, sugestion?: Suggestion } | undefined>;
362-
[basename: string]: (newText: string, getContents: GetContents) => Promise<{ suspect: string, suggestion?: Suggestion } | undefined>;
360+
(path: string, getContents: GetContents): Promise<Explanation | undefined>;
361+
[basename: string]: (newText: string, getContents: GetContents) => Promise<Explanation | undefined>;
363362
}
364363
const configSuspicious = <ConfigSuspicious>(async (path, getContents) => {
365364
const basename = path.replace(/.*\//, "");
366365
const checker = configSuspicious[basename];
367-
if (!checker) return { suspect: `edited` };
366+
if (!checker) return { body: `edited` };
368367
const newText = await getContents("head");
369368
// Removing tslint.json, tsconfig.json, package.json and
370369
// OTHER_FILES.txt is checked by the CI. Specifics are in my commit
@@ -423,7 +422,7 @@ function makeChecker(expectedForm: any, expectedFormUrl: string, options?: { par
423422
if (options && "parse" in options) {
424423
suggestion = options.parse(newText);
425424
} else {
426-
try { suggestion = JSON.parse(newText); } catch (e) { if (e instanceof SyntaxError) return { suspect: `couldn't parse json: ${e.message}` }; }
425+
try { suggestion = JSON.parse(newText); } catch (e) { if (e instanceof SyntaxError) return { body: `couldn't parse json: ${e.message}` }; }
427426
}
428427
const newData = jsonDiff.deepClone(suggestion);
429428
if (options && "ignore" in options) options.ignore(newData);
@@ -432,15 +431,12 @@ function makeChecker(expectedForm: any, expectedFormUrl: string, options?: { par
432431
// suspect
433432
const vsMaster = await ignoreExistingDiffs("master");
434433
if (!vsMaster) return undefined;
435-
if (vsMaster.done) return { suspect: vsMaster.suspect };
434+
if (vsMaster.done) return { body: vsMaster.suspect };
436435
// whereas getting closer relative to existing suggestions means
437436
// no new suggestions
438-
if (!await ignoreExistingDiffs("latestSuggestions")) return { suspect: vsMaster.suspect };
437+
if (!await ignoreExistingDiffs("latestExplanations")) return { body: vsMaster.suspect };
439438
jsonDiff.applyPatch(suggestion, jsonDiff.compare(newData, towardsIt));
440-
return {
441-
suspect: vsMaster.suspect,
442-
suggestion: makeSuggestion(),
443-
};
439+
return makeSuggestion();
444440

445441
// Apply any preexisting diffs to towardsIt
446442
async function ignoreExistingDiffs(ref: keyof Refs) {
@@ -490,7 +486,7 @@ function makeChecker(expectedForm: any, expectedFormUrl: string, options?: { par
490486
return {
491487
startLine,
492488
endLine,
493-
text: suggestionLines.join(""),
489+
body: vsMaster!.suspect + "\n```suggestion\n" + suggestionLines.join("") + "```",
494490
};
495491
}
496492
};

0 commit comments

Comments
 (0)