Skip to content

Commit

Permalink
Add custom handler helper (#3)
Browse files Browse the repository at this point in the history
  • Loading branch information
alexarchambault authored Jul 5, 2023
1 parent f513b84 commit ff17885
Showing 1 changed file with 19 additions and 4 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,10 @@ package scala.cli.directivehandler

import scala.cli.directivehandler.EitherSequence._

final case class DirectiveHandlers[T](handlers: Seq[DirectiveHandler[T]]) {
final case class DirectiveHandlers[T](
handlers: Seq[DirectiveHandler[T]],
customHandler: String => Option[DirectiveHandler[T]] = (key: String) => None
) {

private lazy val handlersMap = handlers.flatMap(h => h.keys.map(_ -> h)).toMap

Expand All @@ -19,7 +22,8 @@ final case class DirectiveHandlers[T](handlers: Seq[DirectiveHandler[T]]) {

directives
.map { dir =>
handlersMap.get(dir.directive.key) match {
val key = dir.directive.key
handlersMap.get(key).orElse(customHandler(key)) match {
case Some(h) =>
h.handleValues(dir)
case None =>
Expand All @@ -31,14 +35,25 @@ final case class DirectiveHandlers[T](handlers: Seq[DirectiveHandler[T]]) {
}

def map[U](f: T => U): DirectiveHandlers[U] =
copy(handlers = handlers.map(_.map(f)))
copy(
handlers = handlers.map(_.map(f)),
customHandler = key => customHandler(key).map(_.map(f))
)

def mapDirectives[U](f: DirectiveHandler[T] => DirectiveHandler[U]): DirectiveHandlers[U] =
copy(handlers = handlers.map(f))
copy(
handlers = handlers.map(f),
customHandler = key => customHandler(key).map(f)
)

def ++(other: DirectiveHandlers[T]): DirectiveHandlers[T] =
if (other.handlers.isEmpty) this
else if (handlers.isEmpty) other
else DirectiveHandlers(handlers ++ other.handlers)

def addCustomHandler(f: String => Option[DirectiveHandler[T]]): DirectiveHandlers[T] =
copy(
customHandler = key => customHandler(key).orElse(f(key))
)

}

0 comments on commit ff17885

Please sign in to comment.