-
Notifications
You must be signed in to change notification settings - Fork 14
/
patch_gomodule.go
78 lines (61 loc) · 1.67 KB
/
patch_gomodule.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
package codegen
import (
"context"
"errors"
"fmt"
"os"
"path"
"strings"
)
type goModuleFinder struct{}
func newGoModuleFinder() *goModuleFinder {
return &goModuleFinder{}
}
func (s *goModuleFinder) Find(ctx context.Context, rootDir string) (packages map[string]string, ok bool, err error) {
contents, ok, err := s.getGoModFile(rootDir)
if err != nil {
return nil, true, err
}
if !ok {
return nil, false, nil
}
moduleName, err := s.getModuleFromModFile(contents)
if err != nil {
return nil, true, fmt.Errorf("failed to parse go.mod in root of project: %w", err)
}
packages = make(map[string]string, 0)
packages[moduleName] = ""
return packages, true, nil
}
func (g *goModuleFinder) getGoModFile(rootDir string) (contents []string, ok bool, err error) {
goMod := path.Join(rootDir, "go.mod")
if _, err := os.Stat(goMod); err != nil {
if errors.Is(err, os.ErrNotExist) {
return nil, false, nil
}
return nil, true, err
}
modFile, err := os.ReadFile(path.Join(rootDir, "go.mod"))
if err != nil {
return nil, true, err
}
lines := strings.Split(string(modFile), "\n")
if len(lines) == 0 {
return nil, true, errors.New("go mod is empty")
}
return lines, true, nil
}
func (g *goModuleFinder) getModuleFromModFile(contents []string) (moduleName string, err error) {
for _, line := range contents {
modFileLine := strings.TrimSpace(line)
if strings.HasPrefix(modFileLine, "module") {
sections := strings.Split(modFileLine, " ")
if len(sections) < 2 {
return "", fmt.Errorf("invalid module line: %s", modFileLine)
}
moduleName := sections[1]
return moduleName, nil
}
}
return "", errors.New("failed to find a valid go.mod file")
}