-
Notifications
You must be signed in to change notification settings - Fork 46
/
index.js
executable file
·734 lines (670 loc) · 21.4 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
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
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
#!/usr/bin/env node
require('dotenv').config()
var program = require('commander')
var childProcess = require('child_process')
var colors = require('colors')
var { Gitlab } = require('@gitbeaker/node')
var editor = require('editor')
var exec = childProcess.exec
var fs = require('fs')
var legacies = {}
var open = require('open')
var projectDir = process.cwd()
var Promise = require('promise')
var URL = require('url')
var options = require('./options')
var packageJson = require('./package.json')
var regexParseProjectName = /(.+:\/\/.+?\/|.+:)(.+\/[^\.]+)+(\.git)?/
var gitlab = new Gitlab(options)
gitlab.options = options
var store = (function() {
return {
set: function(obj) {
Object.assign(this, obj)
},
get: function(key) {
return this[key]
},
}
})()
var log = {
getInstance: function(verbose) {
return {
log: function() {
if (verbose) {
console.log.apply(console, arguments)
}
},
}
},
}
var allRemotes = null
//Will be assigned value after parsing of options
var logger = null
function getMergeRequestTitle(title) {
logger.log('\nGetting merge request title. Argument provided : ' + title)
var promise = new Promise(function(resolve /*, reject*/) {
if (title) {
logger.log('Title obtained with -m option: ' + title.green)
resolve(title)
} else {
exec('git rev-parse --show-toplevel', function(
error,
repoDir /*, stderr*/
) {
var filePath = repoDir.trim() + '/.git/PULL_REQUEST_TITLE'
exec(
'git log -1 --pretty=%B > ' + filePath,
function(/*error, remote, stderr*/) {
exec('git config core.editor', function(
error,
gitEditor /*, stderr*/
) {
editor(
filePath,
{ editor: gitEditor.trim() || null },
function(/*code, sig*/) {
fs.readFile(filePath, 'utf8', function(err, data) {
title = data
logger.log('Input obtained using editor: ' + title.green)
resolve(title)
})
}
)
})
}
)
})
}
})
return promise
}
function getAllRemotes() {
var promise = new Promise(function(resolve /*, reject*/) {
if (allRemotes) {
resolve(allRemotes)
return
}
exec('git remote', { cwd: projectDir }, function(
error,
allRemotes /*, stderr*/
) {
if (error) {
logger.log(colors.red('Error occurred :\n'), colors.red(error))
process.exit(1)
}
allRemotes = allRemotes.split('\n')
resolve(allRemotes)
})
})
return promise
}
function parseBranchRemoteInfo(branchName) {
var promise = new Promise(function(resolve /*, reject*/) {
if (branchName.indexOf('/') != -1) {
getAllRemotes().then(function(allRemotes) {
var splits = branchName.split('/')
var maybeRemote = splits[0].trim()
var remoteName = null
if (allRemotes.indexOf(maybeRemote) != -1) {
branchName = splits.slice(1).join('/')
remoteName = maybeRemote
}
logger.log('Branch name obtained :', branchName.green)
resolve({
branch: branchName,
remote: remoteName,
})
})
} else {
resolve({
branch: branchName,
})
}
})
return promise
}
function getBaseBranchName(baseBranchName) {
logger.log('\nGetting base branch name : ')
var promise = new Promise(function(resolve /*, reject*/) {
if (baseBranchName) {
logger.log('Argument provided : ' + baseBranchName)
parseBranchRemoteInfo(baseBranchName).then(function(branchRemoteInfo) {
logger.log('Base branch name obtained :', branchRemoteInfo.branch.green)
resolve(branchRemoteInfo.branch)
})
} else {
logger.log('Executing git rev-parse --abbrev-ref HEAD')
exec('git rev-parse --abbrev-ref HEAD', { cwd: projectDir }, function(
error,
stdout /*, stderr*/
) {
if (error) {
logger.log(colors.red('Error occured :\n'), colors.red(error))
process.exit(1)
}
var curBranchName = stdout.replace('\n', '')
logger.log('Base branch name obtained :', curBranchName.green)
resolve(curBranchName)
})
}
})
return promise
}
function getTargetBranchName(branchName) {
var promise = new Promise(function(resolve /*, reject*/) {
parseBranchRemoteInfo(branchName).then(function(branchRemoteInfo) {
logger.log('Remote branch name obtained :', branchRemoteInfo.branch.green)
resolve(branchRemoteInfo.branch)
})
})
return promise
}
function getRemoteForBranch(branchName) {
logger.log('\nGetting remote of branch :', branchName)
var promise = new Promise(function(resolve /*, reject*/) {
parseBranchRemoteInfo(branchName).then(function(branchRemoteInfo) {
if (branchRemoteInfo.remote) {
//Remote info supplied in the branch name
logger.log('Remote obtained : ' + branchRemoteInfo.remote.green)
resolve(branchRemoteInfo.remote)
} else {
//Remote info is not supplied. Get it from remote set
logger.log(
'Executing git config branch.' + branchName.trim() + '.remote'
)
exec(
'git config branch.' + branchName.trim() + '.remote',
{ cwd: projectDir },
function(error, remote /*, stderr*/) {
if (error) {
console.error(
colors.red(
'Error occured while getting remote of the branch: ',
branchName,
'\n'
)
)
console.log(
'\n\nSet the remote tracking by `git branch --set-upstream-to=origin/' +
branchName +
'`. Assuming origin is your remote.'
)
console.log(
'Look at https://git-scm.com/docs/git-branch#Documentation/git-branch.txt---set-upstream for more details.'
)
console.log(
'\n\nBonus tip : You can avoid doing this each time by adding -u option while pushing to your origin.'
)
console.log('Eg: `git push origin ' + branchName + ' -u`')
process.exit(1)
}
logger.log('Remote obtained : ' + remote.green)
resolve(remote.trim())
}
)
}
})
})
return promise
}
function getURLOfRemote(remote) {
logger.log('\nGetting URL of remote : ' + remote)
var promise = new Promise(function(resolve /*, reject*/) {
logger.log('Executing ', 'git config remote.' + remote.trim() + '.url')
exec(
'git config remote.' + remote.trim() + '.url',
{ cwd: projectDir },
function(error, remoteURL /*, stderr*/) {
if (error) {
console.error(colors.red('Error occured :\n'), colors.red(error))
process.exit(1)
}
logger.log('URL of remote obtained : ' + remoteURL.green)
resolve(remoteURL.trim())
}
)
})
return promise
}
function browse(options) {
logger = log.getInstance(options.verbose)
getBaseBranchName().then(function(curBranchName) {
getRemoteForBranch(curBranchName).then(function(remote) {
if (!remote) {
console.error(
colors.red(
'Branch ' + curBranchName + ' is not tracked by any remote branch.'
)
)
console.log(
'Set the remote tracking by `git branch --set-upstream <branch-name> <remote-name>/<branch-name>`'
)
console.log('Eg: `git branch --set-upstream foo upstream/foo`')
}
getURLOfRemote(remote).then(function(remoteURL) {
var projectName = remoteURL.match(regexParseProjectName)[2]
var page = options.page || ''
if (page === '') {
open(
gitlab.options.host + '/' + projectName + '/tree/' + curBranchName
)
} else {
open(gitlab.options.host + '/' + projectName + '/' + page)
}
})
})
})
}
function compare(options) {
logger = log.getInstance(options.verbose)
getBaseBranchName(options.base).then(function(baseBranch) {
getRemoteForBranch(baseBranch).then(function(remote) {
if (!remote) {
console.error(
colors.red(
'Branch ' + baseBranch + ' is not tracked by any remote branch.'
)
)
console.log(
'Set the remote tracking by `git branch --set-upstream <branch-name> <remote-name>/<branch-name>`'
)
console.log('Eg: `git branch --set-upstream foo upstream/foo`')
process.exit(1)
}
getURLOfRemote(remote).then(function(remoteURL) {
var projectName = remoteURL.match(regexParseProjectName)[2]
gitlab.Projects.search(projectName, {
search_namespaces: true,
membership: true,
})
.then(function(project) {
project = project[0]
var defaultBranch = project.default_branch
var targetBranch = options.target || defaultBranch
var sourceBranch = baseBranch
open(
gitlab.options.host +
'/' +
projectName +
'/compare/' +
targetBranch +
'...' +
sourceBranch
)
})
.catch(function(err) {
console.log('Project info fetch failed : ' + err)
})
})
})
})
}
function getRemote(options) {
logger.log('\nGetting remote for options provided : ' + options.remote)
var promise = new Promise(function(resolve /*, reject*/) {
if (options.remote) {
resolve(options.remote)
return
}
getBaseBranchName(options.base).then(function(baseBranch) {
getRemoteForBranch(baseBranch).then(function(remote) {
resolve(remote, baseBranch)
})
})
})
return promise
}
function getUser(query) {
var promise = new Promise(function(resolve /*, reject*/) {
if (typeof query !== 'string') {
resolve(null)
return
}
logger.log('\nGetting user matching : ' + query)
gitlab.Users.search(query)
.then(function(userInfo) {
if (userInfo instanceof Array && userInfo.length > 0) {
var user = userInfo[0]
resolve(user)
} else {
console.error(
colors.yellow(
'User matching "' +
query +
'" was not found. Please check input and try again.'
)
)
process.exit(1)
}
})
.catch(function(err) {
console.log('User search fetch failed : ' + err)
})
})
return promise
}
function openMergeRequests(options) {
logger = log.getInstance(options.verbose)
getRemote(options).then(function(remote, baseBranch) {
if (!remote) {
console.error(
colors.red(
'Branch ' + baseBranch + ' is not tracked by any remote branch.'
)
)
console.log(
'Set the remote tracking by `git branch --set-upstream <branch-name> <remote-name>/<branch-name>`'
)
console.log('Eg: `git branch --set-upstream foo upstream/foo`')
process.exit(1)
}
getURLOfRemote(remote).then(function(remoteURL) {
getUser(options.assignee).then(function(assignee) {
var projectName = remoteURL.match(regexParseProjectName)[2]
var query = '?'
if (options.state) {
query += 'state=' + options.state + '&'
}
if (assignee) {
query += 'assignee_id=' + assignee.id + '&'
}
open(
gitlab.options.host +
'/' +
projectName +
'/merge_requests' +
query.slice(0, -1)
)
})
})
})
}
function createMergeRequest(options) {
logger = log.getInstance(options.verbose)
if (options.verbose) {
logger.log(
'Verbose option used. Detailed logging information will be emitted.'.green
)
}
logger.log('\n\n\nGetting base branch information'.blue)
getBaseBranchName(options.base)
.then(function(sourceBranch) {
store.set({ sourceBranch: sourceBranch })
return getRemoteForBranch(options.base || store.get('sourceBranch'))
})
.then(function(remote) {
store.set({ sourceRemote: remote })
return getURLOfRemote(remote)
})
.then(function(remoteURL) {
var gitlabHost = URL.parse(gitlab.options.host).host
logger.log('\ngitlab host obtained : ' + gitlabHost.green)
var match = remoteURL.match(regexParseProjectName)
if (match) {
var projectName = match[2]
} else {
console.error(
colors.red(
'The remote at which ' +
store.get('sourceBranch') +
" is tracked doesn't match the expected format."
)
)
console.log(
'Please contact developer if this is a valid gitlab repository.'
)
process.exit(1)
}
logger.log('\nProject name derived from host :', projectName)
logger.log('\nGetting gitlab project info for :', projectName)
store.set({ sourceRemoteURL: remoteURL })
store.set({ sourceProjectName: projectName })
return gitlab.Projects.search(projectName, {
search_namespaces: true,
membership: true,
})
})
.then(function(project) {
var sourceProjectName = store.get('sourceProjectName')
project = project.find((innerProject)=>{ return innerProject.path_with_namespace === sourceProjectName})
logger.log('Base project info obtained :', JSON.stringify(project).green)
var defaultBranch = project.default_branch
var targetBranch = options.target || defaultBranch
logger.log('\n\n\nGetting target branch information'.blue)
store.set({ sourceProject: project })
return getTargetBranchName(options.target || targetBranch)
})
.then(function(targetBranch) {
store.set({ targetBranch: targetBranch })
return getRemoteForBranch(options.target || targetBranch)
})
.then(function(targetRemote) {
store.set({ targetRemote: targetRemote })
return getURLOfRemote(targetRemote)
})
.then(function(targetRemoteUrl) {
var targetMatch = targetRemoteUrl.match(regexParseProjectName)
if (targetMatch) {
var targetProjectName = targetMatch[2]
} else {
console.error(
colors.red(
'The remote at which ' +
targetBranch +
" is tracked doesn't match the expected format."
)
)
console.log(
'Please contact developer if this is a valid gitlab repository.'
)
process.exit(1)
}
logger.log('Getting target project information')
store.set({ targetRemoteUrl: targetRemoteUrl })
store.set({ targetProjectName: targetProjectName })
return gitlab.Projects.search(targetProjectName, {
search_namespaces: true,
membership: true,
})
})
.then(function(targetProject) {
var targetProjectName = store.get('targetProjectName')
targetProject = targetProject.find((project)=>{ return project.path_with_namespace === targetProjectName})
logger.log(
'Target project info obtained :',
JSON.stringify(targetProject).green
)
var targetProjectId = targetProject.id
var sourceBranch = store.get('sourceBranch')
var targetBranch = store.get('targetBranch')
var projectId = store.get('sourceProject').id
if (sourceBranch == targetBranch && projectId == targetProjectId) {
console.error(colors.red('\nCan not create this merge request'))
console.log(
colors.red(
'You can not use same project/branch for source and target'
)
)
process.exit(1)
}
store.set({ targetProject: targetProject })
return getUser(options.assignee)
})
.then(function(assignee) {
store.set({ assignee: assignee })
return getMergeRequestTitle(options.message)
})
.then(function(userMessage) {
var title = userMessage.split('\n')[0]
var description =
options.description ||
userMessage
.split('\n')
.slice(2)
.join(' \n')
logger.log('Merge request title : ' + title.green)
if (description)
logger.log('Merge request description : ' + description.green)
logger.log('\n\nCreating merge request'.blue)
var sourceBranch = store.get('sourceBranch')
var targetBranch = store.get('targetBranch')
var sourceProject = store.get('sourceProject')
var sourceProjectId = sourceProject.id
var targetProject = store.get('targetProject')
var targetProjectId = targetProject.id
var labels = options.labels || ''
var remove_source_branch = options.remove_source_branch || false
var squash = options.squash || false
var assignee = store.get('assignee')
return gitlab.MergeRequests.create(
sourceProjectId,
sourceBranch,
targetBranch,
title,
{
description: description,
labels: labels,
assignee_id: assignee && assignee.id,
target_project_id: targetProjectId,
remove_source_branch: remove_source_branch,
squash: squash,
}
)
store.set({ userMessage: userMessage })
})
.then(function(mergeRequestResponse) {
logger.log('Merge request response: \n\n', mergeRequestResponse)
if (mergeRequestResponse.iid) {
var url = mergeRequestResponse.web_url
if (!url) {
url =
gitlab.options.host +
'/' +
targetProjectName +
'/merge_requests/' +
mergeRequestResponse.iid
}
if (options.edit) {
url += '/edit'
}
if (options.open) {
open(url)
} else {
console.log(url)
}
}
})
.catch(function(err) {
if (err.message) {
console.error(colors.red("Couldn't create merge request"))
console.log(colors.red(err.message))
} else if (err instanceof Array) {
console.error(colors.red("Couldn't create merge request"))
console.log(colors.red(err.join()))
}
})
}
program.description('gitlab command line utility').version(packageJson.version)
program.Command.prototype.legacy = function(alias) {
legacies[alias] = this._name
return this
}
program
.command('browse')
.option(
'-v, --verbose [optional]',
'Detailed logging emitted on console for debug purpose'
)
.option(
'-p, --page [optional]',
'Page name. e.g: issues, boards, merge_requests, pipelines, etc.'
)
.description('Open current branch page in gitlab')
.action(function(options) {
browse(options)
})
program
.command('compare')
.option('-b, --base [optional]', 'Base branch name')
.option('-t, --target [optional]', 'Target branch name')
.option(
'-v, --verbose [optional]',
'Detailed logging emitted on console for debug purpose'
)
.description('Open compare page between two branches')
.action(function(options) {
compare(options)
})
program
.command('merge-request')
.alias('mr')
.legacy('create-merge-request')
.option('-b, --base [optional]', 'Base branch name')
.option('-t, --target [optional]', 'Target branch name')
.option('-m, --message [optional]', 'Title of the merge request')
.option('-d, --description [optional]', 'Description for the merge request')
.option('-a, --assignee [optional]', 'User to assign merge request to')
.option(
'-l, --labels [optional]',
'Comma separated list of labels to assign while creating merge request'
)
.option(
'-r, --remove_source_branch [optional]',
'Flag indicating if a merge request should remove the source branch when merging'
)
.option(
'-s, --squash [optional]',
'Squash commits into a single commit when merging'
)
.option(
'-e, --edit [optional]',
'If supplied opens edit page of merge request. Prints the merge request URL otherwise'
)
.option(
'-o, --open [optional]',
'If supplied open the page of the merge request. Prints the merge request URL otherwise'
)
.option(
'-p, --print [deprecated]',
'Doesn`t do anything. Kept here for backward compatibility. Default is print.'
)
.option(
'-v, --verbose [optional]',
'Detailed logging emitted on console for debug purpose'
)
.description('Create merge request on gitlab')
.action(function(options) {
createMergeRequest(options)
})
program
.command('merge-requests')
.alias('mrs')
.legacy('open-merge-requests')
.option(
'-v, --verbose [optional]',
'Detailed logging emitted on console for debug purpose'
)
.option('-r, --remote [optional]', 'If provided this will be used as remote')
.option(
'-a, --assignee [optional]',
'If provided, merge requests assigned to only this user will be shown'
)
.option(
'-s, --state [optional]',
'If provide merge requests with state provided will be shown'
)
.description('Opens merge requests page for the repo')
.action(function(options) {
openMergeRequests(options)
})
program.on('command:*', function() {
console.error(('Invalid command ' + program.args[0]).red)
program.outputHelp()
})
if (legacies[process.argv[2]]) process.argv[2] = legacies[process.argv[2]]
program.parse(process.argv)
if (program.args.length < 1) {
program.outputHelp()
}
module.exports = function() {}