-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcli.js
103 lines (84 loc) · 2.69 KB
/
cli.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
import fs from 'node:fs/promises';
import {createReadStream, createWriteStream} from 'node:fs';
import {pipeline} from 'node:stream/promises';
import {parseArgs} from 'node:util';
import {processDocument} from './index.js';
import {fileURLToPath} from 'node:url';
import path from 'node:path';
import {FileCache, ensureDirectory} from './src/util.js';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const {
values: {
'input-dir': inputDir,
'output-dir': outputDir,
'skip-image-optimization': skipImageOptimization
}
} = parseArgs({
options: {
'input-dir': {
type: 'string',
short: 'i',
default: path.resolve(__dirname, '..', '..', 'pages')
},
'output-dir': {
type: 'string',
short: 'o',
default: path.resolve(__dirname, '..', '..', 'public')
},
'skip-image-optimization': {
type: 'boolean',
short: 's',
default: false
}
}
});
const processable = new Set(['.html', '.md']);
const isTemplate = name => name.endsWith('.template.html');
const fileCache = new FileCache();
const assets = new Map();
const writtenAssets = new Set();
async function processDirectory(pathToDir) {
for (const inputFile of await fs.readdir(pathToDir, {withFileTypes: true})) {
if (inputFile.isDirectory()) {
await processDirectory(path.join(pathToDir, inputFile.name));
continue;
}
const ext = path.extname(inputFile.name);
if (!processable.has(ext) || isTemplate(inputFile.name)) {
continue;
}
const pathToInput = path.join(pathToDir, inputFile.name);
const pathToOutputDir = path.join(outputDir, path.relative(inputDir, pathToDir));
console.log('processing', pathToInput);
const fileContents = await fileCache.get(pathToInput);
const vFile = await processDocument({
inputFile: {
name: pathToInput,
text: fileContents
},
assets,
skipImageOptimization,
fileCache,
writtenAssets,
outputDir: pathToOutputDir
});
await ensureDirectory(pathToOutputDir);
for (const [pathToOldAsset, pathToNewAsset] of assets) {
if (writtenAssets.has(pathToNewAsset)) {
continue;
}
await ensureDirectory(path.dirname(pathToNewAsset));
console.log('write', pathToNewAsset);
await pipeline(
createReadStream(pathToOldAsset),
createWriteStream(pathToNewAsset)
);
writtenAssets.add(pathToNewAsset);
}
const outputName = `${path.basename(inputFile.name, ext)}.html`;
const pathToOutput = path.join(pathToOutputDir, outputName);
console.log('write', pathToOutput);
await fs.writeFile(pathToOutput, String(vFile), 'utf8');
}
}
await processDirectory(inputDir);