2019-03-17 14:52:04 +03:00
|
|
|
package fsutils
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
2021-11-02 03:21:26 +08:00
|
|
|
"os"
|
2019-06-29 16:41:15 +03:00
|
|
|
"sync"
|
2019-03-17 14:52:04 +03:00
|
|
|
|
2019-09-27 20:58:49 -04:00
|
|
|
"github.com/golangci/golangci-lint/pkg/logutils"
|
2019-03-17 14:52:04 +03:00
|
|
|
)
|
|
|
|
|
|
|
|
type FileCache struct {
|
2019-06-29 16:41:15 +03:00
|
|
|
files sync.Map
|
2019-03-17 14:52:04 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
func NewFileCache() *FileCache {
|
2019-06-29 16:41:15 +03:00
|
|
|
return &FileCache{}
|
2019-03-17 14:52:04 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
func (fc *FileCache) GetFileBytes(filePath string) ([]byte, error) {
|
2019-06-29 16:41:15 +03:00
|
|
|
cachedBytes, ok := fc.files.Load(filePath)
|
|
|
|
if ok {
|
|
|
|
return cachedBytes.([]byte), nil
|
2019-03-17 14:52:04 +03:00
|
|
|
}
|
|
|
|
|
2021-11-02 03:21:26 +08:00
|
|
|
fileBytes, err := os.ReadFile(filePath)
|
2019-03-17 14:52:04 +03:00
|
|
|
if err != nil {
|
2023-02-22 02:35:43 +02:00
|
|
|
return nil, fmt.Errorf("can't read file %s: %w", filePath, err)
|
2019-03-17 14:52:04 +03:00
|
|
|
}
|
|
|
|
|
2019-06-29 16:41:15 +03:00
|
|
|
fc.files.Store(filePath, fileBytes)
|
2019-03-17 14:52:04 +03:00
|
|
|
return fileBytes, nil
|
|
|
|
}
|
|
|
|
|
2019-10-13 17:40:51 +03:00
|
|
|
func PrettifyBytesCount(n int64) string {
|
2019-03-17 14:52:04 +03:00
|
|
|
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) {
|
2019-10-13 17:40:51 +03:00
|
|
|
var size int64
|
2019-06-29 16:41:15 +03:00
|
|
|
var mapLen int
|
2023-03-28 17:22:55 +03:00
|
|
|
fc.files.Range(func(_, fileBytes any) bool {
|
2019-06-29 16:41:15 +03:00
|
|
|
mapLen++
|
2019-10-13 17:40:51 +03:00
|
|
|
size += int64(len(fileBytes.([]byte)))
|
2019-06-29 16:41:15 +03:00
|
|
|
|
|
|
|
return true
|
|
|
|
})
|
2019-03-17 14:52:04 +03:00
|
|
|
|
2019-10-13 17:40:51 +03:00
|
|
|
log.Infof("File cache stats: %d entries of total size %s", mapLen, PrettifyBytesCount(size))
|
2019-03-17 14:52:04 +03:00
|
|
|
}
|