Skip to content

Instantly share code, notes, and snippets.

@chowey
Created February 18, 2012 22:32
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chowey/1861203 to your computer and use it in GitHub Desktop.
Save chowey/1861203 to your computer and use it in GitHub Desktop.
Jade Syntax Checker
var jade = require('jade'),
runtime = require('jade/lib/runtime'),
spawn = require('child_process').spawn,
fs = require('fs');
function parse(str, filename){
var options = {filename: filename, compileDebug: true};
try {
// Parse
var parser = new jade.Parser(str, filename, options)
, compiler = new (jade.Compiler)(parser.parse(), options)
, js = compiler.compile();
return ''
+ 'var buf = [];\n'
+ js;
} catch (err) {
parser = parser.context();
runtime.rethrow(err, parser.filename, parser.lexer.lineno);
}
}
function checkSyntax(str, filename) {
var fn, err, lineno;
fn = ['var __jade = [{ lineno: 1, filename: ' + JSON.stringify(filename) + ' }];'
, parse(str, filename)].join('\n');
var child = spawn(process.execPath, ['-e', fn]);
child.stderr.setEncoding('utf8');
child.stderr.on('data', function (data) {
var errLines = data.split('\n'),
descLine = errLines[4];
if (/^SyntaxError: /.test(descLine)) {
// Syntax error was found
var infoLine = errLines[1].split(':');
fn = fn.split('\n').slice(0, infoLine[1]);
for (var i = 0; i < fn.length; i++)
if (!/__jade/.test(fn[i]))
fn[i] = '';
fn = fn.join('\n') + '__jade[0].lineno';
lineno = eval(fn);
err = new SyntaxError(descLine.substr(13));
}
});
child.on('exit', function (code, signal) {
if (err)
runtime.rethrow(err, filename, lineno);
else
console.error('No SyntaxError found');
});
}
function checkFile(path) {
fs.readFile(path, 'utf8', function (err, str) {
if (err) throw err;
checkSyntax(str, path);
});
}
checkFile('./test.jade');
- var o = {a:'Hello', b:'world'}
p= o.a
p= o.b
p(class='foo' id='bar') and fail!
@chowey
Copy link
Author

chowey commented Feb 18, 2012

Outputs the following error:

SyntaxError: ./test.jade:4
    2| p= o.a
    3| p= o.b
  > 4| p(class='foo' id='bar') and fail!

Unexpected identifier
    at Socket.<anonymous>
    at Socket.emit (events.js:67:17)
    at Pipe.onread (net.js:342:31)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment