-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
498 lines (491 loc) · 18.3 KB
/
index.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
#!/usr/bin/env node
const axios = require('axios');
const minimist = require('minimist');
const gitlabTagTrigger = require('./package.json');
/**
* Create new issue on gitlab
* @param projectId
* @param token
* @param data
* @returns {*}
*/
const createNewIssue = (projectId, token, data) => {
const defaultRequest = {
title: '',
description: '',
confidential: false,
assignee_ids: null,
milestone_id: null,
labels: null,
created_at: null,
due_date: null,
merge_request_to_resolve_discussions_of: null,
discussion_to_resolve: null,
weight: null
};
const requestData = Object.assign(defaultRequest, data);
const url = `https://gitlab.com/api/v4/projects/${projectId}/issues`;
return axios({
method: 'POST',
url,
headers: {
'Content-Type': 'application/json',
'PRIVATE-TOKEN': token
},
data: requestData,
responseType: 'json'
}).then(rs => rs.data);
};
/**
* Create new branch on gitlab from ref
* @param projectId
* @param token
* @param data
* @returns {*}
*/
const createNewBranch = (projectId, token, data) => {
const url = `https://gitlab.com/api/v4/projects/${projectId}/repository/branches`;
return axios({
method: 'POST',
url,
headers: {
'Content-Type': 'application/json',
'PRIVATE-TOKEN': token
},
data,
responseType: 'json'
}).then(rs => rs.data);
};
/**
* Create new merge request from commit, branch, ref
* @param projectId
* @param token
* @param data
* @returns {*}
*/
const createNewMergeRequest = (projectId, token, data) => {
const url = `https://gitlab.com/api/v4/projects/${projectId}/merge_requests`;
return axios({
method: 'POST',
url,
headers: {
'Content-Type': 'application/json',
'PRIVATE-TOKEN': token
},
data,
responseType: 'json'
}).then(rs => rs.data);
};
/**
* Accept merge request and merge into master
* @param projectId
* @param token
* @param mergeRequestIID
* @param sha
* @returns {*}
*/
const accpetMergeRequest = (projectId, token, mergeRequestIID, sha) => {
const url = `https://gitlab.com/api/v4/projects/${projectId}/merge_requests/${mergeRequestIID}/merge`;
return axios({
method: 'PUT',
url,
headers: {
'Content-Type': 'application/json',
'PRIVATE-TOKEN': token
},
data: { sha },
responseType: 'json'
}).then(rs => rs.data);
};
/**
* Accept merge request and merge into master
* @param projectId
* @param token
* @param issueIID
* @returns {*}
*/
const closeIssue = (projectId, token, issueIID) => {
const url = `https://gitlab.com/api/v4/projects/${projectId}/issues/${issueIID}?state_event=close`;
return axios({
method: 'PUT',
url,
headers: {
'Content-Type': 'application/json',
'PRIVATE-TOKEN': token
},
responseType: 'json'
}).then(rs => rs.data);
};
/**
* Get raw content of file from filename
* @param projectId
* @param token
* @param data
* @returns {*}
*/
const getRawFile = (projectId, token, data) => {
const url =
`https://gitlab.com/api/v4/projects/${projectId}/repository/files/${data.filename}/raw?ref=${data.ref}`;
return axios({
method: 'GET',
url,
headers: {
'Content-Type': 'application/json',
'PRIVATE-TOKEN': token
},
responseType: 'text',
transformResponse: [txt => txt]
}).then(rs => rs.data);
};
/**
* Create commit of change files
* @param projectId
* @param token
* @param data
* @returns {*}
*/
const createNewCommitPackageJson = (projectId, token, data) => {
const requestData = {
branch: data.branch,
commit_message: data.commitMessage,
author_email: data.authorEmail,
author_name: data.authorName,
actions: data.actions
};
const url = `https://gitlab.com/api/v4/projects/${projectId}/repository/commits`;
return axios({
method: 'POST',
url,
headers: {
'Content-Type': 'application/json',
'PRIVATE-TOKEN': token
},
data: requestData,
responseType: 'json'
}).then(rs => rs.data);
};
/**
* Get options from argument
* Exit the program when arg do not have -v, -p, and -f
* @param {any} args
* @returns {object}
*/
const parseArgs = (args) => {
const opts = minimist(args);
if (opts.i || opts.o || opts.s || opts.u) {
if (!opts.i || !opts.o || !opts.s || !opts.u || !opts.t || !opts.m) {
console.error(`Gitlab Tag Trigger v${gitlabTagTrigger.version}
Command error
for UPDATE FILE, use with args:
-v [name of tag to update]
-i [source file path]
-o [destination file path]
-o [source project ID]
-u [list of project id will be update , separate by comma]
-t [token from gitlab]
-m [true or false - is auto merge into master]
-a [assignee_id - user assigne for merge request]
Example: gitlab-tag-trigger -i lib/test.js -o lib/test.js -s 5265616 -u 5265594 -t 11mHNS3Fzb4rvhy2sKyk -m true -a 198381
for UPDATE package.json, use with args:
-l [name of library]
-v [name of tag to update]
-p [list of project id will be update , separate by comma]
-t [token from gitlab]
-m [true or false - is auto merge into master]
-a [assignee_id - user assigne for merge request]
Example: gitlab-tag-trigger -l lib-test-ci -v v1.3.3 -p 5265594,5297794 -t 11mHNS3Fzb4rvhy2sKyk -m true -a 198381
`);
process.exit(1);
}
return opts;
}
if (!opts.l || !opts.v || !opts.p || !opts.t || !opts.m) {
console.error(`Gitlab Tag Trigger v${gitlabTagTrigger.version}
Command error
for UPDATE FILE, use with args:
-v [name of tag to update]
-i [source file path]
-o [destination file path]
-o [source project ID]
-u [list of project id will be update , separate by comma]
-t [token from gitlab]
-m [true or false - is auto merge into master]
-a [assignee_id - user assigne for merge request]
Example: gitlab-tag-trigger -i lib/test.js -o lib/test.js -s 5265616 -u 5265594 -t 11mHNS3Fzb4rvhy2sKyk -m true -a 198381
for UPDATE package.json, use with args:
-l [name of library]
-v [name of tag to update]
-p [list of project id will be update , separate by comma]
-t [token from gitlab]
-m [true or false - is auto merge into master]
-a [assignee_id - user assigne for merge request]
Example: gitlab-tag-trigger -l lib-test-ci -v v1.3.3 -p 5265594,5297794 -t 11mHNS3Fzb4rvhy2sKyk -m true -a 198381
`);
process.exit(1);
}
return opts;
};
/**
* Main function
* @returns {Promise.<void>}
*/
const updatePackageJSON =
(projectId,
token,
libraryName,
tagName,
merge,
assigneeId) => {
console.log('ProjectID:', projectId, `0. Start process Update ${libraryName} to ${tagName}`);
return getRawFile(projectId, token, {
filename: 'package.json',
ref: 'master'
}).then((packagejsonText) => {
const packagejson = JSON.parse(packagejsonText);
const currentVersion = packagejson.dependencies[libraryName];
if (!packagejson || !currentVersion) {
return console.log('ProjectID:', projectId, `ERROR: Not found current version of ${libraryName} in package.json on master branch`);
}
const issueData = {
title: `update version ${libraryName} to ${tagName}`,
description: `update version ${libraryName} to ${tagName} automation by ci`,
};
return createNewIssue(projectId, token, issueData).then((issueObject) => {
if (!issueObject) {
return console.log('ProjectID:', projectId, `ERROR: Fail to create new issue ${issueData.title}`);
}
console.log('ProjectID:', projectId, '1. Created new Issue success :', issueObject.title);
const issueIID = issueObject.iid;
const branchName = `${issueIID}-${issueObject.title.replace(/ /g, '-')}`;
return createNewBranch(projectId, token, {
branch: branchName,
ref: 'master'
}).then((branchObject) => {
if (!branchObject) {
return console.log('ProjectID:', projectId, `ERROR: Fail to create branch ${branchName}`);
}
console.log('ProjectID:', projectId, '2. Created new Branch success :', branchObject.name);
const tmpArr = currentVersion.split('#', 1);
packagejson.dependencies[libraryName] = `${tmpArr[0]}#${tagName}`;
return createNewCommitPackageJson(
projectId,
token, {
branch: branchName,
commitMessage: issueData.title,
authorName: 'gitlab-automation',
authorEmail: '[email protected]',
actions: [
{
action: 'update',
file_path: 'package.json',
content: JSON.stringify(packagejson, null, 2) + '\n',
encoding: 'text'
}
]
}
).then((commit) => {
if (!commit) {
return console.log('ProjectID:', projectId, 'ERROR: Fail to commit');
}
console.log('ProjectID:', projectId, '3. Created new Commit success :', commit.id);
return createNewMergeRequest(
projectId,
token,
{
source_branch: branchName,
target_branch: 'master',
title: `Resolve ${issueData.title}`,
assignee_id: assigneeId,
milestone_id: null,
labels: '',
description: `Closes #${issueIID}`,
state_event: null,
remove_source_branch: false,
squash: false,
discussion_locked: false
}
).then((mergeRequest) => {
if (!mergeRequest) {
return console.log('ProjectID:', projectId, 'ERROR: Fail to create merge request');
}
console.log('ProjectID:', projectId, '4. Created new Merge request success :', mergeRequest.title);
if (merge === 'true') {
return accpetMergeRequest(projectId, token, mergeRequest.iid, mergeRequest.sha)
.then((accept) => {
if (!accept) {
return console.log('ProjectID:', projectId, 'Accepted merge request fail');
}
console.log('ProjectID:', projectId, '5. Accepted new Merge request success :', accept.title);
return closeIssue(projectId, token, issueIID)
.then((closedIssue) => {
if (closedIssue) {
return console.log('ProjectID:', projectId, `6. Close Issue success : #${issueIID} ${closedIssue.title}`);
}
return console.log('projectIdToUpdate:', projectId, 'ERROR: Close Issue fail');
}).catch(err => console.log('ERROR closeIssue, projectId:', projectId, 'ERROR: ', err.message ? err.message : err));
}).catch(err => console.log('ERROR accpetMergeRequest, projectId:', projectId, 'ERROR: ', err.message ? err.message : err));
}
return null;
}).catch(err => console.log('ERROR createMergeRequest, projectId:', projectId, 'message: ', err.message ? err.message : err));
}).catch(err => console.log('ERROR createCommit, projectId:', projectId, 'message: ', err.message ? err.message : err));
}).catch(err => console.log('ERROR createNewBranch, projectId:', projectId, 'message: ', err.message ? err.message : err));
}).catch(err => console.log('ERROR createNewIssue, projectId:', projectId, 'message: ', err.message ? err.message : err));
}).catch(err => console.log('ERROR getRawFile, projectID: ', projectId, ' message: ', err.message ? err.message : err));
};
/**
* Main function
* @returns {Promise.<void>}
*/
const updateFile =
(projectIdSource,
projectIdToUpdate,
sourceFilePath,
updateFilePath,
token,
tagName,
merge, assigneeId) => {
console.log('ProjectID:', projectIdToUpdate, `0. Start process Update file : ${updateFilePath} ${tagName}`);
return getRawFile(projectIdSource, token, {
filename: encodeURIComponent(sourceFilePath),
ref: tagName
}).then((fileContent) => {
if (!fileContent) {
return console.log('projectIdSource:', projectIdSource, `ERROR: File ${sourceFilePath} doesn't exist on master branch`);
}
const issueData = {
title: `update filename ${updateFilePath} to ${tagName}`,
description: `update filename ${updateFilePath} automation by ci`,
};
return createNewIssue(projectIdToUpdate, token, issueData).then((issueObject) => {
if (!issueObject) {
return console.log('projectIdToUpdate:', projectIdToUpdate, `ERROR: Fail to create new issue ${issueData.title}`);
}
console.log('projectIdToUpdate:', projectIdToUpdate, '1. Created new Issue success :', issueObject.title);
const issueIID = issueObject.iid;
let branchName = `${issueIID}-${issueObject.title.replace(/ /g, '-')}`;
branchName = branchName.replace(/\//g, '-');
return createNewBranch(projectIdToUpdate, token, {
branch: branchName,
ref: 'master'
}).then((branchObject) => {
if (!branchObject) {
return console.log('projectIdToUpdate:', projectIdToUpdate, `ERROR: Fail to create branch ${branchName}`);
}
console.log('projectIdToUpdate:', projectIdToUpdate, '2. Created new Branch success :', branchObject.name);
const requestUpdate = {
branch: branchName,
commitMessage: issueData.title,
authorName: 'gitlab-automation',
actions: [
{
action: 'update',
file_path: updateFilePath,
content: fileContent,
encoding: 'text'
}
]
};
return createNewCommitPackageJson(
projectIdToUpdate,
token, requestUpdate
).then((commit) => {
if (!commit) {
return console.log('projectIdToUpdate:', projectIdToUpdate, 'ERROR: Fail to commit');
}
console.log('projectIdToUpdate:', projectIdToUpdate, '3. Created new Commit success :', commit.id);
return createNewMergeRequest(
projectIdToUpdate,
token,
{
source_branch: branchName,
target_branch: 'master',
title: `Resolve ${issueData.title}`,
assignee_id: assigneeId,
milestone_id: null,
labels: '',
description: `Closes #${issueIID}`,
state_event: null,
remove_source_branch: false,
squash: false,
discussion_locked: false
}
).then((mergeRequest) => {
if (!mergeRequest) {
return console.log('projectIdToUpdate:', projectIdToUpdate, 'ERROR: Fail to create merge request');
}
console.log('projectIdToUpdate:', projectIdToUpdate, '4. Created new Merge request success :', mergeRequest.title);
if (merge === 'true') {
return accpetMergeRequest(
projectIdToUpdate,
token,
mergeRequest.iid,
mergeRequest.sha
)
.then((accept) => {
if (!accept) {
return console.log('projectIdToUpdate:', projectIdToUpdate, 'Accepted merge request fail');
}
console.log('projectIdToUpdate:', projectIdToUpdate, '5. Accepted new Merge request success :', accept.title);
return closeIssue(projectIdToUpdate, token, issueIID)
.then((closedIssue) => {
if (closedIssue) {
return console.log('projectIdToUpdate:', projectIdToUpdate, `6. Close Issue success : #${issueIID} ${closedIssue.title}`);
}
return console.log('projectIdToUpdate:', projectIdToUpdate, 'ERROR: Close Issue fail');
}).catch(err => console.log('ERROR closeIssue, projectId:', projectIdToUpdate, 'ERROR: ', err.message ? err.message : err));
}).catch(err => console.log('ERROR accpetMergeRequest, projectId:', projectIdToUpdate, 'ERROR: ', err.message ? err.message : err));
}
return null;
}).catch(err => console.log('ERROR createMergeRequest, projectId:', projectIdToUpdate, 'message: ', err.message ? err.message : err));
}).catch(err => console.log('ERROR createCommit, projectId:', projectIdToUpdate, 'message: ', err.message ? err.message : err));
}).catch(err => console.log('ERROR createNewBranch, projectId:', projectIdToUpdate, 'message: ', err.message ? err.message : err));
}).catch(err => console.log('ERROR createNewIssue, projectId:', projectIdToUpdate, 'message: ', err.message ? err.message : err));
}).catch(err => console.log('ERROR getRawFile, projectID: ', projectIdToUpdate, ' message: ', err.message ? err.message : err));
};
/**
* UPDATE package.json
* -l Library name to update in package.json
* -v Tag name to update
* -p List of projectId to update package.json separate by comma
* -t Access Token
* -m Is auto merge ? true or false
* UPDATE FILE
* -i Source file path
* -o Destination file path
* -s Source project ID
* -u Destination project ID
*/
const opts = parseArgs(process.argv.slice(2));
const token = opts.t;
const merge = opts.m;
const assigneeId = opts.a;
if (opts.i && opts.i !== '') {
const sourceFilePath = opts.i;
const updateFilePath = opts.o;
const projectIdSource = opts.s;
const projectIdToUpdate = opts.u.toString().split(',');
const tagName = opts.v || 'master';
Promise
.all(
projectIdToUpdate.map(
pId => updateFile(projectIdSource, pId, sourceFilePath, updateFilePath, token, tagName, merge, assigneeId)
)
)
.then(() => console.log('Done !'))
.catch(err => console.log('ERROR: ', err));
} else {
const libraryName = opts.l;
const tagName = opts.v;
const projectIds = opts.p.toString().split(',');
Promise
.all(projectIds.map(projectId => updatePackageJSON(
projectId,
token,
libraryName,
tagName,
merge,
assigneeId
)))
.then(() => console.log('Done !'))
.catch(err => console.log('ERROR: ', err));
}