-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfile_system_store.go
96 lines (75 loc) · 1.86 KB
/
file_system_store.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
package poker
import (
"encoding/json"
"fmt"
"io"
"os"
"sort"
)
func FileSystemPlayerStoreFromFile(path string) (*FileSystemPlayerStore, func(), error) {
db, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE, 0666)
if err != nil {
return nil, nil, fmt.Errorf("problem opening %s %v", path, err)
}
closeFunc := func() {
db.Close()
}
store, err := NewFileSystemPlayerStore(db)
if err != nil {
return nil, nil, fmt.Errorf("problem creating file system player store, %v", err)
}
return store, closeFunc, nil
}
func NewFileSystemPlayerStore(file *os.File) (*FileSystemPlayerStore, error) {
file.Seek(0, 0)
info, err := file.Stat()
if err != nil {
return nil, fmt.Errorf("problem getting file info from file %s, %v", file.Name(), err)
}
if info.Size() == 0 {
file.Write([]byte("[]"))
file.Seek(0, 0)
}
league, err := NewLeague(file)
if err != nil {
return nil, fmt.Errorf("problem loading player store from file %s, %v", file.Name(), err)
}
return &FileSystemPlayerStore{
database: json.NewEncoder(&Tape{file}),
league: league,
}, nil
}
type FileSystemPlayerStore struct {
database *json.Encoder
league League
}
func (f *FileSystemPlayerStore) GetPlayerScore(name string) int {
p := f.league.find(name)
if p != nil {
return p.Wins
}
return 0
}
func (f *FileSystemPlayerStore) RecordWin(name string) {
player := f.league.find(name)
if player != nil {
player.Wins++
} else {
f.league = append(f.league, Player{name, 1})
}
f.database.Encode(f.league)
}
func (f *FileSystemPlayerStore) GetLeague() League {
sort.Slice(f.league, func(i, j int) bool {
return f.league[i].Wins > f.league[j].Wins
})
return f.league
}
func NewLeague(rdr io.Reader) ([]Player, error) {
var league []Player
err := json.NewDecoder(rdr).Decode(&league)
if err != nil {
err = fmt.Errorf("problem parsing league, %v", err)
}
return league, err
}