SaveCachedFile saves a downloaded file to the cache directory using SHA256 in the filename.
(srcFile, cacheDir, fileName, sha256 string, chattrFS *ChattrFS)
| 67 | |
| 68 | // SaveCachedFile saves a downloaded file to the cache directory using SHA256 in the filename. |
| 69 | func 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. |
| 103 | func verifySHA256(filePath, expectedHash string) bool { |