-
Notifications
You must be signed in to change notification settings - Fork 2
/
jira-gerrit-integration.js
481 lines (432 loc) · 18.3 KB
/
jira-gerrit-integration.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
/* Copyright (c) 2014 Jan Chęć
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($) {
var deparam = function (querystring) {
// remove any preceding url and split
querystring = querystring.substring(querystring.indexOf('?')+1).split('&');
var params = {}, pair, d = decodeURIComponent, i;
// march and parse
for (i = querystring.length; i > 0;) {
pair = querystring[--i].split('=');
params[d(pair[0])] = d(pair[1]);
}
return params;
}
var GerritMine = GerritMine || {};
GerritMine.getParameters = function() {
// Source: http://feather.elektrum.org/book/src.html
var scripts = document.getElementsByTagName('script');
var currentlyRunningIndex = scripts.length - 1;
var thisScriptNode = scripts[currentlyRunningIndex];
var queryString = thisScriptNode.src.replace(/^[^\?]+\??/,'');
return deparam(queryString);
};
GerritMine.parameters = GerritMine.getParameters();
$(function() {
var GERRIT_SERVER = GerritMine.parameters.gerrit_server;
var STORAGE_KEY = 'gerrit_integration';
var SECOND = 1000;
var UPDATE_AFTER = GerritMine.parameters.update_interval || 10 * SECOND;
var EMPTY_RESPONSE_CONTENT_LENGTH = 8;
var LINK_GERRIT_LOGIN_ON_ZERO_CHANGES = true;
var JENKINS_USERNAME = 'Jenkins';
var DEFAULT_LANGUAGE = 'EN';
var TRANSLATIONS = {
PL: {
commentLink: "Skomentuj",
needsLoginLink: "Zaloguj się do Gerrita, aby wyświetlały się statusy otwartych zmian przy zagadnieniach.",
openChangesTitle: "Otwarte zmiany",
hideTrivialMessagesTooltip: "Ukryj trywialne wiadomości.",
showTrivialMessagesTooltip: "Pokaż trywialne wiadomości."
},
EN: {
commentLink: "Comment",
needsLoginLink: "Log in to Gerrit to see open changes statuses by issues.",
openChangesTitle: "Open changes",
hideTrivialMessagesTooltip: "Hide trivial messages.",
showTrivialMessagesTooltip: "Show trivial messages."
}
};
var STATUS_COLORS = {
toFix: 'red',
toMerge: 'green',
'default': 'blue'
};
if(isIssueDetailsPagePresent()) {
if(needsUpdate()) {
updateChanges(showChangesForCurrentIssue);
} else {
showChangesForCurrentIssue();
}
}
function isIssueDetailsPagePresent() {
return $('body').hasClass('navigator-issue-only');
}
function needsUpdate() {
try {
var data = getData();
} catch(error) {
return error == 'No data yet.';
}
var now = new Date();
var lastUpdated = new Date(data.updated);
return UPDATE_AFTER < now - lastUpdated;
}
function updateChanges(success) {
$.ajax({
url: GERRIT_SERVER + '/changes/?q=is:open&o=LABELS&o=MESSAGES&o=CURRENT_REVISION',
success: function(responseContent) {
if(hasData(responseContent)) {
save(responseContent);
success();
} else {
if(LINK_GERRIT_LOGIN_ON_ZERO_CHANGES)
informAboutEmptyResponse();
}
},
xhrFields: {
withCredentials: true
},
dataType: 'text',
cache: true
});
function hasData(responseContent) {
return responseContent.length > EMPTY_RESPONSE_CONTENT_LENGTH;
}
function save(data) {
var changes = extractChanges(data);
var toSave = mapIssesToChanges(changes);
saveData(toSave);
}
function extractChanges(data) {
var dataWithoutXSSIProtection = data.substring(5);
return $.parseJSON(dataWithoutXSSIProtection);
}
function mapIssesToChanges(changes) {
var map = {};
for(var i = 0; i < changes.length; i++) {
var issueNumber = getIssueNumber(changes[i].subject);
if(issueNumber != undefined) {
if(map[issueNumber] == undefined)
map[issueNumber] = [];
map[issueNumber].push(changes[i]);
}
}
return map;
}
function getIssueNumber(subject) {
var issueNumberPattern = new RegExp('\\[([A-Z]+-\\d+)]');
var matchSingleton = issueNumberPattern.exec(subject);
if(matchSingleton)
return matchSingleton[1];
else
return undefined;
}
function informAboutEmptyResponse() {
var info = $('<div><a href="' + GERRIT_SERVER + '" style="color: #ED8F64;"></a></div>');
info.find('a').text(getText('needsLoginLink'));
$('#details-module').append(info);
}
}
function showChangesForCurrentIssue() {
var issueNumber = getIssueNumber();
if(typeof issueNumber == 'undefined')
return;
var changes = getChanges(issueNumber);
if(changes.length == 0)
return;
var changesNode = $('<div class="mod-content"></div>');
addTitle(changesNode);
addChanges(changes);
changesNode.append($('<hr>'));
$('#details-module').append(changesNode);
function getIssueNumber() {
var issueTypeAndNumber = $('#key-val').text();
var matches = RegExp('[A-Z]+-\\d+').exec(issueTypeAndNumber);
if(matches)
return issueTypeAndNumber;
else
return undefined;
}
function addTitle(parentNode) {
var title = $('<p><strong></strong></p>');
title.find('strong').text(getText('openChangesTitle'));
parentNode.append(title);
}
function addChanges(changes) {
changes = sortEldestFirst(changes);
for(var i = 0; i < changes.length; i++) {
var change = changes[i];
var changeLink = getChangeLink(change);
var paragraph = $('<p></p>');
paragraph.append(changeLink);
changesNode.append(paragraph);
var lastRevisionNumber = change.revisions[change.current_revision]._number;
var isDraft = change.revisions[change.current_revision].draft;
if(isDraft)
markAsDraft(paragraph);
var messages = getMessagesForRevision(change.messages, lastRevisionNumber);
if(messages.length > 0) {
messages = getDecompositedMessages(messages, lastRevisionNumber);
if(hasAnyTrivial(messages)) {
var toggleMessages = getMessageToggler();
paragraph.append(toggleMessages);
}
var list = createMessagesList(change, messages, lastRevisionNumber);
changesNode.append(list);
}
}
function sortEldestFirst(changes) {
return changes.sort(function(a, b) {
return a._number - b._number;
});
}
function markAsDraft(entryNode) {
var link = entryNode.find('a');
link.text(link.text() + ' [DRAFT]');
}
function hasAnyTrivial(messages) {
var trivial = messages.filter(function(message) {
return message.trivial;
});
return trivial.length > 0;
}
function getMessageToggler() {
var toggleMessages = $('<a></a>').text("▽").addClass('toggle-messages');
toggleMessages.attr('title', getText('showTrivialMessagesTooltip'));
toggleMessages.css({
'padding': '5px',
'cursor': 'pointer'
});
toggleMessages.click(function() {
var self = $(this);
self.parent().next('.messages').find('.trivial').toggle();
if(self.text() == "▽") {
self.attr('title', getText('hideTrivialMessagesTooltip'));
self.text("△");
} else {
self.attr('title', getText('showTrivialMessagesTooltip'));
self.text("▽");
}
});
return toggleMessages;
}
}
function getChangeLink(change) {
var node = createChangeLink(change);
node.css('color', getChangeColor(change, false));
return node.text(getChangeLinkText(change));
function getChangeLinkText(change) {
return getReviewText(change) + " " + drySubject(change.subject);
}
}
function createChangeLink(change) {
var node = $('<a></a>');
var changeUrl = '{{gerritServer}}/{{changeNumber}}/';
changeUrl = changeUrl.replace('{{gerritServer}}', GERRIT_SERVER);
changeUrl = changeUrl.replace('{{changeNumber}}', change._number);
node.attr('href', changeUrl);
return node;
}
function getReviewText(change) {
var codeReview = getCodeReviewState(change);
var verified = getVerifiedState(change);
if(codeReview == 2)
codeReview = '✓';
else if(codeReview == 1)
codeReview = '+1';
else if(codeReview == -2)
codeReview = '✗';
if(verified == 1)
verified = '✓';
else if(verified == -1)
verified = '✗';
else
verified = '0';
return codeReview + verified;
}
function drySubject(subject) {
subject = subject.replace('[#' + issueNumber + '] ', '');
return subject.replace('[close #' + issueNumber + ']', '[close]');
}
function getMessagesForRevision(messages, revisionNumber) {
return messages.filter(function(message) {
return message._revision_number == revisionNumber;
});
}
function getDecompositedMessages(rawMessages, lastRevisionNumber) {
var result = [];
for(var i = 0; i < rawMessages.length; i++) {
var message = rawMessages[i];
var trivial = isTrivial(message);
var messageContent = message.message;
var preamble = messageContent.split('\n\n')[0];
var coverMessage = '';
if(messageContent.indexOf('\n\n') > -1)
coverMessage = messageContent.replace(preamble + '\n\n', '');
preamble = preamble.replace('Patch Set ' + lastRevisionNumber + ': ', '');
preamble = preamble.replace('Patch Set ' + lastRevisionNumber + ':', '');
result.push({
'author': message.author,
'coverMessage': coverMessage,
'messages': message.messages,
'preamble': preamble,
'trivial': trivial
});
}
return result;
function isTrivial(message) {
if(0 == message.message.indexOf("Uploaded patch set"))
return true;
if(typeof JENKINS_USERNAME !== 'undefined' && JENKINS_USERNAME == message.author.name)
return message.message.indexOf('Build Started') > 0
|| message.message.indexOf('Build Successful') > 0;
return false;
}
}
function createMessagesList(change, messages, lastRevisionNumber) {
var list = $('<ul></ul>').addClass('messages');
var trivials = 0;
for(var i = 0; i < messages.length; i++) {
var message = messages[i];
var trivial = message.trivial;
var entry = createMessageListEntry(message);
if(trivial) {
entry = markAsTrivial(entry);
trivials++;
}
list.append(entry);
}
var commentLink = generateCommentLink(change, lastRevisionNumber);
if(trivials == messages.length)
commentLink = markAsTrivial(commentLink);
list.append(commentLink);
return list;
function createMessageListEntry(message) {
var preamble = message.preamble;
var coverMessage = message.coverMessage;
var entry = $('<li></li>');
entry.text(message.author.name);
if(preamble) {
entry.text(entry.text() + ' - ');
entry.append($('<b></b>').text(preamble));
}
if(coverMessage) {
coverMessage = coverMessage.replace(/\n/g, '<br>');
entry.append($('<blockquote></blockquote>').append(coverMessage).linkify());
}
return entry;
}
function generateCommentLink(change, lastRevisionNumber) {
var commentLink = $('<a></a>');
var commentUrl = '{{gerritUrl}}/#/c/{{changeId}}/{{revision}},publish';
commentUrl = commentUrl.replace('{{gerritUrl}}', GERRIT_SERVER);
commentUrl = commentUrl.replace('{{changeId}}', change._number);
commentUrl = commentUrl.replace('{{revision}}', lastRevisionNumber);
commentLink.attr('href', commentUrl);
commentLink.text(getText('commentLink'));
return $('<li></li>').append(commentLink).css('list-style', 'none');
}
function markAsTrivial(node) {
return node.addClass('trivial').css('display', 'none');
}
}
}
function getChanges(issueNumber) {
var data = getData();
return data[issueNumber] || [];
}
function saveData(toSave) {
toSave.updated = new Date();
localStorage.setItem(STORAGE_KEY, JSON.stringify(toSave));
}
function isIssueListPagePresent() {
return $('body').hasClass('action-index');
}
function getData() {
var raw = localStorage.getItem(STORAGE_KEY);
if(raw)
return JSON.parse(raw);
else
throw 'No data yet.';
}
function getText(source) {
if($('html').attr('lang') == 'pl')
return getTextForLanguage(source, 'PL');
else
return getTextForLanguage(source);
}
function getTextForLanguage(source, language) {
if(language === undefined || !(language in TRANSLATIONS))
language = DEFAULT_LANGUAGE;
var possibleTranslations = [
TRANSLATIONS[language][source],
TRANSLATIONS[DEFAULT_LANGUAGE][source],
''
];
return getFirstDefined(possibleTranslations);
function getFirstDefined(array) {
var defined = array.filter(function(element) {
return typeof element !== 'undefined';
});
return defined[0];
}
}
function getChangeColor(change, useDefault) {
useDefault = typeof useDefault !== 'undefined' ? useDefault : true;
if(needsFix(change))
return STATUS_COLORS['toFix'];
else if(needsMerge(change))
return STATUS_COLORS['toMerge'];
else if(useDefault)
return STATUS_COLORS['default'];
else
return undefined;
}
function needsFix(change) {
var codeReview = getCodeReviewState(change);
var verified = getVerifiedState(change);
return codeReview < 0 || verified < 0;
}
function needsMerge(change) {
var codeReview = getCodeReviewState(change);
var verified = getVerifiedState(change);
return verified == 1 && codeReview == 2;
}
function getCodeReviewState(change) {
if(change.labels['Code-Review'].rejected)
return -2;
else if(change.labels['Code-Review'].approved)
return 2;
else if(change.labels['Code-Review'].disliked)
return -1;
else if(change.labels['Code-Review'].recommended)
return 1;
else
return 0;
}
function getVerifiedState(change) {
if(change.labels['Verified'].rejected)
return -1;
else if(change.labels['Verified'].approved)
return 1;
else
return 0;
}
});
})(jQuery)