forked from bitrise-steplib/steps-xcode-build-for-simulator
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
711 lines (598 loc) · 23.5 KB
/
main.go
File metadata and controls
711 lines (598 loc) · 23.5 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
package main
import (
"fmt"
"os"
"path"
"path/filepath"
"strings"
"github.com/bitrise-io/go-steputils/stepconf"
"github.com/bitrise-io/go-steputils/tools"
"github.com/bitrise-io/go-utils/errorutil"
"github.com/bitrise-io/go-utils/log"
"github.com/bitrise-io/go-utils/pathutil"
"github.com/bitrise-io/go-utils/sliceutil"
"github.com/bitrise-io/go-utils/stringutil"
"github.com/bitrise-io/go-xcode/simulator"
"github.com/bitrise-io/go-xcode/utility"
"github.com/bitrise-io/go-xcode/xcodebuild"
cache "github.com/bitrise-io/go-xcode/xcodecache"
"github.com/bitrise-io/go-xcode/xcpretty"
"github.com/bitrise-io/xcode-project/serialized"
"github.com/bitrise-io/xcode-project/xcodeproj"
"github.com/bitrise-io/xcode-project/xcscheme"
"github.com/bitrise-io/xcode-project/xcworkspace"
"github.com/bitrise-steplib/steps-xcode-archive/utils"
"github.com/bitrise-steplib/steps-xcode-build-for-simulator/util"
shellquote "github.com/kballard/go-shellquote"
)
const (
minSupportedXcodeMajorVersion = 7
iOSSimName = "iphonesimulator"
tvOSSimName = "appletvsimulator"
watchOSSimName = "watchsimulator"
)
const (
bitriseXcodeRawResultTextEnvKey = "BITRISE_XCODE_RAW_RESULT_TEXT_PATH"
)
// Config ...
type Config struct {
ProjectPath string `env:"project_path,required"`
Scheme string `env:"scheme,required"`
Configuration string `env:"configuration"`
ArtifactName string `env:"artifact_name"`
XcodebuildOptions string `env:"xcodebuild_options"`
Workdir string `env:"workdir"`
OutputDir string `env:"output_dir,required"`
IsCleanBuild bool `env:"is_clean_build,opt[yes,no]"`
OutputTool string `env:"output_tool,opt[xcpretty,xcodebuild]"`
SimulatorDevice string `env:"simulator_device,required"`
SimulatorOsVersion string `env:"simulator_os_version,required"`
SimulatorPlatform string `env:"simulator_platform,opt[iOS,tvOS]"`
DisableIndexWhileBuilding bool `env:"disable_index_while_building,opt[yes,no]"`
VerboseLog bool `env:"verbose_log,required"`
CacheLevel string `env:"cache_level,opt[none,swift_packages]"`
}
func main() {
// Config
var cfg Config
if err := stepconf.Parse(&cfg); err != nil {
failf("Issue with input: %s", err)
}
stepconf.Print(cfg)
fmt.Println()
log.SetEnableDebugLog(cfg.VerboseLog)
// Determined configs
log.Infof("Step determined configs:")
// Detect Xcode major version
xcodebuildVersion, err := utility.GetXcodeVersion()
if err != nil {
failf("Failed to determin xcode version, error: %s", err)
}
log.Printf("- xcodebuildVersion: %s (%s)", xcodebuildVersion.Version, xcodebuildVersion.BuildVersion)
xcodeMajorVersion := xcodebuildVersion.MajorVersion
if xcodeMajorVersion < minSupportedXcodeMajorVersion {
failf("Invalid xcode major version (%d), should not be less then min supported: %d", xcodeMajorVersion, minSupportedXcodeMajorVersion)
}
outputTool := cfg.OutputTool
{
// Detect xcpretty version
if outputTool == "xcpretty" {
fmt.Println()
log.Infof("Checking if output tool (xcpretty) is installed")
installed, err := xcpretty.IsInstalled()
if err != nil {
log.Warnf("Failed to check if xcpretty is installed, error: %s", err)
log.Printf("Switching to xcodebuild for output tool")
outputTool = "xcodebuild"
} else if !installed {
log.Warnf(`xcpretty is not installed`)
fmt.Println()
log.Printf("Installing xcpretty")
if cmds, err := xcpretty.Install(); err != nil {
log.Warnf("Failed to create xcpretty install command: %s", err)
log.Warnf("Switching to xcodebuild for output tool")
outputTool = "xcodebuild"
} else {
for _, cmd := range cmds {
if out, err := cmd.RunAndReturnTrimmedCombinedOutput(); err != nil {
if errorutil.IsExitStatusError(err) {
log.Warnf("%s failed: %s", out)
} else {
log.Warnf("%s failed: %s", err)
}
log.Warnf("Switching to xcodebuild for output tool")
outputTool = "xcodebuild"
}
}
}
}
}
if outputTool == "xcpretty" {
xcprettyVersion, err := xcpretty.Version()
if err != nil {
log.Warnf("Failed to determine xcpretty version, error: %s", err)
log.Printf("Switching to xcodebuild for output tool")
outputTool = "xcodebuild"
}
log.Printf("- xcprettyVersion: %s", xcprettyVersion.String())
}
}
// ABS out dir pth
absOutputDir, err := pathutil.AbsPath(cfg.OutputDir)
if err != nil {
failf("Failed to expand OutputDir (%s), error: %s", cfg.OutputDir, err)
}
if exist, err := pathutil.IsPathExists(absOutputDir); err != nil {
failf("Failed to check if OutputDir exist, error: %s", err)
} else if !exist {
if err := os.MkdirAll(absOutputDir, 0777); err != nil {
failf("Failed to create OutputDir (%s), error: %s", absOutputDir, err)
}
}
// Output files
rawXcodebuildOutputLogPath := filepath.Join(absOutputDir, "raw-xcodebuild-output.log")
//
// Cleanup
{
filesToCleanup := []string{
rawXcodebuildOutputLogPath,
}
for _, pth := range filesToCleanup {
if err := os.RemoveAll(pth); err != nil {
failf("Failed to remove path (%s), error: %s", pth, err)
}
}
}
//
// Get simulator info from the provided OS, platform and device
var simulatorID string
{
fmt.Println()
log.Infof("Simulator info")
// Simulator Destination
simulatorID, err = simulatorDestinationID(cfg.SimulatorOsVersion, cfg.SimulatorPlatform, cfg.SimulatorDevice)
if err != nil {
failf("Failed to find simulator, error: %s", err)
}
}
absProjectPath, err := filepath.Abs(cfg.ProjectPath)
if err != nil {
failf("Failed to get absolute project path: %s", err)
}
//
// Read the Scheme
var scheme *xcscheme.Scheme
var schemeContainerDir string
var conf string
{
scheme, schemeContainerDir, err = readScheme(absProjectPath, cfg.Scheme)
if err != nil {
failf("Failed to read schema: %s", err)
}
if cfg.Configuration != "" {
conf = cfg.Configuration
} else {
conf = scheme.ArchiveAction.BuildConfiguration
}
}
//
// Create the app with Xcode Command Line tools
{
fmt.Println()
log.Infof("Running build")
var isWorkspace bool
if xcworkspace.IsWorkspace(absProjectPath) {
isWorkspace = true
} else if !xcodeproj.IsXcodeProj(absProjectPath) {
failf("Project file extension should be .xcodeproj or .xcworkspace, but got: %s", filepath.Ext(absProjectPath))
}
// Build for simulator command
xcodeBuildCmd := xcodebuild.NewCommandBuilder(absProjectPath, isWorkspace, xcodebuild.BuildAction)
xcodeBuildCmd.SetScheme(cfg.Scheme)
xcodeBuildCmd.SetConfiguration(conf)
// Disable the code signing for simulator build
xcodeBuildCmd.SetDisableCodesign(true)
// Set simulator destination and disable code signing for the build
xcodeBuildCmd.SetDestination("id=" + simulatorID)
// Clean build
if cfg.IsCleanBuild {
xcodeBuildCmd.SetCustomBuildAction("clean")
}
// XcodeBuild Options
if cfg.XcodebuildOptions != "" {
options, err := shellquote.Split(cfg.XcodebuildOptions)
if err != nil {
failf("Failed to shell split XcodebuildOptions (%s), error: %s", cfg.XcodebuildOptions)
}
xcodeBuildCmd.SetCustomOptions(options)
}
// Disabe indexing while building
xcodeBuildCmd.SetDisableIndexWhileBuilding(cfg.DisableIndexWhileBuilding)
var swiftPackagesPath string
if xcodeMajorVersion >= 11 {
var err error
if swiftPackagesPath, err = cache.SwiftPackagesPath(absProjectPath); err != nil {
failf("Failed to get Swift Packages path, error: %s", err)
}
}
rawXcodeBuildOut, err := runCommandWithRetry(xcodeBuildCmd, outputTool == "xcpretty", swiftPackagesPath)
if err != nil {
if outputTool == "xcpretty" {
log.Errorf("\nLast lines of the Xcode's build log:")
fmt.Println(stringutil.LastNLines(rawXcodeBuildOut, 10))
if err := utils.ExportOutputFileContent(rawXcodeBuildOut, rawXcodebuildOutputLogPath, bitriseXcodeRawResultTextEnvKey); err != nil {
log.Warnf("Failed to export %s, error: %s", bitriseXcodeRawResultTextEnvKey, err)
} else {
log.Warnf(`You can find the last couple of lines of Xcode's build log above, but the full log is also available in the raw-xcodebuild-output.log
The log file is stored in $BITRISE_DEPLOY_DIR, and its full path is available in the $BITRISE_XCODE_RAW_RESULT_TEXT_PATH environment variable
(value: %s)`, rawXcodebuildOutputLogPath)
}
}
failf("Build failed, error: %s", err)
}
}
//
// Export artifacts
var exportedArtifacts []string
{
fmt.Println()
log.Infof("Copy artifacts from Derived Data to %s", absOutputDir)
proj, err := findBuiltProject(scheme, schemeContainerDir, conf)
if err != nil {
failf("Failed to open xcproj - (%s), error:", absProjectPath, err)
}
customOptions, err := shellquote.Split(cfg.XcodebuildOptions)
if err != nil {
failf("Failed to shell split XcodebuildOptions (%s), error: %s", cfg.XcodebuildOptions)
}
// Get the simulator name
{
simulatorName := iOSSimName
if cfg.SimulatorPlatform == "tvOS" {
simulatorName = tvOSSimName
}
customOptions = append(customOptions, "-sdk")
customOptions = append(customOptions, simulatorName)
}
schemeBuildDir, err := buildTargetDirForScheme(proj, absProjectPath, cfg.Scheme, conf, customOptions...)
if err != nil {
failf("Failed to get scheme (%s) build target dir, error: %s", err)
}
log.Debugf("Scheme build dir: %s", schemeBuildDir)
// Export the artifact from the build dir to the output_dir
if exportedArtifacts, err = exportArtifacts(proj, cfg.Scheme, schemeBuildDir, conf, cfg.SimulatorPlatform, absOutputDir); err != nil {
failf("Failed to export the artifacts, error: %s", err)
}
}
//
// Export output
fmt.Println()
log.Infof("Exporting outputs")
if len(exportedArtifacts) == 0 {
log.Warnf("No exportable artifact have found.")
} else {
mainTargetAppPath, pathMap, err := exportOutput(exportedArtifacts)
if err != nil {
failf("Failed to export outputs (BITRISE_APP_DIR_PATH & BITRISE_APP_DIR_PATH_LIST), error: %s", err)
}
log.Donef("BITRISE_APP_DIR_PATH -> %s", mainTargetAppPath)
log.Donef("BITRISE_APP_DIR_PATH_LIST -> %s", pathMap)
fmt.Println()
log.Donef("You can find the exported artifacts in: %s", absOutputDir)
}
// Cache swift PM
if xcodeMajorVersion >= 11 && cfg.CacheLevel == "swift_packages" {
if err := cache.CollectSwiftPackages(absProjectPath); err != nil {
log.Warnf("Failed to mark swift packages for caching, error: %s", err)
}
}
}
func exportOutput(artifacts []string) (string, string, error) {
if err := tools.ExportEnvironmentWithEnvman("BITRISE_APP_DIR_PATH", artifacts[0]); err != nil {
return "", "", err
}
pathMap := strings.Join(artifacts, "|")
pathMap = strings.Trim(pathMap, "|")
if err := tools.ExportEnvironmentWithEnvman("BITRISE_APP_DIR_PATH_LIST", pathMap); err != nil {
return "", "", err
}
return artifacts[0], pathMap, nil
}
func readScheme(pth, schemeName string) (*xcscheme.Scheme, string, error) {
var scheme *xcscheme.Scheme
var schemeContainerDir string
if xcodeproj.IsXcodeProj(pth) {
project, err := xcodeproj.Open(pth)
if err != nil {
return nil, "", err
}
scheme, _, err = project.Scheme(schemeName)
if err != nil {
return nil, "", fmt.Errorf("failed to get scheme (%s) from project (%s), error: %s", schemeName, pth, err)
}
schemeContainerDir = filepath.Dir(pth)
} else if xcworkspace.IsWorkspace(pth) {
workspace, err := xcworkspace.Open(pth)
if err != nil {
return nil, "", err
}
var containerProject string
scheme, containerProject, err = workspace.Scheme(schemeName)
if err != nil {
return nil, "", fmt.Errorf("no scheme found with name: %s in workspace: %s, error: %s", schemeName, pth, err)
}
schemeContainerDir = filepath.Dir(containerProject)
} else {
return nil, "", fmt.Errorf("unknown project extension: %s", filepath.Ext(pth))
}
return scheme, schemeContainerDir, nil
}
// findBuiltProject returns the Xcode project which will be built for the provided scheme
func findBuiltProject(scheme *xcscheme.Scheme, schemeContainerDir, configurationName string) (xcodeproj.XcodeProj, error) {
if configurationName == "" {
configurationName = scheme.ArchiveAction.BuildConfiguration
}
if configurationName == "" {
return xcodeproj.XcodeProj{}, fmt.Errorf("no configuration provided nor default defined for the scheme's (%s) archive action", scheme.Name)
}
var archiveEntry xcscheme.BuildActionEntry
for _, entry := range scheme.BuildAction.BuildActionEntries {
if entry.BuildForArchiving != "YES" || !entry.BuildableReference.IsAppReference() {
continue
}
archiveEntry = entry
break
}
if archiveEntry.BuildableReference.BlueprintIdentifier == "" {
return xcodeproj.XcodeProj{}, fmt.Errorf("archivable entry not found")
}
projectPth, err := archiveEntry.BuildableReference.ReferencedContainerAbsPath(schemeContainerDir)
if err != nil {
return xcodeproj.XcodeProj{}, err
}
project, err := xcodeproj.Open(projectPth)
if err != nil {
return xcodeproj.XcodeProj{}, err
}
return project, nil
}
// buildTargetDirForScheme returns the TARGET_BUILD_DIR for the provided scheme
func buildTargetDirForScheme(proj xcodeproj.XcodeProj, projectPath, scheme, configuration string, customOptions ...string) (string, error) {
// Fetch project's main target from .xcodeproject
var buildSettings serialized.Object
if xcodeproj.IsXcodeProj(projectPath) {
mainTarget, err := mainTargetOfScheme(proj, scheme)
if err != nil {
return "", fmt.Errorf("failed to fetch project's targets, error: %s", err)
}
buildSettings, err = proj.TargetBuildSettings(mainTarget.Name, configuration, customOptions...)
if err != nil {
return "", fmt.Errorf("failed to parse project (%s) build settings, error: %s", projectPath, err)
}
} else if xcworkspace.IsWorkspace(projectPath) {
workspace, err := xcworkspace.Open(projectPath)
if err != nil {
return "", fmt.Errorf("Failed to open xcworkspace (%s), error: %s", projectPath, err)
}
buildSettings, err = workspace.SchemeBuildSettings(scheme, configuration, customOptions...)
if err != nil {
return "", fmt.Errorf("failed to parse workspace (%s) build settings, error: %s", projectPath, err)
}
} else {
return "", fmt.Errorf("project file extension should be .xcodeproj or .xcworkspace, but got: %s", filepath.Ext(projectPath))
}
schemeBuildDir, err := buildSettings.String("TARGET_BUILD_DIR")
if err != nil {
return "", fmt.Errorf("failed to parse build settings, error: %s", err)
}
return schemeBuildDir, nil
}
func wrapperNameForScheme(proj xcodeproj.XcodeProj, projectPath, scheme, configuration string, customOptions ...string) (string, error) {
// Fetch project's main target from .xcodeproject
var buildSettings serialized.Object
if xcodeproj.IsXcodeProj(projectPath) {
mainTarget, err := mainTargetOfScheme(proj, scheme)
if err != nil {
return "", fmt.Errorf("failed to fetch project's targets, error: %s", err)
}
buildSettings, err = proj.TargetBuildSettings(mainTarget.Name, configuration, customOptions...)
if err != nil {
return "", fmt.Errorf("failed to parse project (%s) build settings, error: %s", projectPath, err)
}
} else if xcworkspace.IsWorkspace(projectPath) {
workspace, err := xcworkspace.Open(projectPath)
if err != nil {
return "", fmt.Errorf("Failed to open xcworkspace (%s), error: %s", projectPath, err)
}
buildSettings, err = workspace.SchemeBuildSettings(scheme, configuration, customOptions...)
if err != nil {
return "", fmt.Errorf("failed to parse workspace (%s) build settings, error: %s", projectPath, err)
}
} else {
return "", fmt.Errorf("project file extension should be .xcodeproj or .xcworkspace, but got: %s", filepath.Ext(projectPath))
}
wrapperName, err := buildSettings.String("WRAPPER_NAME")
if err != nil {
return "", fmt.Errorf("failed to parse build settings, error: %s", err)
}
return wrapperName, nil
}
// exportArtifacts exports the main target and it's .app dependencies.
func exportArtifacts(proj xcodeproj.XcodeProj, scheme string, schemeBuildDir string, configuration, simulatorPlatform, deployDir string, customOptions ...string) ([]string, error) {
var exportedArtifacts []string
splitSchemeDir := strings.Split(schemeBuildDir, "Build/")
var schemeDir string
// Split the scheme's TARGET_BUILD_DIR by the BUILD dir. This path will be the base path for the targets's TARGET_BUILD_DIR
//
// xcodebuild -showBuildSettings will produce different outputs if you call it with a -workspace & -scheme or if you call it with a -project & -target.
// We need to call xcodebuild -showBuildSettings for all of the project targets to find the build artifacts (iOS, watchOS etc...)
if len(splitSchemeDir) != 2 {
log.Debugf("failed to parse scheme's build target dir: %s. Using the original build dir (%s)\n", schemeBuildDir, schemeBuildDir)
schemeDir = schemeBuildDir
} else {
schemeDir = filepath.Join(splitSchemeDir[0], "Build")
}
mainTarget, err := mainTargetOfScheme(proj, scheme)
if err != nil {
return nil, fmt.Errorf("failed to fetch project's targets, error: %s", err)
}
targets := append([]xcodeproj.Target{mainTarget}, mainTarget.DependentTargets()...)
for _, target := range targets {
log.Donef(target.Name + "...")
// Is the target an application? -> If not skip the export
if !strings.HasSuffix(target.ProductReference.Path, ".app") {
log.Printf("Target (%s) is not an .app - SKIP", target.Name)
continue
}
//
// Find out the sdk for the target
simulatorName := iOSSimName
if simulatorPlatform == "tvOS" {
simulatorName = tvOSSimName
}
{
settings, err := proj.TargetBuildSettings(target.Name, configuration)
if err != nil {
log.Debugf("Failed to fetch project settings (%s), error: %s", proj.Path, err)
}
sdkRoot, err := settings.String("SDKROOT")
if err != nil {
log.Debugf("No SDKROOT config found for (%s) target", target.Name)
}
log.Debugf("sdkRoot: %s", sdkRoot)
if strings.Contains(sdkRoot, "WatchOS.platform") {
simulatorName = watchOSSimName
}
}
//
// Find the TARGET_BUILD_DIR for the target
options := []string{"-sdk", simulatorName}
var targetDir string
{
if sliceutil.IsStringInSlice("-sdk", customOptions) {
options = customOptions
} else {
options = append(options, customOptions...)
}
buildSettings, err := proj.TargetBuildSettings(target.Name, configuration, options...)
if err != nil {
return nil, fmt.Errorf("failed to get project build settings, error: %s", err)
}
buildDir, err := buildSettings.String("TARGET_BUILD_DIR")
if err != nil {
return nil, fmt.Errorf("failed to get build target dir for target (%s), error: %s", target.Name, err)
}
log.Debugf("Target (%s) TARGET_BUILD_DIR: %s", target.Name, buildDir)
// Split the target's TARGET_BUILD_DIR by the BUILD dir. This path will be joined to the `schemeBuildDir`
//
// xcodebuild -showBuildSettings will produce different outputs if you call it with a -workspace & -scheme or if you call it with a -project & -target.
// We need to call xcodebuild -showBuildSettings for all of the project targets to find the build artifacts (iOS, watchOS etc...)
splitTargetDir := strings.Split(buildDir, "build/ios")
if len(splitTargetDir) != 2 {
log.Debugf("failed to parse build target dir (%s) for target: %s. Using the original build dir (%s)\n", buildDir, target.Name, buildDir)
targetDir = buildDir
} else {
targetDir = filepath.Join("Products", splitTargetDir[1])
}
}
//
// Copy - export
{
// Search for the generated build artifact in the next dirs:
// Parent dir (main target's build dir by the provided scheme) + current target's build dir (This is a default for a nativ iOS project)
// current target's build dir (If the project settings uses a custom TARGET_BUILD_DIR env)
// .xcodeproj's directory + current target's build dir (If the project settings uses a custom TARGET_BUILD_DIR env & the project is not in the root dir)
sourceDirs := []string{filepath.Join(schemeDir, targetDir), schemeDir, filepath.Join(path.Dir(proj.Path), schemeDir)}
destination := filepath.Join(deployDir, target.ProductReference.Path)
// Search for the generated build artifact
var exported bool
for _, sourceDir := range sourceDirs {
source := filepath.Join(sourceDir, target.ProductReference.Path)
log.Debugf("searching for the generated app in %s", source)
if exists, err := pathutil.IsPathExists(source); err != nil {
log.Debugf("failed to check if the path exists: (%s), error: ", source, err)
continue
} else if !exists {
log.Debugf("path not exists: %s", source)
// Also check to see if a path exists with the target name
wrapperName, err := wrapperNameForScheme(proj, proj.Path, scheme, configuration, customOptions...)
if err != nil {
failf("Failed to get scheme (%s) build target dir, error: %s", err)
}
source = filepath.Join(sourceDir, wrapperName)
if exists, err := pathutil.IsPathExists(source); err != nil {
log.Debugf("failed to check if the path exists: (%s), error: ", source, err)
continue
} else if !exists {
log.Debugf("2nd path does not exist: %s", source)
continue
}
}
// Copy the build artifact
cmd := util.CopyDir(source, destination)
cmd.SetStdout(os.Stdout)
cmd.SetStderr(os.Stderr)
log.Debugf("$ " + cmd.PrintableCommandArgs())
if err := cmd.Run(); err != nil {
log.Debugf("failed to copy the generated app from (%s) to the Deploy dir\n", source)
continue
}
exported = true
break
}
if exported {
exportedArtifacts = append(exportedArtifacts, destination)
log.Debugf("Success\n")
} else {
return nil, fmt.Errorf("failed to copy the generated app to the Deploy dir")
}
}
}
return exportedArtifacts, nil
}
// mainTargetOfScheme return the main target
func mainTargetOfScheme(proj xcodeproj.XcodeProj, scheme string) (xcodeproj.Target, error) {
projTargets := proj.Proj.Targets
sch, _, err := proj.Scheme(scheme)
if err != nil {
return xcodeproj.Target{}, fmt.Errorf("failed to get scheme (%s) from project (%s), error: %s", scheme, proj.Path, err)
}
var blueIdent string
for _, entry := range sch.BuildAction.BuildActionEntries {
if entry.BuildableReference.IsAppReference() {
blueIdent = entry.BuildableReference.BlueprintIdentifier
break
}
}
// Search for the main target
for _, t := range projTargets {
if t.ID == blueIdent {
return t, nil
}
}
return xcodeproj.Target{}, fmt.Errorf("failed to find the project's main target for scheme (%s)", scheme)
}
// simulatorDestinationID return the simulator's ID for the selected device version.
func simulatorDestinationID(simulatorOsVersion, simulatorPlatform, simulatorDevice string) (string, error) {
var simulatorID string
if simulatorOsVersion == "latest" {
info, _, err := simulator.GetLatestSimulatorInfoAndVersion(simulatorPlatform, simulatorDevice)
if err != nil {
return "", fmt.Errorf("failed to get latest simulator info - error: %s", err)
}
simulatorID = info.ID
log.Printf("Latest simulator for %s = %s", simulatorDevice, simulatorID)
} else {
info, err := simulator.GetSimulatorInfo((simulatorPlatform + " " + simulatorOsVersion), simulatorDevice)
if err != nil {
return "", fmt.Errorf("failed to get simulator info (%s-%s) - error: %s", (simulatorPlatform + simulatorOsVersion), simulatorDevice, err)
}
simulatorID = info.ID
log.Printf("Simulator for %s %s = %s", simulatorDevice, simulatorOsVersion, simulatorID)
}
return simulatorID, nil
}
func failf(format string, v ...interface{}) {
log.Errorf(format, v...)
os.Exit(1)
}