forked from gomods/athens
-
Notifications
You must be signed in to change notification settings - Fork 0
/
parser.go
51 lines (40 loc) · 1004 Bytes
/
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
package parser
import (
"bufio"
"errors"
"io"
"regexp"
)
const (
moduleRegexp = `module "([\w\.@:%_\+-.~#?&]+/.+)"`
)
var (
re = regexp.MustCompile(moduleRegexp)
// ErrNotFound describe an error when can't find module name
ErrNotFound = errors.New("name not found")
)
// GomodParser retrieves module name from parsable source
type GomodParser interface {
ModuleName() (string, error)
}
// Parse parses file passed as a reader and returns module name out of it.
func Parse(reader io.Reader) (string, error) {
scanner := bufio.NewScanner(reader)
for scanner.Scan() {
line := scanner.Text()
if name, found := checkVersion(line, re); found {
return name, nil
}
}
if err := scanner.Err(); err != nil {
return "", err
}
return "", ErrNotFound
}
func checkVersion(line string, expression *regexp.Regexp) (string, bool) {
matches := expression.FindAllStringSubmatch(line, 1)
if len(matches) == 0 || len(matches[0]) < 2 {
return "", false
}
return matches[0][1], true
}