M4: Persistenz - JSON-Dateispeicher mit Load/Save, Konvertierung zu/from Logik
This commit is contained in:
@@ -0,0 +1,89 @@
|
||||
// Package persistenz provides file-based persistence for the scoreboard state.
|
||||
package persistenz
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
|
||||
"git.jlserver.de/goSportpunktetafel/internal/logik"
|
||||
)
|
||||
|
||||
// State represents the persisted scoreboard state.
|
||||
type State struct {
|
||||
CurrentRound int `json:"current_round"`
|
||||
Rounds []logik.Round `json:"rounds"`
|
||||
RedScore int `json:"red_score"`
|
||||
GreenScore int `json:"green_score"`
|
||||
}
|
||||
|
||||
// Manager handles loading and saving of scoreboard state.
|
||||
type Manager struct {
|
||||
stateFile string
|
||||
}
|
||||
|
||||
// NewManager creates a new state manager.
|
||||
func NewManager(dataDir string) (*Manager, error) {
|
||||
// Ensure data directory exists
|
||||
if err := os.MkdirAll(dataDir, 0755); err != nil {
|
||||
return nil, fmt.Errorf("failed to create data directory %s: %w", dataDir, err)
|
||||
}
|
||||
|
||||
return &Manager{
|
||||
stateFile: filepath.Join(dataDir, "state.json"),
|
||||
}, nil
|
||||
}
|
||||
|
||||
// Load loads the scoreboard state from disk.
|
||||
// Returns nil if no state file exists.
|
||||
func (m *Manager) Load() (*State, error) {
|
||||
data, err := os.ReadFile(m.stateFile)
|
||||
if err != nil {
|
||||
if os.IsNotExist(err) {
|
||||
return nil, nil // No state file yet
|
||||
}
|
||||
return nil, fmt.Errorf("failed to read state file: %w", err)
|
||||
}
|
||||
|
||||
var state State
|
||||
if err := json.Unmarshal(data, &state); err != nil {
|
||||
return nil, fmt.Errorf("failed to parse state file: %w", err)
|
||||
}
|
||||
|
||||
return &state, nil
|
||||
}
|
||||
|
||||
// Save saves the current scoreboard state to disk.
|
||||
func (m *Manager) Save(state *State) error {
|
||||
data, err := json.MarshalIndent(state, "", " ")
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to marshal state: %w", err)
|
||||
}
|
||||
|
||||
if err := os.WriteFile(m.stateFile, data, 0644); err != nil {
|
||||
return fmt.Errorf("failed to write state file: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// StateToLogik converts a persisted State to a logik.Scoreboard.
|
||||
func StateToLogik(state *State) *logik.Scoreboard {
|
||||
return &logik.Scoreboard{
|
||||
CurrentRound: state.CurrentRound,
|
||||
Rounds: state.Rounds,
|
||||
RedScore: state.RedScore,
|
||||
GreenScore: state.GreenScore,
|
||||
}
|
||||
}
|
||||
|
||||
// LogikToState converts a logik.Scoreboard to a persisted State.
|
||||
func LogikToState(sb *logik.Scoreboard) *State {
|
||||
return &State{
|
||||
CurrentRound: sb.CurrentRound,
|
||||
Rounds: sb.Rounds,
|
||||
RedScore: sb.RedScore,
|
||||
GreenScore: sb.GreenScore,
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user