-
Notifications
You must be signed in to change notification settings - Fork 0
/
db.go
88 lines (76 loc) · 1.32 KB
/
db.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
package main
import (
"encoding/json"
"errors"
"io"
"io/fs"
"os"
"time"
)
type DBKey struct {
BuildID int `json:"build_id"`
Email string `json:"email"`
}
type DBEntry struct {
DBKey
Time time.Time `json:"time"`
}
type DB struct {
fileName string
entries map[DBKey]time.Time
}
func OpenDB(fileName string) (*DB, error) {
db := DB{
fileName: fileName,
entries: make(map[DBKey]time.Time),
}
file, err := os.Open(fileName)
if err != nil {
if errors.Is(err, fs.ErrNotExist) {
return &db, nil
}
return nil, err
}
defer file.Close()
dec := json.NewDecoder(file)
lnum := 0
for {
lnum++
var e DBEntry
err := dec.Decode(&e)
if errors.Is(err, io.EOF) {
break
}
if err != nil {
return nil, err
}
db.entries[e.DBKey] = e.Time
}
return &db, nil
}
func (db *DB) Close() error {
file, err := os.Create(db.fileName)
if err != nil {
return err
}
defer file.Close()
enc := json.NewEncoder(file)
for key, time := range db.entries {
e := DBEntry{
DBKey: key,
Time: time,
}
if err := enc.Encode(e); err != nil {
return err
}
}
return nil
}
func (db *DB) Add(buildID int, email string) {
key := DBKey{buildID, email}
db.entries[key] = time.Now().UTC()
}
func (db *DB) Has(buildID int, email string) bool {
_, ok := db.entries[DBKey{buildID, email}]
return ok
}