1
0
Fork 0
mirror of https://github.com/jashkenas/coffeescript.git synced 2022-11-09 12:23:24 -05:00
jashkenas--coffeescript/lib/coffee-script/command.js

525 lines
15 KiB
JavaScript
Raw Normal View History

2013-06-02 01:37:45 -04:00
// Generated by CoffeeScript 1.6.3
(function() {
var BANNER, CoffeeScript, EventEmitter, SWITCHES, compileJoin, compileOptions, compilePath, compileScript, compileStdio, exec, forkNode, fs, helpers, hidden, joinTimeout, mkdirp, notSources, optionParser, optparse, opts, outputPath, parseOptions, path, printLine, printTokens, printWarn, removeSource, removeSourceDir, silentUnlink, sourceCode, sources, spawn, timeLog, usage, useWinPathSep, version, wait, watch, watchDir, watchedDirs, writeJs, _ref,
__indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; };
fs = require('fs');
path = require('path');
2010-11-04 23:05:04 -04:00
helpers = require('./helpers');
optparse = require('./optparse');
CoffeeScript = require('./coffee-script');
mkdirp = require('mkdirp');
_ref = require('child_process'), spawn = _ref.spawn, exec = _ref.exec;
EventEmitter = require('events').EventEmitter;
useWinPathSep = path.sep === '\\';
helpers.extend(CoffeeScript, new EventEmitter);
printLine = function(line) {
return process.stdout.write(line + '\n');
};
printWarn = function(line) {
return process.stderr.write(line + '\n');
};
hidden = function(file) {
2012-02-26 11:48:33 -05:00
return /^\.|~$/.test(file);
};
2012-02-26 11:48:33 -05:00
BANNER = 'Usage: coffee [options] path/to/script.coffee -- [args]\n\nIf called without options, `coffee` will run your script.';
SWITCHES = [['-b', '--bare', 'compile without a top-level function wrapper'], ['-c', '--compile', 'compile to JavaScript and save as .js files'], ['-e', '--eval', 'pass a string from the command line as input'], ['-h', '--help', 'display this help message'], ['-i', '--interactive', 'run an interactive CoffeeScript REPL'], ['-j', '--join [FILE]', 'concatenate the source CoffeeScript before compiling'], ['-m', '--map', 'generate source map and save as .map files'], ['-n', '--nodes', 'print out the parse tree that the parser produces'], ['--nodejs [ARGS]', 'pass options directly to the "node" binary'], ['--no-header', 'suppress the "Generated by" header'], ['-o', '--output [DIR]', 'set the output directory for compiled JavaScript'], ['-p', '--print', 'print out the compiled JavaScript'], ['-s', '--stdio', 'listen for and compile scripts over stdio'], ['-l', '--literate', 'treat stdio as literate style coffee-script'], ['-t', '--tokens', 'print out the tokens that the lexer/rewriter produce'], ['-v', '--version', 'display the version number'], ['-w', '--watch', 'watch scripts for changes and rerun commands']];
opts = {};
sources = [];
sourceCode = [];
notSources = {};
watchedDirs = {};
optionParser = null;
exports.run = function() {
var literals, replCliOpts, source, _i, _len, _ref1, _results;
parseOptions();
replCliOpts = {
useGlobal: true
};
2012-04-10 14:57:45 -04:00
if (opts.nodejs) {
return forkNode();
}
if (opts.help) {
return usage();
}
if (opts.version) {
return version();
}
if (opts.interactive) {
return require('./repl').start(replCliOpts);
2012-04-10 14:57:45 -04:00
}
if (opts.stdio) {
return compileStdio();
}
if (opts["eval"]) {
return compileScript(null, opts["arguments"][0]);
2012-04-10 14:57:45 -04:00
}
if (!opts["arguments"].length) {
return require('./repl').start(replCliOpts);
2012-04-10 14:57:45 -04:00
}
literals = opts.run ? opts["arguments"].splice(1) : [];
process.argv = process.argv.slice(0, 2).concat(literals);
2011-04-30 10:59:55 -04:00
process.argv[0] = 'coffee';
if (opts.output) {
opts.output = path.resolve(opts.output);
}
if (opts.join) {
opts.join = path.resolve(opts.join);
}
_ref1 = opts["arguments"];
_results = [];
for (_i = 0, _len = _ref1.length; _i < _len; _i++) {
source = _ref1[_i];
source = path.resolve(source);
_results.push(compilePath(source, true, source));
}
return _results;
};
compilePath = function(source, topLevel, base) {
var code, err, file, files, stats, _i, _len, _results;
if (__indexOf.call(sources, source) >= 0 || watchedDirs[source] || !topLevel && (notSources[source] || hidden(source))) {
return;
}
try {
stats = fs.statSync(source);
} catch (_error) {
err = _error;
if (err.code === 'ENOENT') {
console.error("File not found: " + source);
process.exit(1);
}
throw err;
}
if (stats.isDirectory()) {
if (path.basename(source) === 'node_modules') {
notSources[source] = true;
return;
}
if (opts.watch) {
watchDir(source, base);
}
try {
files = fs.readdirSync(source);
} catch (_error) {
err = _error;
if (err.code === 'ENOENT') {
return;
} else {
throw err;
2012-04-10 14:57:45 -04:00
}
}
_results = [];
for (_i = 0, _len = files.length; _i < _len; _i++) {
file = files[_i];
_results.push(compilePath(path.join(source, file), false, base));
}
return _results;
} else if (topLevel || helpers.isCoffee(source)) {
sources.push(source);
sourceCode.push(null);
delete notSources[source];
if (opts.watch) {
watch(source, base);
}
try {
code = fs.readFileSync(source);
} catch (_error) {
err = _error;
if (err.code === 'ENOENT') {
return;
} else {
throw err;
2012-04-10 14:57:45 -04:00
}
}
return compileScript(source, code.toString(), base);
} else {
return notSources[source] = true;
}
};
compileScript = function(file, input, base) {
var compiled, err, message, o, options, t, task;
if (base == null) {
base = null;
}
o = opts;
options = compileOptions(file, base);
try {
t = task = {
file: file,
input: input,
options: options
};
CoffeeScript.emit('compile', task);
if (o.tokens) {
return printTokens(CoffeeScript.tokens(t.input, t.options));
} else if (o.nodes) {
return printLine(CoffeeScript.nodes(t.input, t.options).toString().trim());
} else if (o.run) {
return CoffeeScript.run(t.input, t.options);
} else if (o.join && t.file !== o.join) {
if (helpers.isLiterate(file)) {
t.input = helpers.invertLiterate(t.input);
}
sourceCode[sources.indexOf(t.file)] = t.input;
return compileJoin();
} else {
2013-03-04 09:45:25 -05:00
compiled = CoffeeScript.compile(t.input, t.options);
t.output = compiled;
if (o.map) {
t.output = compiled.js;
t.sourceMap = compiled.v3SourceMap;
}
CoffeeScript.emit('success', task);
if (o.print) {
return printLine(t.output.trim());
} else if (o.compile || o.map) {
return writeJs(base, t.file, t.output, options.jsPath, t.sourceMap);
}
}
} catch (_error) {
err = _error;
CoffeeScript.emit('failure', err, task);
2012-04-10 14:57:45 -04:00
if (CoffeeScript.listeners('failure').length) {
return;
}
message = err.stack || ("" + err);
2012-04-10 14:57:45 -04:00
if (o.watch) {
return printLine(message + '\x07');
2013-02-25 12:41:34 -05:00
} else {
printWarn(message);
return process.exit(1);
2012-04-10 14:57:45 -04:00
}
}
};
compileStdio = function() {
var code, stdin;
code = '';
stdin = process.openStdin();
stdin.on('data', function(buffer) {
2012-04-10 14:57:45 -04:00
if (buffer) {
return code += buffer.toString();
}
});
return stdin.on('end', function() {
return compileScript(null, code);
});
};
joinTimeout = null;
compileJoin = function() {
2012-04-10 14:57:45 -04:00
if (!opts.join) {
return;
}
if (!sourceCode.some(function(code) {
return code === null;
})) {
clearTimeout(joinTimeout);
2011-12-18 15:27:08 -05:00
return joinTimeout = wait(100, function() {
return compileScript(opts.join, sourceCode.join('\n'), opts.join);
2011-12-18 15:27:08 -05:00
});
}
2010-12-23 00:26:15 -05:00
};
watch = function(source, base) {
var compile, compileTimeout, e, prevStats, rewatch, watchErr, watcher;
2011-12-18 09:05:42 -05:00
prevStats = null;
compileTimeout = null;
2011-12-18 14:15:33 -05:00
watchErr = function(e) {
if (e.code === 'ENOENT') {
2012-04-10 14:57:45 -04:00
if (sources.indexOf(source) === -1) {
return;
}
try {
rewatch();
return compile();
} catch (_error) {
e = _error;
2013-12-01 05:30:24 -05:00
removeSource(source, base);
return compileJoin();
}
2011-12-18 14:15:33 -05:00
} else {
throw e;
}
};
2011-12-18 09:05:42 -05:00
compile = function() {
clearTimeout(compileTimeout);
2011-12-18 14:26:23 -05:00
return compileTimeout = wait(25, function() {
return fs.stat(source, function(err, stats) {
2012-04-10 14:57:45 -04:00
if (err) {
return watchErr(err);
}
2011-12-24 15:44:51 -05:00
if (prevStats && stats.size === prevStats.size && stats.mtime.getTime() === prevStats.mtime.getTime()) {
return rewatch();
}
prevStats = stats;
return fs.readFile(source, function(err, code) {
2012-04-10 14:57:45 -04:00
if (err) {
return watchErr(err);
}
compileScript(source, code.toString(), base);
return rewatch();
});
2011-12-18 09:05:42 -05:00
});
2011-12-18 14:26:23 -05:00
});
};
try {
watcher = fs.watch(source, compile);
} catch (_error) {
e = _error;
watchErr(e);
}
return rewatch = function() {
if (watcher != null) {
watcher.close();
2012-04-10 14:57:45 -04:00
}
return watcher = fs.watch(source, compile);
};
};
watchDir = function(source, base) {
var e, readdirTimeout, watcher;
readdirTimeout = null;
try {
watchedDirs[source] = true;
return watcher = fs.watch(source, function() {
clearTimeout(readdirTimeout);
2011-12-18 15:27:08 -05:00
return readdirTimeout = wait(25, function() {
var err, file, files, _i, _len, _results;
try {
files = fs.readdirSync(source);
} catch (_error) {
err = _error;
if (err.code !== 'ENOENT') {
throw err;
}
watcher.close();
return removeSourceDir(source, base);
}
_results = [];
for (_i = 0, _len = files.length; _i < _len; _i++) {
file = files[_i];
_results.push(compilePath(path.join(source, file), false, base));
}
return _results;
2011-12-18 15:27:08 -05:00
});
});
} catch (_error) {
e = _error;
2012-04-10 14:57:45 -04:00
if (e.code !== 'ENOENT') {
throw e;
}
}
};
removeSourceDir = function(source, base) {
var file, sourcesChanged, _i, _len;
delete watchedDirs[source];
sourcesChanged = false;
for (_i = 0, _len = sources.length; _i < _len; _i++) {
file = sources[_i];
if (!(source === path.dirname(file))) {
continue;
}
2013-12-01 05:30:24 -05:00
removeSource(file, base);
sourcesChanged = true;
}
if (sourcesChanged) {
return compileJoin();
}
};
2013-12-01 05:30:24 -05:00
removeSource = function(source, base) {
var index;
index = sources.indexOf(source);
sources.splice(index, 1);
sourceCode.splice(index, 1);
2013-12-01 05:30:24 -05:00
if (!opts.join) {
silentUnlink(outputPath(source, base));
silentUnlink(outputPath(source, base, '.map'));
return timeLog("removed " + source);
}
};
silentUnlink = function(path) {
var err;
try {
return fs.unlinkSync(path);
} catch (_error) {
err = _error;
if (err.code !== 'ENOENT') {
throw err;
}
}
};
2013-02-28 15:51:29 -05:00
outputPath = function(source, base, extension) {
var basename, dir, srcDir;
2013-02-28 15:51:29 -05:00
if (extension == null) {
extension = ".js";
}
basename = helpers.baseFileName(source, true, useWinPathSep);
srcDir = path.dirname(source);
if (!opts.output) {
dir = srcDir;
} else if (source === base) {
dir = opts.output;
} else {
dir = path.join(opts.output, path.relative(base, srcDir));
}
return path.join(dir, basename + extension);
};
writeJs = function(base, sourcePath, js, jsPath, generatedSourceMap) {
var compile, jsDir, sourceMapPath;
if (generatedSourceMap == null) {
generatedSourceMap = null;
2013-02-28 15:51:29 -05:00
}
sourceMapPath = outputPath(sourcePath, base, ".map");
jsDir = path.dirname(jsPath);
compile = function() {
2013-02-28 15:51:29 -05:00
if (opts.compile) {
if (js.length <= 0) {
js = ' ';
}
if (generatedSourceMap) {
2013-07-30 00:06:41 -04:00
js = "" + js + "\n//# sourceMappingURL=" + (helpers.baseFileName(sourceMapPath, false, useWinPathSep)) + "\n";
2013-02-28 15:51:29 -05:00
}
fs.writeFile(jsPath, js, function(err) {
if (err) {
return printLine(err.message);
} else if (opts.compile && opts.watch) {
return timeLog("compiled " + sourcePath);
}
});
}
if (generatedSourceMap) {
return fs.writeFile(sourceMapPath, generatedSourceMap, function(err) {
2013-02-28 15:51:29 -05:00
if (err) {
return printLine("Could not write source map: " + err.message);
}
});
}
};
return fs.exists(jsDir, function(itExists) {
if (itExists) {
return compile();
} else {
2013-08-01 17:14:12 -04:00
return mkdirp(jsDir, compile);
}
});
};
2011-12-18 14:26:23 -05:00
wait = function(milliseconds, func) {
return setTimeout(func, milliseconds);
};
timeLog = function(message) {
return console.log("" + ((new Date).toLocaleTimeString()) + " - " + message);
};
printTokens = function(tokens) {
var strings, tag, token, value;
2010-12-23 13:50:52 -05:00
strings = (function() {
var _i, _len, _results;
2010-11-09 00:17:08 -05:00
_results = [];
for (_i = 0, _len = tokens.length; _i < _len; _i++) {
2010-10-01 18:26:37 -04:00
token = tokens[_i];
tag = token[0];
value = token[1].toString().replace(/\n/, '\\n');
_results.push("[" + tag + " " + value + "]");
}
2010-11-09 00:17:08 -05:00
return _results;
2010-12-23 13:50:52 -05:00
})();
return printLine(strings.join(' '));
};
parseOptions = function() {
var o;
optionParser = new optparse.OptionParser(SWITCHES, BANNER);
o = opts = optionParser.parse(process.argv.slice(2));
o.compile || (o.compile = !!o.output);
o.run = !(o.compile || o.print || o.map);
return o.print = !!(o.print || (o["eval"] || o.stdio && o.compile));
};
compileOptions = function(filename, base) {
var answer, cwd, jsDir, jsPath;
answer = {
filename: filename,
literate: opts.literate || helpers.isLiterate(filename),
bare: opts.bare,
header: opts.compile && !opts['no-header'],
sourceMap: opts.map
};
if (filename) {
if (base) {
cwd = process.cwd();
jsPath = outputPath(filename, base);
jsDir = path.dirname(jsPath);
answer = helpers.merge(answer, {
jsPath: jsPath,
sourceRoot: path.relative(jsDir, cwd),
sourceFiles: [path.relative(cwd, filename)],
generatedFile: helpers.baseFileName(jsPath, false, useWinPathSep)
});
} else {
answer = helpers.merge(answer, {
sourceRoot: "",
sourceFiles: [helpers.baseFileName(filename, false, useWinPathSep)],
generatedFile: helpers.baseFileName(filename, true, useWinPathSep) + ".js"
});
}
}
return answer;
};
forkNode = function() {
var args, nodeArgs, p;
nodeArgs = opts.nodejs.split(/\s+/);
args = process.argv.slice(1);
args.splice(args.indexOf('--nodejs'), 2);
p = spawn(process.execPath, nodeArgs.concat(args), {
cwd: process.cwd(),
env: process.env,
customFds: [0, 1, 2]
});
return p.on('exit', function(code) {
return process.exit(code);
});
};
usage = function() {
return printLine((new optparse.OptionParser(SWITCHES, BANNER)).help());
2010-03-07 00:28:58 -05:00
};
version = function() {
return printLine("CoffeeScript version " + CoffeeScript.VERSION);
2010-03-07 00:28:58 -05:00
};
2011-12-14 10:39:20 -05:00
}).call(this);