github.com/zxy12/go_duplicate_112_new@v0.0.0-20200807091221-747231827200/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 "cmd/go/internal/base" 15 ) 16 17 // Default returns the default cache to use, or nil if no cache should be used. 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 // cacheREADME is a message stored in a README in the cache directory. 29 // Because the cache lives outside the normal Go trees, we leave the 30 // README as a courtesy to explain where it came from. 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 See golang.org to learn more about Go. 34 ` 35 36 // initDefaultCache does the work of finding the default cache 37 // the first time Default is called. 38 func initDefaultCache() { 39 dir := DefaultDir() 40 if dir == "off" { 41 if defaultDirErr != nil { 42 base.Fatalf("build cache is required, but could not be located: %v", defaultDirErr) 43 } 44 base.Fatalf("build cache is disabled by GOCACHE=off, but required as of Go 1.12") 45 } 46 if err := os.MkdirAll(dir, 0777); err != nil { 47 base.Fatalf("failed to initialize build cache at %s: %s\n", dir, err) 48 } 49 if _, err := os.Stat(filepath.Join(dir, "README")); err != nil { 50 // Best effort. 51 ioutil.WriteFile(filepath.Join(dir, "README"), []byte(cacheREADME), 0666) 52 } 53 54 c, err := Open(dir) 55 if err != nil { 56 base.Fatalf("failed to initialize build cache at %s: %s\n", dir, err) 57 } 58 defaultCache = c 59 } 60 61 var ( 62 defaultDirOnce sync.Once 63 defaultDir string 64 defaultDirErr error 65 ) 66 67 // DefaultDir returns the effective GOCACHE setting. 68 // It returns "off" if the cache is disabled. 69 func DefaultDir() string { 70 // Save the result of the first call to DefaultDir for later use in 71 // initDefaultCache. cmd/go/main.go explicitly sets GOCACHE so that 72 // subprocesses will inherit it, but that means initDefaultCache can't 73 // otherwise distinguish between an explicit "off" and a UserCacheDir error. 74 75 defaultDirOnce.Do(func() { 76 defaultDir = os.Getenv("GOCACHE") 77 if filepath.IsAbs(defaultDir) || defaultDir == "off" { 78 return 79 } 80 if defaultDir != "" { 81 defaultDir = "off" 82 defaultDirErr = fmt.Errorf("GOCACHE is not an absolute path") 83 return 84 } 85 86 // Compute default location. 87 dir, err := os.UserCacheDir() 88 if err != nil { 89 defaultDir = "off" 90 defaultDirErr = fmt.Errorf("GOCACHE is not defined and %v", err) 91 return 92 } 93 defaultDir = filepath.Join(dir, "go-build") 94 }) 95 96 return defaultDir 97 }