-
Notifications
You must be signed in to change notification settings - Fork 26
Expand file tree
/
Copy pathapp.js
More file actions
653 lines (528 loc) · 16.9 KB
/
Copy pathapp.js
File metadata and controls
653 lines (528 loc) · 16.9 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
var token = ''
var repoList = []
var intervalIds = []
var githubApiUrl = 'https://api.github.com/'
$(window).on('unload', () => {
intervalIds.forEach(clearInterval)
return
})
// don't try to re initialize the extension if there's a token in memory
if (token === '') {
intervalIds.push(
setInterval(() => {
initializeExtension()
}, 1000)
)
}
function initializeExtension() {
const {
currentRepo,
error,
githubApiUrl: currentGithubApiUrl,
githubOrigin,
issueNumber,
organization,
url,
} = populateUrlMetadata(document.location.href)
if (error) {
return
}
githubApiUrl = currentGithubApiUrl
if (!isIssueDetailUrl({ currentRepo, issueNumber, organization, url })) {
return
}
// if the page is a pull request page(view or create)
// or the page is a new issue page
// or there is a Kamino button in the DOM, exit
if (
url.indexOf(`${organization}/${currentRepo}/compare/`) > -1 ||
url.indexOf(`${organization}/${currentRepo}/pull/`) > -1 ||
url.indexOf(`${organization}/${currentRepo}/issues/new`) > -1 ||
$('.kaminoButton').length > 0 ||
$('.batchButton').length > 0
) {
intervalIds.forEach(clearInterval)
return
}
intervalIds.forEach(clearInterval)
saveAppliedFilters({ currentRepo, githubOrigin, issueNumber, organization, url })
const kaminoButton = $(Handlebars.templates.button().replace(/(\r\n|\n|\r)/gm, ''))
const modalContext = {
confirmText:
'Are you sure you want to clone this issue to another repository? Choose whether to clone and close or clone and keep the original issue open.',
}
const modal = $(Handlebars.templates.modal(modalContext).replace(/(\r\n|\n|\r)/gm, ''))
let targetElement;
if ($('.sidebar-assignee').length) {
targetElement = $('.sidebar-assignee');
} else if ($('[data-testid="sidebar-section"]').length) {
targetElement = $('[data-testid="sidebar-section"]').first();
} else {
console.warn("It appears GitHub has changed their page structure, preventing the Kamino button from being rendered. Please go to https://github.com/gatewayapps/kamino and create an issue and we will try to remedy the issue as quickly as possible. Thanks");
return;
}
$(kaminoButton).insertBefore(targetElement)
$(modal).insertBefore(targetElement)
const kaminoButtonExists = $('.kaminoButton').length > 0
$('.btn-group').removeClass('open')
chrome.storage.sync.get(
{
githubToken: '',
},
(item) => {
token = item.githubToken
if (kaminoButtonExists) {
loadRepos()
}
}
)
$('.kaminoButton').click(() => {
openDropdown()
})
$('.quickClone').click(() => {
if ($('.quickClone').attr('data-repo') === undefined) {
openDropdown()
} else {
itemClick($('.quickClone').attr('data-repo'))
}
})
$('.cloneAndClose').click(async () => {
toggleModal(false)
await getGithubIssue($('.cloneAndClose').attr('data-repo'), true)
})
$('.cloneAndKeepOpen').click(async () => {
toggleModal(false)
await getGithubIssue($('.cloneAndKeepOpen').attr('data-repo'), false)
})
$('.close').click(() => {
toggleModal(false)
})
$('.noClone').click(() => {
toggleModal(false)
})
}
function isIssueDetailUrl(urlMetadata) {
try {
const issueUrl = new URL(urlMetadata.url)
return (
issueUrl.pathname === `/${urlMetadata.organization}/${urlMetadata.currentRepo}/issues/${urlMetadata.issueNumber}` &&
!isNaN(urlMetadata.issueNumber)
)
} catch {
return false
}
}
function saveAppliedFilters(urlMetadata) {
const { currentRepo, githubOrigin, issueNumber, organization, url } = urlMetadata
// url should have /issues and should not track any url that has an issue number at the end
if (url.indexOf('/issues') > 0 && isNaN(issueNumber)) {
const querystring = url.substring(url.indexOf('/issues'))
// another check to try and prevent a bad querystring from being added to filters
if (querystring.indexOf('?') === 0) {
return
}
var newFilter = {
filter: querystring,
githubOrigin,
organization,
currentRepo,
}
chrome.storage.sync.get(
{
filters: [],
},
(item) => {
const { filters, changed } = createFilters(newFilter, item)
// only save if changed, otherwise the max quota per minute will be exceeded throwing errors
if (changed) {
chrome.storage.sync.set({
filters,
})
}
}
)
}
}
async function getRepos(url) {
const response = await ajaxRequest('GET', '', url)
repoList = repoList.concat(response.data)
const linkValue = response.header.getResponseHeader('Link')
if (linkValue) {
let nextLink
const links = linkValue.split(',')
links.forEach((link) => {
if (link.indexOf('rel="next"') > -1) {
const re = /\<(.*?)\>/
nextLink = link.match(re)[1]
}
})
compileRepositoryList(response.data)
if (nextLink) {
return await getRepos(nextLink)
} else {
return null
}
} else {
compileRepositoryList(response.data)
return null
}
}
async function loadRepos() {
let lastValue = ''
$('.repoSearch').on('change keyup paste mouseup', function () {
if ($(this).val() != lastValue) {
lastValue = $(this).val()
searchRepositories(lastValue)
}
})
$('.kamino-heading').click(() => {
chrome.runtime.sendMessage({ action: 'goToOptions' }, () => {})
})
if (token === '') {
console.warn(
'disabling button because there is no Personal Access Token for authentication with GitHub. Please check your Kamino settings to make sure there is a stored Access Token'
)
$('.kaminoButton').prop('disabled', true)
$('.quickClone').prop('disabled', true)
}
repoList = []
$('.repoDropdown').empty()
$('.repoDropdown').append('<li class="dropdown-header dropdown-header-used">Last Used</li>')
$('.repoDropdown').append('<li class="dropdown-header dropdown-header-rest">The Rest</li>')
await getRepos(`${githubApiUrl}user/repos?per_page=100`)
}
function compileRepositoryList(mainRepoList, searchTerm) {
chrome.storage.sync.get(
{
mostUsed: [],
},
(item) => {
if (item.mostUsed && item.mostUsed.length > 0) {
$('.quickClone').attr('data-repo', item.mostUsed[0])
$('.quickClone').text(`Clone to ${item.mostUsed[0].substring(item.mostUsed[0].indexOf('/') + 1)}`)
$('.dropdown-header-used').addClass('active')
let mostUsed = item.mostUsed
if (searchTerm && searchTerm !== '') {
mostUsed = item.mostUsed.filter((item) => {
return item.indexOf(searchTerm) > -1
})
}
if (!mostUsed || mostUsed.length === 0) {
$('.dropdown-header-used').removeClass('active')
}
mostUsed.forEach((fullRepositoryName) => {
addRepoToList(fullRepositoryName, 'used')
mainRepoList = mainRepoList.filter((i) => {
return i.full_name !== fullRepositoryName
})
})
} else {
$('.dropdown-header-used').removeClass('active')
$('.quickClone').text('Clone to')
}
if (!mainRepoList || mainRepoList.length === 0) {
$('.dropdown-header-rest').removeClass('active')
} else {
$('.dropdown-header-rest').addClass('active')
}
mainRepoList.forEach((repo) => {
addRepoToList(repo.full_name)
})
}
)
}
function searchRepositories(searchTerm) {
var repositoryMatches = repoList.filter((item) => {
return item.full_name.indexOf(searchTerm) > -1
})
$('.repoDropdown :not(.dropdown-header)').remove()
$('.dropdown-header-used').removeClass('active')
$('.dropdown-header-rest').removeClass('active')
compileRepositoryList(repositoryMatches, searchTerm)
}
async function getGithubIssue(repo, closeOriginal) {
const { currentRepo, error, githubApiUrl: currentGithubApiUrl, issueNumber, organization } = populateUrlMetadata(
document.location.href
)
if (error) {
return
}
githubApiUrl = currentGithubApiUrl
const repoName = repo.split('/')[1]
// Make the assumption that if users are using Kamino, then enable issues for the repo.
// Otherwise Kamino will not function
await ajaxRequest('PATCH', { has_issues: true, name: repoName }, `${githubApiUrl}repos/${repo}`)
const issue = await ajaxRequest(
'GET',
'',
`${githubApiUrl}repos/${organization}/${currentRepo}/issues/${issueNumber}`
)
await createGithubIssue(repo, issue.data, closeOriginal)
}
function getSyncStorage(defaults) {
return new Promise((resolve) => {
chrome.storage.sync.get(defaults, resolve)
})
}
function getDatePart(timestamp) {
return timestamp ? timestamp.split('T')[0] : ''
}
function applyCloneTextOptions(text, options) {
let updatedText = text
if (options.preventMentions) {
updatedText = preventMentions(updatedText)
}
if (options.preventReferences) {
updatedText = preventReferences(updatedText)
}
return updatedText
}
function formatClonedBody(body, options) {
if (!body) {
return ''
}
return options.addBlockquote ? addBlockQuote(body) : body
}
function createClonedIssueBody(oldIssue, sourceIssueReference, options) {
const clonedBody = formatClonedBody(oldIssue.body, options)
if (!options.addBlockquote) {
return applyCloneTextOptions(clonedBody, options)
}
const createdAt = getDatePart(oldIssue.created_at)
const attribution = `**[<img src="https://avatars.githubusercontent.com/u/${oldIssue.user.id}?s=17&v=4" width="17" height="17"> ${oldIssue.user.login}](${oldIssue.user.html_url})** cloned issue [${sourceIssueReference}](${oldIssue.html_url}) on ${createdAt}:`
const newIssueBody = `${attribution}${clonedBody ? ` \n\n${clonedBody}` : ''}`
return applyCloneTextOptions(newIssueBody, options)
}
function createClonedCommentBody(comment, options) {
const clonedBody = formatClonedBody(comment.body, options)
if (!options.addBlockquote) {
return applyCloneTextOptions(clonedBody, options)
}
const createdAt = getDatePart(comment.created_at)
const attribution = `**[<img src="https://avatars.githubusercontent.com/u/${comment.user.id}?s=17&v=4" width="17" height="17"> ${comment.user.login}](${comment.user.html_url})** [commented](${comment.html_url}) on ${createdAt}:`
const newCommentBody = `${attribution}${clonedBody ? ` \n\n${clonedBody}` : ''}`
return applyCloneTextOptions(newCommentBody, options)
}
async function createGithubIssue(repo, oldIssue, closeOriginal) {
const { currentRepo, error, githubApiUrl: currentGithubApiUrl, issueNumber, organization } = populateUrlMetadata(
document.location.href
)
if (error) {
return
}
githubApiUrl = currentGithubApiUrl
const options = await getSyncStorage({
addBlockquote: true,
preventMentions: false,
preventReferences: false,
})
const newIssue = {
title: oldIssue.title,
body: createClonedIssueBody(oldIssue, `${organization}/${currentRepo}#${issueNumber}`, options),
labels: oldIssue.labels,
}
const response = await ajaxRequest('POST', newIssue, `${githubApiUrl}repos/${repo}/issues`)
await cloneOldIssueComments(
response.data.number,
repo,
`${githubApiUrl}repos/${organization}/${currentRepo}/issues/${issueNumber}/comments?per_page=100`
)
await commentOnIssue(repo, response.data, closeOriginal)
return response
}
async function cloneOldIssueComments(newIssue, repo, url) {
const options = await getSyncStorage({
addBlockquote: true,
cloneComments: false,
preventMentions: false,
preventReferences: false,
})
if (!options.cloneComments) {
return null
}
const response = await ajaxRequest('GET', '', url)
if (!response || !response.data || response.data.length === 0) {
return response
}
for (const current of response.data) {
const comment = {
body: createClonedCommentBody(current, options),
}
await ajaxRequest('POST', comment, `${githubApiUrl}repos/${repo}/issues/${newIssue}/comments`)
}
return response
}
async function closeGithubIssue() {
const issueToClose = {
state: 'closed',
}
const { currentRepo, error, githubApiUrl: currentGithubApiUrl, issueNumber, organization } = populateUrlMetadata(
document.location.href
)
if (error) {
return
}
githubApiUrl = currentGithubApiUrl
await ajaxRequest('PATCH', issueToClose, `${githubApiUrl}repos/${organization}/${currentRepo}/issues/${issueNumber}`)
}
async function commentOnIssue(repo, newIssue, closeOriginal) {
const {
currentRepo,
error,
githubApiUrl: currentGithubApiUrl,
issueNumber,
organization,
} = populateUrlMetadata(document.location.href)
if (error) {
return
}
githubApiUrl = currentGithubApiUrl
const newIssueLink = `[${repo}](${newIssue.html_url})`
const comment = {
body: closeOriginal
? `Kamino closed and cloned this issue to ${newIssueLink}`
: `Kamino cloned this issue to ${newIssueLink}`,
}
const item = await getSyncStorage({
disableCommentsOnOriginal: false,
})
if (!item.disableCommentsOnOriginal) {
await ajaxRequest('POST', comment, `${githubApiUrl}repos/${organization}/${currentRepo}/issues/${issueNumber}/comments`)
}
if (closeOriginal) {
await closeGithubIssue()
}
goToIssueList(repo, newIssue.number, organization, currentRepo)
}
function goToIssueList(repo, issueNumber, org, oldRepo) {
const { githubOrigin } = populateUrlMetadata(document.location.href)
chrome.runtime.sendMessage(
{ repo: repo, issueNumber: issueNumber, organization: org, oldRepo: oldRepo, githubOrigin },
() => {}
)
}
function delay(milliseconds) {
return new Promise((resolve) => setTimeout(resolve, milliseconds))
}
function shouldRetryAjax(xhr, textStatus) {
if (textStatus === 'timeout') {
return true
}
if (!xhr) {
return false
}
if ([429, 502, 503, 504].includes(xhr.status)) {
return true
}
return xhr.status === 403
}
function makeAjaxRequest(settings) {
return new Promise((resolve, reject) => {
$.ajax(settings)
.done((data, status, header) => {
resolve({
data: data,
status: status,
header: header,
})
})
.fail((xhr, textStatus, errorThrown) => {
reject({ xhr, textStatus, errorThrown })
})
})
}
async function ajaxRequest(type, data, url, options = {}) {
const item = await getSyncStorage({
githubToken: '',
})
const retryLimit = options.retryLimit ?? 3
token = item.githubToken
for (let attempt = 0; attempt <= retryLimit; attempt += 1) {
try {
return await makeAjaxRequest({
type: type,
beforeSend: (request) => {
request.setRequestHeader('Authorization', `token ${token}`)
request.setRequestHeader('Content-Type', 'application/json')
},
data: JSON.stringify(data),
timeout: options.timeout ?? 30000,
url: url,
})
} catch (error) {
if (attempt === retryLimit || !shouldRetryAjax(error.xhr, error.textStatus)) {
throw error
}
await delay(1000 * (attempt + 1))
}
}
}
function addRepoToList(repoFullName, section) {
// replace slashes and periods because they aren't valid HTML ids
const periodReplace = repoFullName.replace(/\./g, '_').replace(/\//g, '_')
const listItem = `<li data-toggle="modal" id="${periodReplace}" data-target="#kaminoModal"><a class="repoItem" href="#" title="${repoFullName}">${repoFullName}</a></li>`
if (section === 'used') {
if ($(`#${periodReplace}`).length === 0) {
$('.dropdown-header-rest').before(listItem)
}
} else {
$('.repoDropdown').append(listItem)
}
$(`#${periodReplace}`).bind('click', () => {
itemClick(repoFullName)
})
}
function addToMostUsed(repo) {
chrome.storage.sync.get(
{
mostUsed: [],
},
(item) => {
if (
item.mostUsed.find((e) => {
return e === repo
})
) {
const index = item.mostUsed.indexOf(repo)
item.mostUsed.splice(index, 1)
item.mostUsed.unshift(repo)
if (item.mostUsed.length > 5) {
item.mostUsed.pop()
}
} else {
item.mostUsed.unshift(repo)
if (item.mostUsed.length > 5) {
item.mostUsed.pop()
}
}
chrome.storage.sync.set({
mostUsed: item.mostUsed,
})
}
)
}
function openDropdown() {
if ($('.btn-group').hasClass('open')) {
$('.btn-group').removeClass('open')
} else {
$('.btn-group').addClass('open')
}
}
function itemClick(repo) {
addToMostUsed(repo)
$('.cloneAndClose').attr('data-repo', repo)
$('.cloneAndKeepOpen').attr('data-repo', repo)
$('.confirmText').text(
`Are you sure you want to clone this issue to ${repo}? Choose whether to clone and close or clone and keep the original issue open.`
)
toggleModal(true)
}
function toggleModal(open) {
if (open) {
$('#kaminoModal').addClass('in')
$('#kaminoModal').css('display', 'block')
} else {
$('#kaminoModal').removeClass('in')
$('#kaminoModal').css('display', '')
}
}