From 175776812e32e93ec9c85efb5576e4b10663aadf Mon Sep 17 00:00:00 2001 From: Myk Taylor Date: Tue, 3 Nov 2020 16:19:50 -0800 Subject: [PATCH] implement a nice API wrapper for getopt --- library/lua/utils.lua | 49 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) diff --git a/library/lua/utils.lua b/library/lua/utils.lua index 43dcdcd60..ee2cadd29 100644 --- a/library/lua/utils.lua +++ b/library/lua/utils.lua @@ -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