-
Notifications
You must be signed in to change notification settings - Fork 6
/
framework.lua
1842 lines (1606 loc) · 53.9 KB
/
framework.lua
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
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
-- Copyright 2015 Boundary, Inc.
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.-
---------------
-- A Boundary Plugin Framework for easy development of custom Boundary.com plugins.
--
-- [https://github.com/boundary/boundary-plugin-framework-lua](https://github.com/boundary/boundary-plugin-framework-lua)
-- @module Boundary Plugin Framework for LUA
-- @author Gabriel Nicolas Avellaneda <[email protected]>
-- @license Apache 2.0
-- @copyright 2015 Boundary, Inc
local Emitter = require('core').Emitter
local Object = require('core').Object
local timer = require('timer')
local math = require('math')
local string = require('string')
local os = require('os')
local fs = require('fs')
local http = require('http')
local https = require('https')
local net = require('net')
local bit = require('bit')
local table = require('table')
local childprocess = require('childprocess')
local json = require('json')
local _url = require('url')
local framework = {}
local querystring = require('querystring')
local boundary = require('boundary')
local io = require('io')
local hrtime = require('uv').Process.hrtime
local utils = require('utils')
local callable = function (class, func)
class.meta.__call = func
end
local factory = function (class)
local mt = getmetatable(class)
mt.__call = function (t, ...)
return t:new(...)
end
end
framework.version = '0.11.0'
framework.boundary = boundary
framework.params = boundary.param or json.parse(fs.readFileSync('param.json')) or {}
framework.plugin_params = boundary.plugin or json.parse(fs.readFileSync('plugin.json')) or {}
framework.metrics = boundary.metrics or json.parse(fs.readFileSync('metrics.json')) or {}
local plugin_params = framework.plugin_params
framework.string = {}
framework.functional = {}
framework.table = {}
framework.util = {}
framework.http = {}
local EventTracker = Object:extend()
function EventTracker:initialize(delay)
self.delay = delay or 5 * 60
self.events = {}
end
function EventTracker:hash(event)
return string.format("%s_%s_%s", event.type, event.msg, event.source)
end
function EventTracker:track(event)
local hash = self:hash(event)
local time = os.time() + self.delay
self.events[hash] = time
end
function EventTracker:canEmit(event, time)
local hash = self:hash(event)
local next_time = self.events[hash]
local result = (not next_time) or next_time <= time
return result
end
local Logger = Object:extend()
Logger.CRITICAL = 50
Logger.ERROR = 40
Logger.WARNING = 30
Logger.INFO = 20
Logger.DEBUG = 10
Logger.NOTSET = 60
Logger.level_map = {
critical = Logger.CRITICAL,
error = Logger.ERROR,
warning = Logger.WARNING,
info = Logger.INFO,
debug = Logger.DEBUG,
notset = Logger.NOTSET
}
function Logger.parseLevel(level)
return tonumber(level) or Logger.level_map[level] or Logger.NOTSET
end
function Logger:initialize(stream, level)
self.out = stream
self.levels = {}
self.levels[Logger.CRITICAL] = self.critical
self.levels[Logger.ERROR] = self.error
self.levels[Logger.WARNING] = self.warning
self.levels[Logger.INFO] = self.info
self.levels[Logger.DEBUG] = self.debug
self:setLevel(level)
end
function Logger:isEnabledFor(level)
return level >= self.level
end
function Logger:setLevel(level)
self.level = level or Logger.NOTSET
end
function Logger:getLevel()
return self.level
end
function Logger:dump(args)
return args and utils.dump(args, nil, true) or ''
end
function Logger:write(level_string, message, args)
local formatted = ('%s:\t%s %s\n'):format(level_string, message, self:dump(args))
self.out:write(formatted)
end
function Logger:info(message, args)
if self:isEnabledFor(Logger.INFO) then
self:write('INFO', message, args)
end
end
function Logger:warning(message, args)
if self:isEnabledFor(Logger.WARNING) then
self:write('WARNING', message, args)
end
end
function Logger:debug(message, args)
if self:isEnabledFor(Logger.DEBUG) then
self:write('DEBUG', message, args)
end
end
function Logger:error(message, args)
if self:isEnabledFor(Logger.ERROR) then
self:write('ERROR', message, args)
end
end
function Logger:critical(message, args)
if self:isEnabledFor(Logger.CRITICAL) then
self:write('CRITICAL', message, args)
end
end
function Logger:exception(message, args)
if self:isEnabledFor(Logger.ERROR) then
self:write('ERROR', message, args)
end
end
function Logger:log(level, message, args)
local func = self.levels[level]
if func and self:isEnabledFor(level) then
func(self, message, args)
end
end
framework.Logger = Logger
local function getDefaultLogger(level)
return Logger:new(process.stderr, Logger.parseLevel(level))
end
do
local encode_alphabet = {
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/'
}
local decode_alphabet = {}
for i, v in ipairs(encode_alphabet) do
decode_alphabet[v] = i-1
end
local function translate(sixbit)
return encode_alphabet[sixbit + 1]
end
local function unTranslate(char)
return decode_alphabet[char]
end
local function toBytes(str)
return { str:byte(1, #str) }
end
local function mask6bits(byte)
return bit.band(0x3f, byte)
end
local function pad(bytes)
local to_pad = 3 - #bytes % 3
while to_pad > 0 and to_pad ~= 3 do
table.insert(bytes, 0x0)
to_pad = to_pad - 1
end
return bytes
end
local function encode(str, no_padding)
local bytes = toBytes(str)
local bytesTotal = #bytes
if bytesTotal == 0 then
return ''
end
bytes = pad(bytes)
local output = {}
local i = 1
while i < #bytes do
-- read three bytes into a 24 bit buffer to produce 4 coded bytes.
local buffer = bit.rol(bytes[i], 16)
buffer = bit.bor(buffer, bit.rol(bytes[i+1], 8))
buffer = bit.bor(buffer, bytes[i+2])
-- get six bits at a time and translate to base64
for j = 18, 0, -6 do
table.insert(output, translate(mask6bits(bit.ror(buffer, j))))
end
i = i + 3
end
-- If was padded then replace with = characters
local padding_char = no_padding and '' or '='
if bytesTotal % 3 == 1 then
output[#output-1] = padding_char
output[#output] = padding_char
elseif bytesTotal % 3 == 2 then
output[#output] = padding_char
end
return table.concat(output)
end
local function decode(str)
-- take four encoded octets and produce 3 decoded bytes.
local output = {}
local i = 1
while i < #str do
local buffer = 0
-- get the octet represented by the coded base64 char
-- shift left by 6 bits and or
-- mask the 3 bytes, and convert to ascii
for j = 18, 0, -6 do
local octet = unTranslate(str:sub(i, i))
buffer = bit.bor(bit.rol(octet, j), buffer)
i = i + 1
end
for j = 16, 0, -8 do
local byte = bit.band(0xff, bit.ror(buffer, j))
table.insert(output, byte)
end
end
return string.char(unpack(output))
end
framework.util.base64Encode = encode
framework.util.base64Decode = decode
end
local base64Encode = framework.util.base64Encode
do
local _pairs = pairs({ a = 0 }) -- get the generating function from pairs
local gpairs = function(t, key)
local value
key, value = _pairs(t, key)
return key, key, value
end
local function iterator (obj, param, state)
if (type(obj) == 'table') then
if #obj > 0 then
return ipairs(obj)
else
return gpairs, obj, nil
end
elseif type(obj) == 'function' then
return obj, param, state
end
error(("object %s of type %s can not be iterated."):format(obj, type(obj)))
end
local function call(func, state, ...)
if state == nil then
return nil
end
return state, func(...)
end
local function _each(func, gen, param, state)
repeat
state = call(func, gen(param, state))
until state == nil
end
local function each(func, gen, param, state)
_each(func, iterator(gen, param, state))
end
framework.functional.each = each
local function toMap(gen, param, state)
local t = {}
each(function (k, v)
v = v or k
t[k] = v
end, gen, param, state)
return t
end
framework.functional.toMap = toMap
-- naive version of map
local function map(func, xs)
local t = {}
table.foreach(xs, function (i, v)
--t[i] = func(v, i)
table.insert(t, func(v))
end)
return t
end
framework.functional.map = map
-- naive version of filter
local function filter(func, xs)
local t = {}
table.foreach(xs, function (i, v)
if func(v) then
table.insert(t, v)
--t[i] = v
end
end)
return t
end
framework.functional.filter = filter
-- naive version of reduce
local function reduce(func, acc, xs)
table.foreach(xs, function (i, v)
acc = func(acc, v)
end)
return acc
end
framework.functional.reduce = reduce
end
--- String functions
-- @section string
--- Trim blanks from the string.
-- @param self The string to trim
-- @return The string with trimmed blanks
function framework.string.trim(self)
return string.match(self, '^%s*(.-)%s*$')
end
local trim = framework.string.trim
function framework.util.parseUrl(url, parseQueryString)
assert(url, 'parse expect a non-nil value')
url = trim(url)
local href = url
local chunk, protocol = url:match("^(([a-zA-Z0-9+]+)://)")
url = url:sub((chunk and #chunk or 0) + 1)
local auth
chunk, auth = url:match('(([0-9a-zA-Z]+:?[0-9a-zA-Z]+)@)')
url = url:sub((chunk and #chunk or 0) + 1)
local host
local hostname
local port
if protocol then
host = url:match("^([%a%.%d-]+:?%d*)")
if host then
hostname = host:match("^([^:/]+)")
port = host:match(":(%d+)$")
end
url = url:sub((host and #host or 0) + 1)
end
host = hostname -- Just to be compatible with our code base. Discuss this.
local path
local pathname
local search
local query
local hash
hash = url:match("(#.*)$")
url = url:sub(1, (#url - (hash and #hash or 0)))
if url ~= '' then
path = url
local temp
temp = url:match("^[^?]*")
if temp ~= '' then
pathname = temp
end
temp = url:sub((pathname and #pathname or 0) + 1)
if temp ~= '' then
search = temp
end
if search then
temp = search:sub(2)
if temp ~= '' then
query = temp
end
end
end
if parseQueryString then
query = querystring.parse(query)
end
return {
href = href,
protocol = protocol,
host = host,
hostname = hostname,
port = port,
pathname = pathname or '/',
search = search,
query = query,
auth = auth,
hash = hash
}
end
_url.parse = framework.util.parseUrl
--- Returns the char from a string at the specified position.
-- @param str the string from were a char will be extracted.
-- @param pos the position in the string. Should be a numeric value greater or equal than 1.
-- @return the char at the specified position. If the position does not exist in the string, nil is returned.
function framework.string.charAt(str, pos)
return string.sub(str, pos, pos)
end
local charAt = framework.string.charAt
--- Check if a string contains the specified pattern.
-- @param pattern the pattern to look for.
-- @param str the string to search from
-- @return true if the pattern exist inside the string.
function framework.string.contains(pattern, str)
local s,_ = string.find(str, pattern)
return s ~= nil
end
--- Replace placeholders with named keys inside a string.
-- @param str the string that has placeholders to be replaced. In example "Hello, {name}"
-- @param map a table with a list of key and values for replacement.
-- @return a string with all the ocurrences of placedholders replaced.
function framework.string.replace(str, map)
for k, v in pairs(map) do
str = str:gsub('{' .. k .. '}', v)
end
return str
end
local replace = framework.string.replace
--- Escape special characters used by pattern matching functionality.
-- @param str the string that will be escaped.
-- @return a new string with all the special characters escaped.
function framework.string.escape(str)
local s, _ = string.gsub(str, '%.', '%%.')
s, _ = string.gsub(s, '%-', '%%-')
return s
end
--- Decode an URL encoded string
-- @param str the URL encoded string
-- @return a new string decoded
function framework.string.urldecode(str)
local char, gsub, tonumber = string.char, string.gsub, tonumber
local function _(hex) return char(tonumber(hex, 16)) end
str = gsub(str, '%%(%x%x)', _)
return str
end
--- URL encode a string
-- @param str the string that will be encoded
-- @return a new string URL encoded
function framework.string.urlencode(str)
if str then
str = string.gsub(str, '\n', '\r\n')
str = string.gsub(str, '([^%w])', function(c)
return string.format('%%%02X', string.byte(c))
end)
end
return str
end
function framework.string.jsonsplit(self)
local outResults = {}
local theStart,theSplitEnd = string.find(self, "{")
local numOpens = theStart and 1 or 0
theSplitEnd = theSplitEnd and theSplitEnd + 1
while theSplitEnd < string.len(self) do
if self[theSplitEnd] == '{' then
numOpens = numOpens + 1
elseif self[theSplitEnd] == '}' then
numOpens = numOpens - 1
end
if numOpens == 0 then
table.insert( outResults, string.sub ( self, theStart, theSplitEnd ) )
theStart,theSplitEnd = string.find(self, "{", theSplitEnd)
numOpens = theStart and 0 or 1
theSplitEnd = theSplitEnd or string.len(self)
end
theSplitEnd = theSplitEnd + 1
end
return outResults
end
--- TODO: To be composable we need to change this interface to gsplit(separator, data)
function framework.string.gsplit(data, separator)
local pos = 1
local iter = function()
if not pos then -- stop the generator (maybe using stateless is a better option?)
return nil
end
local s, e = string.find(data, separator, pos)
if s then
local part = string.sub(data, pos, s-1)
pos = e + 1
return part
else
local part = string.sub(data, pos)
pos = nil
return part
end
end
return iter, data, 1
end
local gsplit = framework.string.gsplit
--- Split as an iterator
-- @param data that will be splitted.
-- @param separator a string or character for the split
-- @func func a function to call for each splitted part of the string
function framework.string.isplit(data, separator, func)
for part in gsplit(data, separator) do
func(part)
end
end
local isplit = framework.string.isplit
-- Split a string into parts
-- @param data the string to split
-- @param separator a string or character that breaks each part of the string.
-- @return a table with all the parts splitted from the string.
function framework.string.split(data, separator)
if not data then
return nil
end
local result = {}
isplit(data, separator, function (part) table.insert(result, part) end)
return result
end
local split = framework.string.split
--- Check if the string is empty. Before checking it will be trimmed to remove blank spaces.
function framework.string.isEmpty(str)
return (str == nil or framework.string.trim(str) == '')
end
local isEmpty = framework.string.isEmpty
--- If not empty returns the value. If is empty, an a default value was specified, it will return that value.
-- @param str the string that will be checked for empty
-- @param default a default value that will be returned if the string is empty
-- @return str or default is str is an empty string.
function framework.string.notEmpty(str, default)
return not framework.string.isEmpty(str) and str or default
end
local notEmpty = framework.string.notEmpty
--- Join two strings using a character
-- @param s1 any string
-- @param s2 any string
-- @param char a character
-- @return a new string with the join of s1 and s2 with character inbetween.
function framework.string.concat(s1, s2, char)
if isEmpty(s2) then
return s1
end
return s1 .. char .. s2
end
--- Utility functions.
-- Various functions that helps with common tasks.
-- @section util
--- Parses anchor links from an HTML string
-- @param html_str the html string from where links will be parsed.
-- @return a table with extracted links
function framework.util.parseLinks(html_str)
local links = {}
for link in string.gmatch(html_str, '<a%s+h?ref=["\']([^"^\']+)["\'][^>]*>[^<]*</%s*a>') do
table.insert(links, link)
end
return links
end
--- Creates an absolute link from a basePath and a relative link.
-- @param basePath the base path to generate an absolute link.
-- @param link a relative link
-- @return A string that represents the absolute link.
function framework.util.absoluteLink(basePath, link)
return basePath .. trim(link)
end
--- Check if the a link is a relative one.
-- @param link the link to check
-- @return true if the link is relative. false otherwise.
function framework.util.isRelativeLink(link)
return not string.match(string.lower(link), '^https?')
end
--- Wraps a function to calculate the time passed between the wrap and the function execution.
function framework.util.timed(func, startTime)
startTime = startTime or os.time()
return function(...)
return os.time() - startTime, func(...)
end
end
--- Check if an HTTP Status code is of a success kind.
-- @param status the status code number
-- @return true if status code is a success one.
function framework.util.isHttpSuccess(status)
return status >= 200 and status < 300
end
-- Check if an HTTP Status code is of a redirect kind.
-- @param status the status code number
-- @return true if status code is a redirect one.
function framework.util.isHttpRedirect(status)
return status >= 300 and status < 400
end
--- Round a number by the to the specified decimal places.
-- @param val the value that will be rounded
-- @param decimal the number of decimal places
-- @return the val rounded at decimal places
function framework.util.round(val, decimal)
assert(val, 'round expect a non-nil value')
if (decimal) then
return math.floor( (val * 10^decimal) + 0.5) / (10^decimal)
else
return math.floor(val+0.5)
end
end
--- Return the current timestamp
-- @return the current timestamp
function framework.util.currentTimestamp()
return os.time()
end
--- Convert megabytes to bytes.
-- @param mb the number of megabytes
-- @return the number of bytes that represent mb
function framework.util.megaBytesToBytes(mb)
return mb * 1024 * 1024
end
--- Represent a number as a percentage
-- @param number the number to represent as a percentage
-- @return number/100
function framework.util.percentage(number)
return number/100
end
--- Pack a tuple that represent a metric into a table
function framework.util.pack(metric, value, timestamp, source)
if value then
return { metric = metric, value = value, timestamp = timestamp, source = source }
end
return nil
end
--- Pack a value for a metric into a table
function framework.util.packValue(value, timestamp, source)
return { value = value, timestamp = timestamp, source = source }
end
function framework.util.ipack(metrics, ...)
table.insert(metrics, framework.util.pack(...))
end
--- Create an auth for HTTP Basic Authentication
function framework.util.auth(username, password)
return notEmpty(username) and notEmpty(password) and (username .. ':' .. password) or nil
end
-- Returns an string for a Boundary Meter event.
-- @param type could be 'CRITICAL', 'ERROR', 'WARN', 'INFO'
function framework.util.eventString(type, message, tags)
tags = tags or ''
return string.format('_bevent:%s|t:%s|tags:%s', message, type, tags)
end
local eventString = framework.util.eventString
--- Functional functions
-- @section functional
--- Return the partial application of a function.
-- @param func a function that will be partially applied.
-- @param x the parameter to partially apply.
-- @return A new function with the application of the x parameter.
function framework.functional.partial(func, x)
return function (...)
return func(x, ...)
end
end
--- Represents the identity function
-- @param x any value
-- @return x
function framework.functional.identity(...)
return ...
end
local identity = framework.functional.identity
-- Propagate the event to another emitter.
function Emitter:propagate(eventName, target, transform)
if (target and target.emit) then
transform = transform or identity
self:on(eventName, function (...) target:emit(eventName, transform(...)) end)
return target
end
return self
end
--- Compose to functions g(f(x))
-- @param f any function
-- @param g any function
-- @return A new function that is the composition of f and g
function framework.functional.compose(f, g)
return function(...)
return g(f(...))
end
end
--- Table functions
-- @section table
--- Get the value at the specified key for a table
-- @param key the key for indexing the table
-- @param t a any table
-- @return the value at the specified key. If t is not a table nil will be returned.
function framework.table.get(key, t)
if type(t) ~= 'table' then
return nil
end
return t[key]
end
--- Find a value inside a table
-- @param a predicate function that test the items of the table
-- @return the first item in the table that satisfy the test condition
function framework.table.find(func, t)
for i, v in pairs(t) do
if func(v, i, t) then
return v, i
end
end
return nil
end
--- Get the number of elements of a table
-- @param t a table
-- @return the number of items from the table
function framework.table.count(t)
local count = 0
for _ in pairs(t) do
count = count + 1
end
return count
end
function framework.table.toSet(t)
if not t then return nil end
local result = {}
local n = 0
for _, v in pairs(t) do
v = trim(v)
if v ~= '' then
n = n + 1
result[v] = true
end
end
return n > 0 and result or nil
end
function framework.util.add(a, b)
return a + b
end
local add = framework.util.add
local reduce = framework.functional.reduce
function framework.util.sum(t)
return reduce(add, 0, t)
end
local sum = framework.util.sum
--- Get the mean value of the elements from a table
-- @param t a table
-- @return the mean value
function framework.util.mean(t)
local count = table.getn(t)
if count == 0 then
return 0
end
local s = sum(t)
return s/count
end
function framework.util.ratio(x, y)
if y and tonumber(y) > 0 then
return x / y
end
return 0
end
function framework.util.parseJson(body)
return pcall(json.parse, body)
end
local parseJson = framework.util.parseJson
--- Get returns true if there is any element in the table.
-- @param t a table
-- @return true if there is any element in the table, false otherwise
function framework.table.hasAny(t)
return next(t) ~= nil
end
--- Get the index in the table for the specified value.
-- @param self any table
-- @param value the value to look for
-- @return a number that represent the index of value in the table. If the value does not exist, or t is not a table, nil will be returned.
function framework.table.indexOf(self, value)
if type(self) ~= 'table' then
return nil
end
for i,v in ipairs(self) do
if value == v then
return i
end
end
return nil
end
--- Get all the keys from the table.
-- @param t any table
-- @return a table with all the keys of t
function framework.table.keys(t)
local result = {}
for k,_ in pairs(t) do
table.insert(result, k)
end
return result
end
--- Get a deep copy of a table
-- @param t a table to be cloned
-- @return a new table that is the copy of t.
local clone
clone = function (t)
if type(t) ~= 'table' then return t end
local meta = getmetatable(t)
local target = {}
for k,v in pairs(t) do
if type(v) == 'table' then
target[k] = clone(v)
else
target[k] = v
end
end
setmetatable(target, meta)
return target
end
framework.table.clone = clone
--- Creates a table from a list of keys and values
-- @param keys a list of keys
-- @param values a list of kayes
-- @return a new table with the corresponding keys and values
function framework.table.create(keys, values)
local result = {}
for i, k in ipairs(keys) do
if notEmpty(trim(k)) then
result[k] = values[i]
end
end
return result
end
--- Merge to tables
-- @param t1 any table
-- @param t2 any table
-- @return return a new table with t1 and t2 merged.
function framework.table.merge(t1, t2)
local output = clone(t1)
for k, v in pairs(t2) do
if type(k) == 'number' then
table.insert(output, v)
else
output[k] = v
end
end
return output
end
local merge = framework.table.merge
--- Try to coerce a number or at least to a string.
-- @param x the value that will be converted.
-- @return return a number if x can be parsed, 0 if is an empty string or a string if is not convertible to a number.
function framework.util.parseValue(x)
return tonumber(x) or (isEmpty(x) and 0) or tostring(x) or 0
end
local parseValue = framework.util.parseValue
local map = framework.functional.map
-- TODO: Convert this to a generator
-- TODO: Use gsplit instead of split
function framework.string.parseCSV(data, separator, comment, header)
separator = separator or ','
local parsed = {}
local lines = split(data, '\n')
local headers
if header then
local header_line = string.match(lines[1], comment .. '%s*([' .. separator .. '%S]+)%s*')
headers = split(trim(header_line), separator)
end
for _, v in ipairs(lines) do
if notEmpty(v) then
if not comment or not (charAt(v, 1) == comment) then
local values = split(v, separator)
values = map(parseValue, values)
if headers then
table.insert(parsed, framework.table.create(headers, values))
else
table.insert(parsed, values)
end
end
end
end
return parsed
end
-- You can call framework.string() to export all functions to the string table to the global table for easy access.
local function exportable(t)
setmetatable(t, {
__call = function (u, warn)
for k,v in pairs(u) do
if (warn) then
if _G[k] ~= nil then
process.stderr:write('Warning: Overriding function ' .. k ..' on global space.')
end
end