UI for Zipcoin Blue

compile-dots.js 2.4KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. //compile doT templates to js functions
  2. 'use strict';
  3. var glob = require('glob')
  4. , fs = require('fs')
  5. , path = require('path')
  6. , doT = require('dot')
  7. , beautify = require('js-beautify').js_beautify;
  8. var defsRootPath = process.argv[2] || path.join(__dirname, '../lib');
  9. var defs = {};
  10. var defFiles = glob.sync('./dot/**/*.def', { cwd: defsRootPath });
  11. defFiles.forEach(function (f) {
  12. var name = path.basename(f, '.def');
  13. defs[name] = fs.readFileSync(path.join(defsRootPath, f));
  14. });
  15. var filesRootPath = process.argv[3] || path.join(__dirname, '../lib');
  16. var files = glob.sync('./dot/**/*.jst', { cwd: filesRootPath });
  17. var dotjsPath = path.join(filesRootPath, './dotjs');
  18. try { fs.mkdirSync(dotjsPath); } catch(e) {}
  19. console.log('\n\nCompiling:');
  20. var FUNCTION_NAME = /function\s+anonymous\s*\(it[^)]*\)\s*{/;
  21. var OUT_EMPTY_STRING = /out\s*\+=\s*'\s*';/g;
  22. var ISTANBUL = /'(istanbul[^']+)';/g;
  23. var ERROR_KEYWORD = /\$errorKeyword/g;
  24. var ERROR_KEYWORD_OR = /\$errorKeyword\s+\|\|/g;
  25. var VARS = [
  26. '$errs', '$valid', '$lvl', '$data', '$dataLvl',
  27. '$errorKeyword', '$closingBraces', '$schemaPath',
  28. '$validate'
  29. ];
  30. files.forEach(function (f) {
  31. var keyword = path.basename(f, '.jst');
  32. var targetPath = path.join(dotjsPath, keyword + '.js');
  33. var template = fs.readFileSync(path.join(filesRootPath, f));
  34. var code = doT.compile(template, defs);
  35. code = code.toString()
  36. .replace(OUT_EMPTY_STRING, '')
  37. .replace(FUNCTION_NAME, 'function generate_' + keyword + '(it, $keyword, $ruleType) {')
  38. .replace(ISTANBUL, '/* $1 */');
  39. removeAlwaysFalsyInOr();
  40. VARS.forEach(removeUnusedVar);
  41. code = "'use strict';\nmodule.exports = " + code;
  42. code = beautify(code, { indent_size: 2 }) + '\n';
  43. fs.writeFileSync(targetPath, code);
  44. console.log('compiled', keyword);
  45. function removeUnusedVar(v) {
  46. v = v.replace(/\$/g, '\\$$');
  47. var regexp = new RegExp(v + '[^A-Za-z0-9_$]', 'g');
  48. var count = occurrences(regexp);
  49. if (count == 1) {
  50. regexp = new RegExp('var\\s+' + v + '\\s*=[^;]+;|var\\s+' + v + ';');
  51. code = code.replace(regexp, '');
  52. }
  53. }
  54. function removeAlwaysFalsyInOr() {
  55. var countUsed = occurrences(ERROR_KEYWORD);
  56. var countOr = occurrences(ERROR_KEYWORD_OR);
  57. if (countUsed == countOr + 1) code = code.replace(ERROR_KEYWORD_OR, '');
  58. }
  59. function occurrences(regexp) {
  60. return (code.match(regexp) || []).length;
  61. }
  62. });