-
Notifications
You must be signed in to change notification settings - Fork 0
/
build.js
201 lines (179 loc) · 6.13 KB
/
build.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
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
/* eslint-disable no-console */
import { basename, extname, join, resolve } from 'path';
import { rmSync, mkdirSync, rename } from 'fs';
import { cp, readdir, readFile } from 'fs/promises';
import sharp from 'sharp';
import buildRecipes from './src/buildRecipes.js';
import buildRecipeIndex from './src/buildRecipeIndex.js';
import configs from './config.js';
import { __dirname, filterByExtension } from './src/libs/fsUtils.js';
import { ColorTypes, Colors } from './src/libs/ConsoleColors.js';
const THUMBNAIL_WIDTH = 260;
const showOverrideMsg = (cmdArgs) => {
const { Reset } = ColorTypes;
const { Orange, Cyan, Yellow, Magenta } = Colors;
console.log(`\n${
Yellow}Using command line overrides:\n${Magenta}${JSON
.stringify(cmdArgs, null, 3)
.replace(/^(\s*)"([^"]+)": ("?)(.*?)("?)(,?)$/gm, `$1${Magenta}"${Orange}$2${Magenta}": ${Magenta}$3${Cyan}$4${Magenta}$5$6`)}${
Reset}\n`);
};
const showDoneMsg = (recipeCount, time) => {
const { Reset } = ColorTypes;
const { Orange, Cyan, Yellow } = Colors;
console.log(`\n${
Yellow}Processed ${
Cyan}${recipeCount}${
Yellow} recipes in ${
Cyan}${time}${
Orange}ms${
Reset
}\n`);
};
function setupOutputDir(outputPath) {
rmSync(outputPath, { recursive: true, force: true });
mkdirSync(outputPath);
mkdirSync(resolve(outputPath, 'sources'));
mkdirSync(resolve(outputPath, 'images'));
mkdirSync(resolve(outputPath, 'images/thumbnails'));
}
/** Lies a little bit: resolves the promise quickle, before actually done */
function changeExtension(mdDestinationPath) {
return new Promise((promResolve) => {
readdir(mdDestinationPath)
.then((filelist) => {
const onError = (e) => e && console.log(e);
filelist.forEach((file) => {
if (extname(file) !== '.md') {
return;
}
const originalPath = join(mdDestinationPath, file);
const newPath = join(mdDestinationPath, `${basename(file, '.md')}.txt`);
rename(originalPath, newPath, onError);
});
})
.then(() => {
promResolve(true);
});
});
}
/** IE, ahem, sorry, "Edge" doesn't support .avif yet, so let's fix that */
function legacyImageType(imgDestinationPath) {
return new Promise((promResolve) => {
readdir(imgDestinationPath)
.then((filelist) => {
filelist.forEach((file) => {
if (extname(file) !== '.avif') {
return;
}
const originalPath = join(imgDestinationPath, file);
const imgPath = join(imgDestinationPath, `${basename(file, '.avif')}.jpg`);
sharp(originalPath)
.jpeg({ quality: 70 })
.toFile(imgPath)
.catch((err) => console.error(`Problem generating ${imgPath}`, err));
});
})
.then(() => {
promResolve(true);
});
});
}
function swapJpegForAvif(images) {
images
.filter(({ fileName }) => extname(fileName) === '.avif')
// eslint-disable-next-line no-return-assign
.forEach((img) => img.fileName = img.fileName.replace(/avif$/, 'jpg'));
return images;
}
function copyStatic({ staticPath, imagesPath, outputPath, recipesPath }) {
const mdDestinationPath = resolve(outputPath, 'sources');
const imgDestinationPath = resolve(outputPath, 'images');
Promise.all([
cp(staticPath, outputPath, { recursive: true }),
cp(imagesPath, imgDestinationPath, { recursive: true }),
cp(recipesPath, mdDestinationPath, { recursive: true }),
])
.then(() => {
changeExtension(mdDestinationPath);
legacyImageType(imgDestinationPath);
})
.catch((err) => {
console.error(err);
});
}
function makeThumbnails(outputPath, images) {
images
.forEach(({ file, name }) => {
const thumbnailPath = resolve(outputPath, `images/thumbnails/${name}.jpg`);
sharp(file)
.resize(THUMBNAIL_WIDTH)
.jpeg({ quality: 70 })
.toFile(thumbnailPath)
.catch((err) => console.error(`Problem generating ${thumbnailPath}`, err));
});
}
/**
* Intended for, well, me: makes it easier to have my own private directory of images outside
* of this git repo. For example, on a Mac you might use:
*
* ```sh
* npm run build imageDir="~/documents/recipes/images" recipeDir="~/documents/recipes/recipes" outputDir="~/websites/recipes/html"
* ```
*/
function getCommanLineOverrides(args) {
const cmdArgs = args
?.filter((z, index) => index > 1)
.reduce((acc, arg) => {
const [key, value] = arg.split('=');
if (key && value) {
acc[key] = value;
}
return acc;
}, {});
if (cmdArgs && Object.keys(cmdArgs).length) {
showOverrideMsg(cmdArgs);
}
return cmdArgs;
}
function main(opts) {
const startTime = new Date();
const imagesPath = resolve(__dirname, opts.imageDir);
const outputPath = resolve(__dirname, opts.outputDir);
const recipesPath = resolve(__dirname, opts.recipeDir);
const staticPath = resolve(__dirname, './src/static/');
const templatesPath = resolve(__dirname, './src/templates/');
const options = {
...opts,
imagesPath,
outputPath,
recipesPath,
staticPath,
templatesPath,
};
Promise.all([
readdir(recipesPath),
readdir(imagesPath),
readFile(resolve(templatesPath, 'index.html'), { encoding: 'utf8' }),
readFile(resolve(templatesPath, 'recipe.html'), { encoding: 'utf8' }),
])
.then(async ([markdownFiles, images, indexTemplate, recipeTemplate]) => {
markdownFiles = filterByExtension(markdownFiles, recipesPath, ['.md']);
images = filterByExtension(images, imagesPath, ['.jpg', '.jpeg', '.png', '.webp', '.avif']);
setupOutputDir(outputPath);
copyStatic({ staticPath, imagesPath, outputPath, recipesPath });
makeThumbnails(outputPath, images);
images = swapJpegForAvif(images);
const recipeInfo = await buildRecipes(recipeTemplate, options, markdownFiles, images);
buildRecipeIndex(indexTemplate, options, markdownFiles, images, recipeInfo);
const endTime = new Date();
showDoneMsg(markdownFiles.length, endTime - startTime);
})
.catch((err) => {
console.error(err);
});
}
main({
...configs,
...getCommanLineOverrides(process.argv),
});