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

lunarmodules / Penlight / 20584422718

29 Dec 2025 10:50PM UTC coverage: 88.862% (-0.4%) from 89.278%
20584422718

push

github

Tieske
temp: use busted from master [REVERT ME]

5457 of 6141 relevant lines covered (88.86%)

257.86 hits per line

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

94.67
/lua/pl/lapp.lua
1
--- Simple command-line parsing using human-readable specification.
2
-- Supports GNU-style parameters.
3
--
4
--      lapp = require 'pl.lapp'
5
--      local args = lapp [[
6
--      Does some calculations
7
--        -o,--offset (default 0.0)  Offset to add to scaled number
8
--        -s,--scale  (number)  Scaling factor
9
--        <number> (number) Number to be scaled
10
--      ]]
11
--
12
--      print(args.offset + args.scale * args.number)
13
--
14
-- Lines beginning with `'-'` are flags; there may be a short and a long name;
15
-- lines beginning with `'<var>'` are arguments.  Anything in parens after
16
-- the flag/argument is either a default, a type name or a range constraint.
17
--
18
-- See @{08-additional.md.Command_line_Programs_with_Lapp|the Guide}
19
--
20
-- Dependencies: `pl.sip`
21
-- @module pl.lapp
22

23
local status,sip = pcall(require,'pl.sip')
6✔
24
if not status then
6✔
25
    sip = require 'sip'
×
26
end
27
local match = sip.match_at_start
6✔
28
local append,tinsert = table.insert,table.insert
6✔
29

30
sip.custom_pattern('X','(%a[%w_%-]*)')
6✔
31

32
local function lines(s) return s:gmatch('([^\n]*)\n') end
222✔
33
local function lstrip(str)  return str:gsub('^%s+','')  end
1,422✔
34
local function strip(str)  return lstrip(str):gsub('%s+$','') end
1,046✔
35
local function at(s,k)  return s:sub(k,k) end
54✔
36

37
local lapp = {}
6✔
38

39
local open_files,parms,aliases,parmlist,usage,script
40

41
lapp.callback = false -- keep Strict happy
6✔
42

43
local filetypes = {
6✔
44
    stdin = {io.stdin,'file-in'}, stdout = {io.stdout,'file-out'},
6✔
45
    stderr = {io.stderr,'file-out'}
6✔
46
}
47

48
--- controls whether to dump usage on error.
49
-- Defaults to true
50
lapp.show_usage_error = true
6✔
51

52
--- quit this script immediately.
53
-- @string msg optional message
54
-- @bool no_usage suppress 'usage' display
55
function lapp.quit(msg,no_usage)
6✔
56
    if no_usage == 'throw' then
24✔
57
        error(msg)
24✔
58
    end
59
    if msg then
×
60
        io.stderr:write(msg..'\n\n')
×
61
    end
62
    if not no_usage then
×
63
        io.stderr:write(usage)
×
64
    end
65
    os.exit(1)
×
66
end
67

68
--- print an error to stderr and quit.
69
-- @string msg a message
70
-- @bool no_usage suppress 'usage' display
71
function lapp.error(msg,no_usage)
6✔
72
    if not lapp.show_usage_error then
24✔
73
        no_usage = true
×
74
    elseif lapp.show_usage_error == 'throw' then
24✔
75
        no_usage = 'throw'
24✔
76
    end
77
    lapp.quit(script..': '..msg,no_usage)
24✔
78
end
79

80
--- open a file.
81
-- This will quit on error, and keep a list of file objects for later cleanup.
82
-- @string file filename
83
-- @string[opt] opt same as second parameter of `io.open`
84
function lapp.open (file,opt)
6✔
85
    local val,err = io.open(file,opt)
12✔
86
    if not val then lapp.error(err,true) end
12✔
87
    append(open_files,val)
12✔
88
    return val
12✔
89
end
90

91
--- quit if the condition is false.
92
-- @bool condn a condition
93
-- @string msg message text
94
function lapp.assert(condn,msg)
6✔
95
    if not condn then
774✔
96
        lapp.error(msg)
18✔
97
    end
98
end
99

100
local function range_check(x,min,max,parm)
101
    lapp.assert(min <= x and max >= x,parm..' out of range')
12✔
102
end
103

104
local function xtonumber(s)
105
    local val = tonumber(s)
30✔
106
    if not val then lapp.error("unable to convert to number: "..s) end
30✔
107
    return val
24✔
108
end
109

110
local types = {}
6✔
111

112
local builtin_types = {string=true,number=true,['file-in']='file',['file-out']='file',boolean=true}
6✔
113

114
local function convert_parameter(ps,val)
115
    if ps.converter then
408✔
116
        val = ps.converter(val)
16✔
117
    end
118
    if ps.type == 'number' then
408✔
119
        val = xtonumber(val)
38✔
120
    elseif builtin_types[ps.type] == 'file' then
378✔
121
        val = lapp.open(val,(ps.type == 'file-in' and 'r') or 'w' )
16✔
122
    elseif ps.type == 'boolean' then
366✔
123
        return val
66✔
124
    end
125
    if ps.constraint then
336✔
126
        ps.constraint(val)
78✔
127
    end
128
    return val
318✔
129
end
130

131
--- add a new type to Lapp. These appear in parens after the value like
132
-- a range constraint, e.g. '<ival> (integer) Process PID'
133
-- @string name name of type
134
-- @param converter either a function to convert values, or a Lua type name.
135
-- @func[opt] constraint optional function to verify values, should use lapp.error
136
-- if failed.
137
function lapp.add_type (name,converter,constraint)
6✔
138
    types[name] = {converter=converter,constraint=constraint}
6✔
139
end
140

141
local function force_short(short)
142
    lapp.assert(#short==1,short..": short parameters should be one character")
426✔
143
end
144

145
-- deducing type of variable from default value;
146
local function process_default (sval,vtype)
147
    local val, success
148
    if not vtype or vtype == 'number' then
222✔
149
        val = tonumber(sval)
132✔
150
    end
151
    if val then -- we have a number!
222✔
152
        return val,'number'
78✔
153
    elseif filetypes[sval] then
144✔
154
        local ft = filetypes[sval]
36✔
155
        return ft[1],ft[2]
36✔
156
    else
157
        if sval == 'true' and not vtype then
108✔
158
            return true, 'boolean'
24✔
159
        end
160
        if sval:match '^["\']' then sval = sval:sub(2,-2) end
84✔
161

162
        local ps = types[vtype] or {}
84✔
163
        ps.type = vtype
84✔
164

165
        local show_usage_error = lapp.show_usage_error
84✔
166
        lapp.show_usage_error = "throw"
84✔
167
        success, val = pcall(convert_parameter, ps, sval)
112✔
168
        lapp.show_usage_error = show_usage_error
84✔
169
        if success then
84✔
170
          return val, vtype or 'string'
84✔
171
        end
172

173
        return sval,vtype or 'string'
×
174
    end
175
end
176

177
--- process a Lapp options string.
178
-- Usually called as `lapp()`.
179
-- @string str the options text
180
-- @tparam {string} args a table of arguments (default is `_G.arg`)
181
-- @return a table with parameter-value pairs
182
function lapp.process_options_string(str,args)
6✔
183
    local results = {}
216✔
184
    local varargs
185
    local arg = args or _G.arg
216✔
186
    open_files = {}
216✔
187
    parms = {}
216✔
188
    aliases = {}
216✔
189
    parmlist = {}
216✔
190

191
    local function check_varargs(s)
192
        local res,cnt = s:gsub('^%.%.%.%s*','')
528✔
193
        return res, (cnt > 0)
528✔
194
    end
195

196
    local function set_result(ps,parm,val)
197
        parm = type(parm) == "string" and parm:gsub("%W", "_") or parm -- so foo-bar becomes foo_bar in Lua
558✔
198
        if not ps.varargs then
558✔
199
            results[parm] = val
486✔
200
        else
201
            if not results[parm] then
72✔
202
                results[parm] = { val }
54✔
203
            else
204
                append(results[parm],val)
18✔
205
            end
206
        end
207
    end
208

209
    usage = str
216✔
210

211
    for _,a in ipairs(arg) do
690✔
212
      if a == "-h" or a == "--help" then
474✔
213
        return lapp.quit()
×
214
      end
215
    end
216

217

218
    for l in lines(str) do
924✔
219
        local line = l
636✔
220
        local res = {}
636✔
221
        local optparm,defval,vtype,constraint,rest
222
        line = lstrip(line)
848✔
223
        local function check(str)
224
            return match(str,line,res)
1,422✔
225
        end
226

227
        -- flags: either '-<short>', '-<short>,--<long>' or '--<long>'
228
        if check '-$v{short}, --$o{long} $' or check '-$v{short} $' or check '--$o{long} $' then
1,074✔
229
            if res.long then
528✔
230
                optparm = res.long:gsub('[^%w%-]','_')  -- I'm not sure the $o pattern will let anything else through?
198✔
231
                if #res.rest == 1 then optparm = optparm .. res.rest end
198✔
232
                if res.short then aliases[res.short] = optparm  end
198✔
233
            else
234
                optparm = res.short
330✔
235
            end
236
            if res.short and not lapp.slack then force_short(res.short) end
528✔
237
            res.rest, varargs = check_varargs(res.rest)
704✔
238
        elseif check '$<{name} $'  then -- is it <parameter_name>?
144✔
239
            -- so <input file...> becomes input_file ...
240
            optparm,rest = res.name:match '([^%.]+)(.*)'
54✔
241
            -- follow lua legal variable names
242
            optparm = optparm:sub(1,1):gsub('%A','_') .. optparm:sub(2):gsub('%W', '_')
90✔
243
            varargs = rest == '...'
54✔
244
            append(parmlist,optparm)
54✔
245
        end
246
        -- this is not a pure doc line and specifies the flag/parameter type
247
        if res.rest then
636✔
248
            line = res.rest
582✔
249
            res = {}
582✔
250
            local optional
251
            local defval_str
252
            -- do we have ([optional] [<type>] [default <val>])?
253
            if match('$({def} $',line,res) or match('$({def}',line,res) then
928✔
254
                local typespec = strip(res.def)
384✔
255
                local ftype, rest = typespec:match('^(%S+)(.*)$')
384✔
256
                rest = strip(rest)
512✔
257
                if ftype == 'optional' then
384✔
258
                    ftype, rest = rest:match('^(%S+)(.*)$')
12✔
259
                    rest = strip(rest)
16✔
260
                    optional = true
12✔
261
                end
262
                local default
263
                if ftype == 'default' then
384✔
264
                    default = true
90✔
265
                    if rest == '' then lapp.error("value must follow default") end
90✔
266
                else -- a type specification
267
                    if match('$f{min}..$f{max}',ftype,res) then
392✔
268
                        -- a numerical range like 1..10
269
                        local min,max = res.min,res.max
42✔
270
                        vtype = 'number'
42✔
271
                        constraint = function(x)
272
                            range_check(x,min,max,optparm)
12✔
273
                        end
274
                    elseif not ftype:match '|' then -- plain type
252✔
275
                        vtype = ftype
174✔
276
                    else
277
                        -- 'enum' type is a string which must belong to
278
                        -- one of several distinct values
279
                        local enums = ftype
78✔
280
                        local enump = '|' .. enums .. '|'
78✔
281
                        vtype = 'string'
78✔
282
                        constraint = function(s)
283
                            lapp.assert(enump:find('|'..s..'|', 1, true),
108✔
284
                              "value '"..s.."' not in "..enums
54✔
285
                            )
286
                        end
287
                    end
288
                end
289
                res.rest = rest
384✔
290
                typespec = res.rest
384✔
291
                -- optional 'default value' clause. Type is inferred as
292
                -- 'string' or 'number' if there's no explicit type
293
                if default or match('default $r{rest}',typespec,res) then
482✔
294
                    defval_str = res.rest
222✔
295
                    defval,vtype = process_default(res.rest,vtype)
296✔
296
                end
297
            else -- must be a plain flag, no extra parameter required
298
                defval = false
198✔
299
                vtype = 'boolean'
198✔
300
            end
301
            local ps = {
582✔
302
                type = vtype,
582✔
303
                defval = defval,
582✔
304
                defval_str = defval_str,
582✔
305
                required = defval == nil and not optional,
582✔
306
                comment = res.rest or optparm,
582✔
307
                constraint = constraint,
582✔
308
                varargs = varargs
582✔
309
            }
310
            varargs = nil
582✔
311
            if types[vtype] then
582✔
312
                local converter = types[vtype].converter
12✔
313
                if type(converter) == 'string' then
12✔
314
                    ps.type = converter
×
315
                else
316
                    ps.converter = converter
12✔
317
                end
318
                ps.constraint = types[vtype].constraint
12✔
319
            elseif not builtin_types[vtype] and vtype then
570✔
320
                lapp.error(vtype.." is unknown type")
×
321
            end
322
            parms[optparm] = ps
582✔
323
        end
324
    end
325
    -- cool, we have our parms, let's parse the command line args
326
    local iparm = 1
216✔
327
    local iextra = 1
216✔
328
    local i = 1
216✔
329
    local parm,ps,val
330
    local end_of_flags = false
216✔
331

332
    local function check_parm (parm)
333
        local eqi = parm:find '[=:]'
90✔
334
        if eqi then
90✔
335
            tinsert(arg,i+1,parm:sub(eqi+1))
32✔
336
            parm = parm:sub(1,eqi-1)
32✔
337
        end
338
        return parm,eqi
90✔
339
    end
340

341
    local function is_flag (parm)
342
        return parms[aliases[parm] or parm]
102✔
343
    end
344

345
    while i <= #arg do
516✔
346
        local theArg = arg[i]
330✔
347
        local res = {}
330✔
348
        -- after '--' we don't parse args and they end up in
349
        -- the array part of the result (args[1] etc)
350
        if theArg == '--' then
330✔
351
            end_of_flags = true
12✔
352
            iparm = #parmlist + 1
12✔
353
            i = i + 1
12✔
354
            theArg = arg[i]
12✔
355
            if not theArg then
12✔
356
                break
3✔
357
            end
358
        end
359
        -- look for a flag, -<short flags> or --<long flag>
360
        if not end_of_flags and (match('--$S{long}',theArg,res) or match('-$S{short}',theArg,res)) then
520✔
361
            if res.long then -- long option
264✔
362
                parm = check_parm(res.long)
48✔
363
            elseif #res.short == 1 or is_flag(res.short) then
250✔
364
                parm = res.short
174✔
365
            else
366
                local parmstr,eq = check_parm(res.short)
54✔
367
                if not eq then
54✔
368
                    parm = at(parmstr,1)
48✔
369
                    local flag = is_flag(parm)
36✔
370
                    if flag and flag.type ~= 'boolean' then
36✔
371
                    --if isdigit(at(parmstr,2)) then
372
                        -- a short option followed by a digit is an exception (for AW;))
373
                        -- push ahead into the arg array
374
                        tinsert(arg,i+1,parmstr:sub(2))
32✔
375
                    else
376
                        -- push multiple flags into the arg array!
377
                        for k = 2,#parmstr do
24✔
378
                            tinsert(arg,i+k-1,'-'..at(parmstr,k))
16✔
379
                        end
380
                    end
381
                else
382
                    parm = parmstr
18✔
383
                end
384
            end
385
            if aliases[parm] then parm = aliases[parm] end
264✔
386
            if not parms[parm] and (parm == 'h' or parm == 'help') then
264✔
387
                lapp.quit()
×
388
            end
389
        else -- a parameter
390
            parm = parmlist[iparm]
60✔
391
            if not parm then
60✔
392
               -- extra unnamed parameters are indexed starting at 1
393
               parm = iextra
18✔
394
               ps = { type = 'string' }
18✔
395
               parms[parm] = ps
18✔
396
               iextra = iextra + 1
18✔
397
            else
398
                ps = parms[parm]
42✔
399
            end
400
            if not ps.varargs then
60✔
401
                iparm = iparm + 1
48✔
402
            end
403
            val = theArg
60✔
404
        end
405
        ps = parms[parm]
324✔
406
        if not ps then lapp.error("unrecognized parameter: "..parm) end
324✔
407
        if ps.type ~= 'boolean' then -- we need a value! This should follow
324✔
408
            if not val then
258✔
409
                i = i + 1
198✔
410
                val = arg[i]
198✔
411
                theArg = val
198✔
412
            end
413
            lapp.assert(val,parm.." was expecting a value")
344✔
414
        else -- toggle boolean flags (usually false -> true)
415
            val = not ps.defval
66✔
416
        end
417
        ps.used = true
324✔
418
        val = convert_parameter(ps,val)
424✔
419
        set_result(ps,parm,val)
300✔
420
        if builtin_types[ps.type] == 'file' then
300✔
421
            set_result(ps,parm..'_name',theArg)
12✔
422
        end
423
        if lapp.callback then
300✔
424
            lapp.callback(parm,theArg,res)
18✔
425
        end
426
        i = i + 1
300✔
427
        val = nil
300✔
428
    end
429
    -- check unused parms, set defaults and check if any required parameters were missed
430
    for parm,ps in pairs(parms) do
696✔
431
        if not ps.used then
504✔
432
            if ps.required then lapp.error("missing required parameter: "..parm) end
222✔
433
            set_result(ps,parm,ps.defval)
222✔
434
            if builtin_types[ps.type] == "file" then
222✔
435
                set_result(ps, parm .. "_name", ps.defval_str)
24✔
436
            end
437
        end
438
    end
439
    return results
192✔
440
end
441

442
if arg then
6✔
443
    script = arg[0]
6✔
444
    script = script or rawget(_G,"LAPP_SCRIPT") or "unknown"
6✔
445
    -- strip dir and extension to get current script name
446
    script = script:gsub('.+[\\/]',''):gsub('%.%a+$','')
6✔
447
else
448
    script = "inter"
×
449
end
450

451

452
setmetatable(lapp, {
12✔
453
    __call = function(tbl,str,args) return lapp.process_options_string(str,args) end,
222✔
454
})
455

456

457
return lapp
6✔
458

459

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

© 2026 Coveralls, Inc