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