github.com/vanstinator/golangci-lint@v0.0.0-20240223191551-cc572f00d9d1/pkg/fsutils/filecache.go (about) 1 package fsutils 2 3 import ( 4 "fmt" 5 "os" 6 "sync" 7 8 "github.com/vanstinator/golangci-lint/pkg/logutils" 9 ) 10 11 type FileCache struct { 12 files sync.Map 13 } 14 15 func NewFileCache() *FileCache { 16 return &FileCache{} 17 } 18 19 func (fc *FileCache) GetFileBytes(filePath string) ([]byte, error) { 20 cachedBytes, ok := fc.files.Load(filePath) 21 if ok { 22 return cachedBytes.([]byte), nil 23 } 24 25 fileBytes, err := os.ReadFile(filePath) 26 if err != nil { 27 return nil, fmt.Errorf("can't read file %s: %w", filePath, err) 28 } 29 30 fc.files.Store(filePath, fileBytes) 31 return fileBytes, nil 32 } 33 34 func PrettifyBytesCount(n int64) string { 35 const ( 36 Multiplexer = 1024 37 KiB = 1 * Multiplexer 38 MiB = KiB * Multiplexer 39 GiB = MiB * Multiplexer 40 ) 41 42 if n >= GiB { 43 return fmt.Sprintf("%.1fGiB", float64(n)/GiB) 44 } 45 if n >= MiB { 46 return fmt.Sprintf("%.1fMiB", float64(n)/MiB) 47 } 48 if n >= KiB { 49 return fmt.Sprintf("%.1fKiB", float64(n)/KiB) 50 } 51 return fmt.Sprintf("%dB", n) 52 } 53 54 func (fc *FileCache) PrintStats(log logutils.Log) { 55 var size int64 56 var mapLen int 57 fc.files.Range(func(_, fileBytes any) bool { 58 mapLen++ 59 size += int64(len(fileBytes.([]byte))) 60 61 return true 62 }) 63 64 log.Infof("File cache stats: %d entries of total size %s", mapLen, PrettifyBytesCount(size)) 65 }