-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcomposer.go
94 lines (81 loc) · 1.72 KB
/
composer.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
package gocommerce
import (
"encoding/json"
"errors"
"os"
"regexp"
"strings"
)
type (
composerRoot struct {
Name string `json:"name"`
Version string `json:"version"`
Require map[string]string `json:"require"`
}
composerPackages struct {
Packages []struct {
Name string `json:"name"`
Version string `json:"version"`
} `json:"packages"`
}
)
func getVersionFromComposerJSONFile(
jsonFile string,
pkgRgx *regexp.Regexp,
) (string, error) {
jf, err := os.ReadFile(jsonFile)
if err != nil {
return "", err
}
cr := composerRoot{}
err = json.Unmarshal(jf, &cr)
if err != nil {
return "", err
}
for p, v := range cr.Require {
if pkgRgx.MatchString(p) {
return v, nil
}
}
return "", errors.New("unable to determine version from composer.json")
}
func getVersionFromComposerLockFile(
lockFile string,
pkgRgx *regexp.Regexp,
) (string, error) {
lf, err := os.ReadFile(lockFile)
if err != nil {
return "", err
}
cp := composerPackages{}
err = json.Unmarshal(lf, &cp)
if err != nil {
return "", err
}
for _, p := range cp.Packages {
if pkgRgx.MatchString(p.Name) {
return p.Version, nil
}
}
return "", errors.New("unable to determine version from composer.lock")
}
func stripVersionPrefix(v string) string {
if strings.HasPrefix(v, "v") {
return v[1:]
}
return v
}
func getVersionFromComposer(
docroot string,
pkgRgx *regexp.Regexp,
) (string, error) {
version, err := getVersionFromComposerLockFile(docroot+"/composer.lock", pkgRgx)
if err == nil {
return stripVersionPrefix(version), nil
}
version, err = getVersionFromComposerJSONFile(docroot+"/composer.json", pkgRgx)
if err == nil {
return stripVersionPrefix(version), nil
}
return "", err
}