forked from jessevdk/bugzini
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cache.go
115 lines (89 loc) · 2.01 KB
/
cache.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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
package main
import (
"bugzilla"
"encoding/binary"
"encoding/gob"
"fmt"
"io"
"os"
)
const CacheHeader = "bugzini"
type CacheItem struct {
Products []bugzilla.Product
ProductMap map[int]bugzilla.Product
Bugs map[int][]*bugzilla.Bug
bugsMap map[int]*bugzilla.Bug
}
type Cache struct {
Hosts map[string]*CacheItem
c *CacheItem
}
var cache = Cache{
Hosts: make(map[string]*CacheItem),
}
func newCacheItem() *CacheItem {
return &CacheItem{
Bugs: make(map[int][]*bugzilla.Bug),
ProductMap: make(map[int]bugzilla.Product),
bugsMap: make(map[int]*bugzilla.Bug),
}
}
func (c *Cache) readHeader(r io.Reader) (uint32, error) {
bs := make([]byte, len(CacheHeader))
if _, err := r.Read(bs); err != nil {
return 0, err
}
if string(bs) != CacheHeader {
return 0, fmt.Errorf("Invalid cache header")
}
var version uint32
if err := binary.Read(r, binary.LittleEndian, &version); err != nil {
return 0, err
}
return version, nil
}
func (c *Cache) writeHeader(w io.Writer) error {
if _, err := w.Write([]byte(CacheHeader)); err != nil {
return err
}
var version uint32
version = BugziniVersion
if err := binary.Write(w, binary.LittleEndian, version); err != nil {
return err
}
return nil
}
func (c *Cache) Load() {
if f, err := os.Open(".cache"); err == nil {
defer f.Close()
version, err := c.readHeader(f)
if err == nil && version == BugziniVersion {
dec := gob.NewDecoder(f)
if err := dec.Decode(c); err != nil {
fmt.Fprintf(os.Stderr, "Failed to load cache: %s\n", err.Error())
}
for _, h := range c.Hosts {
h.bugsMap = make(map[int]*bugzilla.Bug)
for _, v := range h.Bugs {
for _, bug := range v {
h.bugsMap[bug.Id] = bug
}
}
}
}
}
if cur, ok := c.Hosts[options.Bugzilla.Host]; ok {
c.c = cur
} else {
c.c = newCacheItem()
c.Hosts[options.Bugzilla.Host] = c.c
}
}
func (c *Cache) Save() {
if f, err := os.Create(".cache"); err == nil {
defer f.Close()
c.writeHeader(f)
enc := gob.NewEncoder(f)
enc.Encode(c)
}
}