forked from codebytere/github-issue-parser
-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
65 lines (56 loc) · 1.57 KB
/
index.js
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
const remark = require('remark')
const html = require('remark-html')
function githubIssueParser (txt) {
if (typeof txt !== 'string') throw new Error('input should be a markdown string')
const trim = val => {
val = val.replace(/^(\s*:\s*|\s*)/, '')
return val.replace(/(\n+$)/, '')
}
const toHtml = remark().use(html)
const lexer = remark()
let tokens = lexer.parse(txt).children
const result = {}
let key = ''
tokens = tokens.filter(token => token.type !== 'html')
tokens.forEach(token => {
if (token.type === 'heading') {
key = token.children[0].value
result[key] = []
return
}
if (token.type === 'list') {
const listKeys = token.children
listKeys.forEach(listItem => {
key = listItem.children[0].children[0].children[0].value
result[key] = []
if (listItem.children[0].hasOwnProperty('children')) {
if (listItem.children[0].children.length > 1) {
result[key].push(listItem.children[0].children[1])
} else {
// push an empty filler node if no data provided
result[key].push({
type: 'text',
value: '',
position: {}
})
}
}
})
return
}
if (!key) return
result[key].push(token)
})
Object.keys(result).forEach(key => {
const tree = {
type: 'root',
children: result[key]
}
result[key] = {
raw: trim(lexer.stringify(tree)),
html: trim(toHtml.stringify(tree))
}
})
return result
}
module.exports = githubIssueParser