forked from bitrise-steplib/steps-avd-manager
-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
executable file
·422 lines (356 loc) · 12.1 KB
/
main.go
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
package main
import (
"bufio"
"fmt"
"os"
"path/filepath"
"regexp"
"strconv"
"strings"
"time"
"github.com/bitrise-steplib/steps-avd-manager/avdconfig"
"github.com/bitrise-tools/go-steputils/input"
"github.com/bitrise-tools/go-steputils/tools"
shellquote "github.com/kballard/go-shellquote"
"github.com/bitrise-io/depman/pathutil"
"github.com/bitrise-io/go-utils/command"
"github.com/bitrise-io/go-utils/log"
)
// ConfigsModel ...
type ConfigsModel struct {
Version string
Resolution string
Orientation string
AndroidHome string
Tag string
ID string
CustomConfig string
Density string
Overwrite string
CustomCommandFlags string
Abi string
Profile string
Verbose string
EmulatorChannel string
}
func createConfigsModelFromEnvs() ConfigsModel {
return ConfigsModel{
Version: os.Getenv("version"),
Resolution: os.Getenv("resolution"),
Orientation: os.Getenv("orientation"),
Tag: os.Getenv("tag"),
ID: os.Getenv("emulator_id"),
Density: os.Getenv("density"),
Overwrite: os.Getenv("overwrite"),
CustomConfig: os.Getenv("custom_hw_config"),
AndroidHome: os.Getenv("ANDROID_HOME"),
CustomCommandFlags: os.Getenv("custom_command_flags"),
Abi: os.Getenv("emulator_abi"),
Profile: os.Getenv("profile"),
Verbose: os.Getenv("verbose_mode"),
EmulatorChannel: os.Getenv("emulator_channel"),
}
}
func (configs ConfigsModel) print() {
log.Infof("Configs:")
log.Printf("- Version: %s", configs.Version)
log.Printf("- Resolution: %s", configs.Resolution)
log.Printf("- Density: %s", configs.Density)
log.Printf("- Orientation: %s", configs.Orientation)
log.Printf("- Tag: %s", configs.Tag)
log.Printf("- ABI: %s", configs.Abi)
log.Printf("- Profile: %s", configs.Profile)
log.Printf("- ID: %s", configs.ID)
log.Printf("- CustomCommandFlags: %s", configs.CustomCommandFlags)
log.Printf("- Overwrite: %s", configs.Overwrite)
log.Printf("- CustomConfig:\n%s", configs.CustomConfig)
log.Printf("- EmulatorChannel: %s", configs.EmulatorChannel)
}
func (configs ConfigsModel) validate() error {
if err := input.ValidateIfNotEmpty(configs.Version); err != nil {
return fmt.Errorf("Version, %s", err)
}
if err := input.ValidateIfNotEmpty(configs.Overwrite); err != nil {
return fmt.Errorf("Overwrite, %s", err)
}
if err := input.ValidateWithOptions(configs.Overwrite, "true", "false"); err != nil {
return fmt.Errorf("Overwrite, %s", err)
}
if err := input.ValidateIfNotEmpty(configs.ID); err != nil {
return fmt.Errorf("ID, %s", err)
}
if err := input.ValidateIfNotEmpty(configs.Orientation); err != nil {
return fmt.Errorf("Orientation, %s", err)
}
if err := input.ValidateWithOptions(configs.Orientation, "portrait", "landscape"); err != nil {
return fmt.Errorf("Orientation, %s", err)
}
if err := input.ValidateIfNotEmpty(configs.Abi); err != nil {
return fmt.Errorf("Abi is not set")
}
if err := input.ValidateIfNotEmpty(configs.Profile); err != nil {
return fmt.Errorf("Profile is not set")
}
if err := input.ValidateIfNotEmpty(configs.AndroidHome); err != nil {
return fmt.Errorf("ANDROID_HOME is not set")
}
if err := input.ValidateIfPathExists(configs.AndroidHome); err != nil {
return fmt.Errorf("ANDROID_HOME does not exists")
}
if err := input.ValidateIfNotEmpty(configs.Tag); err != nil {
return fmt.Errorf("Tag, %s", err)
}
if err := input.ValidateWithOptions(configs.Tag, "google_apis", "google_apis_playstore", "android-wear", "android-tv", "default"); err != nil {
return fmt.Errorf("Tag, %s", err)
}
if err := input.ValidateWithOptions(configs.Abi, "x86", "armeabi-v7a", "arm64-v8a", "x86_64", "mips"); err != nil {
return fmt.Errorf("Abi, %s", err)
}
if err := input.ValidateWithOptions(configs.EmulatorChannel, "0", "1", "2", "3"); err != nil {
return fmt.Errorf("EmulatorChannel, %s", err)
}
return nil
}
func runningDeviceInfos(androidHome string) (map[string]string, error) {
cmd := command.New(filepath.Join(androidHome, "platform-tools/adb"), "devices")
out, err := cmd.RunAndReturnTrimmedCombinedOutput()
if err != nil {
return map[string]string{}, fmt.Errorf("command failed, error: %s", err)
}
// List of devices attached
// emulator-5554 device
deviceListItemPattern := `^(?P<emulator>emulator-\d*)[\s+](?P<state>.*)`
deviceListItemRegexp := regexp.MustCompile(deviceListItemPattern)
deviceStateMap := map[string]string{}
scanner := bufio.NewScanner(strings.NewReader(out))
for scanner.Scan() {
line := scanner.Text()
matches := deviceListItemRegexp.FindStringSubmatch(line)
if len(matches) == 3 {
serial := matches[1]
state := matches[2]
deviceStateMap[serial] = state
}
}
if scanner.Err() != nil {
return map[string]string{}, fmt.Errorf("scanner failed, error: %s", err)
}
return deviceStateMap, nil
}
func failf(msg string, args ...interface{}) {
log.Errorf(msg, args...)
os.Exit(1)
}
func currentlyStartedDeviceSerial(alreadyRunningDeviceInfos, currentlyRunningDeviceInfos map[string]string) string {
startedSerial := ""
for serial := range currentlyRunningDeviceInfos {
_, found := alreadyRunningDeviceInfos[serial]
if !found {
startedSerial = serial
break
}
}
if len(startedSerial) > 0 {
state := currentlyRunningDeviceInfos[startedSerial]
if state == "device" {
return startedSerial
}
}
return ""
}
func ensureResolutionOrientation(res, orientation string) (string, error) {
sides := strings.Split(res, "x")
if len(sides) != 2 {
return "", fmt.Errorf("invalid resolution format: %s", res)
}
a, err := strconv.Atoi(sides[0])
if err != nil {
return "", err
}
b, err := strconv.Atoi(sides[1])
if err != nil {
return "", err
}
if strings.ToLower(orientation) == "portrait" {
if a < b {
return fmt.Sprintf("%dx%d", a, b), nil
}
return fmt.Sprintf("%dx%d", b, a), nil
}
if a > b {
return fmt.Sprintf("%dx%d", a, b), nil
}
return fmt.Sprintf("%dx%d", b, a), nil
}
func main() {
// Input validation
configs := createConfigsModelFromEnvs()
fmt.Println()
configs.print()
if err := configs.validate(); err != nil {
fmt.Println()
log.Errorf("Issue with input: %s", err)
os.Exit(1)
}
fmt.Println()
// update ensure the new sdkmanager, avdmanager
{
requiredSDKPackages := []string{"tools", "platform-tools", fmt.Sprintf("system-images;android-%s;%s;%s", configs.Version, configs.Tag, configs.Abi)}
log.Infof("Ensure sdk packages: %v", requiredSDKPackages)
out, err := command.New(filepath.Join(configs.AndroidHome, "tools/bin/sdkmanager"), requiredSDKPackages...).RunAndReturnTrimmedCombinedOutput()
if err != nil {
failf("Failed to update emulator sdk package, error: %s, output: %s", err, out)
}
// getting emulator from different channel
out, err = command.New(filepath.Join(configs.AndroidHome, "tools/bin/sdkmanager"), "emulator", fmt.Sprintf("--channel=%s", configs.EmulatorChannel)).RunAndReturnTrimmedCombinedOutput()
if err != nil {
failf("Failed to update emulator sdk package, error: %s, output: %s", err, out)
}
log.Donef("- Done")
}
avdPath := filepath.Join(os.Getenv("HOME"), ".android/avd", fmt.Sprintf("%s.avd", configs.ID))
avdPathExists, err := pathutil.IsPathExists(avdPath)
if err != nil {
log.Errorf("Failed to check if path exists: %s", err)
os.Exit(1)
}
iniPath := filepath.Join(os.Getenv("HOME"), ".android/avd", fmt.Sprintf("%s.ini", configs.ID))
iniPathExists, err := pathutil.IsPathExists(iniPath)
if err != nil {
log.Errorf("Failed to check if path exists: %s", err)
os.Exit(1)
}
if configs.Overwrite == "true" {
if iniPathExists || avdPathExists {
fmt.Println()
log.Infof("Delete AVD")
if avdPathExists {
if err := os.RemoveAll(avdPath); err != nil {
log.Errorf("Failed to remove avd dir: %s", err)
os.Exit(1)
}
}
if iniPathExists {
if err := os.RemoveAll(iniPath); err != nil {
log.Errorf("Failed to remove ini file: %s", err)
os.Exit(1)
}
}
avdPathExists = false
iniPathExists = false
log.Donef("- Done")
}
}
// create emulator
{
if !iniPathExists || !avdPathExists {
fmt.Println()
log.Infof("Create AVD")
customProperties, err := avdconfig.NewProperties(strings.Split(configs.CustomConfig, "\n"))
if err != nil {
failf("Failed to parse custom properties, error: %s", err)
}
// -c 100M
cmd := command.New(filepath.Join(configs.AndroidHome, "tools/bin/avdmanager"), "create", "avd", "-f",
"-n", configs.ID,
"-b", configs.Abi,
"-g", configs.Tag,
"-d", configs.Profile,
"-c", customProperties.Get("sdcard.size", "128M"),
"-k", fmt.Sprintf("system-images;android-%s;%s;%s", configs.Version, configs.Tag, configs.Abi))
if out, err := cmd.RunAndReturnTrimmedCombinedOutput(); err != nil {
failf("Failed to create avd, error: %s output: %s", err, out)
}
avdConfig, err := avdconfig.Parse(filepath.Join(os.Getenv("HOME"), fmt.Sprintf(".android/avd/%s.avd/config.ini", configs.ID)))
if err != nil {
failf("Failed to parse config properties, error: %s", err)
}
if configs.Resolution != "" {
avdConfig.Properties.Apply("skin.name", configs.Resolution)
} else {
if avdConfig.Properties.Get("skin.name", "") == "" {
width := avdConfig.Properties.Get("hw.lcd.width", "")
height := avdConfig.Properties.Get("hw.lcd.height", "")
if width != "" && height != "" {
avdConfig.Properties.Apply("skin.name", fmt.Sprintf("%sx%s", width, height))
}
}
}
if configs.Density != "" {
avdConfig.Properties.Apply("hw.lcd.density", configs.Density)
}
avdConfig.Properties.Apply("PlayStore.enabled", fmt.Sprintf("%t", configs.Tag == "google_apis_playstore"))
avdConfig.Properties.Apply("hw.initialOrientation", strings.Title(configs.Orientation))
avdConfig.Properties.Append(customProperties)
// ensure width and height are matching orientation
{
skin := avdConfig.Properties.Get("skin.name", "")
if skin != "" {
res, err := ensureResolutionOrientation(skin, configs.Orientation)
if err != nil {
failf("Failed to ensure device resolution, error: %s", err)
}
avdConfig.Properties.Apply("skin.name", res)
}
}
if err := avdConfig.Save(); err != nil {
failf("Failed to save avd config, error: %s", err)
}
log.Donef("- Done")
} else {
fmt.Println()
log.Donef("Using existing AVD")
}
}
// get currently running devices
runningDevices, err := runningDeviceInfos(configs.AndroidHome)
if err != nil {
failf("Failed to check running devices, error: %s", err)
}
fmt.Println()
// run emulator
{
log.Infof("Start emulator")
customFlags, err := shellquote.Split(configs.CustomCommandFlags)
if err != nil {
log.Errorf("Failed to parse commands, error: %s", err)
os.Exit(1)
}
cmdSlice := []string{"-avd", configs.ID}
cmdSlice = append(cmdSlice, customFlags...)
cmd := command.New(filepath.Join(configs.AndroidHome, "emulator/emulator"), cmdSlice...)
osCommand := cmd.GetCmd()
if configs.Verbose == "true" {
osCommand.Stderr = os.Stderr
osCommand.Stdout = os.Stdout
}
err = osCommand.Start()
if err != nil {
failf("Failed to start emulator, error: %s", err)
}
deviceDetectionStarted := time.Now()
for true {
time.Sleep(5 * time.Second)
if osCommand.ProcessState != nil && osCommand.ProcessState.Exited() {
failf("Emulator exited, error: %s", err)
}
currentRunningDevices, err := runningDeviceInfos(configs.AndroidHome)
if err != nil {
failf("Failed to check running devices, error: %s", err)
}
serial := currentlyStartedDeviceSerial(runningDevices, currentRunningDevices)
if serial != "" {
if err := tools.ExportEnvironmentWithEnvman("BITRISE_EMULATOR_SERIAL", serial); err != nil {
log.Warnf("Failed to export environment (BITRISE_EMULATOR_SERIAL), error: %s", err)
}
log.Printf("- Device with serial: %s started", serial)
break
}
bootWaitTime := time.Duration(300)
if time.Now().After(deviceDetectionStarted.Add(bootWaitTime * time.Second)) {
failf("Failed to boot emulator device within %d seconds.", bootWaitTime)
}
}
log.Donef("- Done")
}
}