internal/deps/gomod.go

545ba0bcdea3b534903bd78c918c0c025a97eda7
gitbay/internal/deps/gomod.go

65 lines · 1825 bytes

2 symbols in this file
 1package deps
 2
 3import "strings"
 4
 5// parseGoMod reads the direct requirements from go.mod. Indirect
 6// requirements are the module graph's business rather than the maintainer's,
 7// and a replaced module does not come from the proxy at all, so both are
 8// skipped.
 9func parseGoMod(read ReadFile) []Dep { return goRequires(read, false) }
10
11// goRequires reads go.mod's requirements, the indirect ones too when asked.
12// Since Go 1.17 go.mod lists every module the build selects, so with them it
13// is the resolved set.
14func goRequires(read ReadFile, withIndirect bool) []Dep {
15	raw, err := read("go.mod")
16	if err != nil {
17		return nil
18	}
19	replaced := map[string]bool{}
20	var reqs [][2]string
21	block := "" // the directive whose ( ... ) block we are inside
22	for _, line := range strings.Split(string(raw), "\n") {
23		line = strings.TrimSpace(line)
24		indirect := false
25		if i := strings.Index(line, "//"); i >= 0 {
26			indirect = strings.Contains(line[i:], "indirect")
27			line = strings.TrimSpace(line[:i])
28		}
29		if line == "" {
30			continue
31		}
32		directive := block
33		if block == "" {
34			d, rest, ok := strings.Cut(line, " ")
35			if !ok || (d != "require" && d != "replace") {
36				continue
37			}
38			if rest = strings.TrimSpace(rest); rest == "(" {
39				block = d
40				continue
41			}
42			directive, line = d, rest
43		} else if line == ")" {
44			block = ""
45			continue
46		}
47		fields := strings.Fields(line)
48		switch {
49		case directive == "require" && (withIndirect || !indirect) && len(fields) >= 2:
50			reqs = append(reqs, [2]string{fields[0], fields[1]})
51		case directive == "replace" && len(fields) >= 1:
52			replaced[fields[0]] = true
53		}
54	}
55	var out []Dep
56	for _, r := range reqs {
57		if replaced[r[0]] {
58			continue
59		}
60		if v := pin(r[1]); v != "" {
61			out = append(out, Dep{Ecosystem: EcoGo, Name: r[0], Current: r[1]})
62		}
63	}
64	return out
65}