From 98ac85299b57c07e719c39f81ce4a226f5df9aa3 Mon Sep 17 00:00:00 2001 From: Anton Sviridov Date: Sat, 20 Jul 2024 17:31:14 +0100 Subject: [PATCH] Cleanup interface --- CommandApplication.scala | 15 ++++++++++++--- macros.scala | 37 ++++++++++++++++++++----------------- 2 files changed, 32 insertions(+), 20 deletions(-) diff --git a/CommandApplication.scala b/CommandApplication.scala index a6f882f..9313d87 100644 --- a/CommandApplication.scala +++ b/CommandApplication.scala @@ -5,10 +5,11 @@ import scala.deriving.* import scala.quoted.* trait CommandApplication[T]: - val opt: Command[T] - private[decline_derive] val subcommands: List[Command[T]] + def command: Command[T] + def subcommands: List[Command[T]] object CommandApplication: + inline def derived[T](using Mirror.Of[T]): CommandApplication[T] = ${ Macros.derivedMacro[T] } @@ -16,5 +17,13 @@ object CommandApplication: args: Seq[String], env: Map[String, String] = Map.empty ): Either[Help, T] = - summon[CommandApplication[T]].opt.parse(args, env) + summon[CommandApplication[T]].command.parse(args, env) + + class Impl[T]( + val opt: Command[T], + val sub: List[Command[T]] + ) extends CommandApplication[T]: + override def command: Command[T] = opt + override def subcommands: List[Command[T]] = this.sub + end Impl end CommandApplication diff --git a/macros.scala b/macros.scala index 4c300d5..83341d7 100644 --- a/macros.scala +++ b/macros.scala @@ -76,19 +76,21 @@ private[decline_derive] object Macros: val command = getString[commandName] val derivedSubcommands = '{ - $elements.map(_.opt).map(Opts.subcommand(_)).reduce(_ orElse _) + $elements.map(_.command).map(Opts.subcommand(_)).reduce(_ orElse _) + } + + val cmd = '{ + Command( + ${ hints.name }.getOrElse($command.toLowerCase()), + ${ hints.help }.getOrElse("") + )($derivedSubcommands.asInstanceOf) } '{ - new CommandApplication[T]: - override val opt: Command[T] = - Command( - ${ hints.name }.getOrElse($command.toLowerCase()), - ${ hints.help }.getOrElse("") - )($derivedSubcommands.asInstanceOf) - - override val subcommands: List[Command[T]] = - $elements.map(_.opt).asInstanceOf + CommandApplication.Impl( + $cmd, + $elements.map(_.command).asInstanceOf + ): CommandApplication[T] } case '{ @@ -129,14 +131,15 @@ private[decline_derive] object Macros: .map($m.fromProduct) } + val cmd = '{ + Command[T]( + ${ hints.name }.getOrElse($name.toLowerCase()), + ${ hints.help }.getOrElse("") + )($combined) + } + '{ - new CommandApplication[T]: - override val opt: Command[T] = - Command[T]( - ${ hints.name }.getOrElse($name.toLowerCase()), - ${ hints.help }.getOrElse("") - )($combined) - override val subcommands: List[Command[T]] = Nil + CommandApplication.Impl($cmd, Nil) } end match end derivedMacro