-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathMergeDependabotPRs.user.js
392 lines (362 loc) · 11.1 KB
/
MergeDependabotPRs.user.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
// ==UserScript==
// @name Auto-Merge Dependabot PRs
// @namespace typpi.online
// @version 2.0
// @description Merges Dependabot PRs in any of your repositories - pulls the PRs into a table and lets you select which ones to merge.
// @author Nick2bad4u
// @match https://github.com/notifications
// @match https://github.com/*/*/pull/*
// @grant GM_xmlhttpRequest
// @grant GM_addStyle
// @grant GM_getValue
// @grant GM_setValue
// @connect api.github.com
// @license UnLicense
// @icon https://www.google.com/s2/favicons?sz=64&domain=github.com
// @homepageURL https://github.com/Nick2bad4u/UserStyles
// @supportURL https://github.com/Nick2bad4u/UserStyles/issues
// ==/UserScript==
/* global GM_getValue, GM_setValue, GM_xmlhttpRequest */
// @var number merge_delay "Delay between merge requests in milliseconds" 2000
(async function () {
'use strict';
// Delay between each merge request in milliseconds, default is 2000ms
let delay = GM_getValue('merge_delay', 2000);
if (isNaN(delay) || Number(delay) <= 0) {
delay = 2000; // default value if invalid
} else {
delay = Number(delay);
}
async function initialize() {
let token;
try {
// Attempt to retrieve and decrypt the GitHub token
token = await retrieveAndDecryptToken();
} catch (error) {
console.error('Failed to retrieve and decrypt token:', error);
alert('Failed to retrieve and decrypt token. Please check the console for more details.');
return;
}
// Prompt the user for the token if it was not successfully retrieved
if (!token) {
while (!token) {
token = prompt('Please enter your GitHub token:');
if (!token) {
alert('GitHub token is required.');
}
}
// Encrypt and store the token if it was provided
if (token) {
try {
await encryptAndStoreToken(token);
} catch (error) {
console.error('Failed to encrypt and store token:', error);
alert('Failed to encrypt and store token. Please check the console for more details.');
return;
}
} else {
alert('GitHub token is required.');
return;
}
}
// Retrieve the GitHub username from storage or prompt the user for it
let username = GM_getValue('github_username');
while (!username) {
username = prompt('Please enter your GitHub username:');
if (username) {
GM_setValue('github_username', username);
} else {
alert('GitHub username is required.');
}
}
// Retrieve the GitHub repository name from storage or prompt the user for it
let repo = GM_getValue('github_repo');
while (!repo) {
repo = prompt('Please enter your GitHub repository name:');
if (repo) {
GM_setValue('github_repo', repo);
} else {
alert('GitHub repository name is required.');
}
}
}
await initialize();
async function encryptAndStoreToken(token) {
try {
// Create a new TextEncoder instance to encode the token
const textEncoder = new TextEncoder();
const encodedToken = textEncoder.encode(token);
let key;
// Retrieve the stored encryption key from storage
const storedKey = GM_getValue('encryption_key', null);
if (storedKey) {
// If a key is already stored, import it for use
key = await crypto.subtle.importKey(
'jwk',
JSON.parse(storedKey),
{
name: 'AES-GCM',
},
true,
['encrypt', 'decrypt'],
);
} else {
// If no key is stored, generate a new one
key = await crypto.subtle.generateKey(
{
name: 'AES-GCM',
length: 256,
},
true,
['encrypt', 'decrypt'],
);
// Store the newly generated key
GM_setValue('encryption_key', JSON.stringify(await crypto.subtle.exportKey('jwk', key)));
}
// Create a random initialization vector (iv)
const iv = crypto.getRandomValues(new Uint8Array(12));
// Encrypt the token using the imported or generated key and the iv
const encryptedToken = await crypto.subtle.encrypt(
{
name: 'AES-GCM',
iv: iv,
},
key,
encodedToken,
);
// Store the encrypted token and iv in storage
GM_setValue(
'github_token',
JSON.stringify({
iv: Array.from(iv),
token: Array.from(new Uint8Array(encryptedToken)),
}),
);
} catch (error) {
console.error('Failed to encrypt and store token:', error);
}
}
async function retrieveAndDecryptToken() {
try {
// Retrieve the stored encrypted token and encryption key from storage
const storedData = GM_getValue('github_token', null);
if (!storedData) return '';
// Parse the stored data to extract the initialization vector (iv) and the token
const { key, iv, token } = JSON.parse(storedData);
// Import the encryption key for decryption
const importedKey = await crypto.subtle.importKey(
'jwk',
key,
{
name: 'AES-GCM',
},
true,
['decrypt'],
);
// Decrypt the token using the imported key and initialization vector
const decryptedToken = await crypto.subtle.decrypt(
{
name: 'AES-GCM',
iv: new Uint8Array(iv),
},
importedKey,
new Uint8Array(token),
);
// Decode the decrypted token into a string and return it
const textDecoder = new TextDecoder();
return textDecoder.decode(decryptedToken);
} catch (error) {
console.error('Failed to retrieve and decrypt token:', error);
return '';
}
}
async function fetchDependabotPRs(username, repo, token) {
return new Promise((resolve, reject) => {
GM_xmlhttpRequest({
method: 'GET',
url: `https://api.github.com/repos/${username}/${repo}/pulls?per_page=100&state=open&user=dependabot[bot]`,
headers: {
Authorization: `token ${token}`,
},
onload: function (response) {
if (response.status === 200) {
const pulls = JSON.parse(response.responseText);
resolve(pulls);
} else {
reject(new Error(`Failed to fetch pull requests: ${response.responseText}`));
}
},
onerror: function (error) {
reject(error);
},
});
});
}
async function mergeDependabotPRs(prs, username, repo, token) {
const statusContainer = document.getElementById('merge-status');
let index = 0;
async function processNextPR() {
if (index < prs.length) {
const pr = prs[index];
try {
await mergePR(pr, username, repo, token);
const messageElement = document.createElement('div');
messageElement.innerHTML = `PR #${pr.number} merged successfully!<br>`;
statusContainer.appendChild(messageElement);
setTimeout(() => messageElement.remove(), 7000);
} catch (error) {
const messageElement = document.createElement('div');
messageElement.innerHTML = `Failed to merge PR #${pr.number}: ${error.message}<br>`;
statusContainer.appendChild(messageElement);
setTimeout(() => messageElement.remove(), 7000);
}
index++;
setTimeout(processNextPR, delay);
}
}
processNextPR();
}
function mergePR(pr, username, repo, token) {
return new Promise((resolve, reject) => {
GM_xmlhttpRequest({
method: 'PUT',
url: `https://api.github.com/repos/${username}/${repo}/pulls/${pr.number}/merge`,
headers: {
Authorization: `token ${token}`,
'Content-Type': 'application/json',
},
data: JSON.stringify({
commit_title: `Merge PR #${pr.number}`,
merge_method: 'merge',
}),
onload: function (response) {
if (response.status === 200) {
resolve();
} else {
reject(new Error(response.responseText));
}
},
onerror: function (error) {
reject(error);
},
});
});
}
function addButton() {
const mergeButton = document.createElement('mergebutton');
mergeButton.textContent = 'Merge Dependabot PRs';
mergeButton.style = 'position: fixed; bottom: 10px; right: 10px; z-index: 1000;';
mergeButton.addEventListener('click', async () => {
try {
const token = await retrieveAndDecryptToken();
if (!token) {
alert('Invalid or missing GitHub token. Please check your settings.');
return;
}
const username = GM_getValue('github_username');
const repo = GM_getValue('github_repo');
const prs = await fetchDependabotPRs(username, repo, token);
if (prs.length > 0) {
displayPRSelection(prs, username, repo, token);
} else {
displayNoPRsMessage();
}
} catch (error) {
console.error('Error during merge operation:', error);
}
});
document.body.appendChild(mergeButton);
}
function displayPRSelection(prs, username, repo, token) {
const container = document.createElement('div');
style.textContent += `
.pr-selection-container {
position: fixed;
bottom: 50px;
right: 10px;
z-index: 1000;
background-color: #79e4f2;
color: #000000;
padding: 10px;
border: 1px solid #ccc;
max-height: 300px;
overflow-y: auto;
}
`;
container.classList.add('pr-selection-container');
const prList = document.createElement('div');
prs.forEach((pr) => {
const prItem = document.createElement('div');
const checkbox = document.createElement('input');
checkbox.type = 'checkbox';
checkbox.value = pr.number;
const label = document.createElement('label');
label.textContent = `PR #${pr.number}: ${pr.title}`;
label.style = 'margin-left: 5px;';
prItem.appendChild(checkbox);
prItem.appendChild(label);
prList.appendChild(prItem);
});
const mergeSelectedButton = document.createElement('button');
mergeSelectedButton.textContent = 'Merge Selected PRs';
mergeSelectedButton.addEventListener('click', async () => {
const selectedPRs = Array.from(prList.querySelectorAll('input:checked')).map((input) => prs.find((pr) => pr.number == input.value));
if (selectedPRs.length > 0) {
container.innerHTML = '<div id="merge-status">Merging PRs...<br></div>';
await mergeDependabotPRs(selectedPRs, username, repo, token);
} else {
container.innerHTML = 'No PRs selected for merging.';
}
});
container.appendChild(prList);
container.appendChild(mergeSelectedButton);
document.body.appendChild(container);
}
function displayNoPRsMessage() {
const container = document.createElement('div');
container.classList.add('pr-container');
container.textContent = 'No Dependabot PRs found to merge.';
document.body.appendChild(container);
// Automatically hide the message after 5 seconds (5000 milliseconds)
setTimeout(() => {
container.remove();
}, 5000);
}
const style = document.createElement('style');
style.textContent = `
mergebutton, body > div.pr-selection-container > button {
background-color: #2ea44f;
color: #ffffff;
border: none;
padding: 10px;
border-radius: 5px;
cursor: pointer;
}
mergebutton:hover {
background-color: #79e4f2;
color: #ffffff;
border: none;
padding: 10px;
border-radius: 5px;
cursor: pointer;
}
#merge-status {
margin-top: 10px;
font-size: 0.9em;
color: #333;
background-color: #79e4f2;
}
.pr-container {
background-color: #ff0000;
color: #ffffff;
position: fixed;
bottom: 50px;
right: 10px;
z-index: 1000;
padding: 10px;
border: 1px solid #cccccc;
}
`;
document.head.appendChild(style);
window.addEventListener('load', addButton);
})();