Skip to content

Commit c5b0f95

Browse files
andreykuchinjirfag
authored andcommitted
fix cuncurrent [read/]write panic
1 parent 360a58d commit c5b0f95

File tree

1 file changed

+15
-12
lines changed

1 file changed

+15
-12
lines changed

pkg/fsutils/filecache.go

Lines changed: 15 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -3,34 +3,33 @@ package fsutils
33
import (
44
"fmt"
55
"io/ioutil"
6+
"sync"
67

78
"github.com/golangci/golangci-lint/pkg/logutils"
89

910
"github.com/pkg/errors"
1011
)
1112

1213
type FileCache struct {
13-
files map[string][]byte
14+
files sync.Map
1415
}
1516

1617
func NewFileCache() *FileCache {
17-
return &FileCache{
18-
files: map[string][]byte{},
19-
}
18+
return &FileCache{}
2019
}
2120

2221
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
2625
}
2726

2827
fileBytes, err := ioutil.ReadFile(filePath)
2928
if err != nil {
3029
return nil, errors.Wrapf(err, "can't read file %s", filePath)
3130
}
3231

33-
fc.files[filePath] = fileBytes
32+
fc.files.Store(filePath, fileBytes)
3433
return fileBytes, nil
3534
}
3635

@@ -56,9 +55,13 @@ func prettifyBytesCount(n int) string {
5655

5756
func (fc *FileCache) PrintStats(log logutils.Log) {
5857
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+
})
6265

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))
6467
}

0 commit comments

Comments
 (0)