github.com/hikaru7719/go@v0.0.0-20181025140707-c8b2ac68906a/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 "fmt" 9 "io/ioutil" 10 "os" 11 "path/filepath" 12 "sync" 13 ) 14 15 // Default returns the default cache to use, or nil if no cache should be used. 16 func Default() *Cache { 17 defaultOnce.Do(initDefaultCache) 18 return defaultCache 19 } 20 21 var ( 22 defaultOnce sync.Once 23 defaultCache *Cache 24 ) 25 26 // cacheREADME is a message stored in a README in the cache directory. 27 // Because the cache lives outside the normal Go trees, we leave the 28 // README as a courtesy to explain where it came from. 29 const cacheREADME = `This directory holds cached build artifacts from the Go build system. 30 Run "go clean -cache" if the directory is getting too large. 31 See golang.org to learn more about Go. 32 ` 33 34 // initDefaultCache does the work of finding the default cache 35 // the first time Default is called. 36 func initDefaultCache() { 37 dir, showWarnings := defaultDir() 38 if dir == "off" { 39 return 40 } 41 if err := os.MkdirAll(dir, 0777); err != nil { 42 if showWarnings { 43 fmt.Fprintf(os.Stderr, "go: disabling cache (%s) due to initialization failure: %s\n", dir, err) 44 } 45 return 46 } 47 if _, err := os.Stat(filepath.Join(dir, "README")); err != nil { 48 // Best effort. 49 ioutil.WriteFile(filepath.Join(dir, "README"), []byte(cacheREADME), 0666) 50 } 51 52 c, err := Open(dir) 53 if err != nil { 54 if showWarnings { 55 fmt.Fprintf(os.Stderr, "go: disabling cache (%s) due to initialization failure: %s\n", dir, err) 56 } 57 return 58 } 59 defaultCache = c 60 } 61 62 // DefaultDir returns the effective GOCACHE setting. 63 // It returns "off" if the cache is disabled. 64 func DefaultDir() string { 65 dir, _ := defaultDir() 66 return dir 67 } 68 69 // defaultDir returns the effective GOCACHE setting. 70 // It returns "off" if the cache is disabled. 71 // The second return value reports whether warnings should 72 // be shown if the cache fails to initialize. 73 func defaultDir() (string, bool) { 74 dir := os.Getenv("GOCACHE") 75 if dir != "" { 76 return dir, true 77 } 78 79 // Compute default location. 80 dir, err := os.UserCacheDir() 81 if err != nil { 82 return "off", true 83 } 84 dir = filepath.Join(dir, "go-build") 85 86 // Do this after filepath.Join, so that the path has been cleaned. 87 showWarnings := true 88 switch dir { 89 case "/.cache/go-build": 90 // probably docker run with -u flag 91 // https://golang.org/issue/26280 92 showWarnings = false 93 } 94 return dir, showWarnings 95 }