This repository was archived by the owner on Aug 31, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathcontent.js
620 lines (502 loc) · 23.9 KB
/
content.js
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
(function(globals) {
'use strict';
class GitLabApiClient {
/**
* The GitLab API client used by the extension. No tokens or authentication needed as every requests are
* performed from inside the context of the page (GitLab allows API calls if they comes from the site).
*/
constructor(baseUrl, csrfToken) {
this.baseUrl = baseUrl;
this.csrfToken = csrfToken;
}
/**
* Returns the full URL to the given GitLab API endpoint.
*/
createEndpointUrl(endpoint, queryStringParameters = null) {
let endpointUrl = new URL(this.baseUrl + endpoint);
if (queryStringParameters) {
queryStringParameters.forEach(function(queryStringParameter) {
endpointUrl.searchParams.append(queryStringParameter[0], queryStringParameter[1]);
});
}
return endpointUrl.toString();
}
/**
* Sends an HTTP request to the GitLab API.
*/
sendRequest(method, endpoint, queryStringParameters = null, data = null) {
let headers = {};
let body = null;
if (['post', 'put', 'patch'].includes(method.toLowerCase())) {
if (!this.csrfToken) {
console.error('Cannot issue POST/PUT/PATCH requests without CSRF token');
return;
}
headers['X-CSRF-Token'] = this.csrfToken;
}
if (data) {
headers['Content-Type'] = 'application/json';
body = JSON.stringify(data);
}
let fetchPromise = fetch(this.createEndpointUrl(endpoint, queryStringParameters), {
method: method,
headers: headers,
body: body,
credentials: 'same-origin'
}).then(function(response) {
if (response.ok) {
return response.json();
} else {
return Promise.reject(response);
}
});
fetchPromise.catch(function(err) {
console.error('Got error from GitLab:', err);
alert('Got error from GitLab, check console for more information.');
});
return fetchPromise;
}
/**
* Fetch details about the given Merge Requests IDs in the given project ID.
*/
getProjectMergeRequests(projectId, mergeRequestIds) {
let queryStringParameters = mergeRequestIds.map(function(mergeRequestId) {
return ['iids[]', mergeRequestId];
});
return this.sendRequest(
'GET',
'projects/' + projectId + '/merge_requests',
queryStringParameters
);
}
/**
* Update the given Merge Request Id in the given project ID.
*/
updateProjectMergeRequest(projectId, mergeRequestId, data) {
let dataToSend = {
id: parseInt(projectId, 10),
merge_request_iid: parseInt(mergeRequestId, 10)
};
Object.assign(dataToSend, data);
return this.sendRequest(
'PUT',
'projects/' + projectId + '/merge_requests/' + mergeRequestId,
null,
dataToSend
);
}
}
class ContentScript {
/**
* The content script of the extension which is executed in the context of the page.
*/
constructor() {
this.currentProjectId = this.getCurrentProjectId();
if (!this.currentProjectId) {
console.error('Aborting: current project ID cannot be found');
return;
}
this.baseProjectUrl = this.getBaseProjectUrl();
if (!this.baseProjectUrl) {
console.error('Aborting: base project URL cannot be found');
return;
}
this.baseUrl = location.protocol + '//' + location.host;
this.baseApiUrl = this.baseUrl + '/api/v4/';
this.baseIconsUrl = this.getBaseIconsUrl();
this.userAuthenticated = this.isUserAuthenticated();
this.pipelineFeatureEnabled = this.isPipelineFeatureEnabled();
this.apiClient = new GitLabApiClient(this.baseApiUrl, this.getCsrfToken());
this.currentMergeRequestIds = this.getCurrentMergeRequestIds();
let preferencesManager = new globals.Gmrle.PreferencesManager();
let self = this;
preferencesManager.getAll(function(preferences) {
self.preferences = preferences;
self.fetchMergeRequestsDetailsThenUpdateUI(self.currentMergeRequestIds);
});
}
/**
* Finds and returns the GitLab project ID whe're looking merge requests at.
*/
getCurrentProjectId() {
let body = document.querySelector('body');
if (!body || !('projectId' in body.dataset)) {
return null;
}
return body.dataset.projectId;
}
/**
* Finds and returns the URI to the project whe're looking merge requests at.
*/
getBaseProjectUrl() {
let link = document.querySelector('.nav-sidebar .context-header a');
return link ? link.getAttribute('href') : null;
}
/**
* Get the current CSRF token that should be sent in any subsequent POST or PUT requests to the Gitlab API.
*/
getCsrfToken() {
let meta = document.querySelector('meta[name="csrf-token"]');
return meta ? meta.getAttribute('content') : null;
}
/**
* Determines if the current user is logged-in to GitLab.
*/
isUserAuthenticated() {
return document.querySelector('.navbar-nav .header-user') ? true : false;
}
/**
* Return the base URL to the SVG icons file.
*/
getBaseIconsUrl() {
let svgUse = document.querySelector('svg.s16 > use');
if (!svgUse || !svgUse.href.baseVal) {
return null;
}
let url = svgUse.href.baseVal;
if (url.startsWith('/')) {
url = this.baseUrl + url;
}
let parsedUrl = new URL(url);
return parsedUrl.protocol + '//' + parsedUrl.host + '/' + parsedUrl.pathname;
}
/**
* Determines if the project do uses the Gitlab "pipeline" feature.
*/
isPipelineFeatureEnabled() {
return document.querySelector('.nav-sidebar .shortcuts-pipelines') ? true : false;
}
/**
* Gets all Merge Requests IDs that are currently displayed.
*/
getCurrentMergeRequestIds() {
return Array.from(
document.querySelectorAll('.mr-list .merge-request .issuable-reference')
).map(function(el) {
return el.textContent.trim().replace('!', '');
});
}
/**
* Performs an HTTP GET request to the GitLab API to retrieve details about Merge Requests that are
* currently displayed. If successful, it actually updates the UI by altering the DOM.
*/
fetchMergeRequestsDetailsThenUpdateUI(mergeRequestIds) {
let self = this;
this.apiClient.getProjectMergeRequests(
this.currentProjectId,
mergeRequestIds
).then(function(responseData) {
if (self.preferences.display_source_and_target_branches) {
self.removeExistingTargetBranchNodes();
}
self.updateMergeRequestsNodes(responseData);
if (self.preferences.enable_buttons_to_copy_source_and_target_branches_name) {
self.attachClickEventToCopyBranchNameButtons();
}
if (self.preferences.enable_button_to_copy_mr_info) {
self.attachClickEventToCopyMergeRequestInfoButtons();
}
if (self.userAuthenticated && self.preferences.enable_button_to_toggle_wip_status) {
self.attachClickEventToToggleWipStatusButtons();
}
});
}
/**
* Removes all branches that may have been already displayed by GitLab.
*/
removeExistingTargetBranchNodes() {
document.querySelectorAll('.mr-list .merge-request .project-ref-path').forEach(function(el) {
el.parentNode.removeChild(el);
});
}
/**
* Parses HTML code and applies a callback on all of the parsed root DOM nodes.
*/
parseHtml(html, callback) {
new DOMParser()
.parseFromString(html, 'text/html')
.querySelector('body')
.childNodes
.forEach(function(node) {
callback(node);
}
);
}
/**
* Prepends the given HTML string at the beginning of the given child target node.
*/
parseHtmlAndPrepend(targetNode, html) {
this.parseHtml(html, function(node) {
targetNode.prepend(node);
});
}
/**
* Appends the given HTML string at the end of the given child target node.
*/
parseHtmlAndAppend(targetNode, html) {
this.parseHtml(html, function(node) {
targetNode.append(node);
});
}
/**
* Inserts the given HTML string before the given child target node.
*/
parseHtmlAndInsertBefore(targetNode, html) {
this.parseHtml(html, function(node) {
targetNode.parentNode.insertBefore(node, targetNode);
});
}
/**
* Actually updates the UI by altering the DOM by adding our stuff.
*/
updateMergeRequestsNodes(mergeRequests) {
mergeRequests.forEach(function(mergeRequest) {
let mergeRequestNode = document.querySelector('.mr-list .merge-request[data-id="' + mergeRequest.id + '"]');
this.setDataAttributesToMergeRequestNode(mergeRequestNode, mergeRequest);
// -----------------------------------------------
// Toggle WIP status button
if (this.userAuthenticated && this.preferences.enable_button_to_toggle_wip_status) {
let toggleWipStatusButton = '<button class="btn btn-secondary btn-md btn-default btn-transparent btn-clipboard has-tooltip gmrle-toggle-wip-status" title="Toggle WIP status" style="padding-left: 0">' +
this.buildSpriteIcon('lock') +
'</button> ';
this.parseHtmlAndPrepend(
mergeRequestNode.querySelector('.merge-request-title'),
toggleWipStatusButton
);
}
// -----------------------------------------------
// Jira ticket link (data attributes are set in setDataAttributesToNode, above)
if (('jiraTicketId' in mergeRequestNode.dataset) && ('jiraTicketUrl' in mergeRequestNode.dataset)) {
let jiraTicketLinkToolip = null;
let jiraTicketLinkLabel = null;
switch (this.preferences.jira_ticket_link_label_type) {
case 'ticket_id':
jiraTicketLinkLabel = mergeRequestNode.dataset.jiraTicketId;
break;
case 'icon':
jiraTicketLinkLabel = this.buildSpriteIcon('issues');
jiraTicketLinkToolip = 'Jira ticket ' + mergeRequestNode.dataset.jiraTicketId;
break;
default:
console.error('Invalid link label type ' + this.preferences.jira_ticket_link_label_type);
}
if (jiraTicketLinkLabel) {
let jiraTicketLink = '<a href="' + mergeRequestNode.dataset.jiraTicketUrl + '" ' +
'class="issuable-milestone ' + (jiraTicketLinkToolip ? 'has-tooltip' : '') + '" ' +
(jiraTicketLinkToolip ? 'title="' + jiraTicketLinkToolip + '"' : '') + '>' +
jiraTicketLinkLabel +
'</a> ';
this.parseHtmlAndInsertBefore(
mergeRequestNode.querySelector('.merge-request-title-text'),
jiraTicketLink
);
}
}
// -----------------------------------------------
// Copy MR info button
if (this.preferences.enable_button_to_copy_mr_info) {
let copyMrInfoButton = '<button class="btn btn-secondary btn-md btn-default btn-transparent btn-clipboard has-tooltip gmrle-copy-mr-info" title="Copy Merge Request info" style="padding-left: 0">' +
this.buildSpriteIcon('share') +
'</button> ';
this.parseHtmlAndPrepend(
mergeRequestNode.querySelector('.issuable-info'),
copyMrInfoButton
);
}
// -----------------------------------------------
// Source and target branches info
if (this.preferences.display_source_and_target_branches) {
let newInfoLineToInject = '<div class="issuable-info">';
// Source branch name
newInfoLineToInject += '<span class="project-ref-path has-tooltip" title="Source branch">' +
'<a class="ref-name" href="' + this.baseProjectUrl + '/-/commits/' + mergeRequest.source_branch + '">' + mergeRequest.source_branch + '</a>' +
'</span>';
// Copy source branch name button
if (this.preferences.enable_buttons_to_copy_source_and_target_branches_name) {
newInfoLineToInject += ' <button class="btn btn-secondary btn-md btn-default btn-transparent btn-clipboard has-tooltip gmrle-copy-branch-name" title="Copy branch name" data-branch-name-to-copy="source">' +
this.buildSpriteIcon('copy-to-clipboard') +
'</button>';
}
// Target branch name
newInfoLineToInject += ' ' + this.buildSpriteIcon('long-arrow') + ' ' +
'<span class="project-ref-path has-tooltip" title="Target branch">' +
'<a class="ref-name" href="' + this.baseProjectUrl + '/-/commits/' + mergeRequest.target_branch + '">' + mergeRequest.target_branch + '</a>' +
'</span>';
// Copy target branch name button
if (this.preferences.enable_buttons_to_copy_source_and_target_branches_name) {
newInfoLineToInject += ' <button class="btn btn-secondary btn-md btn-default btn-transparent btn-clipboard has-tooltip gmrle-copy-branch-name" title="Copy branch name" data-branch-name-to-copy="target">' +
this.buildSpriteIcon('copy-to-clipboard') +
'</button>';
}
newInfoLineToInject += '</div>';
this.parseHtmlAndAppend(
mergeRequestNode.querySelector('.issuable-main-info'),
newInfoLineToInject
);
}
// -----------------------------------------------
// Unresolved discussions indicator
if (this.preferences.enable_unresolved_discussions_indicator && !mergeRequest.blocking_discussions_resolved) {
let unresolvedDiscussionsIndicatorToInject = '<li><span class="has-tooltip" title="Unresolved discussion(s) left">' + this.buildSpriteIcon('comment-dots', 'danger-title') + '</span></li>';
this.parseHtmlAndPrepend(
mergeRequestNode.querySelector('.issuable-meta .controls'),
unresolvedDiscussionsIndicatorToInject
);
}
}, this);
}
/**
* Sets several data-* attributes on a DOM node representing a Merge Request so these values may be used later.
*/
setDataAttributesToMergeRequestNode(mergeRequestNode, mergeRequest) {
mergeRequestNode.dataset.title = mergeRequest.title;
mergeRequestNode.dataset.iid = mergeRequest.iid;
mergeRequestNode.dataset.url = mergeRequest.web_url;
mergeRequestNode.dataset.diffsUrl = mergeRequest.web_url + '/diffs';
mergeRequestNode.dataset.authorName = mergeRequest.author.name;
mergeRequestNode.dataset.status = mergeRequest.state;
mergeRequestNode.dataset.sourceBranchName = mergeRequest.source_branch;
mergeRequestNode.dataset.targetBranchName = mergeRequest.target_branch;
mergeRequestNode.dataset.isWip = mergeRequest.work_in_progress;
if (this.preferences.enable_jira_ticket_link) {
let jiraTicketId = this.findFirstJiraTicketId(mergeRequest);
if (jiraTicketId) {
mergeRequestNode.dataset.jiraTicketId = jiraTicketId;
mergeRequestNode.dataset.jiraTicketUrl = this.createJiraTicketUrl(jiraTicketId);
}
}
}
/**
* Finds a Jira ticket ID in the given Merge Request object. It first tris in the source branch name, then
* fallbacks to the Merge Request title.
*/
findFirstJiraTicketId(mergeRequest) {
let jiraTicketIdRegex = new RegExp('[A-Z]{1,10}-\\d+');
// First try in the source branch name
let results = jiraTicketIdRegex.exec(mergeRequest.source_branch);
if (results) {
return results[0];
}
// Fallback to the Merge Request title if none found in the source branch name
results = jiraTicketIdRegex.exec(mergeRequest.title);
if (results) {
return results[0];
}
return null;
}
/**
* Creates an URL to a given Jira ticket ID, pointing to the Jira base URL the user has defined in its
* preferences.
*/
createJiraTicketUrl(jiraTicketId) {
let baseJiraUrl = new URL(this.preferences.base_jira_url);
if (!baseJiraUrl.pathname.endsWith('/')) {
baseJiraUrl.pathname += '/';
}
baseJiraUrl.pathname += 'browse/' + jiraTicketId;
return baseJiraUrl.toString();
}
/**
* Attach a click event to all buttons inserted by the extension allowing to copy the source and target
* branches name.
*/
attachClickEventToCopyBranchNameButtons() {
document.querySelectorAll('button.gmrle-copy-branch-name').forEach(function(el) {
el.addEventListener('click', function(e) {
e.preventDefault();
let branchName = this.closest('.merge-request').dataset[this.dataset.branchNameToCopy + 'BranchName'];
navigator.clipboard.writeText(branchName).then(function() {
// Do nothing if copy was successful.
}, function() {
alert('Unable to copy branch name.');
});
});
});
}
/**
* Attach a click event to all buttons inserted by the extension allowing to copy Merge Request info.
*/
attachClickEventToCopyMergeRequestInfoButtons() {
let self = this;
document.querySelectorAll('button.gmrle-copy-mr-info').forEach(function(el) {
el.addEventListener('click', function(e) {
e.preventDefault();
let text = self.buildMergeRequestInfoText(this.closest('.merge-request'));
navigator.clipboard.writeText(text).then(function() {
// Do nothing if copy was successful.
}, function() {
alert('Unable to copy Merge Request info.');
});
});
});
}
/**
* Attach a click event to all buttons inserted by the extension allowing to toggle Merge Request WIP status.
*/
attachClickEventToToggleWipStatusButtons() {
let self = this;
document.querySelectorAll('button.gmrle-toggle-wip-status').forEach(function(el) {
el.addEventListener('click', function(e) {
e.preventDefault();
self.toggleMergeRequestWipStatus(this.closest('.merge-request'), this);
});
});
}
/**
* Actually toggle a given Merge Request WIP status.
*/
toggleMergeRequestWipStatus(mergeRequestNode, toggleButton) {
toggleButton.disabled = true;
let isWip = mergeRequestNode.dataset.isWip == 'true';
let newTitle = '';
if (isWip) {
newTitle = mergeRequestNode.dataset.title.replace(new RegExp('^WIP:'), '').trim();
} else {
newTitle = 'WIP: ' + mergeRequestNode.dataset.title.trim();
}
this.apiClient.updateProjectMergeRequest(
this.currentProjectId,
mergeRequestNode.dataset.iid,
{
title: newTitle
}
).then(function(responseData) {
mergeRequestNode.dataset.isWip = responseData.work_in_progress;
mergeRequestNode.dataset.title = responseData.title;
mergeRequestNode.querySelector('.merge-request-title-text a').textContent = responseData.title;
}).finally(function() {
toggleButton.disabled = false;
});
}
/**
* Creates the Merge Request info text from a Merge Request container DOM node.
*/
buildMergeRequestInfoText(mergeRequestNode) {
let placeholders = {
MR_TITLE: mergeRequestNode.dataset.title,
MR_ID: mergeRequestNode.dataset.iid,
MR_URL: mergeRequestNode.dataset.url,
MR_DIFFS_URL: mergeRequestNode.dataset.diffsUrl,
MR_AUTHOR_NAME: mergeRequestNode.dataset.authorName,
MR_STATUS: mergeRequestNode.dataset.status,
MR_SOURCE_BRANCH_NAME: mergeRequestNode.dataset.sourceBranchName,
MR_TARGET_BRANCH_NAME: mergeRequestNode.dataset.targetBranchName,
MR_JIRA_TICKET_ID: ('jiraTicketId' in mergeRequestNode.dataset) ? mergeRequestNode.dataset.jiraTicketId : '',
MR_JIRA_TICKET_URL: ('jiraTicketUrl' in mergeRequestNode.dataset) ? mergeRequestNode.dataset.jiraTicketUrl : ''
};
let placeholdersReplaceRegex = new RegExp('{(' + Object.keys(placeholders).join('|') + ')}', 'g');
return this.preferences.copy_mr_info_format.replace(placeholdersReplaceRegex, function(_, placeholder) {
return placeholders[placeholder];
}).trim();
}
/**
* Generate the HTML code corresponding to an SVG icon.
*/
buildSpriteIcon(iconName, classes = '') {
return '<svg class="s16 ' + classes + '" data-testid="' + iconName + '-icon">' +
'<use xlink:href="' + this.baseIconsUrl + '#' + iconName + '"></use>' +
'</svg>';
}
}
let cs = new ContentScript();
}(this));