-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
naive_pkg_parser.go
72 lines (64 loc) · 1.54 KB
/
naive_pkg_parser.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
package cargo
import (
"bufio"
"fmt"
"io"
"strings"
)
type pkgPosition struct {
start int
end int
}
type minPkg struct {
name string
version string
position pkgPosition
}
func (pkg *minPkg) setEndPositionIfEmpty(n int) {
if pkg.position.end == 0 {
pkg.position.end = n
}
}
type naivePkgParser struct {
r io.Reader
}
func (parser *naivePkgParser) parse() map[string]pkgPosition {
var currentPkg minPkg = minPkg{}
var idx = make(map[string]pkgPosition, 0)
scanner := bufio.NewScanner(parser.r)
lineNum := 1
for scanner.Scan() {
line := scanner.Text()
switch {
case strings.HasPrefix(strings.TrimSpace(line), "["):
if currentPkg.name != "" {
pkgId := packageID(currentPkg.name, currentPkg.version)
currentPkg.setEndPositionIfEmpty(lineNum - 1)
idx[pkgId] = currentPkg.position
}
currentPkg = minPkg{}
currentPkg.position.start = lineNum
case strings.HasPrefix(strings.TrimSpace(line), "name ="):
currentPkg.name = propertyValue(line)
case strings.HasPrefix(strings.TrimSpace(line), "version ="):
currentPkg.version = propertyValue(line)
case strings.TrimSpace(line) == "":
currentPkg.setEndPositionIfEmpty(lineNum - 1)
}
lineNum++
}
// add last item
if currentPkg.name != "" {
pkgId := fmt.Sprintf("%s@%s", currentPkg.name, currentPkg.version)
currentPkg.setEndPositionIfEmpty(lineNum - 1)
idx[pkgId] = currentPkg.position
}
return idx
}
func propertyValue(line string) string {
parts := strings.Split(line, "=")
if len(parts) == 2 {
return strings.Trim(parts[1], ` "`)
}
return ""
}