Diff
Modified: trunk/Tools/ChangeLog (264209 => 264210)
--- trunk/Tools/ChangeLog 2020-07-10 06:00:31 UTC (rev 264209)
+++ trunk/Tools/ChangeLog 2020-07-10 07:02:30 UTC (rev 264210)
@@ -1,3 +1,54 @@
+2020-07-09 Yusuke Suzuki <[email protected]>
+
+ Add Slack-aware WebKitBot implementation
+ https://bugs.webkit.org/show_bug.cgi?id=211707
+
+ Reviewed by Devin Rousso and Brian Burg.
+
+ This patch adds Slack-aware WebKitBot implementation which supports "ping", "revert", and the other commands.
+ I decided to implement this feature in chat-bot because of the following reasons.
+
+ 1. It is the previous way we are familiar with.
+ 2. Creating a revert-patch sometimes takes long time because it involves working-copy clean-up, creating a revert, generating a patch...
+ So asynchronous request-response is better for developers who do not want to watch whether the patch is created until it is done.
+ Chat-bot can tell us when it is ready.
+ 3. Requesting a revert-patch in public channel can easily tell the other developers that reverting is going on now.
+
+ We reuse python's `webkit-patch create-revert` command as it was in the old webkitbot. We enhance WKR bot to support webkitbot feature.
+ Once webkitbot app is installed into a channel, it monitors messages in the channel and works when the mention to this bot's user happens.
+
+ We use Real Time Message Slack API instead of Event API, because Event API requires public facing HTTPS server which accepts incoming webhook.
+ Real Time Message Slack API just requires a server app which connects to Slack via WebSocket, so it is easier to deploy for now.
+
+ The implementation of webkitbot is client-server model inside one process. There is one AsyncTaskQueue, and there is one async main loop which
+ takes the task from the queue and replies when it is done. Every time we noticed the request, this request queues the task to this task queue.
+ This design ensures that only one task is using the working-copy WebKit repository at a time, this is required to make a revert-patch without
+ conflict.
+
+ * WKR/ReadMe.md: Removed.
+ * WKR/WKR.mjs: Removed.
+ * WKR/package-lock.json: Removed.
+ * WKR/package.json: Removed.
+ * WebKitBot/.eslintrc: Added.
+ * WebKitBot/.gitignore: Renamed from Tools/WKR/.gitignore.
+ * WebKitBot/ReadMe.md: Added.
+ * WebKitBot/data/.gitignore: Renamed from Tools/WKR/data/.gitignore.
+ * WebKitBot/package-lock.json: Added.
+ * WebKitBot/package.json: Added.
+ * WebKitBot/src/AsyncTaskQueue.mjs: Added.
+ * WebKitBot/src/Commit.mjs: Added.
+ * WebKitBot/src/Contributors.mjs: Added.
+ * WebKitBot/src/Utility.mjs: Added.
+ * WebKitBot/src/WKR.mjs: Added.
+ * WebKitBot/src/WebKitBot.mjs: Added.
+ * WebKitBot/src/index.mjs: Added.
+ * WebKitBot/tests/Commit.test.mjs: Added.
+ * WebKitBot/tests/WebKitBot.test.mjs: Added.
+ * WebKitBot/tests/resources/.gitattributes: Added.
+ * WebKitBot/tests/resources/HaveRadarAndBugzilla.json: Added.
+ * WebKitBot/tests/resources/HavingBugzilla.json: Added.
+ * WebKitBot/tests/resources/NoRadarAndBugzilla.json: Added.
+
2020-07-09 Andres Gonzalez <[email protected]>
Make accessibility/Mac/selected-visible-position-range.html time-deterministic.
Added: trunk/Tools/WebKitBot/.eslintrc (0 => 264210)
--- trunk/Tools/WebKitBot/.eslintrc (rev 0)
+++ trunk/Tools/WebKitBot/.eslintrc 2020-07-10 07:02:30 UTC (rev 264210)
@@ -0,0 +1,85 @@
+/*
+ * Copyright (C) 2014-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. AND ITS CONTRIBUTORS ``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 ITS 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.
+ */
+
+{
+ "extends": "eslint:recommended",
+ "env": {
+ "es6": true,
+ "node": true,
+ "jest": true,
+ },
+ "parserOptions": {
+ "ecmaVersion": 2020,
+ "sourceType": "module",
+ },
+ "rules": {
+ "array-bracket-spacing": [2, "never"],
+ "block-spacing": [2, "always"],
+ "comma-dangle": [2, "always-multiline"],
+ "comma-spacing": [2, {"before": false, "after": true}],
+ "comma-style": [2, "last"],
+ "consistent-return": 2,
+ "curly": 0,
+ "dot-notation": 0,
+ "eol-last": 2,
+ "eqeqeq": 2,
+ "indent": ["error", 4],
+ "func-call-spacing": [2, "never"],
+ "key-spacing": [2, {"beforeColon": false, "afterColon": true}],
+ "keyword-spacing": [2, {"before": true, "after": true}],
+ "new-cap": 0,
+ "new-parens": 0,
+ "no-console": 0,
+ "no-constant-condition": 0,
+ "no-control-regex": 0,
+ "no-extra-bind": 2,
+ "no-extra-parens": [2, "all", {"nestedBinaryExpressions": false}],
+ "no-extra-semi": 2,
+ "no-global-assign": 2,
+ "no-inner-declarations": 0,
+ "no-multi-spaces": 2,
+ "no-new": 0,
+ "no-proto": 0,
+ "no-redeclare": 0,
+ "no-return-assign": 2,
+ "no-return-await": 2,
+ "no-self-compare": 2,
+ "no-shadow": 0,
+ "no-trailing-spaces": 2,
+ "no-undef": 2,
+ "no-underscore-dangle": 0,
+ "no-unused-expressions": 2,
+ "no-unused-vars": [2, {"vars": "all", "args": "none"}],
+ "no-use-before-define": 0,
+ "object-curly-spacing": [2, "never"],
+ "quotes": [2, "double"],
+ "semi": 2,
+ "semi-spacing": [2, {"before": false, "after": true}],
+ "space-infix-ops": 2,
+ "spaced-comment": [2, "always"],
+ "strict": 0,
+ "valid-typeof": 2,
+ }
+}
Copied: trunk/Tools/WebKitBot/.gitignore (from rev 264208, trunk/Tools/WKR/.gitignore) (0 => 264210)
--- trunk/Tools/WebKitBot/.gitignore (rev 0)
+++ trunk/Tools/WebKitBot/.gitignore 2020-07-10 07:02:30 UTC (rev 264210)
@@ -0,0 +1 @@
+.env
Added: trunk/Tools/WebKitBot/ReadMe.md (0 => 264210)
--- trunk/Tools/WebKitBot/ReadMe.md (rev 0)
+++ trunk/Tools/WebKitBot/ReadMe.md 2020-07-10 07:02:30 UTC (rev 264210)
@@ -0,0 +1,36 @@
+# WebKitBot
+
+New WebKitBot implementation for WebKit Slack #changes and #dev channels.
+This node.js app has two bot features, WKR and WebKitBot.
+WKR is fetching git.webkit.org RSS feed periodically, extracting data from that, and posting them to #changes channel.
+WebKitBot is an interactive bot in #dev to serve `revert` feature for you without clobbering your WebKit working copy.
+
+## Steps to run
+
+1. Run `npm install` to install libraries
+2. Put `.env` file, which should include five parameters. See "Configuration" section below.
+3. Run `npm start`
+
+## Configuration
+
+Put `.env` file including the followings.
+
+```
+slackURL="<Slack Endpoint URL>"
+SLACK_TOKEN="<Slack API Token>"
+webkitWorkingDirectory="/path/to/WebKit/repository/used/used/by/revert/command"
+webkitBugzillaUsername="[email protected]"
+webkitBugzillaPassword="<commit-queue's password>"
+```
+
+- Find Slack endpoint URL from [https://webkit.slack.com/apps/A0F7XDUAZ-incoming-webhooks?next_id=0](Incomming WebHook page).
+- Find Slack API Token (called `Bot User OAuth Access Token`) from [https://api.slack.com/apps/A013CJ77QFM](WebKitBot's app page).
+
+## How to test
+
+- Test via `npm test`.
+- Lint via `npm run lint`.
+
+## Details
+
+The lastest posted revision data is stored in `data/` directory. You can clean up state if you remove files in `data/`.
Copied: trunk/Tools/WebKitBot/data/.gitignore (from rev 264208, trunk/Tools/WKR/data/.gitignore) (0 => 264210)
--- trunk/Tools/WebKitBot/data/.gitignore (rev 0)
+++ trunk/Tools/WebKitBot/data/.gitignore 2020-07-10 07:02:30 UTC (rev 264210)
@@ -0,0 +1,2 @@
+*
+!.gitignore
Added: trunk/Tools/WebKitBot/src/AsyncTaskQueue.mjs (0 => 264210)
--- trunk/Tools/WebKitBot/src/AsyncTaskQueue.mjs (rev 0)
+++ trunk/Tools/WebKitBot/src/AsyncTaskQueue.mjs 2020-07-10 07:02:30 UTC (rev 264210)
@@ -0,0 +1,87 @@
+/*
+ * 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.
+ */
+
+export default class AsyncTaskQueue {
+ constructor(limit = Infinity)
+ {
+ this._tasks = [];
+ this._limit = limit;
+ this._setUpCondition();
+ }
+
+ async take()
+ {
+ while (!this._tasks.length)
+ await this._conditionPromise;
+ let task = this._tasks.shift();
+ this._wakeUp();
+ return task;
+ }
+
+ async post(task)
+ {
+ while (this._tasks.length >= this._limit)
+ await this._conditionPromise;
+ return this._postTask(task);
+ }
+
+ async postOrFailWhenExceedingLimit(task)
+ {
+ if (this._tasks.length >= this._limit)
+ throw new Error("Too many tasks are queued");
+ return this._postTask(task);
+ }
+
+ get length()
+ {
+ return this._tasks.length;
+ }
+
+ _postTask(task)
+ {
+ return new Promise((resolve, reject) => {
+ this._tasks.push({
+ task,
+ resolve,
+ reject,
+ });
+ this._wakeUp();
+ });
+ }
+
+ _setUpCondition()
+ {
+ this._conditionPromise = new Promise((resolve) => {
+ this._conditionPromiseResolve = resolve;
+ });
+ }
+
+ _wakeUp()
+ {
+ let resolve = this._conditionPromiseResolve;
+ this._setUpCondition();
+ resolve();
+ }
+}
Added: trunk/Tools/WebKitBot/src/Commit.mjs (0 => 264210)
--- trunk/Tools/WebKitBot/src/Commit.mjs (rev 0)
+++ trunk/Tools/WebKitBot/src/Commit.mjs 2020-07-10 07:02:30 UTC (rev 264210)
@@ -0,0 +1,128 @@
+/*
+ * 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 replaceAll from "replaceall";
+import {escapeForSlackText} from "./Utility.mjs";
+
+function findAndRemove(change, regExp)
+{
+ let matched = change.match(regExp);
+ if (matched) {
+ change = change.replace(regExp, "");
+ return [matched[1], change];
+ }
+ return [null, change];
+}
+
+function cleanUpChange(change, contributors)
+{
+ for (let entry of contributors.entries) {
+ if (!entry.nicks)
+ continue;
+
+ let nameWithNicks = `${entry.fullName} (@${entry.nicks[0]})`;
+ if (change.includes(entry.fullName)) {
+ change = replaceAll(entry.fullName, nameWithNicks, change);
+ for (let email of entry.emails)
+ change = replaceAll(`<${email}>`, "", change);
+ } else {
+ for (let email of entry.emails)
+ change = replaceAll(` ${email} `, ` ${nameWithNicks} `, change);
+ }
+ }
+ return change;
+}
+
+export default class Commit {
+ constructor(feedItem, contributors)
+ {
+ let originalChange = feedItem.contentSnippet;
+ let change = cleanUpChange(originalChange, contributors);
+ [this._revision, change] = findAndRemove(change, /^git-svn-id: https:\/\/svn\.webkit\.org\/repository\/webkit\/trunk@(\d+) /im);
+ [this._patchBy, change] = findAndRemove(change, /^Patch\s+by\s+(.+?)\s+on(?:\s+\d{4}-\d{2}-\d{2})?\n?/im);
+ [this._revert, change] = findAndRemove(change, /(?:rolling out|reverting) (r?\d+(?:(?:,\s*|,?\s*and\s+)?r?\d+)*)\.?\s*/im);
+ [this._bugzilla, change] = findAndRemove(change, /https?:\/\/(?:bugs\.webkit\.org\/show_bug\.cgi\?id=|webkit\.org\/b\/)(\d+)/im);
+ [this._radar, change] = findAndRemove(change, /<rdar:\/\/(?:problem\/)?(\d+)>/im);
+ this._email = feedItem.author;
+
+ let lines = originalChange.split("\n");
+ this._title = feedItem.title;
+ if (lines.length)
+ this._title = lines[0];
+
+ if (this._patchBy)
+ this._author = this._patchBy;
+ if (!this._author) {
+ this._author = this._email;
+ if (this._email) {
+ let entry = contributors.queryWithEmail(this._email);
+ if (entry && entry.nicks && entry.nicks[0])
+ this._author = `${entry.fullName} (@${entry.nicks[0]})`;
+ }
+ }
+ if (this._revert) {
+ let matched = change.match(/^"?(.+?)"? \(Requested\s+by\s+(.+?)\s+on\s+#webkit\)\./im);
+ if (matched) {
+ // FIXME: Implement more descriptive message when we detect that this commit is revert commit.
+ // let reason = matched[0];
+ // let author = matched[1];
+ }
+ }
+
+ if (!this._revision)
+ throw new Error("Cannot find revision");
+ this._revision = Number.parseInt(this._revision, 10);
+ this._bugzilla = this._bugzilla ? Number.parseInt(this._bugzilla, 10) : null;
+ this._radar = this._radar ? Number.parseInt(this._radar, 10) : null;
+ this._url = `https://trac.webkit.org/r${this._revision}`;
+ }
+
+ get revision() { return this._revision; }
+ get patchBy() { return this._patchBy; }
+ get revert() { return this._revert; }
+ get bugzilla() { return this._bugzilla; }
+ get email() { return this._email; }
+ get radar() { return this._radar; }
+ get title() { return this._title; }
+ get author() { return this._author; }
+ get url() { return this._url; }
+
+ message()
+ {
+ let results = [];
+ results.push(escapeForSlackText(`${this._title}`));
+ results.push(escapeForSlackText(`${this._url} by ${this._author}`));
+ let urls = [];
+ if (this._bugzilla !== null)
+ urls.push(escapeForSlackText(`https://webkit.org/b/${this._bugzilla}`));
+ if (this._radar !== null) {
+ // Link it in Slack format `<>`.
+ urls.push(`<rdar://problem/${this._radar}>`);
+ }
+ if (urls.length !== 0)
+ results.push(urls.join(" "));
+ return results.join("\n");
+ }
+}
Added: trunk/Tools/WebKitBot/src/Contributors.mjs (0 => 264210)
--- trunk/Tools/WebKitBot/src/Contributors.mjs (rev 0)
+++ trunk/Tools/WebKitBot/src/Contributors.mjs 2020-07-10 07:02:30 UTC (rev 264210)
@@ -0,0 +1,53 @@
+/*
+ * 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 axios from "axios";
+
+const contributorsURL = "https://svn.webkit.org/repository/webkit/trunk/Tools/Scripts/webkitpy/common/config/contributors.json";
+
+export default class Contributors {
+ static async create()
+ {
+ let response = await axios.get(contributorsURL);
+ return new Contributors(response.data);
+ }
+
+ constructor(data)
+ {
+ this.emails = new Map;
+ this.entries = [];
+ for (let [fullName, entry] of Object.entries(data)) {
+ entry.fullName = fullName;
+ this.entries.push(entry);
+ for (let email of entry.emails)
+ this.emails.set(email, entry);
+ }
+ }
+
+ queryWithEmail(email)
+ {
+ return this.emails.get(email);
+ }
+}
Added: trunk/Tools/WebKitBot/src/Utility.mjs (0 => 264210)
--- trunk/Tools/WebKitBot/src/Utility.mjs (rev 0)
+++ trunk/Tools/WebKitBot/src/Utility.mjs 2020-07-10 07:02:30 UTC (rev 264210)
@@ -0,0 +1,55 @@
+/*
+ * 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";
+
+// https://api.slack.com/reference/surfaces/formatting#escaping
+export function escapeForSlackText(text)
+{
+ return text.replace("&", "&").replace("<", "<").replace(">", ">");
+}
+
+const DEBUG = false;
+
+export function dataLogLn(message)
+{
+ if (DEBUG)
+ console.log(message);
+}
+
+export function isASCII(string)
+{
+ return /^[\u0000-\u007F]*$/.test(string);
+}
+
+export function rootDirectoryOfWebKitBot()
+{
+ return path.dirname(new URL(import.meta.url).pathname);
+}
+
+export function rootDirectoryOfWebKit()
+{
+ return path.resolve(rootDirectoryOfWebKitBot(), "..", "..", "..");
+}
Added: trunk/Tools/WebKitBot/src/WKR.mjs (0 => 264210)
--- trunk/Tools/WebKitBot/src/WKR.mjs (rev 0)
+++ trunk/Tools/WebKitBot/src/WKR.mjs 2020-07-10 07:02:30 UTC (rev 264210)
@@ -0,0 +1,105 @@
+/*
+ * 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 RSS from "rss-parser";
+import storage from "node-persist";
+import axios from "axios";
+import Commit from "./Commit.mjs";
+import Contributors from "./Contributors.mjs";
+import {dataLogLn} from "./Utility.mjs";
+
+// Change to true when debugging to avoid posting notifications to Slack.
+const DRY = false;
+
+const commitEndpointURL = "https://git.webkit.org/?p=WebKit-https.git;a=atom";
+const defaultInterval = 60 * 1000;
+
+async function sleep(milliseconds)
+{
+ return new Promise((resolve) => setTimeout(resolve, milliseconds));
+}
+
+export default class WKR {
+ constructor(webClient, auth, revision)
+ {
+ this._web = webClient;
+ this._auth = auth;
+ this._revision = revision;
+ }
+
+ async postToSlack(commit)
+ {
+ let data = {
+ text: commit.message(),
+ };
+ dataLogLn(data);
+ if (!DRY)
+ await axios.post(process.env.slackURL, JSON.stringify(data));
+ await sleep(500);
+ }
+
+ async action()
+ {
+ dataLogLn(`${Date.now()}: poll data`);
+ let contributors = await Contributors.create();
+ let parser = new RSS;
+ let response = await parser.parseURL(commitEndpointURL);
+ let commits = response.items.map((feedItem) => new Commit(feedItem, contributors));
+ commits.sort((a, b) => a.revision - b.revision);
+ if (this._revision) {
+ commits = commits.filter((commit) => commit.revision > this._revision);
+ for (let commit of commits)
+ await this.postToSlack(commit);
+ }
+
+ let latestCommit = commits[commits.length - 1];
+ if (latestCommit) {
+ this._revision = latestCommit.revision;
+ await storage.setItem("revision", this._revision);
+ }
+ }
+
+ static async create(webClient, auth)
+ {
+ let revision = await storage.getItem("revision");
+ dataLogLn(`Previous Revision: ${revision}`);
+ dataLogLn(`Endpoint: ${process.env.slackURL}`);
+ return new WKR(webClient, auth, revision);
+ }
+
+ static async main(webClient, auth)
+ {
+ let bot = await WKR.create(webClient, auth);
+ while (true) {
+ let start = Date.now();
+ try {
+ await bot.action();
+ } catch (error) {
+ console.error(error);
+ }
+ await sleep(Math.max(defaultInterval - (Date.now() - start), 0));
+ }
+ }
+}
Added: trunk/Tools/WebKitBot/src/WebKitBot.mjs (0 => 264210)
--- trunk/Tools/WebKitBot/src/WebKitBot.mjs (rev 0)
+++ trunk/Tools/WebKitBot/src/WebKitBot.mjs 2020-07-10 07:02:30 UTC (rev 264210)
@@ -0,0 +1,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: "[email protected]",
+ 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);
+ }
+ }
+ }
+}
Added: trunk/Tools/WebKitBot/src/index.mjs (0 => 264210)
--- trunk/Tools/WebKitBot/src/index.mjs (rev 0)
+++ trunk/Tools/WebKitBot/src/index.mjs 2020-07-10 07:02:30 UTC (rev 264210)
@@ -0,0 +1,46 @@
+/*
+ * 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 dotenv from "dotenv";
+import storage from "node-persist";
+import WKR from "./WKR.mjs";
+import WebKitBot from "./WebKitBot.mjs";
+import SlackWebAPI from "@slack/web-api";
+
+dotenv.config();
+
+async function main() {
+ await storage.init({
+ dir: "data",
+ });
+
+ let webClient = new SlackWebAPI.WebClient(process.env.SLACK_TOKEN);
+ let auth = await webClient.auth.test();
+
+ WKR.main(webClient, auth);
+ WebKitBot.main(webClient, auth);
+}
+
+main();
Added: trunk/Tools/WebKitBot/tests/Commit.test.mjs (0 => 264210)
--- trunk/Tools/WebKitBot/tests/Commit.test.mjs (rev 0)
+++ trunk/Tools/WebKitBot/tests/Commit.test.mjs 2020-07-10 07:02:30 UTC (rev 264210)
@@ -0,0 +1,85 @@
+/*
+ * 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 {readFile, readFileSync} from "fs";
+import path from "path";
+import util from "util";
+import Commit from "../src/Commit.mjs";
+import Contributors from "../src/Contributors.mjs";
+import {rootDirectoryOfWebKit} from "../src/Utility.mjs";
+
+const localContributorsPath = path.resolve(rootDirectoryOfWebKit(), "Tools", "Scripts", "webkitpy", "common", "config", "contributors.json");
+const contributors = new Contributors(JSON.parse(readFileSync(localContributorsPath)));
+const readFileAsync = util.promisify(readFile);
+
+test("Commit can parse one having radar and buzilla", async () => {
+ let feedItem = JSON.parse(await readFileAsync(path.resolve("tests", "resources", "HaveRadarAndBugzilla.json")));
+ let commit = new Commit(feedItem, contributors);
+ expect(commit.revision).toBe(263476);
+ expect(commit.patchBy).toBe(null);
+ expect(commit.revert).toBe(null);
+ expect(commit.bugzilla).toBe(212392);
+ expect(commit.radar).toBe(61799040);
+ expect(commit.email).toBe("[email protected]");
+ expect(commit.title).toBe("Use ObjectIdentifier<> instead of uint64_t for context IDs in VideoFullscreenManagerProxy");
+ expect(commit.author).toBe("David Kilzer (@ddkilzer)");
+ expect(commit.url).toBe("https://trac.webkit.org/r263476");
+ expect(commit.message()).toBe(`Use ObjectIdentifier<> instead of uint64_t for context IDs in VideoFullscreenManagerProxy
+https://trac.webkit.org/r263476 by David Kilzer (@ddkilzer)
+https://webkit.org/b/212392 <rdar://problem/61799040>`);
+});
+
+test("Commit can parse one not having radar and buzilla", async () => {
+ let feedItem = JSON.parse(await readFileAsync(path.resolve("tests", "resources", "NoRadarAndBugzilla.json")));
+ let commit = new Commit(feedItem, contributors);
+ expect(commit.revision).toBe(263465);
+ expect(commit.patchBy).toBe(null);
+ expect(commit.revert).toBe(null);
+ expect(commit.bugzilla).toBe(null);
+ expect(commit.radar).toBe(null);
+ expect(commit.email).toBe("[email protected]");
+ expect(commit.title).toBe("Unreviewed GTK gardening");
+ expect(commit.author).toBe("Philippe Normand (@philn)");
+ expect(commit.url).toBe("https://trac.webkit.org/r263465");
+ expect(commit.message()).toBe(`Unreviewed GTK gardening
+https://trac.webkit.org/r263465 by Philippe Normand (@philn)`);
+});
+
+test("Commit can parse one having buzilla", async () => {
+ let feedItem = JSON.parse(await readFileAsync(path.resolve("tests", "resources", "HavingBugzilla.json")));
+ let commit = new Commit(feedItem, contributors);
+ expect(commit.revision).toBe(263470);
+ expect(commit.patchBy).toBe(null);
+ expect(commit.revert).toBe(null);
+ expect(commit.bugzilla).toBe(213191);
+ expect(commit.radar).toBe(null);
+ expect(commit.email).toBe("[email protected]");
+ expect(commit.title).toBe("Add DFG/FTL fast path for GetPrototypeOf based on OverridesGetPrototype flag");
+ expect(commit.author).toBe("Alexey Shvayka (@shvaikalesh)");
+ expect(commit.url).toBe("https://trac.webkit.org/r263470");
+ expect(commit.message()).toBe(`Add DFG/FTL fast path for GetPrototypeOf based on OverridesGetPrototype flag
+https://trac.webkit.org/r263470 by Alexey Shvayka (@shvaikalesh)
+https://webkit.org/b/213191`);
+});
Added: trunk/Tools/WebKitBot/tests/WebKitBot.test.mjs (0 => 264210)
--- trunk/Tools/WebKitBot/tests/WebKitBot.test.mjs (rev 0)
+++ trunk/Tools/WebKitBot/tests/WebKitBot.test.mjs 2020-07-10 07:02:30 UTC (rev 264210)
@@ -0,0 +1,154 @@
+/*
+ * 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 {extractRevisionsAndReason, extractTextIfMentioned, extractCommandAndArgs} from "../src/WebKitBot.mjs";
+const WebKitBotID = 42;
+
+test("revert command basic", () => {
+ let message = `<@${WebKitBotID}> revert 263483 testing revert`;
+
+ let text = extractTextIfMentioned(message, WebKitBotID);
+ expect(text).toBe(" revert 263483 testing revert");
+
+ let {command, args} = extractCommandAndArgs(text);
+ expect(command).toBe("revert");
+ expect(args).toEqual(["263483", "testing", "revert"]);
+
+ let {revisions, reason} = extractRevisionsAndReason(args);
+ expect(reason).toBe("testing revert");
+ expect(revisions).toEqual(["263483"]);
+});
+
+test("revert command not mentioned", () => {
+ let message = "revert 263483 testing revert";
+
+ let text = extractTextIfMentioned(message, WebKitBotID);
+ expect(text).toBe(null);
+});
+
+test("remove quotes in revert reason", () => {
+ let message = `<@${WebKitBotID}> revert 263483 "testing revert"`;
+
+ let text = extractTextIfMentioned(message, WebKitBotID);
+ expect(text).toBe(" revert 263483 \"testing revert\"");
+
+ let {command, args} = extractCommandAndArgs(text);
+ expect(command).toBe("revert");
+ expect(args).toEqual(["263483", "\"testing", "revert\""]);
+
+ let {revisions, reason} = extractRevisionsAndReason(args);
+ expect(reason).toBe("testing revert");
+ expect(revisions).toEqual(["263483"]);
+});
+
+test("remove single smartquotes in revert reason", () => {
+ let message = `<@${WebKitBotID}> revert 263483 \u2018testing revert\u2019`;
+
+ let text = extractTextIfMentioned(message, WebKitBotID);
+ expect(text).toBe(" revert 263483 'testing revert'");
+
+ let {command, args} = extractCommandAndArgs(text);
+ expect(command).toBe("revert");
+ expect(args).toEqual(["263483", "'testing", "revert'"]);
+
+ let {revisions, reason} = extractRevisionsAndReason(args);
+ expect(reason).toBe("testing revert");
+ expect(revisions).toEqual(["263483"]);
+});
+
+test("remove double smartquotes in revert reason", () => {
+ let message = `<@${WebKitBotID}> revert 263483 \u201Ctesting revert\u201D`;
+
+ let text = extractTextIfMentioned(message, WebKitBotID);
+ expect(text).toBe(" revert 263483 \"testing revert\"");
+
+ let {command, args} = extractCommandAndArgs(text);
+ expect(command).toBe("revert");
+ expect(args).toEqual(["263483", "\"testing", "revert\""]);
+
+ let {revisions, reason} = extractRevisionsAndReason(args);
+ expect(reason).toBe("testing revert");
+ expect(revisions).toEqual(["263483"]);
+});
+
+test("remove line terminators", () => {
+ let message = `<@${WebKitBotID}> revert 263483 testing revert\nis this work?`;
+
+ let text = extractTextIfMentioned(message, WebKitBotID);
+ expect(text).toBe(" revert 263483 testing revert is this work?");
+
+ let {command, args} = extractCommandAndArgs(text);
+ expect(command).toBe("revert");
+ expect(args).toEqual(["263483", "testing", "revert", "is", "this", "work?"]);
+
+ let {revisions, reason} = extractRevisionsAndReason(args);
+ expect(reason).toBe("testing revert is this work?");
+ expect(revisions).toEqual(["263483"]);
+});
+
+test("multiple revisions", () => {
+ let message = `<@${WebKitBotID}> revert 263483,263484,r263485,r263486: testing revert`;
+
+ let text = extractTextIfMentioned(message, WebKitBotID);
+ expect(text).toBe(" revert 263483,263484,r263485,r263486: testing revert");
+
+ let {command, args} = extractCommandAndArgs(text);
+ expect(command).toBe("revert");
+ expect(args).toEqual(["263483,263484,r263485,r263486:", "testing", "revert"]);
+
+ let {revisions, reason} = extractRevisionsAndReason(args);
+ expect(reason).toBe("testing revert");
+ expect(revisions).toEqual(["263483", "263484", "263485", "263486"]);
+});
+
+test("multiple revisions with spaces", () => {
+ let message = `<@${WebKitBotID}> revert 263483, 263484, r263485, r263486: testing revert`;
+
+ let text = extractTextIfMentioned(message, WebKitBotID);
+ expect(text).toBe(" revert 263483, 263484, r263485, r263486: testing revert");
+
+ let {command, args} = extractCommandAndArgs(text);
+ expect(command).toBe("revert");
+ expect(args).toEqual(["263483,", "263484,", "r263485,", "r263486:", "testing", "revert"]);
+
+ let {revisions, reason} = extractRevisionsAndReason(args);
+ expect(reason).toBe("testing revert");
+ expect(revisions).toEqual(["263483", "263484", "263485", "263486"]);
+});
+
+test("mention in different place", () => {
+ let message = `revert 263483, 263484, r263485, r263486: testing revert <@${WebKitBotID}>`;
+
+ let text = extractTextIfMentioned(message, WebKitBotID);
+ expect(text).toBe("revert 263483, 263484, r263485, r263486: testing revert ");
+
+ let {command, args} = extractCommandAndArgs(text);
+ expect(command).toBe("revert");
+ expect(args).toEqual(["263483,", "263484,", "r263485,", "r263486:", "testing", "revert"]);
+
+ let {revisions, reason} = extractRevisionsAndReason(args);
+ expect(reason).toBe("testing revert");
+ expect(revisions).toEqual(["263483", "263484", "263485", "263486"]);
+});
Added: trunk/Tools/WebKitBot/tests/resources/.gitattributes (0 => 264210)
--- trunk/Tools/WebKitBot/tests/resources/.gitattributes (rev 0)
+++ trunk/Tools/WebKitBot/tests/resources/.gitattributes 2020-07-10 07:02:30 UTC (rev 264210)
@@ -0,0 +1,2 @@
+*.atom binary
+*.json binary