forked from WebKit/WebKit
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWebKitBot.mjs
More file actions
467 lines (416 loc) · 16.3 KB
/
WebKitBot.mjs
File metadata and controls
467 lines (416 loc) · 16.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
/*
* Copyright (C) 2020 Apple Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import path from "path";
import util from "util";
import {execFile, spawn} from "child_process";
import SlackRTMAPI from "@slack/rtm-api";
import AsyncTaskQueue from "./AsyncTaskQueue.mjs";
import {dataLogLn, escapeForSlackText, isASCII, rootDirectoryOfWebKit} from "./Utility.mjs";
const webkitPatchPath = path.resolve(rootDirectoryOfWebKit(), "Tools", "Scripts", "webkit-patch");
const defaultTaskLimit = 10;
const defaultPullPeriod = 60 * 1000 * 60;
const defaultTimeoutForRevert = 60 * 1000 * 10;
const execFileAsync = util.promisify(execFile);
function parseBugId(string)
{
if (!string)
return null;
let match = string.match(/^https?:\/\/webkit\.org\/b\/(\d+)$/m);
if (match)
return match[1];
match = string.match(/^https?:\/\/bugs\.webkit\.org\/show_bug\.cgi\?id=(\d+)(?:&ctype=xml|&excludefield=attachmentdata)*$/m);
if (match)
return match[1];
return null;
}
function extractRevision(text)
{
let revisions = [];
for (let candidate of text.split(",")) {
candidate = candidate.trim();
if (!candidate)
continue;
let match = candidate.match(/^r?(\d+):?$/);
if (!match)
return null;
revisions.push(match[1]);
}
return revisions;
}
export function extractRevisionsAndReason(args)
{
let revisions = [];
let reason = "";
for (let i = 0; i < args.length; ++i) {
let arg = args[i];
let extracted = extractRevision(arg);
if (!extracted) {
let reasons = [];
for (; i < args.length; ++i)
reasons.push(args[i]);
reason = reasons.join(" ").trim();
break;
}
revisions.push(...extracted);
}
// If reason starts with quote and ends with the same quote, remove them once.
if (reason.length >= 2) {
let firstCharacterOfReason = reason.charAt(0);
if (firstCharacterOfReason === "'" || firstCharacterOfReason === "\"" || firstCharacterOfReason === "`") {
if (reason.charAt(reason.length - 1) === firstCharacterOfReason)
reason = reason.slice(1, reason.length - 1);
}
}
return {revisions, reason};
}
export function extractCommandAndArgs(text)
{
let args = text.trim().split(/\s+/);
let command = args.shift().toLowerCase();
return {command, args};
}
export function extractTextIfMentioned(text, id)
{
let regexp = new RegExp(`<@${id}>`);
let globalRegexp = new RegExp(`<@${id}>`, "g");
let matched = text.match(regexp);
if (!matched)
return null;
text = text.replace(globalRegexp, "");
// Preprocessing for the text.
// 1. Convert smart quotes to normal ASCII quotes because webkit-patch cannot accept non-ASCII text and slack may convert normal quotes to smart quotes.
text = text.replace(/[\u2018\u2019]/g, "'");
text = text.replace(/[\u201C\u201D]/g, "\"");
// 2. Convert line-terminators to spaces. It is unlikely that we want to have line-terminators in webkitbot commands.
text = text.replace(/(\r\n|\n|\r|\u2028|\u2029)/g, " ");
return text;
}
export default class WebKitBot {
constructor(webClient, auth)
{
this._taskQueue = new AsyncTaskQueue(defaultTaskLimit);
this._web = webClient;
this._auth = auth;
this._commands = new Map;
let revertCommand = {
description: "Opens a bug to revert the specified revision, CCing author + reviewer, and attaching the reverse-diff of the given revisions marked as commit-queue=?.",
usage: `\`revert SVN_REVISION [SVN_REVISIONS] REASON\`
e.g. \`revert 260220 Ensure it is working after refactoring\`
\`revert 260220,260221 Ensure it is working after refactoring\``,
operation: this.revertCommand.bind(this),
};
this._commands.set("rollout", revertCommand);
this._commands.set("revert", revertCommand);
this._commands.set("dry-revert", {
description: "Parse revert message, but do not revert actually.",
usage: `\`dry-revert SVN_REVISION [SVN_REVISIONS] REASON\`
e.g. \`dry-revert 260220 Ensure it is working after refactoring\`
\`dry-revert 260220,260221 Ensure it is working after refactoring\``,
operation: this.dryRevertCommand.bind(this),
});
this._commands.set("ping", {
description: "Responds with pong to check if WebKitBot is alive/working",
usage: "`ping`",
operation: this.pingCommand.bind(this),
});
this._commands.set("pull", {
description: "Pulls the latest checkout of WebKit checkout for reverting queue.",
usage: "`pull`",
operation: this.pullCommand.bind(this),
});
this._commands.set("help", {
description: "Provides help on my individual commands.",
usage: "`help [COMMAND]`",
operation: this.helpCommand.bind(this),
});
this._commands.set("status", {
description: "Shows current reverting queue status.",
usage: "`status`",
operation: this.statusCommand.bind(this),
});
this._rtm = new SlackRTMAPI.RTMClient(process.env.SLACK_TOKEN);
this._rtm.on("message", async (event) => {
if (event.type !== "message")
return;
// If message has subtype, this is not an usual message.
if (event.subtype)
return;
let text = extractTextIfMentioned(event.text, this._auth.user_id);
if (text) {
let {command, args} = extractCommandAndArgs(text);
let operation = this._commands.get(command);
if (operation)
await operation.operation(event, command, args);
else
await this.unknownCommand(event, command, args);
}
});
setInterval(() => {
this._taskQueue.postOrFailWhenExceedingLimit({
command: "pull",
});
}, defaultPullPeriod);
}
async revertCommand(event, command, args)
{
let {revisions, reason} = extractRevisionsAndReason(args);
if (!isASCII(reason)) {
await this._web.chat.postMessage({
channel: event.channel,
text: `<@${event.user}> webkit-patch only accepts an ASCII string for reason: \`${escapeForSlackText(reason)}\``,
});
return;
}
dataLogLn(revisions, reason);
if (revisions.length) {
try {
await this._web.chat.postMessage({
channel: event.channel,
text: `<@${event.user}> Preparing revert for ${revisions.map((revision) => `<${escapeForSlackText(`https://trac.webkit.org/r${revision}|r${revision}`)}>`).join(" ")} ...`,
});
let bugId = await this._taskQueue.postOrFailWhenExceedingLimit({
command: "revert",
revisions,
reason,
});
await this._web.chat.postMessage({
channel: event.channel,
text: `<@${event.user}> Created a revert patch https://webkit.org/b/${escapeForSlackText(bugId)}`,
});
} catch (error) {
console.error(error);
await this._web.chat.postMessage({
channel: event.channel,
text: `<@${event.user}> Failed to create revert patch.`,
});
}
return;
}
await this._web.chat.postMessage({
channel: event.channel,
text: `<@${event.user}> Failed to parse revision and reason`,
});
}
async dryRevertCommand(event, command, args)
{
let {revisions, reason} = extractRevisionsAndReason(args);
if (!isASCII(reason)) {
await this._web.chat.postMessage({
channel: event.channel,
text: `<@${event.user}> webkit-patch only accepts an ASCII string for reason: \`${escapeForSlackText(reason)}\``,
});
return;
}
if (!revisions.length) {
await this._web.chat.postMessage({
channel: event.channel,
text: `<@${event.user}> No revision is found: reason = \`${escapeForSlackText(reason)}\``,
});
return;
}
await this._web.chat.postMessage({
channel: event.channel,
text: `<@${event.user}> revisions = \`${escapeForSlackText(revisions.join(","))}\`, reason = \`${escapeForSlackText(reason)}\``,
});
}
async pullCommand(event, command, args)
{
await this._web.chat.postMessage({
channel: event.channel,
text: `<@${event.user}> Preparing pulling the latest WebKit checkout.`,
});
await this._taskQueue.postOrFailWhenExceedingLimit({
command: "pull",
});
await this._web.chat.postMessage({
channel: event.channel,
text: `<@${event.user}> Pulled the latest checkout.`,
});
}
async pingCommand(event, command, args)
{
await this._web.chat.postMessage({
channel: event.channel,
text: `<@${event.user}> pong`,
});
}
async helpCommand(event, command, args)
{
if (args.length) {
let commandName = args[0];
let operation = this._commands.get(commandName);
if (operation) {
await this._web.chat.postMessage({
channel: event.channel,
text: `<@${event.user}> \`${escapeForSlackText(commandName)}\`: ${escapeForSlackText(operation.description)}
Usage: ${escapeForSlackText(operation.usage)}`,
});
} else {
await this._web.chat.postMessage({
channel: event.channel,
text: `<@${event.user}> Unknown command \`${escapeForSlackText(commandName)}\``,
});
}
} else {
let commandNames = [];
for (let key of this._commands.keys())
commandNames.push("`" + key + "`");
await this._web.chat.postMessage({
channel: event.channel,
text: `<@${event.user}> Available commands: ${escapeForSlackText(commandNames.join(", "))}
Type \`help COMMAND\` for help on my individual commands.`,
});
}
}
async statusCommand(event, command, args)
{
await this._web.chat.postMessage({
channel: event.channel,
text: `<@${event.user}> ${escapeForSlackText(this._taskQueue.length)} requests in queue.`,
});
}
async unknownCommand(event, command, args)
{
dataLogLn("Unknown command: ", command);
await this._web.chat.postMessage({
channel: event.channel,
text: `<@${event.user}> Unknown command \`${escapeForSlackText(command)}\``,
});
}
execInWebKitDirectorySimple(command, args)
{
return new Promise((resolve, reject) => {
let task = spawn(command, args, {
cwd: process.env.webkitWorkingDirectory,
env: {},
stdio: "inherit",
});
task.on("close", (code) => {
if (!code)
resolve(code);
else
reject(code);
});
});
}
async cleanUpWorkingCopy()
{
dataLogLn("1. Resetting");
await this.execInWebKitDirectorySimple("git", ["reset", "--hard"]);
dataLogLn("2. Cleaning");
await this.execInWebKitDirectorySimple("git", ["clean", "-df"]);
dataLogLn("3. Pulling");
await this.execInWebKitDirectorySimple("git", ["pull", "origin", "master"]);
dataLogLn("4. Fetching");
await this.execInWebKitDirectorySimple("git", ["svn", "fetch"]);
}
async generateRevertingPatch(revisions, reason)
{
dataLogLn("Reverting ", revisions, reason);
let revisionsArgument = revisions.map((revision) => {
let number = Number.parseInt(revision, 10);
if (!Number.isFinite(number))
throw new Error(`Invalid svn revision number "${String(revision)}"`);
return number;
}).join(" ");
if (reason.startsWith("-"))
throw new Error(`The revert reason may not begin with - ("${reason}")`);
await this.cleanUpWorkingCopy();
dataLogLn("5. Creating revert patch ", revisions, reason);
let results;
try {
results = await execFileAsync(webkitPatchPath, [
"create-revert",
"--force-clean",
// In principle, we should pass --non-interactive here, but it
// turns out that create-revert doesn't need it yet. We can't
// pass it prophylactically because we reject unrecognized command
// line switches.
"--parent-command=sheriff-bot",
revisionsArgument,
reason,
], {
cwd: process.env.webkitWorkingDirectory,
env: {
CHANGE_LOG_NAME: "Commit Queue",
CHANGE_LOG_EMAIL_ADDRESS: "commit-queue@webkit.org",
webkit_bugzilla_username: process.env.webkitBugzillaUsername,
webkit_bugzilla_password: process.env.webkitBugzillaPassword,
},
timeout: defaultTimeoutForRevert,
maxBuffer: 1024 * 1024 * 50,
});
} catch (error) {
dataLogLn(error);
throw new Error("Revert command failed");
}
let {stdout, stderr} = results;
dataLogLn(stdout);
dataLogLn(stderr);
{
let bugId = parseBugId(stdout);
if (bugId !== null)
return bugId;
}
{
let bugId = parseBugId(stderr);
if (bugId !== null)
return bugId;
}
throw new Error("bug-id cannot be found");
}
async action(task)
{
dataLogLn(task);
switch (task.command) {
case "revert": {
let {revisions, reason} = task;
return this.generateRevertingPatch(revisions, reason);
}
case "pull":
return this.cleanUpWorkingCopy();
}
throw new Error(`${task.command} is undefined action`);
}
static async create(webClient, auth)
{
let bot = new WebKitBot(webClient, auth);
await bot._rtm.start();
return bot;
}
static async main(webClient, auth)
{
let bot = await WebKitBot.create(webClient, auth);
while (true) {
let {task, resolve, reject} = await bot._taskQueue.take();
try {
let result = await bot.action(task);
resolve(result);
} catch (error) {
reject(error);
}
}
}
}