-
Notifications
You must be signed in to change notification settings - Fork 0
/
common.lua
540 lines (469 loc) · 10.9 KB
/
common.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
local _, table_clear = pcall(require, 'table.clear')
local format = string.format
local common = {}
local ripairsIterator = function(t, i)
if i == 1 then
return nil
end
i = i - 1
return i, t[i]
end
function common.noop() end
function common.pass(...) return ... end
common.empty = setmetatable({}, {
__metatable = false,
__newindex = function() end
})
function common.isEmpty(t)
return nil == next(t)
end
function common.array(...)
local arr = {}
local length = 0
for v in ... do
length = length + 1
arr[length] = v
end
return arr
end
function common.array2(...)
local arr = {}
local length = 0
for v1, v2 in ... do
length = length + 1
arr[length] = {v1, v2}
end
return arr
end
function common.get(t, ...)
for i = 1, select('#', ...) do
if type(t) ~= 'table' then
return nil
end
t = t[select(i, ...)]
end
return t
end
function common.set(t, ...)
local argLen = select('#', ...)
assert(argLen > 0)
if argLen == 1 then
return (...)
end
for i = 1, argLen - 2 do
local key = select(i, ...)
if t[key] == nil then
t[key] = {}
end
t = t[key]
assert(type(t) ~= 'string', 'tried to index a string, but it\'s not allowed')
end
t[select(argLen - 1, ...)] = select(argLen, ...)
return t
end
function common.delete(t, ...)
local argLen = select('#', ...)
assert(argLen > 0)
if argLen == 1 then
local key = ...
t[key] = nil
if common.isEmpty(t) then
return nil
end
return t
end
local path = {
t
}
for i = 1, argLen - 1 do
local key = select(i, ...)
t = t[key]
if type(t) ~= 'table' then
return path[1]
end
path[i + 1] = t
end
for i = argLen, 1, -1 do
local key = select(i, ...)
t = path[i]
t[key] = nil
if not common.isEmpty(t) then
return path[1]
end
end
return nil
end
common.clear = table_clear or function(t)
for k in pairs(t) do
rawset(t, k, nil)
end
return t
end
common.pack = table.pack or function(...)
return {
n = select('#', ...),
...
}
end
function common.packCaptures(start, stop, ...)
return start, stop, common.pack(...)
end
common.unpack = table.unpack or unpack
function common.toPacked(t, len)
t.n = len or #t
return t
end
function common.toUnpacked(t)
t.n = nil
return t
end
function common.sub(t, i, j)
local tlen = #t
j = j or -1
if j < 0 then j = j + tlen + 1 end
if i < 0 then i = i + tlen + 1 end
if i < 1 then i = 1 end
if j > tlen then j = tlen end
local newT = {}
for k = i, j do
newT[k - i + 1] = t[k]
end
return newT
end
function common.ripairs(t)
return ripairsIterator, t, #t + 1
end
function common.keys(t)
local keys = {}
for k in pairs(t) do
table.insert(keys, k)
end
return keys
end
function common.values(t)
local values = {}
for _, v in pairs(t) do
table.insert(values, v)
end
return values
end
function common.singleToMulti(func)
return function(...)
local count = select('#', ...)
local values = {}
for i = 1, count do
values[i] = func((select(i, ...)))
end
return common.unpack(values, 1, count)
end
end
local qmap = {
[7] = 'a',
[8] = 'b',
[9] = 't',
[11] = 'v',
[12] = 'f',
[13] = 'r',
}
local function quote(value)
local str = format('%q', value)
str = str:gsub('(\\+)([\n%d]+)', function(bslash, match)
if #bslash % 2 == 1 then
if string.byte(match) == 10 then
return bslash .. 'n' .. match:sub(2)
end
local num = tonumber(match:sub(1, 3))
if num then
local map = qmap[num]
if map then
return bslash .. map .. match:sub(4)
end
end
end
end)
return str
end
common.quote = common.singleToMulti(quote)
local indentString = ' '
local function indentation(indent)
return indentString:rep(indent)
end
local function pretty(value, indent, refmap)
indent = indent or 0
local vtype = type(value)
if vtype == 'string' then
return quote(value)
elseif vtype == 'number' or vtype == 'boolean' then
return tostring(value)
end
refmap = refmap or {}
if vtype == 'table' and not refmap[value] then
if common.isEmpty(value) then
return '{}'
end
refmap[value] = true
local sequential = {}
local maxI = -1
local count = 0
local isArray = true
for k in pairs(value) do
if type(k) == 'number' and k >= 1 and k % 1 == 0 then
table.insert(sequential, k)
maxI = math.max(maxI, k)
else
isArray = false
end
count = count + 1
end
if isArray and count == maxI then
do
indent = indent + 1
local str = {'{\n'}
for _, v in ipairs(value) do
table.insert(str, format('%s%s,\n', indentation(indent), pretty(v, indent, refmap)))
end
indent = indent - 1
table.insert(str, indentation(indent))
table.insert(str, '}')
local final = table.concat(str)
local indentCharCount = ((indent + 1) * #indentString * count)
if #final - indentCharCount > 40 then -- If it's too short we just wanna do 1 line
return final
end
end
local str = {}
for _, v in ipairs(value) do
table.insert(str, pretty(v, indent, refmap))
end
return format('{ %s }', table.concat(str, ', '))
end
indent = indent + 1
local str = {'{\n'}
for k, v in pairs(value) do
if type(k) == 'string' then
if not k:match('^[%a_][%w_]*$') then
k = format('[%q]', k)
end
else
k = format('[%s]', pretty(k, 0, refmap))
end
table.insert(str, format('%s%s = %s,\n', indentation(indent), k, pretty(v, indent, refmap)))
end
indent = indent - 1
table.insert(str, indentation(indent))
table.insert(str, '}')
return table.concat(str)
end
return format('<%s>', value)
end
common.pretty = common.singleToMulti(pretty)
function common.fpprint(file, ...)
local values = {}
local vlen = select('#', ...)
for i = 1, vlen do
values[i] = pretty((select(i, ...)))
end
file:write(table.concat(values, ', ', 1, vlen), '\n')
end
function common.pprint(...)
common.fpprint(io.stdout, ...)
end
function common.epprint(...)
common.fpprint(io.stderr, ...)
end
local function readStream(stream, bytes)
if bytes == nil then bytes = -1 end
local result, err
if bytes < 0 then
if bytes == -1 then
result, err = stream:read '*a'
else
local size = stream:seek 'end'
stream:seek 'set'
result, err = stream:read(size + bytes + 1)
end
else
result, err = stream:read(bytes)
end
if not result then
stream:close()
return nil, err or 'could not read from stream'
end
local status
status, err = stream:close()
if not status then
return nil, err
end
return result
end
local function writeStream(stream, data)
local status, err = stream:write(data)
if not status then
stream:close()
return false, err or 'could not write to stream'
end
status, err = stream:close()
if not status then
return false, err
end
return true
end
function common.readFile(path, bytes)
local stream, err = io.open(path, 'rb')
if not stream then
return nil, err
end
return readStream(stream, bytes)
end
local function writeFile(path, data, mode)
local stream, err = io.open(path, mode)
if not stream then
return false, err
end
return writeStream(stream, data)
end
function common.writeFile(path, data)
return writeFile(path, data, 'wb')
end
function common.appendFile(path, data)
return writeFile(path, data, 'ab')
end
function common.fileLines(path)
local stream, err = io.open(path, 'r')
if not stream then
return nil, err
end
-- FIXME: technically this does not explicitly close the stream. It still gets closed when garbage collected
-- If we provide our own iterator we can close it, though it still wouldn't be closed on loop break
return stream:lines()
end
if jit then
common.isWindows = jit.os == 'Windows'
else
common.isWindows = os.getenv('OS') == 'Windows_NT'
end
if common.isWindows then
local escapes = {
[ '\0'] = '\\0',
['\10'] = '\\n',
['\13'] = '\\r',
[ '%'] = '"%"',
}
function common.formCommand(program, ...)
assert(program)
local args = common.pack(program:gsub('/', '\\'), ...)
for i = 1, args.n do
if not args[i]:match('^[%w_%-/\\:%?]+$') then
local val = args[i]:gsub('[%z\10\13%%]', function(char)
return escapes[char]
end)
args[i] = string.format('"%s"', val:gsub('(\\*)(")', function(bslash, dquote)
return bslash:rep(2) .. '\\' .. dquote
end))
end
end
return string.format('"%s"', table.concat(args, ' ', 1, args.n))
end
else
local escapes = {
['\0'] = '\\0',
}
function common.formCommand(program, ...)
assert(program)
local args = common.pack(program, ...)
for i = 1, args.n do
if not args[i]:match('^[%w_-/]+$') then
local val = args[i]:gsub('[%z\10\13]', function(char)
return escapes[char]
end)
args[i] = string.format("'%s'", val:gsub("'", "'\\''"))
end
end
return table.concat(args, ' ', 1, args.n)
end
end
function common.execute(program, ...)
return os.execute(common.formCommand(program, ...))
end
function common.readProcess(program, ...)
local line = common.formCommand(program, ...)
local mode = common.isWindows and 'rb' or 'r'
local stream, err = io.popen(line, mode)
if not stream then
return nil, err
end
return readStream(stream)
end
function common.writeProcess(data, program, ...)
local line = common.formCommand(program, ...)
local mode = common.isWindows and 'wb' or 'w'
local stream, err = io.popen(line, mode)
if not stream then
return false, err
end
return writeStream(stream, data)
end
function common.processLines(program, ...)
local line = common.formCommand(program, ...)
local stream, err = io.popen(line, 'r')
if not stream then
return nil, err
end
-- FIXME: technically this does not explicitly close the stream. It still gets closed when garbage collected
-- If we provide our own iterator we can close it, though it still wouldn't be closed on loop break
return stream:lines()
end
function common.readCommand(command)
local mode = common.isWindows and 'rb' or 'r'
local stream, err = io.popen(command, mode)
if not stream then
return nil, err
end
return readStream(stream)
end
function common.writeCommand(data, command)
local mode = common.isWindows and 'wb' or 'w'
local stream, err = io.popen(command, mode)
if not stream then
return false, err
end
return writeStream(stream, data)
end
function common.commandLines(command)
local stream, err = io.popen(command, 'r')
if not stream then
return nil, err
end
-- FIXME: technically this does not explicitly close the stream. It still gets closed when garbage collected
-- If we provide our own iterator we can close it, though it still wouldn't be closed on loop break
return stream:lines()
end
function common.equalAny(value, ...)
local count = select('#', ...)
if count == 0 then return true end
for i = 1, count do
if value == select(i, ...) then
return true
end
end
return false
end
function common.equalOne(value, ...)
local count = select('#', ...)
for i = 1, count do
if value == select(i, ...) then
return true
end
end
return false
end
function common.equalAll(value, ...)
local count = select('#', ...)
for i = 1, count do
if value ~= select(i, ...) then
return false
end
end
return true
end
return common