github.com/nalekseevs/itns-golangci-lint@v1.0.2/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 "log" 10 "os" 11 "path/filepath" 12 "sync" 13 ) 14 15 const envGolangciLintCache = "GOLANGCI_LINT_CACHE" 16 17 // Default returns the default cache to use. 18 func Default() (*Cache, error) { 19 defaultOnce.Do(initDefaultCache) 20 return defaultCache, defaultDirErr 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 golangci-lint. 32 ` 33 34 // initDefaultCache does the work of finding the default cache 35 // the first time Default is called. 36 func initDefaultCache() { 37 dir := DefaultDir() 38 if err := os.MkdirAll(dir, 0744); err != nil { 39 log.Fatalf("failed to initialize build cache at %s: %s\n", dir, err) 40 } 41 if _, err := os.Stat(filepath.Join(dir, "README")); err != nil { 42 // Best effort. 43 if wErr := os.WriteFile(filepath.Join(dir, "README"), []byte(cacheREADME), 0666); wErr != nil { 44 log.Fatalf("Failed to write README file to cache dir %s: %s", dir, err) 45 } 46 } 47 48 c, err := Open(dir) 49 if err != nil { 50 log.Fatalf("failed to initialize build cache at %s: %s\n", dir, err) 51 } 52 defaultCache = c 53 } 54 55 var ( 56 defaultDirOnce sync.Once 57 defaultDir string 58 defaultDirErr error 59 ) 60 61 // DefaultDir returns the effective GOLANGCI_LINT_CACHE setting. 62 func DefaultDir() string { 63 // Save the result of the first call to DefaultDir for later use in 64 // initDefaultCache. cmd/go/main.go explicitly sets GOCACHE so that 65 // subprocesses will inherit it, but that means initDefaultCache can't 66 // otherwise distinguish between an explicit "off" and a UserCacheDir error. 67 68 defaultDirOnce.Do(func() { 69 defaultDir = os.Getenv(envGolangciLintCache) 70 if filepath.IsAbs(defaultDir) { 71 return 72 } 73 if defaultDir != "" { 74 defaultDirErr = fmt.Errorf("%s is not an absolute path", envGolangciLintCache) 75 return 76 } 77 78 // Compute default location. 79 dir, err := os.UserCacheDir() 80 if err != nil { 81 defaultDirErr = fmt.Errorf("%s is not defined and %w", envGolangciLintCache, err) 82 return 83 } 84 defaultDir = filepath.Join(dir, "golangci-lint") 85 }) 86 87 return defaultDir 88 }