implement a nice API wrapper for getopt

develop
Myk Taylor 2020-11-03 16:19:50 -08:00 committed by myk002
parent 3b45878d41
commit 175776812e
No known key found for this signature in database
GPG Key ID: 8A39CA0FA0C16E78
1 changed files with 49 additions and 0 deletions

@ -613,6 +613,55 @@ function processArgs(args, validArgs)
return result
end
-- processes commandline options according to optionActions and returns all
-- argument strings that are not options.
--
-- optionActions is a vector with elements in the following format:
-- {shortOptionName, longOptionAlias, hasArg=boolean, handler=fn}
-- shortOptionName and handler are required. If the option takes an argument,
-- it will be passed to the handler function.
-- longOptionAlias is optional.
-- hasArgument defaults to false.
--
-- example usage:
--
-- local filename = nil
-- local open_readonly = false
-- local nonoptions = processArgs2(args, {
-- {'r', handler=function() open_readonly = true end},
-- {'f', 'filename', hasArg=true,
-- handler=function(optarg) filename = optarg end}
-- })
--
-- when args is {'first', '-f', 'fname', 'second'}
-- then filename will be fname and nonoptions will contain {'first', 'second'}
function processArgs2(args, optionActions)
local sh_opts, long_opts = '', {}
local handlers = {}
for _,optionAction in ipairs(optionActions) do
local sh_opt,long_opt = optionAction[1], optionAction[2]
if not sh_opt or type(sh_opt) ~= 'string' or #sh_opt ~= 1 then
qerror('optionAction missing option letter at index 1')
end
if not optionAction.handler then
qerror(string.format('handler missing for option "%s"', sh_opt))
end
sh_opts = sh_opts .. sh_opt
if optionAction.hasArg then sh_opts = sh_opts .. ':' end
handlers[sh_opt] = optionAction.handler
if long_opt then
long_opts[long_opt] = sh_opt
handlers[long_opt] = optionAction.handler
end
end
local getopt = require('3rdparty.alt_getopt').get_ordered_opts
local opts, optargs, nonoptions = getopt(args, sh_opts, long_opts)
for i,v in ipairs(opts) do
handlers[v](optargs[i])
end
return nonoptions
end
function fillTable(table1,table2)
for k,v in pairs(table2) do
table1[k] = v