• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

lunarmodules / Penlight / 452

pending completion
452

push

appveyor

fix(filepattern): the pattern only matches filenames, not full paths

5 of 5 new or added lines in 1 file covered. (100.0%)

5372 of 6008 relevant lines covered (89.41%)

348.4 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

96.07
/lua/pl/utils.lua
1
--- Generally useful routines.
2
-- See  @{01-introduction.md.Generally_useful_functions|the Guide}.
3
--
4
-- Dependencies: `pl.compat`, all exported fields and functions from
5
-- `pl.compat` are also available in this module.
6
--
7
-- @module pl.utils
8
local format = string.format
352✔
9
local compat = require 'pl.compat'
352✔
10
local stdout = io.stdout
352✔
11
local append = table.insert
352✔
12
local concat = table.concat
352✔
13
local _unpack = table.unpack  -- always injected by 'compat'
352✔
14
local find = string.find
352✔
15
local sub = string.sub
352✔
16
local next = next
352✔
17
local floor = math.floor
352✔
18

19
local is_windows = compat.is_windows
352✔
20
local err_mode = 'default'
352✔
21
local raise
22
local operators
23
local _function_factories = {}
352✔
24

25

26
local utils = { _VERSION = "1.13.1" }
352✔
27
for k, v in pairs(compat) do utils[k] = v  end
3,344✔
28

29
--- Some standard patterns
30
-- @table patterns
31
utils.patterns = {
352✔
32
    FLOAT = '[%+%-%d]%d*%.?%d*[eE]?[%+%-]?%d*', -- floating point number
176✔
33
    INTEGER = '[+%-%d]%d*',                     -- integer number
176✔
34
    IDEN = '[%a_][%w_]*',                       -- identifier
176✔
35
    FILE = '[%a%.\\][:%][%w%._%-\\]*',          -- file
176✔
36
}
352✔
37

38

39
--- Standard meta-tables as used by other Penlight modules
40
-- @table stdmt
41
-- @field List the List metatable
42
-- @field Map the Map metatable
43
-- @field Set the Set metatable
44
-- @field MultiMap the MultiMap metatable
45
utils.stdmt = {
352✔
46
    List = {_name='List'},
352✔
47
    Map = {_name='Map'},
352✔
48
    Set = {_name='Set'},
352✔
49
    MultiMap = {_name='MultiMap'},
352✔
50
}
352✔
51

52

53
--- pack an argument list into a table.
54
-- @param ... any arguments
55
-- @return a table with field `n` set to the length
56
-- @function utils.pack
57
-- @see compat.pack
58
-- @see utils.npairs
59
-- @see utils.unpack
60
utils.pack = table.pack  -- added here to be symmetrical with unpack
352✔
61

62
--- unpack a table and return its contents.
63
--
64
-- NOTE: this implementation differs from the Lua implementation in the way
65
-- that this one DOES honor the `n` field in the table `t`, such that it is 'nil-safe'.
66
-- @param t table to unpack
67
-- @param[opt] i index from which to start unpacking, defaults to 1
68
-- @param[opt] j index of the last element to unpack, defaults to `t.n` or else `#t`
69
-- @return multiple return values from the table
70
-- @function utils.unpack
71
-- @see compat.unpack
72
-- @see utils.pack
73
-- @see utils.npairs
74
-- @usage
75
-- local t = table.pack(nil, nil, nil, 4)
76
-- local a, b, c, d = table.unpack(t)   -- this `unpack` is NOT nil-safe, so d == nil
77
--
78
-- local a, b, c, d = utils.unpack(t)   -- this is nil-safe, so d == 4
79
function utils.unpack(t, i, j)
352✔
80
    return _unpack(t, i or 1, j or t.n or #t)
800✔
81
end
82

83
--- print an arbitrary number of arguments using a format.
84
-- Output will be sent to `stdout`.
85
-- @param fmt The format (see `string.format`)
86
-- @param ... Extra arguments for format
87
function utils.printf(fmt, ...)
352✔
88
    utils.assert_string(1, fmt)
24✔
89
    utils.fprintf(stdout, fmt, ...)
16✔
90
end
91

92
--- write an arbitrary number of arguments to a file using a format.
93
-- @param f File handle to write to.
94
-- @param fmt The format (see `string.format`).
95
-- @param ... Extra arguments for format
96
function utils.fprintf(f,fmt,...)
352✔
97
    utils.assert_string(2,fmt)
186✔
98
    f:write(format(fmt,...))
186✔
99
end
100

101
do
102
    local function import_symbol(T,k,v,libname)
103
        local key = rawget(T,k)
892✔
104
        -- warn about collisions!
105
        if key and k ~= '_M' and k ~= '_NAME' and k ~= '_PACKAGE' and k ~= '_VERSION' then
892✔
106
            utils.fprintf(io.stderr,"warning: '%s.%s' will not override existing symbol\n",libname,k)
2✔
107
            return
2✔
108
        end
109
        rawset(T,k,v)
890✔
110
    end
111

112
    local function lookup_lib(T,t)
113
        for k,v in pairs(T) do
923✔
114
            if v == t then return k end
907✔
115
        end
116
        return '?'
16✔
117
    end
118

119
    local already_imported = {}
352✔
120

121
    --- take a table and 'inject' it into the local namespace.
122
    -- @param t The table (table), or module name (string), defaults to this `utils` module table
123
    -- @param T An optional destination table (defaults to callers environment)
124
    function utils.import(t,T)
352✔
125
        T = T or _G
24✔
126
        t = t or utils
24✔
127
        if type(t) == 'string' then
24✔
128
            t = require (t)
8✔
129
        end
130
        local libname = lookup_lib(T,t)
24✔
131
        if already_imported[t] then return end
24✔
132
        already_imported[t] = libname
24✔
133
        for k,v in pairs(t) do
916✔
134
            import_symbol(T,k,v,libname)
892✔
135
        end
136
    end
137
end
138

139
--- return either of two values, depending on a condition.
140
-- @param cond A condition
141
-- @param value1 Value returned if cond is truthy
142
-- @param value2 Value returned if cond is falsy
143
function utils.choose(cond, value1, value2)
352✔
144
    return cond and value1 or value2
48✔
145
end
146

147
--- convert an array of values to strings.
148
-- @param t a list-like table
149
-- @param[opt] temp (table) buffer to use, otherwise allocate
150
-- @param[opt] tostr custom tostring function, called with (value,index). Defaults to `tostring`.
151
-- @return the converted buffer
152
function utils.array_tostring (t,temp,tostr)
352✔
153
    temp, tostr = temp or {}, tostr or tostring
192✔
154
    for i = 1,#t do
1,304✔
155
        temp[i] = tostr(t[i],i)
1,112✔
156
    end
157
    return temp
192✔
158
end
159

160

161

162
--- is the object of the specified type?
163
-- If the type is a string, then use type, otherwise compare with metatable
164
-- @param obj An object to check
165
-- @param tp String of what type it should be
166
-- @return boolean
167
-- @usage utils.is_type("hello world", "string")   --> true
168
-- -- or check metatable
169
-- local my_mt = {}
170
-- local my_obj = setmetatable(my_obj, my_mt)
171
-- utils.is_type(my_obj, my_mt)  --> true
172
function utils.is_type (obj,tp)
352✔
173
    if type(tp) == 'string' then return type(obj) == tp end
24✔
174
    local mt = getmetatable(obj)
8✔
175
    return tp == mt
8✔
176
end
177

178

179

180
--- an iterator with indices, similar to `ipairs`, but with a range.
181
-- This is a nil-safe index based iterator that will return `nil` when there
182
-- is a hole in a list. To be safe ensure that table `t.n` contains the length.
183
-- @tparam table t the table to iterate over
184
-- @tparam[opt=1] integer i_start start index
185
-- @tparam[opt=t.n or #t] integer i_end end index
186
-- @tparam[opt=1] integer step step size
187
-- @treturn integer index
188
-- @treturn any value at index (which can be `nil`!)
189
-- @see utils.pack
190
-- @see utils.unpack
191
-- @usage
192
-- local t = utils.pack(nil, 123, nil)  -- adds an `n` field when packing
193
--
194
-- for i, v in utils.npairs(t, 2) do  -- start at index 2
195
--   t[i] = tostring(t[i])
196
-- end
197
--
198
-- -- t = { n = 3, [2] = "123", [3] = "nil" }
199
function utils.npairs(t, i_start, i_end, step)
352✔
200
  step = step or 1
176✔
201
  if step == 0 then
176✔
202
    error("iterator step-size cannot be 0", 2)
8✔
203
  end
204
  local i = (i_start or 1) - step
168✔
205
  i_end = i_end or t.n or #t
168✔
206
  if step < 0 then
168✔
207
    return function()
208
      i = i + step
64✔
209
      if i < i_end then
64✔
210
        return nil
16✔
211
      end
212
      return i, t[i]
48✔
213
    end
214

215
  else
216
    return function()
217
      i = i + step
512✔
218
      if i > i_end then
512✔
219
        return nil
136✔
220
      end
221
      return i, t[i]
376✔
222
    end
223
  end
224
end
225

226

227

228
--- an iterator over all non-integer keys (inverse of `ipairs`).
229
-- It will skip any key that is an integer number, so negative indices or an
230
-- array with holes will not return those either (so it returns slightly less than
231
-- 'the inverse of `ipairs`').
232
--
233
-- This uses `pairs` under the hood, so any value that is iterable using `pairs`
234
-- will work with this function.
235
-- @tparam table t the table to iterate over
236
-- @treturn key
237
-- @treturn value
238
-- @usage
239
-- local t = {
240
--   "hello",
241
--   "world",
242
--   hello = "hallo",
243
--   world = "Welt",
244
-- }
245
--
246
-- for k, v in utils.kpairs(t) do
247
--   print("German: ", v)
248
-- end
249
--
250
-- -- output;
251
-- -- German: hallo
252
-- -- German: Welt
253
function utils.kpairs(t)
352✔
254
  local index
255
  return function()
256
    local value
257
    while true do
258
      index, value = next(t, index)
192✔
259
      if type(index) ~= "number" or floor(index) ~= index then
192✔
260
        break
5✔
261
      end
262
    end
263
    return index, value
128✔
264
  end
265
end
266

267

268

269
--- Error handling
270
-- @section Error-handling
271

272
--- assert that the given argument is in fact of the correct type.
273
-- @param n argument index
274
-- @param val the value
275
-- @param tp the type
276
-- @param verify an optional verification function
277
-- @param msg an optional custom message
278
-- @param lev optional stack position for trace, default 2
279
-- @return the validated value
280
-- @raise if `val` is not the correct type
281
-- @usage
282
-- local param1 = assert_arg(1,"hello",'table')  --> error: argument 1 expected a 'table', got a 'string'
283
-- local param4 = assert_arg(4,'!@#$%^&*','string',path.isdir,'not a directory')
284
--      --> error: argument 4: '!@#$%^&*' not a directory
285
function utils.assert_arg (n,val,tp,verify,msg,lev)
352✔
286
    if type(val) ~= tp then
33,870✔
287
        error(("argument %d expected a '%s', got a '%s'"):format(n,tp,type(val)),lev or 2)
64✔
288
    end
289
    if verify and not verify(val) then
33,906✔
290
        error(("argument %d: '%s' %s"):format(n,val,msg),lev or 2)
24✔
291
    end
292
    return val
33,782✔
293
end
294

295
--- creates an Enum or constants lookup table for improved error handling.
296
-- This helps prevent magic strings in code by throwing errors for accessing
297
-- non-existing values, and/or converting strings/identifiers to other values.
298
--
299
-- Calling on the object does the same, but returns a soft error; `nil + err`, if
300
-- the call is succesful (the key exists), it will return the value.
301
--
302
-- When calling with varargs or an array the values will be equal to the keys.
303
-- The enum object is read-only.
304
-- @tparam table|vararg ... the input for the Enum. If varargs or an array then the
305
-- values in the Enum will be equal to the names (must be strings), if a hash-table
306
-- then values remain (any type), and the keys must be strings.
307
-- @return Enum object (read-only table/object)
308
-- @usage -- Enum access at runtime
309
-- local obj = {}
310
-- obj.MOVEMENT = utils.enum("FORWARD", "REVERSE", "LEFT", "RIGHT")
311
--
312
-- if current_movement == obj.MOVEMENT.FORWARD then
313
--   -- do something
314
--
315
-- elseif current_movement == obj.MOVEMENT.REVERES then
316
--   -- throws error due to typo 'REVERES', so a silent mistake becomes a hard error
317
--   -- "'REVERES' is not a valid value (expected one of: 'FORWARD', 'REVERSE', 'LEFT', 'RIGHT')"
318
--
319
-- end
320
-- @usage -- standardized error codes
321
-- local obj = {
322
--   ERR = utils.enum {
323
--     NOT_FOUND = "the item was not found",
324
--     OUT_OF_BOUNDS = "the index is outside the allowed range"
325
--   },
326
--
327
--   some_method = function(self)
328
--     return self.ERR.OUT_OF_BOUNDS
329
--   end,
330
-- }
331
--
332
-- local result, err = obj:some_method()
333
-- if not result then
334
--   if err == obj.ERR.NOT_FOUND then
335
--     -- check on error code, not magic strings
336
--
337
--   else
338
--     -- return the error description, contained in the constant
339
--     return nil, "error: "..err  -- "error: the index is outside the allowed range"
340
--   end
341
-- end
342
-- @usage -- validating/converting user-input
343
-- local color = "purple"
344
-- local ansi_colors = utils.enum {
345
--   black     = 30,
346
--   red       = 31,
347
--   green     = 32,
348
-- }
349
-- local color_code, err = ansi_colors(color) -- calling on the object, returns the value from the enum
350
-- if not color_code then
351
--   print("bad 'color', " .. err)
352
--   -- "bad 'color', 'purple' is not a valid value (expected one of: 'black', 'red', 'green')"
353
--   os.exit(1)
354
-- end
355
function utils.enum(...)
352✔
356
  local first = select(1, ...)
144✔
357
  local enum = {}
144✔
358
  local lst
359

360
  if type(first) ~= "table" then
144✔
361
    -- vararg with strings
362
    lst = utils.pack(...)
100✔
363
    for i, value in utils.npairs(lst) do
424✔
364
      utils.assert_arg(i, value, "string")
192✔
365
      enum[value] = value
176✔
366
    end
367

368
  else
369
    -- table/array with values
370
    utils.assert_arg(1, first, "table")
64✔
371
    lst = {}
64✔
372
    -- first add array part
373
    for i, value in ipairs(first) do
112✔
374
      if type(value) ~= "string" then
56✔
375
        error(("expected 'string' but got '%s' at index %d"):format(type(value), i), 2)
8✔
376
      end
377
      lst[i] = value
48✔
378
      enum[value] = value
48✔
379
    end
380
    -- add key-ed part
381
    for key, value in utils.kpairs(first) do
160✔
382
      if type(key) ~= "string" then
48✔
383
        error(("expected key to be 'string' but got '%s'"):format(type(key)), 2)
8✔
384
      end
385
      if enum[key] then
40✔
386
        error(("duplicate entry in array and hash part: '%s'"):format(key), 2)
8✔
387
      end
388
      enum[key] = value
32✔
389
      lst[#lst+1] = key
32✔
390
    end
391
  end
392

393
  if not lst[1] then
104✔
394
    error("expected at least 1 entry", 2)
24✔
395
  end
396

397
  local valid = "(expected one of: '" .. concat(lst, "', '") .. "')"
80✔
398
  setmetatable(enum, {
160✔
399
    __index = function(self, key)
400
      error(("'%s' is not a valid value %s"):format(tostring(key), valid), 2)
16✔
401
    end,
402
    __newindex = function(self, key, value)
403
      error("the Enum object is read-only", 2)
8✔
404
    end,
405
    __call = function(self, key)
406
      if type(key) == "string" then
16✔
407
        local v = rawget(self, key)
16✔
408
        if v ~= nil then
16✔
409
          return v
8✔
410
        end
411
      end
412
      return nil, ("'%s' is not a valid value %s"):format(tostring(key), valid)
8✔
413
    end
414
  })
415

416
  return enum
80✔
417
end
418

419

420
--- process a function argument.
421
-- This is used throughout Penlight and defines what is meant by a function:
422
-- Something that is callable, or an operator string as defined by <code>pl.operator</code>,
423
-- such as '>' or '#'. If a function factory has been registered for the type, it will
424
-- be called to get the function.
425
-- @param idx argument index
426
-- @param f a function, operator string, or callable object
427
-- @param msg optional error message
428
-- @return a callable
429
-- @raise if idx is not a number or if f is not callable
430
function utils.function_arg (idx,f,msg)
352✔
431
    utils.assert_arg(1,idx,'number')
2,608✔
432
    local tp = type(f)
2,608✔
433
    if tp == 'function' then return f end  -- no worries!
2,608✔
434
    -- ok, a string can correspond to an operator (like '==')
435
    if tp == 'string' then
536✔
436
        if not operators then operators = require 'pl.operator'.optable end
456✔
437
        local fn = operators[f]
456✔
438
        if fn then return fn end
456✔
439
        local fn, err = utils.string_lambda(f)
56✔
440
        if not fn then error(err..': '..f) end
56✔
441
        return fn
56✔
442
    elseif tp == 'table' or tp == 'userdata' then
80✔
443
        local mt = getmetatable(f)
72✔
444
        if not mt then error('not a callable object',2) end
72✔
445
        local ff = _function_factories[mt]
64✔
446
        if not ff then
64✔
447
            if not mt.__call then error('not a callable object',2) end
×
448
            return f
×
449
        else
450
            return ff(f) -- we have a function factory for this type!
64✔
451
        end
452
    end
453
    if not msg then msg = " must be callable" end
8✔
454
    if idx > 0 then
8✔
455
        error("argument "..idx..": "..msg,2)
8✔
456
    else
457
        error(msg,2)
×
458
    end
459
end
460

461

462
--- assert the common case that the argument is a string.
463
-- @param n argument index
464
-- @param val a value that must be a string
465
-- @return the validated value
466
-- @raise val must be a string
467
-- @usage
468
-- local val = 42
469
-- local param2 = utils.assert_string(2, val) --> error: argument 2 expected a 'string', got a 'number'
470
function utils.assert_string (n, val)
352✔
471
    return utils.assert_arg(n,val,'string',nil,nil,3)
24,253✔
472
end
473

474
--- control the error strategy used by Penlight.
475
-- This is a global setting that controls how `utils.raise` behaves:
476
--
477
-- - 'default': return `nil + error` (this is the default)
478
-- - 'error': throw a Lua error
479
-- - 'quit': exit the program
480
--
481
-- @param mode either 'default', 'quit'  or 'error'
482
-- @see utils.raise
483
function utils.on_error (mode)
352✔
484
    mode = tostring(mode)
80✔
485
    if ({['default'] = 1, ['quit'] = 2, ['error'] = 3})[mode] then
80✔
486
      err_mode = mode
56✔
487
    else
488
      -- fail loudly
489
      local err = "Bad argument expected string; 'default', 'quit', or 'error'. Got '"..tostring(mode).."'"
24✔
490
      if err_mode == 'default' then
24✔
491
        error(err, 2)  -- even in 'default' mode fail loud in this case
8✔
492
      end
493
      raise(err)
16✔
494
    end
495
end
496

497
--- used by Penlight functions to return errors. Its global behaviour is controlled
498
-- by `utils.on_error`.
499
-- To use this function you MUST use it in conjunction with `return`, since it might
500
-- return `nil + error`.
501
-- @param err the error string.
502
-- @see utils.on_error
503
-- @usage
504
-- if some_condition then
505
--   return utils.raise("some condition was not met")  -- MUST use 'return'!
506
-- end
507
function utils.raise (err)
352✔
508
    if err_mode == 'default' then
72✔
509
        return nil, err
40✔
510
    elseif err_mode == 'quit' then
32✔
511
        return utils.quit(err)
16✔
512
    else
513
        error(err, 2)
16✔
514
    end
515
end
516
raise = utils.raise
352✔
517

518

519

520
--- File handling
521
-- @section files
522

523
--- return the contents of a file as a string
524
-- @param filename The file path
525
-- @param is_bin open in binary mode
526
-- @return file contents
527
function utils.readfile(filename,is_bin)
352✔
528
    local mode = is_bin and 'b' or ''
628✔
529
    utils.assert_string(1,filename)
628✔
530
    local f,open_err = io.open(filename,'r'..mode)
628✔
531
    if not f then return raise (open_err) end
628✔
532
    local res,read_err = f:read('*a')
628✔
533
    f:close()
628✔
534
    if not res then
628✔
535
        -- Errors in io.open have "filename: " prefix,
536
        -- error in file:read don't, add it.
537
        return raise (filename..": "..read_err)
×
538
    end
539
    return res
628✔
540
end
541

542
--- write a string to a file
543
-- @param filename The file path
544
-- @param str The string
545
-- @param is_bin open in binary mode
546
-- @return true or nil
547
-- @return error message
548
-- @raise error if filename or str aren't strings
549
function utils.writefile(filename,str,is_bin)
352✔
550
    local mode = is_bin and 'b' or ''
136✔
551
    utils.assert_string(1,filename)
136✔
552
    utils.assert_string(2,str)
136✔
553
    local f,err = io.open(filename,'w'..mode)
136✔
554
    if not f then return raise(err) end
136✔
555
    local ok, write_err = f:write(str)
136✔
556
    f:close()
136✔
557
    if not ok then
136✔
558
        -- Errors in io.open have "filename: " prefix,
559
        -- error in file:write don't, add it.
560
        return raise (filename..": "..write_err)
×
561
    end
562
    return true
136✔
563
end
564

565
--- return the contents of a file as a list of lines
566
-- @param filename The file path
567
-- @return file contents as a table
568
-- @raise error if filename is not a string
569
function utils.readlines(filename)
352✔
570
    utils.assert_string(1,filename)
8✔
571
    local f,err = io.open(filename,'r')
8✔
572
    if not f then return raise(err) end
8✔
573
    local res = {}
8✔
574
    for line in f:lines() do
2,568✔
575
        append(res,line)
2,560✔
576
    end
577
    f:close()
8✔
578
    return res
8✔
579
end
580

581
--- OS functions
582
-- @section OS-functions
583

584
--- execute a shell command and return the output.
585
-- This function redirects the output to tempfiles and returns the content of those files.
586
-- @param cmd a shell command
587
-- @param bin boolean, if true, read output as binary file
588
-- @return true if successful
589
-- @return actual return code
590
-- @return stdout output (string)
591
-- @return errout output (string)
592
function utils.executeex(cmd, bin)
352✔
593
    local outfile = os.tmpname()
304✔
594
    local errfile = os.tmpname()
304✔
595

596
    if is_windows and not outfile:find(':') then
304✔
597
        outfile = os.getenv('TEMP')..outfile
×
598
        errfile = os.getenv('TEMP')..errfile
×
599
    end
600
    cmd = cmd .. " > " .. utils.quote_arg(outfile) .. " 2> " .. utils.quote_arg(errfile)
608✔
601

602
    local success, retcode = utils.execute(cmd)
304✔
603
    local outcontent = utils.readfile(outfile, bin)
304✔
604
    local errcontent = utils.readfile(errfile, bin)
304✔
605
    os.remove(outfile)
304✔
606
    os.remove(errfile)
304✔
607
    return success, retcode, (outcontent or ""), (errcontent or "")
304✔
608
end
609

610
--- Quote and escape an argument of a command.
611
-- Quotes a single (or list of) argument(s) of a command to be passed
612
-- to `os.execute`, `pl.utils.execute` or `pl.utils.executeex`.
613
-- @param argument (string or table/list) the argument to quote. If a list then
614
-- all arguments in the list will be returned as a single string quoted.
615
-- @return quoted and escaped argument.
616
-- @usage
617
-- local options = utils.quote_arg {
618
--     "-lluacov",
619
--     "-e",
620
--     "utils = print(require('pl.utils')._VERSION",
621
-- }
622
-- -- returns: -lluacov -e 'utils = print(require('\''pl.utils'\'')._VERSION'
623
function utils.quote_arg(argument)
352✔
624
    if type(argument) == "table" then
892✔
625
        -- encode an entire table
626
        local r = {}
40✔
627
        for i, arg in ipairs(argument) do
168✔
628
            r[i] = utils.quote_arg(arg)
192✔
629
        end
630

631
        return concat(r, " ")
40✔
632
    end
633
    -- only a single argument
634
    if is_windows then
852✔
635
        if argument == "" or argument:find('[ \f\t\v]') then
852✔
636
            -- Need to quote the argument.
637
            -- Quotes need to be escaped with backslashes;
638
            -- additionally, backslashes before a quote, escaped or not,
639
            -- need to be doubled.
640
            -- See documentation for CommandLineToArgvW Windows function.
641
            argument = '"' .. argument:gsub([[(\*)"]], [[%1%1\"]]):gsub([[\+$]], "%0%0") .. '"'
48✔
642
        end
643

644
        -- os.execute() uses system() C function, which on Windows passes command
645
        -- to cmd.exe. Escape its special characters.
646
        return (argument:gsub('["^<>!|&%%]', "^%0"))
852✔
647
    else
648
        if argument == "" or argument:find('[^a-zA-Z0-9_@%+=:,./-]') then
×
649
            -- To quote arguments on posix-like systems use single quotes.
650
            -- To represent an embedded single quote close quoted string ('),
651
            -- add escaped quote (\'), open quoted string again (').
652
            argument = "'" .. argument:gsub("'", [['\'']]) .. "'"
×
653
        end
654

655
        return argument
×
656
    end
657
end
658

659
--- error out of this program gracefully.
660
-- @param[opt] code The exit code, defaults to -`1` if omitted
661
-- @param msg The exit message will be sent to `stderr` (will be formatted with the extra parameters)
662
-- @param ... extra arguments for message's format'
663
-- @see utils.fprintf
664
-- @usage utils.quit(-1, "Error '%s' happened", "42")
665
-- -- is equivalent to
666
-- utils.quit("Error '%s' happened", "42")  --> Error '42' happened
667
function utils.quit(code, msg, ...)
352✔
668
    if type(code) == 'string' then
48✔
669
        utils.fprintf(io.stderr, code, msg, ...)
24✔
670
        io.stderr:write('\n')
24✔
671
        code = -1 -- TODO: this is odd, see the test. Which returns 255 as exit code
24✔
672
    elseif msg then
24✔
673
        utils.fprintf(io.stderr, msg, ...)
16✔
674
        io.stderr:write('\n')
16✔
675
    end
676
    os.exit(code, true)
48✔
677
end
678

679

680
--- String functions
681
-- @section string-functions
682

683
--- escape any Lua 'magic' characters in a string
684
-- @param s The input string
685
function utils.escape(s)
352✔
686
    utils.assert_string(1,s)
952✔
687
    return (s:gsub('[%-%.%+%[%]%(%)%$%^%%%?%*]','%%%1'))
952✔
688
end
689

690
--- split a string into a list of strings separated by a delimiter.
691
-- @param s The input string
692
-- @param re optional A Lua string pattern; defaults to '%s+'
693
-- @param plain optional If truthy don't use Lua patterns
694
-- @param n optional maximum number of elements (if there are more, the last will remian un-split)
695
-- @return a list-like table
696
-- @raise error if s is not a string
697
-- @see splitv
698
function utils.split(s,re,plain,n)
352✔
699
    utils.assert_string(1,s)
1,387✔
700
    local i1,ls = 1,{}
1,387✔
701
    if not re then re = '%s+' end
1,387✔
702
    if re == '' then return {s} end
1,387✔
703
    while true do
704
        local i2,i3 = find(s,re,i1,plain)
4,857✔
705
        if not i2 then
4,857✔
706
            local last = sub(s,i1)
1,227✔
707
            if last ~= '' then append(ls,last) end
1,227✔
708
            if #ls == 1 and ls[1] == '' then
1,227✔
709
                return {}
16✔
710
            else
711
                return ls
1,211✔
712
            end
713
        end
714
        append(ls,sub(s,i1,i2-1))
5,442✔
715
        if n and #ls == n then
3,630✔
716
            ls[#ls] = sub(s,i1)
216✔
717
            return ls
144✔
718
        end
719
        i1 = i3+1
3,486✔
720
    end
721
end
722

723
--- split a string into a number of return values.
724
-- Identical to `split` but returns multiple sub-strings instead of
725
-- a single list of sub-strings.
726
-- @param s the string
727
-- @param re A Lua string pattern; defaults to '%s+'
728
-- @param plain don't use Lua patterns
729
-- @param n optional maximum number of splits
730
-- @return n values
731
-- @usage first,next = splitv('user=jane=doe','=', false, 2)
732
-- assert(first == "user")
733
-- assert(next == "jane=doe")
734
-- @see split
735
function utils.splitv (s,re, plain, n)
352✔
736
    return _unpack(utils.split(s,re, plain, n))
444✔
737
end
738

739

740
--- Functional
741
-- @section functional
742

743

744
--- 'memoize' a function (cache returned value for next call).
745
-- This is useful if you have a function which is relatively expensive,
746
-- but you don't know in advance what values will be required, so
747
-- building a table upfront is wasteful/impossible.
748
-- @param func a function of at least one argument
749
-- @return a function with at least one argument, which is used as the key.
750
function utils.memoize(func)
352✔
751
    local cache = {}
360✔
752
    return function(k)
753
        local res = cache[k]
152✔
754
        if res == nil then
152✔
755
            res = func(k)
216✔
756
            cache[k] = res
144✔
757
        end
758
        return res
152✔
759
    end
760
end
761

762

763
--- associate a function factory with a type.
764
-- A function factory takes an object of the given type and
765
-- returns a function for evaluating it
766
-- @tab mt metatable
767
-- @func fun a callable that returns a function
768
function utils.add_function_factory (mt,fun)
352✔
769
    _function_factories[mt] = fun
16✔
770
end
771

772
local function _string_lambda(f)
773
    if f:find '^|' or f:find '_' then
128✔
774
        local args,body = f:match '|([^|]*)|(.+)'
128✔
775
        if f:find '_' then
128✔
776
            args = '_'
72✔
777
            body = f
72✔
778
        else
779
            if not args then return raise 'bad string lambda' end
56✔
780
        end
781
        local fstr = 'return function('..args..') return '..body..' end'
128✔
782
        local fn,err = utils.load(fstr)
128✔
783
        if not fn then return raise(err) end
128✔
784
        fn = fn()
192✔
785
        return fn
128✔
786
    else
787
        return raise 'not a string lambda'
×
788
    end
789
end
790

791

792
--- an anonymous function as a string. This string is either of the form
793
-- '|args| expression' or is a function of one argument, '_'
794
-- @param lf function as a string
795
-- @return a function
796
-- @function utils.string_lambda
797
-- @usage
798
-- string_lambda '|x|x+1' (2) == 3
799
-- string_lambda '_+1' (2) == 3
800
utils.string_lambda = utils.memoize(_string_lambda)
528✔
801

802

803
--- bind the first argument of the function to a value.
804
-- @param fn a function of at least two values (may be an operator string)
805
-- @param p a value
806
-- @return a function such that f(x) is fn(p,x)
807
-- @raise same as @{function_arg}
808
-- @see func.bind1
809
-- @usage local function f(msg, name)
810
--   print(msg .. " " .. name)
811
-- end
812
--
813
-- local hello = utils.bind1(f, "Hello")
814
--
815
-- print(hello("world"))     --> "Hello world"
816
-- print(hello("sunshine"))  --> "Hello sunshine"
817
function utils.bind1 (fn,p)
352✔
818
    fn = utils.function_arg(1,fn)
120✔
819
    return function(...) return fn(p,...) end
264✔
820
end
821

822

823
--- bind the second argument of the function to a value.
824
-- @param fn a function of at least two values (may be an operator string)
825
-- @param p a value
826
-- @return a function such that f(x) is fn(x,p)
827
-- @raise same as @{function_arg}
828
-- @usage local function f(a, b, c)
829
--   print(a .. " " .. b .. " " .. c)
830
-- end
831
--
832
-- local hello = utils.bind1(f, "world")
833
--
834
-- print(hello("Hello", "!"))  --> "Hello world !"
835
-- print(hello("Bye", "?"))    --> "Bye world ?"
836
function utils.bind2 (fn,p)
352✔
837
    fn = utils.function_arg(1,fn)
12✔
838
    return function(x,...) return fn(x,p,...) end
16✔
839
end
840

841

842

843

844
--- Deprecation
845
-- @section deprecation
846

847
do
848
  -- the default implementation
849
  local deprecation_func = function(msg, trace)
850
    if trace then
64✔
851
      warn(msg, "\n", trace)  -- luacheck: ignore
60✔
852
    else
853
      warn(msg)  -- luacheck: ignore
24✔
854
    end
855
  end
856

857
  --- Sets a deprecation warning function.
858
  -- An application can override this function to support proper output of
859
  -- deprecation warnings. The warnings can be generated from libraries or
860
  -- functions by calling `utils.raise_deprecation`. The default function
861
  -- will write to the 'warn' system (introduced in Lua 5.4, or the compatibility
862
  -- function from the `compat` module for earlier versions).
863
  --
864
  -- Note: only applications should set/change this function, libraries should not.
865
  -- @param func a callback with signature: `function(msg, trace)` both arguments are strings, the latter being optional.
866
  -- @see utils.raise_deprecation
867
  -- @usage
868
  -- -- write to the Nginx logs with OpenResty
869
  -- utils.set_deprecation_func(function(msg, trace)
870
  --   ngx.log(ngx.WARN, msg, (trace and (" " .. trace) or nil))
871
  -- end)
872
  --
873
  -- -- disable deprecation warnings
874
  -- utils.set_deprecation_func()
875
  function utils.set_deprecation_func(func)
352✔
876
    if func == nil then
112✔
877
      deprecation_func = function() end
8✔
878
    else
879
      utils.assert_arg(1, func, "function")
104✔
880
      deprecation_func = func
96✔
881
    end
882
  end
883

884
  --- raises a deprecation warning.
885
  -- For options see the usage example below.
886
  --
887
  -- Note: the `opts.deprecated_after` field is the last version in which
888
  -- a feature or option was NOT YET deprecated! Because when writing the code it
889
  -- is quite often not known in what version the code will land. But the last
890
  -- released version is usually known.
891
  -- @param opts options table
892
  -- @see utils.set_deprecation_func
893
  -- @usage
894
  -- warn("@on")   -- enable Lua warnings, they are usually off by default
895
  --
896
  -- function stringx.islower(str)
897
  --   raise_deprecation {
898
  --     source = "Penlight " .. utils._VERSION,                   -- optional
899
  --     message = "function 'islower' was renamed to 'is_lower'", -- required
900
  --     version_removed = "2.0.0",                                -- optional
901
  --     deprecated_after = "1.2.3",                               -- optional
902
  --     no_trace = true,                                          -- optional
903
  --   }
904
  --   return stringx.is_lower(str)
905
  -- end
906
  -- -- output: "[Penlight 1.9.2] function 'islower' was renamed to 'is_lower' (deprecated after 1.2.3, scheduled for removal in 2.0.0)"
907
  function utils.raise_deprecation(opts)
352✔
908
    utils.assert_arg(1, opts, "table")
136✔
909
    if type(opts.message) ~= "string" then
128✔
910
      error("field 'message' of the options table must be a string", 2)
8✔
911
    end
912
    local trace
913
    if not opts.no_trace then
120✔
914
      trace = debug.traceback("", 2):match("[\n%s]*(.-)$")
88✔
915
    end
916
    local msg
917
    if opts.deprecated_after and opts.version_removed then
120✔
918
      msg = (" (deprecated after %s, scheduled for removal in %s)"):format(
144✔
919
        tostring(opts.deprecated_after), tostring(opts.version_removed))
144✔
920
    elseif opts.deprecated_after then
48✔
921
      msg = (" (deprecated after %s)"):format(tostring(opts.deprecated_after))
8✔
922
    elseif opts.version_removed then
40✔
923
      msg = (" (scheduled for removal in %s)"):format(tostring(opts.version_removed))
32✔
924
    else
925
      msg = ""
8✔
926
    end
927

928
    msg = opts.message .. msg
120✔
929

930
    if opts.source then
120✔
931
      msg = "[" .. opts.source .."] " .. msg
88✔
932
    else
933
      if msg:sub(1,1) == "@" then
48✔
934
        -- in Lua 5.4 "@" prefixed messages are control messages to the warn system
935
        error("message cannot start with '@'", 2)
×
936
      end
937
    end
938

939
    deprecation_func(msg, trace)
120✔
940
  end
941

942
end
943

944

945
return utils
352✔
946

947

STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc