Skip to content

Commit

Permalink
[ADD] Save unparsed arguments on ProgramArgs instance
Browse files Browse the repository at this point in the history
  • Loading branch information
katyukha committed Feb 23, 2023
1 parent a31c064 commit 1aa0ce1
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 0 deletions.
22 changes: 22 additions & 0 deletions source/commandr/args.d
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,7 @@ public class ProgramArgs {
int[string] _flags;
string[][string] _options;
string[][string] _args;
string[] _args_rest;
ProgramArgs _parent;
ProgramArgs _command;
}
Expand Down Expand Up @@ -222,6 +223,27 @@ public class ProgramArgs {
/// ditto
alias args = argAll;

/**
* Rest (unparsed) arguments.
*
* Useful, if you need to access unparsed arguments,
* usually supplied after '--'.
*
* Returns:
* array of arguments that were not handled by parser
*
* Examples:
* ---
* auto args = ["my-command", "--opt", "arg", "--", "other-arg", "o-arg"];
* auto res = parse(args);
*
* // Not we can access unparsed args as res.argsRest
* assert(res.argsRest == ["other-arg", "o-arg"])
* ---
*/
public string[] argsRest() {
return _args_rest;
}

/**
* Gets subcommand arguments.
Expand Down
5 changes: 5 additions & 0 deletions source/commandr/parser.d
Original file line number Diff line number Diff line change
Expand Up @@ -189,6 +189,9 @@ private ProgramArgs parseArgs(
}
}

if (args.length > 0)
result._args_rest = args.dup;

if (result.flag("help")) {
program.printHelp(helpConfig);
exit(0);
Expand Down Expand Up @@ -527,6 +530,7 @@ unittest {
.defaultValue("reee"))
.parseArgs(args);
assert(a.args("test") == ["reee"]);
assert(a.argsRest == ["bar"]);
assert(args == ["bar"]);
}

Expand Down Expand Up @@ -576,6 +580,7 @@ unittest {
assert(a.args("test") == ["cccc"]);
assert(a.command !is null);
assert(a.command.name == "a");
assert(a.command.argsRest == ["c"]);
assert(args == ["c"]);

assertThrown!InvalidArgumentsException(
Expand Down

0 comments on commit 1aa0ce1

Please sign in to comment.