-
Notifications
You must be signed in to change notification settings - Fork 347
Expand file tree
/
Copy pathcomposer.go
More file actions
1131 lines (957 loc) · 33.6 KB
/
composer.go
File metadata and controls
1131 lines (957 loc) · 33.6 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
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
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package composer
import (
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net/http"
"os"
"os/exec"
"path/filepath"
"regexp"
"strings"
"github.com/cloudfoundry/libbuildpack"
"github.com/cloudfoundry/php-buildpack/src/php/config"
"github.com/cloudfoundry/php-buildpack/src/php/extensions"
"github.com/cloudfoundry/php-buildpack/src/php/util"
)
// ComposerExtension downloads, installs and runs Composer
type ComposerExtension struct {
jsonPath string
lockPath string
authPath string
buildDir string
bpDir string
cacheDir string
webDir string
libDir string
tmpDir string
detected bool
composerHome string
composerVendorDir string
}
// Name returns the extension name
func (e *ComposerExtension) Name() string {
return "composer"
}
// ShouldCompile determines if Composer should be installed
func (e *ComposerExtension) ShouldCompile(ctx *extensions.Context) bool {
e.buildDir = ctx.GetString("BUILD_DIR")
e.bpDir = ctx.GetString("BP_DIR")
e.webDir = ctx.GetString("WEBDIR")
// Find composer.json and composer.lock
e.jsonPath = findComposerPath(e.buildDir, e.webDir, "composer.json")
e.lockPath = findComposerPath(e.buildDir, e.webDir, "composer.lock")
e.authPath = findComposerPath(e.buildDir, e.webDir, "auth.json")
e.detected = (e.jsonPath != "" || e.lockPath != "")
return e.detected
}
// findComposerPath searches for a Composer file in various locations
func findComposerPath(buildDir, webDir, fileName string) string {
paths := []string{
filepath.Join(buildDir, fileName),
filepath.Join(buildDir, webDir, fileName),
}
// Check for COMPOSER_PATH environment variable
if composerPath := os.Getenv("COMPOSER_PATH"); composerPath != "" {
paths = append(paths,
filepath.Join(buildDir, composerPath, fileName),
filepath.Join(buildDir, webDir, composerPath, fileName),
)
}
for _, path := range paths {
if _, err := os.Stat(path); err == nil {
return path
}
}
return ""
}
// Configure runs early configuration to set PHP version and extensions
func (e *ComposerExtension) Configure(ctx *extensions.Context) error {
if !e.detected {
return nil
}
// Read PHP version and extensions from composer files
var exts []string
// Include any existing extensions
if existing := ctx.GetStringSlice("PHP_EXTENSIONS"); existing != nil {
exts = append(exts, existing...)
}
// Add 'openssl' extension (required for Composer)
exts = append(exts, "openssl")
// Add platform extensions from composer.json
if e.jsonPath != "" {
jsonExts, err := e.readExtensionsFromFile(e.jsonPath)
if err != nil {
return fmt.Errorf("failed to read extensions from composer.json: %w", err)
}
exts = append(exts, jsonExts...)
}
// Add platform extensions from composer.lock
if e.lockPath != "" {
lockExts, err := e.readExtensionsFromFile(e.lockPath)
if err != nil {
return fmt.Errorf("failed to read extensions from composer.lock: %w", err)
}
exts = append(exts, lockExts...)
}
// Read PHP version requirement from composer.json
phpVersion, err := e.readPHPVersionFromComposer()
if err != nil {
return fmt.Errorf("failed to read PHP version from composer files: %w", err)
}
if phpVersion != "" {
// Also check composer.lock for package PHP constraints
lockConstraints := e.readPHPConstraintsFromLock()
selectedVersion := e.pickPHPVersion(ctx, phpVersion, lockConstraints)
ctx.Set("PHP_VERSION", selectedVersion)
}
// Update context with unique extensions
ctx.Set("PHP_EXTENSIONS", util.UniqueStrings(exts))
ctx.Set("PHP_VM", "php")
return nil
}
// readExtensionsFromFile extracts ext-* requirements from composer files
func (e *ComposerExtension) readExtensionsFromFile(path string) ([]string, error) {
data, err := os.ReadFile(path)
if err != nil {
return nil, err
}
var exts []string
// Match "require" sections and extract ext-* entries
reqPattern := regexp.MustCompile(`"require"\s*:\s*\{([^}]*)\}`)
extPattern := regexp.MustCompile(`"ext-([^"]+)"`)
reqMatches := reqPattern.FindAllStringSubmatch(string(data), -1)
for _, reqMatch := range reqMatches {
if len(reqMatch) > 1 {
extMatches := extPattern.FindAllStringSubmatch(reqMatch[1], -1)
for _, extMatch := range extMatches {
if len(extMatch) > 1 {
exts = append(exts, extMatch[1])
}
}
}
}
return exts, nil
}
// readPHPVersionFromComposer reads PHP version requirement
func (e *ComposerExtension) readPHPVersionFromComposer() (string, error) {
// Try composer.json first
if e.jsonPath != "" {
version, err := e.readVersionFromFile(e.jsonPath, "require", "php")
if err != nil {
return "", err
}
if version != "" {
return version, nil
}
}
// Try composer.lock
if e.lockPath != "" {
version, err := e.readVersionFromFile(e.lockPath, "platform", "php")
if err != nil {
return "", err
}
if version != "" {
return version, nil
}
}
return "", nil
}
// readVersionFromFile reads a version constraint from a JSON file
func (e *ComposerExtension) readVersionFromFile(path, section, key string) (string, error) {
data, err := os.ReadFile(path)
if err != nil {
return "", err
}
var parsed map[string]interface{}
if err := json.Unmarshal(data, &parsed); err != nil {
return "", fmt.Errorf("invalid JSON in %s: %w", filepath.Base(path), err)
}
if sectionData, ok := parsed[section].(map[string]interface{}); ok {
if value, ok := sectionData[key].(string); ok {
return value, nil
}
}
return "", nil
}
// readPHPConstraintsFromLock reads PHP constraints from all packages in composer.lock
func (e *ComposerExtension) readPHPConstraintsFromLock() []string {
if e.lockPath == "" {
return nil
}
data, err := os.ReadFile(e.lockPath)
if err != nil {
return nil
}
var lockData struct {
Packages []struct {
Name string `json:"name"`
Require map[string]interface{} `json:"require"`
} `json:"packages"`
}
if err := json.Unmarshal(data, &lockData); err != nil {
return nil
}
var constraints []string
for _, pkg := range lockData.Packages {
if phpConstraint, ok := pkg.Require["php"].(string); ok && phpConstraint != "" {
constraints = append(constraints, phpConstraint)
}
}
return constraints
}
// pickPHPVersion selects the appropriate PHP version based on requirements
func (e *ComposerExtension) pickPHPVersion(ctx *extensions.Context, requested string, lockConstraints []string) string {
if requested == "" {
return ctx.GetString("PHP_VERSION")
}
fmt.Printf("-----> Composer requires PHP %s\n", requested)
// If we have composer.lock constraints, show them
if len(lockConstraints) > 0 {
fmt.Printf(" Locked dependencies have %d additional PHP constraints\n", len(lockConstraints))
}
// Get all available PHP versions from context
// Context should have ALL_PHP_VERSIONS set by supply phase
allVersionsStr := ctx.GetString("ALL_PHP_VERSIONS")
if allVersionsStr == "" {
fmt.Println(" Warning: ALL_PHP_VERSIONS not set in context, using default")
return ctx.GetString("PHP_DEFAULT")
}
// Parse available versions (comma-separated)
availableVersions := strings.Split(allVersionsStr, ",")
for i := range availableVersions {
availableVersions[i] = strings.TrimSpace(availableVersions[i])
}
// Find the best matching version for composer.json constraint
selectedVersion := e.matchVersion(requested, availableVersions)
if selectedVersion == "" {
fmt.Printf(" Warning: No matching PHP version found for %s, using default\n", requested)
return ctx.GetString("PHP_DEFAULT")
}
// If we have lock constraints, ensure the selected version satisfies ALL of them
if len(lockConstraints) > 0 {
// Filter available versions to only those matching ALL constraints (composer.json + lock)
validVersions := []string{}
for _, version := range availableVersions {
// Check composer.json constraint
if !e.versionMatchesConstraint(version, requested) {
continue
}
// Check all lock constraints
matchesAll := true
for _, lockConstraint := range lockConstraints {
if !e.versionMatchesConstraint(version, lockConstraint) {
matchesAll = false
break
}
}
if matchesAll {
validVersions = append(validVersions, version)
}
}
if len(validVersions) == 0 {
fmt.Printf(" Warning: No PHP version satisfies all constraints, using default\n")
return ctx.GetString("PHP_DEFAULT")
}
// Find the highest valid version
selectedVersion = e.findHighestVersion(validVersions)
fmt.Printf(" Selected PHP version: %s (satisfies all %d constraints)\n", selectedVersion, len(lockConstraints)+1)
} else {
fmt.Printf(" Selected PHP version: %s\n", selectedVersion)
}
return selectedVersion
}
// matchVersion finds the best matching version for a given constraint
func (e *ComposerExtension) matchVersion(constraint string, availableVersions []string) string {
// Remove leading/trailing spaces
constraint = strings.TrimSpace(constraint)
// Handle compound constraints FIRST (before single operator checks)
// OR constraint: find highest version matching any constraint
if strings.Contains(constraint, "||") {
parts := strings.Split(constraint, "||")
var matches []string
for _, part := range parts {
if result := e.matchVersion(strings.TrimSpace(part), availableVersions); result != "" {
matches = append(matches, result)
}
}
if len(matches) > 0 {
return e.findHighestVersion(matches)
}
return ""
}
// AND constraint (multiple constraints): check all
// Must check BEFORE single operators, as ">=8.1.0 <8.3.0" contains spaces
if strings.Contains(constraint, " ") {
parts := strings.Fields(constraint)
candidates := availableVersions
for _, part := range parts {
newCandidates := []string{}
for _, v := range candidates {
if e.versionMatchesConstraint(v, part) {
newCandidates = append(newCandidates, v)
}
}
candidates = newCandidates
}
if len(candidates) > 0 {
return e.findHighestVersion(candidates)
}
return ""
}
// Handle single operator constraints
if strings.HasPrefix(constraint, ">=") {
// >= constraint: find highest version that is >= requested
minVersion := strings.TrimSpace(constraint[2:])
return e.findHighestVersionGTE(minVersion, availableVersions)
} else if strings.HasPrefix(constraint, ">") {
// > constraint: find highest version that is > requested
minVersion := strings.TrimSpace(constraint[1:])
return e.findHighestVersionGT(minVersion, availableVersions)
} else if strings.HasPrefix(constraint, "<=") {
// <= constraint: find highest version that is <= requested
maxVersion := strings.TrimSpace(constraint[2:])
return e.findHighestVersionLTE(maxVersion, availableVersions)
} else if strings.HasPrefix(constraint, "<") {
// < constraint: find highest version that is < requested
maxVersion := strings.TrimSpace(constraint[1:])
return e.findHighestVersionLT(maxVersion, availableVersions)
} else if strings.HasPrefix(constraint, "^") {
// ^ constraint: compatible version (same major version)
baseVersion := strings.TrimSpace(constraint[1:])
return e.findCompatibleVersion(baseVersion, availableVersions)
} else if strings.HasPrefix(constraint, "~") {
// ~ constraint: approximately equivalent (same major.minor)
baseVersion := strings.TrimSpace(constraint[1:])
return e.findApproximateVersion(baseVersion, availableVersions)
} else {
// Exact version or wildcard
if strings.Contains(constraint, "*") {
return e.findWildcardMatch(constraint, availableVersions)
}
// Check if exact version exists
for _, v := range availableVersions {
if v == constraint {
return v
}
}
}
return ""
}
// versionMatchesConstraint checks if a version matches a single constraint
func (e *ComposerExtension) versionMatchesConstraint(version, constraint string) bool {
constraint = strings.TrimSpace(constraint)
// Handle OR constraints (||)
if strings.Contains(constraint, "||") {
parts := strings.Split(constraint, "||")
for _, part := range parts {
if e.versionMatchesConstraint(version, strings.TrimSpace(part)) {
return true
}
}
return false
}
// Handle AND constraints (space-separated)
if strings.Contains(constraint, " ") {
parts := strings.Fields(constraint)
for _, part := range parts {
if !e.versionMatchesConstraint(version, strings.TrimSpace(part)) {
return false
}
}
return true
}
if strings.HasPrefix(constraint, ">=") {
minVersion := strings.TrimSpace(constraint[2:])
return util.CompareVersions(version, minVersion) >= 0
} else if strings.HasPrefix(constraint, ">") {
minVersion := strings.TrimSpace(constraint[1:])
return util.CompareVersions(version, minVersion) > 0
} else if strings.HasPrefix(constraint, "<=") {
maxVersion := strings.TrimSpace(constraint[2:])
return util.CompareVersions(version, maxVersion) <= 0
} else if strings.HasPrefix(constraint, "<") {
maxVersion := strings.TrimSpace(constraint[1:])
return util.CompareVersions(version, maxVersion) < 0
} else if strings.HasPrefix(constraint, "^") {
baseVersion := strings.TrimSpace(constraint[1:])
return e.isCompatible(version, baseVersion)
} else if strings.HasPrefix(constraint, "~") {
baseVersion := strings.TrimSpace(constraint[1:])
return e.isApproximatelyEquivalent(version, baseVersion)
} else if constraint == version {
return true
}
return false
}
// findHighestVersionGTE finds the highest version >= minVersion
func (e *ComposerExtension) findHighestVersionGTE(minVersion string, versions []string) string {
var best string
for _, v := range versions {
if util.CompareVersions(v, minVersion) >= 0 {
if best == "" || util.CompareVersions(v, best) > 0 {
best = v
}
}
}
return best
}
// findHighestVersionGT finds the highest version > minVersion
func (e *ComposerExtension) findHighestVersionGT(minVersion string, versions []string) string {
var best string
for _, v := range versions {
if util.CompareVersions(v, minVersion) > 0 {
if best == "" || util.CompareVersions(v, best) > 0 {
best = v
}
}
}
return best
}
// findHighestVersionLTE finds the highest version <= maxVersion
func (e *ComposerExtension) findHighestVersionLTE(maxVersion string, versions []string) string {
var best string
for _, v := range versions {
if util.CompareVersions(v, maxVersion) <= 0 {
if best == "" || util.CompareVersions(v, best) > 0 {
best = v
}
}
}
return best
}
// findHighestVersionLT finds the highest version < maxVersion
func (e *ComposerExtension) findHighestVersionLT(maxVersion string, versions []string) string {
var best string
for _, v := range versions {
if util.CompareVersions(v, maxVersion) < 0 {
if best == "" || util.CompareVersions(v, best) > 0 {
best = v
}
}
}
return best
}
// findHighestVersion finds the highest version from a list
func (e *ComposerExtension) findHighestVersion(versions []string) string {
if len(versions) == 0 {
return ""
}
best := versions[0]
for _, v := range versions[1:] {
if util.CompareVersions(v, best) > 0 {
best = v
}
}
return best
}
// findCompatibleVersion finds the highest compatible version (^ constraint)
func (e *ComposerExtension) findCompatibleVersion(baseVersion string, versions []string) string {
var best string
for _, v := range versions {
if e.isCompatible(v, baseVersion) {
if best == "" || util.CompareVersions(v, best) > 0 {
best = v
}
}
}
return best
}
// findApproximateVersion finds the highest approximately equivalent version (~ constraint)
func (e *ComposerExtension) findApproximateVersion(baseVersion string, versions []string) string {
var best string
for _, v := range versions {
if e.isApproximatelyEquivalent(v, baseVersion) {
if best == "" || util.CompareVersions(v, best) > 0 {
best = v
}
}
}
return best
}
// findWildcardMatch finds versions matching a wildcard pattern
func (e *ComposerExtension) findWildcardMatch(pattern string, versions []string) string {
// Replace * with empty string to get prefix
prefix := strings.Replace(pattern, "*", "", -1)
prefix = strings.TrimSuffix(prefix, ".")
var best string
for _, v := range versions {
if strings.HasPrefix(v, prefix) {
if best == "" || util.CompareVersions(v, best) > 0 {
best = v
}
}
}
return best
}
// isCompatible checks if version is compatible with base (^ constraint)
// Compatible means same major version, and >= base version
func (e *ComposerExtension) isCompatible(version, base string) bool {
vParts := strings.Split(version, ".")
bParts := strings.Split(base, ".")
if len(vParts) < 1 || len(bParts) < 1 {
return false
}
// Must have same major version
if vParts[0] != bParts[0] {
return false
}
// Must be >= base version
return util.CompareVersions(version, base) >= 0
}
// isApproximatelyEquivalent checks if version is approximately equivalent to base (~ constraint)
// Approximately equivalent means same major.minor, and >= base version
func (e *ComposerExtension) isApproximatelyEquivalent(version, base string) bool {
vParts := strings.Split(version, ".")
bParts := strings.Split(base, ".")
if len(vParts) < 2 || len(bParts) < 2 {
return false
}
// Must have same major.minor version
if vParts[0] != bParts[0] || vParts[1] != bParts[1] {
return false
}
// Must be >= base version
return util.CompareVersions(version, base) >= 0
}
// compareVersions compares two semantic versions
// Returns: -1 if v1 < v2, 0 if v1 == v2, 1 if v1 > v2
// Compile downloads and runs Composer
func (e *ComposerExtension) Compile(ctx *extensions.Context, installer *extensions.Installer) error {
if !e.detected {
return nil
}
e.cacheDir = ctx.GetString("CACHE_DIR")
e.libDir = ctx.GetString("LIBDIR")
e.tmpDir = ctx.GetString("TMPDIR")
e.composerHome = filepath.Join(e.cacheDir, "composer")
// Get COMPOSER_VENDOR_DIR from context
e.composerVendorDir = ctx.GetString("COMPOSER_VENDOR_DIR")
if e.composerVendorDir == "" {
// Default to LIBDIR/vendor if not specified
e.composerVendorDir = filepath.Join(e.libDir, "vendor")
}
// Clean old cache directory
e.cleanCacheDir()
// Move local vendor folder if it exists
if err := e.moveLocalVendorFolder(); err != nil {
return fmt.Errorf("failed to move vendor folder: %w", err)
}
// Install PHP (required for Composer to run)
fmt.Println("-----> Installing PHP for Composer")
if err := installer.Package("php"); err != nil {
return fmt.Errorf("failed to install PHP: %w", err)
}
// Load user-requested extensions from .bp-config/php/php.ini.d/*.ini files
// and add them to the context so they're available during composer
if err := e.loadUserExtensions(ctx); err != nil {
return fmt.Errorf("failed to load user extensions: %w", err)
}
// Setup PHP configuration (config files + process extensions in php.ini)
if err := e.setupPHPConfig(ctx); err != nil {
return fmt.Errorf("failed to setup PHP config: %w", err)
}
// Install Composer itself
if err := e.installComposer(ctx, installer); err != nil {
return fmt.Errorf("failed to install Composer: %w", err)
}
// Move composer files to build directory root
e.moveComposerFilesToRoot()
// Sanity check for composer.lock
if _, err := os.Stat(filepath.Join(e.buildDir, "composer.lock")); os.IsNotExist(err) {
msg := "PROTIP: Include a `composer.lock` file with your application! " +
"This will make sure the exact same version of dependencies are used " +
"when you deploy to CloudFoundry."
fmt.Printf("-----> %s\n", msg)
}
// Run composer install
if err := e.runComposer(ctx); err != nil {
return fmt.Errorf("failed to run composer: %w", err)
}
return nil
}
// cleanCacheDir removes old cache directory if needed
func (e *ComposerExtension) cleanCacheDir() {
cacheDir := filepath.Join(e.composerHome, "cache")
if _, err := os.Stat(cacheDir); os.IsNotExist(err) {
// Old style cache exists, remove it
os.RemoveAll(e.composerHome)
}
}
// moveLocalVendorFolder moves existing vendor directory to configured location
func (e *ComposerExtension) moveLocalVendorFolder() error {
vendorPath := filepath.Join(e.buildDir, e.webDir, "vendor")
if _, err := os.Stat(vendorPath); os.IsNotExist(err) {
return nil
}
fmt.Printf("-----> Moving existing vendor directory to %s\n", e.composerVendorDir)
destPath := filepath.Join(e.buildDir, e.composerVendorDir)
// Create parent directory if it doesn't exist
destDir := filepath.Dir(destPath)
if err := os.MkdirAll(destDir, 0755); err != nil {
return fmt.Errorf("failed to create vendor parent directory: %w", err)
}
if err := os.Rename(vendorPath, destPath); err != nil {
return fmt.Errorf("failed to move vendor directory: %w", err)
}
return nil
}
// installComposer downloads and installs Composer
func (e *ComposerExtension) installComposer(ctx *extensions.Context, installer *extensions.Installer) error {
composerVersion := ctx.GetString("COMPOSER_VERSION")
dest := filepath.Join(e.buildDir, "php", "bin", "composer.phar")
if composerVersion == "latest" {
// Check if we're in a cached buildpack
depsPath := filepath.Join(e.bpDir, "dependencies")
if _, err := os.Stat(depsPath); err == nil {
return fmt.Errorf("\"COMPOSER_VERSION\": \"latest\" is not supported in the cached buildpack. " +
"Please vendor your preferred version of composer with your app, or use the provided default composer version")
}
// Download latest composer from getcomposer.org
url := "https://getcomposer.org/composer.phar"
fmt.Println("-----> Downloading latest Composer")
if err := e.downloadFile(url, dest); err != nil {
return fmt.Errorf("failed to download latest composer: %w", err)
}
} else {
// Install from manifest using InstallDependency (supports cached buildpack)
fmt.Printf("-----> Installing composer %s\n", composerVersion)
// Create a temporary directory for the composer download
tmpDir, err := ioutil.TempDir("", "composer-install")
if err != nil {
return fmt.Errorf("failed to create temp dir: %w", err)
}
defer os.RemoveAll(tmpDir)
// Use InstallDependency to download composer (works with cached buildpack)
dep := libbuildpack.Dependency{
Name: "composer",
Version: composerVersion,
}
if err := installer.InstallDependency(dep, tmpDir); err != nil {
return fmt.Errorf("failed to install composer from manifest: %w", err)
}
// Find the downloaded .phar file (e.g., composer_2.8.8_linux_noarch_cflinuxfs4_abc123.phar)
files, err := ioutil.ReadDir(tmpDir)
if err != nil {
return fmt.Errorf("failed to read temp dir: %w", err)
}
var pharFile string
for _, f := range files {
if strings.HasSuffix(f.Name(), ".phar") {
pharFile = filepath.Join(tmpDir, f.Name())
break
}
}
if pharFile == "" {
return fmt.Errorf("no .phar file found after composer installation")
}
// Create destination directory
if err := os.MkdirAll(filepath.Dir(dest), 0755); err != nil {
return fmt.Errorf("failed to create composer bin dir: %w", err)
}
// Move the .phar file to the correct location
if err := os.Rename(pharFile, dest); err != nil {
return fmt.Errorf("failed to move composer.phar: %w", err)
}
// Make executable
if err := os.Chmod(dest, 0755); err != nil {
return fmt.Errorf("failed to make composer.phar executable: %w", err)
}
}
return nil
}
// downloadFile downloads a file from a URL
func (e *ComposerExtension) downloadFile(url, dest string) error {
resp, err := http.Get(url)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("download failed with status: %s", resp.Status)
}
// Create destination directory
if err := os.MkdirAll(filepath.Dir(dest), 0755); err != nil {
return err
}
// Create file
file, err := os.Create(dest)
if err != nil {
return err
}
defer file.Close()
// Copy data
if _, err := io.Copy(file, resp.Body); err != nil {
return err
}
// Make executable
return os.Chmod(dest, 0755)
}
// moveComposerFilesToRoot moves composer files to build directory root
func (e *ComposerExtension) moveComposerFilesToRoot() {
e.moveFileToRoot(e.jsonPath, "composer.json")
e.moveFileToRoot(e.lockPath, "composer.lock")
e.moveFileToRoot(e.authPath, "auth.json")
}
// moveFileToRoot moves a file to the build directory root if needed
func (e *ComposerExtension) moveFileToRoot(filePath, fileName string) {
if filePath == "" {
return
}
destPath := filepath.Join(e.buildDir, fileName)
if filePath == destPath {
return // Already in root
}
if err := os.Rename(filePath, destPath); err != nil {
fmt.Printf("-----> WARNING: Failed to move %s: %v\n", fileName, err)
}
}
// runComposer executes composer install
func (e *ComposerExtension) runComposer(ctx *extensions.Context) error {
phpPath := filepath.Join(e.buildDir, "php", "bin", "php")
composerPath := filepath.Join(e.buildDir, "php", "bin", "composer.phar")
// Check if buildpack is cached (has dependencies directory)
depsPath := filepath.Join(e.bpDir, "dependencies")
_, hasDeps := os.Stat(depsPath)
// Set up GitHub OAuth token if provided and not cached
tokenValid := false
if os.IsNotExist(hasDeps) {
if token := os.Getenv("COMPOSER_GITHUB_OAUTH_TOKEN"); token != "" {
tokenValid = e.setupGitHubToken(phpPath, composerPath, token)
}
// Check GitHub rate limit
e.checkGitHubRateLimit(tokenValid)
}
// Get Composer install options
installOpts := ctx.GetStringSlice("COMPOSER_INSTALL_OPTIONS")
if installOpts == nil {
installOpts = []string{"--no-interaction", "--no-dev"}
}
// Install global Composer dependencies if specified
globalDeps := ctx.GetStringSlice("COMPOSER_INSTALL_GLOBAL")
if len(globalDeps) > 0 {
fmt.Println("-----> Installing global Composer dependencies")
args := []string{"global", "require", "--no-progress"}
args = append(args, globalDeps...)
if err := e.runComposerCommand(ctx, phpPath, composerPath, args...); err != nil {
return fmt.Errorf("failed to install global dependencies: %w", err)
}
}
// Run composer install
fmt.Println("-----> Installing Composer dependencies")
args := []string{"install", "--no-progress"}
args = append(args, installOpts...)
if err := e.runComposerCommand(ctx, phpPath, composerPath, args...); err != nil {
fmt.Println("-----> Composer command failed")
return fmt.Errorf("composer install failed: %w", err)
}
return nil
}
// setupPHPConfig sets up PHP configuration files and processes extensions
func (e *ComposerExtension) setupPHPConfig(ctx *extensions.Context) error {
phpInstallDir := filepath.Join(e.buildDir, "php")
phpEtcDir := filepath.Join(phpInstallDir, "etc")
phpVersion := ctx.GetString("PHP_VERSION")
if phpVersion == "" {
return fmt.Errorf("PHP_VERSION not set in context")
}
versionParts := strings.Split(phpVersion, ".")
if len(versionParts) < 2 {
return fmt.Errorf("invalid PHP version format: %s", phpVersion)
}
majorMinor := fmt.Sprintf("%s.%s", versionParts[0], versionParts[1])
phpConfigPath := fmt.Sprintf("php/%s.x", majorMinor)
if err := config.ExtractConfig(phpConfigPath, phpEtcDir); err != nil {
return fmt.Errorf("failed to extract PHP config: %w", err)
}
phpIniDir := filepath.Join(phpEtcDir, "php.ini.d")
if err := os.MkdirAll(phpIniDir, 0755); err != nil {
return fmt.Errorf("failed to create php.ini.d directory: %w", err)
}
phpIniPath := filepath.Join(phpEtcDir, "php.ini")
if err := e.processPhpIni(ctx, phpIniPath); err != nil {
return fmt.Errorf("failed to process php.ini: %w", err)
}
tmpPhpIniPath := filepath.Join(e.tmpDir, "php.ini")
if err := util.CopyFile(phpIniPath, tmpPhpIniPath); err != nil {
return fmt.Errorf("failed to copy php.ini to TMPDIR: %w", err)
}
return nil
}
func (e *ComposerExtension) processPhpIni(ctx *extensions.Context, phpIniPath string) error {
phpExtensions := ctx.GetStringSlice("PHP_EXTENSIONS")
zendExtensions := ctx.GetStringSlice("ZEND_EXTENSIONS")
phpInstallDir := filepath.Join(e.buildDir, "php")
additionalReplacements := map[string]string{
"@{HOME}": e.buildDir,
"@{TMPDIR}": e.tmpDir,
"#{LIBDIR}": e.libDir,
}
logWarning := func(format string, args ...interface{}) {
fmt.Printf(" WARNING: "+format+"\n", args...)
}
if err := config.ProcessPhpIni(
phpIniPath,
phpInstallDir,
phpExtensions,
zendExtensions,
additionalReplacements,
logWarning,
); err != nil {
return err
}
phpExtDir := ""
phpLibDir := filepath.Join(e.buildDir, "php", "lib", "php", "extensions")
if entries, err := os.ReadDir(phpLibDir); err == nil {
for _, entry := range entries {
if entry.IsDir() && strings.HasPrefix(entry.Name(), "no-debug-non-zts-") {
phpExtDir = filepath.Join(phpLibDir, entry.Name())
break
}
}
}
if phpExtDir != "" {
content, err := os.ReadFile(phpIniPath)
if err != nil {
return fmt.Errorf("failed to read php.ini: %w", err)
}
phpIniContent := string(content)
lines := strings.Split(phpIniContent, "\n")
for i, line := range lines {
trimmed := strings.TrimSpace(line)
if strings.HasPrefix(trimmed, "extension_dir") && !strings.HasPrefix(trimmed, ";") {
lines[i] = fmt.Sprintf("extension_dir = \"%s\"", phpExtDir)
break
}
}
phpIniContent = strings.Join(lines, "\n")
if err := os.WriteFile(phpIniPath, []byte(phpIniContent), 0644); err != nil {
return fmt.Errorf("failed to write php.ini: %w", err)
}
}
fmt.Printf(" Configured PHP with extensions\n")
return nil
}
// setupGitHubToken configures GitHub OAuth token for Composer
func (e *ComposerExtension) setupGitHubToken(phpPath, composerPath, token string) bool {
if !e.isValidGitHubToken(token) {
fmt.Println("-----> The GitHub OAuth token supplied from $COMPOSER_GITHUB_OAUTH_TOKEN is invalid")
return false
}
fmt.Println("-----> Using custom GitHub OAuth token in $COMPOSER_GITHUB_OAUTH_TOKEN")
// Run: composer config -g github-oauth.github.com TOKEN
cmd := exec.Command(phpPath, composerPath, "config", "-g", "github-oauth.github.com", token)
cmd.Dir = e.buildDir
cmd.Env = e.buildComposerEnv()
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr