-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathcontent.js
More file actions
1054 lines (913 loc) · 31.6 KB
/
content.js
File metadata and controls
1054 lines (913 loc) · 31.6 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
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
function colorizeAnnotations() {
for (const element of document.querySelectorAll(
'div[class*="Annotation-module__annotationMessage--"]',
)) {
const div = document.createElement("div");
div.classList.add("highlight", "highlight-source-diff");
const lines = element.textContent
.split("\n")
.filter((x) => x !== "--- " && x !== "+++ " && x[0] !== "@");
div.style.whiteSpace = "pre";
div.style.fontFamily = "monospace";
element.replaceWith(div);
for (const line of lines) {
const span = document.createElement("span");
span.textContent = line + "\n";
if (line[0] === "+") {
span.classList.add("pl-mi1");
} else if (line[0] === "-") {
span.classList.add("pl-md");
} else if (line[0] === "@") {
span.classList.add("pl-mdr");
}
div.appendChild(span);
}
}
}
function colorizePullRequests() {
const me = document.querySelector('meta[name="user-login"]').content;
const isMultiRepoView =
document
.querySelector('meta[name="selected-link"]')
.getAttribute("value") === "/pulls";
const colorMode = document.querySelector("html").dataset.colorMode;
let darkMode = false;
if (colorMode === "auto") {
if (
window.matchMedia &&
window.matchMedia("(prefers-color-scheme: dark)").matches
) {
darkMode = true;
}
} else if (colorMode === "dark") {
darkMode = true;
}
[].forEach.call(document.querySelectorAll(".js-issue-row"), (row) => {
const prIcon = row.querySelector("svg.octicon-git-pull-request");
const draftPrIcon = row.querySelector("svg.octicon-git-pull-request-draft");
const isPR = !!prIcon || !!draftPrIcon;
const isDraftPR = !!draftPrIcon;
row.classList.add("github-pull-request-colorizer--row");
if (darkMode) {
row.classList.add("github-pull-request-colorizer--dark-mode");
}
if (isMultiRepoView) {
row.classList.add("github-pull-request-colorizer--multi-repo");
}
const hasDeferredContent =
row.querySelector("batch-deferred-content") !== null;
const approved =
(row.querySelector("a.Link--muted.tooltipped") || {}).innerText ===
"Approved";
const changesRequested =
(row.querySelector("a.Link--muted.tooltipped") || {}).innerText ===
"Changes requested";
const reviewRequired = !(approved || changesRequested);
const assignees = Array.from(row.querySelectorAll(".from-avatar")).map(
// Copilot does not have a username
(assignee) => assignee.alt?.slice(1),
).filter(it => it);
const author = (row.querySelector(".opened-by .Link--muted") || {})
.innerText;
const title = (row.querySelector(".Link--primary.h4") || {}).innerText;
const failsTravis = !!row.querySelector(
".commit-build-statuses .color-fg-danger",
);
const passesTravis = !!row.querySelector(
".commit-build-statuses .color-fg-success",
);
const skipLabel = row.querySelector(
'a.IssueLabel[data-name="Skip colorization"]',
);
const repositoryElement = row.querySelector(
"[data-hovercard-type=repository]",
);
const informationLineElement = row.querySelector("span.opened-by");
const titleElement = row.querySelector(".Link--primary.h4");
const PRIconElement = row.firstElementChild.firstElementChild;
const buildStatusElement = row.querySelector(".commit-build-statuses");
if (repositoryElement) {
const name = repositoryElement.innerText;
repositoryElement.innerText = name.replace(/^HyreAS\//, "");
repositoryElement.classList.add(
"github-pull-request-colorizer--repository",
);
}
if (informationLineElement) {
informationLineElement.parentElement.classList.add(
"github-pull-request-colorizer--information-line",
);
}
if (isMultiRepoView && PRIconElement) {
PRIconElement.style.display = "none";
}
if (titleElement) {
titleElement.classList.add("github-pull-request-colorizer--title");
}
if (buildStatusElement) {
buildStatusElement.classList.add(
"github-pull-request-colorizer--build-status",
);
}
let highlight = false;
if (failsTravis && author === me) {
highlight = true;
}
if (changesRequested && author === me) {
highlight = true;
}
if (
!failsTravis &&
isPR &&
reviewRequired &&
author !== me &&
(assignees.includes(me) || assignees.length === 0)
) {
highlight = true;
}
if (approved && passesTravis) {
highlight = true;
}
if (title.slice(0, 3) === "WIP") {
highlight = true;
}
if (title.slice(0, 5) === "[WIP]") {
highlight = true;
}
if (title.slice(0, 3) === "WIP" && author != me) {
highlight = false;
}
if (title.slice(0, 5) === "[WIP]" && author != me) {
highlight = false;
}
if (skipLabel) {
highlight = false;
}
if (hasDeferredContent) {
highlight = false;
}
if (highlight) {
row.classList.add("github-pull-request-colorizer--highlight");
}
if (isDraftPR) {
row.classList.add("github-pull-request-colorizer--draft-pr");
}
const updatedClock = row.querySelector(".octicon-clock");
if (updatedClock) {
updatedClock.style.width = "12px";
updatedClock.style.paddingBottom = "2px";
}
});
const hasDeferredContent =
document.querySelector("batch-deferred-content") !== null;
if (hasDeferredContent) {
setTimeout(colorizePullRequests, 100);
}
}
function checkForUpdates() {
function setUpdateNotification(text) {
const container = document.querySelector(
".Box .Box-header .table-list-header-toggle",
);
const notificationClassName = "github-pull-request-colorizer--notification";
let notificationElement = container.querySelector(
"." + notificationClassName,
);
if (notificationElement) {
notificationElement.textContent = text;
return;
}
notificationElement = document.createElement("div");
notificationElement.textContent = text;
notificationElement.classList.add(notificationClassName);
container.appendChild(notificationElement);
}
function onError() {
setUpdateNotification(
"Checking for github-pull-request-colorizer updates doesn't work in this browser, it seems :/ Consider investigating and making a pull request!",
);
}
fetch(
"https://api.github.com/repos/sigvef/github-pull-request-colorizer/contents/manifest.json",
)
.then((response) => {
if (response.status !== 403) {
return response.json();
}
throw new Error("ratelimited");
})
.then((data) => {
try {
const localManifest = chrome.runtime.getManifest();
const masterManifest = JSON.parse(atob(data.content));
if (masterManifest.version !== localManifest.version) {
setUpdateNotification(
"Update for GitHub Pull Request Colorizer is available!",
);
}
} catch {
onError();
}
})
.catch((e) => {
if (e.message !== "ratelimited") {
onError();
}
});
}
checkForUpdates();
try {
colorizePullRequests();
} catch (e) {
console.log(e);
}
try {
colorizeAnnotations();
} catch (e) {}
document.addEventListener("DOMContentLoaded", colorizePullRequests);
document.addEventListener("DOMContentLoaded", colorizeAnnotations);
setInterval(colorizeAnnotations, 500);
let currentHref = location.href;
setInterval(() => {
if (currentHref !== location.href) {
currentHref = location.href;
try {
colorizePullRequests();
} catch (e) {
console.log(e);
}
try {
autoFetchCheckSummary();
} catch (e) {
console.log(e);
}
try {
handleStackedPR();
} catch (e) {
console.log(e);
}
}
}, 500);
// GitHub Check Fetcher
console.log("GitHub Pull Request Colorizer: Check fetcher loaded");
function extractRepoInfoFromUrl() {
const match = location.pathname.match(/^\/([^/]+)\/([^/]+)\/pull\/(\d+)/);
if (!match) {
return null;
}
return {
owner: match[1],
repo: match[2],
pullNumber: match[3],
};
}
async function fetchStatusChecks(owner, repo, pullNumber) {
const url = `https://github.com/${owner}/${repo}/pull/${pullNumber}/page_data/status_checks`;
try {
const response = await fetch(url, {
headers: {
Accept: "application/json",
"X-Requested-With": "XMLHttpRequest",
},
});
if (!response.ok) {
throw new Error(`GitHub internal API error: ${response.status}`);
}
return await response.json();
} catch (error) {
console.error("Error fetching status checks:", error);
return null;
}
}
async function fetchCheckDetails(targetUrl) {
const fullUrl = `https://github.com${targetUrl}`;
try {
const response = await fetch(fullUrl);
if (!response.ok) {
throw new Error(`Failed to fetch check page: ${response.status}`);
}
const html = await response.text();
// Parse the HTML
const parser = new DOMParser();
const doc = parser.parseFromString(html, "text/html");
let summaryHtml = null;
let summaryText = null;
// Look for the check run summary section
const summarySection = doc.querySelector(
'[aria-label="Check run summary"]',
);
if (summarySection) {
const markdownBody = summarySection.querySelector(".markdown-body");
if (markdownBody) {
summaryHtml = markdownBody.cloneNode(true); // Clone the HTML element with formatting
summaryText = markdownBody.textContent.trim();
}
}
// Also try to find the check annotation messages
const annotations = [];
doc.querySelectorAll('[data-testid="check-annotation"]').forEach((ann) => {
annotations.push(ann.textContent.trim());
});
return {
summaryHtml, // The actual HTML element with formatting
summaryText, // Plain text version
annotations,
fullHtml: html, // Include full HTML for debugging
};
} catch (error) {
console.error("Error fetching check details:", error);
return null;
}
}
function getCommitShaFromPage() {
// Try multiple selectors to find the commit SHA
const selectors = [
'a[data-hovercard-type="commit"]',
'.commit-ref.current-branch a[href*="/commit/"]',
'.head-ref a[href*="/commit/"]',
'span.commit-ref a[href*="/commits/"]',
'[data-url*="/commit/"]',
];
for (const selector of selectors) {
const element = document.querySelector(selector);
if (element && element.href) {
const match = element.href.match(/\/commits?\/([a-f0-9]{40})/);
if (match) {
return match[1];
}
}
}
// Try to find it in the timeline
const timelineCommit = document.querySelector(".TimelineItem .commit-id");
if (timelineCommit && timelineCommit.textContent) {
const sha = timelineCommit.textContent.trim();
if (sha.length >= 7) {
return sha;
}
}
return null;
}
async function fetchCheckSummary(checkName) {
const repoInfo = extractRepoInfoFromUrl();
if (!repoInfo) {
console.log("Not on a PR page");
return;
}
console.log(
`Fetching status checks for ${repoInfo.owner}/${repoInfo.repo} #${repoInfo.pullNumber}`,
);
const data = await fetchStatusChecks(
repoInfo.owner,
repoInfo.repo,
repoInfo.pullNumber,
);
if (!data) {
console.log("Failed to fetch status checks");
return;
}
console.log("Status checks data:", data);
// GitHub's internal API returns {statusChecks: [...], statusRollup: {...}, aliveChannels: {...}}
const checks = data.statusChecks || [];
if (!checks.length) {
console.log("No status checks found");
return;
}
console.log(`Found ${checks.length} checks`);
if (checkName) {
// Try to find by displayName or description (case-insensitive)
const check = checks.find(
(run) =>
run.displayName?.toLowerCase().includes(checkName.toLowerCase()) ||
run.description?.toLowerCase().includes(checkName.toLowerCase()),
);
if (check) {
console.log(`\n=== Check: ${check.displayName} ===`);
console.log(`Description: ${check.description}`);
console.log(`State: ${check.state}`);
console.log(`Duration: ${check.durationInSeconds}s`);
console.log(`Changed at: ${check.stateChangedAt}`);
console.log(`Is Required: ${check.isRequired}`);
console.log(`Additional Context: ${check.additionalContext || "None"}`);
console.log(`Target URL: ${check.targetUrl}`);
if (check.copilotCheckRunFailureContext) {
console.log(
"\nCopilot Failure Context:",
check.copilotCheckRunFailureContext,
);
}
console.log("\nFull check data:", check);
// Fetch the detailed check page
if (check.targetUrl) {
console.log("\nFetching detailed check output...");
const details = await fetchCheckDetails(check.targetUrl);
if (details) {
if (details.summaryHtml) {
console.log("\n=== Check Output/Summary ===");
console.log(details.summaryText);
// Inject the summary into the PR timeline
injectCheckSummaryIntoTimeline(
check.displayName,
details.summaryHtml,
);
console.log("✓ Summary injected into PR timeline");
} else {
console.log("\nNo summary found in standard locations.");
console.log("Full HTML length:", details.fullHtml.length);
console.log(
"You can inspect the HTML to find where the summary is located.",
);
// Log a snippet of the HTML for debugging
const snippet = details.fullHtml.substring(0, 1000);
console.log("HTML snippet (first 1000 chars):", snippet);
}
if (details.annotations && details.annotations.length > 0) {
console.log("\n=== Annotations ===");
details.annotations.forEach((ann, i) => {
console.log(`${i + 1}. ${ann}`);
});
}
}
}
return check; // Return the check for the button handler
} else {
console.log(`Check matching "${checkName}" not found`);
console.log("\nAvailable checks:");
checks.forEach((run, i) => {
console.log(
`${i + 1}. ${run.displayName} - ${run.state} (${run.description})`,
);
});
}
} else {
// List all checks
console.log("\nAvailable checks:");
checks.forEach((run, i) => {
const duration = run.durationInSeconds
? ` (${run.durationInSeconds}s)`
: "";
console.log(`${i + 1}. ${run.displayName} - ${run.state}${duration}`);
console.log(` ${run.description}`);
});
// Show rollup summary
if (data.statusRollup) {
console.log("\nStatus Rollup:");
console.log(`Combined State: ${data.statusRollup.combinedState}`);
if (data.statusRollup.summary) {
data.statusRollup.summary.forEach((s) => {
console.log(` ${s.state}: ${s.count}`);
});
}
}
}
}
function showGlobalSpinner() {
const spinnerId = "check-summaries-global-spinner";
// Don't create if already exists
if (document.getElementById(spinnerId)) {
return;
}
// Find the merge box - it's typically at the end of the timeline
const mergeBox = document.querySelector(".merge-pr") || document.querySelector("[data-testid='mergebox-partial']");
if (!mergeBox) {
console.log("Could not find merge box to inject spinner");
return;
}
// Create a simple centered spinner container
const container = document.createElement("div");
container.id = spinnerId;
container.style.padding = "16px";
container.style.textAlign = "center";
container.style.marginBottom = "16px";
container.innerHTML = `
<svg style="box-sizing: content-box; color: var(--color-icon-primary);" width="32" height="32" viewBox="0 0 16 16" fill="none">
<circle cx="8" cy="8" r="7" stroke="currentColor" stroke-opacity="0.25" stroke-width="2" vector-effect="non-scaling-stroke"></circle>
<path d="M15 8a7.002 7.002 0 00-7-7" stroke="currentColor" stroke-width="2" stroke-linecap="round" vector-effect="non-scaling-stroke">
<animateTransform attributeName="transform" type="rotate" from="0 8 8" to="360 8 8" dur="1s" repeatCount="indefinite"/>
</path>
</svg>
`;
// Insert before the merge box
mergeBox.parentNode.insertBefore(container, mergeBox);
// Remove border-top from discussion-timeline-actions to make it flow better
const timelineActions = document.querySelector(
".discussion-timeline-actions",
);
if (timelineActions) {
timelineActions.style.borderTop = "none";
}
}
function hideGlobalSpinner() {
const spinner = document.getElementById("check-summaries-global-spinner");
if (spinner) {
spinner.remove();
}
}
function injectCheckSummaryIntoTimeline(checkName, summaryHtml, checkData) {
// Create a unique ID for this check summary
const safeName = checkName.replace(/[^a-zA-Z0-9]/g, "-");
const containerId = `check-summary-${safeName}`;
// Remove any existing summary for this check
const existingSummary = document.getElementById(containerId);
if (existingSummary) {
existingSummary.remove();
}
// Find where to insert - before the global spinner if it exists, otherwise before merge box
const spinner = document.getElementById("check-summaries-global-spinner");
const mergeBox = document.querySelector(".merge-pr") || document.querySelector("[data-testid='mergebox-partial']");
let insertBefore;
if (spinner) {
insertBefore = spinner;
} else if (mergeBox) {
insertBefore = mergeBox;
} else {
console.log("Could not find merge box to inject summary");
return;
}
// Create a simple container for the summary (no timeline graphics)
const container = document.createElement("div");
container.id = containerId;
container.style.marginBottom = "16px";
container.style.marginLeft = "56px";
// Create a box similar to GitHub's comment boxes
const box = document.createElement("div");
box.className = "Box";
box.style.maxHeight = "448px";
box.style.display = "flex";
box.style.flexDirection = "column";
// Header with avatar
const header = document.createElement("div");
header.className = "Box-header";
header.style.padding = "8px 16px";
header.style.fontWeight = "600";
header.style.flexShrink = "0";
header.style.display = "flex";
header.style.alignItems = "center";
header.style.gap = "8px";
// Add avatar if available
if (checkData && checkData.avatarUrl) {
const avatar = document.createElement("img");
avatar.src = checkData.avatarUrl;
avatar.alt = checkName;
avatar.width = 20;
avatar.height = 20;
avatar.style.borderRadius = "3px";
header.appendChild(avatar);
}
// Add check name
const nameSpan = document.createElement("span");
nameSpan.textContent = checkName;
nameSpan.style.flex = "1";
header.appendChild(nameSpan);
// Add status indicator if available
if (checkData && checkData.state) {
const statusBadge = document.createElement("span");
statusBadge.style.fontSize = "12px";
statusBadge.style.padding = "2px 8px";
statusBadge.style.borderRadius = "12px";
statusBadge.style.fontWeight = "500";
// Style based on state
if (checkData.state === "FAILURE") {
statusBadge.style.background = "#d1242f";
statusBadge.style.color = "white";
statusBadge.textContent = "Failed";
} else if (checkData.state === "SUCCESS") {
statusBadge.style.background = "#1a7f37";
statusBadge.style.color = "white";
statusBadge.textContent = "Passed";
} else if (checkData.state === "PENDING") {
statusBadge.style.background = "#bf8700";
statusBadge.style.color = "white";
statusBadge.textContent = "Pending";
} else {
statusBadge.style.background = "#6e7781";
statusBadge.style.color = "white";
statusBadge.textContent = checkData.state;
}
header.appendChild(statusBadge);
}
// Body with the summary
const summaryBody = document.createElement("div");
summaryBody.className = "Box-body";
summaryBody.style.padding = "16px";
summaryBody.style.overflowY = "auto";
summaryBody.style.overflowX = "hidden";
summaryBody.style.flex = "1";
summaryBody.style.minHeight = "0";
summaryBody.appendChild(summaryHtml);
box.appendChild(header);
box.appendChild(summaryBody);
container.appendChild(box);
// Insert before the spinner or merge box
insertBefore.parentNode.insertBefore(container, insertBefore);
// Remove border-top from discussion-timeline-actions to make it flow better
const timelineActions = document.querySelector(
".discussion-timeline-actions",
);
if (timelineActions) {
timelineActions.style.borderTop = "none";
}
}
async function waitForChecksToLoad(maxWaitMs = 10000) {
const startTime = Date.now();
while (Date.now() - startTime < maxWaitMs) {
// Look for the Checks section
const checksSection = document.querySelector(
'section[aria-label="Checks"]',
);
if (checksSection) {
console.log("Checks section found in DOM");
return true;
}
// Wait 100ms before checking again (faster polling)
await new Promise((resolve) => setTimeout(resolve, 100));
}
console.log("Timeout waiting for checks to load");
return false;
}
async function fetchAllInterestingCheckSummaries(priorityCheckNames = []) {
const repoInfo = extractRepoInfoFromUrl();
if (!repoInfo) {
console.log("Not on a PR page");
return;
}
console.log(
`Fetching status checks for ${repoInfo.owner}/${repoInfo.repo} #${repoInfo.pullNumber}`,
);
const data = await fetchStatusChecks(
repoInfo.owner,
repoInfo.repo,
repoInfo.pullNumber,
);
if (!data) {
console.log("Failed to fetch status checks");
return;
}
const checks = data.statusChecks || [];
if (!checks.length) {
console.log("No status checks found");
return;
}
console.log(`Found ${checks.length} checks`);
const checksToFetch = [];
const addedCheckNames = new Set();
// First, add all FAILURE checks
for (const check of checks) {
if (
check.state === "FAILURE" &&
check.targetUrl &&
!addedCheckNames.has(check.displayName)
) {
console.log(`Adding failed check: ${check.displayName}`);
checksToFetch.push(check);
addedCheckNames.add(check.displayName);
}
}
// Then, add priority checks if they're not SUCCESS (and not already added)
for (const checkName of priorityCheckNames) {
if (addedCheckNames.has(checkName)) {
continue; // Already added as a failed check
}
const check = checks.find((run) => run.displayName === checkName);
if (check && check.targetUrl) {
if (check.state === "SUCCESS") {
console.log(
`Priority check "${check.displayName}" has SUCCESS status, skipping`,
);
} else {
console.log(
`Adding priority check: ${check.displayName} (${check.state})`,
);
checksToFetch.push(check);
addedCheckNames.add(check.displayName);
}
} else {
console.log(`Priority check "${checkName}" not found`);
}
}
if (checksToFetch.length === 0) {
console.log("No checks to fetch");
return;
}
// Show global spinner
showGlobalSpinner();
// Fetch the actual details for each check
for (const check of checksToFetch) {
console.log(`\n=== Fetching details: ${check.displayName} ===`);
const details = await fetchCheckDetails(check.targetUrl);
if (details && details.summaryHtml) {
injectCheckSummaryIntoTimeline(
check.displayName,
details.summaryHtml,
check,
);
console.log(`✓ Summary injected for ${check.displayName}`);
}
}
// Hide global spinner when all checks are loaded
hideGlobalSpinner();
}
async function autoFetchCheckSummary() {
const repoInfo = extractRepoInfoFromUrl();
if (!repoInfo) {
return; // Not on a PR page
}
// Check if we've already fetched for this page (look for any check summary)
const summaryExists = document.querySelector('[id^="check-summary-"]');
if (summaryExists) {
return; // Already fetched
}
console.log("Waiting for checks to load...");
const checksLoaded = await waitForChecksToLoad();
if (!checksLoaded) {
console.log("Checks didn't load in time, skipping auto-fetch");
return;
}
console.log("Auto-fetching check summaries...");
try {
// Fetch all failed checks, plus Mypy and GDPR if they're not successful
await fetchAllInterestingCheckSummaries(["Mypy", "GDPR"]);
} catch (error) {
console.error("Error auto-fetching check summary:", error);
}
}
// Auto-fetch when on PR page
try {
autoFetchCheckSummary();
} catch (e) {
console.error("Error auto-fetching check summary:", e);
}
document.addEventListener("DOMContentLoaded", autoFetchCheckSummary);
// Stacked PR Detection
console.log("GitHub Pull Request Colorizer: Stacked PR detector loaded");
function getBaseBranchFromPage() {
// Try multiple selectors to find the base branch
// GitHub shows "username wants to merge X commits into base:branch from head:branch"
// Look for the base branch in the PR header
const baseRefSelector = ".base-ref";
const baseRefElement = document.querySelector(baseRefSelector);
if (baseRefElement) {
// The text content might be just the branch name or include "base:"
const text = baseRefElement.textContent.trim();
// Remove "base:" prefix if present
const branchName = text.replace(/^base:/, "").trim();
if (branchName) {
return branchName;
}
}
// Alternative: look for span.commit-ref with css-truncate
const commitRefElements = document.querySelectorAll(".commit-ref");
for (const element of commitRefElements) {
// Check if this is the base ref (usually the first one in the merge info)
const titleAttr = element.getAttribute("title");
if (titleAttr) {
// Title might contain the full branch name
const parts = titleAttr.split(":");
if (parts.length > 0) {
const branchName = parts[parts.length - 1].trim();
if (branchName) {
return branchName;
}
}
}
}
// Another approach: look for the merge info text
const mergeInfoElement = document.querySelector(".gh-header-meta");
if (mergeInfoElement) {
const text = mergeInfoElement.textContent;
// Match pattern "into base_branch from"
const match = text.match(/into\s+([^\s]+)\s+from/);
if (match && match[1]) {
// Remove any prefix like "base:" or repo prefix
const branchName = match[1].replace(/^(base:|[^:]+:)/, "").trim();
if (branchName) {
return branchName;
}
}
}
return null;
}
function isMainBranch(branchName) {
const mainBranches = ["main", "master"];
return mainBranches.includes(branchName.toLowerCase());
}
function handleStackedPR() {
const repoInfo = extractRepoInfoFromUrl();
if (!repoInfo) {
return; // Not on a PR page
}
// Check if we've already handled this page
const alreadyHandled = document.getElementById("stacked-pr-warning");
if (alreadyHandled) {
return;
}
console.log("Checking if PR is stacked...");
const baseBranch = getBaseBranchFromPage();
if (!baseBranch) {
console.log("Could not determine base branch from page");
return;
}
console.log(`Base branch: ${baseBranch}`);
if (isMainBranch(baseBranch)) {
console.log("PR merges into main branch, no action needed");
return;
}
console.log(`PR is stacked! Base branch is "${baseBranch}"`);
// Find the merge button
const mergeBox = document.querySelector(".merge-pr") || document.querySelector("[data-testid='mergebox-partial']");
if (!mergeBox) {
console.log("Could not find merge box");
return;
}
// Hide the merge box by default
mergeBox.style.display = "none";
mergeBox.dataset.hiddenByStackedPrDetector = "true";
// Create warning box
const warningContainer = document.createElement("div");
warningContainer.id = "stacked-pr-warning";
warningContainer.style.marginBottom = "16px";
warningContainer.style.marginTop = "16px";
warningContainer.style.marginLeft = "56px";
const warningBox = document.createElement("div");
warningBox.className = "Box Box--warning";
warningBox.style.border = "1px solid #bf8700";
// Header
const header = document.createElement("div");
header.className = "Box-header";
header.style.padding = "12px 16px";
header.style.fontWeight = "600";
header.style.display = "flex";
header.style.alignItems = "center";
header.style.gap = "8px";
header.style.background = "rgba(187, 128, 9, 0.1)";
// Warning icon
const icon = document.createElement("svg");
icon.setAttribute("width", "16");
icon.setAttribute("height", "16");
icon.setAttribute("viewBox", "0 0 16 16");
icon.setAttribute("fill", "currentColor");
icon.style.color = "#bf8700";
icon.innerHTML = `
<path d="M6.457 1.047c.659-1.234 2.427-1.234 3.086 0l6.082 11.378A1.75 1.75 0 0 1 14.082 15H1.918a1.75 1.75 0 0 1-1.543-2.575Zm1.763.707a.25.25 0 0 0-.44 0L1.698 13.132a.25.25 0 0 0 .22.368h12.164a.25.25 0 0 0 .22-.368Zm.53 3.996v2.5a.75.75 0 0 1-1.5 0v-2.5a.75.75 0 0 1 1.5 0ZM9 11a1 1 0 1 1-2 0 1 1 0 0 1 2 0Z"></path>
`;
header.appendChild(icon);
const headerText = document.createElement("span");
headerText.textContent = "Stacked PR Detected";
headerText.style.flex = "1";
header.appendChild(headerText);
// Body
const body = document.createElement("div");
body.className = "Box-body";
body.style.padding = "16px";
const message = document.createElement("p");
message.style.margin = "0 0 12px 0";
message.innerHTML = `This pull request merges into <strong>${baseBranch}</strong> (not main). The merge button is hidden to prevent accidental merging of stacked PRs.`;
body.appendChild(message);
// Try to find the base PR by searching for open PRs with the same head branch as our base
// We'll create a link to search for PRs with the base branch name