Skip to content

Commit

Permalink
Remove scalastyle in favor of scalafmt (#1267)
Browse files Browse the repository at this point in the history
  • Loading branch information
sergeykolbasov committed Sep 25, 2020
1 parent abd0aa4 commit f1e7ed1
Show file tree
Hide file tree
Showing 107 changed files with 2,185 additions and 2,159 deletions.
7 changes: 7 additions & 0 deletions .scalafix.conf
@@ -0,0 +1,7 @@
OrganizeImports {
groupedImports = Keep
removeUnused = true
}
rules = [
OrganizeImports
]
11 changes: 11 additions & 0 deletions .scalafmt.conf
@@ -0,0 +1,11 @@
version = 2.7.2
maxColumn = 160
align.preset = some
rewrite.rules = [
RedundantBraces,
RedundantParens,
SortModifiers,
PreferCurlyFors
]
assumeStandardLibraryStripMargin = true
optIn.breakChainOnFirstMethodDot = false
4 changes: 2 additions & 2 deletions CONTRIBUTING.md
Expand Up @@ -17,12 +17,12 @@ _contributing process_ looks as follows:
Finch follows the [Effective Scala][1] code style guide. When in doubt, look around the codebase and see how it's done
elsewhere.

* Code and comments should be formatted to a width no greater than 120 columns
* Code and comments should be formatted to a width no greater than 160 columns
* Files should be exempt of trailing spaces
* Each abstraction with corresponding implementations should live in its own Scala file, i.e `Endpoint.scala`
* Each implicit conversion (if possible) should be defined in the corresponding companion object

That said, the Scala style checker `sbt scalastyle` should pass on the code.
That said, the Scala source code shall be formatted with `sbt fmt`

## Write Tests
Finch uses both [ScalaTest][2] and [ScalaCheck][3] with the following settings:
Expand Down
10 changes: 5 additions & 5 deletions argonaut/src/main/scala/io/finch/argonaut/Decoders.scala
@@ -1,21 +1,21 @@
package io.finch.argonaut

import argonaut._
import argonaut.DecodeJson
import argonaut._
import cats.syntax.either._
import io.finch._
import io.finch.internal.HttpContent

trait Decoders {

/**
* Maps Argonaut's [[DecodeJson]] to Finch's [[Decode]].
*/
* Maps Argonaut's [[DecodeJson]] to Finch's [[Decode]].
*/
implicit def decodeArgonaut[A](implicit d: DecodeJson[A]): Decode.Json[A] =
Decode.json { (b, cs) =>
Parse.parse(b.asString(cs)).flatMap(_.as[A].result.leftMap(_._1)) match {
case Right(result) => Right(result)
case Left(error) => Left(new Exception(error))
case Left(error) => Left(new Exception(error))
}
}
}
}
4 changes: 2 additions & 2 deletions argonaut/src/main/scala/io/finch/argonaut/Encoders.scala
Expand Up @@ -9,8 +9,8 @@ trait Encoders {
protected def printer: PrettyParams

/**
* Maps Argonaut's [[EncodeJson]] to Finch's [[Encode]].
*/
* Maps Argonaut's [[EncodeJson]] to Finch's [[Encode]].
*/
implicit def encodeArgonaut[A](implicit e: EncodeJson[A]): Encode.Json[A] =
Encode.json((a, cs) => Buf.ByteArray.Owned(printer.pretty(e.encode(a)).getBytes(cs.name)))
}
8 changes: 4 additions & 4 deletions argonaut/src/main/scala/io/finch/argonaut/package.scala
Expand Up @@ -11,15 +11,15 @@ package object argonaut extends Encoders with Decoders {
}

/**
* Provides an implicit [[PrettyParams]] that preserves order of the JSON fields.
*/
* Provides an implicit [[PrettyParams]] that preserves order of the JSON fields.
*/
object preserveOrder extends Encoders with Decoders {
override protected val printer: PrettyParams = PrettyParams.nospace.copy(preserveOrder = true)
}

/**
* Provides an implicit [[PrettyParams]] that both preserves order of the JSON fields and drop null keys.
*/
* Provides an implicit [[PrettyParams]] that both preserves order of the JSON fields and drop null keys.
*/
object preserveOrderAndDropNullKeys extends Encoders with Decoders {
override protected val printer: PrettyParams = PrettyParams.nospace.copy(preserveOrder = true, dropNullKeys = true)
}
Expand Down
@@ -1,7 +1,7 @@
package io.finch.argonaut

import argonaut._
import argonaut.Argonaut._
import argonaut._
import io.finch.test.AbstractJsonSpec
import io.finch.test.data._

Expand Down
17 changes: 8 additions & 9 deletions benchmarks/src/main/scala/io/finch/benchmarks.scala
@@ -1,5 +1,8 @@
package io.finch

import java.nio.charset.{Charset, StandardCharsets}
import java.util.concurrent.{ThreadLocalRandom, TimeUnit}

import cats.effect.IO
import com.twitter.finagle.Service
import com.twitter.finagle.http.{Request, Response}
Expand All @@ -8,8 +11,6 @@ import com.twitter.util.Await
import io.circe.generic.auto._
import io.finch.circe._
import io.finch.data.Foo
import java.nio.charset.{Charset, StandardCharsets}
import java.util.concurrent.{ThreadLocalRandom, TimeUnit}
import org.openjdk.jmh.annotations._
import shapeless._

Expand Down Expand Up @@ -184,14 +185,13 @@ class JsonBenchmark extends FinchBenchmark {
@BenchmarkMode(Array(Mode.Throughput))
@OutputTimeUnit(TimeUnit.SECONDS)
abstract class BootstrapBenchmark[CT](init: Bootstrap[Id, HNil, HNil])(implicit
tsf: Compile[IO, Endpoint[IO, List[Foo]] :: HNil, CT :: HNil]
tsf: Compile[IO, Endpoint[IO, List[Foo]] :: HNil, CT :: HNil]
) extends FinchBenchmark {

protected def issueRequest(): Request = Request()

private val foo: Service[Request, Response] = init
.serve[CT](Endpoint[IO].const(List.fill(128)(Foo(scala.util.Random.alphanumeric.take(10).mkString))))
.toService
private val foo: Service[Request, Response] =
init.serve[CT](Endpoint[IO].const(List.fill(128)(Foo(scala.util.Random.alphanumeric.take(10).mkString)))).toService

@Benchmark
def foos: Response = Await.result(foo.apply(issueRequest()))
Expand All @@ -201,8 +201,7 @@ class JsonBootstrapBenchmark extends BootstrapBenchmark[Application.Json](Bootst

class TextBootstrapBenchmark extends BootstrapBenchmark[Text.Plain](Bootstrap)

class JsonAndTextNegotiatedBootstrapBenchmark extends BootstrapBenchmark[Application.Json :+: Text.Plain :+: CNil](
Bootstrap) {
class JsonAndTextNegotiatedBootstrapBenchmark extends BootstrapBenchmark[Application.Json :+: Text.Plain :+: CNil](Bootstrap) {

private val acceptValues: Array[String] = Array("application/json", "text/plain")

Expand Down Expand Up @@ -243,6 +242,6 @@ class HttpMessageBenchmark extends FinchBenchmark {
@Benchmark
def slowCharset: Charset = req.charset match {
case Some(cs) => Charset.forName(cs)
case None => StandardCharsets.UTF_8
case None => StandardCharsets.UTF_8
}
}
2 changes: 1 addition & 1 deletion benchmarks/src/main/scala/io/finch/data/Foo.scala
@@ -1,8 +1,8 @@
package io.finch.data

import com.twitter.io.Buf
import io.finch.{Decode, DecodeEntity, Encode}
import io.finch.internal.HttpContent
import io.finch.{Decode, DecodeEntity, Encode}

case class Foo(s: String)

Expand Down
30 changes: 19 additions & 11 deletions build.sbt
Expand Up @@ -17,9 +17,9 @@ lazy val argonautVersion = "6.3.1"
lazy val iterateeVersion = "0.19.0"
lazy val refinedVersion = "0.9.16"
lazy val catsEffectVersion = "2.2.0"
lazy val fs2Version = "2.4.4"
lazy val fs2Version = "2.4.4"

def compilerOptions(scalaVersion: String) = Seq(
def compilerOptions(scalaVersion: String): Seq[String] = Seq(
"-deprecation",
"-encoding", "UTF-8",
"-feature",
Expand All @@ -36,7 +36,7 @@ def compilerOptions(scalaVersion: String) = Seq(
})

lazy val scala212CompilerOptions = Seq(
"-Yno-adapted-args",
"-Yno-adapted-args",
"-Ywarn-unused-import",
"-Xfuture"
)
Expand Down Expand Up @@ -65,13 +65,16 @@ val baseSettings = Seq(
Resolver.sonatypeRepo("snapshots")
),
scalacOptions ++= compilerOptions(scalaVersion.value),
scalacOptions in (Compile, console) ~= {
scalacOptions in(Compile, console) ~= {
_.filterNot(Set("-Ywarn-unused-import"))
},
scalacOptions in (Compile, console) += "-Yrepl-class-based",
scalacOptions in(Compile, console) += "-Yrepl-class-based",
fork in Test := true,
javaOptions in ThisBuild ++= Seq("-Xss2048K"),
addCompilerPlugin("org.typelevel" % "kind-projector" % "0.10.3" cross CrossVersion.binary)
addCompilerPlugin("org.typelevel" % "kind-projector" % "0.10.3" cross CrossVersion.binary),
ThisBuild / scalafixDependencies += "com.github.liancheng" %% "organize-imports" % "0.4.1",
semanticdbEnabled := true,
semanticdbVersion := scalafixSemanticdb.revision
)

def updateVersionInFile(selectVersion: sbtrelease.Versions => String): ReleaseStep =
Expand All @@ -92,7 +95,8 @@ def updateVersionInFile(selectVersion: sbtrelease.Versions => String): ReleaseSt
pattern.replaceAllIn(content,
m => m.matched.replaceAllLiterally(m.subgroups.head, newVersion))
new PrintWriter(fileName) {
write(newContent); close()
write(newContent);
close()
}
val vcs = Project.extract(st).get(releaseVcs).get
vcs.add(fileName).!
Expand All @@ -109,7 +113,7 @@ lazy val publishSettings = Seq(
if (isSnapshot.value)
Some("snapshots" at nexus + "content/repositories/snapshots")
else
Some("releases" at nexus + "service/local/staging/deploy/maven2")
Some("releases" at nexus + "service/local/staging/deploy/maven2")
},
publishArtifact in Test := false,
pgpSecretRing := file("local.secring.gpg"),
Expand Down Expand Up @@ -199,9 +203,9 @@ lazy val docSettings = allSettings ++ Seq(
"gray-light" -> "#E5E6E5",
"gray-lighter" -> "#F4F3F4",
"white-color" -> "#FFFFFF"),
addMappingsToSiteDir(mappings in (ScalaUnidoc, packageDoc), micrositeDocumentationUrl),
addMappingsToSiteDir(mappings in(ScalaUnidoc, packageDoc), micrositeDocumentationUrl),
ghpagesNoJekyll := false,
scalacOptions in (ScalaUnidoc, unidoc) ++= Seq(
scalacOptions in(ScalaUnidoc, unidoc) ++= Seq(
"-groups",
"-implicits",
"-skip-packages", "scalaz",
Expand All @@ -213,7 +217,7 @@ lazy val docSettings = allSettings ++ Seq(
_.filterNot(Set("-Yno-predef", "-Xlint", "-Ywarn-unused-import"))
},
git.remoteRepo := "git@github.com:finagle/finch.git",
unidocProjectFilter in (ScalaUnidoc, unidoc) := inAnyProject -- inProjects(benchmarks, jsonTest),
unidocProjectFilter in(ScalaUnidoc, unidoc) := inAnyProject -- inProjects(benchmarks, jsonTest),
includeFilter in makeSite := "*.html" | "*.css" | "*.png" | "*.jpg" | "*.gif" | "*.svg" | "*.js" | "*.swf" | "*.yml" | "*.md",
siteSubdirName in ScalaUnidoc := "docs"
)
Expand Down Expand Up @@ -397,10 +401,14 @@ lazy val benchmarks = project
val validateCommands = List(
"clean",
"compile",
"scalafix --check",
"scalafmtCheckAll",
"test:compile",
"coverage",
"test",
"coverageReport",
"coverageAggregate"
)
addCommandAlias("validate", validateCommands.mkString(";", ";", ""))
addCommandAlias("fmt", "all compile:scalafix; all test:scalafix; scalafmtAll")

28 changes: 14 additions & 14 deletions circe/src/main/scala/io/finch/circe/AccumulatingDecoders.scala
Expand Up @@ -7,8 +7,8 @@ import cats.data.Validated
import io.circe._
import io.circe.iteratee._
import io.circe.jawn.{decodeAccumulating, decodeByteBufferAccumulating}
import io.finch.{Application, Decode, DecodeStream}
import io.finch.internal.HttpContent
import io.finch.{Application, Decode, DecodeStream}
import io.iteratee.{Enumeratee, Enumerator}

trait AccumulatingDecoders {
Expand All @@ -26,25 +26,25 @@ trait AccumulatingDecoders {
attemptJson.fold[Either[Throwable, A]](nel => Left(Errors(nel)), Right.apply)
}

implicit def iterateeCirceDecoder[F[_], A : Decoder](implicit
monadError: MonadError[F, Throwable]
): DecodeStream.Json[Enumerator, F, A] = DecodeStream.instance[Enumerator, F, A, Application.Json]((enum, cs) => {
val parsed = cs match {
case StandardCharsets.UTF_8 =>
enum.map(_.asByteArray).through(byteStreamParser[F])
case _ =>
enum.map(_.asString(cs)).through(stringStreamParser[F])
}
parsed.through(decoderAccumulating[F, A])
})
implicit def iterateeCirceDecoder[F[_], A: Decoder](implicit
monadError: MonadError[F, Throwable]
): DecodeStream.Json[Enumerator, F, A] = DecodeStream.instance[Enumerator, F, A, Application.Json] { (enum, cs) =>
val parsed = cs match {
case StandardCharsets.UTF_8 =>
enum.map(_.asByteArray).through(byteStreamParser[F])
case _ =>
enum.map(_.asString(cs)).through(stringStreamParser[F])
}
parsed.through(decoderAccumulating[F, A])
}

private def decoderAccumulating[F[_], A](implicit
F: MonadError[F, Throwable],
F: MonadError[F, Throwable],
decode: Decoder[A]
): Enumeratee[F, Json, A] = Enumeratee.flatMap(json =>
decode.decodeAccumulating(json.hcursor) match {
case Validated.Invalid(errors) => Enumerator.liftM(F.raiseError(Errors(errors)))
case Validated.Valid(a) => Enumerator.enumOne(a)
case Validated.Valid(a) => Enumerator.enumOne(a)
}
)

Expand Down
3 changes: 2 additions & 1 deletion circe/src/main/scala/io/finch/circe/CirceError.scala
@@ -1,8 +1,9 @@
package io.finch.circe

import cats.syntax.show._
import scala.util.control.NoStackTrace

import cats.syntax.show._

private class CirceError(cause: io.circe.Error) extends Exception with NoStackTrace {
override def getMessage: String = cause.show
}
31 changes: 14 additions & 17 deletions circe/src/main/scala/io/finch/circe/Decoders.scala
@@ -1,59 +1,56 @@
package io.finch.circe

import java.nio.charset.StandardCharsets

import cats.MonadError
import cats.effect.Sync
import fs2.{Chunk, Stream}
import io.circe.Decoder
import io.circe.fs2
import io.circe.iteratee
import io.circe.jawn._
import io.finch.{Application, Decode, DecodeStream}
import io.finch.internal.HttpContent
import io.finch.{Application, Decode, DecodeStream}
import io.iteratee.Enumerator
import java.nio.charset.StandardCharsets

trait Decoders {

/**
* Maps a Circe's [[Decoder]] to Finch's [[Decode]].
*/
* Maps a Circe's [[Decoder]] to Finch's [[Decode]].
*/
implicit def decodeCirce[A: Decoder]: Decode.Json[A] = Decode.json { (b, cs) =>
val decoded = cs match {
case StandardCharsets.UTF_8 => decodeByteBuffer[A](b.asByteBuffer)
case _ => decode[A](b.asString(cs))
case _ => decode[A](b.asString(cs))
}

decoded match {
case Left(error) => Left(new CirceError(error))
case right => right
case right => right
}
}

implicit def enumerateCirce[F[_], A: Decoder](implicit
F: MonadError[F, Throwable]
F: MonadError[F, Throwable]
): DecodeStream.Json[Enumerator, F, A] =
DecodeStream.instance[Enumerator, F, A, Application.Json]((enum, cs) => {
DecodeStream.instance[Enumerator, F, A, Application.Json] { (enum, cs) =>
val parsed = cs match {
case StandardCharsets.UTF_8 =>
enum.map(_.asByteArray).through(iteratee.byteStreamParser[F])
case _ =>
enum.map(_.asString(cs)).through(iteratee.stringStreamParser[F])
}
parsed.through(iteratee.decoder[F, A])
})
}

implicit def fs2Circe[F[_]: Sync, A: Decoder]: DecodeStream.Json[Stream, F, A] =
DecodeStream.instance[Stream, F, A, Application.Json]((stream, cs) => {
DecodeStream.instance[Stream, F, A, Application.Json] { (stream, cs) =>
val parsed = cs match {
case StandardCharsets.UTF_8 =>
stream
.mapChunks(chunk => chunk.flatMap(buf => Chunk.array(buf.asByteArray)))
.through(fs2.byteStreamParser[F])
stream.mapChunks(chunk => chunk.flatMap(buf => Chunk.array(buf.asByteArray))).through(fs2.byteStreamParser[F])
case _ =>
stream
.map(_.asString(cs))
.through(fs2.stringStreamParser[F])
stream.map(_.asString(cs)).through(fs2.stringStreamParser[F])
}
parsed.through(fs2.decoder[F, A])
})
}
}

0 comments on commit f1e7ed1

Please sign in to comment.