forked from hamaxx/browscap_go
/
loader.go
107 lines (84 loc) · 1.97 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
// 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
nComment = []byte{'#'} // number signal
sComment = []byte{';'} // semicolon signal
sStart = []byte{'['} // section start signal
sEnd = []byte{']'} // section end signal
versionSection = "GJK_Browscap_Version"
versionKey = "Version"
)
func NewBrowsCapFromFile(path string) (*BrowsCap, error) {
file, err := os.Open(path)
if err != nil {
return nil, err
}
defer file.Close()
return NewBrowsCapFromReader(file)
}
func NewBrowsCapFromReader(reader io.Reader) (*BrowsCap, error) {
dict := newDictionary()
var version string
sectionName := ""
lineNum := 0
scanner := bufio.NewScanner(reader)
for scanner.Scan() {
line := scanner.Bytes()
line = bytes.TrimSpace(line)
if len(line) == 0 {
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
kvSplit := bytes.IndexByte(line, '=')
// Parse Key
keyb := bytes.TrimSpace(line[0:kvSplit])
// Parse Value
valb := bytes.TrimSpace(line[kvSplit+1:])
if len(valb) == 0 {
continue
}
if valb[0] == '"' || valb[0] == '\'' {
valb = valb[1 : len(valb)-1]
}
key := string(keyb)
val := string(valb)
if sectionName == versionSection {
if key == versionKey {
version = val
}
continue
}
if _, ok := dict.browsers[sectionName]; !ok {
dict.tree.Add(sectionName, lineNum)
browser := &Browser{
Section: sectionName,
}
browser.setValue(key, val)
dict.browsers[sectionName] = browser
} else {
dict.browsers[sectionName].setValue(key, val)
}
lineNum++
}
if err := scanner.Err(); err != nil {
return nil, err
}
return &BrowsCap{dict, version}, nil
}