-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathgithub-bugzilla-content.js
More file actions
526 lines (447 loc) · 15.4 KB
/
github-bugzilla-content.js
File metadata and controls
526 lines (447 loc) · 15.4 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
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
"use strict";
/**
* Content script that runs in the context of github web pages and:
*
* 1. susses out PR page and adds "attach to bug" links
* 2. linkifies bugzilla bug numbers
*/
// Regexp to match against PR title
const BUG_RE = /\b(ticket|bug|tracker item|issue)(?:s?:?\s*|-)([\d ,\+&#and]+)\b/ig;
// Base url for attaching a github pr to a bug
const ATTACH_BASE_URL = "https://bugzilla.mozilla.org/attachment.cgi?action=enter&bugid=";
// Url for bug lists
const LIST_BASE_URL = "https://bugzilla.mozilla.org/buglist.cgi?bug_id=";
const BUG_BASE_URL = "https://bugzilla.mozilla.org/show_bug.cgi?id=";
const ATTACH_CONTAINER_ID = "robBugsonAttachLinks";
const MERGE_CONTAINER_ID = "robBugsonMergeLinks";
const LIST_CONTAINER_ID = "robBugsonListLinks";
const PR_STATE_CLOSED = "Closed";
const PR_STATE_MERGED = "Merged";
const PR_STATE_OPEN = "Open";
const PR_STATE_UNKNOWN = "Unknown";
const TAB_CONVERSATION = "Conversation";
const TAB_OTHER = "Other";
/**
* Retrieve the PR number from the pull request page.
*/
function getPRNum() {
// Get the PR number which is like "#4099"
let elem = document.querySelectorAll('[data-component="PH_Title"] span')[1];
if (!elem) {
return;
}
// Peel off the "#" and return
return elem.textContent.substring(1);
}
/**
* Retrieve the PR title from the pull request page.
*/
function getPRTitle() {
let elem = document.querySelector('[data-component="PH_Title"] span.markdown-title');
if (!elem) {
return;
}
return elem.textContent.trim();
}
/**
* Retrieve the PR url.
*
* Make sure to drop # and anything after it because it makes Bugzilla sad.
*/
function getPRUrl() {
let url = document.URL;
return url.replace(/#.*/, "");
}
/**
* Retrieve the repo organization and repo name.
*/
function getRepoInfo() {
// Grab the first two parts of the url path
let url = new URL(document.URL);
let pathname = url.pathname;
let pathParts = pathname.split("/");
return {
repoOrg: pathParts[1],
repoName: pathParts[2]
};
}
/**
* Retrieve PR state.
*/
function getPRState() {
let state = document.querySelector('[data-status]');
if (state === null) {
return PR_STATE_UNKNOWN;
}
switch (state.getAttribute('data-status')) {
case 'pullMerged': return PR_STATE_MERGED;
case 'pullOpened': return PR_STATE_OPEN;
case 'pullClosed': return PR_STATE_CLOSED;
default: return PR_STATE_UNKNOWN;
}
}
/**
* For PRs, get the selected tab.
*/
function getSelectedTab() {
let tab = document.querySelector('[role="tab"][aria-selected="true"]');
if (!tab) {
return TAB_OTHER;
}
let tabText = tab.textContent.trim();
if (tabText.startsWith("Conversation")) {
return TAB_CONVERSATION;
}
return TAB_OTHER;
}
/**
* Get list of bug ids from PR title.
*/
function getBugIdsFromPRTitle(text) {
let bugSet = new Set();
const matches = text.matchAll(BUG_RE);
for (const match of matches) {
match[2].split(/\D+/).filter((bugId) => !!bugId).forEach((bugId) => bugSet.add(bugId));
}
return Array.from(bugSet);
}
/**
* Get list of bug ids from commits.
*/
function getBugIdsFromCommits() {
let bugIds = [];
let elements = document.querySelectorAll("a.message, div.commit-desc pre");
Array.prototype.forEach.call(elements, (el) => {
bugIds = bugIds.concat(getBugIds(el.textContent));
});
return bugIds;
}
/**
* Return array of "bugzilla links"--one for each bug.
*/
function getBugLinks(bugIds) {
return bugIds.map((k) => {
let bugLink = document.createElement("a");
bugLink.href = BUG_BASE_URL + k;
bugLink.target = "_blank";
bugLink.className = "bugzilla_link";
bugLink.appendChild(document.createTextNode(k));
return bugLink;
});
}
/**
* Return array of "attach links"--one for each bug.
*
* Attach links are set up with an event listener to sends the data to the
* background script for opening and manipulating the new tab.
*/
function getAttachLinks(bugIds, repoInfo, prUrl, prNum, prTitle) {
return bugIds.map((bugId) => {
let link = document.createElement("a");
link.href = "#";
link.className = "bugzilla_link";
link.addEventListener("click", (event) => {
// Send a message to the background script. That handles creating a
// tab, opening the attach page, and filling in the form.
let url = ATTACH_BASE_URL + bugId;
var sending = browser.runtime.sendMessage({
eventName: "attachLink",
attachUrl: url,
repoOrg: repoInfo.repoOrg,
repoName: repoInfo.repoName,
prUrl: prUrl,
prNum: prNum,
prTitle: prTitle
});
sending.then(
(message) => console.info("rob-bugson: attachlink success: " + message),
(error) => console.info("rob-bugson: attachlink error: " + error)
);
event.preventDefault();
});
link.appendChild(document.createTextNode(bugId));
return link;
});
}
/**
* Returns true if the URL is a github pull request page.
*
* @param {URL} url
* @returns {bool}
*/
function isPullRequest(url) {
return (
url.origin == "https://github.com"
&& url.pathname.split("/")[3] == "pull"
);
}
/**
* Returns true if the URL is a github compare page.
*
* @param {URL} url
* @returns {bool}
*/
function isComparePage(url) {
return (
url.origin == "https://github.com"
&& url.pathname.split("/")[3] == "compare"
);
}
/**
* Checks if there's already a container and if not, creates one with attach
* links in it.
*/
function addAttachLinksToPage(pageKind, repoInfo, prNum, prTitle, prUrl, bugIds) {
// If this is not a pull request page, then return.
if (pageKind != "pr") {
return;
}
// If there's already a link container, then return.
let linkContainer = document.getElementById(ATTACH_CONTAINER_ID);
if (linkContainer == null) {
// If there"s no link container, then we create a new one
linkContainer = document.createElement("p");
linkContainer.id = ATTACH_CONTAINER_ID;
linkContainer.style.cssText = "font-size: 16px;";
}
// Remove everything from the link container so we don't end up with
// duplicates
while (linkContainer.firstChild) {
linkContainer.removeChild(linkContainer.firstChild);
}
// If there are no bug ids, just return
if (bugIds.length == 0) {
return;
}
linkContainer.appendChild(document.createTextNode("Attach this PR to bug: "));
let separator = document.createTextNode(", ");
getAttachLinks(bugIds, repoInfo, prUrl, prNum, prTitle).forEach((bugLink, i) => {
if (i > 0) {
linkContainer.appendChild(separator.cloneNode(false));
}
linkContainer.appendChild(bugLink);
});
let headerShow = document.querySelector('[data-component="PH_Navigation"]').parentElement;
headerShow.insertAdjacentElement('beforebegin',linkContainer);
}
function createBugsList(bugIds){
let bugsListContainer = document.getElementById(LIST_CONTAINER_ID);
if (bugsListContainer == null) {
bugsListContainer = document.createElement("p");
bugsListContainer.id = LIST_CONTAINER_ID;
bugsListContainer.style.cssText = "font-size: 16px;";
}
// Remove everything from container so we don't have duplicates
while (bugsListContainer.firstChild) {
bugsListContainer.removeChild(bugsListContainer.firstChild);
}
if (bugIds.length == 0) {
return bugsListContainer;
}
bugsListContainer.appendChild(document.createTextNode("View bugs in commits ("));
let openAll = document.createElement("a");
openAll.href = LIST_BASE_URL + bugIds.join(",");
openAll.id = "open_all_bugzilla_links";
openAll.target = "_blank";
openAll.appendChild(document.createTextNode("open all"));
bugsListContainer.appendChild(openAll);
bugsListContainer.appendChild(document.createTextNode("): "));
let separator = document.createTextNode(", ");
getBugLinks(bugIds).forEach((bugLink, i) => {
if (i > 0) {
bugsListContainer.appendChild(separator.cloneNode(false));
}
bugsListContainer.appendChild(bugLink);
});
return bugsListContainer;
}
function addBugListToPage(pageKind, bugIds) {
let parentElement;
// If this is a compare page
if (pageKind == "compare") {
let insertBeforeEl = document.getElementById('commits_bucket');
parentElement = insertBeforeEl.parentElement;
parentElement.insertBefore(createBugsList(bugIds), insertBeforeEl);
} else if (pageKind == "pr") {
parentElement = document.querySelector('[data-component="PH_Navigation"]').parentElement;
parentElement.insertAdjacentElement('beforebegin', createBugsList(bugIds));
}
}
/**
* Checks if this PR has been merged and if so and there are no merge
* links, yet, creates them.
*/
function addMergeLinks(pageKind, repoInfo, prNum, prTitle, prUrl, prState, bugIds) {
// If this is not a pull request page, then return.
if (pageKind != "pr") {
return;
}
let linkContainer = document.getElementById(MERGE_CONTAINER_ID);
if (linkContainer == null) {
// If there"s no link container, then we create a new one
linkContainer = document.createElement("p");
linkContainer.id = MERGE_CONTAINER_ID;
linkContainer.style.cssText = "font-size: 16px;";
}
// Removes everything from the link container so we don't end up
// with duplicates
while (linkContainer.firstChild) {
linkContainer.removeChild(linkContainer.firstChild);
}
// If there are no bugs or this isn't merged, return
if (bugIds.length == 0 || prState != PR_STATE_MERGED) {
return;
}
linkContainer.appendChild(document.createTextNode("Add merge comment to bug: "));
// Find the merge commit event and the bits we want
let elements = document.querySelectorAll("div.TimelineItem-body");
let author = "";
let commitSha = "";
let commitUrl = "";
// This goes through all the events to figure out the merge commit
Array.prototype.forEach.call(elements, (el) => {
if (
el.textContent.match(/merged commit/) ||
// For PRs merged via a merge queue, we need two different events,
// since there isn't a single event that has both the GitHub username
// and the commit hash.
el.textContent.match(/added this pull request to the merge queue/) ||
el.textContent.match(/via the queue/)
) {
if (!author) {
author = el.querySelector("a.author").textContent.trim();
}
// NOTE(willkg): the a tag we want is the one that has no id or class--that"s
// really irritating
let linkElems = el.querySelectorAll("a");
Array.prototype.forEach.call(linkElems, (elem) => {
let href = elem.getAttribute("href")
if (href && href.match(/\/commit\//)) {
commitUrl = "https://github.com" + href;
commitSha = elem.textContent.trim();
}
});
}
});
let headerShow = document.querySelector('[data-component="PH_Navigation"]').parentElement;
let separator = document.createTextNode(", ");
if (author && prNum && commitSha && commitUrl) {
let bugLinks = bugIds.map((bugId) => {
let link = document.createElement("a");
link.href = "#";
link.className = "merge_link";
link.addEventListener("click", (event) => {
// Send a message to the background script. That handles creating a
// tab, opening the bug page, and adding a comment.
let url = BUG_BASE_URL + bugId;
browser.runtime.sendMessage({
"eventName": "mergeComment",
"bugUrl": url,
"author": author,
"repoOrg": repoInfo.repoOrg,
"repoName": repoInfo.repoName,
"prNum": prNum,
"prUrl": prUrl,
"prTitle": prTitle,
"authorUrl": "https://github.com/" + author,
"commitSha": commitSha,
"commitUrl": commitUrl
});
event.preventDefault();
});
link.appendChild(document.createTextNode(bugId));
return link;
});
bugLinks.forEach((bugLink, i) => {
if (i > 0) {
linkContainer.appendChild(separator.cloneNode(false));
}
linkContainer.appendChild(bugLink);
});
}
headerShow.insertAdjacentElement('beforebegin',linkContainer);
}
function runEverything() {
let prNum = getPRNum();
if (!prNum) {
return;
}
let prTitle = getPRTitle();
let prUrl = getPRUrl();
let prState = getPRState();
let repoInfo = getRepoInfo();
let selectedTab = getSelectedTab();
let bugIds;
let pageKind;
let url = new URL(window.location.href);
if (isComparePage(url)) {
pageKind = "compare";
bugIds = getBugIdsFromCommits();
} else if (isPullRequest(url)) {
pageKind = "pr";
bugIds = getBugIdsFromPRTitle(prTitle);
} else {
pageKind = "";
bugIds = [];
}
// Show the links if we're on a Compare page or a PR page and the
// conversation tab
if (pageKind == "compare" || (pageKind == "pr" && selectedTab == TAB_CONVERSATION)) {
addBugListToPage(pageKind, bugIds);
addAttachLinksToPage(pageKind, repoInfo, prNum, prTitle, prUrl, bugIds);
addMergeLinks(pageKind, repoInfo, prNum, prTitle, prUrl, prState, bugIds);
}
}
function debounce(func, func_name, wait) {
var debouncing = false;
function debouncedFunc() {
console.info("rob-bugson: debouncing state: " + debouncing);
if (debouncing) {
return;
}
debouncing = true;
var later = function() {
console.info("rob-bugson: running function: " + func_name + ": start");
func();
console.info("rob-bugson: running function: " + func_name + ": end");
}
setTimeout(() => later(), wait);
setTimeout(() => debouncing = false, wait);
};
return debouncedFunc;
};
let debounceRunEverything = debounce(runEverything, "runEverything", 200);
console.info("rob-bugson: init");
debounceRunEverything();
// Set up an observer to handle page changes
let config = {
childList: true,
attributes: false,
characterData: false,
subtree: true,
};
let pjaxContainer = document.getElementById("js-repo-pjax-container");
if (pjaxContainer) {
const pjaxContainerObserver = new window.MutationObserver((mutations, observer) => {
debounceRunEverything();
});
pjaxContainerObserver.observe(pjaxContainer, config);
console.info("rob-bugson: set up observer");
}
module.exports = {
addMergeLinks,
BUG_BASE_URL,
getAttachLinks,
getBugIdsFromPRTitle,
getPRNum,
getPRState,
getPRTitle,
getSelectedTab,
MERGE_CONTAINER_ID,
PR_STATE_CLOSED,
PR_STATE_MERGED,
PR_STATE_OPEN,
PR_STATE_UNKNOWN,
TAB_CONVERSATION,
TAB_OTHER,
}