react / wstein / node_modules / jest-cli / node_modules / jasmine-only / node_modules / coffee-script / lib / coffee-script / command.js
81146 views// Generated by CoffeeScript 1.6.31(function() {2var BANNER, CoffeeScript, EventEmitter, SWITCHES, compileJoin, compileOptions, compilePath, compileScript, compileStdio, exec, exists, forkNode, fs, helpers, hidden, joinTimeout, notSources, optionParser, optparse, opts, outputPath, parseOptions, path, printLine, printTokens, printWarn, removeSource, sourceCode, sources, spawn, timeLog, unwatchDir, usage, useWinPathSep, version, wait, watch, watchDir, watchers, writeJs, _ref;34fs = require('fs');56path = require('path');78helpers = require('./helpers');910optparse = require('./optparse');1112CoffeeScript = require('./coffee-script');1314_ref = require('child_process'), spawn = _ref.spawn, exec = _ref.exec;1516EventEmitter = require('events').EventEmitter;1718exists = fs.exists || path.exists;1920useWinPathSep = path.sep === '\\';2122helpers.extend(CoffeeScript, new EventEmitter);2324printLine = function(line) {25return process.stdout.write(line + '\n');26};2728printWarn = function(line) {29return process.stderr.write(line + '\n');30};3132hidden = function(file) {33return /^\.|~$/.test(file);34};3536BANNER = 'Usage: coffee [options] path/to/script.coffee -- [args]\n\nIf called without options, `coffee` will run your script.';3738SWITCHES = [['-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'], ['-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']];3940opts = {};4142sources = [];4344sourceCode = [];4546notSources = {};4748watchers = {};4950optionParser = null;5152exports.run = function() {53var literals, source, _i, _len, _results;54parseOptions();55if (opts.nodejs) {56return forkNode();57}58if (opts.help) {59return usage();60}61if (opts.version) {62return version();63}64if (opts.interactive) {65return require('./repl').start();66}67if (opts.watch && !fs.watch) {68return printWarn("The --watch feature depends on Node v0.6.0+. You are running " + process.version + ".");69}70if (opts.stdio) {71return compileStdio();72}73if (opts["eval"]) {74return compileScript(null, sources[0]);75}76if (!sources.length) {77return require('./repl').start();78}79literals = opts.run ? sources.splice(1) : [];80process.argv = process.argv.slice(0, 2).concat(literals);81process.argv[0] = 'coffee';82_results = [];83for (_i = 0, _len = sources.length; _i < _len; _i++) {84source = sources[_i];85_results.push(compilePath(source, true, path.normalize(source)));86}87return _results;88};8990compilePath = function(source, topLevel, base) {91return fs.stat(source, function(err, stats) {92if (err && err.code !== 'ENOENT') {93throw err;94}95if ((err != null ? err.code : void 0) === 'ENOENT') {96console.error("File not found: " + source);97process.exit(1);98}99if (stats.isDirectory() && path.dirname(source) !== 'node_modules') {100if (opts.watch) {101watchDir(source, base);102}103return fs.readdir(source, function(err, files) {104var file, index, _ref1, _ref2;105if (err && err.code !== 'ENOENT') {106throw err;107}108if ((err != null ? err.code : void 0) === 'ENOENT') {109return;110}111index = sources.indexOf(source);112files = files.filter(function(file) {113return !hidden(file);114});115[].splice.apply(sources, [index, index - index + 1].concat(_ref1 = (function() {116var _i, _len, _results;117_results = [];118for (_i = 0, _len = files.length; _i < _len; _i++) {119file = files[_i];120_results.push(path.join(source, file));121}122return _results;123})())), _ref1;124[].splice.apply(sourceCode, [index, index - index + 1].concat(_ref2 = files.map(function() {125return null;126}))), _ref2;127return files.forEach(function(file) {128return compilePath(path.join(source, file), false, base);129});130});131} else if (topLevel || helpers.isCoffee(source)) {132if (opts.watch) {133watch(source, base);134}135return fs.readFile(source, function(err, code) {136if (err && err.code !== 'ENOENT') {137throw err;138}139if ((err != null ? err.code : void 0) === 'ENOENT') {140return;141}142return compileScript(source, code.toString(), base);143});144} else {145notSources[source] = true;146return removeSource(source, base);147}148});149};150151compileScript = function(file, input, base) {152var compiled, err, message, o, options, t, task, useColors;153if (base == null) {154base = null;155}156o = opts;157options = compileOptions(file, base);158try {159t = task = {160file: file,161input: input,162options: options163};164CoffeeScript.emit('compile', task);165if (o.tokens) {166return printTokens(CoffeeScript.tokens(t.input, t.options));167} else if (o.nodes) {168return printLine(CoffeeScript.nodes(t.input, t.options).toString().trim());169} else if (o.run) {170return CoffeeScript.run(t.input, t.options);171} else if (o.join && t.file !== o.join) {172if (helpers.isLiterate(file)) {173t.input = helpers.invertLiterate(t.input);174}175sourceCode[sources.indexOf(t.file)] = t.input;176return compileJoin();177} else {178compiled = CoffeeScript.compile(t.input, t.options);179t.output = compiled;180if (o.map) {181t.output = compiled.js;182t.sourceMap = compiled.v3SourceMap;183}184CoffeeScript.emit('success', task);185if (o.print) {186return printLine(t.output.trim());187} else if (o.compile || o.map) {188return writeJs(base, t.file, t.output, options.jsPath, t.sourceMap);189}190}191} catch (_error) {192err = _error;193CoffeeScript.emit('failure', err, task);194if (CoffeeScript.listeners('failure').length) {195return;196}197useColors = process.stdout.isTTY && !process.env.NODE_DISABLE_COLORS;198message = helpers.prettyErrorMessage(err, file || '[stdin]', input, useColors);199if (o.watch) {200return printLine(message + '\x07');201} else {202printWarn(message);203return process.exit(1);204}205}206};207208compileStdio = function() {209var code, stdin;210code = '';211stdin = process.openStdin();212stdin.on('data', function(buffer) {213if (buffer) {214return code += buffer.toString();215}216});217return stdin.on('end', function() {218return compileScript(null, code);219});220};221222joinTimeout = null;223224compileJoin = function() {225if (!opts.join) {226return;227}228if (!sourceCode.some(function(code) {229return code === null;230})) {231clearTimeout(joinTimeout);232return joinTimeout = wait(100, function() {233return compileScript(opts.join, sourceCode.join('\n'), opts.join);234});235}236};237238watch = function(source, base) {239var compile, compileTimeout, e, prevStats, rewatch, watchErr, watcher;240prevStats = null;241compileTimeout = null;242watchErr = function(e) {243if (e.code === 'ENOENT') {244if (sources.indexOf(source) === -1) {245return;246}247try {248rewatch();249return compile();250} catch (_error) {251e = _error;252removeSource(source, base, true);253return compileJoin();254}255} else {256throw e;257}258};259compile = function() {260clearTimeout(compileTimeout);261return compileTimeout = wait(25, function() {262return fs.stat(source, function(err, stats) {263if (err) {264return watchErr(err);265}266if (prevStats && stats.size === prevStats.size && stats.mtime.getTime() === prevStats.mtime.getTime()) {267return rewatch();268}269prevStats = stats;270return fs.readFile(source, function(err, code) {271if (err) {272return watchErr(err);273}274compileScript(source, code.toString(), base);275return rewatch();276});277});278});279};280try {281watcher = fs.watch(source, compile);282} catch (_error) {283e = _error;284watchErr(e);285}286return rewatch = function() {287if (watcher != null) {288watcher.close();289}290return watcher = fs.watch(source, compile);291};292};293294watchDir = function(source, base) {295var e, readdirTimeout, watcher;296readdirTimeout = null;297try {298return watcher = fs.watch(source, function() {299clearTimeout(readdirTimeout);300return readdirTimeout = wait(25, function() {301return fs.readdir(source, function(err, files) {302var file, _i, _len, _results;303if (err) {304if (err.code !== 'ENOENT') {305throw err;306}307watcher.close();308return unwatchDir(source, base);309}310_results = [];311for (_i = 0, _len = files.length; _i < _len; _i++) {312file = files[_i];313if (!(!hidden(file) && !notSources[file])) {314continue;315}316file = path.join(source, file);317if (sources.some(function(s) {318return s.indexOf(file) >= 0;319})) {320continue;321}322sources.push(file);323sourceCode.push(null);324_results.push(compilePath(file, false, base));325}326return _results;327});328});329});330} catch (_error) {331e = _error;332if (e.code !== 'ENOENT') {333throw e;334}335}336};337338unwatchDir = function(source, base) {339var file, prevSources, toRemove, _i, _len;340prevSources = sources.slice(0);341toRemove = (function() {342var _i, _len, _results;343_results = [];344for (_i = 0, _len = sources.length; _i < _len; _i++) {345file = sources[_i];346if (file.indexOf(source) >= 0) {347_results.push(file);348}349}350return _results;351})();352for (_i = 0, _len = toRemove.length; _i < _len; _i++) {353file = toRemove[_i];354removeSource(file, base, true);355}356if (!sources.some(function(s, i) {357return prevSources[i] !== s;358})) {359return;360}361return compileJoin();362};363364removeSource = function(source, base, removeJs) {365var index, jsPath;366index = sources.indexOf(source);367sources.splice(index, 1);368sourceCode.splice(index, 1);369if (removeJs && !opts.join) {370jsPath = outputPath(source, base);371return exists(jsPath, function(itExists) {372if (itExists) {373return fs.unlink(jsPath, function(err) {374if (err && err.code !== 'ENOENT') {375throw err;376}377return timeLog("removed " + source);378});379}380});381}382};383384outputPath = function(source, base, extension) {385var baseDir, basename, dir, srcDir;386if (extension == null) {387extension = ".js";388}389basename = helpers.baseFileName(source, true, useWinPathSep);390srcDir = path.dirname(source);391baseDir = base === '.' ? srcDir : srcDir.substring(base.length);392dir = opts.output ? path.join(opts.output, baseDir) : srcDir;393return path.join(dir, basename + extension);394};395396writeJs = function(base, sourcePath, js, jsPath, generatedSourceMap) {397var compile, jsDir, sourceMapPath;398if (generatedSourceMap == null) {399generatedSourceMap = null;400}401sourceMapPath = outputPath(sourcePath, base, ".map");402jsDir = path.dirname(jsPath);403compile = function() {404if (opts.compile) {405if (js.length <= 0) {406js = ' ';407}408if (generatedSourceMap) {409js = "" + js + "\n/*\n//@ sourceMappingURL=" + (helpers.baseFileName(sourceMapPath, false, useWinPathSep)) + "\n*/\n";410}411fs.writeFile(jsPath, js, function(err) {412if (err) {413return printLine(err.message);414} else if (opts.compile && opts.watch) {415return timeLog("compiled " + sourcePath);416}417});418}419if (generatedSourceMap) {420return fs.writeFile(sourceMapPath, generatedSourceMap, function(err) {421if (err) {422return printLine("Could not write source map: " + err.message);423}424});425}426};427return exists(jsDir, function(itExists) {428if (itExists) {429return compile();430} else {431return exec("mkdir -p " + jsDir, compile);432}433});434};435436wait = function(milliseconds, func) {437return setTimeout(func, milliseconds);438};439440timeLog = function(message) {441return console.log("" + ((new Date).toLocaleTimeString()) + " - " + message);442};443444printTokens = function(tokens) {445var strings, tag, token, value;446strings = (function() {447var _i, _len, _results;448_results = [];449for (_i = 0, _len = tokens.length; _i < _len; _i++) {450token = tokens[_i];451tag = token[0];452value = token[1].toString().replace(/\n/, '\\n');453_results.push("[" + tag + " " + value + "]");454}455return _results;456})();457return printLine(strings.join(' '));458};459460parseOptions = function() {461var i, o, source, _i, _len;462optionParser = new optparse.OptionParser(SWITCHES, BANNER);463o = opts = optionParser.parse(process.argv.slice(2));464o.compile || (o.compile = !!o.output);465o.run = !(o.compile || o.print || o.map);466o.print = !!(o.print || (o["eval"] || o.stdio && o.compile));467sources = o["arguments"];468for (i = _i = 0, _len = sources.length; _i < _len; i = ++_i) {469source = sources[i];470sourceCode[i] = null;471}472};473474compileOptions = function(filename, base) {475var answer, cwd, jsDir, jsPath;476answer = {477filename: filename,478literate: opts.literate || helpers.isLiterate(filename),479bare: opts.bare,480header: opts.compile,481sourceMap: opts.map482};483if (filename) {484if (base) {485cwd = process.cwd();486jsPath = outputPath(filename, base);487jsDir = path.dirname(jsPath);488answer = helpers.merge(answer, {489jsPath: jsPath,490sourceRoot: path.relative(jsDir, cwd),491sourceFiles: [path.relative(cwd, filename)],492generatedFile: helpers.baseFileName(jsPath, false, useWinPathSep)493});494} else {495answer = helpers.merge(answer, {496sourceRoot: "",497sourceFiles: [helpers.baseFileName(filename, false, useWinPathSep)],498generatedFile: helpers.baseFileName(filename, true, useWinPathSep) + ".js"499});500}501}502return answer;503};504505forkNode = function() {506var args, nodeArgs;507nodeArgs = opts.nodejs.split(/\s+/);508args = process.argv.slice(1);509args.splice(args.indexOf('--nodejs'), 2);510return spawn(process.execPath, nodeArgs.concat(args), {511cwd: process.cwd(),512env: process.env,513customFds: [0, 1, 2]514});515};516517usage = function() {518return printLine((new optparse.OptionParser(SWITCHES, BANNER)).help());519};520521version = function() {522return printLine("CoffeeScript version " + CoffeeScript.VERSION);523};524525}).call(this);526527528