From e0afff8a0e538a7c4504e8f238a5f0ead8740a5e Mon Sep 17 00:00:00 2001 From: Koert Kuipers Date: Tue, 10 May 2022 10:07:54 -0400 Subject: [PATCH] allow option to wrap something thats repeatable and keep it repeatable --- mainargs/src/TokensReader.scala | 21 ++++++++++++++++----- mainargs/test/src/OptionSeqTests.scala | 21 +++++++++++++++++++++ 2 files changed, 37 insertions(+), 5 deletions(-) diff --git a/mainargs/src/TokensReader.scala b/mainargs/src/TokensReader.scala index 064d3a1..6c70b13 100644 --- a/mainargs/src/TokensReader.scala +++ b/mainargs/src/TokensReader.scala @@ -21,14 +21,25 @@ object TokensReader{ implicit def OptionRead[T: TokensReader]: TokensReader[Option[T]] = new TokensReader[Option[T]]( implicitly[TokensReader[T]].shortName, strs => { - strs.lastOption match{ - case None => Right(None) - case Some(s) => implicitly[TokensReader[T]].read(Seq(s)) match{ - case Left(s) =>Left(s) - case Right(s) => Right(Some(s)) + if (implicitly[TokensReader[T]].alwaysRepeatable) { + Option(strs).filter(_.nonEmpty) match{ + case None => Right(None) + case Some(strs) => implicitly[TokensReader[T]].read(strs) match{ + case Left(s) => Left(s) + case Right(s) => Right(Some(s)) + } + } + } else { + strs.lastOption match{ + case None => Right(None) + case Some(s) => implicitly[TokensReader[T]].read(Seq(s)) match{ + case Left(s) => Left(s) + case Right(s) => Right(Some(s)) + } } } }, + alwaysRepeatable = implicitly[TokensReader[T]].alwaysRepeatable, allowEmpty = true ) implicit def SeqRead[C[_] <: Iterable[_], T: TokensReader](implicit factory: Factory[T, C[T]]): TokensReader[C[T]] = new TokensReader[C[T]]( diff --git a/mainargs/test/src/OptionSeqTests.scala b/mainargs/test/src/OptionSeqTests.scala index 30af766..6a45ee9 100644 --- a/mainargs/test/src/OptionSeqTests.scala +++ b/mainargs/test/src/OptionSeqTests.scala @@ -18,6 +18,9 @@ object OptionSeqTests extends TestSuite{ @main def runInt(int: Int) = int + + @main + def runOptionSeq(os: Option[Seq[Int]]) = os } val tests = Tests { @@ -42,6 +45,24 @@ object OptionSeqTests extends TestSuite{ Seq(123) } } + + test("option seq") { + test { + ParserForMethods(Main).runOrThrow(Array("runOptionSeq", "--os", "123")) ==> + Some(Seq(123)) + } + + test { + ParserForMethods(Main).runOrThrow(Array("runOptionSeq", "--os", "123", "--os", "456")) ==> + Some(Seq(123, 456)) + } + + test { + ParserForMethods(Main).runOrThrow(Array("runOptionSeq")) ==> + None + } + } + test("vec"){ ParserForMethods(Main).runOrThrow(Array("runVec", "--seq", "123", "--seq", "456")) ==> Vector(123, 456)