-
Notifications
You must be signed in to change notification settings - Fork 18
/
main.go
572 lines (471 loc) · 16.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
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
package main
import (
"fmt"
"os"
"path/filepath"
"regexp"
"strconv"
"strings"
"time"
"github.com/bitrise-io/go-steputils/cache"
"github.com/bitrise-io/go-steputils/command/gems"
"github.com/bitrise-io/go-steputils/command/rubycommand"
"github.com/bitrise-io/go-steputils/stepconf"
"github.com/bitrise-io/go-steputils/v2/ruby"
"github.com/bitrise-io/go-utils/command"
"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/v2/analytics"
v2command "github.com/bitrise-io/go-utils/v2/command"
"github.com/bitrise-io/go-utils/v2/env"
"github.com/bitrise-io/go-utils/v2/errorutil"
v2log "github.com/bitrise-io/go-utils/v2/log"
"github.com/bitrise-io/go-xcode/pathfilters"
)
// ConfigsModel ...
type ConfigsModel struct {
Command string `env:"command,opt[install,update]"`
SourceRootPath string `env:"source_root_path,dir"`
PodfilePath string `env:"podfile_path"`
Verbose bool `env:"verbose,opt[true,false]"`
IsCacheDisabled bool `env:"is_cache_disabled,opt[true,false]"`
}
func createConfigsModelFromEnvs() (ConfigsModel, error) {
var c ConfigsModel
if err := stepconf.Parse(&c); err != nil {
return ConfigsModel{}, err
}
if c.PodfilePath != "" {
if _, err := os.Stat(c.PodfilePath); os.IsNotExist(err) {
return ConfigsModel{}, fmt.Errorf("%s is not exist", c.PodfilePath)
}
}
return c, nil
}
func failf(format string, v ...interface{}) {
log.Errorf(format, v...)
os.Exit(1)
}
func findMostRootPodfileInFileList(fileList []string) (string, error) {
podfiles, err := pathutil.FilterPaths(fileList,
pathfilters.AllowPodfileBaseFilter,
pathfilters.ForbidCarthageDirComponentFilter,
pathfilters.ForbidPodsDirComponentFilter,
pathfilters.ForbidGitDirComponentFilter,
pathfilters.ForbidFramworkComponentWithExtensionFilter)
if err != nil {
return "", err
}
podfiles, err = pathutil.SortPathsByComponents(podfiles)
if err != nil {
return "", err
}
if len(podfiles) < 1 {
return "", nil
}
return podfiles[0], nil
}
func findMostRootPodfile(dir string) (string, error) {
fileList, err := pathutil.ListPathInDirSortedByComponents(dir, false)
if err != nil {
return "", err
}
return findMostRootPodfileInFileList(fileList)
}
func cocoapodsVersionFromPodfileLockContent(content string) string {
exp := regexp.MustCompile("COCOAPODS: (.+)")
match := exp.FindStringSubmatch(content)
if len(match) == 2 {
return match[1]
}
return ""
}
func cocoapodsVersionFromPodfileLock(podfileLockPth string) (string, error) {
content, err := fileutil.ReadStringFromFile(podfileLockPth)
if err != nil {
return "", err
}
return cocoapodsVersionFromPodfileLockContent(content), nil
}
// VersionSpec ...
type VersionSpec struct {
Operator string
Version string
}
func splitOperatorAndVersion(input string) (VersionSpec, error) {
splittedString := strings.Split(input, " ")
cnt := len(splittedString)
if cnt == 1 {
out := VersionSpec{"", splittedString[0]}
return out, nil
}
if cnt != 2 {
err := fmt.Errorf("Invalid version range: %s", input)
return VersionSpec{}, err
}
out := VersionSpec{splittedString[0], splittedString[1]}
return out, nil
}
func isIncludedInGemfileLockVersionRanges(input string, gemfileLockVersion string) (bool, error) {
var splittedVersions = strings.Split(gemfileLockVersion, ", ")
for _, each := range splittedVersions {
versionSpec, err := splitOperatorAndVersion(each)
if err != nil {
return false, err
}
switch versionSpec.Operator {
case "":
if input != versionSpec.Version {
return false, nil
}
continue
case "~>":
if input != versionSpec.Version {
return false, nil
}
continue
case ">=":
versions := strings.Split(versionSpec.Version, ".")
inputVersions := strings.Split(input, ".")
for i, version := range versions {
v1, err := strconv.Atoi(version)
if err != nil {
return false, err
}
v2, err := strconv.Atoi(inputVersions[i])
if err != nil {
return false, err
}
if i != len(versions)-1 && v1 == v2 {
continue
}
if v2 >= v1 {
break
} else {
return false, nil
}
}
continue
case "<":
versions := strings.Split(versionSpec.Version, ".")
inputVersions := strings.Split(input, ".")
for i, version := range versions {
v1, err := strconv.Atoi(version)
if err != nil {
return false, err
}
v2, err := strconv.Atoi(inputVersions[i])
if err != nil {
return false, err
}
if i != len(versions)-1 && v1 == v2 {
continue
}
if v2 < v1 {
break
} else {
return false, nil
}
}
continue
default:
err := fmt.Errorf("Unknown version operator: %s", each)
return false, err
}
}
return true, nil
}
func main() {
configs, err := createConfigsModelFromEnvs()
if err != nil {
failf(err.Error())
}
stepconf.Print(configs)
envRepository := env.NewRepository()
cmdLocator := env.NewCommandLocator()
cmdFactory := v2command.NewFactory(envRepository)
rubyCmdFactory, err := ruby.NewCommandFactory(cmdFactory, cmdLocator)
if err != nil {
failf("failed to create ruby command factory: %s", err)
}
logger := v2log.NewLogger()
tracker := analytics.NewDefaultTracker(logger, analytics.Properties{})
defer tracker.Wait()
//
// Search for Podfile
podfilePath := ""
if configs.PodfilePath == "" {
fmt.Println()
log.Infof("Searching for Podfile")
absSourceRootPath, err := pathutil.AbsPath(configs.SourceRootPath)
if err != nil {
failf("Failed to expand (%s), error: %s", configs.SourceRootPath, err)
}
absPodfilePath, err := findMostRootPodfile(absSourceRootPath)
if err != nil {
failf("Failed to find Podfile, error: %s", err)
}
if absPodfilePath == "" {
failf("No Podfile found")
}
log.Donef("Found Podfile: %s", absPodfilePath)
podfilePath = absPodfilePath
} else {
absPodfilePath, err := pathutil.AbsPath(configs.PodfilePath)
if err != nil {
failf("Failed to expand (%s), error: %s", configs.PodfilePath, err)
}
fmt.Println()
log.Infof("Using Podfile: %s", absPodfilePath)
podfilePath = absPodfilePath
}
isUsingSpecsRepo, err := isPodfileUsingSpecsRepo(podfilePath)
if err != nil {
log.Warnf("Failed to determine if Podfile is using Specs repo, error: %s", err)
} else {
if isUsingSpecsRepo {
addSpecsRepoAnnotation(cmdFactory)
}
tracker.Enqueue("step_cocoapods_install_podfile_used", analytics.Properties{
"step_execution_id": envRepository.Get("BITRISE_STEP_EXECUTION_ID"),
"build_slug": envRepository.Get("BITRISE_BUILD_SLUG"),
"is_using_specs_repo": isUsingSpecsRepo,
})
}
podfileDir := filepath.Dir(podfilePath)
//
// Install required cocoapods version
fmt.Println()
log.Infof("Determining required cocoapods version")
useBundler := false
useCocoapodsVersionFromPodfileLock := ""
useCocoapodsVersionFromGemfileLock := ""
log.Printf("Searching for Podfile.lock")
// Check Podfile.lock for CocoaPods version
podfileLockPth := filepath.Join(podfileDir, "Podfile.lock")
isPodfileLockExists, err := pathutil.IsPathExists(podfileLockPth)
if err != nil {
failf("Failed to check Podfile.lock at: %s, error: %s", podfileLockPth, err)
}
if isPodfileLockExists {
// Podfile.lock exist search for version
log.Printf("Found Podfile.lock: %s", podfileLockPth)
version, err := cocoapodsVersionFromPodfileLock(podfileLockPth)
if err != nil {
failf("Failed to determine CocoaPods version, error: %s", err)
}
if version != "" {
useCocoapodsVersionFromPodfileLock = version
log.Donef("Required CocoaPods version (from Podfile.lock): %s", useCocoapodsVersionFromPodfileLock)
} else {
log.Warnf("No CocoaPods version found in Podfile.lock! (%s)", podfileLockPth)
}
} else {
log.Warnf("No Podfile.lock found at: %s", podfileLockPth)
log.Warnf("Make sure it's committed into your repository!")
}
var pod gems.Version
var bundler gems.Version
log.Printf("Searching for gem lockfile with cocoapods gem")
// Check gem lockfile for CocoaPods version
gemfileLockPth, err := gems.GemFileLockPth(podfileDir)
if err != nil && err != gems.ErrGemLockNotFound {
failf("Failed to check gem lockfile at: %s, error: %s", podfileDir, err)
}
if gemfileLockPth != "" {
// CocoaPods exist search for version in gem lockfile
log.Printf("Found gem lockfile: %s", gemfileLockPth)
content, err := fileutil.ReadStringFromFile(gemfileLockPth)
if err != nil {
failf("failed to read file (%s) contents, error: %s", gemfileLockPth, err)
}
pod, err = gems.ParseVersionFromBundle("cocoapods", content)
if err != nil {
failf("Failed to check if gem lockfile contains cocoapods, error: %s", err)
}
bundler, err = gems.ParseBundlerVersion(content)
if err != nil {
failf("Failed to parse bundler version form cocoapods, error: %s", err)
}
if pod.Found {
useCocoapodsVersionFromGemfileLock = pod.Version
log.Donef("Required CocoaPods version (from gem lockfile): %s", useCocoapodsVersionFromGemfileLock)
isIncludedVersionRange, err := isIncludedInGemfileLockVersionRanges(useCocoapodsVersionFromPodfileLock, useCocoapodsVersionFromGemfileLock)
if err != nil {
failf("Failed to compare version range in gem lockfile, error: %s", err)
}
if !isIncludedVersionRange {
log.Warnf("Cocoapods version required in Podfile.lock (%s) does not match Gemfile.lock (%s). Will install Cocoapods using bundler.", useCocoapodsVersionFromPodfileLock, useCocoapodsVersionFromGemfileLock)
}
useBundler = true
}
} else {
log.Printf("No gem lockfile with cocoapods gem found at: %s", gemfileLockPth)
log.Donef("Using system installed CocoaPods version")
}
if rubycommand.RubyInstallType() == rubycommand.ASDFRuby {
isRubyVersionInstalled, rubyVersion, err := rubycommand.IsSpecifiedASDFRubyInstalled(configs.SourceRootPath)
if err != nil {
failf("Failed to check if selected ruby is installed: %s", err)
}
fmt.Println()
log.Infof("Checking selected Ruby version")
asdfCurrentCmd := command.New("asdf", "current", "ruby").
SetStdout(os.Stdout).
SetStderr(os.Stderr).
SetDir(configs.SourceRootPath)
log.Donef("$ %s", asdfCurrentCmd.PrintableCommandArgs())
if err := asdfCurrentCmd.Run(); err != nil {
log.Warnf("Failed to print selected Ruby version: %s", err)
}
fmt.Println()
if !isRubyVersionInstalled {
log.Errorf("The selected Ruby version (%s) is not installed.", rubyVersion)
} else {
log.Donef("The selected Ruby version (%s) is installed.", rubyVersion)
}
if !isRubyVersionInstalled && os.Getenv("CI") == "true" {
log.Infof("Installing missing Ruby version")
cmd := command.New("asdf", "install", "ruby", rubyVersion).SetStdout(os.Stdout).SetStderr(os.Stderr)
log.Donef("$ %s", cmd.PrintableCommandArgs())
if err := cmd.Run(); err != nil {
log.Errorf("Failed to install Ruby version %s, error: %s", rubyVersion, err)
}
}
} else if rubycommand.RubyInstallType() == rubycommand.RbenvRuby {
rubySelectStart := time.Now()
rubyInstalled, rversion, err := rubycommand.IsSpecifiedRbenvRubyInstalled(configs.SourceRootPath)
if err != nil {
log.Errorf("Failed to check if selected ruby is installed: %s", err)
}
// Check ruby version
// Run this logic only in CI environment when the ruby was installed via rbenv for the virtual machine
if os.Getenv("CI") == "true" {
fmt.Println()
log.Infof("Checking selected Ruby version using rbenv")
if !rubyInstalled {
log.Errorf("Ruby %s is not installed", rversion)
fmt.Println()
cmd := command.New("rbenv", "install", rversion).SetStdout(os.Stdout).SetStderr(os.Stderr)
log.Donef("$ %s", cmd.PrintableCommandArgs())
if err := cmd.Run(); err != nil {
log.Errorf("Failed to install Ruby version %s, error: %s", rversion, err)
}
} else {
log.Donef("Ruby %s is installed", rversion)
}
}
rubySelectDuration := time.Since(rubySelectStart)
isRequiredRubyInstalled, _, err := rubycommand.IsSpecifiedRbenvRubyInstalled(podfileDir)
if err != nil {
log.Errorf("Failed to check if selected ruby is installed: %s", err)
}
effectiveRubyVersion, err := command.New("rbenv", "global").RunAndReturnTrimmedOutput()
if err != nil {
log.Errorf("Failed to check global rbenv version: %w", err)
}
if isRequiredRubyInstalled {
effectiveRubyVersion = rversion
}
tracker.Enqueue("step_ruby_version_selected", analytics.Properties{
"step_execution_id": envRepository.Get("BITRISE_STEP_EXECUTION_ID"),
"build_slug": envRepository.Get("BITRISE_BUILD_SLUG"),
"step_id": "cocoapods-install",
"requested_ruby_version": rversion,
"effective_ruby_version": effectiveRubyVersion,
"version_change_duration_s": int64(rubySelectDuration.Seconds()),
})
}
// Install cocoapods
fmt.Println()
log.Infof("Installing cocoapods")
podCmdSlice := []string{"pod"}
if useBundler {
fmt.Println()
log.Infof("Installing bundler")
// install bundler with `gem install bundler [-v version]`
// in some configurations, the command "bunder _1.2.3_" can return 'Command not found', installing bundler solves this
installBundlerCommand := gems.InstallBundlerCommand(bundler)
installBundlerCommand.SetStdout(os.Stdout).SetStderr(os.Stderr)
installBundlerCommand.SetDir(podfileDir)
log.Donef("$ %s", installBundlerCommand.PrintableCommandArgs())
fmt.Println()
if err := installBundlerCommand.Run(); err != nil {
failf("command failed, error: %s", err)
}
// install gem lockfile gems with `bundle [_version_] install ...`
fmt.Println()
log.Infof("Installing cocoapods with bundler")
cmd, err := gems.BundleInstallCommand(bundler)
if err != nil {
failf("failed to create bundle command model, error: %s", err)
}
cmd.SetStdout(os.Stdout).SetStderr(os.Stderr)
cmd.SetDir(podfileDir)
log.Donef("$ %s", cmd.PrintableCommandArgs())
fmt.Println()
if err := cmd.Run(); err != nil {
failf("Command failed, error: %s", err)
}
if useBundler {
podCmdSlice = append(gems.BundleExecPrefix(bundler), podCmdSlice...)
}
} else if useCocoapodsVersionFromPodfileLock != "" {
log.Printf("Checking cocoapods %s gem", useCocoapodsVersionFromPodfileLock)
installed, err := rubycommand.IsGemInstalled("cocoapods", useCocoapodsVersionFromPodfileLock)
if err != nil {
failf("Failed to check if cocoapods %s installed, error: %s", useCocoapodsVersionFromPodfileLock, err)
}
if !installed {
log.Printf("Installing")
cmds, err := rubycommand.GemInstall("cocoapods", useCocoapodsVersionFromPodfileLock, false)
if err != nil {
failf("Failed to create command model, error: %s", err)
}
for _, cmd := range cmds {
log.Donef("$ %s", cmd.PrintableCommandArgs())
cmd.SetDir(podfileDir)
if out, err := cmd.RunAndReturnTrimmedCombinedOutput(); err != nil {
failf("Command failed: %s\noutput: %s", err, out)
}
}
} else {
log.Printf("Installed")
}
podCmdSlice = append(podCmdSlice, fmt.Sprintf("_%s_", useCocoapodsVersionFromPodfileLock))
} else {
log.Printf("Using system installed cocoapods")
}
fmt.Println()
log.Infof("cocoapods version:")
// pod can be in the PATH as an rbenv shim and pod --version will return "rbenv: pod: command not found"
cmd, err := rubycommand.NewFromSlice(append(podCmdSlice, "--version"))
if err != nil {
failf("Failed to create command model, error: %s", err)
}
cmd.SetStdout(os.Stdout).SetStderr(os.Stderr)
cmd.SetDir(podfileDir)
log.Donef("$ %s", cmd.PrintableCommandArgs())
if err := cmd.Run(); err != nil {
failf("command failed, error: %s", err)
}
// Run pod install
fmt.Println()
log.Infof("Installing Pods")
installer := NewCocoapodsInstaller(rubyCmdFactory, logger)
if err := installer.InstallPods(podCmdSlice, configs.Command, podfileDir, configs.Verbose); err != nil {
failf(errorutil.FormattedError(fmt.Errorf("Failed to install Pods: %w", err)))
}
// Collecting caches
if !configs.IsCacheDisabled && isPodfileLockExists {
fmt.Println()
log.Infof("Collecting Pod cache paths...")
podsCache := cache.New()
podsCache.IncludePath(fmt.Sprintf("%s -> %s", filepath.Join(podfileDir, "Pods"), podfileLockPth))
if err := podsCache.Commit(); err != nil {
log.Warnf("Cache collection skipped: failed to commit cache paths.")
}
}
log.Donef("Success!")
}