-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
770 lines (644 loc) · 27.2 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
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
package main
import (
"bufio"
"fmt"
"os"
"path/filepath"
"regexp"
"strings"
"time"
"github.com/bitrise-io/go-steputils/input"
"github.com/bitrise-io/go-steputils/stepconf"
"github.com/bitrise-io/go-utils/colorstring"
"github.com/bitrise-io/go-utils/command"
"github.com/bitrise-io/go-utils/errorutil"
"github.com/bitrise-io/go-utils/fileutil"
"github.com/bitrise-io/go-utils/log"
"github.com/bitrise-io/go-utils/pathutil"
"github.com/bitrise-io/go-utils/stringutil"
"github.com/bitrise-io/go-xcode/exportoptions"
"github.com/bitrise-io/go-xcode/profileutil"
"github.com/bitrise-io/go-xcode/utility"
"github.com/bitrise-io/go-xcode/xcarchive"
"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-steplib/steps-xcode-archive/utils"
"github.com/kballard/go-shellquote"
"howett.net/plist"
)
const (
minSupportedXcodeMajorVersion = 6
)
const (
bitriseXcodeRawResultTextEnvKey = "BITRISE_XCODE_RAW_RESULT_TEXT_PATH"
bitriseIDEDistributionLogsPthEnvKey = "BITRISE_IDEDISTRIBUTION_LOGS_PATH"
bitriseXCArchivePthEnvKey = "BITRISE_XCARCHIVE_PATH"
bitriseXCArchiveZipPthEnvKey = "BITRISE_XCARCHIVE_ZIP_PATH"
bitriseAppDirPthEnvKey = "BITRISE_APP_DIR_PATH"
bitriseIPAPthEnvKey = "BITRISE_IPA_PATH"
bitriseDSYMDirPthEnvKey = "BITRISE_DSYM_DIR_PATH"
bitriseDSYMPthEnvKey = "BITRISE_DSYM_PATH"
)
// configs ...
type configs struct {
ExportMethod string `env:"export_method,opt[auto-detect,app-store,ad-hoc,enterprise,development]"`
UploadBitcode bool `env:"upload_bitcode,opt[yes,no]"`
CompileBitcode bool `env:"compile_bitcode,opt[yes,no]"`
ICloudContainerEnvironment string `env:"icloud_container_environment"`
TeamID string `env:"team_id"`
UseDeprecatedExport bool `env:"use_deprecated_export,opt[yes,no]"`
ForceTeamID string `env:"force_team_id"`
ForceProvisioningProfileSpecifier string `env:"force_provisioning_profile_specifier"`
ForceProvisioningProfile string `env:"force_provisioning_profile"`
ForceCodeSignIdentity string `env:"force_code_sign_identity"`
CustomExportOptionsPlistContent string `env:"custom_export_options_plist_content"`
OutputTool string `env:"output_tool,opt[xcpretty,xcodebuild]"`
Workdir string `env:"workdir"`
ProjectPath string `env:"project_path,file"`
Scheme string `env:"scheme,required"`
Configuration string `env:"configuration"`
OutputDir string `env:"output_dir,required"`
IsCleanBuild bool `env:"is_clean_build,opt[yes,no]"`
XcodebuildOptions string `env:"xcodebuild_options"`
DisableIndexWhileBuilding bool `env:"disable_index_while_building,opt[yes,no]"`
ExportAllDsyms bool `env:"export_all_dsyms,opt[yes,no]"`
ArtifactName string `env:"artifact_name"`
VerboseLog bool `env:"verbose_log,opt[yes,no]"`
CacheLevel string `env:"cache_level,opt[none,swift_packages]"`
}
func fail(format string, v ...interface{}) {
log.Errorf(format, v...)
os.Exit(1)
}
func findIDEDistrubutionLogsPath(output string) (string, error) {
pattern := `IDEDistribution: -\[IDEDistributionLogging _createLoggingBundleAtPath:\]: Created bundle at path '(?P<log_path>.*)'`
re := regexp.MustCompile(pattern)
scanner := bufio.NewScanner(strings.NewReader(output))
for scanner.Scan() {
line := scanner.Text()
if match := re.FindStringSubmatch(line); len(match) == 2 {
return match[1], nil
}
}
if err := scanner.Err(); err != nil {
return "", err
}
return "", nil
}
func currentTimestamp() string {
timeStampFormat := "15:04:05"
currentTime := time.Now()
return currentTime.Format(timeStampFormat)
}
// ColoringFunc ...
type ColoringFunc func(...interface{}) string
func logWithTimestamp(coloringFunc ColoringFunc, format string, v ...interface{}) {
message := fmt.Sprintf(format, v...)
messageWithTimeStamp := fmt.Sprintf("[%s] %s", currentTimestamp(), coloringFunc(message))
fmt.Println(messageWithTimeStamp)
}
func determineExportMethod(desiredExportMethod string, archiveExportMethod exportoptions.Method) (exportoptions.Method, error) {
if desiredExportMethod == "auto-detect" {
log.Printf("auto-detect export method specified: using the archive profile's export method: %s", archiveExportMethod)
return archiveExportMethod, nil
}
exportMethod, err := exportoptions.ParseMethod(desiredExportMethod)
if err != nil {
return "", fmt.Errorf("failed to parse export method: %s", err)
}
log.Printf("export method specified: %s", desiredExportMethod)
return exportMethod, nil
}
func main() {
var cfg configs
if err := stepconf.Parse(&cfg); err != nil {
fail("Issue with input: %s", err)
}
stepconf.Print(cfg)
fmt.Println()
log.SetEnableDebugLog(cfg.VerboseLog)
if cfg.ExportMethod == "auto-detect" {
exportMethods := []exportoptions.Method{exportoptions.MethodAppStore, exportoptions.MethodAdHoc, exportoptions.MethodEnterprise, exportoptions.MethodDevelopment}
log.Warnf("Export method: auto-detect is DEPRECATED, use a direct export method %s", exportMethods)
fmt.Println()
}
if cfg.Workdir != "" {
if err := input.ValidateIfDirExists(cfg.Workdir); err != nil {
fail("issue with input Workdir: " + err.Error())
}
}
if cfg.CustomExportOptionsPlistContent != "" {
var options map[string]interface{}
if _, err := plist.Unmarshal([]byte(cfg.CustomExportOptionsPlistContent), &options); err != nil {
fail("issue with input CustomExportOptionsPlistContent: " + err.Error())
}
}
log.Infof("step determined configs:")
// Detect Xcode major version
xcodebuildVersion, err := utility.GetXcodeVersion()
if err != nil {
fail("Failed to determin xcode version, error: %s", err)
}
log.Printf("- xcodebuildVersion: %s (%s)", xcodebuildVersion.Version, xcodebuildVersion.BuildVersion)
xcodeMajorVersion := xcodebuildVersion.MajorVersion
if xcodeMajorVersion < minSupportedXcodeMajorVersion {
fail("Invalid xcode major version (%d), should not be less then min supported: %d", xcodeMajorVersion, minSupportedXcodeMajorVersion)
}
// Detect xcpretty version
outputTool := cfg.OutputTool
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 determin xcpretty version, error: %s", err)
log.Printf("Switching to xcodebuild for output tool")
outputTool = "xcodebuild"
}
log.Printf("- xcprettyVersion: %s", xcprettyVersion.String())
}
// Validation CustomExportOptionsPlistContent
customExportOptionsPlistContent := strings.TrimSpace(cfg.CustomExportOptionsPlistContent)
if customExportOptionsPlistContent != cfg.CustomExportOptionsPlistContent {
fmt.Println()
log.Warnf("CustomExportOptionsPlistContent is stripped to remove spaces and new lines:")
log.Printf(customExportOptionsPlistContent)
}
if customExportOptionsPlistContent != "" {
if xcodeMajorVersion < 7 {
fmt.Println()
log.Warnf("CustomExportOptionsPlistContent is set, but CustomExportOptionsPlistContent only used if xcodeMajorVersion > 6")
customExportOptionsPlistContent = ""
} else {
fmt.Println()
log.Warnf("Ignoring the following options because CustomExportOptionsPlistContent provided:")
log.Printf("- ExportMethod: %s", cfg.ExportMethod)
log.Printf("- UploadBitcode: %s", cfg.UploadBitcode)
log.Printf("- CompileBitcode: %s", cfg.CompileBitcode)
log.Printf("- TeamID: %s", cfg.TeamID)
log.Printf("- ICloudContainerEnvironment: %s", cfg.ICloudContainerEnvironment)
fmt.Println()
}
}
if cfg.ForceProvisioningProfileSpecifier != "" &&
xcodeMajorVersion < 8 {
fmt.Println()
log.Warnf("ForceProvisioningProfileSpecifier is set, but ForceProvisioningProfileSpecifier only used if xcodeMajorVersion > 7")
cfg.ForceProvisioningProfileSpecifier = ""
}
if cfg.ForceTeamID != "" &&
xcodeMajorVersion < 8 {
fmt.Println()
log.Warnf("ForceTeamID is set, but ForceTeamID only used if xcodeMajorVersion > 7")
cfg.ForceTeamID = ""
}
if cfg.ForceProvisioningProfileSpecifier != "" &&
cfg.ForceProvisioningProfile != "" {
fmt.Println()
log.Warnf("both ForceProvisioningProfileSpecifier and ForceProvisioningProfile are set, using ForceProvisioningProfileSpecifier")
cfg.ForceProvisioningProfile = ""
}
fmt.Println()
absProjectPath, err := filepath.Abs(cfg.ProjectPath)
if err != nil {
fail("Failed to get absolute project path, error: %s", err)
}
// abs out dir pth
absOutputDir, err := pathutil.AbsPath(cfg.OutputDir)
if err != nil {
fail("Failed to expand OutputDir (%s), error: %s", cfg.OutputDir, err)
}
cfg.OutputDir = absOutputDir
if exist, err := pathutil.IsPathExists(cfg.OutputDir); err != nil {
fail("Failed to check if OutputDir exist, error: %s", err)
} else if !exist {
if err := os.MkdirAll(cfg.OutputDir, 0777); err != nil {
fail("Failed to create OutputDir (%s), error: %s", cfg.OutputDir, err)
}
}
// output files
tmpArchiveDir, err := pathutil.NormalizedOSTempDirPath("__archive__")
if err != nil {
fail("Failed to create temp dir for archives, error: %s", err)
}
tmpArchivePath := filepath.Join(tmpArchiveDir, cfg.ArtifactName+".xcarchive")
appPath := filepath.Join(cfg.OutputDir, cfg.ArtifactName+".app")
ipaPath := filepath.Join(cfg.OutputDir, cfg.ArtifactName+".ipa")
exportOptionsPath := filepath.Join(cfg.OutputDir, "export_options.plist")
rawXcodebuildOutputLogPath := filepath.Join(cfg.OutputDir, "raw-xcodebuild-output.log")
dsymZipPath := filepath.Join(cfg.OutputDir, cfg.ArtifactName+".dSYM.zip")
archiveZipPath := filepath.Join(cfg.OutputDir, cfg.ArtifactName+".xcarchive.zip")
ideDistributionLogsZipPath := filepath.Join(cfg.OutputDir, "xcodebuild.xcdistributionlogs.zip")
// cleanup
filesToCleanup := []string{
appPath,
ipaPath,
exportOptionsPath,
rawXcodebuildOutputLogPath,
dsymZipPath,
archiveZipPath,
ideDistributionLogsZipPath,
}
for _, pth := range filesToCleanup {
if exist, err := pathutil.IsPathExists(pth); err != nil {
fail("Failed to check if path (%s) exist, error: %s", pth, err)
} else if exist {
if err := os.RemoveAll(pth); err != nil {
fail("Failed to remove path (%s), error: %s", pth, err)
}
}
}
//
// Open Xcode project
xcodeProj, scheme, configuration, err := utils.OpenArchivableProject(absProjectPath, cfg.Scheme, cfg.Configuration)
if err != nil {
fail("Failed to open project: %s: %s", absProjectPath, err)
}
mainTarget, err := archivableApplicationTarget(xcodeProj, scheme, configuration)
if err != nil {
fail("Failed to read main application target: %s", absProjectPath, err)
}
if mainTarget.ProductType == appClipProductType {
log.Errorf("Selected scheme: '%s' targets an App Clip target (%s),", cfg.Scheme, mainTarget.Name)
log.Errorf("'Xcode Archive & Export for iOS' step is intended to archive the project using a scheme targeting an Application target.")
log.Errorf("Please select a scheme targeting an Application target to archive and export the main Application")
log.Errorf("and use 'Export iOS and tvOS Xcode archive' step to export an App Clip.")
os.Exit(1)
}
//
// Create the Archive with Xcode Command Line tools
log.Infof("Create the Archive ...")
fmt.Println()
isWorkspace := false
ext := filepath.Ext(absProjectPath)
if ext == ".xcodeproj" {
isWorkspace = false
} else if ext == ".xcworkspace" {
isWorkspace = true
} else {
fail("Project file extension should be .xcodeproj or .xcworkspace, but got: %s", ext)
}
archiveCmd := xcodebuild.NewCommandBuilder(absProjectPath, isWorkspace, xcodebuild.ArchiveAction)
archiveCmd.SetScheme(cfg.Scheme)
archiveCmd.SetConfiguration(cfg.Configuration)
if cfg.ForceTeamID != "" {
log.Printf("Forcing Development Team: %s", cfg.ForceTeamID)
archiveCmd.SetForceDevelopmentTeam(cfg.ForceTeamID)
}
if cfg.ForceProvisioningProfileSpecifier != "" {
log.Printf("Forcing Provisioning Profile Specifier: %s", cfg.ForceProvisioningProfileSpecifier)
archiveCmd.SetForceProvisioningProfileSpecifier(cfg.ForceProvisioningProfileSpecifier)
}
if cfg.ForceProvisioningProfile != "" {
log.Printf("Forcing Provisioning Profile: %s", cfg.ForceProvisioningProfile)
archiveCmd.SetForceProvisioningProfile(cfg.ForceProvisioningProfile)
}
if cfg.ForceCodeSignIdentity != "" {
log.Printf("Forcing Code Signing Identity: %s", cfg.ForceCodeSignIdentity)
archiveCmd.SetForceCodeSignIdentity(cfg.ForceCodeSignIdentity)
}
if cfg.IsCleanBuild {
archiveCmd.SetCustomBuildAction("clean")
}
archiveCmd.SetDisableIndexWhileBuilding(cfg.DisableIndexWhileBuilding)
archiveCmd.SetArchivePath(tmpArchivePath)
options := []string{}
if cfg.XcodebuildOptions != "" {
userOptions, err := shellquote.Split(cfg.XcodebuildOptions)
if err != nil {
fail("Failed to shell split XcodebuildOptions (%s), error: %s", cfg.XcodebuildOptions)
}
options = userOptions
}
archiveCmd.SetCustomOptions(options)
var swiftPackagesPath string
if xcodeMajorVersion >= 11 {
var err error
if swiftPackagesPath, err = cache.SwiftPackagesPath(absProjectPath); err != nil {
fail("Failed to get Swift Packages path, error: %s", err)
}
}
rawXcodebuildOut, err := runArchiveCommandWithRetry(archiveCmd, outputTool == "xcpretty", swiftPackagesPath)
if err != nil || outputTool == "xcodebuild" {
const lastLinesMsg = "\nLast lines of the Xcode's build log:"
if err != nil {
log.Infof(colorstring.Red(lastLinesMsg))
} else {
log.Infof(lastLinesMsg)
}
fmt.Println(stringutil.LastNLines(rawXcodebuildOut, 20))
if err := utils.ExportOutputFileContent(rawXcodebuildOut, rawXcodebuildOutputLogPath, bitriseXcodeRawResultTextEnvKey); err != nil {
log.Warnf("Failed to export %s, error: %s", bitriseXcodeRawResultTextEnvKey, err)
} else {
log.Infof(colorstring.Magenta(fmt.Sprintf(`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)))
}
}
if err != nil {
fail("Archive failed, error: %s", err)
}
fmt.Println()
// Ensure xcarchive exists
if exist, err := pathutil.IsPathExists(tmpArchivePath); err != nil {
fail("Failed to check if archive exist, error: %s", err)
} else if !exist {
fail("No archive generated at: %s", tmpArchivePath)
}
// 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)
}
}
if xcodeMajorVersion >= 9 && cfg.UseDeprecatedExport {
fail("Legacy export method (using '-exportFormat ipa' flag) is not supported from Xcode version 9")
}
envsToUnset := []string{"GEM_HOME", "GEM_PATH", "RUBYLIB", "RUBYOPT", "BUNDLE_BIN_PATH", "_ORIGINAL_GEM_PATH", "BUNDLE_GEMFILE"}
for _, key := range envsToUnset {
if err := os.Unsetenv(key); err != nil {
fail("Failed to unset (%s), error: %s", key, err)
}
}
archive, err := xcarchive.NewIosArchive(tmpArchivePath)
if err != nil {
fail("Failed to parse archive, error: %s", err)
}
mainApplication := archive.Application
archiveExportMethod := mainApplication.ProvisioningProfile.ExportType
archiveCodeSignIsXcodeManaged := profileutil.IsXcodeManaged(mainApplication.ProvisioningProfile.Name)
log.Infof("Archive infos:")
log.Printf("team: %s (%s)", mainApplication.ProvisioningProfile.TeamName, mainApplication.ProvisioningProfile.TeamID)
log.Printf("profile: %s (%s)", mainApplication.ProvisioningProfile.Name, mainApplication.ProvisioningProfile.UUID)
log.Printf("export: %s", archiveExportMethod)
log.Printf("xcode managed profile: %v", archiveCodeSignIsXcodeManaged)
fmt.Println()
//
// Exporting the ipa with Xcode Command Line tools
/*
You'll get a "Error Domain=IDEDistributionErrorDomain Code=14 "No applicable devices found."" error
if $GEM_HOME is set and the project's directory includes a Gemfile - to fix this
we'll unset GEM_HOME as that's not required for xcodebuild anyway.
This probably fixes the RVM issue too, but that still should be tested.
See also:
- http://stackoverflow.com/questions/33041109/xcodebuild-no-applicable-devices-found-when-exporting-archive
- https://gist.github.com/claybridges/cea5d4afd24eda268164
*/
log.Infof("Exporting ipa from the archive...")
fmt.Println()
if xcodeMajorVersion <= 6 || cfg.UseDeprecatedExport {
log.Printf("Using legacy export")
/*
Get the name of the profile which was used for creating the archive
--> Search for embedded.mobileprovision in the xcarchive.
It should contain a .app folder in the xcarchive folder
under the Products/Applications folder
*/
legacyExportCmd := xcodebuild.NewLegacyExportCommand()
legacyExportCmd.SetExportFormat("ipa")
legacyExportCmd.SetArchivePath(tmpArchivePath)
legacyExportCmd.SetExportPath(ipaPath)
legacyExportCmd.SetExportProvisioningProfileName(mainApplication.ProvisioningProfile.Name)
if outputTool == "xcpretty" {
xcprettyCmd := xcpretty.New(legacyExportCmd)
logWithTimestamp(colorstring.Green, xcprettyCmd.PrintableCmd())
fmt.Println()
if rawXcodebuildOut, err := xcprettyCmd.Run(); err != nil {
if err := utils.ExportOutputFileContent(rawXcodebuildOut, rawXcodebuildOutputLogPath, bitriseXcodeRawResultTextEnvKey); err != nil {
log.Warnf("Failed to export %s, error: %s", bitriseXcodeRawResultTextEnvKey, err)
} else {
log.Warnf(`If you can't find the reason of the error in the log, please check 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`)
}
fail("Export failed, error: %s", err)
}
} else {
logWithTimestamp(colorstring.Green, legacyExportCmd.PrintableCmd())
fmt.Println()
if err := legacyExportCmd.Run(); err != nil {
fail("Export failed, error: %s", err)
}
}
} else {
log.Printf("Exporting ipa with ExportOptions.plist")
if customExportOptionsPlistContent != "" {
log.Printf("Custom export options content provided, using it:")
fmt.Println(customExportOptionsPlistContent)
if err := fileutil.WriteStringToFile(exportOptionsPath, customExportOptionsPlistContent); err != nil {
fail("Failed to write export options to file, error: %s", err)
}
} else {
log.Printf("No custom export options content provided, generating export options...")
exportMethod, err := determineExportMethod(cfg.ExportMethod, archiveExportMethod)
if err != nil {
fail(err.Error())
}
generator := NewExportOptionsGenerator(xcodeProj, scheme, configuration)
exportOptions, err := generator.GenerateApplicationExportOptions(exportMethod, cfg.ICloudContainerEnvironment, cfg.TeamID,
cfg.UploadBitcode, cfg.CompileBitcode, archiveCodeSignIsXcodeManaged, xcodeMajorVersion)
if err != nil {
fail(err.Error())
}
fmt.Println()
log.Printf("generated export options content:")
fmt.Println()
fmt.Println(exportOptions.String())
if err := exportOptions.WriteToFile(exportOptionsPath); err != nil {
fail(err.Error())
}
}
fmt.Println()
tmpDir, err := pathutil.NormalizedOSTempDirPath("__export__")
if err != nil {
fail("Failed to create tmp dir, error: %s", err)
}
exportCmd := xcodebuild.NewExportCommand()
exportCmd.SetArchivePath(tmpArchivePath)
exportCmd.SetExportDir(tmpDir)
exportCmd.SetExportOptionsPlist(exportOptionsPath)
if outputTool == "xcpretty" {
xcprettyCmd := xcpretty.New(exportCmd)
logWithTimestamp(colorstring.Green, xcprettyCmd.PrintableCmd())
fmt.Println()
if xcodebuildOut, err := xcprettyCmd.Run(); err != nil {
// xcodebuild raw output
if err := utils.ExportOutputFileContent(xcodebuildOut, rawXcodebuildOutputLogPath, bitriseXcodeRawResultTextEnvKey); err != nil {
log.Warnf("Failed to export %s, error: %s", bitriseXcodeRawResultTextEnvKey, err)
} else {
log.Warnf(`If you can't find the reason of the error in the log, please check 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`)
}
// xcdistributionlogs
if logsDirPth, err := findIDEDistrubutionLogsPath(xcodebuildOut); err != nil {
log.Warnf("Failed to find xcdistributionlogs, error: %s", err)
} else if err := utils.ExportOutputDirAsZip(logsDirPth, ideDistributionLogsZipPath, bitriseIDEDistributionLogsPthEnvKey); err != nil {
log.Warnf("Failed to export %s, error: %s", bitriseIDEDistributionLogsPthEnvKey, err)
} else {
criticalDistLogFilePth := filepath.Join(logsDirPth, "IDEDistribution.critical.log")
log.Warnf("IDEDistribution.critical.log:")
if criticalDistLog, err := fileutil.ReadStringFromFile(criticalDistLogFilePth); err == nil {
log.Printf(criticalDistLog)
}
log.Warnf(`Also please check the xcdistributionlogs
The logs directory is stored in $BITRISE_DEPLOY_DIR, and its full path
is available in the $BITRISE_IDEDISTRIBUTION_LOGS_PATH environment variable`)
}
fail("Export failed, error: %s", err)
}
} else {
logWithTimestamp(colorstring.Green, exportCmd.PrintableCmd())
fmt.Println()
if xcodebuildOut, err := exportCmd.RunAndReturnOutput(); err != nil {
// xcdistributionlogs
if logsDirPth, err := findIDEDistrubutionLogsPath(xcodebuildOut); err != nil {
log.Warnf("Failed to find xcdistributionlogs, error: %s", err)
} else if err := utils.ExportOutputDirAsZip(logsDirPth, ideDistributionLogsZipPath, bitriseIDEDistributionLogsPthEnvKey); err != nil {
log.Warnf("Failed to export %s, error: %s", bitriseIDEDistributionLogsPthEnvKey, err)
} else {
criticalDistLogFilePth := filepath.Join(logsDirPth, "IDEDistribution.critical.log")
log.Warnf("IDEDistribution.critical.log:")
if criticalDistLog, err := fileutil.ReadStringFromFile(criticalDistLogFilePth); err == nil {
log.Printf(criticalDistLog)
}
log.Warnf(`If you can't find the reason of the error in the log, please check the xcdistributionlogs
The logs directory is stored in $BITRISE_DEPLOY_DIR, and its full path
is available in the $BITRISE_IDEDISTRIBUTION_LOGS_PATH environment variable`)
}
fail("Export failed, error: %s", err)
}
}
// Search for ipa
fileList := []string{}
ipaFiles := []string{}
if walkErr := filepath.Walk(tmpDir, func(pth string, info os.FileInfo, err error) error {
if err != nil {
return err
}
fileList = append(fileList, pth)
if filepath.Ext(pth) == ".ipa" {
ipaFiles = append(ipaFiles, pth)
}
return nil
}); walkErr != nil {
fail("Failed to search for .ipa file, error: %s", err)
}
if len(ipaFiles) == 0 {
log.Errorf("No .ipa file found at export dir: %s", tmpDir)
log.Printf("File list in the export dir:")
for _, pth := range fileList {
log.Printf("- %s", pth)
}
fail("")
} else {
if err := command.CopyFile(ipaFiles[0], ipaPath); err != nil {
fail("Failed to copy (%s) -> (%s), error: %s", ipaFiles[0], ipaPath, err)
}
if len(ipaFiles) > 1 {
log.Warnf("More than 1 .ipa file found, exporting first one: %s", ipaFiles[0])
log.Warnf("Moving every ipa to the BITRISE_DEPLOY_DIR")
for i, pth := range ipaFiles {
if i == 0 {
continue
}
base := filepath.Base(pth)
deployPth := filepath.Join(cfg.OutputDir, base)
if err := command.CopyFile(pth, deployPth); err != nil {
fail("Failed to copy (%s) -> (%s), error: %s", pth, ipaPath, err)
}
}
}
}
}
log.Infof("Exporting outputs...")
//
// Export outputs
// Export .xcarchive
fmt.Println()
if err := utils.ExportOutputDir(tmpArchivePath, tmpArchivePath, bitriseXCArchivePthEnvKey); err != nil {
fail("Failed to export %s, error: %s", bitriseXCArchivePthEnvKey, err)
}
log.Donef("The xcarchive path is now available in the Environment Variable: %s (value: %s)", bitriseXCArchivePthEnvKey, tmpArchivePath)
if err := utils.ExportOutputDirAsZip(tmpArchivePath, archiveZipPath, bitriseXCArchiveZipPthEnvKey); err != nil {
fail("Failed to export %s, error: %s", bitriseXCArchiveZipPthEnvKey, err)
}
log.Donef("The xcarchive zip path is now available in the Environment Variable: %s (value: %s)", bitriseXCArchiveZipPthEnvKey, archiveZipPath)
// Export .app
fmt.Println()
exportedApp := mainApplication.Path
if err := utils.ExportOutputDir(exportedApp, exportedApp, bitriseAppDirPthEnvKey); err != nil {
fail("Failed to export %s, error: %s", bitriseAppDirPthEnvKey, err)
}
log.Donef("The app directory is now available in the Environment Variable: %s (value: %s)", bitriseAppDirPthEnvKey, appPath)
// Export .ipa
fmt.Println()
if err := utils.ExportOutputFile(ipaPath, ipaPath, bitriseIPAPthEnvKey); err != nil {
fail("Failed to export %s, error: %s", bitriseIPAPthEnvKey, err)
}
log.Donef("The ipa path is now available in the Environment Variable: %s (value: %s)", bitriseIPAPthEnvKey, ipaPath)
// Export .dSYMs
fmt.Println()
appDSYM, frameworkDSYMs, err := archive.FindDSYMs()
if err != nil {
fail("Failed to export dsyms, error: %s", err)
}
if err == nil {
dsymDir, err := pathutil.NormalizedOSTempDirPath("__dsyms__")
if err != nil {
fail("Failed to create tmp dir, error: %s", err)
}
if appDSYM != "" {
if err := command.CopyDir(appDSYM, dsymDir, false); err != nil {
fail("Failed to copy (%s) -> (%s), error: %s", appDSYM, dsymDir, err)
}
} else {
log.Warnf("no app dsyms found")
}
if cfg.ExportAllDsyms {
for _, dsym := range frameworkDSYMs {
if err := command.CopyDir(dsym, dsymDir, false); err != nil {
fail("Failed to copy (%s) -> (%s), error: %s", dsym, dsymDir, err)
}
}
}
if err := utils.ExportOutputDir(dsymDir, dsymDir, bitriseDSYMDirPthEnvKey); err != nil {
fail("Failed to export %s, error: %s", bitriseDSYMDirPthEnvKey, err)
}
log.Donef("The dSYM dir path is now available in the Environment Variable: %s (value: %s)", bitriseDSYMDirPthEnvKey, dsymDir)
if err := utils.ExportOutputDirAsZip(dsymDir, dsymZipPath, bitriseDSYMPthEnvKey); err != nil {
fail("Failed to export %s, error: %s", bitriseDSYMPthEnvKey, err)
}
log.Donef("The dSYM zip path is now available in the Environment Variable: %s (value: %s)", bitriseDSYMPthEnvKey, dsymZipPath)
}
}