Skip to content

Commit

Permalink
Documentation: implement edition using YearMonth
Browse files Browse the repository at this point in the history
Also, add the toString method so that the automatic documentation which
lists all possible options displays this value in a more user-friendly
way.
  • Loading branch information
kitbellew committed Feb 19, 2020
1 parent ba56fe3 commit e6bb469
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 11 deletions.
Original file line number Diff line number Diff line change
@@ -1,24 +1,33 @@
package org.scalafmt.config

import java.time.YearMonth

import metaconfig.{Conf, ConfDecoder, ConfEncoder, Configured}

case class Edition(year: Int, month: Int)
class Edition(val ym: YearMonth) extends AnyVal {
override def toString: String = ym.toString
}

object Edition {
val Latest = Edition(Int.MaxValue, Int.MaxValue)

def apply(year: Int, month: Int): Edition =
new Edition(YearMonth.of(year, month))

val Latest = Edition(9999, 12)

implicit val ordering: Ordering[Edition] =
Ordering.by[Edition, (Int, Int)](e => e.year -> e.month)
(x: Edition, y: Edition) => x.ym.compareTo(y.ym)

lazy val format = "(\\d{4})-(\\d{1,2})".r

implicit val decoder: ConfDecoder[Edition] =
ConfDecoder.instanceExpect("'$year-$month', for example '2019-08'") {
case Conf.Str(format(year, month)) =>
Configured.ok(Edition(year.toInt, month.toInt))
try Configured.ok(Edition(year.toInt, month.toInt))
catch { case e: Exception => Configured.error(e.getMessage) }
case Conf.Str("latest") => Configured.ok(Latest)
}

implicit val encoder: ConfEncoder[Edition] =
ConfEncoder.instance(edition =>
Conf.Str(f"${edition.year}%d-${edition.month}%02d")
)
ConfEncoder.instance(edition => Conf.Str(edition.ym.toString))
}
9 changes: 5 additions & 4 deletions scalafmt-tests/src/test/scala/org/scalafmt/EditionTest.scala
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,15 @@ import org.scalafmt.config.Edition
import org.scalafmt.util.DiffAssertions

class EditionTest extends AnyFunSuite with DiffAssertions {
def check(original: String, expected: Edition): Unit = {
def check(original: String, expected: Edition, expectedStr: String): Unit = {
test(original) {
val conf = Conf.Str(original)
val obtained = Edition.decoder.read(conf).get
assertNoDiff(
Edition.encoder.write(obtained).toString(),
Edition.encoder.write(expected).toString()
)
assertNoDiff(expected.toString, expectedStr)
}
}
def checkError(original: String, expectedError: String): Unit = {
Expand All @@ -26,9 +27,9 @@ class EditionTest extends AnyFunSuite with DiffAssertions {
}
}
}
check("2019-09", Edition(2019, 9))
check("2019-9", Edition(2019, 9))
check("2019-10", Edition(2019, 10))
check("2019-09", Edition(2019, 9), "2019-09")
check("2019-9", Edition(2019, 9), "2019-09")
check("2019-10", Edition(2019, 10), "2019-10")
checkError(
"2019-invalid",
"""|Type mismatch;
Expand Down

0 comments on commit e6bb469

Please sign in to comment.