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

lunarmodules / Penlight / 7854178009

10 Feb 2024 10:07AM UTC coverage: 88.938%. Remained the same
7854178009

Pull #463

github

web-flow
fix(doc): typo in example
Pull Request #463: fix(doc): typo in example

5443 of 6120 relevant lines covered (88.94%)

256.24 hits per line

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

96.15
/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
264✔
9
local compat = require 'pl.compat'
264✔
10
local stdout = io.stdout
264✔
11
local append = table.insert
264✔
12
local concat = table.concat
264✔
13
local _unpack = table.unpack  -- always injected by 'compat'
264✔
14
local find = string.find
264✔
15
local sub = string.sub
264✔
16
local next = next
264✔
17
local floor = math.floor
264✔
18

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

25

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

29
--- Some standard patterns
30
-- @table patterns
31
utils.patterns = {
264✔
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
}
264✔
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 = {
264✔
46
    List = {_name='List'},
264✔
47
    Map = {_name='Map'},
264✔
48
    Set = {_name='Set'},
264✔
49
    MultiMap = {_name='MultiMap'},
264✔
50
}
264✔
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
264✔
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)
264✔
80
    return _unpack(t, i or 1, j or t.n or #t)
606✔
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, ...)
264✔
88
    utils.assert_string(1, fmt)
18✔
89
    utils.fprintf(stdout, fmt, ...)
12✔
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,...)
264✔
97
    utils.assert_string(2,fmt)
140✔
98
    f:write(format(fmt,...))
140✔
99
end
100

101
do
102
    local function import_symbol(T,k,v,libname)
103
        local key = rawget(T,k)
671✔
104
        -- warn about collisions!
105
        if key and k ~= '_M' and k ~= '_NAME' and k ~= '_PACKAGE' and k ~= '_VERSION' then
671✔
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)
669✔
110
    end
111

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

119
    local already_imported = {}
264✔
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)
264✔
125
        T = T or _G
18✔
126
        t = t or utils
18✔
127
        if type(t) == 'string' then
18✔
128
            t = require (t)
6✔
129
        end
130
        local libname = lookup_lib(T,t)
18✔
131
        if already_imported[t] then return end
18✔
132
        already_imported[t] = libname
18✔
133
        for k,v in pairs(t) do
689✔
134
            import_symbol(T,k,v,libname)
671✔
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)
264✔
144
    if cond then
72✔
145
        return value1
42✔
146
    else
147
        return value2
30✔
148
    end
149
end
150

151
--- convert an array of values to strings.
152
-- @param t a list-like table
153
-- @param[opt] temp (table) buffer to use, otherwise allocate
154
-- @param[opt] tostr custom tostring function, called with (value,index). Defaults to `tostring`.
155
-- @return the converted buffer
156
function utils.array_tostring (t,temp,tostr)
264✔
157
    temp, tostr = temp or {}, tostr or tostring
144✔
158
    for i = 1,#t do
978✔
159
        temp[i] = tostr(t[i],i)
834✔
160
    end
161
    return temp
144✔
162
end
163

164

165

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

182

183

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

219
  else
220
    return function()
221
      i = i + step
384✔
222
      if i > i_end then
384✔
223
        return nil
102✔
224
      end
225
      return i, t[i]
282✔
226
    end
227
  end
228
end
229

230

231

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

271

272

273
--- Error handling
274
-- @section Error-handling
275

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

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

364
  if type(first) ~= "table" then
108✔
365
    -- vararg with strings
366
    lst = utils.pack(...)
80✔
367
    for i, value in utils.npairs(lst) do
276✔
368
      utils.assert_arg(i, value, "string")
144✔
369
      enum[value] = value
132✔
370
    end
371

372
  else
373
    -- table/array with values
374
    utils.assert_arg(1, first, "table")
48✔
375
    lst = {}
48✔
376
    -- first add array part
377
    for i, value in ipairs(first) do
84✔
378
      if type(value) ~= "string" then
42✔
379
        error(("expected 'string' but got '%s' at index %d"):format(type(value), i), 2)
6✔
380
      end
381
      lst[i] = value
36✔
382
      enum[value] = value
36✔
383
    end
384
    -- add key-ed part
385
    for key, value in utils.kpairs(first) do
102✔
386
      if type(key) ~= "string" then
36✔
387
        error(("expected key to be 'string' but got '%s'"):format(type(key)), 2)
6✔
388
      end
389
      if enum[key] then
30✔
390
        error(("duplicate entry in array and hash part: '%s'"):format(key), 2)
6✔
391
      end
392
      enum[key] = value
24✔
393
      lst[#lst+1] = key
24✔
394
    end
395
  end
396

397
  if not lst[1] then
78✔
398
    error("expected at least 1 entry", 2)
18✔
399
  end
400

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

420
  return enum
60✔
421
end
422

423

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

465

466
--- assert the common case that the argument is a string.
467
-- @param n argument index
468
-- @param val a value that must be a string
469
-- @return the validated value
470
-- @raise val must be a string
471
-- @usage
472
-- local val = 42
473
-- local param2 = utils.assert_string(2, val) --> error: argument 2 expected a 'string', got a 'number'
474
function utils.assert_string (n, val)
264✔
475
    return utils.assert_arg(n,val,'string',nil,nil,3)
18,893✔
476
end
477

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

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

522

523

524
--- File handling
525
-- @section files
526

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

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

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

585
--- OS functions
586
-- @section OS-functions
587

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

600
    if is_windows and not outfile:find(':') then
192✔
601
        outfile = os.getenv('TEMP')..outfile
×
602
        errfile = os.getenv('TEMP')..errfile
×
603
    end
604
    cmd = cmd .. " > " .. utils.quote_arg(outfile) .. " 2> " .. utils.quote_arg(errfile)
320✔
605

606
    local success, retcode = utils.execute(cmd)
192✔
607
    local outcontent = utils.readfile(outfile, bin)
192✔
608
    local errcontent = utils.readfile(errfile, bin)
192✔
609
    os.remove(outfile)
192✔
610
    os.remove(errfile)
192✔
611
    return success, retcode, (outcontent or ""), (errcontent or "")
192✔
612
end
613

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

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

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

659
        return argument
594✔
660
    end
661
end
662

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

683

684
--- String functions
685
-- @section string-functions
686

687
--- escape any Lua 'magic' characters in a string
688
-- @param s The input string
689
function utils.escape(s)
264✔
690
    utils.assert_string(1,s)
954✔
691
    return (s:gsub('[%-%.%+%[%]%(%)%$%^%%%?%*]','%%%1'))
954✔
692
end
693

694
--- split a string into a list of strings separated by a delimiter.
695
-- @param s The input string
696
-- @param re optional A Lua string pattern; defaults to '%s+'
697
-- @param plain optional If truthy don't use Lua patterns
698
-- @param n optional maximum number of elements (if there are more, the last will remain un-split)
699
-- @return a list-like table
700
-- @raise error if s is not a string
701
-- @see splitv
702
function utils.split(s,re,plain,n)
264✔
703
    utils.assert_string(1,s)
1,047✔
704
    local i1,ls = 1,{}
1,047✔
705
    if not re then re = '%s+' end
1,047✔
706
    if re == '' then return {s} end
1,047✔
707
    while true do
708
        local i2,i3 = find(s,re,i1,plain)
3,651✔
709
        if not i2 then
3,651✔
710
            local last = sub(s,i1)
927✔
711
            if last ~= '' then append(ls,last) end
927✔
712
            if #ls == 1 and ls[1] == '' then
927✔
713
                return {}
12✔
714
            else
715
                return ls
915✔
716
            end
717
        end
718
        append(ls,sub(s,i1,i2-1))
3,630✔
719
        if n and #ls == n then
2,724✔
720
            ls[#ls] = sub(s,i1)
144✔
721
            return ls
108✔
722
        end
723
        i1 = i3+1
2,616✔
724
    end
725
end
726

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

743

744
--- Functional
745
-- @section functional
746

747

748
--- 'memoize' a function (cache returned value for next call).
749
-- This is useful if you have a function which is relatively expensive,
750
-- but you don't know in advance what values will be required, so
751
-- building a table upfront is wasteful/impossible.
752
-- @param func a function that takes exactly one argument (which later serves as the cache key) and returns a single value
753
-- @return a function taking one argument and returning a single value either from the cache or by running the original input function
754
function utils.memoize(func)
264✔
755
    local cache = {}
270✔
756
    return function(k)
757
        local res = cache[k]
114✔
758
        if res == nil then
114✔
759
            res = func(k)
144✔
760
            cache[k] = res
108✔
761
        end
762
        return res
114✔
763
    end
764
end
765

766

767
--- associate a function factory with a type.
768
-- A function factory takes an object of the given type and
769
-- returns a function for evaluating it
770
-- @tab mt metatable
771
-- @func fun a callable that returns a function
772
function utils.add_function_factory (mt,fun)
264✔
773
    _function_factories[mt] = fun
18✔
774
end
775

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

795

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

806

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

826

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

845

846

847

848
--- Deprecation
849
-- @section deprecation
850

851
do
852
  -- the default implementation
853
  local deprecation_func = function(msg, trace)
854
    if trace then
48✔
855
      warn(msg, "\n", trace)  -- luacheck: ignore
40✔
856
    else
857
      warn(msg)  -- luacheck: ignore
18✔
858
    end
859
  end
860

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

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

932
    msg = opts.message .. msg
90✔
933

934
    if opts.source then
90✔
935
      msg = "[" .. opts.source .."] " .. msg
66✔
936
    else
937
      if msg:sub(1,1) == "@" then
32✔
938
        -- in Lua 5.4 "@" prefixed messages are control messages to the warn system
939
        error("message cannot start with '@'", 2)
×
940
      end
941
    end
942

943
    deprecation_func(msg, trace)
90✔
944
  end
945

946
end
947

948

949
return utils
264✔
950

951

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