-
Notifications
You must be signed in to change notification settings - Fork 438
Expand file tree
/
Copy pathrubygems.go
More file actions
315 lines (298 loc) · 8.78 KB
/
Copy pathrubygems.go
File metadata and controls
315 lines (298 loc) · 8.78 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
// Package rubygems scans Bundler artifacts (Gemfile.lock) and installed
// gemspec files.
//
// Gemfile.lock format is well-defined and stable. The parser only reads the
// GEM/GIT/PATH "specs:" blocks for top-level "name (version)" lines.
// Nested dependency lines (further indented) are ignored to avoid
// double-counting transitive deps as their own gems.
//
// Installed *.gemspec files are read for Name + Version via a simple text
// parser (no Ruby interpretation). This is a deliberately conservative
// reader that handles the canonical generated gemspec form.
package rubygems
import (
"bufio"
"bytes"
"errors"
"fmt"
"io"
"os"
"path/filepath"
"regexp"
"strings"
"github.com/perplexityai/bumblebee/internal/model"
)
const Ecosystem = model.EcosystemRubyGems
type Scanner struct {
MaxFileSize int64
Emit func(model.Record)
Diag func(level, path, msg string)
}
func IsGemfileLock(base string) bool { return base == "Gemfile.lock" }
func IsGemspec(base string) bool { return strings.HasSuffix(base, ".gemspec") }
func (s *Scanner) ScanGemfileLock(path string, base model.Record) error {
data, err := s.readBounded(path)
if err != nil {
return err
}
projectPath := filepath.Dir(path)
gems := parseGemfileLock(data)
for _, g := range gems {
r := base
r.Ecosystem = Ecosystem
r.PackageName = g.name
r.NormalizedName = strings.ToLower(g.name)
r.Version = g.version
r.ProjectPath = projectPath
r.PackageManager = "bundler"
r.SourceType = "rubygems-gemfile-lock"
r.SourceFile = path
r.Confidence = "high"
s.Emit(r)
}
return nil
}
type gemEntry struct {
name string
version string
section string
}
func parseGemfileLock(data []byte) []gemEntry {
var out []gemEntry
sc := bufio.NewScanner(bytes.NewReader(data))
sc.Buffer(make([]byte, 0, 64*1024), 4*1024*1024)
section := ""
inSpecs := false
for sc.Scan() {
raw := sc.Text()
trim := strings.TrimSpace(raw)
if !strings.HasPrefix(raw, " ") && trim != "" {
// Section header.
switch trim {
case "GEM", "GIT", "PATH", "PLATFORMS", "DEPENDENCIES", "RUBY VERSION", "BUNDLED WITH", "CHECKSUMS":
section = trim
inSpecs = false
default:
section = ""
inSpecs = false
}
continue
}
if section != "GEM" && section != "GIT" && section != "PATH" {
continue
}
// " specs:" header.
if trim == "specs:" {
inSpecs = true
continue
}
if !inSpecs {
continue
}
// Top-level gem line: exactly 4 spaces of indent.
if strings.HasPrefix(raw, " ") && !strings.HasPrefix(raw, " ") {
name, ver := parseGemfileLockSpec(trim)
if name != "" && ver != "" {
out = append(out, gemEntry{name: name, version: ver, section: section})
}
}
}
return out
}
var gemSpecRe = regexp.MustCompile(`^([A-Za-z0-9_.\-]+)\s*\(([^)]+)\)$`)
func parseGemfileLockSpec(s string) (string, string) {
m := gemSpecRe.FindStringSubmatch(s)
if m == nil {
return "", ""
}
// Gemfile.lock version field may be "1.2.3" or "1.2.3-x86_64-linux".
return m[1], strings.TrimSpace(m[2])
}
// IsInstalledGemspec returns (true, gemsDir) for paths under
// .../specifications/<name>-<ver>.gemspec or a `gems/<name>-<ver>/<name>.gemspec`
// shape that is clearly under a recognized installed-gems root.
//
// We accept the gems/<name>-<ver>/ form only when:
// - the immediate parent dir name is `<name>-<ver>` (contains a `-`), AND
// - its grandparent is named `gems`, AND
// - the gemspec basename matches the `<name>` prefix of the parent dir name
// (real installed gems have `gems/foo-1.2.3/foo.gemspec`), AND
// - the great-grandparent is a recognized gem-root indicator (has a sibling
// `specifications/` dir, or is one of `bundler`, `rubygems`, `.bundle`,
// `cache`, or itself contains a `cache/` subtree, or is `vendor`).
//
// This rejects arbitrary `~/proj/gems/foo-1.0/foo.gemspec` trees that are not
// actually installed-gem metadata.
func IsInstalledGemspec(path string) (bool, string) {
if !IsGemspec(filepath.Base(path)) {
return false, ""
}
parent := filepath.Dir(path)
pb := filepath.Base(parent)
gparent := filepath.Dir(parent)
gpb := filepath.Base(gparent)
// specifications/<name>-<ver>.gemspec — canonical installed metadata.
if pb == "specifications" {
return true, parent
}
// gems/<name>-<ver>/<name>.gemspec — only when the shape is clearly an
// installed gem tree.
if gpb != "gems" || !strings.Contains(pb, "-") {
return false, ""
}
// Filename must match the `<name>` prefix of the parent dir.
bn := strings.TrimSuffix(filepath.Base(path), ".gemspec")
dash := strings.LastIndexByte(pb, '-')
if dash <= 0 {
return false, ""
}
if pb[:dash] != bn {
return false, ""
}
// Great-grandparent must look like an installed-gems root: either has a
// sibling `specifications/` directory, or is one of the recognized roots.
ggparent := filepath.Dir(gparent)
if isInstalledGemRoot(ggparent) {
return true, parent
}
return false, ""
}
func isInstalledGemRoot(dir string) bool {
if dir == "" || dir == "." || dir == "/" {
return false
}
// Sibling specifications/ directory is the strongest signal: a gem home
// has both `gems/` and `specifications/` under the same parent.
if info, err := os.Stat(filepath.Join(dir, "specifications")); err == nil && info.IsDir() {
return true
}
bn := filepath.Base(dir)
switch bn {
case "bundler", "rubygems", ".bundle", "vendor", "cache":
return true
}
// RubyGems install layout: <root>/gems/<ruby_abi>/gems/<name>-<ver>/.
// Great-grandparent of the gemspec is `<root>/gems/<ruby_abi>` whose
// parent is `gems`. Accept that nesting.
if filepath.Base(filepath.Dir(dir)) == "gems" && looksLikeRubyABI(bn) {
return true
}
// Common Bundler layouts: vendor/bundle/ruby/<ver>/gems/...
parent := filepath.Dir(dir)
if filepath.Base(parent) == "ruby" {
gp := filepath.Dir(parent)
gpb := filepath.Base(gp)
if gpb == "bundle" || gpb == "vendor" {
return true
}
}
return false
}
// looksLikeRubyABI reports whether s looks like a Ruby ABI version such as
// "3.2.0" or "2.7.0". This is the directory name RubyGems uses under
// `<gem_home>/gems/`.
func looksLikeRubyABI(s string) bool {
if s == "" {
return false
}
hasDigit := false
for i := range len(s) {
c := s[i]
if c >= '0' && c <= '9' {
hasDigit = true
continue
}
if c == '.' {
continue
}
return false
}
return hasDigit
}
var (
gemspecNameRe = regexp.MustCompile(`(?m)^\s*\w+\.name\s*=\s*["']([^"']+)["']`)
// Matches the canonical generated gemspec forms:
// s.version = "1.2.3"
// s.version = Gem::Version.new("1.2.3")
// s.version = Gem::Version.new('1.2.3')
gemspecVersionRe = regexp.MustCompile(`(?m)^\s*\w+\.version\s*=\s*(?:Gem::Version\.new\(\s*)?["']([^"']+)["']`)
)
func (s *Scanner) ScanGemspec(path, projectPath string, base model.Record) error {
data, err := s.readBounded(path)
if err != nil {
return err
}
name := firstSubmatch(gemspecNameRe, data)
version := firstSubmatch(gemspecVersionRe, data)
if name == "" || version == "" {
// Prefer the parent dir "<name>-<version>" for `gems/<name>-<ver>/<name>.gemspec`:
// the directory carries both fields, while the filename has only the name.
parent := filepath.Base(filepath.Dir(path))
if i := strings.LastIndexByte(parent, '-'); i > 0 && filepath.Base(filepath.Dir(filepath.Dir(path))) == "gems" {
n2, v2 := parent[:i], parent[i+1:]
if name == "" {
name = n2
}
if version == "" {
version = v2
}
}
}
if name == "" || version == "" {
// Fall back to filename pattern "<name>-<version>.gemspec"
// (this is the canonical specifications/ form).
bn := strings.TrimSuffix(filepath.Base(path), ".gemspec")
if i := strings.LastIndexByte(bn, '-'); i > 0 {
n2, v2 := bn[:i], bn[i+1:]
if name == "" {
name = n2
}
if version == "" {
version = v2
}
}
}
if name == "" || version == "" {
return fmt.Errorf("incomplete gemspec at %s", path)
}
r := base
r.Ecosystem = Ecosystem
r.PackageName = name
r.NormalizedName = strings.ToLower(name)
r.Version = version
r.ProjectPath = projectPath
r.PackageManager = "rubygems"
r.SourceType = "rubygems-gemspec"
r.SourceFile = path
r.Confidence = "medium"
s.Emit(r)
return nil
}
func firstSubmatch(re *regexp.Regexp, data []byte) string {
m := re.FindSubmatch(data)
if len(m) < 2 {
return ""
}
return string(m[1])
}
func (s *Scanner) readBounded(path string) ([]byte, error) {
f, err := os.Open(path)
if err != nil {
return nil, err
}
defer f.Close()
info, err := f.Stat()
if err != nil {
return nil, err
}
if !info.Mode().IsRegular() {
return nil, errors.New("not a regular file")
}
if s.MaxFileSize > 0 && info.Size() > s.MaxFileSize {
if s.Diag != nil {
s.Diag("warn", path, fmt.Sprintf("skipping: size %d exceeds max %d", info.Size(), s.MaxFileSize))
}
return nil, fmt.Errorf("file %s exceeds max size %d", path, s.MaxFileSize)
}
return io.ReadAll(f)
}