-
Notifications
You must be signed in to change notification settings - Fork 56
/
Copy pathutils-ruby.go
81 lines (66 loc) · 1.77 KB
/
utils-ruby.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
package common
import (
"fmt"
"io/ioutil"
"regexp"
"strings"
)
var (
rubyVersionRegex = regexp.MustCompile("ruby\\s['\"](.*?)['\"]")
)
// Looks for ruby version in the gemfile. If found returns true, version if not false, ""
func GetRubyVersion(gemFile string) (bool, string) {
buf, err := ioutil.ReadFile(gemFile)
if err != nil {
return false, err.Error()
}
lines := strings.Split(string(buf), "\n")
for _, line := range lines {
if line == "" || strings.HasPrefix(line, "#") {
continue
}
if rubyVersionRegex.MatchString(line) {
sm := rubyVersionRegex.FindStringSubmatch(line)
return true, sm[1]
}
}
return false, ""
}
// returns bool = found any of the gems or not and string = the version of the first found
func GetGemVersion(gemFile string, gemNames ...string) (bool, string) {
buf, err := ioutil.ReadFile(gemFile)
if err != nil {
return false, err.Error()
}
lines := strings.Split(string(buf), "\n")
for _, line := range lines {
for _, gemName := range gemNames {
found, version := ParseLineForGem(gemName, line)
if found {
return true, version
}
}
}
return false, ""
}
// Checks a line to see if it contains the given gem. returns true, version or false, ""
func ParseLineForGem(gemName string, line string) (bool, string) {
line = strings.TrimSpace(line)
if line == "" || strings.HasPrefix(line, "#") {
// empty or comment
return false, ""
}
re := regexp.MustCompile(fmt.Sprintf("gem\\s['\"]%s['\"]\\s*,?\\s*(?P<version>['\"].*?['\"])?", gemName))
if !re.MatchString(line) {
return false, ""
} else {
sm := re.FindStringSubmatch(line)
if len(sm) > 0 {
result := strings.Replace(sm[1], "'", "", -1)
result = strings.Replace(result, "\"", "", -1)
return true, result
} else {
return true, ""
}
}
}