@@ -3,34 +3,33 @@ package fsutils
3
3
import (
4
4
"fmt"
5
5
"io/ioutil"
6
+ "sync"
6
7
7
8
"github.com/golangci/golangci-lint/pkg/logutils"
8
9
9
10
"github.com/pkg/errors"
10
11
)
11
12
12
13
type FileCache struct {
13
- files map [ string ][] byte
14
+ files sync. Map
14
15
}
15
16
16
17
func NewFileCache () * FileCache {
17
- return & FileCache {
18
- files : map [string ][]byte {},
19
- }
18
+ return & FileCache {}
20
19
}
21
20
22
21
func (fc * FileCache ) GetFileBytes (filePath string ) ([]byte , error ) {
23
- cachedBytes := fc .files [ filePath ]
24
- if cachedBytes != nil {
25
- return cachedBytes , nil
22
+ cachedBytes , ok := fc .files . Load ( filePath )
23
+ if ok {
24
+ return cachedBytes .([] byte ) , nil
26
25
}
27
26
28
27
fileBytes , err := ioutil .ReadFile (filePath )
29
28
if err != nil {
30
29
return nil , errors .Wrapf (err , "can't read file %s" , filePath )
31
30
}
32
31
33
- fc .files [ filePath ] = fileBytes
32
+ fc .files . Store ( filePath , fileBytes )
34
33
return fileBytes , nil
35
34
}
36
35
@@ -56,9 +55,13 @@ func prettifyBytesCount(n int) string {
56
55
57
56
func (fc * FileCache ) PrintStats (log logutils.Log ) {
58
57
var size int
59
- for _ , fileBytes := range fc .files {
60
- size += len (fileBytes )
61
- }
58
+ var mapLen int
59
+ fc .files .Range (func (_ , fileBytes interface {}) bool {
60
+ mapLen ++
61
+ size += len (fileBytes .([]byte ))
62
+
63
+ return true
64
+ })
62
65
63
- log .Infof ("File cache stats: %d entries of total size %s" , len ( fc . files ) , prettifyBytesCount (size ))
66
+ log .Infof ("File cache stats: %d entries of total size %s" , mapLen , prettifyBytesCount (size ))
64
67
}
0 commit comments