-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathinterpolate-source-code.mjs
59 lines (47 loc) · 1.49 KB
/
interpolate-source-code.mjs
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
// https://github.com/nuxt/content/pull/676
import path from 'path'
import fs from 'fs/promises'
const interpolateSourceCode = async (file) => {
if (file.extension !== '.md') {
return
}
const lines = file.data.split('\n')
let inCodeBlock = false
for (let i = 0, l = lines.length; i < l; i++) {
const line = lines[i].trim()
if (!inCodeBlock && line.startsWith('```')) {
inCodeBlock = true
// handling indented codeblocks
// could save the codeblock indent and offset the line indent from it.
continue
}
const basePath = 'static/files/'
const sourceKey = 'source:'
if (inCodeBlock && line.startsWith(sourceKey)) {
try {
const [lineIndent, relativePath] = lines[i].split(sourceKey)
const sourceCode = path.resolve(basePath, relativePath.trim())
const buffer = await fs.readFile(sourceCode,{encoding: 'utf8'})
let indentedLine = lineIndent + buffer.toString().replace(/\n/g, "\n" + lineIndent)
if (lineIndent.length) {
// an extra lineIndent is added to the end.
indentedLine = indentedLine.slice(0, lineIndent.length * -1)
}
lines[i] = indentedLine
} catch (e) {
throw e
}
continue
}
if (inCodeBlock && line.startsWith('```')) {
inCodeBlock = false
}
}
file.data = lines.join('\n')
}
// export default {
// hooks: {
// 'content:file:beforeParse': interpolateSourceCode
// }
// }
export default interpolateSourceCode;