github.com/elek/golangci-lint@v1.42.2-0.20211208090441-c05b7fcb3a9a/pkg/fsutils/filecache.go (about)

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