-
Notifications
You must be signed in to change notification settings - Fork 0
/
mboxrd.go
107 lines (81 loc) · 1.75 KB
/
mboxrd.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
package mboxrd
import (
"bufio"
"io"
"regexp"
)
const (
crlf = string("\r\n")
)
var (
reNewMessage = regexp.MustCompile(`^From `)
reUnescape = regexp.MustCompile(`^\>+From `)
)
// Extract processes all lines from the the mboxrd reader
// and puts resulting messages each as its own channel into
// the provided messages channel.
//
// It will stop only if it runs into non-empty lines prior
// to a message header. Otherwise it will continue processing
// the lines in assumption that the message archive format
// is correct.
//
// Each message's channel and the parent messages' channel
// are closed after the mbox data is exhausted.
func Extract(mboxrd io.Reader, messages chan chan string, errors chan error) {
var (
line string
prevEmpty = true
message chan string
)
scanner := bufio.NewScanner(mboxrd)
for scanner.Scan() {
line = scanner.Text()
switch {
case line == "":
if message != nil {
if prevEmpty {
message <- ""
}
prevEmpty = true
}
case reNewMessage.MatchString(line) && prevEmpty:
if message != nil {
close(message)
}
message = make(chan string)
messages <- message
message <- line
prevEmpty = false
case reUnescape.MatchString(line):
line = line[1:]
if message == nil {
errors <- MboxError("Data found before a message beginning")
return
}
if prevEmpty {
message <- ""
}
message <- line
prevEmpty = false
default:
if message == nil {
errors <- MboxError("Data found before a message beginning")
return
}
if prevEmpty {
message <- ""
}
message <- line
prevEmpty = false
}
}
if message != nil {
close(message)
}
if err := scanner.Err(); err != nil {
errors <- err
}
close(messages)
return
}