mirror of
https://github.com/TangentFoxy/argparse.git
synced 2025-07-28 02:52:20 +00:00
Implement command actions
This commit is contained in:
@@ -128,4 +128,34 @@ describe("actions", function()
|
||||
parser:parse{"-n", "-n1", "-n", "-n", "2"}
|
||||
assert.same({0, 1, 0, 2}, numbers)
|
||||
end)
|
||||
|
||||
it("for parser are called", function()
|
||||
local parser = Parser()
|
||||
parser:flag("-f"):count("0-3")
|
||||
local args
|
||||
parser:action(function(passed_args) args = passed_args end)
|
||||
parser:parse{"-ff"}
|
||||
assert.same({f = 2}, args)
|
||||
end)
|
||||
|
||||
it("for commands are called in reverse order", function()
|
||||
local args = {}
|
||||
|
||||
local parser = Parser():action(function(passed_args)
|
||||
args[1] = passed_args
|
||||
args.last = 1
|
||||
end)
|
||||
parser:flag("-f"):count("0-3")
|
||||
local foo = parser:command("foo"):action(function(passed_args)
|
||||
args[2] = passed_args
|
||||
args.last = 2
|
||||
end)
|
||||
foo:flag("-g")
|
||||
parser:parse{"foo", "-f", "-g", "-f"}
|
||||
assert.same({
|
||||
last = 1,
|
||||
{foo = true, f = 2, g = true},
|
||||
{foo = true, f = 2, g = true}
|
||||
}, args)
|
||||
end)
|
||||
end)
|
||||
|
@@ -221,6 +221,7 @@ local Parser = class({
|
||||
typechecked("help", "string"),
|
||||
typechecked("require_command", "boolean"),
|
||||
typechecked("handle_options", "boolean"),
|
||||
typechecked("action", "function"),
|
||||
add_help
|
||||
})
|
||||
|
||||
@@ -236,6 +237,7 @@ local Command = class({
|
||||
typechecked("help", "string"),
|
||||
typechecked("require_command", "boolean"),
|
||||
typechecked("handle_options", "boolean"),
|
||||
typechecked("action", "function"),
|
||||
add_help
|
||||
}, Parser)
|
||||
|
||||
@@ -840,7 +842,8 @@ local ParseState = class({
|
||||
arguments = {},
|
||||
argument_i = 1,
|
||||
element_to_mutexes = {},
|
||||
mutex_to_used_option = {}
|
||||
mutex_to_used_option = {},
|
||||
command_actions = {}
|
||||
})
|
||||
|
||||
function ParseState:__call(parser, error_handler)
|
||||
@@ -858,6 +861,10 @@ end
|
||||
function ParseState:switch(parser)
|
||||
self.parser = parser
|
||||
|
||||
if parser._action then
|
||||
table.insert(self.command_actions, parser._action)
|
||||
end
|
||||
|
||||
for _, option in ipairs(parser._options) do
|
||||
option = ElementState(self, option)
|
||||
table.insert(self.options, option)
|
||||
@@ -1004,6 +1011,10 @@ function ParseState:finalize()
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
for i = #self.command_actions, 1, -1 do
|
||||
self.command_actions[i](self.result)
|
||||
end
|
||||
end
|
||||
|
||||
function ParseState:parse(args)
|
||||
|
Reference in New Issue
Block a user