build.js 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914
  1. /* global module require process */
  2. /* eslint no-undef: "error" */
  3. /* eslint no-console: "off" */
  4. /*
  5. This entire file is one giant hack and really needs to be cleaned up!
  6. */
  7. 'use strict';
  8. const requiredNodeVersion = 12;
  9. if (parseInt((/^v(\d+)\./).exec(process.version)[1]) < requiredNodeVersion) {
  10. throw Error(`requires at least node: ${requiredNodeVersion}`);
  11. }
  12. module.exports = function(settings) { // wrapper in case we're in module_context mode
  13. const hackyProcessSelectFiles = settings.filenames !== undefined;
  14. const cache = new (require('inmemfilecache'))();
  15. const Feed = require('feed').Feed;
  16. const fs = require('fs');
  17. const glob = require('glob');
  18. const Handlebars = require('handlebars');
  19. const hanson = require('hanson');
  20. const marked = require('marked');
  21. const path = require('path');
  22. const Promise = require('promise');
  23. const sitemap = require('sitemap');
  24. const utils = require('./utils');
  25. const moment = require('moment');
  26. const url = require('url');
  27. //process.title = 'build';
  28. let numErrors = 0;
  29. function error(...args) {
  30. ++numErrors;
  31. console.error(...args);
  32. }
  33. const executeP = Promise.denodeify(utils.execute);
  34. marked.setOptions({
  35. rawHtml: true,
  36. //pedantic: true,
  37. });
  38. function applyObject(src, dst) {
  39. Object.keys(src).forEach(function(key) {
  40. dst[key] = src[key];
  41. });
  42. return dst;
  43. }
  44. function mergeObjects() {
  45. const merged = {};
  46. Array.prototype.slice.call(arguments).forEach(function(src) {
  47. applyObject(src, merged);
  48. });
  49. return merged;
  50. }
  51. function readFile(fileName) {
  52. return cache.readFileSync(fileName, 'utf-8');
  53. }
  54. function readHANSON(fileName) {
  55. const text = readFile(fileName);
  56. try {
  57. return hanson.parse(text);
  58. } catch (e) {
  59. throw new Error(`can not parse: ${fileName}: ${e}`);
  60. }
  61. }
  62. function writeFileIfChanged(fileName, content) {
  63. if (fs.existsSync(fileName)) {
  64. const old = readFile(fileName);
  65. if (content === old) {
  66. return;
  67. }
  68. }
  69. fs.writeFileSync(fileName, content);
  70. console.log('Wrote: ' + fileName); // eslint-disable-line
  71. }
  72. function copyFile(src, dst) {
  73. writeFileIfChanged(dst, readFile(src));
  74. }
  75. function replaceParams(str, params) {
  76. const template = Handlebars.compile(str);
  77. if (Array.isArray(params)) {
  78. params = mergeObjects.apply(null, params.slice().reverse());
  79. }
  80. return template(params);
  81. }
  82. function encodeParams(params) {
  83. const values = Object.values(params).filter(v => v);
  84. if (!values.length) {
  85. return '';
  86. }
  87. return '&' + Object.entries(params).map((kv) => {
  88. return `${encodeURIComponent(kv[0])}=${encodeURIComponent(kv[1])}`;
  89. }).join('&');
  90. }
  91. function encodeQuery(query) {
  92. if (!query) {
  93. return '';
  94. }
  95. return '?' + query.split('&').map(function(pair) {
  96. return pair.split('=').map(function(kv) {
  97. return encodeURIComponent(decodeURIComponent(kv));
  98. }).join('=');
  99. }).join('&');
  100. }
  101. function encodeUrl(src) {
  102. const u = url.parse(src);
  103. u.search = encodeQuery(u.query);
  104. return url.format(u);
  105. }
  106. function TemplateManager() {
  107. const templates = {};
  108. this.apply = function(filename, params) {
  109. let template = templates[filename];
  110. if (!template) {
  111. template = Handlebars.compile(readFile(filename));
  112. templates[filename] = template;
  113. }
  114. if (Array.isArray(params)) {
  115. params = mergeObjects.apply(null, params.slice().reverse());
  116. }
  117. return template(params);
  118. };
  119. }
  120. const templateManager = new TemplateManager();
  121. Handlebars.registerHelper('include', function(filename, options) {
  122. let context;
  123. if (options && options.hash && options.hash.filename) {
  124. const varName = options.hash.filename;
  125. filename = options.data.root[varName];
  126. context = Object.assign({}, options.data.root, options.hash);
  127. } else {
  128. context = options.data.root;
  129. }
  130. return templateManager.apply(filename, context);
  131. });
  132. Handlebars.registerHelper('example', function(options) {
  133. options.hash.width = options.hash.width ? 'width: ' + options.hash.width + 'px;' : '';
  134. options.hash.height = options.hash.height ? 'height: ' + options.hash.height + 'px;' : '';
  135. options.hash.caption = options.hash.caption || options.data.root.defaultExampleCaption;
  136. options.hash.examplePath = options.data.root.examplePath;
  137. options.hash.encodedUrl = encodeURIComponent(encodeUrl(options.hash.url));
  138. options.hash.url = encodeUrl(options.hash.url);
  139. options.hash.params = encodeParams({
  140. startPane: options.hash.startPane,
  141. });
  142. return templateManager.apply('build/templates/example.template', options.hash);
  143. });
  144. Handlebars.registerHelper('diagram', function(options) {
  145. options.hash.width = options.hash.width || '400';
  146. options.hash.height = options.hash.height || '300';
  147. options.hash.examplePath = options.data.root.examplePath;
  148. options.hash.className = options.hash.className || '';
  149. options.hash.url = encodeUrl(options.hash.url);
  150. return templateManager.apply('build/templates/diagram.template', options.hash);
  151. });
  152. Handlebars.registerHelper('image', function(options) {
  153. options.hash.examplePath = options.data.root.examplePath;
  154. options.hash.className = options.hash.className || '';
  155. options.hash.caption = options.hash.caption || undefined;
  156. if (options.hash.url.substring(0, 4) === 'http') {
  157. options.hash.examplePath = '';
  158. }
  159. return templateManager.apply('build/templates/image.template', options.hash);
  160. });
  161. Handlebars.registerHelper('selected', function(options) {
  162. const key = options.hash.key;
  163. const value = options.hash.value;
  164. const re = options.hash.re;
  165. const sub = options.hash.sub;
  166. const a = this[key];
  167. let b = options.data.root[value];
  168. if (re) {
  169. const r = new RegExp(re);
  170. b = b.replace(r, sub);
  171. }
  172. return a === b ? 'selected' : '';
  173. });
  174. function slashify(s) {
  175. return s.replace(/\\/g, '/');
  176. }
  177. function articleFilter(f) {
  178. if (hackyProcessSelectFiles) {
  179. if (!settings.filenames.has(f)) {
  180. return false;
  181. }
  182. }
  183. return !process.env['ARTICLE_FILTER'] || f.indexOf(process.env['ARTICLE_FILTER']) >= 0;
  184. }
  185. const Builder = function(outBaseDir, options) {
  186. const g_articlesByLang = {};
  187. let g_articles = [];
  188. let g_langInfo;
  189. let g_originalLangInfo;
  190. const g_langDB = {};
  191. const g_outBaseDir = outBaseDir;
  192. const g_origPath = options.origPath;
  193. const g_originalByFileName = {};
  194. const toc = readHANSON('toc.hanson');
  195. // These are the english articles.
  196. const g_origArticles = glob.sync(path.join(g_origPath, '*.md'))
  197. .map(a => path.basename(a))
  198. .filter(a => a !== 'index.md')
  199. .filter(articleFilter);
  200. const extractHeader = (function() {
  201. const headerRE = /([A-Z0-9_-]+): (.*?)$/i;
  202. return function(content) {
  203. const metaData = { };
  204. const lines = content.split('\n');
  205. for (;;) {
  206. const line = lines[0].trim();
  207. const m = headerRE.exec(line);
  208. if (!m) {
  209. break;
  210. }
  211. metaData[m[1].toLowerCase()] = m[2];
  212. lines.shift();
  213. }
  214. return {
  215. content: lines.join('\n'),
  216. headers: metaData,
  217. };
  218. };
  219. }());
  220. const parseMD = function(content) {
  221. return extractHeader(content);
  222. };
  223. const loadMD = function(contentFileName) {
  224. const content = cache.readFileSync(contentFileName, 'utf-8');
  225. const data = parseMD(content);
  226. data.link = contentFileName.replace(/\\/g, '/').replace(/\.md$/, '.html');
  227. return data;
  228. };
  229. function extractHandlebars(content) {
  230. const tripleRE = /\{\{\{.*?\}\}\}/g;
  231. const doubleRE = /\{\{\{.*?\}\}\}/g;
  232. let numExtractions = 0;
  233. const extractions = {
  234. };
  235. function saveHandlebar(match) {
  236. const id = '==HANDLEBARS_ID_' + (++numExtractions) + '==';
  237. extractions[id] = match;
  238. return id;
  239. }
  240. content = content.replace(tripleRE, saveHandlebar);
  241. content = content.replace(doubleRE, saveHandlebar);
  242. return {
  243. content: content,
  244. extractions: extractions,
  245. };
  246. }
  247. function insertHandlebars(info, content) {
  248. const handlebarRE = /==HANDLEBARS_ID_\d+==/g;
  249. function restoreHandlebar(match) {
  250. const value = info.extractions[match];
  251. if (value === undefined) {
  252. throw new Error('no match restoring handlebar for: ' + match);
  253. }
  254. return value;
  255. }
  256. content = content.replace(handlebarRE, restoreHandlebar);
  257. return content;
  258. }
  259. function isSameDomain(url, pageUrl) {
  260. const fdq1 = new URL(pageUrl);
  261. const fdq2 = new URL(url, pageUrl);
  262. return fdq1.origin === fdq2.origin;
  263. }
  264. function getUrlPath(url) {
  265. // yes, this is a hack
  266. const q = url.indexOf('?');
  267. return q >= 0 ? url.substring(0, q) : url;
  268. }
  269. // Try top fix relative links. This *should* only
  270. // happen in translations
  271. const iframeLinkRE = /(<iframe[\s\S]*?\s+src=")(.*?)(")/g;
  272. const imgLinkRE = /(<img[\s\S]*?\s+src=")(.*?)(")/g;
  273. const aLinkRE = /(<a[\s\S]*?\s+href=")(.*?)(")/g;
  274. const mdLinkRE = /(\[[\s\S]*?\]\()(.*?)(\))/g;
  275. const handlebarLinkRE = /({{{.*?\s+url=")(.*?)(")/g;
  276. const linkREs = [
  277. iframeLinkRE,
  278. imgLinkRE,
  279. aLinkRE,
  280. mdLinkRE,
  281. handlebarLinkRE,
  282. ];
  283. function hackRelLinks(content, pageUrl) {
  284. // console.log('---> pageUrl:', pageUrl);
  285. function fixRelLink(m, prefix, url, suffix) {
  286. if (isSameDomain(url, pageUrl)) {
  287. // a link that starts with "../" should be "../../" if it's in a translation
  288. // a link that starts with "resources" should be "../resources" if it's in a translation
  289. if (url.startsWith('../') ||
  290. url.startsWith('resources')) {
  291. // console.log(' url:', url);
  292. return `${prefix}../${url}${suffix}`;
  293. }
  294. }
  295. return m;
  296. }
  297. return content
  298. .replace(imgLinkRE, fixRelLink)
  299. .replace(aLinkRE, fixRelLink)
  300. .replace(iframeLinkRE, fixRelLink);
  301. }
  302. /**
  303. * Get all the local urls based on a regex that has <prefix><url><suffix>
  304. */
  305. function getUrls(regex, str) {
  306. const links = new Set();
  307. let m;
  308. do {
  309. m = regex.exec(str);
  310. if (m && m[2][0] !== '#' && isSameDomain(m[2], 'http://example.com/a/b/c/d')) {
  311. links.add(getUrlPath(m[2]));
  312. }
  313. } while (m);
  314. return links;
  315. }
  316. /**
  317. * Get all the local links in content
  318. */
  319. function getLinks(content) {
  320. return new Set(linkREs.map(re => [...getUrls(re, content)]).flat());
  321. }
  322. function fixUrls(regex, content, origLinks) {
  323. return content.replace(regex, (m, prefix, url, suffix) => {
  324. const q = url.indexOf('?');
  325. const urlPath = q >= 0 ? url.substring(0, q) : url;
  326. const urlQuery = q >= 0 ? url.substring(q) : '';
  327. if (!origLinks.has(urlPath) &&
  328. isSameDomain(urlPath, 'https://foo.com/a/b/c/d.html') &&
  329. !(/\/..\/^/.test(urlPath)) && // hacky test for link to main page. Example /webgl/lessons/ja/
  330. urlPath[0] !== '#') { // test for same page anchor -- bad test :(
  331. for (const origLink of origLinks) {
  332. if (urlPath.endsWith(origLink)) {
  333. const newUrl = `${origLink}${urlQuery}`;
  334. console.log(' fixing:', url, 'to', newUrl);
  335. return `${prefix}${newUrl}${suffix}`;
  336. }
  337. }
  338. error('could not fix:', url);
  339. }
  340. return m;
  341. });
  342. }
  343. const applyTemplateToContent = function(templatePath, contentFileName, outFileName, opt_extra, data) {
  344. // Call prep's Content which parses the HTML. This helps us find missing tags
  345. // should probably call something else.
  346. //Convert(md_content)
  347. const relativeOutName = slashify(outFileName).substring(g_outBaseDir.length);
  348. const pageUrl = `${settings.baseUrl}${relativeOutName}`;
  349. const metaData = data.headers;
  350. const content = data.content;
  351. //console.log(JSON.stringify(metaData, undefined, ' '));
  352. const info = extractHandlebars(content);
  353. let html = marked(info.content);
  354. // HACK! :-(
  355. // There's probably a way to do this in marked
  356. html = html.replace(/<pre><code/g, '<pre class="prettyprint"><code');
  357. // HACK! :-(
  358. if (opt_extra && opt_extra.home && opt_extra.home.length > 1) {
  359. html = hackRelLinks(html, pageUrl);
  360. }
  361. html = insertHandlebars(info, html);
  362. html = replaceParams(html, [opt_extra, g_langInfo]);
  363. const pathRE = new RegExp(`^\\/${settings.rootFolder}\\/lessons\\/$`);
  364. const langs = Object.keys(g_langDB).map((name) => {
  365. const lang = g_langDB[name];
  366. const url = slashify(path.join(lang.basePath, path.basename(outFileName)))
  367. .replace('index.html', '')
  368. .replace(pathRE, '/');
  369. return {
  370. lang: lang.lang,
  371. language: lang.language,
  372. url: url,
  373. };
  374. });
  375. metaData['content'] = html;
  376. metaData['langs'] = langs;
  377. metaData['src_file_name'] = slashify(contentFileName);
  378. metaData['dst_file_name'] = relativeOutName;
  379. metaData['basedir'] = '';
  380. metaData['toc'] = opt_extra.toc;
  381. metaData['tocHtml'] = g_langInfo.tocHtml;
  382. metaData['templateOptions'] = opt_extra.templateOptions;
  383. metaData['langInfo'] = g_langInfo;
  384. metaData['url'] = pageUrl;
  385. metaData['relUrl'] = relativeOutName;
  386. metaData['screenshot'] = `${settings.baseUrl}/${settings.rootFolder}/lessons/resources/${settings.siteThumbnail}`;
  387. const basename = path.basename(contentFileName, '.md');
  388. ['.jpg', '.png'].forEach(function(ext) {
  389. const filename = path.join(settings.rootFolder, 'lessons', 'screenshots', basename + ext);
  390. if (fs.existsSync(filename)) {
  391. metaData['screenshot'] = `${settings.baseUrl}/${settings.rootFolder}/lessons/screenshots/${basename}${ext}`;
  392. }
  393. });
  394. const output = templateManager.apply(templatePath, metaData);
  395. writeFileIfChanged(outFileName, output);
  396. return metaData;
  397. };
  398. const applyTemplateToFile = function(templatePath, contentFileName, outFileName, opt_extra) {
  399. console.log('processing: ', contentFileName); // eslint-disable-line
  400. opt_extra = opt_extra || {};
  401. const data = loadMD(contentFileName);
  402. const metaData = applyTemplateToContent(templatePath, contentFileName, outFileName, opt_extra, data);
  403. g_articles.push(metaData);
  404. };
  405. const applyTemplateToFiles = function(templatePath, filesSpec, extra) {
  406. const files = glob
  407. .sync(filesSpec)
  408. .sort()
  409. .filter(articleFilter);
  410. const byFilename = {};
  411. files.forEach((fileName) => {
  412. const data = loadMD(fileName);
  413. if (!data.headers.category) {
  414. throw new Error(`no catgeory for article: ${fileName}`);
  415. }
  416. byFilename[path.basename(fileName)] = data;
  417. });
  418. // HACK
  419. if (extra.lang === 'en') {
  420. Object.assign(g_originalByFileName, byFilename);
  421. g_originalLangInfo = g_langInfo;
  422. }
  423. function getLocalizedCategory(category) {
  424. const localizedCategory = g_langInfo.categoryMapping[category];
  425. if (localizedCategory) {
  426. return localizedCategory;
  427. }
  428. console.error(`no localization for category: ${category}`);
  429. const categoryName = g_originalLangInfo.categoryMapping[category];
  430. if (!categoryName) {
  431. throw new Error(`no English mapping for category: ${category}`);
  432. }
  433. return categoryName;
  434. }
  435. function addLangToLink(link) {
  436. return extra.lang === 'en'
  437. ? link
  438. : `${path.dirname(link)}/${extra.lang}/${path.basename(link)}`;
  439. }
  440. function tocLink(fileName) {
  441. let data = byFilename[fileName];
  442. let link;
  443. if (data) {
  444. link = data.link;
  445. } else {
  446. data = g_originalByFileName[fileName];
  447. link = addLangToLink(data.link);
  448. }
  449. const toc = data.headers.toc;
  450. if (toc === '#') {
  451. return [...data.content.matchAll(/<a\s*id="(.*?)"\s*data-toc="(.*?)"\s*><\/a>/g)].map(([, id, title]) => {
  452. const hashlink = `${link}#${id}`;
  453. return `<li><a href="/${hashlink}">${title}</a></li>`;
  454. }).join('\n');
  455. }
  456. return `<li><a href="/${link}">${toc}</a></li>`;
  457. }
  458. function makeToc(toc) {
  459. return `<ul>${
  460. Object.entries(toc).map(([category, files]) => ` <li>${getLocalizedCategory(category)}</li>
  461. <ul>
  462. ${Array.isArray(files)
  463. ? files.map(tocLink).join('\n')
  464. : makeToc(files)
  465. }
  466. </ul>`
  467. ).join('\n')
  468. }</ul>`;
  469. }
  470. g_langInfo.tocHtml = makeToc(toc);
  471. files.forEach(function(fileName) {
  472. const ext = path.extname(fileName);
  473. const baseName = fileName.substr(0, fileName.length - ext.length);
  474. const outFileName = path.join(outBaseDir, baseName + '.html');
  475. applyTemplateToFile(templatePath, fileName, outFileName, extra);
  476. });
  477. };
  478. const addArticleByLang = function(article, lang) {
  479. const filename = path.basename(article.dst_file_name);
  480. let articleInfo = g_articlesByLang[filename];
  481. const url = `${settings.baseUrl}${article.dst_file_name}`;
  482. if (!articleInfo) {
  483. articleInfo = {
  484. url: url,
  485. changefreq: 'monthly',
  486. links: [],
  487. };
  488. g_articlesByLang[filename] = articleInfo;
  489. }
  490. articleInfo.links.push({
  491. url: url,
  492. lang: lang,
  493. });
  494. };
  495. const getLanguageSelection = function(lang) {
  496. const lessons = lang.lessons;
  497. const langInfo = readHANSON(path.join(lessons, 'langinfo.hanson'));
  498. langInfo.langCode = langInfo.langCode || lang.lang;
  499. langInfo.home = lang.home;
  500. g_langDB[lang.lang] = {
  501. lang: lang.lang,
  502. language: langInfo.language,
  503. basePath: '/' + lessons,
  504. langInfo: langInfo,
  505. };
  506. };
  507. this.preProcess = function(langs) {
  508. langs.forEach(getLanguageSelection);
  509. };
  510. this.process = function(options) {
  511. console.log('Processing Lang: ' + options.lang); // eslint-disable-line
  512. g_articles = [];
  513. g_langInfo = g_langDB[options.lang].langInfo;
  514. applyTemplateToFiles(options.template, path.join(options.lessons, settings.lessonGrep), options);
  515. const articlesFilenames = g_articles.map(a => path.basename(a.src_file_name));
  516. // should do this first was easier to add here
  517. if (options.lang !== 'en') {
  518. const existing = g_origArticles.filter(name => articlesFilenames.indexOf(name) >= 0);
  519. existing.forEach((name) => {
  520. const origMdFilename = path.join(g_origPath, name);
  521. const transMdFilename = path.join(g_origPath, options.lang, name);
  522. const origLinks = getLinks(loadMD(origMdFilename).content);
  523. const transLinks = getLinks(loadMD(transMdFilename).content);
  524. if (process.env['ARTICLE_VERBOSE']) {
  525. console.log('---[', transMdFilename, ']---');
  526. console.log('origLinks: ---\n ', [...origLinks].join('\n '));
  527. console.log('transLinks: ---\n ', [...transLinks].join('\n '));
  528. }
  529. let show = true;
  530. transLinks.forEach((link) => {
  531. if (!origLinks.has(link)) {
  532. if (show) {
  533. show = false;
  534. error('---[', transMdFilename, ']---');
  535. }
  536. error(' link:[', link, '] not found in English file');
  537. }
  538. });
  539. if (!show && process.env['ARTICLE_FIX']) {
  540. // there was an error, try to auto-fix
  541. let fixedMd = fs.readFileSync(transMdFilename, {encoding: 'utf8'});
  542. linkREs.forEach((re) => {
  543. fixedMd = fixUrls(re, fixedMd, origLinks);
  544. });
  545. fs.writeFileSync(transMdFilename, fixedMd);
  546. }
  547. });
  548. }
  549. if (hackyProcessSelectFiles) {
  550. return Promise.resolve();
  551. }
  552. // generate place holders for non-translated files
  553. const missing = g_origArticles.filter(name => articlesFilenames.indexOf(name) < 0);
  554. missing.forEach(name => {
  555. const ext = path.extname(name);
  556. const baseName = name.substr(0, name.length - ext.length);
  557. const outFileName = path.join(outBaseDir, options.lessons, baseName + '.html');
  558. const data = Object.assign({}, loadMD(path.join(g_origPath, name)));
  559. data.content = g_langInfo.missing;
  560. const extra = {
  561. origLink: '/' + slashify(path.join(g_origPath, baseName + '.html')),
  562. toc: options.toc,
  563. };
  564. console.log(' generating missing:', outFileName); // eslint-disable-line
  565. applyTemplateToContent(
  566. 'build/templates/missing.template',
  567. path.join(options.lessons, 'langinfo.hanson'),
  568. outFileName,
  569. extra,
  570. data);
  571. });
  572. function utcMomentFromGitLog(result, filename, timeType) {
  573. const dateStr = result.stdout.split('\n')[0].trim();
  574. const utcDateStr = dateStr
  575. .replace(/"/g, '') // WTF to these quotes come from!??!
  576. .replace(' ', 'T')
  577. .replace(' ', '')
  578. .replace(/(\d\d)$/, ':$1');
  579. const m = moment.utc(utcDateStr);
  580. if (m.isValid()) {
  581. return m;
  582. }
  583. const stat = fs.statSync(filename);
  584. return moment(stat[timeType]);
  585. }
  586. const tasks = g_articles.map((article) => {
  587. return function() {
  588. return executeP('git', [
  589. 'log',
  590. '--format="%ci"',
  591. '--name-only',
  592. '--diff-filter=A',
  593. article.src_file_name,
  594. ]).then((result) => {
  595. article.dateAdded = utcMomentFromGitLog(result, article.src_file_name, 'ctime');
  596. });
  597. };
  598. }).concat(g_articles.map((article) => {
  599. return function() {
  600. return executeP('git', [
  601. 'log',
  602. '--format="%ci"',
  603. '--name-only',
  604. '--max-count=1',
  605. article.src_file_name,
  606. ]).then((result) => {
  607. article.dateModified = utcMomentFromGitLog(result, article.src_file_name, 'mtime');
  608. });
  609. };
  610. }));
  611. return tasks.reduce(function(cur, next){
  612. return cur.then(next);
  613. }, Promise.resolve()).then(function() {
  614. let articles = g_articles.filter(function(article) {
  615. return article.dateAdded !== undefined;
  616. });
  617. articles = articles.sort(function(a, b) {
  618. return b.dateAdded - a.dateAdded;
  619. });
  620. if (articles.length) {
  621. const feed = new Feed({
  622. title: g_langInfo.title,
  623. description: g_langInfo.description,
  624. link: g_langInfo.link,
  625. image: `${settings.baseUrl}/${settings.rootFolder}/lessons/resources/${settings.siteThumbnail}`,
  626. date: articles[0].dateModified.toDate(),
  627. published: articles[0].dateModified.toDate(),
  628. updated: articles[0].dateModified.toDate(),
  629. author: {
  630. name: `${settings.siteName} Contributors`,
  631. link: `${settings.baseUrl}/contributors.html`,
  632. },
  633. });
  634. articles.forEach(function(article) {
  635. feed.addItem({
  636. title: article.title,
  637. link: `${settings.baseUrl}${article.dst_file_name}`,
  638. description: '',
  639. author: [
  640. {
  641. name: `${settings.siteName} Contributors`,
  642. link: `${settings.baseUrl}/contributors.html`,
  643. },
  644. ],
  645. // contributor: [
  646. // ],
  647. date: article.dateModified.toDate(),
  648. published: article.dateAdded.toDate(),
  649. // image: posts[key].image
  650. });
  651. addArticleByLang(article, options.lang);
  652. });
  653. try {
  654. const outPath = path.join(g_outBaseDir, options.lessons, 'atom.xml');
  655. console.log('write:', outPath); // eslint-disable-line
  656. writeFileIfChanged(outPath, feed.atom1());
  657. } catch (err) {
  658. return Promise.reject(err);
  659. }
  660. } else {
  661. console.log('no articles!'); // eslint-disable-line
  662. }
  663. return Promise.resolve();
  664. }).then(function() {
  665. // this used to insert a table of contents
  666. // but it was useless being auto-generated
  667. applyTemplateToFile('build/templates/index.template', path.join(options.lessons, 'index.md'), path.join(g_outBaseDir, options.lessons, 'index.html'), {
  668. table_of_contents: '',
  669. templateOptions: g_langInfo,
  670. tocHtml: g_langInfo.tocHtml,
  671. });
  672. return Promise.resolve();
  673. }, function(err) {
  674. error('ERROR!:');
  675. error(err);
  676. if (err.stack) {
  677. error(err.stack); // eslint-disable-line
  678. }
  679. throw new Error(err.toString());
  680. });
  681. };
  682. this.writeGlobalFiles = function() {
  683. const sm = sitemap.createSitemap({
  684. hostname: settings.baseUrl,
  685. cacheTime: 600000,
  686. });
  687. const articleLangs = { };
  688. Object.keys(g_articlesByLang).forEach(function(filename) {
  689. const article = g_articlesByLang[filename];
  690. const langs = {};
  691. article.links.forEach(function(link) {
  692. langs[link.lang] = true;
  693. });
  694. articleLangs[filename] = langs;
  695. sm.add(article);
  696. });
  697. // var langInfo = {
  698. // articles: articleLangs,
  699. // langs: g_langDB,
  700. // };
  701. // var langJS = 'window.langDB = ' + JSON.stringify(langInfo, null, 2);
  702. // writeFileIfChanged(path.join(g_outBaseDir, 'langdb.js'), langJS);
  703. writeFileIfChanged(path.join(g_outBaseDir, 'sitemap.xml'), sm.toString());
  704. copyFile(path.join(g_outBaseDir, `${settings.rootFolder}/lessons/atom.xml`), path.join(g_outBaseDir, 'atom.xml'));
  705. copyFile(path.join(g_outBaseDir, `${settings.rootFolder}/lessons/index.html`), path.join(g_outBaseDir, 'index.html'));
  706. applyTemplateToFile('build/templates/index.template', 'contributors.md', path.join(g_outBaseDir, 'contributors.html'), {
  707. table_of_contents: '',
  708. templateOptions: '',
  709. });
  710. {
  711. const filename = path.join(settings.outDir, 'link-check.html');
  712. const html = `
  713. <html>
  714. <body>
  715. ${langs.map(lang => `<a href="${lang.home}">${lang.lang}</a>`).join('\n')}
  716. </body>
  717. </html>
  718. `;
  719. writeFileIfChanged(filename, html);
  720. }
  721. };
  722. };
  723. const b = new Builder(settings.outDir, {
  724. origPath: `${settings.rootFolder}/lessons`, // english articles
  725. });
  726. const readdirs = function(dirpath) {
  727. const dirsOnly = function(filename) {
  728. const stat = fs.statSync(filename);
  729. return stat.isDirectory();
  730. };
  731. const addPath = function(filename) {
  732. return path.join(dirpath, filename);
  733. };
  734. return fs.readdirSync(`${settings.rootFolder}/lessons`)
  735. .map(addPath)
  736. .filter(dirsOnly);
  737. };
  738. const isLangFolder = function(dirname) {
  739. const filename = path.join(dirname, 'langinfo.hanson');
  740. return fs.existsSync(filename);
  741. };
  742. const pathToLang = function(filename) {
  743. const lang = path.basename(filename);
  744. const lessonBase = `${settings.rootFolder}/lessons`;
  745. const lessons = `${lessonBase}/${lang}`;
  746. return {
  747. lang,
  748. toc: `${settings.rootFolder}/lessons/${lang}/toc.html`,
  749. lessons: `${lessonBase}/${lang}`,
  750. template: 'build/templates/lesson.template',
  751. examplePath: `/${lessonBase}/`,
  752. home: `/${lessons}/`,
  753. };
  754. };
  755. let langs = [
  756. // English is special (sorry it's where I started)
  757. {
  758. template: 'build/templates/lesson.template',
  759. lessons: `${settings.rootFolder}/lessons`,
  760. lang: 'en',
  761. toc: `${settings.rootFolder}/lessons/toc.html`,
  762. examplePath: `/${settings.rootFolder}/lessons/`,
  763. home: '/',
  764. },
  765. ];
  766. langs = langs.concat(readdirs(`${settings.rootFolder}/lessons`)
  767. .filter(isLangFolder)
  768. .map(pathToLang));
  769. b.preProcess(langs);
  770. if (hackyProcessSelectFiles) {
  771. const langsInFilenames = new Set();
  772. [...settings.filenames].forEach((filename) => {
  773. const m = /lessons\/(\w{2}|\w{5})\//.exec(filename);
  774. const lang = m ? m[1] : 'en';
  775. langsInFilenames.add(lang);
  776. });
  777. langs = langs.filter(lang => langsInFilenames.has(lang.lang));
  778. }
  779. const tasks = langs.map(function(lang) {
  780. return function() {
  781. return b.process(lang);
  782. };
  783. });
  784. return tasks.reduce(function(cur, next) {
  785. return cur.then(next);
  786. }, Promise.resolve()).then(function() {
  787. if (!hackyProcessSelectFiles) {
  788. b.writeGlobalFiles(langs);
  789. }
  790. return numErrors ? Promise.reject(new Error(`${numErrors} errors`)) : Promise.resolve();
  791. }).finally(() => {
  792. cache.clear();
  793. });
  794. };