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 func Default() *Cache {
19 defaultOnce.Do(initDefaultCache)
20 return defaultCache
21 }
22
23 var (
24 defaultOnce sync.Once
25 defaultCache *Cache
26 )
27
28
29
30
31 const cacheREADME = `This directory holds cached build artifacts from the Go build system.
32 Run "go clean -cache" if the directory is getting too large.
33 Run "go clean -fuzzcache" to delete the fuzz cache.
34 See golang.org to learn more about Go.
35 `
36
37
38
39 func initDefaultCache() {
40 dir := DefaultDir()
41 if dir == "off" {
42 if defaultDirErr != nil {
43 base.Fatalf("build cache is required, but could not be located: %v", defaultDirErr)
44 }
45 base.Fatalf("build cache is disabled by GOCACHE=off, but required as of Go 1.12")
46 }
47 if err := os.MkdirAll(dir, 0777); err != nil {
48 base.Fatalf("failed to initialize build cache at %s: %s\n", dir, err)
49 }
50 if _, err := os.Stat(filepath.Join(dir, "README")); err != nil {
51
52 os.WriteFile(filepath.Join(dir, "README"), []byte(cacheREADME), 0666)
53 }
54
55 c, err := Open(dir)
56 if err != nil {
57 base.Fatalf("failed to initialize build cache at %s: %s\n", dir, err)
58 }
59 defaultCache = c
60 }
61
62 var (
63 defaultDirOnce sync.Once
64 defaultDir string
65 defaultDirErr error
66 )
67
68
69
70 func DefaultDir() string {
71
72
73
74
75
76 defaultDirOnce.Do(func() {
77 defaultDir = cfg.Getenv("GOCACHE")
78 if filepath.IsAbs(defaultDir) || defaultDir == "off" {
79 return
80 }
81 if defaultDir != "" {
82 defaultDir = "off"
83 defaultDirErr = fmt.Errorf("GOCACHE is not an absolute path")
84 return
85 }
86
87
88 dir, err := os.UserCacheDir()
89 if err != nil {
90 defaultDir = "off"
91 defaultDirErr = fmt.Errorf("GOCACHE is not defined and %v", err)
92 return
93 }
94 defaultDir = filepath.Join(dir, "go-build")
95 })
96
97 return defaultDir
98 }
99
View as plain text