forked from TBD54566975/developer.tbd.website
-
Notifications
You must be signed in to change notification settings - Fork 0
/
extract-snippets.js
83 lines (70 loc) · 2.64 KB
/
extract-snippets.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
const fs = require('fs');
const path = require('path');
function extractSnippetsFromFile(content) {
const snippetStartTag = ':snippet-start:';
const snippetEndTag = ':snippet-end:';
const snippets = {};
let startIndex = 0,
endIndex = 0;
while ((startIndex = content.indexOf(snippetStartTag, endIndex)) !== -1) {
const startTagClose = content.indexOf('\n', startIndex);
if (startTagClose === -1) {
console.log('Snippet start tag not followed by newline. Skipping...');
break;
}
endIndex = content.indexOf(snippetEndTag, startTagClose);
if (endIndex === -1) {
console.log('No closing tag found for a snippet. Skipping...');
break;
}
const snippetName = content
.substring(startIndex + snippetStartTag.length, startTagClose)
.trim();
const endTagStart = content.lastIndexOf('\n', endIndex);
let snippetContent = content.substring(startTagClose + 1, endTagStart);
// Trim leading whitespace from each line
snippetContent = snippetContent
.split('\n')
.map((line) => line.trimStart())
.join('\n')
.trim();
if (snippetName) {
snippets[snippetName] = snippetContent;
}
// Move endIndex past the end tag to avoid including it in the next iteration
endIndex = content.indexOf('\n', endIndex) + 1;
}
return snippets;
}
function processDirectory(directory, outputDirectory, baseDirectory) {
const items = fs.readdirSync(directory);
items.forEach((item) => {
const fullPath = path.join(directory, item);
const stat = fs.statSync(fullPath);
if (stat.isDirectory()) {
processDirectory(fullPath, outputDirectory, baseDirectory);
} else if (stat.isFile()) {
const content = fs.readFileSync(fullPath, 'utf-8');
const fileSnippets = extractSnippetsFromFile(content);
const fileExtension = path.extname(fullPath);
for (const [snippetName, snippetContent] of Object.entries(
fileSnippets
)) {
const relativePath = path.relative(baseDirectory, directory);
const snippetDir = path.join(outputDirectory, relativePath);
if (!fs.existsSync(snippetDir)) {
fs.mkdirSync(snippetDir, { recursive: true });
}
const outputFileName = `${snippetName}.snippet${fileExtension}`;
const outputPath = path.join(snippetDir, outputFileName);
fs.writeFileSync(outputPath, snippetContent);
}
}
});
}
const rootDirectory = './site/__tests__';
const outputDirectory = './site/snippets';
if (!fs.existsSync(outputDirectory)) {
fs.mkdirSync(outputDirectory, { recursive: true });
}
processDirectory(rootDirectory, outputDirectory, rootDirectory);