forked from digitalcrab/browscap_go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
loader.go
117 lines (93 loc) · 2.14 KB
/
loader.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
// Use of this source code is governed by a MIT
// license that can be found in the LICENSE file.
package browscap_go
import (
"bufio"
"bytes"
"io"
"os"
)
var (
// Ini
sEmpty = []byte{} // empty signal
nComment = []byte{'#'} // number signal
sComment = []byte{';'} // semicolon signal
sStart = []byte{'['} // section start signal
sEnd = []byte{']'} // section end signal
sEqual = []byte{'='} // equal signal
sQuote1 = []byte{'"'} // quote " signal
sQuote2 = []byte{'\''} // quote ' signal
versionSection = "GJK_Browscap_Version"
versionKey = "Version"
)
func loadFromIniFile(path string) (*dictionary, error) {
file, err := os.Open(path)
if err != nil {
return nil, err
}
defer file.Close()
buf := bufio.NewReader(file)
return loadFromReader(buf)
}
func loadFromReader(buf *bufio.Reader) (*dictionary, error) {
dict := newDictionary()
sectionName := ""
lineNum := 0
for {
line, _, err := buf.ReadLine()
if err != nil {
if err == io.EOF {
break
} else {
return nil, err
}
}
// Empty line
if bytes.Equal(sEmpty, line) {
continue
}
// Trim
line = bytes.TrimSpace(line)
// Empty line
if bytes.Equal(sEmpty, line) {
continue
}
// Comment line
if bytes.HasPrefix(line, nComment) || bytes.HasPrefix(line, sComment) {
continue
}
// Section line
if bytes.HasPrefix(line, sStart) && bytes.HasSuffix(line, sEnd) {
sectionName = string(line[1 : len(line)-1])
continue
}
// Key => Value
kv := bytes.SplitN(line, sEqual, 2)
// Parse Key
keyb := bytes.TrimSpace(kv[0])
// Parse Value
valb := bytes.TrimSpace(kv[1])
if bytes.HasPrefix(valb, sQuote1) {
valb = bytes.Trim(valb, `"`)
}
if bytes.HasPrefix(valb, sQuote2) {
valb = bytes.Trim(valb, `'`)
}
key := string(keyb)
val := string(valb)
if sectionName == versionSection {
if key == versionKey {
version = val
}
continue
}
// Create section
if _, ok := dict.browsers[sectionName]; !ok {
dict.tree.Add(sectionName, lineNum)
dict.browsers[sectionName] = &Browser{}
lineNum++
}
dict.browsers[sectionName].setValue(key, val)
}
return dict, nil
}