Repository navigation
Expand file tree
/
Copy pathjira-pr-links-improver.user.js
More file actions
347 lines (313 loc) · 10.2 KB
/
Copy pathjira-pr-links-improver.user.js
File metadata and controls
347 lines (313 loc) · 10.2 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
// ==UserScript==
// @name Jira: Pull Request Link Improver
// @namespace https://github.com/rybak/atlassian-tweaks
// @version 15
// @license MIT
// @description Adds more convenient pull request links to Jira tickets.
// @author Andrei Rybak
// @match https://jira.example.com/browse/*
// @include https://*jira*/browse/*
// @icon https://jira.atlassian.com/favicon.ico
// @homepageURL https://github.com/rybak/atlassian-tweaks
// @grant GM_addStyle
// ==/UserScript==
/*
* Copyright (c) 2022-2026 Andrei Rybak
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
(function() {
'use strict';
const LOG_PREFIX = '[PR Link Improver]';
const PANEL_ID = 'PrLinksImproverPanel';
const LIST_ID = 'PrLinksImproverList';
const COPY_BUTTONS_CLASS = 'PrLinksImproverCopyButton';
var loadInProgress = false;
const PARSE_PATH = /[/](projects|users)[/]([^/]*)[/]repos[/]([^/]*)[/].*/;
function log(...toLog) {
console.log(LOG_PREFIX, ...toLog);
}
function info(...toLog) {
console.info(LOG_PREFIX, ...toLog);
}
function warn(...toLog) {
console.warn(LOG_PREFIX, ...toLog);
}
function error(...toLog) {
console.error(LOG_PREFIX, ...toLog);
}
function getJiraMajorVersion() {
return document.querySelector('meta[name="application-name"]').attributes.getNamedItem("data-version").value.split(".")[0];
}
function createPanel() {
var header;
const jiraMajorVersion = getJiraMajorVersion();
switch (jiraMajorVersion) {
case "7":
header = '<div class="mod-header"><h2 class="toggle-title">Pull requests</h2></div>';
break;
case "8":
case "9":
header = '<div class="mod-header"><h4 class="toggle-title">Pull requests</h4></div>';
break;
default:
warn("Jira v" + jiraMajorVersion + " is not supported");
header = '<div class="mod-header"><h4 class="toggle-title">Pull requests</h4></div>';
break;
}
$('#viewissue-devstatus-panel')
.prepend($(header +
`<div class="mod-content" id="${PANEL_ID}" style="margin-bottom:1rem;"></div>`));
}
function addError(errors) {
for (const e of errors) {
error("Error: " + e);
}
const jsonErrors = JSON.stringify(errors, null, 2);
$(`#${PANEL_ID}`).append($(`<p>Could not load from Bitbucket. Got: ${jsonErrors}</p>`));
}
function extractProjectRepoSlugsFromPr(pr) {
const url = pr.url;
const path = new URL(url).pathname;
const matching = path.match(PARSE_PATH);
const project = matching[2];
const repository = matching[3];
return project + '/' + repository;
}
function createAuthorImg(pr) {
const img = document.createElement('img');
img.setAttribute('src', pr.author.avatar);
img.setAttribute('title', pr.author.name);
const spanInner = document.createElement('span');
spanInner.append(img);
spanInner.classList.add('aui-avatar-inner');
const span = document.createElement('span');
span.append(spanInner);
span.classList.add('aui-avatar', 'aui-avatar-small');
return span;
}
const PR_STATUS_CLASSES = {
'OPEN': 'aui-lozenge-current',
'MERGED': 'aui-lozenge-success',
'DECLINED': 'aui-lozenge-error'
};
function createPrStatusPill(pr) {
const span = document.createElement('span');
span.append(pr.status);
span.classList.add('aui-lozenge', 'aui-lozenge-subtle');
if (pr.status in PR_STATUS_CLASSES) {
span.classList.add(PR_STATUS_CLASSES[pr.status]);
} else {
warn('createPrStatusPill: unhandled status in PR_STATUS_CLASSES: ', pr.status);
}
return span;
}
function createPrTitleLink(pr) {
const link = document.createElement('a');
link.href = pr.url;
link.appendChild(document.createTextNode(pr.name));
info("NAME='" + pr.name + "' issue='" + JIRA.Issue.getIssueKey() + "'");
if (pr.name.includes(JIRA.Issue.getIssueKey())) {
link.style.fontWeight = 'bold';
}
if (pr.status === 'DECLINED') {
link.style.textDecoration = 'line-through';
}
return link;
}
function extractReviewerStats(pr) {
const reviewersApproved = pr.reviewers.filter(r => r.approved);
return {
'reviewersApproved': reviewersApproved,
'reviewersCount': pr.reviewers.length,
};
}
function createStatsSpan(pr) {
const reviewStats = extractReviewerStats(pr);
const span = document.createElement('span');
if (reviewStats.reviewersCount > 0) {
span.append("✅".repeat(reviewStats.reviewersApproved.length) + "/" + reviewStats.reviewersCount);
} else {
span.append("0️⃣/0️⃣");
}
span.setAttribute('title', reviewStats.reviewersApproved.map(r => r.name + ': ✅').join('\n'));
return span;
}
function createCopyLink(linkTextAdder, title, textSupplier) {
const link = document.createElement('a');
link.classList.add('aui-button');
link.style.padding = '2px 4px';
link.style.height = '1.8em';
link.href = '#';
link.title = title;
linkTextAdder(link);
link.onclick = e => {
e.preventDefault();
try {
navigator.clipboard.writeText(textSupplier());
} catch (e) {
error('navigator.clipboard is not supported:', e)
}
};
return link;
}
function createCopyLinkText(linkText, title, textSupplier) {
return createCopyLink(
link => link.appendChild(document.createTextNode(linkText)),
title,
textSupplier
);
}
function extractRepoSlugFromPr(pr) {
const url = pr.url;
const path = new URL(url).pathname;
const matching = path.match(PARSE_PATH);
const repository = matching[3];
return repository;
}
function formatMarkdownLink(pr) {
const repository = extractRepoSlugFromPr(pr);
return `[pull request ${pr.id} in ${repository}](${pr.url})`;
}
function formatJiraSyntaxLink(pr) {
const repository = extractRepoSlugFromPr(pr);
return `[pull request ${pr.id} in ${repository}|${pr.url}]`;
}
function createCopyLinks(pr) {
const container = document.createElement('span');
container.classList.add(COPY_BUTTONS_CLASS);
container.append(
createCopyLinkText('#', 'Copy PR number', () => pr.id),
createCopyLinkText('/#', 'Copy PR number with project/repo slugs', () => extractProjectRepoSlugsFromPr(pr) + pr.id),
createCopyLinkText('[]()', 'Copy Markdown link to the PR', () => formatMarkdownLink(pr)),
createCopyLinkText('[|]', 'Copy Jira link to the PR', () => formatJiraSyntaxLink(pr)),
createCopyLink(
link => {
const span = document.createElement('span');
span.classList.add('aui-icon', 'aui-icon-small', 'aui-iconfont-devtools-branch-small');
link.appendChild(span);
},
"Copy pull request's source branch's name",
() => pr.source.branch
)
);
return container;
}
function createPrTooltip(pr) {
const rs = extractReviewerStats(pr);
return 'status: ' + pr.status +
'\nlast update: ' + pr.lastUpdate +
'\napprovals: ' + rs.reviewersApproved.length + '/' + rs.reviewersCount;
}
function addPrLinks(pullRequests) {
$(`#${PANEL_ID}`).append($(`<ul id="${LIST_ID}" class="item-details status-panels devstatus-entry"></ul>`));
const list = $(`#${LIST_ID}`);
for (const pr of pullRequests) {
const img = createAuthorImg(pr);
const firstLine = document.createElement('div');
firstLine.append(
createPrStatusPill(pr),
" ",
createPrTitleLink(pr),
" ",
createStatsSpan(pr),
);
const secondLine = document.createElement('div');
secondLine.append(
extractProjectRepoSlugsFromPr(pr) + pr.id,
" ",
createCopyLinks(pr),
);
const tdImage = document.createElement('td');
tdImage.append(img);
const tdLines = document.createElement('td');
tdLines.append(firstLine, secondLine);
const tr = document.createElement('tr');
tr.append(tdImage, tdLines);
const table = document.createElement('table');
table.append(tr);
const li = document.createElement('li');
li.setAttribute('title', createPrTooltip(pr));
li.append(table);
list.append(li);
}
}
function addStyles() {
GM_addStyle(`.${COPY_BUTTONS_CLASS} {
opacity: 0;
}
#${LIST_ID} li:hover .${COPY_BUTTONS_CLASS} {
opacity: 1;
}
@keyframes fadeOut {
0% {
opacity: 1;
}
100% {
opacity: 0;
}
}
@keyframes fadeIn {
0% {
opacity: 0;
}
100% {
opacity: 1;
}
}`);
}
function addPrLinksPanel() {
if ($(`#${PANEL_ID}`).length) {
// the PR links panel has already been created
loadInProgress = false;
return;
}
addStyles();
const issueId = JIRA.Issue.getIssueId();
// https://community.atlassian.com/t5/Jira-questions/JIRA-REST-API-to-get-list-of-branches-related-to-a-issue/qaq-p/800389
const pullRequestsUrl = `/rest/dev-status/1.0/issue/detail?issueId=${issueId}&applicationType=stash&dataType=pullrequest`;
log("Loading: " + pullRequestsUrl);
$.getJSON(pullRequestsUrl, data => {
if ($(`#${PANEL_ID}`).length) {
// the PR links panel has been created while we were getting the PR data
loadInProgress = false;
return;
}
createPanel();
if (data.detail.length == 0) {
addError(data.errors);
loadInProgress = false;
return;
}
const pullRequests = data.detail[0].pullRequests;
addPrLinks(pullRequests);
loadInProgress = false;
});
}
function startPrLoading() {
if (!loadInProgress) {
loadInProgress = true;
addPrLinksPanel();
} else {
log("Already loading. Skipping...");
}
}
$(document).ready(startPrLoading);
JIRA.bind(JIRA.Events.NEW_CONTENT_ADDED, startPrLoading);
})();