-
Notifications
You must be signed in to change notification settings - Fork 0
/
validation.js
124 lines (97 loc) · 2.96 KB
/
validation.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
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
export const KEY_VALUE_PAIR = 'key_value_pair'
export const BEGINNING_OF_LIST = 'beginning_of_list'
export const LIST_ITEM = 'list_item'
/**
*
* @param {array} previousLines
*/
function anyPreviousLineStartsList ({ previousLines }) {
// todo, deal with a later list (with bad syntax) seeing an earlier list with proper syntax and incorrectly saying things are a-ok
return previousLines.some(line => line.endsWith(':'))
}
/**
*
* @param {string} line
* @param {number} index
* @param {array} array
* @param {string} [nextLine]
*/
export default function validateFrontmatterLine ({ line, index, array, nextLine }) {
const startsWithColon = line.startsWith(':')
const hasColon = line.includes(':')
const endsWithColon = line.endsWith(':')
const startsWithDash = line.startsWith('-')
const nextLineStartsWithDash = nextLine === undefined ? false : nextLine.startsWith('-')
const previousLines = array.slice(0, index)
if (startsWithColon) {
throw new Error(`
Metadata is missing a key in its key value pair:
${line}
Metadata should have a key left of the colon:
correct:
key: value
incorrect:
: value
`)
}
if (!hasColon && !startsWithDash) {
throw new Error(`
Couldn't parse metadata:
${line}
Metadata must either include a colon separator or start with a dash:
correct:
key: value
- list item
beginning of a list:
incorrect:
key value
list item
beginning of list
`)
}
if (endsWithColon && !startsWithDash && !nextLineStartsWithDash) {
throw new Error(`
Couldn't parse metadata list:
${line}
${nextLine}
Metadata lists must end with a colon and must be followed by metadata that starts with a dash (indentation doesn't matter):
correct:
beginning of list:
- list item
beginning of list:
- indented list item
incorrect:
beginning of list:
list item
beginning of list:
indented list item
`)
}
if (startsWithDash && !anyPreviousLineStartsList({ previousLines })) {
throw new Error(`
List item is not part of a list:
${line}
Lists items must follow the beginning of a list. Lists are started by omitting text after the colon (indentation doesn't matter):
correct:
beginning of list:
- list item
- another list item
beginning of list:
- first indented list item
- second indented list item
- an unindented list item mixed in
incorrect:
beginning of list without a colon
- list item
`)
}
if (startsWithDash) {
return LIST_ITEM
}
if (endsWithColon) {
return BEGINNING_OF_LIST
}
if (hasColon && !endsWithColon) {
return KEY_VALUE_PAIR
}
}