|
'use strict'; |
|
var fs = require('fs'); |
|
var os = require('os'); |
|
var vm = require('vm'); |
|
|
|
var marked = require('marked'); |
|
var argv = require('minimist')(process.argv.slice(2)); |
|
|
|
var usage = function () { |
|
var helpText = [ |
|
'Usage: erudite [options] /path/to/filename', |
|
'', |
|
' -h, --help show this help text', |
|
' -o, --outfile write to the given file path' |
|
].join('\n'); |
|
process.stdout.write(helpText + '\n\n'); |
|
}; |
|
|
|
var filename = argv._[0]; |
|
var outfile = argv.o || argv.outfile; |
|
var help = argv.h || argv.help; |
|
|
|
if (help || !fs.existsSync(filename)) { |
|
usage(); |
|
process.exit(1); |
|
} |
|
|
|
var content = fs.readFileSync(filename, 'utf8'); |
|
var tokens = marked.lexer(content); |
|
var SEPARATOR = os.EOL + os.EOL; |
|
var codeBlocks = []; |
|
var buf; |
|
|
|
for (var i = 0; i < tokens.length; i++) { |
|
if (tokens[i].type === 'code') { |
|
codeBlocks.push(new Buffer(tokens[i].text)); |
|
codeBlocks.push(new Buffer(SEPARATOR)); |
|
} |
|
} |
|
|
|
codeBlocks.pop(); // remove trailing EOL adding from the while loop |
|
buf = Buffer.concat(codeBlocks); |
|
|
|
if (outfile) { |
|
return write(outfile, buf); |
|
} |
|
|
|
run(buf.toString()); |
|
|
|
function write (output, script) { |
|
fs.writeFileSync(output, script, 'utf8'); |
|
} |
|
|
|
// Basically copied verbatim from CoffeeScript source... |
|
function run (script) { |
|
var ctx = vm.createContext(global); |
|
ctx.__filename = filename; |
|
ctx.__dirname = process.cwd(); |
|
ctx.global = ctx.root = ctx.GLOBAL = ctx; |
|
|
|
var Module = require('module'); |
|
var _module = ctx.module = new Module('eval'); |
|
var _require = ctx.require = function (path) { |
|
return Module._load(path, _module, true); |
|
}; |
|
_module.filename = ctx.__filename; |
|
Object.getOwnPropertyNames(require).forEach(function (r) { |
|
if (['paths', 'caller', 'callee', 'arguments'].indexOf(r) === -1) { |
|
_require[r] = require[r]; |
|
} |
|
}); |
|
_require.paths = _module.paths = Module._nodeModulePaths(process.cwd()); |
|
_require.resolve = function (request) { |
|
Module._resolveFilename(request, _module); |
|
}; |
|
|
|
vm.runInContext(script, ctx); |
|
} |