-
Notifications
You must be signed in to change notification settings - Fork 7
/
code-loader.js
148 lines (129 loc) · 5.37 KB
/
code-loader.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
const fs = require('fs');
const fetch = require('node-fetch');
const COMMENT_SYMBOL = {
ts: "//",
java: "//",
kotlin: "//",
python: "#",
go: "//",
proto: "//",
rust: "//"
}
const plugin = (options) => {
const codeLoadRegex = /.*CODE_LOAD::([^#?]+)(?:#([^?]*))?(?:\?(.+))?$/g;
const injectCode = async (str) => {
let fileData = null;
str.replace(codeLoadRegex, (match, filePath, customTag, markNumber) => {
fileData = { filePath, customTag, markNumber };
return match;
});
if (!fileData) {
return str;
}
const fileContent = await readFileOrFetch(fileData.filePath);
const data = extractAndClean(fileContent, fileData.customTag, fileData.markNumber, fileData.filePath);
return str.replace(codeLoadRegex, (match) => match.replace(/.*CODE_LOAD::[^#?]+(?:#([^?]*))?(?:\?(.+))?$/, data));
};
async function readFileOrFetch(filepath) {
if (filepath.startsWith('https://raw.githubusercontent.com/')) {
const response = await fetch(filepath);
if (!response.ok) {
throw new Error('Failed to fetch file from GitHub for ' + filepath);
}
return await response.text();
} else {
return fs.readFileSync('./code_snippets/' + filepath, 'utf8');
}
}
function extractCommentSymbol(filePath) {
if (filePath.includes(".java")) {
return COMMENT_SYMBOL.java;
} else if (filePath.includes(".kt")) {
return COMMENT_SYMBOL.kotlin;
} else if (filePath.includes(".ts")) {
return COMMENT_SYMBOL.ts;
} else if (filePath.includes(".py")) {
return COMMENT_SYMBOL.python;
} else if (filePath.includes(".go")) {
return COMMENT_SYMBOL.go;
} else if (filePath.includes(".rs")) {
return COMMENT_SYMBOL.rust;
} else if (filePath.includes(".proto")) {
return COMMENT_SYMBOL.proto;
} else {
throw new Error(`language not detected for filepath ${filePath}`)
}
}
function extractAndClean(fileContent, customTag, markNumber, filePath) {
const commentSymbol = extractCommentSymbol(filePath)
const startTag = (customTag) ? `<start_${customTag}>` : "<start_here>";
const endTag = (customTag) ? `<end_${customTag}>` : "<end_here>";
if (customTag && !fileContent.includes(startTag)) {
throw new Error(`Custom start tag "${startTag}" not found in file ${filePath}`);
}
if (customTag && !fileContent.includes(endTag)) {
throw new Error(`Custom end tag "${endTag}" not found in file ${filePath}`);
}
let lines;
// Only remove the tag lines if there are tags present
if(fileContent.includes(startTag) && fileContent.includes(endTag)){
lines = fileContent.split(startTag).pop().split(endTag).shift().split('\n').slice(1,-1)
// filter out the forced spotless breaks
.filter(line => !line.includes(`${commentSymbol} break`));
} else {
lines = fileContent.split('\n')
// filter out the forced spotless breaks
.filter(line => !line.includes(`${commentSymbol} break`));
}
let finalLines = [];
if (markNumber) {
const markStartTag = `${commentSymbol} <mark_${markNumber}>`;
const markEndTag = `${commentSymbol} </mark_${markNumber}>`;
let needToMark = false;
lines.forEach(function (line, index) {
if(line.includes(markStartTag)){
if(needToMark){
throw new Error(`Mark start tag ${markStartTag} found before mark end tag in file ${filePath}`)
}
needToMark = true;
}
if(line.includes(markEndTag)){
if(!needToMark){
throw new Error(`Mark end tag ${markEndTag} found before mark start tag in file ${filePath}`)
}
needToMark = false;
}
if(!line.includes('<start_') && !line.includes('<end_') && !line.includes('<mark_') && !line.includes('</mark_')) {
if(needToMark){
finalLines.push(`${commentSymbol} !mark`)
}
finalLines.push(line);
}
});
} else {
finalLines = lines;
}
const leadingWhitespace = lines[0].match(/^\s*/)[0];
return finalLines.filter(line => {
// filter out all code loader tags
return !line.includes('<start_') &&
!line.includes('<end_') &&
!line.includes('<mark_') &&
!line.includes('</mark_');
})
.map(line => line.replace(new RegExp(`^${leadingWhitespace}`), ''))
.join('\n');
}
const transformer = async (ast) => {
const { visit } = await import('unist-util-visit');
const codes = [];
await visit(ast, ['code', 'inlineCode'], (node) => {
codes.push(node);
});
await Promise.all(codes.map(async (node) => {
node.value = await injectCode(node.value);
}));
};
return transformer;
};
module.exports = plugin;