This repository was archived by the owner on Oct 2, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 60
/
Copy pathgenerate-json.js
178 lines (168 loc) · 4.88 KB
/
generate-json.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
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
/* This file uses a lot of imperative logic, so continues are allowed. */
/* eslint no-continue: off */
const fs = require('fs')
const path = require('path')
const { dirname, basename } = path
const glob = require('glob')
const mkdirp = require('mkdirp')
const parseMarkdown = require('../lib/parseMarkdown')
function hasError(checks) {
return checks.some(isError)
function isError(node) {
if (node.type === 'item') {
return (node.children || []).some(isError)
}
if (node.type === 'check') {
return node.result.status === false
}
throw new Error(`Invalid node type: ${node.type}`)
}
}
function formatError(checks) {
const out = []
const traverse = (node, prefix) => {
if (node.type === 'item') {
out.push(`${prefix} - ✴️ ${node.title}`)
void (node.children || []).forEach(child =>
traverse(child, `${prefix} `)
)
return
}
if (node.type === 'check') {
if (node.result.status === true) {
out.push(`${prefix} - ✅ ${node.title}`)
} else if (node.result.status === false) {
const message = node.result.message ? `: ${node.result.message}` : ''
out.push(`${prefix} - ❌ ${node.title}${message}`)
} else {
out.push(`${prefix} - *️⃣ ${node.title}`)
}
return
}
throw new Error(`Invalid node type: ${node.type}`)
}
for (const node of checks) {
traverse(node, '')
}
return out.join('\n')
}
function main() {
const diagnostic = { errors: [] }
const files = glob.sync('data/*/*.md')
try {
const events = []
for (const file of files) {
try {
const md = fs.readFileSync(file, 'utf8')
const yearMonthParts = basename(dirname(file)).split('-')
const { checks, event } = parseMarkdown(md, {
expectedYear: parseInt(yearMonthParts[0], 10),
expectedMonth: parseInt(yearMonthParts[1], 10)
})
event.declared = {
filename: file,
line: 1,
column: 1
}
const imageFilepath = findImage(file)
if (imageFilepath) {
event.image = copyEventImage(imageFilepath, event.id)
}
if (hasError(checks)) {
diagnostic.errors.push({
location: event.declared,
message: formatError(checks)
})
continue
}
events.push(event)
} catch (e) {
console.error('Caught error while parsing markdown:', e.stack)
diagnostic.errors.push({
location: {
filename: file,
line: 1,
column: 1
},
message: e.message
})
}
}
validateJson(events)
const calendarJsonFilePath = 'public/calendar.json'
if (!diagnostic.errors.length) {
events.sort(compareEvents)
fs.writeFileSync(
calendarJsonFilePath,
require('format-json').diffy(events)
)
console.log('* Written calendar to', calendarJsonFilePath)
} else {
console.log('* Not writing because of error')
for (const error of diagnostic.errors) {
console.log('')
console.log(error.location.filename)
console.log(error.message)
}
}
} catch (e) {
if (!e.location) {
throw e
}
diagnostic.errors.push({
message: e.message,
location: e.location
})
throw e
} finally {
require('mkdirp').sync('tmp')
const diagnosticFilepath = 'tmp/readme-parse-diagnostic.json'
fs.writeFileSync(diagnosticFilepath, JSON.stringify(diagnostic, null, 2))
console.log('* Diagnostic information written to', diagnosticFilepath)
}
}
function compareEvents(a, b) {
return (
a.start.year - b.start.year ||
a.start.month - b.start.month ||
a.start.date - b.start.date ||
(a.id < b.id ? -1 : 1)
)
}
function validateJson(json) {
const usedIds = {}
for (const event of json) {
if (usedIds[event.id]) {
const error /* : any */ = new Error(
`Validation error at ${formatLocation(event.declared)}: ` +
`Duplicate event ID "${event.id}" ` +
`(previously declared at ${formatLocation(
usedIds[event.id].declared
)})`
)
error.location = event.declared
throw error
}
usedIds[event.id] = event
}
}
function formatLocation(location) {
return `${location.filename}`
}
function findImage(filepath) {
const pngPath = filepath.replace(/\.md$/, '.png')
if (fs.existsSync(pngPath)) return pngPath
const jpgPath = filepath.replace(/\.md$/, '.jpg')
if (fs.existsSync(jpgPath)) return jpgPath
return undefined
}
function copyEventImage(inFilepath, eventId) {
const extname = path.extname(inFilepath)
const outUrl = `event-images/${eventId}${extname}`
const outFilepath = `public/${outUrl}`
console.log(`* Copying image "${outFilepath}"`)
mkdirp.sync(path.dirname(outFilepath))
fs.copyFileSync(inFilepath, outFilepath)
return outUrl
}
main()