Skip to content

Commit b72e1ee

Browse files
committed
experimental: provide hook to allow handling unknown subcommands
1 parent cb4fb81 commit b72e1ee

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed

argparse/src/argparse/core/ParsersApi.scala

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -652,6 +652,32 @@ trait ParsersApi extends VersionSpecificParsersApi { api: TypesApi =>
652652
_commandInfos += CommandInfo(name, action, description)
653653
}
654654

655+
private var _unknownCommand: String => Iterable[String] => String = null
656+
657+
/** Action to run on an unknown subcommand. Use it to support dynamic
658+
* subcommands.
659+
*
660+
* E.g. match on the exact command:
661+
*
662+
* ```
663+
* parser.unknownCommand {
664+
* case "foo" => args => foo(args)
665+
* }
666+
* ```
667+
*
668+
* * E.g. run an external command:
669+
* ```
670+
* parser.unknownCommand { name =>
671+
* args => os.proc("app-$name", args)
672+
* }
673+
* ```
674+
*/
675+
def unknownCommand(
676+
fn: String => Iterable[String] => String
677+
): Unit = {
678+
_unknownCommand = fn
679+
}
680+
655681
/** Parse the given arguments with respect to the parameters defined by
656682
* [[param]], [[requiredParam]], [[repeatedParam]] and [[command]].
657683
*/
@@ -696,6 +722,8 @@ trait ParsersApi extends VersionSpecificParsersApi { api: TypesApi =>
696722
_commandInfos.find(_.name == _command()) match {
697723
case Some(cmd) =>
698724
cmd.action(_commandArgs())
725+
case None if _unknownCommand != null =>
726+
_unknownCommand(_command())(_commandArgs())
699727
case None =>
700728
reportUnknownCommand(
701729
_command(),

0 commit comments

Comments
 (0)