/
p_tabfile.go
121 lines (109 loc) · 2.32 KB
/
p_tabfile.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
package glopher
import (
"bufio"
"fmt"
"io"
"os"
"strings"
"github.com/ilius/glopher/common"
)
func init() {
RegisterPluginType1(&tabfilePlug{})
}
type tabfilePlug struct{}
func (p *tabfilePlug) Name() string {
return "tabfile"
}
func (p *tabfilePlug) Description() string {
return "Tabfile (.txt)"
}
func (p *tabfilePlug) Extentions() []string {
return []string{
".txt",
".tab",
".dic",
}
}
func (p *tabfilePlug) ReadOptionTypes() []*OptionType {
return []*OptionType{}
}
func (p *tabfilePlug) WriteOptionsTypes() []*OptionType {
return []*OptionType{}
}
func (p *tabfilePlug) Count(filename string) (int, error) {
file, err := os.Open(filename)
if err != nil {
return 0, err
}
return CountBlocks(file, Newline)
}
func (p *tabfilePlug) Read(filename string, options ...Option) (func() *Entry, error) {
file, err := os.Open(filename)
if err != nil {
return nil, err
}
scanner := bufio.NewScanner(file)
return func() *Entry {
if !scanner.Scan() {
return &Entry{
Error: io.EOF,
}
}
line := scanner.Text()
if err := scanner.Err(); err != nil {
return &Entry{
Error: err,
}
}
line = strings.TrimSpace(line)
parts := strings.Split(line, "\t")
if len(parts) < 1 {
return &Entry{
Error: fmt.Errorf("tabfile: bad line: %v", line),
}
}
wordsStr := parts[0]
defi := ""
if len(parts) == 1 {
} else if len(parts) == 2 {
defi = parts[1]
} else {
defi = strings.Join(parts[1:], "\t")
}
words := SplitByBarUnescapeNTB(wordsStr)
defi = UnescapeNTB(defi, false)
return &Entry{
Word: words[0],
Defi: defi,
AltWord: words[1:],
}
}, nil
}
func (p *tabfilePlug) Write(glos LimitedGlossary, filename string, options ...Option) error {
file, err := os.Create(filename)
if file != nil {
defer common.Close(file)
}
if err != nil {
return err
}
for _, pair := range glos.Info().Items() {
line := EscapeNTB("##"+pair[0], false) + "\t" + EscapeNTB(pair[1], false)
_, err := file.WriteString(line + "\n")
if err != nil {
return err
}
}
for entry := range glos.Iter() {
if entry.Error != nil {
return entry.Error
}
words := append([]string{entry.Word}, entry.AltWord...)
line := JoinByBarEscapeNTB(words) + "\t" + EscapeNTB(entry.Defi, false)
_, err := file.WriteString(line + "\n")
if err != nil {
return err
}
}
return nil
}