github.com/goproxy0/go@v0.0.0-20171111080102-49cc0c489d2c/src/cmd/go/internal/cache/default.go (about) 1 // Copyright 2017 The Go Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 package cache 6 7 import ( 8 "cmd/go/internal/base" 9 "io/ioutil" 10 "os" 11 "path/filepath" 12 "runtime" 13 "sync" 14 ) 15 16 // Default returns the default cache to use, or nil if no cache should be used. 17 func Default() *Cache { 18 defaultOnce.Do(initDefaultCache) 19 return defaultCache 20 } 21 22 var ( 23 defaultOnce sync.Once 24 defaultCache *Cache 25 ) 26 27 // cacheREADME is a message stored in a README in the cache directory. 28 // Because the cache lives outside the normal Go trees, we leave the 29 // README as a courtesy to explain where it came from. 30 const cacheREADME = `This directory holds cached build artifacts from the Go build system. 31 Run "go clean -cache" if the directory is getting too large. 32 See golang.org to learn more about Go. 33 ` 34 35 // initDefaultCache does the work of finding the default cache 36 // the first time Default is called. 37 func initDefaultCache() { 38 dir := DefaultDir() 39 if dir == "off" { 40 return 41 } 42 if err := os.MkdirAll(dir, 0777); err != nil { 43 base.Fatalf("initializing cache in $GOCACHE: %s", err) 44 } 45 if _, err := os.Stat(filepath.Join(dir, "README")); err != nil { 46 // Best effort. 47 ioutil.WriteFile(filepath.Join(dir, "README"), []byte(cacheREADME), 0666) 48 } 49 50 c, err := Open(dir) 51 if err != nil { 52 base.Fatalf("initializing cache in $GOCACHE: %s", err) 53 } 54 defaultCache = c 55 } 56 57 // DefaultDir returns the effective GOCACHE setting. 58 // It returns "off" if the cache is disabled. 59 func DefaultDir() string { 60 dir := os.Getenv("GOCACHE") 61 if dir != "" { 62 return dir 63 } 64 65 // Compute default location. 66 // TODO(rsc): This code belongs somewhere else, 67 // like maybe ioutil.CacheDir or os.CacheDir. 68 switch runtime.GOOS { 69 case "windows": 70 dir = os.Getenv("LocalAppData") 71 72 case "darwin": 73 dir = os.Getenv("HOME") 74 if dir == "" { 75 return "off" 76 } 77 dir += "/Library/Caches" 78 79 case "plan9": 80 dir = os.Getenv("home") 81 if dir == "" { 82 return "off" 83 } 84 // Plan 9 has no established per-user cache directory, 85 // but $home/lib/xyz is the usual equivalent of $HOME/.xyz on Unix. 86 dir += "/lib/cache" 87 88 default: // Unix 89 // https://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html 90 dir = os.Getenv("XDG_CACHE_HOME") 91 if dir == "" { 92 dir = os.Getenv("HOME") 93 if dir == "" { 94 return "off" 95 } 96 dir += "/.cache" 97 } 98 } 99 return filepath.Join(dir, "go-build") 100 }