-
Notifications
You must be signed in to change notification settings - Fork 7
/
modfile.go
75 lines (62 loc) · 1.54 KB
/
modfile.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
package main
import (
"path/filepath"
"regexp"
"strings"
"golang.org/x/mod/modfile"
)
type Module struct {
Path string
Version string
Deprecated string
GoVersion string
Toolchain string
Documentation *Doc
}
func ModInfo(projectRoot string) (*Module, error) {
filePath := filepath.Join(projectRoot, "go.mod")
bs, err := readFile(filePath)
if err != nil {
return nil, err
}
f, err := modfile.ParseLax(filePath, bs, nil)
if err != nil {
return nil, err
}
mod := f.Module.Mod
Path := mod.Path
Version := mod.Version
Deprecated := f.Module.Deprecated
GoVersion := ""
if f.Go != nil {
GoVersion = f.Go.Version
}
// BUG(jmf): Currently this is not set by ParseLax, see https://github.com/golang/go/issues/67132
Toolchain := ""
if f.Toolchain != nil {
Toolchain = f.Toolchain.Name
}
comments := f.Module.Syntax.Comments.Before
text := stripDeprecation(flattenModComments(comments))
return &Module{
Path: Path,
Version: Version,
Deprecated: Deprecated,
GoVersion: GoVersion,
Toolchain: Toolchain,
Documentation: NewDoc(text),
}, nil
}
func flattenModComments(lines []modfile.Comment) string {
var acc []string
for _, line := range lines {
text := line.Token[2:]
acc = append(acc, text)
}
return strings.Join(acc, "\n")
}
// adapted from deprecatedRE in modfile's rule.go
var deprecatedRE = regexp.MustCompile(`(?ms)((^[ \t]*|\n\n)Deprecated: *(.*?)($|\n\n))`)
func stripDeprecation(text string) string {
return deprecatedRE.ReplaceAllString(text, "\n")
}