Debian Codegraph @

go/loader/hash.go

raw
1 package loader
2
3 import (
4 "fmt"
5 "runtime"
6 "sort"
7 "strings"
8
9 "honnef.co/go/tools/go/buildid"
10 "honnef.co/go/tools/lintcmd/cache"
11 )
12
13 // computeHash computes a package's hash. The hash is based on all Go
14 // files that make up the package, as well as the hashes of imported
15 // packages.
16 func computeHash(c *cache.Cache, pkg *PackageSpec) (cache.ActionID, error) {
17 key := c.NewHash("package " + pkg.PkgPath)
18 fmt.Fprintf(key, "goos %s goarch %s\n", runtime.GOOS, runtime.GOARCH)
19 fmt.Fprintf(key, "import %q\n", pkg.PkgPath)
20
21 // Compute the hashes of all files making up the package. As an
22 // optimization, we use the build ID that Go already computed for us,
23 // because it is virtually identical to hashing all CompiledGoFiles. It is
24 // also sensitive to the Go version declared in go.mod.
25 success := false
26 if pkg.ExportFile != "" {
27 id, err := getBuildid(pkg.ExportFile)
28 if err == nil {
29 if idx := strings.IndexRune(id, '/'); idx > -1 {
30 fmt.Fprintf(key, "files %s\n", id[:idx])
31 success = true
32 }
33 }
34 }
35 if !success {
36 for _, f := range pkg.CompiledGoFiles {
37 h, err := cache.FileHash(f)
38 if err != nil {
39 return cache.ActionID{}, err
40 }
41 fmt.Fprintf(key, "file %s %x\n", f, h)
42 }
43 if pkg.Module != nil && pkg.Module.GoMod != "" {
44 // The go.mod file specifies the language version, which affects how
45 // packages are analyzed.
46 h, err := cache.FileHash(pkg.Module.GoMod)
47 if err != nil {
48 // TODO(dh): this doesn't work for tests because the go.mod file doesn't
49 // exist on disk and is instead provided via an overlay. However, we're
50 // unlikely to get here in the first place, as reading the build ID from
51 // the export file is likely to succeed.
52 return cache.ActionID{}, fmt.Errorf("couldn't hash go.mod: %w", err)
53 } else {
54 fmt.Fprintf(key, "file %s %x\n", pkg.Module.GoMod, h)
55 }
56 }
57 }
58
59 imps := make([]*PackageSpec, 0, len(pkg.Imports))
60 for _, v := range pkg.Imports {
61 imps = append(imps, v)
62 }
63 sort.Slice(imps, func(i, j int) bool {
64 return imps[i].PkgPath < imps[j].PkgPath
65 })
66
67 for _, dep := range imps {
68 if dep.ExportFile == "" {
69 fmt.Fprintf(key, "import %s \n", dep.PkgPath)
70 } else {
71 id, err := getBuildid(dep.ExportFile)
72 if err == nil {
73 fmt.Fprintf(key, "import %s %s\n", dep.PkgPath, id)
74 } else {
75 fh, err := cache.FileHash(dep.ExportFile)
76 if err != nil {
77 return cache.ActionID{}, err
78 }
79 fmt.Fprintf(key, "import %s %x\n", dep.PkgPath, fh)
80 }
81 }
82 }
83 return key.Sum(), nil
84 }
85
86 var buildidCache = map[string]string{}
87
88 func getBuildid(f string) (string, error) {
89 if h, ok := buildidCache[f]; ok {
90 return h, nil
91 }
92 h, err := buildid.ReadFile(f)
93 if err != nil {
94 return "", err
95 }
96 buildidCache[f] = h
97 return h, nil
98 }