diff --git a/pkg/fsutils/filecache.go b/pkg/fsutils/filecache.go index 6c97bddacfea..8e4d8c32618a 100644 --- a/pkg/fsutils/filecache.go +++ b/pkg/fsutils/filecache.go @@ -3,6 +3,7 @@ package fsutils import ( "fmt" "io/ioutil" + "sync" "github.com/golangci/golangci-lint/pkg/logutils" @@ -10,19 +11,17 @@ import ( ) type FileCache struct { - files map[string][]byte + files sync.Map } func NewFileCache() *FileCache { - return &FileCache{ - files: map[string][]byte{}, - } + return &FileCache{} } func (fc *FileCache) GetFileBytes(filePath string) ([]byte, error) { - cachedBytes := fc.files[filePath] - if cachedBytes != nil { - return cachedBytes, nil + cachedBytes, ok := fc.files.Load(filePath) + if ok { + return cachedBytes.([]byte), nil } fileBytes, err := ioutil.ReadFile(filePath) @@ -30,7 +29,7 @@ func (fc *FileCache) GetFileBytes(filePath string) ([]byte, error) { return nil, errors.Wrapf(err, "can't read file %s", filePath) } - fc.files[filePath] = fileBytes + fc.files.Store(filePath, fileBytes) return fileBytes, nil } @@ -56,9 +55,13 @@ func prettifyBytesCount(n int) string { func (fc *FileCache) PrintStats(log logutils.Log) { var size int - for _, fileBytes := range fc.files { - size += len(fileBytes) - } + var mapLen int + fc.files.Range(func(_, fileBytes interface{}) bool { + mapLen++ + size += len(fileBytes.([]byte)) + + return true + }) - log.Infof("File cache stats: %d entries of total size %s", len(fc.files), prettifyBytesCount(size)) + log.Infof("File cache stats: %d entries of total size %s", mapLen, prettifyBytesCount(size)) } diff --git a/pkg/fsutils/linecache.go b/pkg/fsutils/linecache.go index a651a504964e..10f31422a912 100644 --- a/pkg/fsutils/linecache.go +++ b/pkg/fsutils/linecache.go @@ -3,6 +3,7 @@ package fsutils import ( "bytes" "fmt" + "sync" "github.com/pkg/errors" ) @@ -10,13 +11,12 @@ import ( type fileLinesCache [][]byte type LineCache struct { - files map[string]fileLinesCache + files sync.Map fileCache *FileCache } func NewLineCache(fc *FileCache) *LineCache { return &LineCache{ - files: map[string]fileLinesCache{}, fileCache: fc, } } @@ -53,9 +53,9 @@ func (lc *LineCache) getRawLine(filePath string, index0 int) ([]byte, error) { } func (lc *LineCache) getFileCache(filePath string) (fileLinesCache, error) { - fc := lc.files[filePath] - if fc != nil { - return fc, nil + loadedFc, ok := lc.files.Load(filePath) + if ok { + return loadedFc.(fileLinesCache), nil } fileBytes, err := lc.fileCache.GetFileBytes(filePath) @@ -63,7 +63,7 @@ func (lc *LineCache) getFileCache(filePath string) (fileLinesCache, error) { return nil, errors.Wrapf(err, "can't get file %s bytes from cache", filePath) } - fc = bytes.Split(fileBytes, []byte("\n")) - lc.files[filePath] = fc + fc := bytes.Split(fileBytes, []byte("\n")) + lc.files.Store(filePath, fileLinesCache(fc)) return fc, nil }