-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtext.go
More file actions
59 lines (50 loc) · 1.16 KB
/
text.go
File metadata and controls
59 lines (50 loc) · 1.16 KB
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
package parser
import (
"context"
"io"
"strings"
)
// Text is the trivial plain-text parser. It treats the whole document as
// a single section. A smarter heuristic (blank-line splitting, leading
// ALL-CAPS headings) can come later.
type Text struct{}
// NewText returns a new plain-text parser.
func NewText() *Text { return &Text{} }
// Name implements Parser.
func (*Text) Name() string { return "text" }
// Accepts implements Parser.
func (*Text) Accepts(contentType, filename string) bool {
if contentType == "text/plain" {
return true
}
return HasExt(filename, ".txt")
}
// Parse implements Parser.
func (*Text) Parse(_ context.Context, r io.Reader) (*ParsedDoc, error) {
b, err := io.ReadAll(r)
if err != nil {
return nil, err
}
body := string(b)
title := firstNonEmptyLine(body)
if len(title) > 120 {
title = title[:120]
}
return &ParsedDoc{
Title: title,
Sections: []Section{{
Level: 1,
Title: title,
Content: strings.TrimSpace(body),
}},
}, nil
}
func firstNonEmptyLine(s string) string {
for _, line := range strings.Split(s, "\n") {
line = strings.TrimSpace(line)
if line != "" {
return line
}
}
return ""
}