Skip to content

Commit ff17885

Browse files
Add custom handler helper (#3)
1 parent f513b84 commit ff17885

File tree

1 file changed

+19
-4
lines changed

1 file changed

+19
-4
lines changed

directive-handler/src/main/scala/scala/cli/directivehandler/DirectiveHandlers.scala

Lines changed: 19 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,10 @@ package scala.cli.directivehandler
22

33
import scala.cli.directivehandler.EitherSequence._
44

5-
final case class DirectiveHandlers[T](handlers: Seq[DirectiveHandler[T]]) {
5+
final case class DirectiveHandlers[T](
6+
handlers: Seq[DirectiveHandler[T]],
7+
customHandler: String => Option[DirectiveHandler[T]] = (key: String) => None
8+
) {
69

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

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

2023
directives
2124
.map { dir =>
22-
handlersMap.get(dir.directive.key) match {
25+
val key = dir.directive.key
26+
handlersMap.get(key).orElse(customHandler(key)) match {
2327
case Some(h) =>
2428
h.handleValues(dir)
2529
case None =>
@@ -31,14 +35,25 @@ final case class DirectiveHandlers[T](handlers: Seq[DirectiveHandler[T]]) {
3135
}
3236

3337
def map[U](f: T => U): DirectiveHandlers[U] =
34-
copy(handlers = handlers.map(_.map(f)))
38+
copy(
39+
handlers = handlers.map(_.map(f)),
40+
customHandler = key => customHandler(key).map(_.map(f))
41+
)
3542

3643
def mapDirectives[U](f: DirectiveHandler[T] => DirectiveHandler[U]): DirectiveHandlers[U] =
37-
copy(handlers = handlers.map(f))
44+
copy(
45+
handlers = handlers.map(f),
46+
customHandler = key => customHandler(key).map(f)
47+
)
3848

3949
def ++(other: DirectiveHandlers[T]): DirectiveHandlers[T] =
4050
if (other.handlers.isEmpty) this
4151
else if (handlers.isEmpty) other
4252
else DirectiveHandlers(handlers ++ other.handlers)
4353

54+
def addCustomHandler(f: String => Option[DirectiveHandler[T]]): DirectiveHandlers[T] =
55+
copy(
56+
customHandler = key => customHandler(key).orElse(f(key))
57+
)
58+
4459
}

0 commit comments

Comments
 (0)