-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathbuiltins.coffee
401 lines (331 loc) · 10.6 KB
/
builtins.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
fs = require 'fs'
_ = require 'underscore'
util = require 'util'
_inspect = (o) -> util.inspect o, depth: null
helpers = require './helpers'
module.exports = builtins = {}
# Command helpers
valid = (i) ->
if _.isArray i
return (i.length > 0)
if _.isObject i
return (_.keys(i).length > 0)
if _.isString i
return (i.length > 0)
return i?
combine = (inp, args) -> _.flatten([inp].concat(args)).filter valid
# Arithmetic
num = (n) -> Number(n) || 0
bool = (v) ->
if _.isString v
return false if v == 'false'
return true if v == 'true'
else
return !!v
exists = (v) -> v?
reducer = (f) ->
(inp, args, ctx, cb) ->
cb null, combine(inp, args).reduce(f)
builtins['+'] = reducer (a, b) -> num(a) + num(b)
builtins['*'] = reducer (a, b) -> num(a) * num(b)
builtins['-'] = reducer (a, b) -> num(a) - num(b)
builtins['/'] = reducer (a, b) -> num(a) / num(b)
builtins['.'] = reducer (a, b) -> a + b
# Basics
# `id` returns its input
# val -> id -> val
builtins.id = (inp, args, ctx, cb) -> cb null, inp
# `val` returns its first argument as is
# echo val -> "val"
builtins.val = (inp, args, ctx, cb) -> cb null, args[0]
builtins.or = (inp, args, ctx, cb) -> cb null, inp or args[0]
# `echo` returns its arguments joined as a string
# echo val -> "val"
builtins.echo = (inp, args, ctx, cb) ->
cb null, args.join(' ')
# `key` is `echo` without spaces, useful for building keys
# key "a" ":b:" "c" -> "a:b:c"
builtins.key = (inp, args, ctx, cb) -> cb null, args.join('')
# `num` coerces input into a number
# val -> num -> #val
builtins.num = (inp, args, ctx, cb) -> cb null, num inp
# `bool` coerces input into a boolean
# val -> bool -> val?
builtins.bool = (inp, args, ctx, cb) -> cb null, bool inp
builtins.null = (inp, args, ctx, cb) -> cb null, null
# `if [test] [value]`
# Returns the value if the test is true, otherwise nothing
# Not actually very useful
builtins.if = (inp, args, ctx, cb) ->
if args[0]
cb null, args[1]
else
cb()
# `case [key] {cases}`
# Use key as a conditional or case; looks in a cases dictionary to decide what
# to return. Ideally there's something more syntactic and less forcedly
# functional to fill this case. A big problem in this case is you can't use it
# to branch because it can only return computed values. Then again it would be
# almost impossible to write a good multi-case script in one line.
builtins.case = (inp, args, ctx, cb) ->
_case = args[0]
cases = args[1]
cb null, cases[_case]
# Building objects and arrays
# list val val val -> [val, val, val]
builtins.list = (inp, args, ctx, cb) -> cb null, args
# obj "key" val "key" val -> {key: val, key: val}
builtins.obj = (inp, args, ctx, cb) ->
abj = {}
if args.length
i = 0
while i < args.length
abj[args[i]] = args[i+1]
i+=2
cb null, abj
# range #start? #stop -> [#i]
builtins.range = (inp, args, ctx, cb) ->
if args.length == 2
i0 = num(args[0])
i1 = num(args[1]) - 1
else
i0 = 0
i1 = num(args[0]) - 1
cb null, [i0 .. i1]
# String operations
builtins.upper = (inp, args, ctx, cb) -> cb null, inp.toUpperCase()
builtins.lower = (inp, args, ctx, cb) -> cb null, inp.toLowerCase()
capitalize = (s) -> s[0].toUpperCase() + s.slice(1)
builtins.capitalize = (inp, args, ctx, cb) -> cb null, capitalize inp
# List operations
builtins.length = (inp, args, ctx, cb) -> cb null, inp.length
builtins.reverse = (inp, args, ctx, cb) ->
if typeof inp == 'string'
cb null, inp.split('').reverse().join('')
else
cb null, inp.reverse()
builtins.head = (inp, args, ctx, cb) -> cb null, inp[..(args[0]||50)-1]
builtins.tail = (inp, args, ctx, cb) ->
count = args[0]
count = 50 if !count?
if count < 1
cb null, []
else
cb null, inp[inp.length-count..]
builtins.join = (inp, args, ctx, cb) -> cb null, inp.join args[0] || ' '
builtins.split = (inp, args, ctx, cb) -> cb null, inp.split(args[0] || '\n')
builtins.trim = (inp, args, ctx, cb) -> cb null, (args[0] || inp).trim()
builtins.sleep = (inp, args, ctx, cb) ->
setTimeout (-> cb null, inp), Number args[0]
# Matching, filtering
builtins.match = (inp, args, ctx, cb) ->
if args.length == 2
inp = args[0]
match_with = args[1]
else
match_with = args[0]
matched = []
for i in inp
if i.match match_with
matched.push i
cb null, matched
builtins.grep = builtins.match
builtins.filter = (inp, args, ctx, cb) ->
filtered_inp = []
if args.length > 0
filter_code = 'return (' + args.join(' ') + ');'
filter_func = new Function 'i', filter_code
filtered_inp = inp.filter filter_func
else
# Filter out null items
for i in inp
filtered_inp.push(i) if i
cb null, filtered_inp
# Pass through without altering input (isn't this id?)
builtins.tee = (inp, args, ctx, cb) ->
console.log _inspect inp
cb null, inp
builtins.parse = (inp, args, ctx, cb) ->
cb null, JSON.parse inp
builtins.log = (inp, args, ctx, cb) ->
console.log inp || args.join ' '
cb null, inp
builtins.inspect = (inp, args, ctx, cb) ->
console.log 'inp: ' + _inspect inp
console.log 'args: ' + _inspect args
cb null, inp
builtins.stringify = (inp, args, ctx, cb) ->
cb null, JSON.stringify inp
builtins.sort = (inp, args, ctx, cb) ->
if sort_by = args[0]
if sort_by[0] == '-'
sort_by = sort_by[1..]
cb null, inp.sort (a, b) -> b[sort_by] - a[sort_by]
else
cb null, inp.sort (a, b) -> a[sort_by] - b[sort_by]
else
cb null, inp.sort()
builtins.count = (inp, args, ctx, cb) ->
counts = {}
ki = {}
if args[0]?
ik = (i) -> i[args[0]]
else
ik = (i) -> i
for i in inp
counts[ik i] = 0 if not counts[ik i]?
counts[ik i] += 1
ki[ik i] = i
counts_list = []
for k, v of counts
counts_list.push
item: ki[k]
count: v
counts_list.sort (a, b) -> a.count - b.count
cb null, counts_list
builtins.bin = (inp, args, ctx, cb) ->
count = Number args[0]
key = args[1]
ki = {}
if key?
ik = (i) -> i[key]
else
ik = (i) -> i
min = null
max = null
bins = []
for item in inp
k = ik item
if !min? || k < min
min = k
if !max? || k > max
max = k + 0.000000001
interval = ( max - min ) / count
for i in [0..count-1]
bins.push
start: i * interval + min
end: ( i + 1 ) * interval + min
count: 0
items: []
for item in inp
bi = Math.floor( ( (ik item) - min ) / interval )
bins[bi].items.push item
bins[bi].count += 1
cb null, bins
builtins.chunks = (inp, args, ctx, cb) ->
n = args[0] || 10
cs = ([] for i in [0..n-1])
for i in [0..inp.length-1]
ci = Math.floor(i / n)
cs[ci].push inp[i]
cb null, cs
builtins.slice = (inp, args, ctx, cb) ->
a = args[0] || 0
b = args[1] || inp.length
cb null, inp.slice(a, b)
builtins.now = (inp, args, ctx, cb) -> cb null, new Date
builtins.timestamp = (inp, args, ctx, cb) -> cb null, new Date().getTime()
builtins['oid-timestamp'] = (inp, args, ctx, cb) -> cb null, (parseInt((args[0] || inp).toString().substring(0, 8), 16) * 1000)
randstr = (len=5) ->
s = ''
while s.length < len
s += Math.random().toString(36).slice(2, len-s.length+2)
return s
randint = (max=100) ->
return Math.floor(Math.random() * max)
builtins.randstr = (inp, args, ctx, cb) -> cb null, randstr args[0]
builtins.randint = (inp, args, ctx, cb) -> cb null, randint args[0]
builtins.choice = (inp, args, ctx, cb) ->
cb null, _.sample(inp, 1)[0]
builtins.sample = (inp, args, ctx, cb) ->
cb null, _.sample inp, args[0] || inp.length/2
# Array functions
builtins.zip = (inp, args, ctx, cb) ->
if _.every args, _.isArray
cb null, _.zip args...
else # split one list of args into two
args.push null if args.length%2 == 1
l1 = _.first args, args.length/2
l2 = _.last args, args.length/2
cb null, _.zip l1, l2
builtins.zipobj = (inp, args, ctx, cb) ->
builtins.zip inp, args, ctx, (err, zipped) ->
cb null, _.object zipped
# Underscore methods
# ------------------------------------------------------------------------------
umethods = _.pick(_, [
'keys', 'values', 'pairs',
'pick', 'omit', 'extend', 'defaults',
'where', 'findWhere',
'sortBy', 'groupBy', 'indexBy', 'countBy',
'shuffle', 'uniq', 'flatten',
'without', 'union', 'intersection', 'difference'
])
# Wrap them using `sync` and `with_inp` options
_.extend builtins, helpers.wrapall umethods, '', true, true
# Modifying the environment
# ------------------------------------------------------------------------------
builtins.set = (inp, args, ctx, cb) ->
data = args[1] || inp
ctx.set 'vars', args[0], data
cb null, data
builtins.setall = (inp, args, ctx, cb) ->
data = args[1] || inp
for k, v of data
ctx.set 'vars', k, v
cb null, data
# `inc` increments a number given a key
builtins.inc = (inp, args, ctx, cb) ->
inc_key = args[0]
ctx[inc_key] = 0 if !ctx[inc_key]?
cb null, ++ctx[inc_key]
# `push` adds input to the end of the specified array
builtins.push = (inp, args, ctx, cb) ->
data = args[1] || inp
l = ctx.get('vars', args[0]) || []
l.push data
ctx.set('vars', args[0], l)
cb null, l
# `ginc` gets or increments a number given a key and object key
builtins.ginc = (inp, args, ctx, cb) ->
inc_key = args[0]
obj_key = args[1]
if !ctx[inc_key]?
ctx[inc_key] =
val: 0
objs: {}
if ctx[inc_key].objs[obj_key]?
cb null, ctx[inc_key].objs[obj_key]
else
obj_val = ++ctx[inc_key].val
ctx[inc_key].objs[obj_key] = obj_val
cb null, obj_val
# Including modules
builtins.use = (inp, args, ctx, cb) ->
for arg in args
ctx.topScope().use arg
cb null, 'Using: ' + args.join(', ')
builtins.alias = (inp, args, ctx, cb) ->
alias = args[0]
script = args[1]
if !script
# Showing an alias
cb null, ctx.get 'aliases', alias
else
# Setting an alias
ctx.alias alias, script
cb null,
success: true
alias: alias
script: script
builtins.aliases = (inp, args, ctx, cb) ->
if !inp
# Showing aliases
cb null, ctx.get 'aliases'
else
# Setting aliases
for alias, script of inp
ctx.alias alias, script
cb null,
success: true
aliases: inp