1package persistence
2
3import (
4 "context"
5 "fmt"
6 "os"
7 "path/filepath"
8)
9
10// FileRepository implements the InstallationRepository port using filesystem storage
11type FileRepository struct {
12 basePath string
13}
14
15// NewFileRepository creates a new file-based repository
16// basePath is the directory where installation state files will be stored
17func NewFileRepository(basePath string) (*FileRepository, error) {
18 // Ensure base path exists
19 if err := os.MkdirAll(basePath, 0755); err != nil {
20 return nil, fmt.Errorf("failed to create repository base path: %w", err)
21 }
22
23 return &FileRepository{
24 basePath: basePath,
25 }, nil
26}
27
28// Save persists the installation state to a file
29func (fr *FileRepository) Save(ctx context.Context, installationID string, state string) error {
30 select {
31 case <-ctx.Done():
32 return ctx.Err()
33 default:
34 }
35
36 filePath := filepath.Join(fr.basePath, installationID+".state")
37
38 // Write state to file
39 if err := os.WriteFile(filePath, []byte(state), 0644); err != nil {
40 return fmt.Errorf("failed to save installation state: %w", err)
41 }
42
43 return nil
44}
45
46// Load retrieves the installation state from a file
47func (fr *FileRepository) Load(ctx context.Context, installationID string) (string, error) {
48 select {
49 case <-ctx.Done():
50 return "", ctx.Err()
51 default:
52 }
53
54 filePath := filepath.Join(fr.basePath, installationID+".state")
55
56 data, err := os.ReadFile(filePath)
57 if err != nil {
58 if os.IsNotExist(err) {
59 return "", fmt.Errorf("installation state not found: %w", err)
60 }
61 return "", fmt.Errorf("failed to load installation state: %w", err)
62 }
63
64 return string(data), nil
65}
66
67// Exists checks if an installation state exists
68func (fr *FileRepository) Exists(ctx context.Context, installationID string) (bool, error) {
69 select {
70 case <-ctx.Done():
71 return false, ctx.Err()
72 default:
73 }
74
75 filePath := filepath.Join(fr.basePath, installationID+".state")
76
77 _, err := os.Stat(filePath)
78 if err == nil {
79 return true, nil
80 }
81 if os.IsNotExist(err) {
82 return false, nil
83 }
84 return false, fmt.Errorf("failed to check installation existence: %w", err)
85}