-
Notifications
You must be signed in to change notification settings - Fork 1
/
pipeline.coffee
402 lines (340 loc) · 11.6 KB
/
pipeline.coffee
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
grammar = require './grammar'
builtins = require './builtins'
async = require 'async'
fs = require 'fs'
util = require 'util'
_ = require 'underscore'
DEBUG = false
# Grab some tools before you dig in
recv_ = (t, s) -> console.log "[#{ t.toUpperCase() }] #{ s }"
_inspect = (o) -> util.inspect o, depth: null
inspect = (o) -> console.log _inspect o
# Create a context that can be extended with `.use`
class Scope
constructor: (init={}) ->
_.extend @, init
return @
# Set a value on the current scope
set: (t, k, v) ->
if DEBUG
console.log "[Scope set] Setting #{ t } #{ k } to #{ v }"
@[t] = {} if !@[t]?
@[t][k] = v
return @
# Get a value from the current scope, falling back to parent scope
get: (t, k) ->
if DEBUG
console.log "[Scope get] Getting #{ t } #{ k }"
got = @[t]?[k] if k?
got = @[t] if !k?
got || @parent?.get t, k
# Set an alias on the highest ranking scope
alias: (a, s) ->
if @parent?
@parent.alias a, s
else
@set 'fns', a, through s
@set 'aliases', a, s
# Create a new child scope for this scope
subScope: (init={}) ->
init.parent = @
return new Scope init
topScope: ->
if @parent?
@parent.topScope()
else
@
class Context extends Scope
class Pipeline extends Scope
use: (fns) ->
# Module name
if _.isString fns
if fns.match /^\w/
fns = './modules/' + fns
for k, v of require(fns)
@set 'fns', k, v
# Object of functions
else if _.isObject fns
for k, v of fns
@set 'fns', k, v
return @ # for chaining
# Execute a pipeline given a command string, input object,
# context and callback. An empty context object is created
# if none is given.
# exec script, cb
# exec script, inp, cb
# exec script, inp, ctx, cb
exec: (script, inp, ctx, cb) ->
if !cb?
cb = ctx
ctx = @subScope()
if !cb?
cb = inp
inp = null
try
pipelines = parsePipelines(script)
catch e
cb "Error parsing pipeline: " + e
try
runPipelines pipelines, inp, ctx, cb
catch e
cb "Error executing pipeline: " + e
return ctx
execFile: (script_filename, inp, ctx, cb) ->
script = fs.readFileSync(script_filename).toString()
@exec script, inp, ctx, cb
# Parse a command pipeline into a series of tokens
# that can be passed to `runPipeline`
parsePipelines = (cmd) ->
grammar.parse cmd
# Execute a parsed command pipeline, executing each part
# recursively by setting a callback that is either the next
# command in line or a final "stdout" callback
# /~+~+~+~+~+~+~+~+~+~+~+~+~+\
# | PROCEED AT YOUR OWN RISK |
# | dragons afoot |
# \+~+~+~+~+~+~+~+~+~+~+~+~+~/
runPipelines = (pipelines, inp, ctx, cb) ->
if pipelines.length > 1
_runPipeline = (_pipeline, _cb) ->
runPipeline _pipeline, inp, ctx, _cb
async.mapSeries pipelines, _runPipeline, (err, results) ->
cb err, results.slice(-1)[0]
else runPipeline pipelines[0], inp, ctx, cb
runPipeline = (_cmd_tokens, inp, ctx, final_cb) ->
if DEBUG
console.log '\n=== RUNNING PIPELINE ==='
inspect inp
console.log ' ---> '
inspect _cmd_tokens
console.log '========================\n'
cmd_tokens = _.clone _cmd_tokens
cmd_token = cmd_tokens.shift()
cmd_args = cmd_token.cmd
cmd_type = cmd_token.type
cmd_args = ['id'] if !cmd_args
# Replace sub-commands and variables
parseArgs = (inp, args, cb) ->
if DEBUG
console.log 'parsing args for ' + _inspect inp
console.log ':::> ' + _inspect args
if cmd_args[0] == 'alias'
return cb null, args
replaceArg = (arg, _cb) ->
if _.isObject arg
if arg.sub?
return runPipelines arg.sub, inp, ctx, _cb
else if arg.quoted?
return parseArgs inp, arg.quoted, (err, qargs) ->
_cb null, qargs.join(' ')
else if _.isString(arg)
# Int replacement
if $key = arg.match /^-?[0-9]+$/
arg = parseInt arg
# Non replacement (escaped)
else if $key = arg.match /\\\$[a-zA-Z0-9_-]*$/
arg = $key[0].slice(1)
# Within string replacement
else
while $key = arg.match /\$[!a-zA-Z0-9_-]+/
$key = $key[0]
if $key == '$!'
val = inp
else
key = $key.slice(1)
val = ctx.get 'vars', key
arg = arg.replace $key, val
_cb null, arg
async.map args, replaceArg, (err, new_args) ->
cb null, new_args
# Apply an at expression at the end
applyAt = (data, cb) ->
if cmd_token.at?
if cmd_type in ['ppipe', 'spipe']
_at = (_data, _cb) ->
at _data, cmd_token.at, ctx, _cb
async.map data, _at, cb
else
at data, cmd_token.at, ctx, cb
else
cb null, data
# Check if we're at the final step
if cmd_tokens.length == 0
cb = (err, ret) ->
if DEBUG
console.log ' ===> ' + _inspect ret
if err
final_cb err
else
applyAt ret, final_cb
# Create a callback to continue the pipeline otherwise
else cb = (err, ret) ->
applyAt ret, (err, ret) ->
runPipeline cmd_tokens, ret, ctx, final_cb
# Parse arguments and then execute
# Parallel if ppiped
if cmd_type == 'ppipe'
console.log('PPIPE: ' + _inspect cmd_args) if DEBUG
tasks = inp.map (_inp) ->
(_cb) ->
parseArgs _inp, cmd_args, (err, args) ->
doCmd args, _inp, ctx, _cb
async.parallel tasks, cb
# Series if spiped
else if cmd_type == 'spipe'
console.log('SPIPE: ' + _inspect cmd_args) if DEBUG
tasks = inp.map (_inp) ->
(_cb) ->
parseArgs _inp, cmd_args, (err, args) ->
doCmd args, _inp, ctx, _cb
async.series tasks, cb
# Return literal value (number or string) if $val
else if cmd_token.val?
console.log('VAL: ' + _inspect cmd_args) if DEBUG
parseArgs inp, [cmd_token.val], (err, parsed) ->
cb null, parsed[0]
# Return variable value if $var
else if cmd_token.var?
console.log('VAR: ' + _inspect cmd_args) if DEBUG
$key = cmd_token.var
if $key == '$!'
val = inp
else
key = $key.slice(1)
val = ctx.get 'vars', key
cb null, val
# Just execute if single piped
else
console.log('PIPE: ' + _inspect cmd_args) if DEBUG
parseArgs inp, cmd_args, (err, args) ->
doCmd args, inp, ctx, cb
# Execute a given command by looking in `ctx.fns` for a function
# called `[cmd]` and passing that function the split arguments
doCmd = (_args, inp, ctx, cb) ->
if DEBUG
console.log '\n##### DO CMD ######'
inspect _args
inspect inp
console.log '###################\n'
args = _.clone _args
cmd = args.shift()
if fn = builtins[cmd]
fn(inp, args, ctx, cb)
else if fn = ctx.get 'fns', cmd
fn(inp, args, ctx, cb)
else
cb "No command #{ cmd }. "
# Splits a string into "arguments" by separating with whitespace
# while attempting to treat quoted strings as single arguments.
# TODO: Make a more robust grammar that can handle escaping, etc.
splitArgs = (s) ->
args = []
s.trim().replace /"([^"]*)"|'([^']*)'|(\S+)/g, (g0,g1,g2,g3) ->
args.push(g1 || g2 || g3 || '')
return args
# Map a function into array of arrays at a certain depth
mapInto = (l, f, d, cb) ->
if d == 1
async.map l, f, cb
else
_into = (_l, _cb) -> mapInto _l, f, d - 1, _cb
async.map l, _into, cb
# , \-._ >._,_ _,_.< _.-/
# ( ) \(-='( )`--)/ ( _
# `\-\_/-')\/' `\/(`-\_/-/' `
# <`)_--(_\_ _/_)--_('>
# Take an object and an expression and follow the expression
# tree down to the desired result
descendObj = (_obj, _expr, ctx, final_cb) ->
if !_obj?
return final_cb null, undefined
# This is me hoping Node has really good GC
obj = _.clone _obj
expr = _.clone _expr
step = expr.shift()
if DEBUG
console.log "\n/ - - ~ @ ~ - - \\"
inspect obj
console.log " == @ ==> "
inspect step
console.log "\\ - - ~ @ ~ - - /\n"
# Check if we're at the final step
if expr.length == 0
cb = final_cb
else cb = (err, ret) ->
descendObj ret, expr, ctx, final_cb
if !step?
cb null, obj
# Map attributes
if step.map?
map_get = (__obj, _cb) ->
descendObj __obj, [{get: step.map}], ctx, _cb
mapInto obj, map_get, step.depth, cb
# Substitution
else if step.sub?
runPipelines step.sub, obj, ctx, cb
# Array result
else if _.isArray step.get
tasks = step.get.map (step_expr) ->
(_cb) -> descendObj obj, step_expr, ctx, _cb
async.parallel tasks, cb
# Object result
else if _.isObject(step.get) && step.get.obj?
tasks = []
for set in step.get.obj
do (set) ->
k = set.key
e = set.val
if _.isString k
# Key is a string, just get value
tasks.push (_cb) ->
descendObj obj, e, ctx, (err, v_obj) ->
dobj =
key: k
val: v_obj
_cb null, dobj
else
# Key is an expression, get both key value and value value
tasks.push (_cb) ->
descendObj obj, k, ctx, (err, k_obj) ->
descendObj obj, e, ctx, (err, v_obj) ->
dobj =
key: k_obj
val: v_obj
_cb null, dobj
# Combine results into single object
async.parallel tasks, (err, results) ->
result_obj = {}
for result in results
result_obj[result.key] = result.val
cb null, result_obj
# Get attribute
else
cb null, accessor obj, step.get
accessor = (obj, key) ->
if key == '.'
return obj
else
if key.match /^-?\d+/
key = Number key
# Pythonesque negative indexes
if key < 0
return obj.slice(key)[0]
return obj[key]
# create a command out of a script
through = (cmd) -> (inp, args, ctx, cb) ->
pipeline = parsePipelines(cmd)[0]
if pipeline[0].cmd?
pipeline[0].cmd.push args...
runPipeline pipeline, inp, ctx, cb
# Read in an at expression
at = (inp, expr, ctx, cb) ->
descendObj inp, expr, ctx, cb
module.exports =
Pipeline: Pipeline
Context: Context
parsePipelines: parsePipelines
runPipeline: runPipeline
doCmd: doCmd
through: through
at: at