react / wstein / node_modules / jest-cli / node_modules / coffee-script / lib / coffee-script / command.js
80677 views// Generated by CoffeeScript 1.9.31(function() {2var BANNER, CoffeeScript, EventEmitter, SWITCHES, compileJoin, compileOptions, compilePath, compileScript, compileStdio, exec, findDirectoryIndex, forkNode, fs, helpers, hidden, joinTimeout, makePrelude, mkdirp, notSources, optionParser, optparse, opts, outputPath, parseOptions, path, printLine, printTokens, printWarn, ref, removeSource, removeSourceDir, silentUnlink, sourceCode, sources, spawn, timeLog, usage, useWinPathSep, version, wait, watch, watchDir, watchedDirs, writeJs,3indexOf = [].indexOf || function(item) { for (var i = 0, l = this.length; i < l; i++) { if (i in this && this[i] === item) return i; } return -1; };45fs = require('fs');67path = require('path');89helpers = require('./helpers');1011optparse = require('./optparse');1213CoffeeScript = require('./coffee-script');1415ref = require('child_process'), spawn = ref.spawn, exec = ref.exec;1617EventEmitter = require('events').EventEmitter;1819useWinPathSep = path.sep === '\\';2021helpers.extend(CoffeeScript, new EventEmitter);2223printLine = function(line) {24return process.stdout.write(line + '\n');25};2627printWarn = function(line) {28return process.stderr.write(line + '\n');29};3031hidden = function(file) {32return /^\.|~$/.test(file);33};3435BANNER = 'Usage: coffee [options] path/to/script.coffee -- [args]\n\nIf called without options, `coffee` will run your script.';3637SWITCHES = [['-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 .js.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'], ['-r', '--require [MODULE*]', 'require the given module before eval or REPL'], ['-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']];3839opts = {};4041sources = [];4243sourceCode = [];4445notSources = {};4647watchedDirs = {};4849optionParser = null;5051exports.run = function() {52var i, len, literals, ref1, replCliOpts, results, source;53parseOptions();54replCliOpts = {55useGlobal: true56};57if (opts.require) {58opts.prelude = makePrelude(opts.require);59}60replCliOpts.prelude = opts.prelude;61if (opts.nodejs) {62return forkNode();63}64if (opts.help) {65return usage();66}67if (opts.version) {68return version();69}70if (opts.interactive) {71return require('./repl').start(replCliOpts);72}73if (opts.stdio) {74return compileStdio();75}76if (opts["eval"]) {77return compileScript(null, opts["arguments"][0]);78}79if (!opts["arguments"].length) {80return require('./repl').start(replCliOpts);81}82literals = opts.run ? opts["arguments"].splice(1) : [];83process.argv = process.argv.slice(0, 2).concat(literals);84process.argv[0] = 'coffee';85if (opts.output) {86opts.output = path.resolve(opts.output);87}88if (opts.join) {89opts.join = path.resolve(opts.join);90console.error('\nThe --join option is deprecated and will be removed in a future version.\n\nIf for some reason it\'s necessary to share local variables between files,\nreplace...\n\n $ coffee --compile --join bundle.js -- a.coffee b.coffee c.coffee\n\nwith...\n\n $ cat a.coffee b.coffee c.coffee | coffee --compile --stdio > bundle.js\n');91}92ref1 = opts["arguments"];93results = [];94for (i = 0, len = ref1.length; i < len; i++) {95source = ref1[i];96source = path.resolve(source);97results.push(compilePath(source, true, source));98}99return results;100};101102makePrelude = function(requires) {103return requires.map(function(module) {104var _, match, name;105if (match = module.match(/^(.*)=(.*)$/)) {106_ = match[0], name = match[1], module = match[2];107}108name || (name = helpers.baseFileName(module, true, useWinPathSep));109return name + " = require('" + module + "')";110}).join(';');111};112113compilePath = function(source, topLevel, base) {114var code, err, file, files, i, len, results, stats;115if (indexOf.call(sources, source) >= 0 || watchedDirs[source] || !topLevel && (notSources[source] || hidden(source))) {116return;117}118try {119stats = fs.statSync(source);120} catch (_error) {121err = _error;122if (err.code === 'ENOENT') {123console.error("File not found: " + source);124process.exit(1);125}126throw err;127}128if (stats.isDirectory()) {129if (path.basename(source) === 'node_modules') {130notSources[source] = true;131return;132}133if (opts.run) {134compilePath(findDirectoryIndex(source), topLevel, base);135return;136}137if (opts.watch) {138watchDir(source, base);139}140try {141files = fs.readdirSync(source);142} catch (_error) {143err = _error;144if (err.code === 'ENOENT') {145return;146} else {147throw err;148}149}150results = [];151for (i = 0, len = files.length; i < len; i++) {152file = files[i];153results.push(compilePath(path.join(source, file), false, base));154}155return results;156} else if (topLevel || helpers.isCoffee(source)) {157sources.push(source);158sourceCode.push(null);159delete notSources[source];160if (opts.watch) {161watch(source, base);162}163try {164code = fs.readFileSync(source);165} catch (_error) {166err = _error;167if (err.code === 'ENOENT') {168return;169} else {170throw err;171}172}173return compileScript(source, code.toString(), base);174} else {175return notSources[source] = true;176}177};178179findDirectoryIndex = function(source) {180var err, ext, i, index, len, ref1;181ref1 = CoffeeScript.FILE_EXTENSIONS;182for (i = 0, len = ref1.length; i < len; i++) {183ext = ref1[i];184index = path.join(source, "index" + ext);185try {186if ((fs.statSync(index)).isFile()) {187return index;188}189} catch (_error) {190err = _error;191if (err.code !== 'ENOENT') {192throw err;193}194}195}196console.error("Missing index.coffee or index.litcoffee in " + source);197return process.exit(1);198};199200compileScript = function(file, input, base) {201var compiled, err, message, o, options, t, task;202if (base == null) {203base = null;204}205o = opts;206options = compileOptions(file, base);207try {208t = task = {209file: file,210input: input,211options: options212};213CoffeeScript.emit('compile', task);214if (o.tokens) {215return printTokens(CoffeeScript.tokens(t.input, t.options));216} else if (o.nodes) {217return printLine(CoffeeScript.nodes(t.input, t.options).toString().trim());218} else if (o.run) {219CoffeeScript.register();220if (opts.prelude) {221CoffeeScript["eval"](opts.prelude, t.options);222}223return CoffeeScript.run(t.input, t.options);224} else if (o.join && t.file !== o.join) {225if (helpers.isLiterate(file)) {226t.input = helpers.invertLiterate(t.input);227}228sourceCode[sources.indexOf(t.file)] = t.input;229return compileJoin();230} else {231compiled = CoffeeScript.compile(t.input, t.options);232t.output = compiled;233if (o.map) {234t.output = compiled.js;235t.sourceMap = compiled.v3SourceMap;236}237CoffeeScript.emit('success', task);238if (o.print) {239return printLine(t.output.trim());240} else if (o.compile || o.map) {241return writeJs(base, t.file, t.output, options.jsPath, t.sourceMap);242}243}244} catch (_error) {245err = _error;246CoffeeScript.emit('failure', err, task);247if (CoffeeScript.listeners('failure').length) {248return;249}250message = err.stack || ("" + err);251if (o.watch) {252return printLine(message + '\x07');253} else {254printWarn(message);255return process.exit(1);256}257}258};259260compileStdio = function() {261var code, stdin;262code = '';263stdin = process.openStdin();264stdin.on('data', function(buffer) {265if (buffer) {266return code += buffer.toString();267}268});269return stdin.on('end', function() {270return compileScript(null, code);271});272};273274joinTimeout = null;275276compileJoin = function() {277if (!opts.join) {278return;279}280if (!sourceCode.some(function(code) {281return code === null;282})) {283clearTimeout(joinTimeout);284return joinTimeout = wait(100, function() {285return compileScript(opts.join, sourceCode.join('\n'), opts.join);286});287}288};289290watch = function(source, base) {291var compile, compileTimeout, err, prevStats, rewatch, startWatcher, watchErr, watcher;292watcher = null;293prevStats = null;294compileTimeout = null;295watchErr = function(err) {296if (err.code !== 'ENOENT') {297throw err;298}299if (indexOf.call(sources, source) < 0) {300return;301}302try {303rewatch();304return compile();305} catch (_error) {306removeSource(source, base);307return compileJoin();308}309};310compile = function() {311clearTimeout(compileTimeout);312return compileTimeout = wait(25, function() {313return fs.stat(source, function(err, stats) {314if (err) {315return watchErr(err);316}317if (prevStats && stats.size === prevStats.size && stats.mtime.getTime() === prevStats.mtime.getTime()) {318return rewatch();319}320prevStats = stats;321return fs.readFile(source, function(err, code) {322if (err) {323return watchErr(err);324}325compileScript(source, code.toString(), base);326return rewatch();327});328});329});330};331startWatcher = function() {332return watcher = fs.watch(source).on('change', compile).on('error', function(err) {333if (err.code !== 'EPERM') {334throw err;335}336return removeSource(source, base);337});338};339rewatch = function() {340if (watcher != null) {341watcher.close();342}343return startWatcher();344};345try {346return startWatcher();347} catch (_error) {348err = _error;349return watchErr(err);350}351};352353watchDir = function(source, base) {354var err, readdirTimeout, startWatcher, stopWatcher, watcher;355watcher = null;356readdirTimeout = null;357startWatcher = function() {358return watcher = fs.watch(source).on('error', function(err) {359if (err.code !== 'EPERM') {360throw err;361}362return stopWatcher();363}).on('change', function() {364clearTimeout(readdirTimeout);365return readdirTimeout = wait(25, function() {366var err, file, files, i, len, results;367try {368files = fs.readdirSync(source);369} catch (_error) {370err = _error;371if (err.code !== 'ENOENT') {372throw err;373}374return stopWatcher();375}376results = [];377for (i = 0, len = files.length; i < len; i++) {378file = files[i];379results.push(compilePath(path.join(source, file), false, base));380}381return results;382});383});384};385stopWatcher = function() {386watcher.close();387return removeSourceDir(source, base);388};389watchedDirs[source] = true;390try {391return startWatcher();392} catch (_error) {393err = _error;394if (err.code !== 'ENOENT') {395throw err;396}397}398};399400removeSourceDir = function(source, base) {401var file, i, len, sourcesChanged;402delete watchedDirs[source];403sourcesChanged = false;404for (i = 0, len = sources.length; i < len; i++) {405file = sources[i];406if (!(source === path.dirname(file))) {407continue;408}409removeSource(file, base);410sourcesChanged = true;411}412if (sourcesChanged) {413return compileJoin();414}415};416417removeSource = function(source, base) {418var index;419index = sources.indexOf(source);420sources.splice(index, 1);421sourceCode.splice(index, 1);422if (!opts.join) {423silentUnlink(outputPath(source, base));424silentUnlink(outputPath(source, base, '.js.map'));425return timeLog("removed " + source);426}427};428429silentUnlink = function(path) {430var err, ref1;431try {432return fs.unlinkSync(path);433} catch (_error) {434err = _error;435if ((ref1 = err.code) !== 'ENOENT' && ref1 !== 'EPERM') {436throw err;437}438}439};440441outputPath = function(source, base, extension) {442var basename, dir, srcDir;443if (extension == null) {444extension = ".js";445}446basename = helpers.baseFileName(source, true, useWinPathSep);447srcDir = path.dirname(source);448if (!opts.output) {449dir = srcDir;450} else if (source === base) {451dir = opts.output;452} else {453dir = path.join(opts.output, path.relative(base, srcDir));454}455return path.join(dir, basename + extension);456};457458mkdirp = function(dir, fn) {459var mkdirs, mode;460mode = 0x1ff & ~process.umask();461return (mkdirs = function(p, fn) {462return fs.exists(p, function(exists) {463if (exists) {464return fn();465} else {466return mkdirs(path.dirname(p), function() {467return fs.mkdir(p, mode, function(err) {468if (err) {469return fn(err);470}471return fn();472});473});474}475});476})(dir, fn);477};478479writeJs = function(base, sourcePath, js, jsPath, generatedSourceMap) {480var compile, jsDir, sourceMapPath;481if (generatedSourceMap == null) {482generatedSourceMap = null;483}484sourceMapPath = outputPath(sourcePath, base, ".js.map");485jsDir = path.dirname(jsPath);486compile = function() {487if (opts.compile) {488if (js.length <= 0) {489js = ' ';490}491if (generatedSourceMap) {492js = js + "\n//# sourceMappingURL=" + (helpers.baseFileName(sourceMapPath, false, useWinPathSep)) + "\n";493}494fs.writeFile(jsPath, js, function(err) {495if (err) {496printLine(err.message);497return process.exit(1);498} else if (opts.compile && opts.watch) {499return timeLog("compiled " + sourcePath);500}501});502}503if (generatedSourceMap) {504return fs.writeFile(sourceMapPath, generatedSourceMap, function(err) {505if (err) {506printLine("Could not write source map: " + err.message);507return process.exit(1);508}509});510}511};512return fs.exists(jsDir, function(itExists) {513if (itExists) {514return compile();515} else {516return mkdirp(jsDir, compile);517}518});519};520521wait = function(milliseconds, func) {522return setTimeout(func, milliseconds);523};524525timeLog = function(message) {526return console.log(((new Date).toLocaleTimeString()) + " - " + message);527};528529printTokens = function(tokens) {530var strings, tag, token, value;531strings = (function() {532var i, len, results;533results = [];534for (i = 0, len = tokens.length; i < len; i++) {535token = tokens[i];536tag = token[0];537value = token[1].toString().replace(/\n/, '\\n');538results.push("[" + tag + " " + value + "]");539}540return results;541})();542return printLine(strings.join(' '));543};544545parseOptions = function() {546var o;547optionParser = new optparse.OptionParser(SWITCHES, BANNER);548o = opts = optionParser.parse(process.argv.slice(2));549o.compile || (o.compile = !!o.output);550o.run = !(o.compile || o.print || o.map);551return o.print = !!(o.print || (o["eval"] || o.stdio && o.compile));552};553554compileOptions = function(filename, base) {555var answer, cwd, jsDir, jsPath;556answer = {557filename: filename,558literate: opts.literate || helpers.isLiterate(filename),559bare: opts.bare,560header: opts.compile && !opts['no-header'],561sourceMap: opts.map562};563if (filename) {564if (base) {565cwd = process.cwd();566jsPath = outputPath(filename, base);567jsDir = path.dirname(jsPath);568answer = helpers.merge(answer, {569jsPath: jsPath,570sourceRoot: path.relative(jsDir, cwd),571sourceFiles: [path.relative(cwd, filename)],572generatedFile: helpers.baseFileName(jsPath, false, useWinPathSep)573});574} else {575answer = helpers.merge(answer, {576sourceRoot: "",577sourceFiles: [helpers.baseFileName(filename, false, useWinPathSep)],578generatedFile: helpers.baseFileName(filename, true, useWinPathSep) + ".js"579});580}581}582return answer;583};584585forkNode = function() {586var args, nodeArgs, p;587nodeArgs = opts.nodejs.split(/\s+/);588args = process.argv.slice(1);589args.splice(args.indexOf('--nodejs'), 2);590p = spawn(process.execPath, nodeArgs.concat(args), {591cwd: process.cwd(),592env: process.env,593stdio: [0, 1, 2]594});595return p.on('exit', function(code) {596return process.exit(code);597});598};599600usage = function() {601return printLine((new optparse.OptionParser(SWITCHES, BANNER)).help());602};603604version = function() {605return printLine("CoffeeScript version " + CoffeeScript.VERSION);606};607608}).call(this);609610611