-
Notifications
You must be signed in to change notification settings - Fork 0
/
source_data.go
123 lines (98 loc) · 2.09 KB
/
source_data.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
116
117
118
119
120
121
122
123
package ginsa
import (
"archive/zip"
"encoding/json"
"io"
"io/ioutil"
"net/http"
"os"
"path/filepath"
"strings"
)
const (
tagsURL = "https://api.github.com/repos/zengin-code/source-data/git/refs/tags"
archivePrefix = "https://github.com/zengin-code/source-data/archive/"
)
type SourceData struct {
Tag string
Banks map[string]*Bank
Branches map[string]map[string]*Branch
}
func FetchAllSourceData() ([]*SourceData, error) {
resp, err := http.Get(tagsURL)
if err != nil {
return nil, err
}
refs := []Ref{}
decoder := json.NewDecoder(resp.Body)
err = decoder.Decode(&refs)
resp.Body.Close()
if err != nil {
return nil, err
}
sources := make([]*SourceData, len(refs))
for i, ref := range refs {
sources[i] = &SourceData{
Tag: ref.Ref[10:],
}
}
return sources, nil
}
func (s *SourceData) DownloadURL() string {
return archivePrefix + s.Tag + ".zip"
}
func (s *SourceData) Load() error {
fp, err := ioutil.TempFile("", "ginsa-"+s.Tag)
if err != nil {
return err
}
defer os.Remove(fp.Name())
res, err := http.Get(s.DownloadURL())
if err != nil {
return err
}
_, err = io.Copy(fp, res.Body)
res.Body.Close()
fp.Close()
archive, err := zip.OpenReader(fp.Name())
if err != nil {
return err
}
defer archive.Close()
s.Branches = map[string]map[string]*Branch{}
for _, f := range archive.File {
parts := strings.Split(f.Name, string(os.PathSeparator))
if len(parts) < 3 {
continue
}
if parts[2] == "banks.json" {
banks := map[string]*Bank{}
rc, err := f.Open()
if err != nil {
return err
}
defer rc.Close()
decoder := json.NewDecoder(rc)
err = decoder.Decode(&banks)
if err != nil {
return err
}
s.Banks = banks
} else if parts[2] == "branches" && filepath.Ext(f.Name) == ".json" {
bankCode := filepath.Base(f.Name)[0:4]
branches := map[string]*Branch{}
rc, err := f.Open()
if err != nil {
return err
}
defer rc.Close()
decoder := json.NewDecoder(rc)
err = decoder.Decode(&branches)
if err != nil {
return err
}
s.Branches[bankCode] = branches
}
}
return nil
}