-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcatty.js
417 lines (369 loc) · 10.4 KB
/
catty.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
var fs = require('fs');
var path = require('path');
var _ = require('underscore');
var catty = new Catty();
// regex for comments like:
// /* @requires name1, name2, name3 */
// (Comments may span multiple lines, commas are optional)
var REQUIRES_RXP = /\/\*+\s*@requires?\b([\s,;_0-9A-Za-z.-]+)\s*\*+\/\s*\n?/g;
function Catty(opts) {
var prepended = "",
externals = [];
knownFileIndex = {}, // paths of known js files indexed by basename
watchedFiles = {}, // SourceFile objects indexed by basename
jobs = [],
addedDeps = [];
opts = _.extend({
global: false,
follow: false
}, opts || {});
this.internal = { // expose internal functions for unit testing
parseDeps: parseDeps,
stripBOM: stripBOM
};
// @deps array or comma-separated list of depencencies to insert into the
// root document(s)
this.addDeps = function(deps) {
if (_.isString(deps)) {
deps = deps.split(',');
}
addedDeps = _.union(addedDeps, deps);
return this;
};
// @arg name of an external dependency, which shouldn't be bundled
this.external = function(arg) {
externals = _.isArray(arg) ? arg : _.toArray(arguments);
return this;
};
// @js JS string to insert at the beginning of the concatenated files, but
// inside the module closure (could contain variable definitions)
this.prepend = function(js) {
try {
// eval(js); // catch syntax errors
prepended = js;
} catch(e) {
console.error("[prepend] Invalid JavaScript: ", js);
}
return this;
};
// @path A directory containing JavaScript source files
// (subdirectories are also indexed)
this.addLibrary = function(path) {
if (!dirExists(path)) {
die("Not a valid directory: " + path);
}
findSourceFiles(path).forEach(indexFile);
return this;
};
// Compile JS source files
this.cat = function(src, dest) {
var job;
try {
job = new CattyJob(src, dest);
if (addedDeps.length > 0) {
job.addDeps(addedDeps);
}
} catch(e) {
die(e.message);
}
job.run();
jobs.push(job); // save job so it can be run again, if monitoring files
return this;
};
function runJobs() {
jobs.forEach(function(job) {
job.run();
});
}
function getNode(key) {
var node = watchedFiles[key];
if (!node) {
throw new Error("Missing dependency: " + key);
}
return node;
}
function sortNodes(nodes) {
var startId = 0,
len = nodes.length,
sorted = {},
nodeName, i, startNode, reqId;
while (startId < len-1) {
startNode = nodes[startId];
reqId = -1;
if (startNode.name() in sorted === false) {
for (i=startId+1; i<len; i++) {
nodeName = nodes[i].name();
if (nodeName in sorted === false && startNode.requiresFile(nodeName)) {
reqId = i;
}
}
}
if (reqId > 0) {
nodes.splice(startId, 1);
nodes.splice(reqId, 0, startNode);
} else {
startId++;
}
sorted[startNode.name()] = true;
}
}
// Add file to index of known files;
// Assumes @path exists.
//
function indexFile(path) {
var name = getFileInfo(path).basename;
if (!name) {
die("Invalid path: " + path);
} else if (name in knownFileIndex === false) {
knownFileIndex[name] = path;
} else if (knownFileIndex[name] !== path) {
console.error("File name collision.");
console.error("Using:", knownFileIndex[name]);
console.error("Ignoring:", path);
}
return name;
}
function SourceFile(path) {
var info = getFileInfo(path),
_deps = [],
_insertedDeps = [],
_js = "";
if (!info.is_file || info.ext != '.js') {
die("Invalid source file: " + path);
}
watchedFiles[info.basename] = this;
if (opts.follow) {
startMonitoring();
}
findDeps();
this.name = function() { return info.basename; };
this.getContent = function() { return _js; };
this.getDeps = function() { return _deps; };
this.insertDeps = function(deps) {
_insertedDeps = deps;
updateDeps(_deps);
};
this.requiresFile = function(targName, visited) {
visited = visited || {};
visited[this.name()] = true;
var reqs = this.getDeps();
if (_.contains(reqs, targName)) {
return true;
}
for (var i=0; i<reqs.length; i++) {
var reqName = reqs[i];
if (reqName in visited === false) {
var reqNode = watchedFiles[reqName];
if (reqNode.requiresFile(targName, visited)) {
return true;
}
}
}
return false;
};
function findDeps() {
var js = fs.readFileSync(path, {encoding:"utf8"});
js = stripBOM(js);
// (os x) When editor opens file to write, file may
// appear to be empty -- ignoring change if len is 0
var changed = js.length > 0 && js !== _js;
if (changed) {
_js = js;
updateDeps(parseDeps(js));
}
return changed;
}
function updateDeps(deps) {
deps = _.union(deps, _insertedDeps);
deps = _.difference(deps, externals);
deps.forEach(addDependency);
_deps = deps;
}
function addDependency(key) {
if (key in knownFileIndex === false) {
throw new Error("Unknown dependency in " + path + " -- " + key);
}
if (key in watchedFiles === false) {
new SourceFile(knownFileIndex[key]);
}
}
function onChange(err) {
if (err) {
console.error(err.message);
} else {
console.error("Re-catting -- change in " + path);
runJobs(); // TODO: only run jobs that use this the changed source file
}
}
function startMonitoring() {
var timeout = null;
fs.watch(path, function(evt) {
if (evt == "change" || evt == "rename") {
// Use a timeout to make sure file has actually changed
// (Had problems in os x)
timeout && clearTimeout(timeout);
timeout = setTimeout(function() {
try {
if (findDeps()) {
onChange();
}
} catch(e) {
onChange(e);
}
}, 150);
}
});
}
} // SourceFile
function CattyJob(src, dest) {
var roots = [];
var useStdout = !dest || dest == '-' || dest == '/dev/stdout';
var inFiles;
if (_.isString(src)) {
inFiles = [src];
} else if (_.isArray(src)) {
inFiles = src;
} else {
die("Invalid input file(s): " + src);
}
if (opts.follow && useStdout) {
die("-f option is not compatible with output to stdout");
}
roots = inFiles.map(function(ifile) {
ifile = path.join(ifile); // Update slashes on Windows
if (ifile == dest) die("Tried to overwrite a source file: " + ifile);
if (!fileExists(ifile)) die("Source file not found: " + ifile);
var name = indexFile(ifile);
return new SourceFile(ifile);
});
// return list of all deps reached by list of deps
function findDeps(newDeps, foundDeps) {
return newDeps.reduce(function(memo, key) {
if (memo.indexOf(key) == -1) {
memo.push(key);
findDeps(getNode(key).getDeps(), memo);
}
return memo;
}, foundDeps || []);
}
function concatenate() {
var keys = roots.map(function(node) {return node.name();});
var nodes = findDeps(keys).map(getNode);
sortNodes(nodes);
return nodes.map(function(node) { return node.getContent(); }).join('\n\n');
};
function stripComments(js) {
return js.replace(REQUIRES_RXP, '');
}
function addClosure(js) {
return "(function(){\n" + js + "\n}());\n";
}
function bundle() {
var js = "";
if (prepended) {
js += prepended + '\n';
}
js += concatenate();
js = stripComments(js);
if (!opts.global) {
js = addClosure(js);
}
return js;
}
this.addDeps = function(deps) {
roots.forEach(function(node) {node.insertDeps(deps);});
};
this.run = function() {
var js, dirname, err;
try {
js = bundle();
} catch(e) {
err = e;
}
if (_.isFunction(dest)) {
dest(err, js);
} else if (err) {
// Print message, don't exit (let user correct dependency problems
// when monitoring files).
console.error(e.message);
} else if (useStdout) {
console.log(js);
} else if (_.isString(dest)) {
// check that dir (still) exists
dirname = path.dirname(dest);
if (!dirExists(dirname)) {
die("Destination directory not found: " + dirname);
}
fs.writeFileSync(dest, js);
console.error("Wrote " + dest);
}
};
} // CattyJob
} // Catty
function stripBOM(str) {
if (str && str.charCodeAt(0) === 0xFEFF) {
str = str.slice(1);
}
return str;
}
function parseDeps(js) {
var fileRxp = /\*?[_0-9a-z](?:[.-]?[_0-9a-z])*/ig,
deps = [], match, match2;
while (match = REQUIRES_RXP.exec(js)) {
while (match2 = fileRxp.exec(match[1])) {
deps.push(match2[0]);
}
}
return deps;
}
function findSourceFiles(dirPath) {
var results = walkSync(dirPath);
return results.filter(function(filePath) {
return /\.js$/.test(filePath);
});
}
function dirExists(path) {
return !!getFileInfo(path).is_dir;
}
function fileExists(path) {
return !!getFileInfo(path).is_file;
}
function getFileInfo(p) {
var info = {}, stat;
try {
stat = fs.statSync(p);
info.exists = true;
info.is_file = stat.isFile();
info.is_dir = stat.isDirectory();
info.directory = path.dirname(p);
} catch(e) {};
if (info.is_file) {
info.ext = path.extname(p);
info.filename = path.basename(p);
info.basename = info.filename.substr(0, info.filename.length - info.ext.length);
}
return info;
}
function walkSync(dir, memo) {
memo = memo || [];
var list = fs.readdirSync(dir);
list.forEach(function(file) {
var filepath = path.join(dir, file);
var stat = fs.statSync(filepath);
if (stat && stat.isDirectory()) {
walkSync(filepath, memo);
}
else {
memo.push(filepath);
}
});
return memo;
}
function die(msg) {
if (msg) console.error(msg);
process.exit(1);
}
module.exports = function(opts) {
return new Catty(opts); // allow multiple instances with different options
};
_.extend(module.exports, catty);