Files
spore-registry/internal/storage/file.go
2025-10-22 21:14:07 +02:00

75 lines
2.2 KiB
Go

package storage
import (
"fmt"
"io"
"os"
"path/filepath"
)
// FileStorage handles file system operations for firmware binaries
type FileStorage struct {
registryPath string
}
// NewFileStorage creates a new file storage instance
func NewFileStorage(registryPath string) *FileStorage {
return &FileStorage{registryPath: registryPath}
}
// StoreFirmwareBinary stores a firmware binary in the hierarchical file structure
func (fs *FileStorage) StoreFirmwareBinary(name, version string, data io.Reader) (string, int64, error) {
// Create directory path: registry/<name>/<version>/
dirPath := filepath.Join(fs.registryPath, name, version)
if err := os.MkdirAll(dirPath, 0755); err != nil {
return "", 0, fmt.Errorf("failed to create firmware directory: %w", err)
}
// Create firmware file path
filePath := filepath.Join(dirPath, "firmware.bin")
// Create the file
file, err := os.Create(filePath)
if err != nil {
return "", 0, fmt.Errorf("failed to create firmware file: %w", err)
}
defer file.Close()
// Copy data to file and calculate size
size, err := io.Copy(file, data)
if err != nil {
return "", 0, fmt.Errorf("failed to write firmware data: %w", err)
}
return filePath, size, nil
}
// GetFirmwareBinaryPath returns the file path for a firmware binary
func (fs *FileStorage) GetFirmwareBinaryPath(name, version string) string {
return filepath.Join(fs.registryPath, name, version, "firmware.bin")
}
// FirmwareExists checks if a firmware binary exists
func (fs *FileStorage) FirmwareExists(name, version string) bool {
filePath := fs.GetFirmwareBinaryPath(name, version)
_, err := os.Stat(filePath)
return !os.IsNotExist(err)
}
// DeleteFirmwareBinary deletes a firmware binary and its directory
func (fs *FileStorage) DeleteFirmwareBinary(name, version string) error {
// Get directory path: registry/<name>/<version>/
dirPath := filepath.Join(fs.registryPath, name, version)
// Remove the entire version directory
if err := os.RemoveAll(dirPath); err != nil {
return fmt.Errorf("failed to delete firmware directory: %w", err)
}
// Try to remove the name directory if it's empty
nameDir := filepath.Join(fs.registryPath, name)
os.Remove(nameDir) // Ignore error, directory might not be empty
return nil
}