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