forked from osuthailand/hanayo
-
Notifications
You must be signed in to change notification settings - Fork 9
/
parser.go
112 lines (100 loc) · 2.23 KB
/
parser.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
package locale
import (
"bufio"
"fmt"
"os"
"strconv"
"strings"
)
type po struct {
Headers map[string]string
Translations map[string]string
}
// A minimal .po file parser.
func parse(s *bufio.Scanner) *po {
p := &po{
Headers: make(map[string]string, 20),
Translations: make(map[string]string, 500),
}
const (
currentNothing = iota
currentMsgID
currentMsgString
)
var current byte
var currentID string
var currentString string
for s.Scan() {
line := strings.TrimSpace(s.Text())
if line == "" || line[0] == '#' {
continue
}
switch {
case strings.HasPrefix(line, "msgid "):
unq, err := strconv.Unquote(strings.TrimSpace(strings.TrimPrefix(line, "msgid")))
if err != nil {
fmt.Println(line)
fmt.Println(err)
return nil
}
if current != currentNothing && currentID == "" && currentString != "" {
for _, h := range strings.Split(currentString, "\n") {
if h == "" {
continue
}
parts := strings.SplitN(h, ": ", 2)
if len(parts) != 2 {
continue
}
p.Headers[parts[0]] = parts[1]
}
} else {
p.Translations[currentID] = currentString
}
currentID = unq
current = currentMsgID
case strings.HasPrefix(line, "msgstr "):
unq, err := strconv.Unquote(strings.TrimSpace(strings.TrimPrefix(line, "msgstr")))
if err != nil {
fmt.Println(line)
fmt.Println(err)
return nil
}
currentString = unq
current = currentMsgString
case strings.HasPrefix(line, "msgid_plural "), strings.HasPrefix(line, "msgstr["):
// We currently don't support plural in the Go parser, at least hold it off 'til it's needed.
current = currentNothing
default:
if current == currentNothing {
continue
}
unq, err := strconv.Unquote(strings.TrimSpace(line))
if err != nil {
fmt.Println(line)
fmt.Println(err)
return nil
}
switch current {
case currentMsgID:
currentID += unq
case currentMsgString:
currentString += unq
}
}
}
if current == currentMsgString {
p.Translations[currentID] = currentString
}
return p
}
func parseFile(fName string) (*po, error) {
f, err := os.Open(fName)
if err != nil {
return nil, err
}
defer f.Close()
s := bufio.NewScanner(f)
p := parse(s)
return p, nil
}