default.go 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  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. package cache
  5. import (
  6. "fmt"
  7. "io/ioutil"
  8. "log"
  9. "os"
  10. "path/filepath"
  11. "sync"
  12. )
  13. // Default returns the default cache to use.
  14. func Default() (*Cache, error) {
  15. defaultOnce.Do(initDefaultCache)
  16. return defaultCache, defaultDirErr
  17. }
  18. var (
  19. defaultOnce sync.Once
  20. defaultCache *Cache
  21. )
  22. // cacheREADME is a message stored in a README in the cache directory.
  23. // Because the cache lives outside the normal Go trees, we leave the
  24. // README as a courtesy to explain where it came from.
  25. const cacheREADME = `This directory holds cached build artifacts from staticcheck.
  26. `
  27. // initDefaultCache does the work of finding the default cache
  28. // the first time Default is called.
  29. func initDefaultCache() {
  30. dir := DefaultDir()
  31. if err := os.MkdirAll(dir, 0777); err != nil {
  32. log.Fatalf("failed to initialize build cache at %s: %s\n", dir, err)
  33. }
  34. if _, err := os.Stat(filepath.Join(dir, "README")); err != nil {
  35. // Best effort.
  36. ioutil.WriteFile(filepath.Join(dir, "README"), []byte(cacheREADME), 0666)
  37. }
  38. c, err := Open(dir)
  39. if err != nil {
  40. log.Fatalf("failed to initialize build cache at %s: %s\n", dir, err)
  41. }
  42. defaultCache = c
  43. }
  44. var (
  45. defaultDirOnce sync.Once
  46. defaultDir string
  47. defaultDirErr error
  48. )
  49. // DefaultDir returns the effective STATICCHECK_CACHE setting.
  50. func DefaultDir() string {
  51. // Save the result of the first call to DefaultDir for later use in
  52. // initDefaultCache. cmd/go/main.go explicitly sets GOCACHE so that
  53. // subprocesses will inherit it, but that means initDefaultCache can't
  54. // otherwise distinguish between an explicit "off" and a UserCacheDir error.
  55. defaultDirOnce.Do(func() {
  56. defaultDir = os.Getenv("STATICCHECK_CACHE")
  57. if filepath.IsAbs(defaultDir) {
  58. return
  59. }
  60. if defaultDir != "" {
  61. defaultDirErr = fmt.Errorf("STATICCHECK_CACHE is not an absolute path")
  62. return
  63. }
  64. // Compute default location.
  65. dir, err := os.UserCacheDir()
  66. if err != nil {
  67. defaultDirErr = fmt.Errorf("STATICCHECK_CACHE is not defined and %v", err)
  68. return
  69. }
  70. defaultDir = filepath.Join(dir, "staticcheck")
  71. })
  72. return defaultDir
  73. }