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

lunarmodules / Penlight / 4655740294

pending completion
4655740294

push

github

GitHub
fix(template): using magic characters as escapes (#452)

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

5279 of 6022 relevant lines covered (87.66%)

40.21 hits per line

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

94.24
/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')
1✔
24
if not status then
1✔
25
    sip = require 'sip'
×
26
end
27
local match = sip.match_at_start
1✔
28
local append,tinsert = table.insert,table.insert
1✔
29

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

32
local function lines(s) return s:gmatch('([^\n]*)\n') end
37✔
33
local function lstrip(str)  return str:gsub('^%s+','')  end
237✔
34
local function strip(str)  return lstrip(str):gsub('%s+$','') end
131✔
35
local function at(s,k)  return s:sub(k,k) end
9✔
36

37
local lapp = {}
1✔
38

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

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

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

48
--- controls whether to dump usage on error.
49
-- Defaults to true
50
lapp.show_usage_error = true
1✔
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)
1✔
56
    if no_usage == 'throw' then
4✔
57
        error(msg)
4✔
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)
1✔
72
    if not lapp.show_usage_error then
4✔
73
        no_usage = true
×
74
    elseif lapp.show_usage_error == 'throw' then
4✔
75
        no_usage = 'throw'
4✔
76
    end
77
    lapp.quit(script..': '..msg,no_usage)
4✔
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)
1✔
85
    local val,err = io.open(file,opt)
2✔
86
    if not val then lapp.error(err,true) end
2✔
87
    append(open_files,val)
2✔
88
    return val
2✔
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)
1✔
95
    if not condn then
129✔
96
        lapp.error(msg)
3✔
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')
2✔
102
end
103

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

110
local types = {}
1✔
111

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

114
local function convert_parameter(ps,val)
115
    if ps.converter then
68✔
116
        val = ps.converter(val)
2✔
117
    end
118
    if ps.type == 'number' then
68✔
119
        val = xtonumber(val)
5✔
120
    elseif builtin_types[ps.type] == 'file' then
63✔
121
        val = lapp.open(val,(ps.type == 'file-in' and 'r') or 'w' )
2✔
122
    elseif ps.type == 'boolean' then
61✔
123
        return val
11✔
124
    end
125
    if ps.constraint then
56✔
126
        ps.constraint(val)
13✔
127
    end
128
    return val
53✔
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)
1✔
138
    types[name] = {converter=converter,constraint=constraint}
1✔
139
end
140

141
local function force_short(short)
142
    lapp.assert(#short==1,short..": short parameters should be one character")
71✔
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
37✔
149
        val = tonumber(sval)
22✔
150
    end
151
    if val then -- we have a number!
37✔
152
        return val,'number'
13✔
153
    elseif filetypes[sval] then
24✔
154
        local ft = filetypes[sval]
6✔
155
        return ft[1],ft[2]
6✔
156
    else
157
        if sval == 'true' and not vtype then
18✔
158
            return true, 'boolean'
4✔
159
        end
160
        if sval:match '^["\']' then sval = sval:sub(2,-2) end
14✔
161

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

165
        local show_usage_error = lapp.show_usage_error
14✔
166
        lapp.show_usage_error = "throw"
14✔
167
        success, val = pcall(convert_parameter, ps, sval)
14✔
168
        lapp.show_usage_error = show_usage_error
14✔
169
        if success then
14✔
170
          return val, vtype or 'string'
14✔
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)
1✔
183
    local results = {}
36✔
184
    local varargs
185
    local arg = args or _G.arg
36✔
186
    open_files = {}
36✔
187
    parms = {}
36✔
188
    aliases = {}
36✔
189
    parmlist = {}
36✔
190

191
    local function check_varargs(s)
192
        local res,cnt = s:gsub('^%.%.%.%s*','')
88✔
193
        return res, (cnt > 0)
88✔
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
93✔
198
        if not ps.varargs then
93✔
199
            results[parm] = val
81✔
200
        else
201
            if not results[parm] then
12✔
202
                results[parm] = { val }
9✔
203
            else
204
                append(results[parm],val)
3✔
205
            end
206
        end
207
    end
208

209
    usage = str
36✔
210

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

217

218
    for line in lines(str) do
142✔
219
        local res = {}
106✔
220
        local optparm,defval,vtype,constraint,rest
221
        line = lstrip(line)
106✔
222
        local function check(str)
223
            return match(str,line,res)
237✔
224
        end
225

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

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

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

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

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

450

451
setmetatable(lapp, {
2✔
452
    __call = function(tbl,str,args) return lapp.process_options_string(str,args) end,
37✔
453
})
454

455

456
return lapp
1✔
457

458

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