-
Notifications
You must be signed in to change notification settings - Fork 113
/
utils.js
812 lines (758 loc) · 28.2 KB
/
utils.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
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
// @flow
import {
utils as coreUtils,
MiniApp,
Platform,
reactnative,
yarn,
ModuleTypes
} from 'ern-core'
import {
generateRunnerProject,
regenerateRunnerConfig
} from 'ern-runner-gen'
import {
android,
ios,
Dependency,
DependencyPath,
NativeApplicationDescriptor,
spin,
shell
} from 'ern-util'
import {
runLocalContainerGen,
runCauldronContainerGen
} from './publication'
import {
spawn,
spawnSync
} from 'child_process'
import utils from './utils'
import _ from 'lodash'
import inquirer from 'inquirer'
import semver from 'semver'
import Ensure from './Ensure'
import ora from 'ora'
import chalk from 'chalk'
import fs from 'fs'
import path from 'path'
const {
runAndroidProject
} = android
//
// Retrieves all native applications versions from the Cauldron, optionaly
// filtered by platform/and or release status and returns them as an array
// of native application descriptor strings
async function getNapDescriptorStringsFromCauldron ({
platform,
onlyReleasedVersions,
onlyNonReleasedVersions
} : {
platform?: 'ios' | 'android',
onlyReleasedVersions?: boolean,
onlyNonReleasedVersions?: boolean
} = {}) {
const cauldron = await coreUtils.getCauldronInstance()
const nativeApps = await cauldron.getAllNativeApps()
return _.filter(
_.flattenDeep(
_.map(nativeApps, nativeApp =>
_.map(nativeApp.platforms, p =>
_.map(p.versions, version => {
if (!platform || platform === p.name) {
if ((version.isReleased && !onlyNonReleasedVersions) ||
(!version.isReleased && !onlyReleasedVersions)) {
return `${nativeApp.name}:${p.name}:${version.name}`
}
}
})))), elt => elt !== undefined)
}
//
// Ensure that some conditions are satisifed
// If not, log exception error message and exit process
async function logErrorAndExitIfNotSatisfied ({
noGitOrFilesystemPath,
noFileSystemPath,
isValidContainerVersion,
isNewerContainerVersion,
isCompleteNapDescriptorString,
napDescriptorExistInCauldron,
sameNativeApplicationAndPlatform,
napDescritorDoesNotExistsInCauldron,
publishedToNpm,
miniAppNotInNativeApplicationVersionContainer,
miniAppIsInNativeApplicationVersionContainer,
miniAppIsInNativeApplicationVersionContainerWithDifferentVersion,
dependencyNotInNativeApplicationVersionContainer,
dependencyIsInNativeApplicationVersionContainer,
dependencyIsInNativeApplicationVersionContainerWithDifferentVersion,
dependencyNotInUseByAMiniApp,
cauldronIsActive,
isValidNpmPackageName,
isValidElectrodeNativeModuleName
} : {
noGitOrFilesystemPath?: {
obj: string | Array<string>,
extraErrorMessage?: string
},
noFileSystemPath?: {
obj: string | Array<string>,
extraErrorMessage?: string
},
isValidContainerVersion?: {
containerVersion: string,
extraErrorMessage?: string
},
isNewerContainerVersion?: {
descriptor: string,
containerVersion: string,
extraErrorMessage?: string
},
isCompleteNapDescriptorString?: {
descriptor: string,
extraErrorMessage?: string
},
napDescriptorExistInCauldron?: {
descriptor: string | Array<string>,
extraErrorMessage?: string
},
sameNativeApplicationAndPlatform?: {
descriptors: Array<string>,
extraErrorMessage?: string
},
napDescritorDoesNotExistsInCauldron?: {
descriptor: string,
extraErrorMessage?: string
},
publishedToNpm?: {
obj: string | Array<string>,
extraErrorMessage?: string
},
miniAppNotInNativeApplicationVersionContainer?: {
miniApp: string | Array<string> | void,
napDescriptor: NativeApplicationDescriptor,
extraErrorMessage?: string
},
miniAppIsInNativeApplicationVersionContainer?: {
miniApp: string | Array<string> | void,
napDescriptor: NativeApplicationDescriptor,
extraErrorMessage?: string
},
miniAppIsInNativeApplicationVersionContainerWithDifferentVersion?: {
miniApp: string | Array<string> | void,
napDescriptor: NativeApplicationDescriptor,
extraErrorMessage?: string
},
dependencyNotInNativeApplicationVersionContainer?: {
dependency: string | Array<string> | void,
napDescriptor: NativeApplicationDescriptor,
extraErrorMessage?: string
},
dependencyIsInNativeApplicationVersionContainer?: {
dependency: string | Array<string> | void,
napDescriptor: NativeApplicationDescriptor,
extraErrorMessage?: string
},
dependencyIsInNativeApplicationVersionContainerWithDifferentVersion?: {
dependency: string | Array<string> | void,
napDescriptor: NativeApplicationDescriptor,
extraErrorMessage?: string
},
dependencyNotInUseByAMiniApp? : {
dependency: string | Array<string> | void,
napDescriptor: NativeApplicationDescriptor,
extraErrorMessage?: string
},
cauldronIsActive?: {
extraErrorMessage?: string
},
isValidNpmPackageName?: {
name: string,
extraErrorMessage?: string
},
isValidElectrodeNativeModuleName?: {
name: string,
extraErrorMessage?: string
}
} = {}) {
const spinner = ora('Performing validity checks').start()
try {
if (cauldronIsActive) {
spinner.text = 'Ensuring that a Cauldron is active'
await Ensure.cauldronIsActive(
cauldronIsActive.extraErrorMessage
)
}
if (isValidContainerVersion) {
spinner.text = 'Ensuring that container version is valid'
Ensure.isValidContainerVersion(
isValidContainerVersion.containerVersion,
isValidContainerVersion.extraErrorMessage)
}
if (isNewerContainerVersion) {
spinner.text = 'Ensuring that container version is newer compared to the current one'
await Ensure.isNewerContainerVersion(
isNewerContainerVersion.descriptor,
isNewerContainerVersion.containerVersion,
isNewerContainerVersion.extraErrorMessage)
}
if (isCompleteNapDescriptorString) {
spinner.text = 'Ensuring that native application descriptor is complete'
Ensure.isCompleteNapDescriptorString(
isCompleteNapDescriptorString.descriptor,
isCompleteNapDescriptorString.extraErrorMessage)
}
if (noGitOrFilesystemPath) {
spinner.text = 'Ensuring that not git or file system path(s) is/are used'
Ensure.noGitOrFilesystemPath(
noGitOrFilesystemPath.obj,
noGitOrFilesystemPath.extraErrorMessage)
}
if (noFileSystemPath) {
spinner.text = 'Ensuring that no file system path(s) is/are used'
Ensure.noFileSystemPath(
noFileSystemPath.obj,
noFileSystemPath.extraErrorMessage)
}
if (napDescriptorExistInCauldron) {
spinner.text = 'Ensuring that native application descriptor exists in Cauldron'
await Ensure.napDescritorExistsInCauldron(
napDescriptorExistInCauldron.descriptor,
napDescriptorExistInCauldron.extraErrorMessage)
}
if (sameNativeApplicationAndPlatform) {
spinner.text = 'Ensuring that all descriptors are for the same native application and platform'
Ensure.sameNativeApplicationAndPlatform(
sameNativeApplicationAndPlatform.descriptors,
sameNativeApplicationAndPlatform.extraErrorMessage)
}
if (napDescritorDoesNotExistsInCauldron) {
spinner.text = 'Ensuring that native application descriptor does not already exist in Cauldron'
await Ensure.napDescritorDoesNotExistsInCauldron(
napDescritorDoesNotExistsInCauldron.descriptor,
napDescritorDoesNotExistsInCauldron.extraErrorMessage)
}
if (publishedToNpm) {
spinner.text = 'Ensuring that package(s) version(s) have been published to NPM'
await Ensure.publishedToNpm(
publishedToNpm.obj,
publishedToNpm.extraErrorMessage)
}
if (miniAppNotInNativeApplicationVersionContainer) {
spinner.text = 'Ensuring that MiniApp(s) is/are not present in native application version container'
await Ensure.miniAppNotInNativeApplicationVersionContainer(
miniAppNotInNativeApplicationVersionContainer.miniApp,
miniAppNotInNativeApplicationVersionContainer.napDescriptor,
miniAppNotInNativeApplicationVersionContainer.extraErrorMessage)
}
if (miniAppIsInNativeApplicationVersionContainer) {
spinner.text = 'Ensuring that MiniApp(s) is/are present in native application version container'
await Ensure.miniAppIsInNativeApplicationVersionContainer(
miniAppIsInNativeApplicationVersionContainer.miniApp,
miniAppIsInNativeApplicationVersionContainer.napDescriptor,
miniAppIsInNativeApplicationVersionContainer.extraErrorMessage)
}
if (miniAppIsInNativeApplicationVersionContainerWithDifferentVersion) {
spinner.text = 'Ensuring that MiniApp(s) is/are present in native application version container with different version(s)'
await Ensure.miniAppIsInNativeApplicationVersionContainerWithDifferentVersion(
miniAppIsInNativeApplicationVersionContainerWithDifferentVersion.miniApp,
miniAppIsInNativeApplicationVersionContainerWithDifferentVersion.napDescriptor,
miniAppIsInNativeApplicationVersionContainerWithDifferentVersion.extraErrorMessage)
}
if (dependencyNotInNativeApplicationVersionContainer) {
spinner.text = 'Ensuring that dependency(ies) is/are not present in native application version container'
await Ensure.dependencyNotInNativeApplicationVersionContainer(
dependencyNotInNativeApplicationVersionContainer.dependency,
dependencyNotInNativeApplicationVersionContainer.napDescriptor,
dependencyNotInNativeApplicationVersionContainer.extraErrorMessage)
}
if (dependencyIsInNativeApplicationVersionContainer) {
spinner.text = 'Ensuring that dependency(ies) is/are present in native application version container'
await Ensure.dependencyIsInNativeApplicationVersionContainer(
dependencyIsInNativeApplicationVersionContainer.dependency,
dependencyIsInNativeApplicationVersionContainer.napDescriptor,
dependencyIsInNativeApplicationVersionContainer.extraErrorMessage)
}
if (dependencyIsInNativeApplicationVersionContainerWithDifferentVersion) {
spinner.text = 'Ensuring that dependency(ies) is/are present in native application version container with different version(s)'
await Ensure.dependencyIsInNativeApplicationVersionContainerWithDifferentVersion(
dependencyIsInNativeApplicationVersionContainerWithDifferentVersion.dependency,
dependencyIsInNativeApplicationVersionContainerWithDifferentVersion.napDescriptor,
dependencyIsInNativeApplicationVersionContainerWithDifferentVersion.extraErrorMessage)
}
if (dependencyNotInUseByAMiniApp) {
spinner.text = 'Ensuring that no MiniApp(s) is/are using a dependency'
await Ensure.dependencyNotInUseByAMiniApp(
dependencyNotInUseByAMiniApp.dependency,
dependencyNotInUseByAMiniApp.napDescriptor,
dependencyNotInUseByAMiniApp.extraErrorMessage)
}
if (isValidNpmPackageName) {
spinner.text = 'Ensuring that NPM package name is valid'
await Ensure.isValidNpmPackageName(
isValidNpmPackageName.name,
isValidNpmPackageName.extraErrorMessage)
}
if (isValidElectrodeNativeModuleName) {
spinner.text = 'Ensuring that Electrode Native module name is valid'
await Ensure.isValidElectrodeNativeModuleName(
isValidElectrodeNativeModuleName.name,
isValidElectrodeNativeModuleName.extraErrorMessage
)
}
spinner.succeed('Validity checks have passed')
} catch (e) {
spinner.fail(e.message)
process.exit(1)
}
}
//
// Inquire user to choose a native application version from the Cauldron, optionally
// filtered by platform/and or release status and returns the selected one as a string
async function askUserToChooseANapDescriptorFromCauldron ({
platform,
onlyReleasedVersions,
onlyNonReleasedVersions,
message
} : {
platform?: 'ios' | 'android',
onlyReleasedVersions?: boolean,
onlyNonReleasedVersions?: boolean,
message?: string
} = {}) : Promise<string> {
const napDescriptorStrings = await getNapDescriptorStringsFromCauldron({
platform,
onlyReleasedVersions,
onlyNonReleasedVersions
})
if (_.isEmpty(napDescriptorStrings)) {
throw new Error('Could not find any qualifying native application version in the Cauldron')
}
const { userSelectedCompleteNapDescriptor } = await inquirer.prompt([{
type: 'list',
name: 'userSelectedCompleteNapDescriptor',
message: message || 'Choose a native application version',
choices: napDescriptorStrings
}])
return userSelectedCompleteNapDescriptor
}
//
// Inquire user to choose one or more native application version(s) from the Cauldron, optionally
// filtered by platform/and or release status and returns the selected choices as an array of strings
async function askUserToChooseOneOrMoreNapDescriptorFromCauldron ({
platform,
onlyReleasedVersions,
onlyNonReleasedVersions,
message
} : {
platform?: 'ios' | 'android',
onlyReleasedVersions?: boolean,
onlyNonReleasedVersions?: boolean,
message?: string
} = {}) : Promise<Array<string>> {
const napDescriptorStrings = await getNapDescriptorStringsFromCauldron({
platform,
onlyReleasedVersions,
onlyNonReleasedVersions
})
if (_.isEmpty(napDescriptorStrings)) {
throw new Error('Could not find any qualifying native application version in the Cauldron')
}
const { userSelectedCompleteNapDescriptors } = await inquirer.prompt([{
type: 'checkbox',
name: 'userSelectedCompleteNapDescriptors',
message: message || 'Choose a native application version',
choices: napDescriptorStrings
}])
return userSelectedCompleteNapDescriptors
}
//
// Perform some custom work on a container in Cauldron, provided as a
// function, that is going to change the state of the container,
// and regenerate a new container and publish it.
// If any part of this function fails, the Cauldron will not get updated
async function performContainerStateUpdateInCauldron (
stateUpdateFunc: () => Promise<*>,
napDescriptor: NativeApplicationDescriptor,
commitMessage: string | Array<string>, {
containerVersion
} : {
containerVersion?: string
} = {}) {
try {
var cauldron = await coreUtils.getCauldronInstance()
let cauldronContainerVersion
if (containerVersion) {
cauldronContainerVersion = containerVersion
} else {
cauldronContainerVersion = await cauldron.getTopLevelContainerVersion(napDescriptor)
if (cauldronContainerVersion) {
cauldronContainerVersion = semver.inc(cauldronContainerVersion, 'patch')
} else {
// Default to 1.0.0 for Container version
cauldronContainerVersion = '1.0.0'
}
}
// Begin a Cauldron transaction
await cauldron.beginTransaction()
// Perform the custom container state update
await stateUpdateFunc()
// Run container generator
await spin(`Generating new container version ${cauldronContainerVersion} for ${napDescriptor.toString()}`,
runCauldronContainerGen(
napDescriptor,
cauldronContainerVersion,
{ publish: true }))
// Update container version in Cauldron
await cauldron.updateContainerVersion(napDescriptor, cauldronContainerVersion)
// Commit Cauldron transaction
await spin(`Updating Cauldron`, cauldron.commitTransaction(commitMessage))
log.debug(`Published new container version ${cauldronContainerVersion} for ${napDescriptor.toString()}`)
} catch (e) {
log.error(`[performContainerStateUpdateInCauldron] An error occurred: ${e}`)
if (cauldron) {
cauldron.discardTransaction()
}
throw e
}
}
function epilog ({command} : {command: string}) {
const rootUrl = 'https://electrode.gitbooks.io/electrode-native/content/cli'
const commandWithoutOptions = command.split(' ')[0]
const idx = _.indexOf(process.argv, commandWithoutOptions)
let commandPath = _.slice(process.argv, 2, idx).join('/')
commandPath = commandPath ? `/${commandPath}` : ''
return `More info about this command @ ${chalk.bold(`${rootUrl}${commandPath}/${commandWithoutOptions}.html`)}`
}
async function runMiniApp (platform: 'android' | 'ios', {
mainMiniAppName,
miniapps,
dependencies,
descriptor,
dev
} : {
mainMiniAppName?: string,
miniapps?: Array<string>,
dependencies?: Array<string>,
descriptor?: string,
dev?: boolean
} = {}) {
const cwd = process.cwd()
let napDescriptor: ?NativeApplicationDescriptor
if (miniapps && miniapps.length > 1 && !mainMiniAppName) {
throw new Error('If you provide multiple MiniApps you need to provide the name of the MiniApp to launch')
}
if (miniapps && miniapps.length > 1 && dev) {
throw new Error('You cannot enable development mode yet when running multiple MiniApps')
}
if (dependencies && (dependencies.length > 0) && descriptor) {
throw new Error('You cannot pass extra native dependencies when using a Native Application Descriptor')
}
if (miniapps && descriptor) {
throw new Error('You cannot use miniapps and descriptor at the same time')
}
if (descriptor) {
await utils.logErrorAndExitIfNotSatisfied({
isCompleteNapDescriptorString: { descriptor },
napDescriptorExistInCauldron: {
descriptor,
extraErrorMessage: 'You cannot create a Runner for a non existing native application version.'
}
})
napDescriptor = NativeApplicationDescriptor.fromString(descriptor)
}
let entryMiniAppName = mainMiniAppName || ''
let dependenciesObjs = []
let miniAppsPaths = []
if (miniapps) {
if (MiniApp.existInPath(cwd)) {
const miniapp = MiniApp.fromPath(cwd)
miniAppsPaths = [ DependencyPath.fromFileSystemPath(cwd) ]
log.debug(`This command is being run from the ${miniapp.name} MiniApp directory.`)
log.info(`All extra MiniApps will be included in the Runner container along with ${miniapp.name}`)
if (!mainMiniAppName) {
log.info(`${miniapp.name} will be set as the main MiniApp`)
log.info(`You can select another one instead through '--mainMiniAppName' option`)
entryMiniAppName = miniapp.name
}
}
dependenciesObjs = _.map(dependencies, d => Dependency.fromString(d))
miniAppsPaths = miniAppsPaths.concat(_.map(miniapps, m => DependencyPath.fromString(m)))
} else if (!miniapps && !descriptor) {
entryMiniAppName = MiniApp.fromCurrentPath().name
log.debug(`This command is being run from the ${entryMiniAppName} MiniApp directory.`)
log.debug(`Initializing Runner`)
dependenciesObjs = _.map(dependencies, d => Dependency.fromString(d))
miniAppsPaths = [ DependencyPath.fromFileSystemPath(cwd) ]
if (dev === undefined) { // If dev is not defined it will default to true in the case of standalone MiniApp runner
dev = true
await reactnative.startPackagerInNewWindow(cwd)
}
}
await generateContainerForRunner(platform, {
napDescriptor: napDescriptor || undefined,
dependenciesObjs,
miniAppsPaths
})
const pathToRunner = path.join(cwd, platform)
if (!fs.existsSync(pathToRunner)) {
shell.mkdir('-p', pathToRunner)
await spin(`Generating ${platform} Runner project`,
generateRunnerProject(
platform,
pathToRunner,
path.join(Platform.rootDirectory, 'containergen'),
entryMiniAppName,
{ reactNativeDevSupportEnabled: dev }))
} else {
await spin(`Regenerating ${platform} Runner Configuration`,
regenerateRunnerConfig(
platform,
pathToRunner,
path.join(Platform.rootDirectory, 'containergen'),
entryMiniAppName,
{ reactNativeDevSupportEnabled: dev }))
}
await launchRunner(platform, pathToRunner)
}
async function generateContainerForRunner (
platform: 'android' | 'ios', {
napDescriptor,
dependenciesObjs = [],
miniAppsPaths = []
} : {
napDescriptor?: NativeApplicationDescriptor,
dependenciesObjs: Array<Dependency>,
miniAppsPaths: Array<DependencyPath>
} = {}) {
if (napDescriptor) {
await runCauldronContainerGen(
napDescriptor,
'1.0.0', {
publish: false,
containerName: 'runner'
})
} else {
await spin('Generating Container locally', runLocalContainerGen(
miniAppsPaths,
platform, {
containerVersion: '1.0.0',
nativeAppName: 'runner',
extraNativeDependencies: dependenciesObjs
}))
}
}
async function launchRunner (platform: string, pathToRunner: string) {
if (platform === 'android') {
return launchAndroidRunner(pathToRunner)
} else if (platform === 'ios') {
return launchIosRunner(pathToRunner)
}
}
async function launchAndroidRunner (pathToAndroidRunner: string) {
return runAndroidProject({
projectPath: pathToAndroidRunner,
packageName: 'com.walmartlabs.ern'
})
}
async function launchIosRunner (pathToIosRunner: string) {
const iosDevices = ios.getiPhoneRealDevices()
if (iosDevices && iosDevices.length > 0) {
launchOnDevice(pathToIosRunner, iosDevices)
} else {
launchOnSimulator(pathToIosRunner)
}
}
async function launchOnDevice (pathToIosRunner: string, devices) {
const iPhoneDevice = await ios.askUserToSelectAniPhoneDevice(devices)
shell.cd(pathToIosRunner)
const spinner = ora('Waiting for device to boot').start()
try {
spinner.text = 'Building iOS Runner project'
await buildIosRunner(pathToIosRunner, iPhoneDevice.udid)
.then(() => {
const iosDeployInstallArgs = [
'--bundle', `${pathToIosRunner}/build/Debug-iphoneos/ErnRunner.app`,
'--id', iPhoneDevice.udid,
'--justlaunch'
]
log.info(`Start installing ErnRunner on ${iPhoneDevice.name}...`)
const iosDeployOutput = spawnSync('ios-deploy', iosDeployInstallArgs, {encoding: 'utf8'})
if (iosDeployOutput.error) {
log.error('INSTALLATION FAILED')
log.warn('Make sure you have done "npm install -g ios-deploy".')
} else {
spinner.succeed('Installed and Launched ErnRunner on device ')
}
})
} catch (e) {
spinner.fail(e.message)
throw e
}
}
async function launchOnSimulator (pathToIosRunner: string) {
const iPhoneSim = await ios.askUserToSelectAniPhoneSimulator()
await ios.killAllRunningSimulators()
const spinner = ora(`Waiting for device to boot`).start()
await ios.launchSimulator(iPhoneSim.udid)
shell.cd(pathToIosRunner)
try {
spinner.text = 'Building iOS Runner project'
await buildIosRunner(pathToIosRunner, iPhoneSim.udid)
spinner.text = 'Installing runner project on simulator'
await ios.installApplicationOnSimulator(iPhoneSim.udid, `${pathToIosRunner}/build/Debug-iphonesimulator/ErnRunner.app`)
spinner.text = 'Launching runner project'
await ios.launchApplication(iPhoneSim.udid, 'com.yourcompany.ernrunner')
spinner.succeed('Done')
} catch (e) {
spinner.fail(e.message)
throw e
}
}
async function buildIosRunner (pathToIosRunner: string, udid: string) {
return new Promise((resolve, reject) => {
const xcodebuildProc = spawn('xcodebuild', [
`-scheme`, 'ErnRunner', 'build',
`-destination`, `id=${udid}`,
`SYMROOT=${pathToIosRunner}/build` ],
{ cwd: pathToIosRunner })
xcodebuildProc.stdout.on('data', data => {
log.debug(data)
})
xcodebuildProc.stderr.on('data', data => {
log.debug(data)
})
xcodebuildProc.on('close', code => {
code === 0
? resolve()
: reject(new Error(`XCode xcbuild command failed with exit code ${code}`))
})
})
}
async function doesPackageExistInNpm (packageName: string) : Promise<boolean> {
try {
const result = await yarn.info(DependencyPath.fromString(packageName), {field: 'versions 2> /dev/null', json: true})
if (result && result.type === `inspect`) {
return true
}
} catch (e) {
// If the package name doesn't exist in the NPM registry, Do nothing
// {"type":"error","data":"Received invalid response from npm."}
}
return false
}
async function performPkgNameConflictCheck (name: string) : Promise<boolean> {
// check if the packageName exists
let isPackageNameInNpm = await doesPackageExistInNpm(name)
if (isPackageNameInNpm) {
const {continueIfPkgNameExists} = await inquirer.prompt([{
type: 'confirm',
name: 'continueIfPkgNameExists',
message: `The package with name ${name} is already published in NPM registry. Do you wish to continue?`,
default: false
}])
return continueIfPkgNameExists
}
return true // If package name doesn't exist continue with command execution
}
function checkIfModuleNameContainsSuffix (moduleName: string, moduleType: string): boolean {
if (moduleName) {
switch (moduleType) {
case ModuleTypes.MINIAPP:
return moduleName.toUpperCase().indexOf('MINIAPP') > -1
case ModuleTypes.API:
return moduleName.toUpperCase().indexOf('API') > -1
case ModuleTypes.JS_API_IMPL:
return moduleName.toUpperCase().indexOf('APIIMPLJS') > -1
case ModuleTypes.NATIVE_API_IMPL:
return moduleName.toUpperCase().indexOf('APIIMPLNATIVE') > -1
default:
return false
}
}
return false
}
async function promptUserToUseSuffixModuleName (moduleName: string, moduleType: string): Promise<string> {
let message = ''
let suffixedModuleName = moduleName
if (moduleName) {
switch (moduleType) {
case ModuleTypes.MINIAPP:
suffixedModuleName = `${moduleName}MiniApp`
message = `We recommend suffixing the name of ${moduleName} with MiniApp, Do you want to use ${suffixedModuleName}?`
break
case ModuleTypes.API:
suffixedModuleName = `${moduleName}Api`
message = `We recommend suffixing the name of ${moduleName} with Api, Do you want to use ${suffixedModuleName}?`
break
case ModuleTypes.JS_API_IMPL:
suffixedModuleName = `${moduleName}ApiImplJs`
message = `We recommend suffixing the name of ${moduleName} with ApiImplJs, Do you want to use ${suffixedModuleName}?`
break
case ModuleTypes.NATIVE_API_IMPL:
suffixedModuleName = `${moduleName}ApiImplNative`
message = `We recommend suffixing the name of ${moduleName} with ApiImplNative, Do you want to use ${suffixedModuleName}?`
break
default:
throw new Error(`Unsupported module type : ${moduleType}`)
}
}
const {useSuffixedModuleName} = await inquirer.prompt(
{
type: 'confirm',
name: 'useSuffixedModuleName',
message: message,
default: true
}
)
return useSuffixedModuleName ? suffixedModuleName : moduleName
}
async function getDescriptorsMatchingSemVerDescriptor (semVerDescriptor: NativeApplicationDescriptor)
: Promise<Array<NativeApplicationDescriptor>> {
if (!semVerDescriptor.platform || !semVerDescriptor.version) {
throw new Error(`${semVerDescriptor.toString()} descriptor is missing platform and/or version`)
}
const result = []
const cauldron = await coreUtils.getCauldronInstance()
const versionsNames = await cauldron.getVersionsNames(semVerDescriptor)
const semVerVersionNames = normalizeVersionsToSemver(versionsNames)
const zippedVersions = _.zipWith(versionsNames, semVerVersionNames, (nonSemVer, semVer) => ({nonSemVer, semVer}))
const versions = _.filter(zippedVersions, z => semver.satisfies(z.semVer, semVerDescriptor.version))
for (const version of versions) {
const descriptor = new NativeApplicationDescriptor(semVerDescriptor.name, semVerDescriptor.platform, version.nonSemVer)
result.push(descriptor)
}
return result
}
function normalizeVersionsToSemver (versions: Array<string>) : Array<string> {
const validSemVerRe = /^\d+\.\d+.\d+.*/
const versionMissingPatchRe = /^(\d+\.\d+)(.*)/
const versionMissingMinorRe = /^(\d+)(.*)/
return _.map(versions, v => {
if (validSemVerRe.test(v)) {
return v
} else {
if (versionMissingPatchRe.test(v)) {
return v.replace(versionMissingPatchRe, '$1.0$2')
} else if (versionMissingMinorRe.test(v)) {
return v.replace(versionMissingMinorRe, '$1.0.0$2')
}
}
})
}
export default {
getNapDescriptorStringsFromCauldron,
logErrorAndExitIfNotSatisfied,
askUserToChooseANapDescriptorFromCauldron,
askUserToChooseOneOrMoreNapDescriptorFromCauldron,
performContainerStateUpdateInCauldron,
epilog,
runMiniApp,
doesPackageExistInNpm,
performPkgNameConflictCheck,
checkIfModuleNameContainsSuffix,
promptUserToUseSuffixModuleName,
getDescriptorsMatchingSemVerDescriptor,
normalizeVersionsToSemver
}