Skip to content

Commit

Permalink
[cats] add NonEmptyList arg parser (#225)
Browse files Browse the repository at this point in the history
  • Loading branch information
YannMoisan authored Aug 13, 2020
1 parent ed160b7 commit 455cea0
Show file tree
Hide file tree
Showing 4 changed files with 29 additions and 1 deletion.
2 changes: 1 addition & 1 deletion build.sbt
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ lazy val coreJS = core.js

lazy val tests = crossProject(JSPlatform, JVMPlatform)
.disablePlugins(MimaPlugin)
.dependsOn(cats, core)
.dependsOn(cats % "test", core)
.settings(
shared,
caseAppPrefix,
Expand Down
16 changes: 16 additions & 0 deletions cats/shared/src/main/scala/caseapp/cats/CatsArgParser.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
package caseapp.cats

import caseapp.core.argparser.{AccumulatorArgParser, ArgParser}
import cats.data.NonEmptyList

object CatsArgParser {
implicit def nonEmptyListArgParser[T](
implicit parser: ArgParser[T]
): AccumulatorArgParser[NonEmptyList[T]] =
AccumulatorArgParser.from(parser.description + "*") { (prevOpt, s) =>
parser(None, s).map { t =>
// inefficient for big lists
prevOpt.fold(NonEmptyList.one(t))(_ :+ t)
}
}
}
10 changes: 10 additions & 0 deletions tests/shared/src/test/scala/caseapp/CaseAppTests.scala
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
package caseapp

import _root_.cats.data.NonEmptyList
import caseapp.core.Error
import caseapp.core.Error.SeveralErrors
import caseapp.core.help.{Help, WithHelp}
import caseapp.demo._
import shapeless.{Inl, Inr}
import utest._
import caseapp.core.util.Formatter
import caseapp.cats.CatsArgParser._

object CaseAppTests extends TestSuite {

Expand Down Expand Up @@ -105,6 +107,14 @@ object CaseAppTests extends TestSuite {
assert(res == expectedRes)
}

"parse nonEmptyList args" - {
val res =
Parser[WithNonEmptyList].parse(Seq("--nel", "2", "--nel", "5", "extra"))
val expectedRes =
Right((WithNonEmptyList(nel = NonEmptyList.of("2", "5")), Seq("extra")))
assert(res == expectedRes)
}

"parse a user-defined argument type" - {
val res = Parser[WithCustom].parse(Seq("--custom", "a"))
val expectedRes = Right((WithCustom(custom = Custom("a")), Seq.empty))
Expand Down
2 changes: 2 additions & 0 deletions tests/shared/src/test/scala/caseapp/Definitions.scala
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package caseapp

import caseapp.core.Error
import caseapp.core.argparser.{ArgParser, SimpleArgParser}
import _root_.cats.data.NonEmptyList

object Definitions {

Expand Down Expand Up @@ -29,6 +30,7 @@ object Definitions {
final case class WithTaggedList(
list : List[String]
)
final case class WithNonEmptyList(nel: NonEmptyList[String])

final case class OptBool(
opt : Option[Boolean]
Expand Down

0 comments on commit 455cea0

Please sign in to comment.