-
Notifications
You must be signed in to change notification settings - Fork 0
/
regions.go
88 lines (72 loc) · 1.67 KB
/
regions.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 aptdata
import (
"encoding/csv"
"fmt"
"io"
"os"
"github.com/coreos/bbolt"
"github.com/pkg/errors"
"github.com/vmihailenco/msgpack"
)
//Region maps a region code to region name and local code
type Region struct {
Code string
LocalCode string
Name string
Country string
}
//loadRegions processes regions.csv and loads a Region struct into
//the Regions bucket in the DB for every record
func loadRegions(db *bolt.DB, dataDir string) error {
regions, err := os.Open(fmt.Sprintf("%s/%s", dataDir, "regions.csv"))
if err != nil {
return err
}
defer regions.Close()
r := csv.NewReader(regions)
_, err = r.Read() // skip header
err = db.Update(func(tx *bolt.Tx) error {
_, err = tx.CreateBucketIfNotExists([]byte("Regions"))
if err != nil {
return err
}
b := tx.Bucket([]byte("Regions"))
for {
record, err := r.Read()
if err == io.EOF {
break
}
if err != nil {
return errors.Wrap(err, "region read")
}
region := Region{record[1],
record[2],
record[3],
record[5]}
m, err := msgpack.Marshal(®ion)
if err != nil {
return errors.Wrap(err, "region marshal")
}
err = b.Put([]byte(record[1]), m)
if err != nil {
return errors.Wrap(err, "database put")
}
}
return nil
})
return err
}
//GetRegion returns a Region struct representing the given code
func (a *AptDB) GetRegion(ident string) (*Region, error) {
var region Region
err := a.boltDB.View(func(tx *bolt.Tx) error {
b := tx.Bucket([]byte("Regions"))
v := b.Get([]byte(ident))
err := msgpack.Unmarshal(v, ®ion)
return err
})
if err != nil {
return ®ion, errors.Wrap(err, "get region")
}
return ®ion, nil
}