Uh oh!
There was an error while loading. Please reload this page.
forked from ietf-tools/datatracker
- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcli.js
More file actions
Latest commit
904 lines (861 loc) · 33.4 KB
/
Copy pathcli.js
File metadata and controls
904 lines (861 loc) · 33.4 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
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
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
#!/usr/bin/env node
importDockerfrom'dockerode'
importchalkfrom'chalk'
importpathfrom'path'
importosfrom'os'
importfsfrom'fs-extra'
importgotfrom'got'
import{pipeline}from'stream/promises'
import{PassThrough}from'stream'
importprettyBytesfrom'pretty-bytes'
importextractfrom'extract-zip'
importtarfrom'tar'
import{kebabCase}from'lodash-es'
import{Listr}from'listr2'
import{performance}from'perf_hooks'
import{Duration}from'luxon'
importkeypressfrom'keypress'
letdock=null
letdiffOutput=[]
constdiffStack=[]
constconfig={
options: [],
source: process.cwd(),
target: null,
tmpDir: null,
savePath: null,
shouldCleanup: false
}
constcontainers={
net: null,
dbSource: null,
dbTarget: null,
appSource: null,
appTarget: null
}
constsha1reg=/^[0-9a-f]{5,40}$/
/**
* Prompt the user for a path
*
* @param {Task} task Listr task instance
* @param {String} msg Prompt message
* @param {Boolean} mustExist Whether the path must already exist
* @returns path
*/
asyncfunctionpromptForPath(task,msg,mustExist=true,initial){
returntask.prompt([
{
type: 'input',
name: 'path',
message: msg,
initial,
asyncvalidate(input){
if(!input){
return'You must provide a valid path!'
}
constproposedPath=path.resolve('.',input)
if(proposedPath.includes(config.source)){
return'Path must be different than the current datatracker project path!'
}elseif(mustExist&&!(awaitfs.pathExists(proposedPath))){
return'Path is invalid or doesn\'t exist!'
}else{
returntrue
}
}
}
])
}
/**
* Download and Extract a zip archive
*
* @param {Task} task Listr task instance
* @param {Object} param1 Options
*/
asyncfunctiondownloadExtractZip(task,{ msg, url, ext ='zip', branch }){
constarchivePath=path.join(config.target,`archive.${ext}`)
awaitfs.emptyDir(config.target)
// Download zip
try{
task.title=msg
constdownloadBranchStream=got.stream(url)
downloadBranchStream.on('downloadProgress',progress=>{
task.output=`${prettyBytes(progress.transferred)} downloaded.`
})
awaitpipeline(
downloadBranchStream,
fs.createWriteStream(archivePath)
)
task.title=`Downloaded ${ext} archive successfully.`
}catch(err){
thrownewError(`Failed to download ${ext} archive from GitHub. ${err.message}`)
}
// Extract zip
try{
task.title=`Extracting ${ext} archive contents...`
if(ext==='zip'){
consttmpDir=awaitfs.mkdtemp(path.join(os.tmpdir(),'dt-'))
awaitfs.ensureDir(tmpDir)
awaitextract(archivePath,{
dir: tmpDir,
onEntry(entry){
task.output=entry.fileName
}
})
task.title='Moving extracted files to final location...'
task.output=config.target
awaitfs.move(path.join(tmpDir,kebabCase(`datatracker-${branch}`)),config.target,{overwrite: true})
awaitfs.remove(tmpDir)
}elseif(ext==='tgz'){
awaittar.x({
strip: 1,
file: archivePath,
cwd: config.target,
filter(path){
task.output=path
returntrue
}
})
}
task.title=`Extracted ${ext} archive successfully.`
awaitfs.remove(archivePath)
}catch(err){
thrownewError(`Failed to extract ${ext} archive contents. ${err.message}`)
}
}
/**
* Run a command on a running container
*
* @param {Task} task Listr task instance
* @param {Docker.Container} container Docker container instance
* @param {Array<String>} cmd Command to execute
* @param {Boolean} collectOutput Whether to collect and return the command output
*/
asyncfunctionexecuteCommand(task,container,cmd,collectOutput=false,silent=false){
constlogStack=[]
consterrStack=[]
letlogFStream=null
returnnewPromise(async(resolve,reject)=>{
// Handle stream output
constlogStream=newPassThrough()
logStream.on('data',chunk=>{
constlogLine=chunk.toString('utf8').trim()
if(logLine&&!silent){
task.output=logLine
if(collectOutput){
logStack.push(...logLine.split('\n').filter(l=>l))
}
}
})
logStream.on('error',chunk=>{
task.output=chunk.toString('utf8')
errStack.push(chunk.toString('utf8'))
})
if(collectOutput){
logFStream=fs.createWriteStream(path.join(config.savePath))
logStream.pipe(logFStream)
}
// Execute command in container
constexecChmod=awaitcontainer.exec({
Cmd: cmd,
AttachStdout: true,
AttachStderr: true
})
constexecChmodStream=awaitexecChmod.start()
// Handle stream close
execChmodStream.on('close',()=>{
if(collectOutput){
logFStream.close()
}
if(errStack.length>0){
reject(newError(errStack))
}else{
if(!silent){
}
task.output=''
resolve(logStack)
}
})
// Pipe container stream to log stream
container.modem.demuxStream(execChmodStream,logStream,logStream)
})
}
/**
* Run cleanup tasks (e.g. stop/remove docker resources)
*
* @param {Boolean} exitAfter Whether to exit the process at the end
*/
asyncfunctioncleanup(exitAfter=false){
try{
constcleanupTasks=newListr([
// ------------------------
// Stop + Remove Containers
// ------------------------
{
title: 'Stop + remove docker containers',
task: async(ctx,task)=>{
task.output='Stopping containers...'
try{
awaitPromise.allSettled([
containers.dbSource&&containers.dbSource.stop(),
containers.dbTarget&&containers.dbTarget.stop(),
containers.appSource&&containers.appSource.stop(),
containers.appTarget&&containers.appTarget.stop()
])
}catch(err){}
task.output='Removing containers...'
try{
awaitPromise.allSettled([
containers.dbSource&&containers.dbSource.remove({v: true}),
containers.dbTarget&&containers.dbTarget.remove({v: true}),
containers.appSource&&containers.appSource.remove({v: true}),
containers.appTarget&&containers.appTarget.remove({v: true})
])
}catch(err){}
task.output='Removing network...'
try{
awaitcontainers.net.remove()
}catch(err){}
}
},
// --------------------
// Restore config files
// --------------------
{
title: 'Restore original source settings file',
task: async(ctx,task)=>{
constsourceSettingsPath=path.join(config.source,'ietf/settings_local.py')
if(awaitfs.pathExists(`${sourceSettingsPath}.bak`)){
awaitfs.move(`${sourceSettingsPath}.bak`,sourceSettingsPath,{overwrite: true})
task.title='Restored original source settings file.'
}else{
task.skip('Nothing to restore.')
}
}
},
{
title: 'Restore original target settings file',
task: async(ctx,task)=>{
consttargetSettingsPath=path.join(config.target,'ietf/settings_local.py')
if(awaitfs.pathExists(`${targetSettingsPath}.bak`)){
awaitfs.move(`${targetSettingsPath}.bak`,targetSettingsPath,{overwrite: true})
task.title='Restored original target settings file.'
}else{
task.skip('Nothing to restore.')
}
}
}
],{
registerSignalListeners: false
})
awaitcleanupTasks.run()
// Cleanup
if(config.tmpDir){
awaitfs.remove(config.tmpDir)
}
}catch(err){
console.error(chalk.redBright(err.message))
process.exit(1)
}
if(exitAfter){
process.exit(0)
}
}
asyncfunctionmain(){
console.clear()
console.info('╔════════════════════════════╗')
console.info('║ IETF DATATRACKER DIFF TOOL ║')
console.info('╚════════════════════════════╝\n')
try{
consttasks=newListr([
// ----------------------------
// Connect to Docker Engine API
// ----------------------------
{
title: 'Connect to Docker Engine API',
task: async(ctx,task)=>{
dock=newDocker()
awaitdock.ping()
task.title='Connected to Docker Engine API.'
}
},
// ---------------------------------------------------------------
// Find base path so that it works from both / and /dev/diff paths
// ---------------------------------------------------------------
{
title: 'Find base datatracker instance base path',
task: async(ctx,task)=>{
letparentIdx=0
while(!(awaitfs.pathExists(path.join(config.source,'requirements.txt')))){
config.source=path.resolve(config.source,'..')
parentIdx++
if(parentIdx>2){
thrownewError('Start the CLI from a valid datatracker project path.')
}
}
task.title=`Using path ${config.source} for source datatracker instance.`
}
},
// --------------------------------------
// Select comparison datatracker instance
// --------------------------------------
{
title: 'Select diff target',
task: async(ctx,task)=>{
ctx.targetMode=awaittask.prompt({
type: 'select',
message: 'What do you want to compare against?',
choices: [
{name: 'local',message: 'Local folder path...'},
{name: 'branch',message: 'Remote GitHub branch...'},
{name: 'tag',message: 'Remote GitHub tag...'},
{name: 'commit',message: 'Remote GitHub commit hash...'}
// { name: 'release', message: 'Latest GitHub release', disabled: true }
]
})
task.title=`Selected diff target: ${ctx.targetMode}`
}
},
// ---------------------------------
// Fetch target datatracker instance
// ---------------------------------
{
title: 'Fetch diff target',
task: async(ctx,task)=>{
switch(ctx.targetMode){
// MODE: LOCAL
// ------------------------------------------------
case'local': {
task.title='Waiting for diff target path input'
config.target=awaitpromptForPath(task,'Enter the local path to the datatracker project to compare against:')
task.title=`Using path ${config.target} for target datatracker instance.`
break
}
// MODE: REMOTE BRANCH
// ------------------------------------------------
case'branch': {
// Prompt for branch
constbranches=[]
letbranch='main'
try{
task.title='Fetching available remote branches...'
constbranchesResp=awaitgot('https://api.github.com/repos/ietf-tools/datatracker/branches?per_page=100').json()
if(branchesResp?.length<1){
thrownewError('No remote branches available.')
}
branches.push(...branchesResp.map(b=>b.name))
task.output=`Fetched ${branches.length} remote branches.`
}catch(err){
thrownewError(`Failed to fetch branches! ${err.message}`)
}
branch=awaittask.prompt([
{
type: 'select',
message: 'Select the remote branch to compare against:',
choices: branches
}
])
// Prompt for local path where to download branch contents
config.target=awaitpromptForPath(task,'Enter a local path where the branch contents will be downloaded to:',false)
awaitfs.ensureDir(config.target)
// Download / Extract branch zip
awaitdownloadExtractZip(task,{
msg: `Downloading ${branch} branch contents...`,
url: `https://github.com/ietf-tools/datatracker/archive/refs/heads/${branch}.tar.gz`,
ext: 'tgz'
})
task.title=`Fetched branch ${branch} to ${config.target}`
break
}
// MODE: REMOTE TAG
// ------------------------------------------------
case'tag': {
// Prompt for tag
consttag=awaittask.prompt([
{
type: 'input',
message: 'Enter the remote repository tag to compare against:'
}
])
// Prompt for local path where to download tag contents
config.target=awaitpromptForPath(task,'Enter a local path where the tag contents will be downloaded to:',false)
awaitfs.ensureDir(config.target)
// Download / Extract tag tarball
awaitdownloadExtractZip(task,{
msg: `Downloading tag ${tag} contents...`,
url: `https://github.com/ietf-tools/datatracker/archive/refs/tags/${tag}.tar.gz`,
ext: 'tgz'
})
task.title=`Fetched tag ${tag} to ${config.target}`
break
}
// MODE: REMOTE COMMIT
// ------------------------------------------------
case'commit': {
// Prompt for commit hash
constcommit=awaittask.prompt([
{
type: 'input',
message: 'Enter the FULL commit hash to compare against:',
asyncvalidate(input){
if(!input){
return'You must provide a hash!'
}elseif(!sha1reg.test(input)){
return'Invalid hash!'
}
returntrue
}
}
])
// Prompt for local path where to download commit contents
config.target=awaitpromptForPath(task,'Enter a local path where the commit contents will be downloaded to:',false)
awaitfs.ensureDir(config.target)
// Download / Extract commit tarball
awaitdownloadExtractZip(task,{
msg: `Downloading commit ${commit} contents...`,
url: `https://github.com/ietf-tools/datatracker/archive/${commit}.tar.gz`,
ext: 'tgz'
})
task.title=`Fetched commit ${commit} to ${config.target}`
break
}
// MODE: LATEST RELEASE
// ------------------------------------------------
case'release': {
task.title='Waiting for diff target download location'
// Prompt for local path where to download release
config.target=awaitpromptForPath(task,'Enter a local path where the latest release will be downloaded to:',false)
awaitfs.ensureDir(config.target)
// Download / extract latest release
awaitdownloadExtractZip(task,{
msg: 'Downloading latest release...',
url: 'https://github.com/ietf-tools/datatracker/releases/latest/download/release.tar.gz',
ext: 'tgz'
})
task.title=`Fetched latest release to ${config.target}`
break
}
default: {
thrownewError('Invalid selection. Exiting...')
}
}
// Add missing files not present in branch
if(!(awaitfs.pathExists(path.join(config.target,'dev/diff')))){
task.output=`Add missing diff tool files...`
awaitfs.ensureDir(path.join(config.target,'dev/diff'))
awaitfs.copy(path.join(config.source,'dev/diff/prepare.sh'),path.join(config.target,'dev/diff/prepare.sh'))
awaitfs.copy(path.join(config.source,'dev/diff/settings_local.py'),path.join(config.target,'dev/diff/settings_local.py'))
}
}
},
// ------------------------
// Prompt for crawl options
// ------------------------
{
title: 'Select additional crawl options',
task: async(ctx,task)=>{
consttoggleIndicatorFn=(state,choice)=>{
returnchoice.enabled ? chalk.greenBright('✔') : chalk.gray('o')
}
config.options=awaittask.prompt([
{
type: 'multiselect',
message: 'Select additional options to enable:',
hint: '(use <SPACE> to toggle, <ENTER> to confirm)',
choices: [
{message: 'Skip HTML Validation',name: '--skip-html-validation',hint: 'Skip HTML Validation',indicator: toggleIndicatorFn},
{message: 'Fail-fast',name: '--failfast',hint: 'Stop the crawl on the first page failure',indicator: toggleIndicatorFn},
{message: 'No-Follow',name: '--no-follow',hint: 'Do not follow URLs found in fetched pages, just check the given URLs',indicator: toggleIndicatorFn},
{message: 'No-Revisit',name: '--no-revisit',hint: 'Don\'t revisit already visited URLs',indicator: toggleIndicatorFn},
{message: 'Pedantic',name: '--pedantic',hint: 'Stop the crawl on the first error or warning',indicator: toggleIndicatorFn},
{message: 'Random',name: '--random',hint: 'Crawl URLs randomly',indicator: toggleIndicatorFn},
{message: 'Validate All',name: '--validate-all',hint: 'Run html 5 validation on all pages, without skipping similar urls',indicator: toggleIndicatorFn},
{message: 'Verbose',name: '--verbose',hint: 'Be more verbose',indicator: toggleIndicatorFn}
]
}
])
if(config.options.length>0){
task.title=`Selected additional crawl options: ${config.options.join(' ')}`
}
}
},
// ---------------------------
// Prompt to save crawl output
// ---------------------------
{
title: 'Save crawl output',
task: async(ctx,task)=>{
constsaveToDisk=awaittask.prompt({
type: 'confirm',
message: 'Save the crawl output to file?'
})
if(saveToDisk){
config.savePath=awaitpromptForPath(task,'Enter the path where the crawl output will be saved:',false,path.join(os.homedir(),'Desktop/crawl-out.txt'))
task.title=`Crawl output will be saved to ${config.savePath}`
}else{
config.tmpDir=awaitfs.mkdtemp(path.join(os.tmpdir(),'dt-'))
config.savePath=path.join(config.tmpDir,'out.txt')
task.title='Crawl output will not be saved.'
}
}
},
// ----------------------------
// Set datatracker config files
// ----------------------------
{
title: 'Set datatracker config files',
task: async(ctx,task)=>{
// Source
constsourceSettingsPath=path.join(config.source,'ietf/settings_local.py')
if(awaitfs.pathExists(sourceSettingsPath)){
awaitfs.move(sourceSettingsPath,`${sourceSettingsPath}.bak`,{overwrite: true})
}
constcfgSourceRaw=awaitfs.readFile(path.join(config.source,'dev/diff/settings_local.py'),'utf8')
awaitfs.outputFile(sourceSettingsPath,cfgSourceRaw.replace('__DBHOST__','dt-diff-db-source'))
// Target
consttargetSettingsPath=path.join(config.target,'ietf/settings_local.py')
if(awaitfs.pathExists(targetSettingsPath)){
awaitfs.move(targetSettingsPath,`${targetSettingsPath}.bak`,{overwrite: true})
}
constcfgTargetRaw=awaitfs.readFile(path.join(config.target,'dev/diff/settings_local.py'),'utf8')
awaitfs.outputFile(targetSettingsPath,cfgTargetRaw.replace('__DBHOST__','dt-diff-db-target'))
}
},
// ------------------
// Pull latest images
// ------------------
{
title: 'Pull latest docker images',
task: (ctx,task)=>task.newListr([
{
title: 'Pulling latest DB docker image...',
task: async(subctx,subtask)=>{
constdbImagePullStream=awaitdock.pull('ghcr.io/ietf-tools/datatracker-db:latest')
awaitnewPromise((resolve,reject)=>{
dock.modem.followProgress(dbImagePullStream,(err,res)=>err ? reject(err) : resolve(res))
})
subtask.title=`Pulled latest DB docker image successfully.`
}
},
{
title: 'Pulling latest Datatracker base docker image...',
task: async(subctx,subtask)=>{
constappImagePullStream=awaitdock.pull('ghcr.io/ietf-tools/datatracker-app-base:latest')
awaitnewPromise((resolve,reject)=>{
dock.modem.followProgress(appImagePullStream,(err,res)=>err ? reject(err) : resolve(res))
})
subtask.title=`Pulled latest Datatracker base docker image successfully.`
}
}
],{
concurrent: true,
rendererOptions: {
collapse: false
}
})
},
// --------------
// Create network
// --------------
{
title: 'Create docker network',
task: async(ctx,task)=>{
config.shouldCleanup=true
containers.net=awaitdock.createNetwork({
Name: 'dt-diff-net',
CheckDuplicate: true
})
task.title='Created docker network (dt-diff-net).'
}
},
// ----------------------------
// Create + Start DB containers
// ----------------------------
{
title: 'Create DB docker containers',
task: (ctx,task)=>task.newListr([
{
title: 'Creating source DB docker container...',
task: async(subctx,subtask)=>{
containers.dbSource=awaitdock.createContainer({
Image: 'ghcr.io/ietf-tools/datatracker-db:latest',
name: 'dt-diff-db-source',
Hostname: 'dbsource',
HostConfig: {
NetworkMode: 'dt-diff-net'
}
})
awaitcontainers.dbSource.start()
subtask.title=`Created source DB docker container (dt-diff-db-source) successfully.`
}
},
{
title: 'Creating target DB docker container...',
task: async(subctx,subtask)=>{
containers.dbTarget=awaitdock.createContainer({
Image: 'ghcr.io/ietf-tools/datatracker-db:latest',
name: 'dt-diff-db-target',
Hostname: 'dbtarget',
HostConfig: {
NetworkMode: 'dt-diff-net'
}
})
awaitcontainers.dbTarget.start()
subtask.title=`Created target DB docker container (dt-diff-db-target) successfully.`
}
}
],{
concurrent: true,
rendererOptions: {
collapse: false
}
})
},
// -------------------------------------
// Create + Start Datatracker containers
// -------------------------------------
{
title: 'Create Datatracker docker containers',
task: (ctx,task)=>task.newListr([
{
title: 'Creating source Datatracker docker container...',
task: async(subctx,subtask)=>{
containers.appSource=awaitdock.createContainer({
Image: 'ghcr.io/ietf-tools/datatracker-app-base:latest',
name: 'dt-diff-app-source',
Tty: true,
Hostname: 'appsource',
HostConfig: {
NetworkMode: 'dt-diff-net'
}
})
awaitcontainers.appSource.start()
subtask.title=`Created source Datatracker docker container (dt-diff-app-source) successfully.`
}
},
{
title: 'Creating target Datatracker docker container...',
task: async(subctx,subtask)=>{
containers.appTarget=awaitdock.createContainer({
Image: 'ghcr.io/ietf-tools/datatracker-app-base:latest',
name: 'dt-diff-app-target',
Tty: true,
Hostname: 'apptarget',
HostConfig: {
NetworkMode: 'dt-diff-net'
}
})
awaitcontainers.appTarget.start()
subtask.title=`Created target Datatracker docker container (dt-diff-app-target) successfully.`
}
}
],{
concurrent: true,
rendererOptions: {
collapse: false
}
})
},
// --------------------------------------------
// Copy working files to Datatracker containers
// --------------------------------------------
{
title: 'Copy working files to Datatracker docker containers',
task: (ctx,task)=>task.newListr([
{
title: 'Copying workfing files into source Datatracker docker container...',
task: async(subctx,subtask)=>{
consttgzPath=path.join(config.source,'diff-import.tgz')
awaittar.c({
gzip: true,
file: tgzPath,
cwd: config.source,
filter(path){
if(path.includes('.git')||path.includes('node_modules')){returnfalse}
subtask.output=path
returntrue
}
},['.'])
subtask.output='Injecting into container...'
awaitcontainers.appSource.putArchive(tgzPath,{
path: '/workspace'
})
awaitfs.remove(tgzPath)
subtask.title=`Imported working files into source Datatracker docker container (dt-diff-app-source) successfully.`
}
},
{
title: 'Copying working files into target Datatracker docker container...',
task: async(subctx,subtask)=>{
consttgzPath=path.join(config.target,'diff-import.tgz')
awaittar.c({
gzip: true,
file: tgzPath,
cwd: config.target,
filter(path){
if(path.includes('.git')||path.includes('node_modules')){returnfalse}
subtask.output=path
returntrue
}
},['.'])
subtask.output='Injecting into container...'
awaitcontainers.appTarget.putArchive(tgzPath,{
path: '/workspace'
})
awaitfs.remove(tgzPath)
subtask.title=`Imported working files into target Datatracker docker container (dt-diff-app-target) successfully.`
}
}
],{
concurrent: true,
rendererOptions: {
collapse: false
}
})
},
// -------------------
// Run prepare scripts
// -------------------
{
title: 'Prepare Datatracker instances',
task: (ctx,task)=>task.newListr([
{
title: 'Preparing source Datatracker instance...',
task: async(subctx,subtask)=>{
awaitexecuteCommand(subtask,containers.appSource,['bash','-c','chmod +x ./dev/diff/prepare.sh'])
awaitexecuteCommand(subtask,containers.appSource,['bash','./dev/diff/prepare.sh'])
subtask.title=`Source Datatracker instance is now ready.`
}
},
{
title: 'Preparing target Datatracker instance...',
task: async(subctx,subtask)=>{
awaitexecuteCommand(subtask,containers.appTarget,['bash','-c','chmod +x ./dev/diff/prepare.sh'])
awaitexecuteCommand(subtask,containers.appTarget,['bash','./dev/diff/prepare.sh'])
subtask.title=`Run target Datatracker instance - Starting server...`
executeCommand(subtask,containers.appTarget,['bash','-c','./ietf/manage.py runserver 0.0.0.0:8000 --settings=settings_local'])
subtask.title=`Run target Datatracker instance - Waiting for server to accept connections...`
awaitexecuteCommand(subtask,containers.appTarget,['bash','-c','/usr/local/bin/wait-for localhost:8000 -t 300'])
subtask.title=`Target Datatracker instance is now ready and accepting connections.`
}
}
],{
concurrent: true,
rendererOptions: {
collapse: false
}
})
},
// --------------
// Run crawl tool
// --------------
{
title: 'Run crawl',
task: async(ctx,task)=>{
task.title='Running crawl... (Press F10 to cancel)'
task.output='Starting ./bin/test-crawl... (Results will start appearing soon)'
conststartMs=performance.now()
config.options.push('--settings=ietf.settings_testcrawl')
config.options.push('--diff http://dt-diff-app-target:8000/')
// Run crawl
consterrStack=[]
letexecChmodStream=null
letlinesScanned=0
constexecPromise=newPromise(async(resolve,reject)=>{
// Handle stream output
constlogStream=newPassThrough()
logStream.on('data',chunk=>{
constlogLines=chunk.toString('utf8').trim().split('\n').filter(l=>l.trim())
// Check for DIFF mentions
if(logLines.length>0){
linesScanned+=logLines.length
for(constlogLineoflogLines){
if(logLine.includes('DIFF')){
diffStack.push(logLine)
}
}
constcurrentDur=Duration.fromMillis(performance.now()-startMs)
task.output=`[${currentDur.toFormat('hh:mm:ss')}] Scanned ${linesScanned} lines. Found ${diffStack.length} DIFF mentions.`
}
})
// Handle error stream
logStream.on('error',chunk=>{
task.output=chunk.toString('utf8')
errStack.push(chunk.toString('utf8'))
})
// Pipe to file stream
constlogFStream=fs.createWriteStream(path.join(config.savePath))
logStream.pipe(logFStream)
// Execute command in container
constexecChmod=awaitcontainers.appSource.exec({
Cmd: ['bash','-c',`./bin/test-crawl ${config.options.join(' ')}`],
AttachStdout: true,
AttachStderr: true
})
execChmodStream=awaitexecChmod.start()
// Handle stream close
execChmodStream.on('close',()=>{
logFStream.close()
process.stdin.setRawMode(false)
process.stdin.resume()
if(errStack.length>0){
reject(newError(errStack))
}else{
resolve()
}
})
// Pipe container stream to log stream
containers.appSource.modem.demuxStream(execChmodStream,logStream,logStream)
})
// Handle F10 Exit
keypress(process.stdin)
process.stdin.on('keypress',(ch,key)=>{
if(key&&key.name==='f10'){
task.title='Run crawl'
execChmodStream.destroy()
task.skip()
}
})
process.stdin.setRawMode(true)
process.stdin.resume()
returnexecPromise
}
}
])
awaittasks.run()
}catch(err){
console.error(chalk.redBright(err.message))
}
// ------------------------
// Cleanup
// ------------------------
awaitcleanup()
// ------------------------
// Output results
// ------------------------
console.info('\n=====================')
console.info('RESULTS')
console.info('=====================\n')
if(diffStack.length>0){
for(constdiffLineofdiffStack){
console.info(`> ${diffLine}`)
}
console.info(chalk.blueBright(`\nFound ${diffStack.length} mention(s) of DIFF.\n`))
}else{
console.info(chalk.blueBright(`No mention of DIFF were found.\n`))
}
process.exit(0)
}
// Handle user interrupt
// process.once('SIGINT', async () => {
// console.info('Trying to shutdown gracefully...')
// if (config.shouldCleanup) {
// setTimeout(() => { process.exit(1) }, 30000).unref()
// try {
// await cleanup()
// } catch (err) {
// console.warn(`Failed to shutdown gracefully: ${err.message}`)
// }
// }
// process.exit(0)
// })
main()