-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathimport_file_parser.go
426 lines (373 loc) · 9.38 KB
/
import_file_parser.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
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
package main
import (
"errors"
"fmt"
"io"
"io/ioutil"
"log"
"regexp"
"strings"
"github.com/russross/blackfriday/v2"
"github.com/glestaris/issuez/domain"
)
func ParseImportFile(markdownFile io.Reader) ([]*domain.Issue, error) {
data, err := ioutil.ReadAll(markdownFile)
if err != nil {
return nil, fmt.Errorf("Failed to read markdown file: %s", err)
}
md := blackfriday.New(blackfriday.WithExtensions(
blackfriday.FencedCode | blackfriday.Strikethrough,
))
node := md.Parse(data)
// parsing did not produce a doc, no issues
if node == nil {
return []*domain.Issue{}, nil
}
// make document
doc, err := newDocument(node)
if err != nil {
log.Printf("Failed to create document: %s", err)
return nil, errors.New("Failed to parse markdown file")
}
// find sections
sections, err := doc.sections()
if err != nil {
return nil, fmt.Errorf(
"Failed to extract issues from markdown file: %s", err,
)
}
if len(sections) == 0 {
return []*domain.Issue{}, nil
}
// create issues
issues := make([]*domain.Issue, len(sections))
for i, section := range sections {
issue, err := section.makeIssue()
if err != nil {
return nil, fmt.Errorf(
"Failed parsing issue %d in markdown file: %s", i+1, err,
)
}
issues[i] = issue
}
return issues, nil
}
type document struct {
root *blackfriday.Node
}
func newDocument(doc *blackfriday.Node) (*document, error) {
if doc.Type != blackfriday.Document {
return nil, errors.New("Document not found")
}
return &document{root: doc}, nil
}
func isNodeEmpty(node *blackfriday.Node) bool {
// nil node is empty
if node == nil {
return true
}
// doesn't have children: empty if literal is empty
if node.FirstChild == nil {
return len(node.Literal) == 0
}
// has children: empty if all children are empty
foundNonEmpty := false
node.Walk(func(n *blackfriday.Node, entering bool) blackfriday.WalkStatus {
if !entering {
return blackfriday.GoToNext
}
if n == node {
return blackfriday.GoToNext
}
if !isNodeEmpty(n) {
foundNonEmpty = true
return blackfriday.Terminate
}
return blackfriday.SkipChildren
})
return !foundNonEmpty
}
func (d *document) sections() ([]*section, error) {
boundaries := []*blackfriday.Node{}
currNode := d.root.FirstChild
for currNode != nil {
// remove HRs
if currNode.Type == blackfriday.HorizontalRule {
// mark prev as boundary
// IFF
// 1) prev != nil: not the first node
// 2) next != nil: not the last node
if currNode.Prev != nil && currNode.Next != nil {
b := currNode.Prev
// boundary does not already exist in list
if len(boundaries) == 0 ||
boundaries[len(boundaries)-1] != b {
boundaries = append(boundaries, b)
}
}
nextNode := currNode.Next
currNode.Unlink()
currNode = nextNode
continue
}
// remove empty nodes
if isNodeEmpty(currNode) {
nextNode := currNode.Next
currNode.Unlink()
currNode = nextNode
continue
}
currNode = currNode.Next
}
if d.root.FirstChild == nil {
return []*section{}, nil
}
var sections []*section
// no boundaries? - single issue
if len(boundaries) == 0 {
sections = []*section{
{
firstNode: d.root.FirstChild,
lastNode: d.root.LastChild,
},
}
} else {
sections = make([]*section, len(boundaries)+1)
// first section
sections[0] = §ion{
firstNode: d.root.FirstChild,
lastNode: boundaries[0],
}
// sections in between
for sectionIdx := 1; sectionIdx < len(boundaries); sectionIdx++ {
sections[sectionIdx] = §ion{
firstNode: boundaries[sectionIdx-1].Next,
lastNode: boundaries[sectionIdx],
}
}
// last section
sections[len(boundaries)] = §ion{
firstNode: boundaries[len(boundaries)-1].Next,
lastNode: d.root.LastChild,
}
}
return sections, nil
}
type section struct {
firstNode *blackfriday.Node
lastNode *blackfriday.Node
}
func (s *section) makeIssue() (*domain.Issue, error) {
// parse header
issueType, title, err := s.parseHeader()
if err != nil {
return nil, err
}
// parse footer
epicID, labels := s.parseFooter()
// parse description
var incLastNode bool
if epicID == "" && labels == nil {
// last node was not used as footer
incLastNode = true
}
description, err := s.parseDescription(incLastNode)
if err != nil {
return nil, err
}
// make issue
issue := &domain.Issue{}
// issue title
issue.Title = title
// issue type
if issueType == "" || issueType == "Story" || issueType == "Issue" {
issue.Type = domain.IssueTypeStory
} else if issueType == "Bug" {
issue.Type = domain.IssueTypeBug
} else if issueType == "Chore" || issueType == "Task" {
issue.Type = domain.IssueTypeChore
} else {
return nil, fmt.Errorf("Unknown issue type %s", issueType)
}
// issue description
issue.Description = description
// issue epic
if epicID != "" {
issue.Epic = &domain.Epic{ID: epicID}
}
// issue labels
if labels != nil && len(labels) != 0 {
for _, label := range labels {
issue.Labels = append(issue.Labels, domain.Label{
Label: label,
})
}
}
return issue, nil
}
func (s *section) parseHeader() (string, string, error) {
f := s.firstNode
if f.Type != blackfriday.Paragraph ||
f.FirstChild == nil ||
f.FirstChild != f.LastChild ||
f.FirstChild.Type != blackfriday.Text {
return "", "", errors.New(
"First line in issue section needs to be of the form" +
" '[ISSUE TYPE] ISSUE TITLE'",
)
}
firstLine := string(f.FirstChild.Literal)
re := regexp.MustCompile(`^\s*(?:\[([^\[\]]+)\])?\s*(.+)\s*$`)
matches := re.FindStringSubmatch(firstLine)
if len(matches) == 2 {
return "", strings.TrimSpace(matches[1]), nil
}
if len(matches) == 3 {
return strings.TrimSpace(matches[1]),
strings.TrimSpace(matches[2]),
nil
}
return "", "", errors.New(
"First line in issue section needs to be of the form" +
" '[ISSUE TYPE] ISSUE TITLE'",
)
}
func (s *section) parseFooter() (string, []string) {
l := s.lastNode
if l.Type != blackfriday.Paragraph ||
l.FirstChild == nil ||
l.FirstChild != l.LastChild ||
l.FirstChild.Type != blackfriday.Text {
return "", nil
}
lastParagraph := string(l.FirstChild.Literal)
var epicID string
epicRe := regexp.MustCompile(`(?:E|Epic):\s*(.+)`)
epicReMatches := epicRe.FindStringSubmatch(lastParagraph)
if len(epicReMatches) == 2 {
epicID = strings.TrimSpace(epicReMatches[1])
}
var labels []string
labelsRe := regexp.MustCompile(`(?:L|Labels):\s*(.+)`)
labelsReMatches := labelsRe.FindStringSubmatch(lastParagraph)
if len(labelsReMatches) == 2 {
labels = []string{}
for _, label := range strings.Split(labelsReMatches[1], ",") {
labels = append(labels, strings.TrimSpace(label))
}
}
return epicID, labels
}
func parseTextContainer(node *blackfriday.Node, tc *domain.TextContainer) {
textMode := domain.TextMode{}
linkURL := ""
node.Walk(func(
in *blackfriday.Node, entering bool,
) blackfriday.WalkStatus {
switch in.Type {
case blackfriday.Strong:
textMode.Bold = !textMode.Bold
case blackfriday.Emph:
textMode.Italics = !textMode.Italics
case blackfriday.Del:
textMode.Strikethrough = !textMode.Strikethrough
case blackfriday.Link:
if entering {
linkURL = string(in.LinkData.Destination)
} else {
linkURL = ""
}
// Leafs
case blackfriday.Code:
text := string(in.Literal)
if text == "" {
return blackfriday.GoToNext
}
textMode.Code = true
if linkURL == "" {
tc.AddText(text, textMode)
} else {
tc.AddLink(text, linkURL, textMode)
}
textMode.Code = false
case blackfriday.Text:
text := string(in.Literal)
if text == "" {
return blackfriday.GoToNext
}
if linkURL == "" {
tc.AddText(text, textMode)
} else {
tc.AddLink(text, linkURL, textMode)
}
}
return blackfriday.GoToNext
})
}
func parseText(node *blackfriday.Node) string {
text := ""
node.Walk(func(
in *blackfriday.Node, entering bool,
) blackfriday.WalkStatus {
text += string(in.Literal)
return blackfriday.GoToNext
})
return text
}
func headingLevel(nodeHeadingLevel int) domain.HeadingLevel {
switch nodeHeadingLevel {
case 1:
return domain.HeadingLevel1
case 2:
return domain.HeadingLevel2
case 3:
return domain.HeadingLevel3
case 4:
return domain.HeadingLevel4
case 5:
return domain.HeadingLevel5
default:
return domain.HeadingLevel5
}
}
func (s *section) parseDescription(incLastNode bool) (*domain.Document, error) {
if s.firstNode == s.lastNode {
// no description
return nil, nil
}
startNode := s.firstNode.Next
stopNode := s.lastNode.Prev
if incLastNode {
stopNode = s.lastNode
}
domainDoc := &domain.Document{}
for node := startNode; node != stopNode.Next; node = node.Next {
switch node.Type {
case blackfriday.Paragraph:
tc := domainDoc.AddParagraph()
parseTextContainer(node, tc)
case blackfriday.List:
var list *domain.ListData
if node.ListData.ListFlags&blackfriday.ListTypeOrdered ==
blackfriday.ListTypeOrdered {
list = domainDoc.AddOrderedList()
} else {
list = domainDoc.AddUnorderedList()
}
for in := node.FirstChild; in != nil; in = in.Next {
tc := list.AddItem()
parseTextContainer(in, tc)
}
case blackfriday.CodeBlock:
domainDoc.AddCodeBlock(
string(node.CodeBlockData.Info), string(node.Literal),
)
case blackfriday.Heading:
text := parseText(node)
domainDoc.AddHeading(headingLevel(node.HeadingData.Level), text)
default:
return nil, fmt.Errorf("Unknown node type: %s", node.Type)
}
}
return domainDoc, nil
}