-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrun.js
executable file
·119 lines (102 loc) · 3.05 KB
/
run.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
#!/usr/bin/env node
const program = require('commander')
const { spawn } = require('child_process')
const inquirer = require('inquirer')
const exitWithErrorMessage = message => {
console.log('')
console.log(message)
process.exit(1)
}
const getAvailableOsWithDevices = (acc, curr) => {
if (acc.currentDeviceSection && !curr.startsWith('--')) {
const device = curr.match(/(.*)\s\(([a-zA-Z0-9-]+)\)\s\([a-zA-Z]+\)$/i)
const isFirstArrayConstruction = acc.devices[acc.currentDeviceSection]
return device
? {
...acc,
devices: {
...acc.devices,
[acc.currentDeviceSection]: isFirstArrayConstruction
? [
...acc.devices[acc.currentDeviceSection],
{ name: device[1], id: device[2] },
]
: [{ name: device[1], id: device[2] }],
},
}
: acc
}
const matchOsHeadline = curr.match(/^--\siOS\s([0-9.]+)\s--/)
return matchOsHeadline
? { ...acc, currentDeviceSection: matchOsHeadline[1] }
: { ...acc, currentDeviceSection: null }
}
const getAvailableEmulatorsData = data =>
new Promise(resolve => {
const outputArray = data
.toString()
.split('\n')
.map(item => item.replace(/^ +(?=)/g, ''))
const filteredOutput = outputArray.reduce(getAvailableOsWithDevices, {
devices: {},
})
resolve(filteredOutput.devices)
})
const chooseOsPrompt = ({ choices }) =>
choices.length > 1
? inquirer.prompt([
{
type: 'list',
name: 'chosenOs',
message: 'Choose the OS you want to run:',
choices,
pageSize: 40,
},
])
: Promise.resolve({ chosenOs: choices[0] })
const chooseDevice = ({ choices }) =>
inquirer.prompt([
{
type: 'list',
name: 'chosenDevice',
message: 'Choose the device you want to use:',
choices,
pageSize: 40,
},
])
const run = () => {
const cmd = spawn('xcrun', ['simctl', 'list'])
cmd.stdout.on('data', data =>
getAvailableEmulatorsData(data)
.then(devices => {
const availableOs = Object.keys(devices)
if (availableOs.length) {
chooseOsPrompt({
choices: availableOs.reverse(),
}).then(({ chosenOs }) =>
chooseDevice({
choices: devices[chosenOs].map(item => item.name),
}).then(({ chosenDevice }) => {
const device = devices[chosenOs].reduce(
(acc, curr) => (curr.name === chosenDevice ? curr : acc),
{}
)
if (!device.id) {
exitWithErrorMessage("Couldn't find a matching emulator")
}
spawn('xcrun', ['simctl', 'boot', device.id])
spawn('open', [
'/Applications/Xcode.app/Contents/Developer/Applications/Simulator.app',
])
})
)
}
})
.catch(e => exitWithErrorMessage(e))
)
}
program
.version('0.1.0')
.usage('launch-emulator')
.action(run)
.parse(process.argv)