Skip to content

Commit

Permalink
Merge pull request #15 from katyukha/dev-unparsed-args
Browse files Browse the repository at this point in the history
Save unparsed (rest) args on result
  • Loading branch information
robik authored Feb 17, 2024
2 parents bfb7531 + 1aa0ce1 commit 08708fe
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 1 deletion.
4 changes: 3 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -12,4 +12,6 @@ commandr-test-*
*.obj
*.lst
/commandr
source/app.d
source/app.d
libcommandr.a
*.sw[npo]
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 08708fe

Please sign in to comment.