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