MCPcopy Create free account
hub / github.com/celer-pkg/celer / SaveCachedFile

Function SaveCachedFile

pkgs/fileio/cache_file.go:69–100  ·  view source on GitHub ↗

SaveCachedFile saves a downloaded file to the cache directory using SHA256 in the filename.

(srcFile, cacheDir, fileName, sha256 string, chattrFS *ChattrFS)

Source from the content-addressed store, hash-verified

67
68// SaveCachedFile saves a downloaded file to the cache directory using SHA256 in the filename.
69func SaveCachedFile(srcFile, cacheDir, fileName, sha256 string, chattrFS *ChattrFS) (string, error) {
70 if sha256 == "" {
71 panic(fmt.Sprintf("no sha-256 provided when caching file to pkgcache for %s", fileName))
72 }
73
74 if !PathExists(cacheDir) {
75 if err := chattrFS.MkdirAll(cacheDir, CacheDirPerm); err != nil {
76 return "", fmt.Errorf("failed to create cache dir -> %w", err)
77 }
78 }
79
80 cachedFileName := fmt.Sprintf("%s-%s%s", Base(fileName), sha256, Ext(fileName))
81 cachedFilePath := filepath.Join(cacheDir, cachedFileName)
82
83 // If cache file exists and SHA256 matches, return it directly.
84 if PathExists(cachedFilePath) {
85 computedHash, err := ComputeSHA256(cachedFilePath)
86 if err != nil {
87 return "", fmt.Errorf("failed to computer hash for cached file: %s -> %w", cachedFilePath, err)
88 }
89 if computedHash == sha256 {
90 return cachedFilePath, nil
91 }
92 }
93
94 // Copy file to cache (overwrite in-place if it exists, compatible with chattr +a).
95 if err := chattrFS.CopyFile(srcFile, cachedFilePath); err != nil {
96 return "", fmt.Errorf("failed to copy file to cache: %w", err)
97 }
98
99 return cachedFilePath, nil
100}
101
102// verifySHA256 verifies if a file's SHA256 matches the expected hash.
103func verifySHA256(filePath, expectedHash string) bool {

Callers 2

handleRemoteURLMethod · 0.85

Calls 7

PathExistsFunction · 0.85
BaseFunction · 0.85
ExtFunction · 0.85
ComputeSHA256Function · 0.85
SprintfMethod · 0.80
MkdirAllMethod · 0.80
CopyFileMethod · 0.80

Tested by 1