build.js 27 KB

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