Skip to content

Commit

Permalink
Cleanup interface
Browse files Browse the repository at this point in the history
  • Loading branch information
keynmol committed Jul 20, 2024
1 parent e13b2e3 commit 98ac852
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 20 deletions.
15 changes: 12 additions & 3 deletions CommandApplication.scala
Original file line number Diff line number Diff line change
Expand Up @@ -5,16 +5,25 @@ 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] }

inline def parse[T: 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
37 changes: 20 additions & 17 deletions macros.scala
Original file line number Diff line number Diff line change
Expand Up @@ -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 '{
Expand Down Expand Up @@ -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
Expand Down

0 comments on commit 98ac852

Please sign in to comment.