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