/
actions.js
executable file
·488 lines (420 loc) · 13.2 KB
/
actions.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
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
require('node_extensions');
require('shelljs/global');
var fs = require('fs');
var os = require('os');
var async = require('async');
var util = require('util');
var path = require('path');
var colors = require('colors');
// disable colors if output is not going to terminal
if (!require('tty').isatty(process.stdout.fd))
colors.mode = 'none';
var exec = require('./executor.js').execute;
var spawn = require('./executor.js').spawn;
var dgraph = require('./dependency_graph');
var DependencyGraph = dgraph.DependencyGraph;
var execute = dgraph.execute;
var read_graph = dgraph.read_graph;
var write_graph = dgraph.write_graph;
var registry = require('./registry/registry').registry;
var exists = util.exists;
var retrieve = util.retrieve;
var cache = util.cache;
var hash = util.hash;
var rebuild_targets = {};
var missing_targets = {};
function check_for_updates(cmd, cb) {
if (!exists(cmd.target)) return cb();
fs.stat(cmd.target, function(err, target) {
if (err) {
rebuild_targets[cmd.target] = true;
missing_targets[cmd.target] = true;
return cb();
}
for (var idx in cmd.sources) {
if (exists(rebuild_targets[cmd.sources[idx]])) {
rebuild_targets[cmd.target] = true;
return cb();
}
}
async.map(cmd.sources, fs.stat, function(err, results) {
for (var idx in results) {
var stat = results[idx];
if (stat.mtime.getTime() > target.mtime.getTime()) {
rebuild_targets[cmd.target] = true;
return cb();
}
};
cb();
});
});
}
var posh_root = path.resolve('.posh');
var fingerprint_path = path.resolve(posh_root, 'fingerprints.json');
var graph_path = path.resolve(posh_root, 'graph.gen');
var nodes_path = path.resolve(posh_root, 'nodes.gen');
var dot_path = path.resolve(posh_root, 'graph.dot');
var svg_path = path.resolve(posh_root, 'graph.svg');
var new_fingerprints = {};
var old_fingerprints = {};
// cb(null, true) if file is unchanged, otherwise cb(null, false)
function fingerprint(file, cb) {
// use relative path entries for caching fingerprints
var relative = path.relative(process.cwd(), file);
var cached = new_fingerprints[relative];
if (exists(cached)) return cb(null, old_fingerprints[relative] === cached);
try {
hash(file, function(err, newval) {
if (err) return cb(null, false);
new_fingerprints[relative] = newval;
cb(null, newval === old_fingerprints[relative]);
})
}
catch(err) {
cb(null, false);
}
}
function touch(file) {
fs.utimes(file, new Date(), new Date());
}
function colored_exec(cmd, args, cb) {
if (!exists(cb)) {
cb = args;
args = null;
}
exec(cmd, args, function(err, stdout, stderr) {
if (err) {
console.log(cmd.red);
console.error(stderr.red);
return cb(err);
}
console.log(cmd.green);
return cb();
});
};
function build(graph, node, cmd, cb) {
cmd.action = cmd.action || 'build';
if (cmd.action !== 'build') return cb();
// TODO: refactor
if (!exists(cmd.target)) {
var current = cmd;
current.sources = current.sources.map(async.apply(path.resolve, cmd.cwd || node.base || process.cwd()).only(1));
async.map(current.sources, fingerprint, function(err, results) {
var no_update = true;
results.forEach(function(result) {
if (!result) no_update = false;
});
if (no_update)
return cb();
var cmd_str = [current.cmd].concat(current.args).join(' ');
console.log(cmd_str.yellow);
var cwd = current.cwd || node.base || process.cwd();
var proc = spawn(cmd.cmd, cmd.args, {stdio: 'inherit', cwd: cwd});
proc.on('exit', function(err) {
if (err) throw new Error('Command: ' + cmd_str + ' failed with error code: ' + err);
cb();
});
});
return;
}
// if this target does not need to be rebuilt, skip it
if (!exists(rebuild_targets[cmd.target]))
return cb();
// if the target is missing, we *must* rebuild it
if (exists(missing_targets[cmd.target])) {
return async.series([
async.apply(colored_exec, [cmd.cmd].concat(cmd.args).join(' '), {cwd: cmd.cwd || node.base || process.cwd()}),
async.apply(async.map, cmd.sources, fingerprint),
async.apply(fingerprint, cmd.target)
], cb);
}
// fingerprint the input sources against cached values
async.map(cmd.sources, fingerprint, function(err, results) {
var no_update = true;
results.forEach(function(result) {
if (!result) no_update = false;
});
if (no_update) {
// update the timestamp on the target to exceed the sources
touch(cmd.target);
return cb();
}
// needs rebuilding... so rebuild and add anything which depends on
// this to the set of rebuild targets
var cmd_str = [cmd.cmd].concat(cmd.args).join(' ');
colored_exec(cmd_str, {cwd: cmd.cwd || node.base || process.cwd()}, cb);
});
}
function execute_cmd(action, graph, node, cmd, cb) {
if (cmd.action !== action) return cb();
var cmd_str = [cmd.cmd].concat(cmd.args).join(' ');
console.log(cmd_str.yellow);
var cwd = cmd.cwd || node.base;
var proc = spawn(cmd.cmd, cmd.args, {stdio: 'inherit', cwd: cwd});
proc.on('exit', function(err) {
cb(err);
});
}
function print_sources(cmd, cb) {
if (cmd.action === 'update') return cb();
cmd.sources = cmd.sources || [];
async.forEach(cmd.sources, function(source, cb) { console.log(source.yellow); cb(); }, cb);
}
function print_target(cmd, cb) {
if (!exists(cmd.target) || cmd.action === 'update') return cb();
console.log(cmd.target.yellow);
cb();
}
function clean(cmd, cb) {
if (!exists(cmd.target) || cmd.action === 'update') return cb();
console.log('rm -rf'.red, cmd.target.yellow);
rm('-rf', cmd.target);
}
function wordwrap( str, width, brk, cut ) {
brk = brk || '\n';
width = width || 75;
cut = cut || false;
if (!str) { return str; }
var regex = '.{1,' +width+ '}(\\s|$)' + (cut ? '|.{' +width+ '}|.+$' : '|\\S+?(\\s|$)');
return str.match( RegExp(regex, 'g') ).join( brk );
}
function render_graph(g, action) {
var dot = 'digraph {\n';
dot += ' compound=true;\n';
dot += ' node[shape=record];\n';
var node_count = 0;
var cmd_count = 0;
var collapsed = {};
g.nodes.forEach(function(node) {
node.cmds = node.cmds.filter(function(cmd) { return cmd.action === action; });
if (node.cmds.length === 0) {
collapsed[node.id] = true;
return;
}
dot += ' "' + node.id + '";\n';
dot += ' subgraph "cluster' + node.id + '"{\n';
dot += ' style=filled;\n';
dot += ' color=lightgrey;\n';
dot += ' node [style=filled,color=white];\n';
dot += ' label = "' + node.id + ' commands";\n';
var idx = 0;
node.cmds.forEach(function(cmd) {
dot += ' "' + node.id + '.' + idx + '" [label="' + node.id + '.' + idx + '",tooltip="' + cmd.cmd + '"];\n';
++idx;
});
dot += ' }\n';
dot += ' "' + node.id + '" -> "' + node.id + '.0" [lhead="cluster' + node.id + '"];\n';
});
g.nodes.forEach(function(node) {
if (collapsed[node.id])
return;
var children = g.children[node.id];
children.forEach(function(child_id) {
dot += ' "' + node.id + '" -> "' + child_id + '" [id="' + node.id + '.' + child_id + '"];\n';
});
});
dot += '}';
return dot;
}
function get_nodes() {
try {
return new registry(nodes_path).nodes;
}
catch(err) {
return [];
}
}
function register(cb) {
cb = cb || function() {};
console.log('Scanning .dep files in'.cyan, process.cwd().yellow);
var proc = spawn('node', [path.resolve(__dirname, 'register.js')], {stdio: 'inherit'});
proc.on('exit', function(code) {
console.log('Done'.cyan);
console.log('Writing node list to:'.cyan, nodes_path.yellow);
cb(code);
});
}
function generate(cb) {
cb = cb || function() {};
register(function(err) {
if (err) return cb(err);
// construct dependency graph of nodes which have the specified action name
var nodes = get_nodes().filter(function(node) { return exists(node.generate); });
console.log('Constructing command graph for nodes'.cyan);
var graph = new DependencyGraph(nodes);
graph.generated = [];
execute(graph,
{
action: 'generate',
begin: function(node) {
console.log('Generating commands for node:'.cyan, node.id.yellow);
},
end: function(node) {
console.log('Done with node:'.cyan, node.id.yellow);
}
},
function(err) {
var cmd_graph = new DependencyGraph(graph.generated);
console.log('Writing command graph to'.cyan, graph_path.yellow);
write_graph(cmd_graph, graph_path);
console.log('Done'.cyan);
cb(err);
});
});
}
function generic(name, cb) {
cb = cb || function() {};
try {
console.log('Loading command graph from'.cyan, graph_path.yellow);
var graph = read_graph(graph_path);
dgraph.execute(graph,
{
action: function(node, g, cb) {
async.map(node.cmds, async.apply(execute_cmd, name, g, node), cb);
}
},
function(err) {
console.log('Done'.cyan);
cb(err);
});
}
catch(err) {
console.log('Unable to read graph'.red);
cb();
}
}
function posh(action) {
switch(action) {
case 'scan':
register();
break;
case 'generate':
generate();
break;
case 'status':
console.log('Loading command graph from'.cyan, graph_path.yellow);
var graph = read_graph(graph_path);
console.log('Calculating outdated targets'.cyan);
dgraph.execute(graph,
{
action: function(node, g, cb) {
async.map(node.cmds, check_for_updates, cb)
}
},
function() {
Object.keys(rebuild_targets).forEach(function(target) {
console.log(target.yellow);
});
console.log('Done'.cyan);
});
break;
case 'build':
console.log('Loading command graph from'.cyan, graph_path.yellow);
var graph = read_graph(graph_path);
console.log('Loading fingerprints from'.cyan, fingerprint_path.yellow);
try {
old_fingerprints = retrieve(fingerprint_path);
} catch(err) {
console.log('Unable to load fingerprint file: '.red + fingerprint_path.yellow);
}
console.log('Building potentially outdated dependencies'.cyan);
async.series([
async.apply(dgraph.execute, graph,
{
action: function(node, g, cb) {
async.map(node.cmds, check_for_updates, cb)
}
}),
async.apply(dgraph.execute, graph,
{
action: function(node, g, cb) {
async.map(node.cmds, async.apply(build, g, node), cb);
}
})
], function(err, cb) {
Object.keys(new_fingerprints).forEach(function(file) {
old_fingerprints[file] = new_fingerprints[file];
});
cache(fingerprint_path, old_fingerprints);
console.log('Done'.cyan);
})
break;
case 'clean':
console.log('Loading command graph from'.cyan, graph_path.yellow);
var graph = read_graph(graph_path);
console.log('Removing targets'.cyan);
dgraph.execute(graph,
{
action: function(node, g, cb) {
async.map(node.cmds, clean, cb)
}
},
function(err) {
console.log('Done'.cyan);
});
break;
case 'sources':
console.log('Loading command graph from'.cyan, graph_path.yellow);
var graph = read_graph(graph_path);
console.log('Sources:'.cyan);
dgraph.execute(graph,
{
action: function(node, g, cb) {
async.map(node.cmds, print_sources, cb);
}
},
function(err) {
console.log('Done'.cyan);
});
break;
case 'targets':
console.log('Loading command graph from'.cyan, graph_path.yellow);
var graph = read_graph(graph_path);
console.log('Targets:'.cyan);
dgraph.execute(graph,
{
action: function(node, g, cb) {
async.map(node.cmds, print_target, cb);
}
},
function(err) {
console.log('Done'.cyan);
});
break;
case 'graph':
console.log('Loading command graph from'.cyan, graph_path.yellow);
var graph = read_graph(graph_path);
console.log('Rendering graph in .dot format'.cyan);
var action = process.argv[3] || 'build';
var dot = render_graph(graph, action);
console.log('Writing .dot file:'.cyan, dot_path.yellow);
fs.writeFileSync(dot_path, dot);
async.series([
async.apply(colored_exec, 'dot ' + dot_path + ' -Tsvg -o' + svg_path),
async.apply(colored_exec, '/usr/bin/google-chrome ' + svg_path)
], function(err) {
console.log('Done'.cyan);
});
break;
case 'update':
var count_call = function(cb) {
cb(null, get_nodes().length);
};
var update_call = async.apply(generic, 'update');
async.series(
[count_call, update_call, generate, count_call],
function(err, results) {
if (results[0] !== results[3]) {
var proc = spawn('posh', ['update'], {stdio: 'inherit'});
}
}
);
break;
default:
generic(action);
}
}
process.on('uncaughtException', function(err) {
console.log(err.stack.red);
});
module.exports.posh = posh;