-
-
Notifications
You must be signed in to change notification settings - Fork 8.7k
/
Copy pathgenerate.js
414 lines (377 loc) · 14.5 KB
/
generate.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
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
/**
* Copyright (c) 2017-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
async function execute() {
require('../write-translations.js');
const metadataUtils = require('./metadataUtils');
const blog = require('./blog');
const docs = require('./docs');
const CWD = process.cwd();
const fs = require('fs-extra');
const readMetadata = require('./readMetadata.js');
const path = require('path');
const {minifyCss, isSeparateCss, autoPrefixCss} = require('./utils');
const React = require('react');
const mkdirp = require('mkdirp');
const glob = require('glob');
const chalk = require('chalk');
const Site = require('../core/Site.js');
const env = require('./env.js');
const siteConfig = require(`${CWD}/siteConfig.js`);
const translate = require('./translate.js');
const feed = require('./feed.js');
const sitemap = require('./sitemap.js');
const join = path.join;
const sep = path.sep;
const escapeStringRegexp = require('escape-string-regexp');
const {renderToStaticMarkupWithDoctype} = require('./renderUtils');
const commander = require('commander');
const imagemin = require('imagemin');
const imageminJpegtran = require('imagemin-jpegtran');
const imageminOptipng = require('imagemin-optipng');
const imageminSvgo = require('imagemin-svgo');
const imageminGifsicle = require('imagemin-gifsicle');
commander.option('--skip-image-compression').parse(process.argv);
// create the folder path for a file if it does not exist, then write the file
function writeFileAndCreateFolder(file, content) {
mkdirp.sync(path.dirname(file));
fs.writeFileSync(file, content);
// build extra file for extension-less url if "cleanUrl" siteConfig is true
if (siteConfig.cleanUrl && file.indexOf('index.html') === -1) {
const extraFile = file.replace(/\.html$/, '/index.html');
mkdirp.sync(path.dirname(extraFile));
fs.writeFileSync(extraFile, content);
}
}
console.log('generate.js triggered...');
readMetadata.generateMetadataDocs();
const Metadata = require('../core/metadata.js');
// TODO: what if the project is a github org page? We should not use
// siteConfig.projectName in this case. Otherwise a GitHub org doc URL would
// look weird: https://myorg.github.io/myorg/docs
// TODO: siteConfig.projectName is a misnomer. The actual project name is
// `title`. `projectName` is only used to generate a folder, which isn't
// needed when the project's a GitHub org page
const buildDir = join(CWD, 'build', siteConfig.projectName);
fs.removeSync(join(CWD, 'build'));
// create html files for all docs by going through all doc ids
const mdToHtml = metadataUtils.mdToHtml(Metadata, siteConfig.baseUrl);
Object.keys(Metadata).forEach(id => {
const metadata = Metadata[id];
const file = docs.getFile(metadata);
if (!file) {
return;
}
const rawContent = metadataUtils.extractMetadata(file).rawContent;
const str = docs.getMarkup(rawContent, mdToHtml, metadata);
const targetFile = join(buildDir, metadata.permalink);
writeFileAndCreateFolder(targetFile, str);
// generate english page redirects when languages are enabled
const redirectMarkup = docs.getRedirectMarkup(metadata);
if (!redirectMarkup) {
return;
}
const redirectFile = join(
buildDir,
metadata.permalink.replace('docs/en', 'docs')
);
writeFileAndCreateFolder(redirectFile, redirectMarkup);
});
// copy docs assets if they exist
if (fs.existsSync(join(CWD, '..', readMetadata.getDocsPath(), 'assets'))) {
fs.copySync(
join(CWD, '..', readMetadata.getDocsPath(), 'assets'),
join(buildDir, 'docs', 'assets')
);
}
// create html files for all blog posts (each article)
if (fs.existsSync(join(__dirname, '..', 'core', 'MetadataBlog.js'))) {
fs.removeSync(join(__dirname, '..', 'core', 'MetadataBlog.js'));
}
readMetadata.generateMetadataBlog();
const MetadataBlog = require('../core/MetadataBlog.js');
let files = glob.sync(join(CWD, 'blog', '**', '*.*'));
files
.sort()
.reverse()
.forEach(file => {
// Why normalize? In case we are on Windows.
// Remember the nuance of glob: https://www.npmjs.com/package/glob#windows
const normalizedFile = path.normalize(file);
const extension = path.extname(normalizedFile);
if (extension !== '.md' && extension !== '.markdown') {
return;
}
const urlPath = blog.fileToUrl(normalizedFile);
const blogPost = blog.getPostMarkup(normalizedFile, siteConfig);
if (!blogPost) {
return;
}
const targetFile = join(buildDir, 'blog', urlPath);
writeFileAndCreateFolder(targetFile, blogPost);
});
// create html files for all blog pages (collections of article previews)
const blogPages = blog.getPagesMarkup(MetadataBlog.length, siteConfig);
Object.keys(blogPages).forEach(pagePath => {
const targetFile = join(buildDir, 'blog', pagePath);
writeFileAndCreateFolder(targetFile, blogPages[pagePath]);
});
// create rss files for all blog pages, if there are any blog files
if (MetadataBlog.length > 0) {
let targetFile = join(buildDir, 'blog', 'feed.xml');
writeFileAndCreateFolder(targetFile, feed());
targetFile = join(buildDir, 'blog', 'atom.xml');
writeFileAndCreateFolder(targetFile, feed('atom'));
}
// create sitemap
if (MetadataBlog.length > 0 || Object.keys(Metadata).length > 0) {
sitemap((err, xml) => {
if (!err) {
const targetFile = join(buildDir, 'sitemap.xml');
writeFileAndCreateFolder(targetFile, xml);
}
});
}
// copy blog assets if they exist
if (fs.existsSync(join(CWD, 'blog', 'assets'))) {
fs.copySync(join(CWD, 'blog', 'assets'), join(buildDir, 'blog', 'assets'));
}
// copy all static files from docusaurus
files = glob.sync(join(__dirname, '..', 'static', '**'));
files.forEach(file => {
// Why normalize? In case we are on Windows.
// Remember the nuance of glob: https://www.npmjs.com/package/glob#windows
let targetFile = path.normalize(file);
targetFile = join(
buildDir,
targetFile.split(`${sep}static${sep}`)[1] || ''
);
// parse css files to replace colors according to siteConfig
if (file.match(/\.css$/)) {
let cssContent = fs.readFileSync(file, 'utf8');
if (
!siteConfig.colors ||
!siteConfig.colors.primaryColor ||
!siteConfig.colors.secondaryColor
) {
console.error(
`${chalk.yellow(
'Missing color configuration.'
)} Make sure siteConfig.colors includes primaryColor and secondaryColor fields.`
);
}
Object.keys(siteConfig.colors).forEach(key => {
const color = siteConfig.colors[key];
cssContent = cssContent.replace(new RegExp(`\\$${key}`, 'g'), color);
});
if (siteConfig.fonts) {
Object.keys(siteConfig.fonts).forEach(key => {
const fontString = siteConfig.fonts[key]
.map(font => `"${font}"`)
.join(', ');
cssContent = cssContent.replace(
new RegExp(`\\$${key}`, 'g'),
fontString
);
});
}
mkdirp.sync(path.dirname(targetFile));
fs.writeFileSync(targetFile, cssContent);
} else if (!fs.lstatSync(file).isDirectory()) {
mkdirp.sync(path.dirname(targetFile));
fs.copySync(file, targetFile);
}
});
// Copy all static files from user.
files = glob.sync(join(CWD, 'static', '**'), {dot: true});
files.forEach(file => {
// Why normalize? In case we are on Windows.
// Remember the nuance of glob: https://www.npmjs.com/package/glob#windows
const normalizedFile = path.normalize(file);
// parse css files to replace colors and fonts according to siteConfig
if (
normalizedFile.match(/\.css$/) &&
!isSeparateCss(normalizedFile, siteConfig.separateCss)
) {
const mainCss = join(buildDir, 'css', 'main.css');
let cssContent = fs.readFileSync(normalizedFile, 'utf8');
cssContent = `${fs.readFileSync(mainCss, 'utf8')}\n${cssContent}`;
Object.keys(siteConfig.colors).forEach(key => {
const color = siteConfig.colors[key];
cssContent = cssContent.replace(new RegExp(`\\$${key}`, 'g'), color);
});
if (siteConfig.fonts) {
Object.keys(siteConfig.fonts).forEach(key => {
const fontString = siteConfig.fonts[key]
.map(font => `"${font}"`)
.join(', ');
cssContent = cssContent.replace(
new RegExp(`\\$${key}`, 'g'),
fontString
);
});
}
fs.writeFileSync(mainCss, cssContent);
} else if (
normalizedFile.match(/\.png$|.jpg$|.svg$|.gif$/) &&
!commander.skipImageCompression
) {
const parts = normalizedFile.split(`${sep}static${sep}`);
const targetDirectory = join(
buildDir,
parts[1].substring(0, parts[1].lastIndexOf(sep))
);
mkdirp.sync(path.dirname(targetDirectory));
imagemin([normalizedFile], targetDirectory, {
use: [
imageminOptipng(),
imageminJpegtran(),
imageminSvgo({
plugins: [{removeViewBox: false}],
}),
imageminGifsicle(),
],
});
} else if (!fs.lstatSync(normalizedFile).isDirectory()) {
const parts = normalizedFile.split(`${sep}static${sep}`);
const targetFile = join(buildDir, parts[1]);
mkdirp.sync(path.dirname(targetFile));
fs.copySync(normalizedFile, targetFile);
}
});
// Use cssnano to minify the final combined CSS.
// Use autoprefixer to add vendor prefixes
const mainCss = join(buildDir, 'css', 'main.css');
const cssContent = fs.readFileSync(mainCss, 'utf8');
const minifiedCSS = await minifyCss(cssContent);
const css = await autoPrefixCss(minifiedCSS);
fs.writeFileSync(mainCss, css);
// compile/copy pages from user
const enabledLanguages = env.translation
.enabledLanguages()
.map(lang => lang.tag);
files = glob.sync(join(CWD, 'pages', '**'));
files.forEach(file => {
// Why normalize? In case we are on Windows.
// Remember the nuance of glob: https://www.npmjs.com/package/glob#windows
const normalizedFile = path.normalize(file);
// render .js files to strings
if (normalizedFile.match(/\.js$/)) {
const pageID = path.basename(normalizedFile, '.js');
// make temp file for sake of require paths
const parts = normalizedFile.split('pages');
let tempFile = join(__dirname, '..', 'pages', parts[1]);
tempFile = tempFile.replace(
path.basename(normalizedFile),
`temp${path.basename(normalizedFile)}`
);
mkdirp.sync(path.dirname(tempFile));
fs.copySync(normalizedFile, tempFile);
const ReactComp = require(tempFile);
let targetFile = join(buildDir, parts[1]);
targetFile = targetFile.replace(/\.js$/, '.html');
const regexLang = new RegExp(
`${escapeStringRegexp(`${sep}pages${sep}`)}(.*)${escapeStringRegexp(
sep
)}`
);
const match = regexLang.exec(normalizedFile);
const langParts = match[1].split(sep);
if (langParts.indexOf('en') !== -1) {
// Copy and compile a page for each enabled language from the English file.
for (let i = 0; i < enabledLanguages.length; i++) {
const language = enabledLanguages[i];
// Skip conversion from English file if a file exists for this language.
if (
language === 'en' ||
!fs.existsSync(
normalizedFile.replace(`${sep}en${sep}`, sep + language + sep)
)
) {
translate.setLanguage(language);
const str = renderToStaticMarkupWithDoctype(
<Site
language={language}
config={siteConfig}
title={ReactComp.title}
description={ReactComp.description}
metadata={{id: pageID}}>
<ReactComp language={language} />
</Site>
);
writeFileAndCreateFolder(
// TODO: use path functions
targetFile.replace(`${sep}en${sep}`, sep + language + sep),
str
);
}
}
// write to base level
const language = env.translation.enabled ? 'en' : '';
translate.setLanguage(language);
const str = renderToStaticMarkupWithDoctype(
<Site
title={ReactComp.title}
language={language}
config={siteConfig}
description={ReactComp.description}
metadata={{id: pageID}}>
<ReactComp language={language} />
</Site>
);
writeFileAndCreateFolder(
targetFile.replace(`${sep}en${sep}`, sep),
str
);
} else {
// allow for rendering of other files not in pages/en folder
const language = env.translation.enabled ? 'en' : '';
translate.setLanguage(language);
const str = renderToStaticMarkupWithDoctype(
<Site
title={ReactComp.title}
language={language}
config={siteConfig}
description={ReactComp.description}
metadata={{id: pageID}}>
<ReactComp language={language} />
</Site>
);
writeFileAndCreateFolder(
targetFile.replace(`${sep}en${sep}`, sep),
str
);
}
fs.removeSync(tempFile);
} else if (siteConfig.wrapPagesHTML && normalizedFile.match(/\.html$/)) {
const pageID = path.basename(normalizedFile, '.html');
const parts = normalizedFile.split('pages');
const targetFile = join(buildDir, parts[1]);
const str = renderToStaticMarkupWithDoctype(
<Site language="en" config={siteConfig} metadata={{id: pageID}}>
<div
dangerouslySetInnerHTML={{
__html: fs.readFileSync(normalizedFile, {encoding: 'utf8'}),
}}
/>
</Site>
);
writeFileAndCreateFolder(targetFile, str);
} else if (!fs.lstatSync(normalizedFile).isDirectory()) {
// copy other non .js files
const parts = normalizedFile.split('pages');
const targetFile = join(buildDir, parts[1]);
mkdirp.sync(path.dirname(targetFile));
fs.copySync(normalizedFile, targetFile);
}
});
// Generate CNAME file if a custom domain is specified in siteConfig
if (siteConfig.cname) {
const targetFile = join(buildDir, 'CNAME');
fs.writeFileSync(targetFile, siteConfig.cname);
}
}
module.exports = execute;