libgo: update to Go1.10rc1
[official-gcc.git] / libgo / go / cmd / go / internal / cache / default.go
blob8285f787d4c9cae46b178f6ecee94ae538fdcfbe
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.
5 package cache
7 import (
8 "cmd/go/internal/base"
9 "io/ioutil"
10 "os"
11 "path/filepath"
12 "runtime"
13 "sync"
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
22 var (
23 defaultOnce sync.Once
24 defaultCache *Cache
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.
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
42 if err := os.MkdirAll(dir, 0777); err != nil {
43 base.Fatalf("initializing cache in $GOCACHE: %s", err)
45 if _, err := os.Stat(filepath.Join(dir, "README")); err != nil {
46 // Best effort.
47 ioutil.WriteFile(filepath.Join(dir, "README"), []byte(cacheREADME), 0666)
50 c, err := Open(dir)
51 if err != nil {
52 base.Fatalf("initializing cache in $GOCACHE: %s", err)
54 defaultCache = c
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
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 if dir == "" {
72 // Fall back to %AppData%, the old name of
73 // %LocalAppData% on Windows XP.
74 dir = os.Getenv("AppData")
76 if dir == "" {
77 return "off"
80 case "darwin":
81 dir = os.Getenv("HOME")
82 if dir == "" {
83 return "off"
85 dir += "/Library/Caches"
87 case "plan9":
88 dir = os.Getenv("home")
89 if dir == "" {
90 return "off"
92 // Plan 9 has no established per-user cache directory,
93 // but $home/lib/xyz is the usual equivalent of $HOME/.xyz on Unix.
94 dir += "/lib/cache"
96 default: // Unix
97 // https://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html
98 dir = os.Getenv("XDG_CACHE_HOME")
99 if dir == "" {
100 dir = os.Getenv("HOME")
101 if dir == "" {
102 return "off"
104 dir += "/.cache"
107 return filepath.Join(dir, "go-build")