quoted args are optional

This commit is contained in:
Er2 2022-02-13 15:22:12 +03:00
parent e8a1270932
commit fefafd4923
2 changed files with 56 additions and 32 deletions

View file

@ -7,6 +7,9 @@ local tools = require 'api.tools'
local api = require 'api.api' local api = require 'api.api'
api.__index = api api.__index = api
api.parseArgs = tools.parseArgs
api.unparseArgs = tools.unparseArgs
function api:_ev(t, i, name, ...) function api:_ev(t, i, name, ...)
local v = t[i] local v = t[i]
if v.name == name then if v.name == name then
@ -37,38 +40,8 @@ local function receiveUpdate(self, update)
-- remove needn't text -- remove needn't text
msg.text = msg.text:sub(#cmd + #(to or '') + 3) msg.text = msg.text:sub(#cmd + #(to or '') + 3)
local args = {}
-- "quoted" and not quoted args support for v in msg.text:gmatch '%S+' do table.insert(args, v) end
-- inside quotes, buffer and final args
local iq, buf, args = false, '', {}
local qt, esc = nil, false -- quote type and escape, addition
-- helper function, add args and clean buffer
local function psh()
if #buf > 0 then table.insert(args, buf) end
buf = ''
qt = nil
end
for i = 1, #msg.text do
local v = msg.text:sub(i, i)
print(v, buf, iq)
-- if space and not inside quotes
if (v == ' ' or v == '\n' or v == '\t')
and not iq then psh()
elseif esc then esc, buf = false, buf.. v
elseif v == '\\' then esc = true
elseif (not qt or qt == v)
and (v == '"' or v == "'") then
psh()
qt, iq = v, not iq -- quote type, inside quote
else buf = buf.. v -- append buffer
end
end
psh() -- if has something
msg.cmd = cmd msg.cmd = cmd
msg.args = args msg.args = args

View file

@ -18,6 +18,57 @@ function tools.fetchCmd(text)
text:match '/[%w_]+@([%w_]+)' -- to text:match '/[%w_]+@([%w_]+)' -- to
end end
function tools.parseArgs(text)
-- inside quotes, buffer and final args
local iq, buf, args = false, '', {}
local qt, esc = nil, false -- quote type and escape, addition
-- helper functin, add args and clear buffer
local function psh()
if #buf > 0 then table.insert(args, buf) end
buf, qt = '', nil
end
for i = 1, #text + 1 do
local v = text:sub(i, i)
-- if space and inside quotes, or end of string
if ((v == ' ' or v == '\n' or v == '\t') and not iq)
or v == ''
then psh()
elseif esc then esc, buf = false, buf.. v
elseif v == '\\' then esc = true
-- if (no current quote or same quote) and quote is supported
elseif (not qt or qt == v)
and (v == '"' or v == "'")
then psh()
qt, iq = v, not iq -- quote type, inside quote
else buf = buf.. v -- append buffer
end
end
return args
end
function tools.unparseArgs(args)
-- args to string
local text = ''
for i = 1, #args do
local v = args[i]
if type(v) == 'string' then
if v:match '%s'
then text = text.. '"'.. v ..'" '
else text = text.. v ..' '
end
end
end
return text
end
function tools._req(url, meth, data, ctype) function tools._req(url, meth, data, ctype)
assert(url, 'Provide URL!') assert(url, 'Provide URL!')
assert(meth, 'Provide method!') assert(meth, 'Provide method!')