-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathprocessor.go
More file actions
80 lines (69 loc) · 1.87 KB
/
processor.go
File metadata and controls
80 lines (69 loc) · 1.87 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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
package mdbook
import (
"fmt"
"github.com/yuin/goldmark"
"github.com/yuin/goldmark/ast"
"github.com/yuin/goldmark/extension"
"github.com/yuin/goldmark/text"
)
type Handler interface {
HandleChapter(chapter *Chapter, contentHandler func(walker ast.Walker) error) error
HandleSeparator(separator *Separator) error
HandlePartTitle(partTitle *PartTitle) error
}
type Processor struct {
renderContext *RenderContext
handler Handler
md goldmark.Markdown
}
func NewProcessor(renderContext *RenderContext, handler Handler) *Processor {
md := goldmark.New(
goldmark.WithExtensions(extension.GFM, extension.Footnote),
goldmark.WithParserOptions(),
)
return &Processor{
renderContext: renderContext,
handler: handler,
md: md,
}
}
func Process(renderContext *RenderContext, handler Handler) error {
p := NewProcessor(renderContext, handler)
return p.Process()
}
func (p *Processor) Process() error {
for _, item := range p.renderContext.Book.GetItems() {
if err := p.handleBookItem(item); err != nil {
return err
}
}
return nil
}
func (p *Processor) handleBookItem(bookItem *BookItem) error {
if bookItem.Chapter != nil {
return p.handleChapter(bookItem.Chapter)
} else if bookItem.Separator != nil {
return p.handler.HandleSeparator(bookItem.Separator)
} else if bookItem.PartTitle != nil {
return p.handler.HandlePartTitle(bookItem.PartTitle)
} else {
return fmt.Errorf("invalid book item")
}
}
func (p *Processor) handleChapter(chapter *Chapter) error {
err := p.handler.HandleChapter(chapter, func(walker ast.Walker) error {
sourceBytes := []byte(chapter.Content)
doc := p.md.Parser().Parse(text.NewReader(sourceBytes))
return ast.Walk(doc, walker)
})
if err != nil {
return err
}
for _, subItem := range chapter.SubItems {
err := p.handleBookItem(subItem)
if err != nil {
return err
}
}
return nil
}