Skip to content

Commit

Permalink
wip: inspector
Browse files Browse the repository at this point in the history
  • Loading branch information
Javakky-pxv committed Nov 10, 2023
1 parent 3513359 commit c15ac1f
Show file tree
Hide file tree
Showing 25 changed files with 54 additions and 69 deletions.
7 changes: 0 additions & 7 deletions core/src/main/scala/com/iheart/playSwagger/Domain.scala

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ trait OutputTransformer extends (JsObject => Try[JsObject]) {
}

object OutputTransformer {
final case class SimpleOutputTransformer(run: (JsObject => Try[JsObject])) extends OutputTransformer {
final case class SimpleOutputTransformer(run: JsObject => Try[JsObject]) extends OutputTransformer {
override def apply(value: JsObject): Try[JsObject] = run(value)
}

Expand Down Expand Up @@ -55,7 +55,7 @@ object OutputTransformer {
}
}

class PlaceholderVariablesTransformer(map: String => Option[String], pattern: Regex = "^\\$\\{(.*)\\}$".r)
class PlaceholderVariablesTransformer(map: String => Option[String], pattern: Regex = ("^\\$\\{(.*)\\}$").r)
extends OutputTransformer {
def apply(value: JsObject): Try[JsObject] = OutputTransformer.traverseTransformer(value) {
case JsString(pattern(key)) => map(key) match {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ object SwaggerSpecRunner extends App {
val domainModelQualifier = PrefixDomainModelQualifier(domainNameSpaceArgs.split(","): _*)
val transformersStrs: Seq[String] = if (outputTransformersArgs.isEmpty) Seq() else outputTransformersArgs.split(",")
val transformers = transformersStrs.map { clazz =>
Try(cl.loadClass(clazz).asSubclass(classOf[OutputTransformer]).newInstance()) match {
Try(cl.loadClass(clazz).asSubclass(classOf[OutputTransformer]).getDeclaredConstructor().newInstance()) match {
case Failure(ex: ClassCastException) =>
throw new IllegalArgumentException(
"Transformer should be a subclass of com.iheart.playSwagger.OutputTransformer:" + clazz,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,6 @@ object CustomTypeMapping {
(JsPath \ "type").read[String] and
(JsPath \ "specAsParameter").read[List[JsObject]] and
(JsPath \ "specAsProperty").readNullable[JsObject] and
((JsPath \ "required").read[Boolean].orElse(Reads.pure(true)))
(JsPath \ "required").read[Boolean].orElse(Reads.pure(true))
)(CustomTypeMapping.apply _)
}
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ class SwaggerParameterWriter(swaggerV3: Boolean) {

val referencePrefix: String = if (swaggerV3) "#/components/schemas/" else "#/definitions/"

lazy val propWrites: Writes[SwaggerParameter] = Writes {
private lazy val propWrites: Writes[SwaggerParameter] = Writes {
case g: GenSwaggerParameter => genPropWrites.writes(g)
case c: CustomSwaggerParameter => customPropWrites.writes(c)
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@ class RoutesParseException(errors: Seq[RoutesParseErrorDetail]) extends RuntimeE
)

object RoutesParseException {
case class RoutesParseErrorTargetLine()
case class RoutesParseErrorDetail(
sourceFileName: String,
message: String,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ final case class DefinitionGenerator(

private val refinedTypePattern = raw"(eu\.timepit\.refined\.api\.Refined(?:\[.+])?)".r

def dealiasParams(t: Type): Type = {
private def dealiasParams(t: Type): Type = {
t.toString match {
case refinedTypePattern(_) => t.typeArgs.headOption.getOrElse(t)
case _ =>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,8 @@ sealed abstract class NamingConvention(f: String => String) extends (String => S
}

object NamingConvention {
val regex: Regex = "[A-Z\\d]".r
val skipNumberRegex: Regex = "[A-Z]".r
private val regex: Regex = "[A-Z\\d]".r
private val skipNumberRegex: Regex = "[A-Z]".r

object None extends NamingConvention(identity)
object SnakeCase extends NamingConvention(x => regex.replaceAllIn(x, { m => "_" + m.group(0).toLowerCase() }))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,6 @@ object SwaggerSpecGenerator {
private val refKey = "$ref"
private val baseSpecFileName = "swagger"

private val marker = "##"

def apply(namingConvention: NamingConvention, swaggerV3: Boolean, domainNameSpaces: String*)(implicit
cl: ClassLoader): SwaggerSpecGenerator = {
SwaggerSpecGenerator(
Expand Down Expand Up @@ -132,9 +130,9 @@ final case class SwaggerSpecGenerator(
}

/** .routes を除いたファイル名がタグ名となる */
def tagFromFile(fileName: String): Tag = fileName.replace(routesExt, "")
private def tagFromFile(fileName: String): Tag = fileName.replace(routesExt, "")

def loop(path: Path, routesFile: String): RoutesData = {
private def loop(path: Path, routesFile: String): RoutesData = {
// TODO: better error handling
ResourceReader.read(routesFile).flatMap { lines =>
lines.headOption match {
Expand Down Expand Up @@ -207,7 +205,7 @@ final case class SwaggerSpecGenerator(
* @param routes [[Route]]s compiled by Play routes compiler
* @param base swagger.yaml に記載された基本設定
*/
def generateFromRoutes(routes: ListMap[Tag, (String, Seq[Route])], base: JsObject): JsObject = {
private def generateFromRoutes(routes: ListMap[Tag, (String, Seq[Route])], base: JsObject): JsObject = {
val docs = routes.map {
case (tag, (path, routes)) =>
tag -> paths(routes, path, Some(tag))
Expand Down
2 changes: 0 additions & 2 deletions core/src/main/scala/com/iheart/playSwagger/package.scala
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,6 @@ package com.iheart

package object playSwagger {
type Line = String
type APIName = String
type Tag = String
type RoutesDocumentation = Seq[(String, String, String)]

}
Original file line number Diff line number Diff line change
Expand Up @@ -24,13 +24,4 @@ object ExtendJsValue {
case _ => JsNull
}
}

implicit class PathAdditions(path: JsPath) {
def writeNullableIterable[A <: Iterable[_]](implicit writes: Writes[A]): Writes[A] =
Writes[A] { (a: A) =>
if (a.isEmpty) Json.obj()
else JsPath.createObj(path -> writes.writes(a))
}
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ class OutputTransformerSpec extends Specification {
case _ => Failure(new IllegalStateException())
})
val b = SimpleOutputTransformer(OutputTransformer.traverseTransformer(_) {
case JsString(content) => Failure(new IllegalStateException("not strings"))
case JsString(_) => Failure(new IllegalStateException("not strings"))
case _ => Failure(new IllegalStateException())
})

Expand Down
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
package com.iheart.playSwagger

import scala.collection.immutable

import enumeratum.EnumEntry.Snakecase
import enumeratum._

sealed trait SampleEnumeratumEnum extends EnumEntry with Snakecase

object SampleEnumeratumEnum extends Enum[SampleEnumeratumEnum] {
val values = findValues
val values: immutable.IndexedSeq[SampleEnumeratumEnum] = findValues

case object InfoOne extends SampleEnumeratumEnum
case object InfoTwo extends SampleEnumeratumEnum
Expand Down
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
package com.iheart.playSwagger

import scala.collection.immutable

import enumeratum.values.{StringEnum, StringEnumEntry}

sealed abstract class SampleEnumeratumValueEnum(val value: String) extends StringEnumEntry

object SampleEnumeratumValueEnum extends StringEnum[SampleEnumeratumValueEnum] {
val values = findValues
val values: immutable.IndexedSeq[SampleEnumeratumValueEnum] = findValues

case object ValueOne extends SampleEnumeratumValueEnum("valueOne")
case object ValueTwo extends SampleEnumeratumValueEnum("valueTwo")
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
package com.iheart.playSwagger

import com.iheart.playSwagger

object SampleScalaEnum extends Enumeration {
type SampleScalaEnum = Value

val One = Value
val Two = Value
val One: playSwagger.SampleScalaEnum.Value = Value
val Two: playSwagger.SampleScalaEnum.Value = Value
}
Original file line number Diff line number Diff line change
Expand Up @@ -202,13 +202,13 @@ class SwaggerSpecGeneratorIntegrationSpec extends Specification {
}

"read seq of referenced type" >> {
val relatedProp = (trackJson \ "properties" \ "related")
val relatedProp = trackJson \ "properties" \ "related"
(relatedProp \ "type").asOpt[String] === Some("array")
(relatedProp \ "items" \ "$ref").asOpt[String] === Some("#/definitions/com.iheart.playSwagger.Artist")
}

"read seq of primitive type" >> {
val numberProps = (trackJson \ "properties" \ "numbers")
val numberProps = trackJson \ "properties" \ "numbers"
(numberProps \ "type").asOpt[String] === Some("array")
(numberProps \ "items" \ "type").asOpt[String] === Some("integer")
}
Expand Down
2 changes: 1 addition & 1 deletion example/build.sbt
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ name := """example"""

version := "1.0-SNAPSHOT"

scalafixDependencies in ThisBuild ++= Seq(
ThisBuild / scalafixDependencies ++= Seq(
"com.github.liancheng" %% "organize-imports" % "0.6.0",
"net.pixiv" %% "scalafix-pixiv-rule" % "4.5.3"
)
Expand Down
14 changes: 7 additions & 7 deletions project/Dependencies.scala
Original file line number Diff line number Diff line change
Expand Up @@ -9,31 +9,31 @@ object Dependencies {
val refined = "0.11.0"
}

val playTest = Seq(
val playTest: Seq[ModuleID] = Seq(
"com.typesafe.play" %% "play-test" % Versions.play % Test
)

val playRoutesCompiler = Seq(
val playRoutesCompiler: Seq[ModuleID] = Seq(
"com.typesafe.play" %% "routes-compiler" % Versions.play
)

val playJson = Seq(
val playJson: Seq[ModuleID] = Seq(
"com.typesafe.play" %% "play-json" % Versions.playJson % "provided"
)

val yaml = Seq(
val yaml: Seq[ModuleID] = Seq(
"org.yaml" % "snakeyaml" % "2.2"
)

val enumeratum = Seq(
val enumeratum: Seq[ModuleID] = Seq(
"com.beachape" %% "enumeratum" % Versions.enumeratum % Test
)

val refined = Seq(
val refined: Seq[ModuleID] = Seq(
"eu.timepit" %% "refined" % Versions.refined % Test
)

val test = Seq(
val test: Seq[ModuleID] = Seq(
"org.specs2" %% "specs2-core" % Versions.specs2 % "test",
"org.specs2" %% "specs2-mock" % Versions.specs2 % "test"
)
Expand Down
6 changes: 3 additions & 3 deletions project/Testing.scala
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
import org.scoverage.coveralls.Imports.CoverallsKeys._
import sbt._
import sbt.{Def, _}
import sbt.Keys._

object Testing {

lazy val settings = Seq(
scalacOptions in Test ++= Seq("-Yrangepos")
lazy val settings: Seq[Def.Setting[Task[Seq[String]]]] = Seq(
Test / scalacOptions ++= Seq("-Yrangepos")
)

}
6 changes: 3 additions & 3 deletions project/Versioning.scala
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import sbt.Keys._
import sbt._
import sbt.{Def, _}

object Versioning {

def writeVersionFile(path: String) = Def.task {
val file = (resourceManaged in Compile).value / path
def writeVersionFile(path: String): Def.Initialize[Task[Seq[File]]] = Def.task {
val file = (Compile / resourceManaged).value / path
IO.write(file, version.value.getBytes)
Seq(file)
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,10 @@ import sbt.Keys.*
import sbt.{AutoPlugin, *}

object SwaggerPlugin extends AutoPlugin {
lazy val SwaggerConfig: Configuration = config("play-swagger").hide
lazy val playSwaggerVersion: String = com.iheart.playSwagger.BuildInfo.version
private lazy val SwaggerConfig: Configuration = config("play-swagger").hide
private lazy val playSwaggerVersion: String = com.iheart.playSwagger.BuildInfo.version

object autoImport extends SwaggerKeys
private object autoImport extends SwaggerKeys

override def requires: Plugins = JavaAppPackaging

Expand All @@ -21,7 +21,7 @@ object SwaggerPlugin extends AutoPlugin {

override def projectConfigurations: Seq[Configuration] = Seq(SwaggerConfig)

override def projectSettings: Seq[Setting[_]] = Seq(
override def projectSettings: Seq[Setting[?]] = Seq(
ivyConfigurations += SwaggerConfig,
resolvers += Resolver.jcenterRepo,
// todo: remove hardcoded org name using BuildInfo
Expand All @@ -39,7 +39,7 @@ object SwaggerPlugin extends AutoPlugin {
swaggerOperationIdNamingFully := false,
embedScaladoc := false,
swagger := Def.task[File] {
(swaggerTarget.value).mkdirs()
swaggerTarget.value.mkdirs()
val file = swaggerTarget.value / swaggerFileName.value
IO.delete(file)
val args: Seq[String] = file.absolutePath :: swaggerRoutesFile.value ::
Expand All @@ -54,7 +54,7 @@ object SwaggerPlugin extends AutoPlugin {
embedScaladoc.value.toString ::
Nil
val swaggerClasspath =
data((fullClasspath in Runtime).value) ++ update.value.select(configurationFilter(SwaggerConfig.name))
data((Runtime / fullClasspath).value) ++ update.value.select(configurationFilter(SwaggerConfig.name))
runner.value.run(
"com.iheart.playSwagger.SwaggerSpecRunner",
swaggerClasspath,
Expand All @@ -63,10 +63,10 @@ object SwaggerPlugin extends AutoPlugin {
).failed foreach (sys error _.getMessage)
file
}.value,
unmanagedResourceDirectories in Assets += swaggerTarget.value,
mappings in (Compile, packageBin) += (swagger.value) -> s"public/${swaggerFileName.value}", // include it in the unmanagedResourceDirectories in Assets doesn't automatically include it package
packageBin in Universal := (packageBin in Universal).dependsOn(swagger).value,
run := (run in Compile).dependsOn(swagger).evaluated,
Assets / unmanagedResourceDirectories += swaggerTarget.value,
Compile / packageBin / mappings += swagger.value -> s"public/${swaggerFileName.value}", // include it in the unmanagedResourceDirectories in Assets doesn't automatically include it package
Universal / packageBin := (Universal / packageBin).dependsOn(swagger).value,
run := (Compile / run).dependsOn(swagger).evaluated,
stage := stage.dependsOn(swagger).value
)
}
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import spray.json._
import DefaultJsonProtocol._

logLevel in update := sbt.Level.Warn
update / logLevel := sbt.Level.Warn

enablePlugins(PlayScala, SwaggerPlugin)

Expand Down Expand Up @@ -148,7 +148,7 @@ TaskKey[Unit]("check") := {
s"Result > $resultLine"
}.mkString("\n")

val left = ep.takeRight(ep.size - rs.size).mkString("\n")
val left = ep.takeRight(ep.length - rs.length).mkString("\n")

sys.error(
s"""Swagger.json is off.
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
logLevel in update := sbt.Level.Warn
update / logLevel := sbt.Level.Warn

addSbtPlugin("com.typesafe.sbt" %% "sbt-native-packager" % "1.3.2")
addSbtPlugin("com.typesafe.play" %% "sbt-plugin" % "2.8.16")
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import spray.json._
import DefaultJsonProtocol._

logLevel in update := sbt.Level.Warn
update / logLevel := sbt.Level.Warn

enablePlugins(PlayScala, SwaggerPlugin)

Expand Down Expand Up @@ -140,7 +140,7 @@ TaskKey[Unit]("check") := {
s"Result > $resultLine"
}.mkString("\n")

val left = ep.takeRight(ep.size - rs.size).mkString("\n")
val left = ep.takeRight(ep.length - rs.length).mkString("\n")

sys.error(
s"""Swagger.json is off.
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
logLevel in update := sbt.Level.Warn
update / logLevel := sbt.Level.Warn

addSbtPlugin("com.typesafe.sbt" %% "sbt-native-packager" % "1.3.2")
addSbtPlugin("com.typesafe.play" %% "sbt-plugin" % "2.8.16")
Expand Down

0 comments on commit c15ac1f

Please sign in to comment.