1
2
3
4
5 package cache
6
7 import (
8 "fmt"
9 "os"
10 "path/filepath"
11 "sync"
12
13 "cmd/go/internal/base"
14 "cmd/go/internal/cfg"
15 )
16
17
18
19 func Default() Cache {
20 return initDefaultCacheOnce()
21 }
22
23 var initDefaultCacheOnce = sync.OnceValue(initDefaultCache)
24
25
26
27
28 const cacheREADME = `This directory holds cached build artifacts from the Go build system.
29 Run "go clean -cache" if the directory is getting too large.
30 Run "go clean -fuzzcache" to delete the fuzz cache.
31 See golang.org to learn more about Go.
32 `
33
34
35
36 func initDefaultCache() Cache {
37 dir, _, err := DefaultDir()
38 if err != nil {
39 base.Fatalf("build cache is required, but could not be located: %v", err)
40 }
41 if dir == "off" {
42 base.Fatalf("build cache is disabled by GOCACHE=off, but required as of Go 1.12")
43 }
44 if err := os.MkdirAll(dir, 0o777); err != nil {
45 base.Fatalf("failed to initialize build cache at %s: %s\n", dir, err)
46 }
47 if _, err := os.Stat(filepath.Join(dir, "README")); err != nil {
48
49 os.WriteFile(filepath.Join(dir, "README"), []byte(cacheREADME), 0666)
50 }
51
52 diskCache, err := Open(dir)
53 if err != nil {
54 base.Fatalf("failed to initialize build cache at %s: %s\n", dir, err)
55 }
56
57 if cfg.GOCACHEPROG != "" {
58 return startCacheProg(cfg.GOCACHEPROG, diskCache)
59 }
60
61 return diskCache
62 }
63
64 var (
65 defaultDirOnce sync.Once
66 defaultDir string
67 defaultDirChanged bool
68 defaultDirErr error
69 )
70
71
72
73
74 func DefaultDir() (string, bool, error) {
75
76
77
78
79
80 defaultDirOnce.Do(func() {
81
82 dir, err := os.UserCacheDir()
83 if err != nil {
84 defaultDir = "off"
85 defaultDirErr = fmt.Errorf("GOCACHE is not defined and %v", err)
86 } else {
87 defaultDir = filepath.Join(dir, "go-build")
88 }
89
90 newDir := cfg.Getenv("GOCACHE")
91 if newDir != "" {
92 defaultDirErr = nil
93 defaultDirChanged = newDir != defaultDir
94 defaultDir = newDir
95 if filepath.IsAbs(defaultDir) || defaultDir == "off" {
96 return
97 }
98 defaultDir = "off"
99 defaultDirErr = fmt.Errorf("GOCACHE is not an absolute path")
100 return
101 }
102 })
103
104 return defaultDir, defaultDirChanged, defaultDirErr
105 }
106
View as plain text