-
Notifications
You must be signed in to change notification settings - Fork 38
/
document.go
250 lines (214 loc) · 5.83 KB
/
document.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
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
package document
import (
"bytes"
"fmt"
"sync"
"github.com/pkg/errors"
"github.com/yuin/goldmark"
"github.com/yuin/goldmark/ast"
"github.com/yuin/goldmark/parser"
"github.com/yuin/goldmark/text"
"github.com/stateful/runme/v3/internal/renderer/cmark"
"github.com/stateful/runme/v3/pkg/document/constants"
)
var DefaultAttributeParser = newFailoverAttributeParser(
[]attributeParser{
&jsonParser{},
&babikMLParser{},
},
&jsonParser{},
)
var defaultRenderer = cmark.Render
type Document struct {
source []byte
identityResolver identityResolver
nameResolver *nameResolver
parser parser.Parser
renderer renderer
onceParse sync.Once
parseErr error
onceSplitSource sync.Once
splitSourceErr error
rootASTNode ast.Node
rootNode *Node
frontmatterRaw []byte
content []byte // raw data after frontmatter
contentOffset int
trailingLineBreaksCount int
onceParseFrontmatter sync.Once
parseFrontmatterErr error
frontmatter *Frontmatter
}
func New(source []byte, identityResolver identityResolver) *Document {
return &Document{
source: source,
identityResolver: identityResolver,
nameResolver: &nameResolver{
namesCounter: map[string]int{},
cache: map[interface{}]string{},
},
parser: goldmark.DefaultParser(),
renderer: defaultRenderer,
onceParse: sync.Once{},
onceSplitSource: sync.Once{},
onceParseFrontmatter: sync.Once{},
contentOffset: -1,
}
}
func (d *Document) Content() []byte {
return d.content
}
// ContentOffset returns the position of source from which
// the actual content starts. If a value <0 is returned,
// it means that the source is not parsed yet.
//
// Frontmatter is not a part of the content.
func (d *Document) ContentOffset() int {
return d.contentOffset
}
func (d *Document) Parse() error {
return d.splitAndParse()
}
func (d *Document) Root() (*Node, error) {
if err := d.splitAndParse(); err != nil {
return nil, err
}
return d.rootNode, nil
}
func (d *Document) RootAST() (ast.Node, error) {
if err := d.splitAndParse(); err != nil {
return nil, err
}
return d.rootASTNode, nil
}
func (d *Document) TrailingLineBreaksCount() int {
return d.trailingLineBreaksCount
}
func (d *Document) splitAndParse() error {
d.splitSource()
if err := d.splitSourceErr; err != nil {
return err
}
d.parse()
if d.parseErr != nil {
return d.parseErr
}
return nil
}
// splitSource splits source into FrontMatter and content.
// TODO(adamb): replace it with an extension to goldmark.
// Example: https://github.com/abhinav/goldmark-frontmatter
func (d *Document) splitSource() {
d.onceSplitSource.Do(func() {
l := &itemParser{input: d.source}
runItemParser(l, parseInit)
for _, item := range l.items {
switch item.Type() {
case parsedItemFrontMatter:
d.frontmatterRaw = item.Value(d.source)
case parsedItemContent:
d.content = item.Value(d.source)
d.contentOffset = item.start
case parsedItemError:
if errors.Is(item.err, errParseRawFrontmatter) {
d.parseFrontmatterErr = item.err
} else {
d.splitSourceErr = item.err
}
return
}
}
})
}
func (d *Document) parse() {
d.onceParse.Do(func() {
d.rootASTNode = d.parser.Parse(text.NewReader(d.content))
node := &Node{}
if err := d.buildBlocksTree(d.rootASTNode, node); err != nil {
d.parseErr = err
return
}
d.rootNode = node
d.trailingLineBreaksCount = countTrailingLineBreaks(d.source, detectLineBreak(d.source))
// Retain trailing new lines. This information must be stored in
// ast.Node's attributes because it's later used by internal/renderer/cmark.Render,
// which does not use anything else than ast.Node.
d.rootASTNode.SetAttributeString(constants.FinalLineBreaksKey, d.trailingLineBreaksCount)
})
}
func (d *Document) buildBlocksTree(parent ast.Node, node *Node) error {
for astNode := parent.FirstChild(); astNode != nil; astNode = astNode.NextSibling() {
switch astNode.Kind() {
case ast.KindFencedCodeBlock:
block, err := newCodeBlock(
d,
astNode.(*ast.FencedCodeBlock),
d.identityResolver,
d.nameResolver,
d.content,
d.renderer,
)
if err != nil {
return errors.WithStack(err)
}
node.add(block)
case ast.KindBlockquote, ast.KindList, ast.KindListItem:
block, err := newInnerBlock(astNode, d.content, d.renderer)
if err != nil {
return errors.WithStack(err)
}
nNode := node.add(block)
if err := d.buildBlocksTree(astNode, nNode); err != nil {
return err
}
default:
block, err := newMarkdownBlock(astNode, d.content, d.renderer)
if err != nil {
return errors.WithStack(err)
}
node.add(block)
}
}
return nil
}
type nameResolver struct {
namesCounter map[string]int
cache map[interface{}]string
}
func (r *nameResolver) Get(obj interface{}, name string) string {
if v, ok := r.cache[obj]; ok {
return v
}
var result string
r.namesCounter[name]++
if r.namesCounter[name] == 1 {
result = name
} else {
result = fmt.Sprintf("%s-%d", name, r.namesCounter[name])
}
r.cache[obj] = result
return result
}
func CountTrailingLineBreaks(source []byte, lineBreak []byte) int {
return countTrailingLineBreaks(source, lineBreak)
}
func countTrailingLineBreaks(source []byte, lineBreak []byte) int {
i := len(source) - len(lineBreak)
numBreaks := 0
for i >= 0 && bytes.Equal(source[i:i+len(lineBreak)], lineBreak) {
i -= len(lineBreak)
numBreaks++
}
return numBreaks
}
func DetectLineBreak(source []byte) []byte {
return detectLineBreak(source)
}
func detectLineBreak(source []byte) []byte {
crlfCount := bytes.Count(source, []byte{'\r', '\n'})
lfCount := bytes.Count(source, []byte{'\n'})
if crlfCount == lfCount {
return []byte{'\r', '\n'}
}
return []byte{'\n'}
}